Printing C ++ Class Objects Using GDB

Is there some kind of “default function” for printing an object, such as a string, in GDB when we debug C ++ applications? Something like: toString ();

Or should my class implement something like this?

+4
source share
4 answers

You can always print std::string(or anything else in this case) with the command print. However, struggling with the internal components of C ++ template templates may not be pleasant. In the latest versions of toolchains (GDB + Python + Pretty Printers, which are usually installed together as part of development packages on most Linux-friendly distributions), they are automatically recognized and printed (pretty!). For instance:

$ 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 pointed out by @ 111111, check out http://sourceware.org/gdb/wiki/STLSupport for instructions on how to install this yourself.

+3
source

- . gdb. std::string c_str(), const char*:

(gdb) p str.c_str()
$1 = "Hello, World!"

, .

+2

gdb print, gdb , . gdb.

+1

operator<< GDB

C++ Java toString? , operator<< to string .

, , , , :

  • ( !)
  • - GDB
  • C++

, operator<< GDB, : & lt; & lt; GDB

", !":

(gdb) call (void)operator<<(std::cerr, my_class)
MyClass: i = 0(gdb)

, .

main.cpp

#include <iostream>

struct MyClass {
    int i;
    MyClass() { i = 0; }
};

std::ostream& operator<<(std::ostream &oss, const MyClass &my_class) {
    return oss << "MyClass: i = " << my_class.i;
}

int main() {
    MyClass my_class;
    std::cout << my_class << std::endl;
}

:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp

Tested in GDB 8.1.0, Ubuntu 18.04.

0
source

All Articles