c - 外部、内部且没有链接,或者为什么这不起作用?

标签 c language-lawyer linkage

根据C标准:

In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.

在我的示例中,我们有三个单独的声明,每个标识符都有不同的链接。那么为什么这行不通呢?

static int a; //a_Internal

int main(void) {
    int a; //a_Local
    {
        extern int a; //a_External
    }
    return 0;
}

错误:

In function 'main': Line 9: error: variable previously declared 'static' redeclared 'extern'

为什么编译器坚持要我重新声明而不是尝试访问另一个文件中的外部对象?

供引用的有效 C++ 示例:

static void f();
static int i = 0;               // #1
void g() {
  extern void f();              // internal linkage
  int i;                        // #2 i has no linkage
  {
    extern void f();            // internal linkage
    extern int i;               // #3 external linkage
  }
}

Clang 和 VC 似乎都适合我的 C 示例;只有某些版本的 GCC(不是全部)会产生上述错误。

最佳答案

§6.2.2, 7 说:

If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

所以,你的程序有undefined behaviour .

§6.2.2, 4 说

extern int a; //a_External

具有外部链接,因为先前的声明在范围 int a 中可见;//a_Local 没有链接。但是

static int a; //a_Internal

声明带有内部链接的a。因此,根据 §6.2.2, 7,它未定义

关于c - 外部、内部且没有链接,或者为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39767348/

相关文章:

c - 使用 write 递归打印数字 c

c - 使用 getpass() 后,我无法再在 linux 命令提示符中输入内容。它正在记录我的击键,但不回显它们

c++ - 在 C++17 中 i++ + i++ 会评估什么?

c++ - 模板非类型参数

c++ - 使用 C 样式链接从函数返回类模板安全吗?

c - 嵌入式系统的libxml交叉编译

c - 在 C 中打印出非均匀参数列表

c++ - 合格类(class)成员

c++ - 类名注入(inject)和构造函数

c++ - 传递给 C 库的函数指针的 C 链接