Why GCC compiles and links two files even if 'extern' is not used?
Following are the two separate codes written in two separate files Test1.c and Test2.c. I am not using extern keyword in any file.
int a = 1;
printf("test1 - a val = %d\n",a);
printf("After Return : %d",a);
printf("test2 - a val = %d\n",a);
I compiled this code using gcc:
gcc Test1.c Test2.c
It generates the following output:
test1 - a val = 1
test2 - a val = 1
I tried printing address of variable a in both codes. The address is also same.
Now I have following questions:
Does gcc automatically compile and link even if extern is not used?? Here apparently gcc internally does that as I am compiling these two files together.
Is this behaviour with/without extern keyword is compiler-dependent?
From 6.9.2 External object definitions in C11 specs:
A declaration of an identifier for an object that has file scope
without an initializer, and without a storage-class specifier or with
the storage-class specifier static, constitutes a tentative
definition. If a translation unit contains one or more tentative
definitions for an identifier, and the translation unit contains no
external definition for that identifier, then the behavior is exactly
as if the translation unit contains a file scope declaration of that
identifier, with the composite type as of the end of the translation
unit, with an initializer equal to 0.
int i4; // tentative definition, external linkage
static int i5; // tentative definition, internal linkage
int a; in your case is equivalent to extern if not declared static explicitly.
Asked in January 2017Viewed 3,894 timesVoted 5Answered 1 times