Printing C++ class objects with GDB

前端 未结 4 1244
不思量自难忘°
不思量自难忘° 2021-01-12 19:54

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

4条回答
  •  广开言路
    2021-01-12 20:47

    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:

    • it is less to stop compiling (one would hope!)
    • it is readily available without any GDB setup
    • it can be called from C++ itself when needed

    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.

提交回复
热议问题