Why does a global static variable take precedence over an extern within a function?

不想你离开。 提交于 2021-01-06 05:54:08

问题


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;
}

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.


回答1:


From n1256 §6.2.2 ¶4:

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.

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.




回答2:


The static class-modifier denotes that the variable will only be visible in this translation-unit (f2.c) By using extern for a, you only declared that variable, but not defined it. Yet, there was an a available in the translation-unit f2.c, so this one will be used.



来源:https://stackoverflow.com/questions/15669654/why-does-a-global-static-variable-take-precedence-over-an-extern-within-a-functi

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