Search code examples
cglobal-variablesextern

C - Using extern to access global variable. Case study


I thought externs were to share variables between compilation units. Why does the below code work ? and how does it work exactly ? Is this good practice ?

#include <stdio.h>
int x = 50;

int main(void){ 
    int x = 10; 
    printf("Value of local x is %d\n", x);

    {
        extern int x;
        printf("Value of global x is %d\n", x);
    }

    return 0; 
}

Prints out :

Value of local x is 10
Value of global x is 50 

Solution

  • When you use the extern keyword, the linker finds a symbol with a matching name in object files / libraries / archives. Symbols are, simply speaking, functions and global variables (local variables are just some space on the stack), thus the linker can do it's magic here.

    About it being a good practice - global variables in general are not considered a good practice since they cause spaghetti code and 'pollute' the symbols pool.