为什么全局静态变量优先于函数中的外部变量? [英] Why does a global static variable take precedence over an extern within a function?

查看:67
本文介绍了为什么全局静态变量优先于函数中的外部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很难用文字解释,所以我举一个例子.

this is hard to explain in text, so I will give an example.

//f1.c
int a = 5;

int main()
{
    printf("func2() output is: %i\n", func2() );
    return 0;
}


//f2.c
static int a = 3

int func2()
{
    extern int a;
    return a;
}

当我编译并运行此程序时,我得到3,而我期望为5.有人可以向我解释为什么我得到3吗?我本以为在函数中使用extern不会使用静态变量的值.

When I compile and run this, I get 3, while I was expecting 5. Can anyone explain to me why I get 3? I would have thought that by using extern within the function, it wouldn't use the value of the static variable.

推荐答案

来自n1256§6.2.2¶4:

From n1256 §6.2.2 ¶4:

对于在可见该标识符的先前声明的范围中用存储类说明符 extern 声明的标识符,如果该先前声明指定了内部或外部链接,则该标识符的链接在后面的声明中的链接与在前面的声明中指定的链接相同.如果没有任何在先声明可见,或者在先声明未指定任何链接,则标识符具有外部链接.

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

因此,函数范围内的 extern 表示该变量具有默认值的外部链接,但是如果存在另一个可见的定义,则使用该定义.

So, extern within function scope means that the variable has external linkage by default, but if there's another visible definition, that definition is used instead.

这篇关于为什么全局静态变量优先于函数中的外部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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