10

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.
9
  • Could be related to this. If you add a definition or make it inline, does it work then? Commented Aug 5, 2021 at 20:37
  • 1
    Hmm, not even if I add a constructor and set a breakpoint in it does it think that bar or foo::bar exists in the current context. Commented Aug 5, 2021 at 20:52
  • 2
    It could well be that you can not. Such name doesn't have linkage, and gdb so it doesn't exist as a symbol for gdb. And gdb is not a compiler, so it can not extract this information from the C++ code itself. It is just a limitation of the toolchain. Commented Aug 5, 2021 at 20:52
  • @TedLyngmo no instance was created, why would it think otherwise? it would inline the value of static member, that's all. Commented Aug 5, 2021 at 22:04
  • 1
    If I add an instance of foo, then p foo::bar works for me in gdb. Commented Aug 6, 2021 at 14:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.