Why is Borland compiling with multiple definitions of the same object in different C files, but not GCC?

I study the behavior of global variables.

So far, I have thought that pluralizing global variables is an illegal way and should receive an error message. But I got an unexpected result from the Borland C / C ++ compiler, while GCC gave me the expected result.

the 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; } 

At the 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 are no errors and compiling & link successfully (this is unexpected for me). After running test1.exe the console printed 2. This is the num value defined in test2.c .

  • GCC:

GCC gave me an error with several num definitions. Of course a.exe not done (this is what I expected)

Why is this happening? Please let me know. Thanks!

+5
source share
1 answer

Several external object definitions are undefined behavior in C. A common extension is to accept multiple definitions if they disagree (usually with the same type and without an initialization value).

C99 6.9p5 says:

If an identifier declared with external connection is used in an expression (different from the operand of the sizeof operator, the result of which is an integer constant), somewhere in the entire program there must be exactly one external definition for the identifier; otherwise there should be no more than one

and C99, 4.p2:

Violation of "must" out of limitation implies UB

+8
source

Source: https://habr.com/ru/post/1209955/


All Articles