gpt4 book ai didi

c++ - 在 block 作用域中使用 extern

转载 作者:可可西里 更新时间:2023-11-01 15:22:31 24 4
gpt4 key购买 nike

clang、gcc 和 VS2013 都提示在 main() 中重新定义了 w,但我在标准中找不到任何不允许这样做的内容。

namespace N {
extern int j;
int j;
}

int main()
{
extern int w;
int w;
}

这些段落说明了在 block 范围内使用 extern 声明,但它们似乎没有证明错误消息的合理性:

§3.3.1/4

Given a set of declarations in a single declarative region, ...

[ Note: These restrictions apply to the declarative region into which a name is introduced, which is not necessarily the same as the region in which the declaration occurs. In particular, elaborated-type-specifiers (7.1.6.3) and friend declarations (11.3) may introduce a (possibly not visible) name into an enclosing namespace; these restrictions apply to that region. Local extern declarations (3.5) may introduce a name into the declarative region where the declaration appears and also introduce a (possibly not visible) name into an enclosing namespace; these restrictions apply to both regions. —end note ]

§3.3.2/10

[ Note: Friend declarations refer to functions or classes that are members of the nearest enclosing namespace, but they do not introduce new names into that namespace (7.3.1.2). Function declarations at block scope and variable declarations with the extern specifier at block scope refer to declarations that are members of an enclosing namespace, but they do not introduce new names into that scope. —end note ]

最佳答案

我相信这主要包含在 §3.5/6 中。

特别是:

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage.

因此,extern int w; 声明了一个具有链接的 w(外部链接,在这种情况下,因为此时没有匹配的实体可见)。

然后您尝试定义一个没有链接的本地 w(根据 §3.5/8)。

这给出了在相同范围内的两个同名声明,但具有不同的链接。这是 §3.3.1/4 禁止的:

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,

  • they shall all refer to the same entity, or all refer to functions and function templates; or
  • exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall all refer to the same variable or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden (3.3.10).

两者均未引用函数、函数模板、类名称或枚举名称,因此这些“转义条款”均不适用。这两个声明必须引用同一个实体,该实体必须既有外部链接又没有链接。由于这是不可能的,因此代码格式错误。

关于c++ - 在 block 作用域中使用 extern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23367912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com