extern如何工作? [英] How does extern work?

查看:129
本文介绍了extern如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

extern 是C中的存储类。它如何工作?下面给出的代码的输出是20.这是输出呢?

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;


推荐答案

这意味着三件事:


  • 该变量具有外部链接,可从程序中的任何位置访问;

  • 具有静态存储持续时间,因此其生存期是程序的(或多或少);和

  • 声明只是声明,而不是定义。变量也必须定义在某个地方(不带 extern ,或者带有初始化程序,或者两者都有)。

  • 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).

具体来说,您的 extern int a; 声明变量存在,但在此时未定义。此时,您可以使用它,并且链接器将确保您的使用引用定义。然后你有必要的定义, int a = 20; 在结尾,所以一切都很好。

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.

这篇关于extern如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆