This seems very trivial, but a somewhat rigorous explanation of the following behavior will help my understanding extern lot. Therefore, I will be grateful for your answers.
In the following sample program, I declared the extern x variable inside the function ( main() ). Now, if I define a variable in the file scope immediately after main() and assign 8 then the program works fine and prints 8 . But if I define the variable x inside main() after printf() , expecting the extern declaration to reference 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 error in the code that the int x=8 operator means that we declare x again as a variable with the storage class auto . I do not understand. Can you tell me the following:
1) Why are we allowed to declare extern variable internally without any warnings or errors? If it is valid, what exactly does this mean?
2) . Since we declared x as extern inside the function and did not detect errors, why then this expression does not refer to the definition of the variable inside the function, but looks outside when the variable is defined outside? Is a conflicting auto-vs-extern storage class declaration causing this?
source share