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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With