Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of extern in the same file

Tags:

c

extern

linker

I am confused with the usage of extern in the same file as shown in the code below. The first case was actually a solution to print a global variable in C (when same name local variable exist), but I am not able to understand how that worked and how the third case didn't work.

Case 1:

int a = 10;
int main()
{
    int a = 20;
    {
        extern int a; // Is this telling the linker to use global variable? 
        printf("A value: %d\n", a);
    }
    return 0;
}

Case 2:

extern int a; // If in the above case extern was telling linker to use global variable 
              // then how in this local variable is getting referred
int main()
{
    int a = 20;
    {
        printf("A value: %d\n", a);
    }
    return 0;
}

Case 3:

// int a = 10;
int main()
{
    int a = 20;
    {
         extern int a; // Why now I get a linking error
         printf("A value: %d\n", a);
    }
    return 0;
}
like image 853
Pranjal Avatar asked Dec 13 '22 16:12

Pranjal


1 Answers

In the first case you have a global a that you override with a local (automatic) a that you again override with the global a (extern can only refer to variables global in some module). It will print 10.

In the second case you have a global a, that resides in this or in another module (c file/compilation unit) that you override with a local a. It will print 20.

In the third case you have a local a that you override with a global a that apparently does not exist in any of your compilation units, hence the linker error.

like image 158
Paul Ogilvie Avatar answered Dec 27 '22 23:12

Paul Ogilvie