Inside main() function when I create a separate block (new pair of curly braces) like this one-:
int main(void){
int x = 10;
{
extern int y;
printf("\tNo. is %d\n", y);
int y = 20;
}
}
When I compile this code I come across an error :
test.c: In function ‘main’:
test.c:12:9: error: declaration of ‘y’ with no linkage follows extern declaration
int y = 20;
test.c:9:16: note: previous declaration of ‘y’ was here
extern int y;
But
If the definitaion for int y is placed at end of the main function the code compiles and run perfectly okay.
What could be reason behind this error? According to my book if a variable is declared as extern then we can use it before defining it and the compiler will search in the whole file for definition of the variable.
C distinguishes variables in file scope (= outside any function) and variables in a local scope.
The
y-variable that you declare withexternand use in theprintfrefers to a variable in file scope. That variable is only declared and must be "defined" elsewhere. That is storage must be allocated for it.If you you have the second declaration of
yinside any of the{}this is a local variable that is different from the file scope variable. If it is outside, it is a declaration of a file scope variable and a "tentative definition" of that file scope variable. So in this later case you have a declaration that is visible where the variable is used, and somewhere else a definition such that storage is provided, and everything works fine.