这很难用文字解释,所以我举个例子。
//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,它不会使用静态变量的值。
最佳答案
来自 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.
因此,函数作用域内的 extern
意味着该变量默认具有外部链接,但如果有另一个可见的定义,则会使用该定义。
关于c - 为什么函数中全局静态变量优先于外部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15669654/