Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a concept behind using extern in c/c++?

Tags:

c++

c

extern

Sorry for this type of question. But, I am very curious about the keyword extern in C\C++.

while searching for explanation for extern I got to know that extern tell the compiler that the variable or function is already defined in some other file or program.

But if this is a case then why we use extern?

as I tried some codes as follows:

extern int var;
int main(void)
{
 var = 10;
 return 0;
}

This code is giving me an error message as unresolved external symbol "int var" (?var@@3HA).

and if I am using some code like:

extern int var;
int main(void)
{
 int var = 10;
 return 0;
}

It is not showing any error and gives value same as I have defined in main function.

So, Can any one help me about the behavior of extern? I am little confused on this. Please forgive me if it is not a valid question. Thank you in Advance.

like image 926
A B Avatar asked Dec 19 '22 18:12

A B


1 Answers

extern is used to refer to a variable in another translation unit ("source file"). For instance, your code in main.c looks like this:

extern int var;
int main(void)
{
    var = 10;
    return 0;
}

This code contains a declaration for an integer named var, but no definition, because extern explicitly says: "the definition for this is somewhere else"

You could define another source file, say, other.c:

int var = 0;

Then, after you add this new translation unit to your build command, your program will link fine, and the code in both files can operate on the shared var variable.

In the second version, you just override the declaration of the extern var with a local variable in your main function. Since the extern var is not (ODR-)used anymore, the linker does not require it, so your executable can build successfully.

like image 75
Martin J. Avatar answered Dec 24 '22 00:12

Martin J.