Search code examples
cexternlinkage

Can't understand difference between a global variable and a variable having external storage class?


What is the difference when I write:-

#include<stdio.h>

int a=10; 

main( )
{
     printf ("%d", a);
}  

And the other one is:-

#include<stdio.h>

main ( )    
{
    extern int a=10; 
    printf ("%d", a); 
}

Solution

  • For starters according to the C Standard the function main without parameters shall be declared like

    int main( void ) 
    

    This program

    #include<stdio.h>
    
    main ( )    
    {
        extern int a=10; 
        printf ("%d", a); 
    }
    

    is incorrect. According to the C Standard (6.7.9 Initialization)

    5 If the declaration of an identifier has block scope, and the identifier has external or internal linkage, the declaration shall have no initializer for the identifier.

    However if you will remove the initializer as for example

    #include<stdio.h>
    
    main ( )    
    {
        extern int a; 
        printf ("%d", a); 
    }
    

    nevertheless the program will have undefined behavior. According to the C Standard (6.9 External definitions)

    5 An external definition is an external declaration that is also a definition of a function (other than an inline definition) or an object. If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one.

    Take into account that in the program above the identifier a has external linkage (6.2.2 Linkages of identifiers)

    4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

    A correct program can look like for example the following way

    #include <stdio.h>
    
    int main(void) 
    {
        extern int a;
        printf( "a = %d\n", a );
    
        return 0;
    }
    
    int a = 10;
    

    Its output is

    a = 10
    

    In this program there is external definition of the identifier a with external linkage

    int a = 10;