如果我在头文件中
namespace Bob
{
extern const T x;
};
在源文件中
extern const T Bob::x = 123;
源文件中的第二个extern
是必须的还是可选的?
我搜索并发现了相互矛盾的信息。
从这个网页: http://msdn.microsoft.com/en-us/library/357syhfh.aspx
但要在 C++ 中获得相同的行为,您必须 [在源文件中] 将 const 变量声明为:
extern const int i = 2;
最佳答案
通常,extern
关键字告诉编译器不要定义符号,因为它将在其他地方定义。所以写例如
namespace Bob {
extern T x;
}
没有定义变量x
,而是声明了它。您可以有任意多个 extern
声明。但是,如果您不提供定义,链接将失败。所以你必须定义
T Bob::x;
代码中的某处以提供定义。
const
关键字在这里有点特殊,因为它表示内部链接。这意味着 x
的定义在定义它的特定编译单元之外是不可见的。要改变这种行为,你需要写
extern const T Bob::x = 123;
如果您希望x
为const
并且还从其他编译单元引用它。
----又一次编辑----
只是为了绝对清楚:
如果一个 const
变量应该在其编译单元之外被引用,那么您必须显式声明它 extern
。
但是,如果声明和定义分开给出,那么定义就不一定需要再次指定关键字extern
。另一个演示示例:
myheader.h
extern const int i;
这声明了 i
一个带有外部链接的 const
整数,但没有定义它。
main.cpp,版本 1
#include "myheader.h" //Through the include, the above declaration of `i` comes before its definition.
const int i=123; // Although the `extern` modifier is omitted here,
// it's still in effect because we already declared `i` as `extern`
// Therefore it makes no difference here, whether or not you specify `extern` again.
// The compiler knows this is a definition either way, because of the initialization.
main.cpp,版本 2
//#include "myheader.h"
extern const int i=123; // this line is declaration and definition in one, because we did not include
// the declaration from myheader.h. Thus, to tell the compiler that you want
// `i` with external linkage, you MUST specify `extern`. Otherwise you'll get
// internal linkage.
我希望现在所有这些对您来说都有意义。
关于c++ - 这里是否需要extern关键字,cpp文件中的const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24698515/