c - 使用外部链接声明的对象的外部定义

标签 c language-lawyer declaration definition linkage

我对 N2310 C18 的 6.9 p5 中的措辞有点困惑:

If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or _Alignof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one. 164)

问题:从这句话中是否可以明显看出,程序中某处的外部定义(如果有)也应该声明具有外部链接的标识符?

正如我所强调的,在整个程序的某个地方,应该有一个标识符的外部定义。它没有指定定义应使用哪个链接来声明标识符。示例:

tu1.c:

int a = 10;

tu2.c:

static int a = 20;

正式来说,我们在 tu1.c 中声明了一个标识符 a 的外部定义,在 tu2.c 中声明了另一个外部定义,因此我们可以应用我在上面引用的这个例子。

尽管要表示以不同方式声明的相同实体标识符,但应按照 6.2.2/2 中的规定使用外部链接进行声明:

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.

这里的情况并非如此。

最佳答案

参见 C11 §6.2.2 Linkages of identifiers :

… There are three kinds of linkage: external, internal, and none.

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.

If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

已添加强调。

如果使用 static 指定文件作用域变量,则它具有内部链接,并且与具有外部链接的变量的讨论无关。

关于c - 使用外部链接声明的对象的外部定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588854/

相关文章:

c++ - 如何找到我的进程在 Linux 中打开的文件句柄?

c++ - [ranges.subrange] 中 `iterator-sentinel-pair` 概念的目的是什么?

c++ - 仅存在声明时不包含类头

此处不允许 java.util.Scanner 对象声明

c - 如何破解这个位域?

c - 如何在 C 中根据用户输入编辑文件的特定部分?

c++ - 作为非类型模板参数的引用

c++ - 为什么不能在没有可变参数的情况下在 lambda 内部转发参数?

c++ - 使用非常量变量声明局部数组来设置长度,它有效吗?

c - C语言如何提示用户从键盘输入一个整数和一个字符