Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'extern' Keyword [duplicate]

Tags:

c

i am confused in the use of extern keyword in C. when it is used with a variable, then it means the declaration of variable. I declare the variable tmp outside the main() function and define it in a separate block in main but when i print the value in subsequent block i got an error "UNRESOLVED EXTERNAL LINK". I am confused please give me detailed explanation.


#include <stdio.h>
extern int tmp ;
int main()
{
    {
        int tmp = 50;
    }
    {
        printf("%d",tmp);
    }
    return 0;
}

like image 599
Rohit Sehgal Avatar asked Dec 21 '22 00:12

Rohit Sehgal


1 Answers

No; extern int tmp; means "somewhere else there is a definition of the variable tmp"; this is a declaration — you can reference tmp but it is not defined. Further, when you write extern int tmp; outside a function, it means that the variable will be defined outside a function — it is a global variable which may be defined elsewhere in the current source file or in another source file. (The rules for extern int tmp; written inside a function are moderately complex; let's not go there now!)

Your local variable int tmp = 50; in the function is unrelated to the global variable tmp declared outside. The local variable hides the global variable inside the braces. (The local variable is also unused.) The printf() statement, though, references the global variable; the local variable is not in scope for the printf().

Because you do not define the global variable (for example, by adding int tmp = -2; at the bottom of the file), your program fails to link and will continue to do so until you either define the variable in this source file or link in another source file where the variable is defined.

like image 61
Jonathan Leffler Avatar answered Dec 24 '22 02:12

Jonathan Leffler