Search code examples
cdeclarationexternaccess-specifier

C - Writing extern keyword explicitly for global variable


I have 2 C files below. From what i read i know that global variables' default storage class is extern. If i type it explicitly i am getting undefined variable error. What am i missing here? Does that mean when i omit extern keyword it becomes a definition but when i type it out its only a declaration?

file1.c

#include <stdio.h>
#include <stdlib.h>
extern void file2function();

int variable; // if i put extern i will get error, isnt it implicitly extern?

int main()
{
    variable = 1;
    printf("file1 %d\n",variable);
    file2function();
    return 0;
}

file2.c

#include <stdio.h>
#include <stdlib.h>

extern int variable;


void file2function(){
    variable = 2;
    printf("file2 %d\n",variable);
    return;
}

Solution

  • You need to take a look at the difference between a definition and a declaration

    That said, a variable declaration with extern storage is a hint to the compiler that the object is defined in some other place (or translation unit). It is not a definition on its' own.

    You need to have a definition in one of the translation units used to generate the binary.

    In your case, if you put extern in both the files, int variable becomes the declaration in both the cases. That's why, in linking stage, compiler cannot find a definition which was promised, so it screams.

    On the other hand, if you remove the extern from one (only one) of the files, in that file, int variable; is a definition and the other translation unit refers to this definition, so, all good.