2

This seems to be a trivial question, but I could not find an answer to it.

Suppose that I have defined a class Widget and created the overload:

std::ostream& operator<< (std::ostream& o, const Widget &w) {...}

Is there a way to examine a Widget object in gdb by simply printing it using the above overload?

I am using gdb version 7.7.1.

EDIT:

Suppose that w is a Widget object. I am trying this:

call operator<<(std::cout, w)

and getting the following error message from gdb:

(std::ostream &) @0x615120: <incomplete type>
AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68

1 Answers1

2

This works for me (gdb 7.9.1):

#include <iostream>

struct Foo {
    int i = 17;
};

std::ostream& operator<<(std::ostream &os, const Foo &foo)
{
    os << "i: " << foo.i << "\n";
    return os;
}

int main()
{
    Foo f;
    f.i = 40;

    std::cout << f;
}

I compiled it like this (gcc 5.2):

g++ -Wall -ggdb -std=c++11 test.cpp

and run under gdb

(gdb) br main Breakpoint 1 at 0x400858: file test.cpp, line 14. (gdb) r Starting program: /home/evgeniy/projects/study_c++/operator_print_gdb/a.out

Breakpoint 1, main () at test.cpp:14 14 { (gdb) n 15 Foo f; (gdb) 16 f.i = 40; (gdb) call operator<<(std::cout, f)

(gdb) set var f.i=5

(gdb) call operator<<(std::cout, f)

and it printed 17 and 5

fghj
  • 8,898
  • 4
  • 28
  • 56
  • May be it is fixed in the later gdb version. My gdb chokes on the return value of operator<< and does not flush its stdout buffer. When I call a dump() function of mine, gdb shows the results of the failed call to operatror<< as well. – AlwaysLearning Nov 11 '15 at 17:33
  • I tried your example with gdb 7.10 and could not get it to work. I compiled exactly like you did, set a break point on the last line of `main()` , called `operator<<' and got the same `incomplete type` error. Could it be because I am using the older gcc 4.8.2? – AlwaysLearning Nov 12 '15 at 09:39
  • May be, try also `-g3` instead of `-ggdb` if not help, then it is `gcc` fault – fghj Nov 12 '15 at 09:41
  • Do you get the error in addition to the output? – AlwaysLearning Nov 12 '15 at 09:43
  • @AlwaysLearning `warning`, not `errror`, like this https://sourceware.org/bugzilla/show_bug.cgi?id=11171 but it print right value so I not care about its warnings – fghj Nov 12 '15 at 09:48
  • Hmm... I stand corrected. I also get the output followed by the warning. But it still does not work with my code. There is probably something about the type of my objects... – AlwaysLearning Nov 12 '15 at 10:05
  • For me, the issue was that `std::cout` was line-buffering, and that the output was appearing in a different VSCode tab. Using `std::cerr` avoided the buffering issue. – Eric Nov 13 '22 at 23:35