c - 为什么函数中全局静态变量优先于外部变量?

标签 c static extern

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

//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/

相关文章:

python - Django 找不到静态文件。需要第二双眼睛,我快疯了

带有静态初始值设定项的java嵌套类

c++ - 可以将变量重新声明为推断为相同类型的 auto 吗?

c - 从文件读取并使用 strtok while 循环仅打印每行的第一个单词

c - 如何引用动态链接库中的全局变量?

java - Java中serialVersionUID是如何序列化的?

compiler-construction - 如何链接两个nasm源文件

c++ - 使用 "extern"关键字而没有 #include "file.h"

c - 在C中设计队列。向队列添加元素时出现段错误

c - C 结构中奇怪的 const char 指针成员初始化