问题
I am studying the behavior of global variables.
So far , I thought the multiple definition of global variables is an illegal way , and must get an error. But I got an unexpected result from Borland C/C++ compiler , while GCC gave me the expected result.
Code:
test1.c
:
#include<stdio.h>
void func(void);
int num=1;
void main(){
func();
return;
}
test2.c
:
#include<stdio.h>
int num=2;
void func(){
printf("%d",num);
return;
}
On MS-DOS prompt
Borland C/C++ :
c:\test>bcc32 test1.c test2.c
GCC :
c:\test>gcc test1.c test2.c
Results
- Borland C/C++ :
There's no error and compile&link successfully(This is unexpected for me).After executing test1.exe
, 2 was printed on the console. This is num
's value defined in test2.c
.
- GCC :
GCC gave me an error of multiple definition of num
. Of course , a.exe
was not made.(This is what I was expecting)
Why does that happen? Please let me know. Thank you!
回答1:
Multiple external definitions of an object is undefined behavior in C. A common extension is to accept multiple definitions if they don't disagree (usually with same type and no initialization value).
C99 6.9p5 says:
If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one"
and C99, 4.p2:
violation of a "shall" outside of a constraint implies UB
来源:https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c