【问题标题】:c++ linking error on static const [duplicate]静态常量上的c ++链接错误[重复]
【发布时间】:2015-03-18 17:20:51
【问题描述】:

我正在使用 gcc (Debian 4.4.5-8) 4.4.5。使用以下代码,我收到链接错误:

/tmp/ccOeGgC9.o:在函数A::func()':
(.text+0x1b): undefined reference to
B::CONST_B'
(.text+0x23): 对 `A::CONST_A' 的未定义引用

标题:

class A {
    public:
    static const int CONST_A = 10;
    int func();
};
class B {
    public:
        static const int CONST_B = 20;
};

cpp 文件(有链接错误):

int A::func() {
    bool c = true;
    const int a = (c == true) ? B::CONST_B : CONST_A;
}

int main() {
    return 0;
}

要修复错误,我必须编写 cpp 文件如下:

cpp 文件(工作):

int A::func() {
    bool c = true;
    int a = CONST_A;
    a = (c == true) ? B::CONST_B : a;
}

int main() {
    return 0;
}

你能解释一下为什么我不能编译第一个代码吗?

【问题讨论】:

  • 我看不到您的示例如何给出链接器错误。在这种情况下,CONST_BCONST_A 不使用 odr。 coliru.stacked-crooked.com/a/0e25fcbbc9d39dab
  • 我用较新版本的 gcc 进行了尝试,但没有看到链接器错误,但我只能用 gcc (Debian 4.4.5-8) 4.4.5 编译我的代码
  • @0x499602D2 这类 ODR 违规不需要诊断,因此干净的编译并不能证明代码是正确的

标签: c++


【解决方案1】:
class A {
    public:
    static const int CONST_A = 10;
    int func();
};

在这个例子中像CONST_A这样的静态成员必须在类外定义

喜欢这个

class A {
   public:
   static const int CONST_A = 10;
   int func();
};

const int A::CONST_A = 10;

【讨论】:

猜你喜欢
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2013-10-08
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
相关资源
最近更新 更多