How does extern work?

倖福魔咒の 提交于 2019-12-22 09:18:56

问题


extern is a storage class in C. How exactly does it work? The output of the code given below is 20. How is this the output?

#include <stdio.h>

int main()
{
    extern int a;
    printf("%d", a);
    return 0;
}
int a=20;

回答1:


It means three things:

  • The variable has external linkage, and is accessible from anywhere in the program;
  • It has static storage duration, so its lifetime is that of the program (more or less); and
  • The declaration is just a declaration, not a definition. The variable must also be defined somewhere (either without the extern, or with an initialiser, or in your case, both).

Specifically, your extern int a; declares that the variable exists, but doesn't define it at that point. At this point, you can use it, and the linker will make sure your use refers to the definition. Then you have the required definition, int a=20; at the end, so all is well.




回答2:


extern in this case indicates that the symbol a is defined in a different location, such as a different module. So the linker looks for a symbol with the same name in all of the modules that are linked, and if one exists then it sets the address to your local variable a with the address to the externally defined variable. Since you have another a defined outside of your main() function, the a inside your main() function is (basically) the same variable as the one outside.

Since the global a is initialized before the main function executes, the value is 20 by the time you access it.




回答3:


extern means i declare a variable, just like you implement a function in a source file and declare the prototype in a header to allow other source file to use it.

If you put a global variable in a source file, and use a header to declare it with the extern keyword, each source file including the header will see the variable.

The linker will do the job to tie everything just as it does with functions




回答4:


extern as a storage class specifier tells the compiler that the object being declared is not a new object, but has storage elsewhere, i.e., is defined elsewhere. You can try this experiment with your code to see how it works. Leave out the keyword extern in your declaration of int a in main(). Then your printf() will print some garbage value, as it would be a new definition of an int with the same identifier, which would hide the global a declared elsewhere.




回答5:


You use extern to tell the compiler that the variable is defined elsewhere. Without extern in your program compiler would define another variable a (in addition to this in the global scope) in your main() function that would be printed uninitialized.



来源:https://stackoverflow.com/questions/18449838/how-does-extern-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!