Undefined reference for static const class member

Jonathan Wakely jwakely.gcc@gmail.com
Wed Oct 14 15:58:00 GMT 2015


On 14 October 2015 at 16:34, Hellmund, Andre-Marcel (MRT) wrote:
> Hi,
>
> I am currently facing a strange behavior of the compiler when using static
> const class members in C++14 mode as described below. I tested this with gcc
> versions 4.9.2 (self-build) and 5.1.0 (from Ubuntu repositories). The
> reproducer is the following:
>
> ### test.cpp ###
> #include <utility>
>
> class TestClass {
> public:
>   static const int ID = 0;
> };
>
> void doStuff () {
>   auto t = std::make_pair(TestClass::ID, TestClass::ID);
> }
>
> //void doStuff1 () {
> //  auto t = static_cast<int>(TestClass::ID);
> //}
> ### END test.cpp ###
>
> If I compile this test program into an object file and check the undefined
> symbols, I get this:
>
> # g++ test.cpp -c -std=c++14
> # nm -C test.o | grep ID
>     U TestClass::ID
>
> If the very same test program is compiled with -O1 or higher optimization
> levels, the symbol TestClass::ID is not undefined anymore. Basically, it
> does not even occur in the object file. Likewise, if I replace doStuff with
> doStuff1 and run the compilation again with -O0, the symbol is _NOT_
> undefined.
>
> Is this behavior expected? And if so, what is the reason for this behavior?
> Since clang behaves the same way: Is the code possibly buggy?

The code is buggy. This is a FAQ:

https://gcc.gnu.org/wiki/VerboseDiagnostics#missing_static_const_definition



More information about the Gcc-help mailing list