Examining static const class members in gdb

Viewed 159

How can I print the value of static const class members in gdb?

Say I have:

#include <iostream>

struct foo {
    static const int bar = 5;
};

int main() { 
    std::cout << foo::bar;
    return 0; 
}

How do I examine the contents foo::bar in gdb?

I tried:

(gdb) p foo::bar
No symbol "foo" in current context.
(gdb) p 'foo::bar'
No symbol "foo::bar" in current context.
2 Answers

You can't because gcc does not resolve this to a symbol but to an actual value in the assembly so gdb has nothing to look at. If you needed to you might be able to add the volatile keyword to prevent the compiler from performing this optimization.

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.

Related