【问题标题】:class using global extern const variable which is defined with internal linkage使用通过内部链接定义的全局 extern const 变量的类
【发布时间】: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


    【解决方案1】:

    您对 const 定义的内部链接的假设并不总是正确的。请参阅标准部分3.5 Program linkage,第 3 页。 3(我引用 N3690):

    具有命名空间范围 (3.3.6) 的名称如果是以下名称,则具有内部链接

    • 显式声明为静态的变量、函数或函数模板;或者,

    • 一个非易失性变量,显式声明为 const 或 constexpr,既没有显式声明 extern,也没有之前声明有外部链接;或

    • 匿名联合的数据成员。

    所以对于第一种情况,param 有外部链接,一切正常。

    对于第二种情况,core.cpp 中有一个内部链接的param,但还有另一个仅声明的param 具有外部链接但没有定义。

    第三种情况,又是一个param

    【讨论】:

    • 感谢完美回答!
    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 2022-09-28
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多