Search code examples
cglobalexternalextern

extern and global variables with the same name in C


I'm trying to figure out what happens if in some program we'll have like that:

extern int x;

void foo(){...}
void bar(){...}

void main(){
foo();
bar();
}
int x=0;

So what is suppose to happen?Why is it allowed to have two such variables with the same name?are they different?


Solution

  • They are not "two" variables. They are the same.

    extern int x;
    

    is a declaration of x.

    and

    int x=0;
    

    provides the definition for x. This is perfectly fine and valid.


    You can have multiple declarations like:

    extern int x;
    extern int x;
    

    too and it'll compile as well.

    Note when you are providing the multiple declarations for the same identifier, the rules are somewhat complex. See: 6.2.2 Linkages of identifiers for details. See static declaration of m follows non-static declaration for an example.