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.
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;
}
Borland C/C++ :
c:\test>bcc32 test1.c test2.c
GCC :
c:\test>gcc test1.c test2.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 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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With