Tag: 单定义规则

c&c ++默认全局变量链接,多个声明和定义问题

例如: code1.c / .cpp int a; // … and so on code2.c / .cpp int a; int main(void) { return 0; } 去编译: $gcc code1.c code2.c # this is fine $ $g++ code1.cpp code2.cpp # this is dead /tmp/ccLY66HQ.o:(.bss+0x0): multiple definition of `a’ /tmp/ccnIOmPC.o:(.bss+0x0): first defined here collect2: ld returned 1 exit status C&C ++之间是否存在全局变量链接差异?

全局变量与局部变量的重新声明

当我编译下面的代码时 #include int main() { int a; int a = 10; printf(“a is %d \n”,a); return 0; } 我收到一个错误: test3.c: In function ‘main’: test3.c:6:5: error: redeclaration of ‘a’ with no linkage test3.c:5:5: note: previous declaration of ‘a’ was here 但是,如果我将变量设为全局,那么它可以正常工作。 #include int a; int a = 10; int main() { printf(“a is %d \n”,a); return […]

C在不同文件中定义的相同全局变量

我正在这里阅读这段代码 (中文)。 有一段关于在C中测试全局变量的代码。变量a已经在文件中定义了两次。 在文件foo.c定义了一个带有一些值和一个main函数的struct b 。 在main.c文件中,定义了两个没有初始化的变量。 /* th */ #ifndef _H_ #define _H_ int a; #endif /* foo.c */ #include #include “th” 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, ba, bb, main); } /* main.c */ #include […]