在最接近的范围内具有using-directive的局部extern变量声明 [英] Local extern variable declaration with using-directive in the nearest enclosing scope

查看:76
本文介绍了在最接近的范围内具有using-directive的局部extern变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此程序是否符合c ++标准的格式?

Is this program well-formed according to the c++ standard?

namespace X { int i = 1; }

using namespace X;

int main() {
    extern int i;
    i = 2;
}

我用不同的编译器得到不同的结果:

I get different results with different compilers:

  • GCC和Clang给出了链接器错误:未定义对i的引用.

  • GCC and Clang gives a linker error: Undefined reference to i.

Visual c ++接受该程序.

Visual c++ accepts the program.

推荐答案

[basic.link]/p6:

[basic.link]/p6:

如果存在具有相同名称和类型的链接的实体的可见声明,忽略在最内层封闭的命名空间范围之外声明的实体,则块范围声明将声明该相同的实体并接收链接之前的声明.如果有多个这样的匹配实体,则程序格式错误.否则,如果找不到匹配的实体,则块作用域实体将接收外部链接.

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.

X :: i 在extern声明的最内层封闭名称空间(即全局名称空间)之外声明,因此将其忽略.这意味着未找到 i 的声明,因此 extern int i 是具有外部链接的名为 i 的新变量的声明.

X::i was declared outside the innermost enclosing namespace of the extern declaration (i.e the global namespace) so it is ignored. This means no declaration was found for i and therefore extern int i is a declaration of a new variable named i with external linkage.

您的程序将编译,但如果使用块范围 i ,则不会链接.

Your program will compile, but will not link if the block-scope i is odr-used.

这篇关于在最接近的范围内具有using-directive的局部extern变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆