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 int varis a declaration, it does not allocate any memory forvar, hence when you usevar = 10your program searches for the definition ofvarbut cannot find it.