简体   繁体   中英

Problems compiling program with extern variable

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;

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 with extern and use in the printf refers 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 y inside 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.

yes there is problem there when you used extern there. that means this int y is defined globally in the same file or different file. but without defining y (globally) you are printing that extern value that's why its error for linker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM