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