【发布时间】:2013-07-21 22:22:42
【问题描述】:
我正在阅读this code from here(中文)。有一段代码是关于在 C 中测试全局变量的。变量a 已在文件t.h 中定义,该文件已包含两次。在文件foo.c 中定义了一个带有一些值的struct b 和一个main 函数。在main.c 文件中,定义了两个未初始化的变量。
/* t.h */
#ifndef _H_
#define _H_
int a;
#endif
/* foo.c */
#include <stdio.h>
#include "t.h"
struct {
char a;
int b;
} b = { 2, 4 };
int main();
void foo()
{
printf("foo:\t(&a)=0x%08x\n\t(&b)=0x%08x\n
\tsizeof(b)=%d\n\tb.a=%d\n\tb.b=%d\n\tmain:0x%08x\n",
&a, &b, sizeof b, b.a, b.b, main);
}
/* main.c */
#include <stdio.h>
#include "t.h"
int b;
int c;
int main()
{
foo();
printf("main:\t(&a)=0x%08x\n\t(&b)=0x%08x\n
\t(&c)=0x%08x\n\tsize(b)=%d\n\tb=%d\n\tc=%d\n",
&a, &b, &c, sizeof b, b, c);
return 0;
}
使用Ubuntu GCC 4.4.3编译后,结果如下:
foo: (&a)=0x0804a024
(&b)=0x0804a014
sizeof(b)=8
b.a=2
b.b=4
main:0x080483e4
main: (&a)=0x0804a024
(&b)=0x0804a014
(&c)=0x0804a028
size(b)=4
b=2
c=0
变量a和b在两个函数中地址相同,但b的大小发生了变化。我无法理解它是如何工作的!
【问题讨论】:
-
你有什么问题?
-
使用
%p打印指针,你也应该在标题中添加foo。 -
如果要解决冲突,请声明 var static。
-
来自coolshell(中文)对吧?
-
@liuan 不,我只是好奇,仅此而已。我认为这不是问题,因为您没有复制整篇文章。就我个人而言,我也不喜欢那篇文章中的解释。所以我很高兴看到这里讨论的问题。
标签: c linker one-definition-rule