As @ssbssa pointed out, as long as one instance of the class is created, it works. Doesn't matter where, instance could even be created in an unused function. For example:
#include <iostream>
struct foo {
static const int bar = 5;
};
void unused() {
foo f;
}
int main() {
return 0;
}
And in gdb:
gdb) info variables
All defined variables:
...
File test.cpp:
4: const int foo::bar;
...
(gdb) p foo::bar
$1 = 5
You can see that as long as there is one instance of foo somewhere, there is a symbol for it in .debug_info
section of the binary, i.e.:
user@krypton:~$ readelf -w a.out | grep foo
<28ee> DW_AT_name : foo
<2901> DW_AT_linkage_name: (indirect string, offset: 0xcfa): _ZN3foo3barE
Note that the same symbol is missing if the compiler detects that no instances of the class are ever created. Seems to be some quirk/optimization of GCC that can't be disabled.