【发布时间】:2014-01-11 16:55:17
【问题描述】:
我有这种情况:
// Test.h
extern const int param;
class Test
{
private:
int i;
public:
int foo();
};
和
// Test.cpp
#include "Test.h"
int Test::foo() { return param*10; }
和
// core.h
#include "Test.h"
const int param = 1; // should have internal linkage later in core.cpp
int do_stuff ();
和
// core.cpp
#include "core.h"
int do_stuff () { Test obj; return obj.foo(); }
int main() { return do_stuff(); }
但是没有链接器错误。链接器如何查看 Test.cpp 的 const int param,它是通过 core.h 在 core.cpp 中定义的,具有内部链接(默认为 const 定义)?
当我像这样重写 core.h 时(更改两行):
// core.h
const int param = 1;
#include "Test.h"
int do_stuff ();
缺少param 会出现链接器错误。然后,当我这样改变它时:
// core.h
extern const int param = 1;
#include "Test.h"
int do_stuff ();
一切都恢复正常了。
我想,可能在原始情况下,core.cpp 中自动内联了类 Test,因此 Test.cpp 不存在,整个代码都在 core.cpp 中,所以一切正常。但是为什么它应该依赖于更改 core.h 中的两行呢?
【问题讨论】:
标签: c++ static global-variables constants extern