Undefined reference for static const class member

Hellmund, Andre-Marcel (MRT) andre-marcel.hellmund@kit.edu
Wed Oct 14 15:32:00 GMT 2015


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 {
   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?

Thank you for your support in advance and best regards,

I would like to ask if someone could explain if this behavior is as 
expected and i

Karlsruhe Institute of Technology (KIT)
Department of Measurement and Control (Institut für Mess- und Regelungstechnik)

André-Marcel Hellmund, M.Sc.
Wissenschaftlicher Mitarbeiter

Engler-Bunte-Ring 21
76131 Karlsruhe, Germany
Geb. 40.32, Zi. 033

Phone: +49 721 608-47146
Email: andre-marcel.hellmund@kit.edu
Web:  www.mrt.uni-karlsruhe.de
KIT - Universität des Landes Baden-Württemberg und nationales Großforschungszentrum in der Helmholtz-Gemeinschaft

More information about the Gcc-help mailing list