sandeep.ganage January 2017

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.

#include <stdio.h>

int a = 1;
int main()
    printf("test1 - a val = %d\n",a);
    printf("After Return : %d",a);

#include <stdio.h>

int a;
int fn()
    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:

  1. 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.
  2. Is this behaviour with/without extern keyword is compiler-dependent?


Mohit Jain January 2017

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.

Post Status

Asked in January 2017
Viewed 3,894 times
Voted 5
Answered 1 times


Leave an answer