为什么枚举常量没有链接?

Why do enumeration constants have no linkage?

我试图了解 enumeration constant 的链接,但在标准 N1570 中找不到明确的答案。 6.2.2(p6):

The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier extern.

所以我需要明白常量不是对象。对象定义为 3.15:

region of data storage in the execution environment, the contents of which can represent values

还有6.2.2(p4)(强调我的):

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) 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.

总之6.4.4.3(p2):

An identifier declared as an enumeration constant has type int.

结合所有我不明白为什么

enum test {
    a = 1
};

extern int a; //compile-error. UB?

不编译?我希望 a 有外部链接。

LIVE DEMO

行为是否明确?您能否提供对标准的参考解释?

An identifier declared as an enumeration constant has type int

这并不意味着它是一个int类型的变量

但是

extern int a;

说有一个int类型的变量叫a,这个和枚举常量冲突


Why does not enumeration constant have no linkage

出于同样的原因,常量 123(也具有类型 int,但无论如何)也没有链接

链接在这里无关紧要。在同一个编译单元中你尝试有两个相同的标识符想象一下如果代码编译:

enum test {
    a = 1
};

extern int a; 


int b = a;   // which `a`? a as the external variable or `a` as a constant? How to decide.

在6.2.2 4中,标准只打算讨论对象和函数的标识符的链接,但没有明确这一点。

枚举常量只是值,不是对象或函数,它们的标识符从来没有任何联系。

遵守声明 extern int a;a 声明为 int 对象的标识符。 int 对象与 int 值不同,因此名为 a 的枚举常量不能与名为 aint 对象相同。因此,即使在考虑链接之前,extern int a; 的声明也是无效的。