Is there some \"default function\" to print an object like a string on the GDB when we are debugging C++ applications? Something like: toString();
Or my class have t
Define operator<<
and call it from GDB
C++ equivalent of Java's toString? was mentioned in the comments, and operator<<
is the most common way of defining a to string method on a class.
This is likely the sanest approach because the resulting string method will be part of the codebase itself, and so:
Unfortunately I haven't found a completely sane way of calling operator<<
from GDB, what a mess: calling operator<< in gdb
This has worked on my hello world test:
(gdb) call (void)operator<<(std::cerr, my_class)
MyClass: i = 0(gdb)
There is no newline at the end, but I can live with that.
main.cpp
#include
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;
}
Compiled with:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
Tested in GDB 8.1.0, Ubuntu 18.04.