我的简单代码如下:
a.cpp:
#include <iostream>
namespace asd
{
class B
{
public:
void ss()
{
extern int i;
std::cout << i;
}
};
}
int main()
{
asd::B e;
e.ss();
}
b.cpp:
int i = 4;
这段代码是否符合标准?
Visual Studio编译它时没有错误,但是Intel C++编译器说:
未解析的外部符号“int asd::i”(?i @ asd @@@ 3HA)
如果我将b.cpp更改为:
namespace asd
{
int i = 4;
}
然后Visual Studio C++ 2013说:
未解析的外部符号“int i”(?i @@ 3HA)
但是英特尔C++编译器说还可以:)
如果我想在类成员函数中使用这个extern(合法吗?),此代码的正确版本是什么?
编辑:
最好的结果是,当我们将b.cpp更改为:
namespace asd
{
int i = 4;
}
int i = 5;
Visual c++打印5,intel编译器4 :)
最佳答案
在任何函数中声明extern
或static
变量是合法的。您对b.cpp
的修复(将命名空间放在该extern
的定义周围)也是正确的修复。
Visual Studio C++ 2013提示asd
命名空间之外的名称(请检查demangler以查看i
名称周围的这些多余字符代表什么)。这是不正确的,因为该声明将i
放入命名空间asd
中。
C++标准在3.5.7节中对此进行了说明。它以extern
函数为例,但它说明了名称在封闭 namespace 中的放置规则。
namespace X {
void p() {
q(); // error: q not yet declared
extern void q(); // q is a member of namespace X
}
void middle() {
q(); // error: q not yet declared
}
void q() { /* ... */ } // definition of X::q
}
void q() { /* ... */ } // some other, unrelated q
第4、9和11行的注释显示,成员函数中用
extern
声明的名称需要放在封闭的 namespace 中。这是一个很好的独立测试用例,说明了Microsoft编译器中的错误。