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!
gcc -Wall -Wextra -g
– Imperturbable