简体   繁体   English

使用extern变量编译程序时出现问题

[英]Problems compiling program with extern variable

Inside main() function when I create a separate block (new pair of curly braces) like this one-: 当我创建一个像这样的单独的块(一对新的花括号)时,在main()函数中:

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. 如果将int的定义放在主函数的末尾,则代码将编译并完全正常运行。

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. 根据我的书,如果将变量声明为extern,则可以在定义变量之前使用它,编译器将在整个文件中搜索变量的定义。

您不能在具有相同块作用域的块中两次声明相同名称的变量。

C distinguishes variables in file scope (= outside any function) and variables in a local scope. C区分文件作用域中的变量(=在任何函数之外)和局部作用域中的变量。

The y -variable that you declare with extern and use in the printf refers to a variable in file scope. extern声明并在printf使用的y变量是指文件范围内的变量。 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. 如果您在任何{}都包含y的第二个声明,则这是一个与文件作用域变量不同的局部变量。 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. 是的,在那里使用extern时出现问题。 that means this int y is defined globally in the same file or different file. 这意味着此int y是在同一文件或不同文件中全局定义的。 but without defining y (globally) you are printing that extern value that's why its error for linker 但没有定义y(全局),您正在打印该外部值,这就是其链接器错误的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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