This seems very trivial but a somewhat rigorous explanation for the following behavior will help my understanding of extern
a lot.So I'll appreciate your answers.
In the following sample program,I've declared an extern
variable x
inside a function (main()
).Now if I define the variable at file scope right after main()
and assign 8
to it, then the program works fine and 8
is printed.But if I define the variable x
inside main()
after the printf()
,expecting the extern
declaration to link to it, then it fails and gives the following error:
test.c||In function 'main':|
test.c|7|error: declaration of 'x' with no linkage follows extern declaration|
test.c|5|note: previous declaration of 'x' was here|
||=== Build finished: 1 errors, 0 warnings ===|
#include<stdio.h>
int main()
{
extern int x;
printf("%d",x);
int x=8; //This causes error
}
//int x=8; //This definition works fine when activated
I see only one fault in the code,that the statement int x=8
means we are declaring x
again as a variable with auto
storage class.Rest I don't understand.Can you tell me the following:
1) Why are we allowed to declare an extern
variable inside a function,without any warning or error?If valid,what exactly does it mean?
2) Since we declared x
as extern
inside the function and it showed no error,why then this declaration doesn't link to the definition of the variable inside the function,but looks outside,when the variable is defined outside? Is conflicting storage-class declaration auto-vs-extern
the reason for this?
extern
variable declaration is a promise to the compiler that there would be a definition of a global variable some place else. Local variables do not qualify as fulfillments of the promise to the compiler, because they are invisible to linkers. In a sense, extern
declarations are similar to forward declarations of functions: you say to the compiler "I know this function is there, so let me use it now, and let linker take care of locating the actual implementation".