Printing C++ class objects with GDB
You could always have printed std::string
(or anything else for that matter) using print
command. However, struggling with C++ template container internals might not be pleasant. In the recent versions of toolchains (GDB + Python + Pretty Printers that are usually installed together as part of the development packages on most user-friendly Linux distros), those are automatically recognized and printed (pretty!). For example:
$ cat test.cpp
#include <string>
#include <iostream>
int main()
{
std::string s = "Hello, World!";
std::cout << s << std::endl;
}
$ g++ -Wall -ggdb -o test ./test.cpp
$ gdb ./test
(gdb) break main
Breakpoint 1 at 0x400ae5: file ./test.cpp, line 6.
(gdb) run
Starting program: /tmp/test
Breakpoint 1, main () at ./test.cpp:6
6 std::string s = "Hello, World!";
Missing separate debuginfos, use: debuginfo-install glibc-2.16-28.fc18.x86_64 libgcc-4.7.2-8.fc18.x86_64 libstdc++-4.7.2-8.fc18.x86_64
(gdb) next
7 std::cout << s << std::endl;
(gdb) p s
$1 = "Hello, World!"
(gdb)
As @111111 pointed out, check out http://sourceware.org/gdb/wiki/STLSupport for instructions on how to get this installed yourself.
You can call any member functions from Standard Library or your own data type during debug session. This is sometimes the easiest way to output object state in gdb. For std::string
you could call it's c_str()
member which returns const char*
:
(gdb) p str.c_str()
$1 = "Hello, World!"
Though this will work only for debugging live process, but not for core dump debugging.