C++标准中冲突声明的定义出处是什么?附示例解析
Great question! Let's break down exactly where this is covered in the C++ standard, using your example of extern const int a; vs extern int a; in namespace scope.
核心标准条款依据
First, let's clarify: when you declare the same name (for a variable, in this case) in the same scope, all declarations must refer to the same entity with a compatible type. If they don't, that's a conflicting declaration, and the program is considered ill-formed (i.e., invalid) per the standard.
Here are the key sections in the C20 standard (earlier versions like C17 have nearly identical wording):
- [basic.link]/6: This clause states that if two declarations declare the same variable name and their types (including cv-qualifiers like
const) are not compatible, the program is ill-formed (no diagnostic required, though most compilers will throw an error anyway). - [decl.dcl]/10: This section reinforces that multiple declarations for the same entity must agree on the type, including any const/volatile qualifiers. A
const intandintare not considered the same or compatible here.
针对你的示例的解释
Your example—extern const int a; and extern int a; in the same namespace scope—fits exactly this scenario:
- The first declaration tells the compiler that
ais a constant integer with external linkage. - The second declares
aas a non-constant integer with external linkage.
Since const int and int are distinct types (the const qualifier makes the type incompatible with its non-qualified counterpart), these two declarations conflict. The standard explicitly disallows this because the compiler can't resolve which type the actual variable a is supposed to have.
额外说明
It's worth noting that this rule applies to declarations that refer to the same entity. If you were to declare these in different scopes (e.g., one inside a function and one at namespace scope), that's a different scenario (shadowing, not conflicting declarations)—but in your case, same namespace scope means they're trying to refer to the same external variable, hence the conflict.
内容的提问来源于stack exchange,提问作者user42768

