C ++ static constexpr类成员,具有复杂的类链接问题

时间:2015-08-08 03:11:45

标签: c++ c++11 gcc static constexpr

我有以下内容:

标题文件:

class CU
{
  const char *u;
public:
  constexpr CU (const char *u) :u(u) {}
  constexpr const char *c_str () const { return u; } ;
  constexpr operator const char *  () const { return u; } ;
};

void test2 (const CU & r) ;

class S
{
public:
  static constexpr CU u = CU("foo"); // linker error
  /*
    when I use the u in the normal constructor in a separate file I get a linker error
  */
  S();     
};

源文件:

#include "test.hpp"
#include <iostream>

void test2 (const CU & r) 
{
  std::cerr << r;
}

S::S() 
{
  test2(S::u);
}

int main () {
  S a;  
}

编译器的输出:

g++ -std=gnu++11 test.cpp test.hpp
/tmp/cceBFmJM.o: In function S::S():
test.cpp:(.text+0x35): undefined reference to S::u
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'test' failed
make: *** [test] Error 1

请在此处查看bugzilla报告: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67155

1 个答案:

答案 0 :(得分:1)

答案是将其添加到源文件中:

constexpr CU S :: u;

感谢@chris和@Drew Dormann。