0

I have the following :

Header file:

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();     
};

Source file :

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

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

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

int main () {
  S a;  
}

Output from the compiler :

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

See the bugzilla report here : https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67155

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
h4ck3rm1k3
  • 2,060
  • 22
  • 33
  • 2
    I don't see a definition for `S::u`. Making it `constexpr` doesn't mean that the declaration is a definition. – chris Aug 08 '15 at 03:17
  • The object is defined inline in the header. If used in the header it works, if it is a c string it works, see the code here https://github.com/h4ck3rm1k3/gcc-plugin-cpp-template/tree/constexpr/testcase – h4ck3rm1k3 Aug 08 '15 at 03:56
  • adding this to the c file solved the problem. constexpr CU S::u; – h4ck3rm1k3 Aug 08 '15 at 03:59
  • here is the best description of the problem https://gcc.gnu.org/wiki/VerboseDiagnostics#missing_static_const_definition thanks to Jonathan Wakely (@redi ) – h4ck3rm1k3 Aug 08 '15 at 13:29

1 Answers1

1

The answer is to add this to the source file :

constexpr CU S::u;

Thanks @chris and @Drew Dormann.

h4ck3rm1k3
  • 2,060
  • 22
  • 33