可变量声明为静态和extern? [英] Can a variable be declared both static and extern?

查看:229
本文介绍了可变量声明为静态和extern?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面没有编制?

...
extern int i;
static int i;
...

但如果顺序颠倒,它编译罚款。

but if you reverse the order, it compiles fine.

...
static int i;
extern int i;
...

这是怎么回事呢?

What is going on here?

推荐答案

这是因为在C ++标准为例具体给出时,它的讨论,宣布外部或内部连接的复杂性。这是在第7.1.1.7,这有这样使出:

This is specifically given as an example in the C++ standard when it's discussing the intricacies of declaring external or internal linkage. It's in section 7.1.1.7, which has this exert:

static int b ; // b has internal linkage
extern int b ; // b still has internal linkage

extern int d ; // d has external linkage
static int d ; // error: inconsistent linkage

第3.5.6节讨论如何的extern 应该表现在这种情况下。

Section 3.5.6 discusses how extern should behave in this case.

发生了什么事是这样的:静态INT I (在这种情况下)是一个定义,其中静态表示该 I 的内部连接。当的extern 后发生的静态编译器看到这个符号已经存在,并且接受它已经具有内部连接,并进行上。这就是为什么你的第二个例子编译。

What's happening is this: static int i (in this case) is a definition, where the static indicates that i has internal linkage. When extern occurs after the static the compiler sees that the symbol already exists and accepts that it already has internal linkage and carries on. Which is why your second example compiles.

的extern ,另一方面是一个宣言,它含蓄地指出,符号有外部链接,但实际上并没有创造任何。由于没有 I 在第一个例子中,编译器的寄存器 I 为具有外部链接,但是当它到达你的静态发现不兼容的声明,它具有内部连接,并给出了一个错误。

The extern on the other hand is a declaration, it implicitly states that the symbol has external linkage but doesn't actually create anything. Since there's no i in your first example the compiler registers i as having external linkage but when it gets to your static it finds the incompatible statement that it has internal linkage and gives an error.

在换句话说,它是因为声明是不是定义'软'。例如,你可以多次申报同一件事没有错误,但只能定义一次。

In other words it's because declarations are 'softer' than definitions. For example, you could declare the same thing multiple times without error, but you can only define it once.

这是否是在C一样的,我不知道(但低于净codeR的回答告诉我们,C标准包含相同的要求)。

Whether this is the same in C, I do not know (but netcoder's answer below informs us that the C standard contains the same requirement).

这篇关于可变量声明为静态和extern?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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