Search code examples
clinuxstaticextern

extern variable definition in other file


Hi I have following 2 files in a.c I have

#include <stdio.h>

int i;
static int j;
int main()
{
        printf("i = %d\n",i);
        printf("j = %d\n",j);
        return 0;
}

and in b.c I have

#include <stdio.h>

extern int i=2;
extern int j=5;

In this example when I run, I get answer as 2,0 but complier throws warning initialized and declared ‘extern’ for both variables.

How b.c is able to access j and not throws error since scope of j is for a.c only?


Solution

  • First of all, initializing a variable at the same time as you declare it as extern doesn't make any sense. Which is why you get a compiler warning. C allows it if the variable is at file scope, but as always, C allows many bad things.

    Also note that the use of extern is almost always bad practice and should be avoided.

    Now for the code, i behaves as expected because the i in both files refer to the same variable. j on the other hand is static, so the scope of that variable is reduced to the local file. There is a rule in the standard saying that all static variables must be initialized to 0 unless the programmer initialized them explicitly. So the value of j will be 0.

    Since j is static, extern int j; refers to "another j somewhere else", because there is no j variable visible to the file where you wrote the extern. Since "another j somewhere else" isn't used by the program, that variable will simply get discarded.

    static and extern are in many ways each other's opposites. If you think it makes sense to declare the same variable both static and extern, you need to study the static keyword more.