块范围extern声明 [英] block scope extern declaration

查看:200
本文介绍了块范围extern声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11标准提供了下面的代码片段(我删除了不相关的代码),并说名称 i 有外部链接。 (第3.5.6节)

  static int i = 0; //#1 
void g(){
extern int i; //#3 external linkage
}

为什么要这样做?我误会了什么?两个 i 是指vs2012中的同一个对象。当我在其他地方使用 i 时,我得到了一个未解决的外部错误。我不知道vs2012是否支持这个功能或不。



编辑:
我认为VS2012正在做正确的事情。 #3中的 i 仅需要引用具有链接的 i 。如果编译器找不到一个,那么 i 应该在其他翻译单元中定义。因此, i 应该引用上面代码片段中的相同对象。




如果有一个具有
相同名称和类型的链接的实体的可见声明,忽略在最内层
包含命名空间范围,块范围声明声明
同一个实体并接收先前声明的链接。如果
没有找到匹配实体,则块范围实体接收外部
链接。


这个功能?

解决方案

#3 它声明一个名为 i 的变量存在于程序中的某处,具有外部链接,但不定义该变量。声明允许您在 g 范围内使用#1 的静态变量,而不使用它。 / p>

您还需要在包含 g 的命名空间中定义它。在这种情况下,它必须在不同的翻译单元中,以便它不会与具有相同名称的静态变量冲突。



要清楚,在这里有两个不同的变量叫做 i ,如下面例子中的解释。 #1 在这里定义; #3 只会声明,需要单独定义。


The C++11 standard give the code snippet below (I deleted unrelated code) and said the name i have external linkage. (clause 3.5.6)

static int i = 0; // #1
void g() {
    extern int i; // #3 external linkage
}

Why do they do this? Did I misunderstand something? The two i refer to the same object in vs2012. And when I use i somewhere else, i got an unresolved external error. I have no idea whether vs2012 support this feature or not.

Edit: I think VS2012 is doing the right thing. The i in #3 only need to refers to an i that has a linkage. If the compiler can't find one, than the i should be defined in other translation unit. So the two i should refer to the same object in the code snippet above.

The quote from the standard:

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 no matching entity is found, the block scope entity receives external linkage.

But why people need this feature?

解决方案

#3 is only a declaration; it states that a variable called i exists somewhere in the program, with external linkage, but does not define that variable. The declaration allows you to use that, rather than the static variable from #1, within the scope of g.

You will also need to define it, in the namespace that contains g. In this case, it will have to be in a different translation unit, so that it doesn't conflict with the static variable with the same name.

To be clear, there are two different variables called i here, as explained in the paragraph following the example. #1 is defined here; #3 is only declared, and needs a separate definition.

这篇关于块范围extern声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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