20

你如何operator<<(std::ostream &os, const ClassX &x)从 gdb 内部调用?

换句话说,你如何在 gdb 中打印一个对象?

call std::cout<<x或者call operator<<(std::cout, x)似乎对我不起作用!

有任何想法吗?

4

4 回答 4

11

我发现的唯一方法是:

call 'operator<<(std::ostream&, myclass&)'(mycout, c)

由于由于std::cout某种原因对 gdb 不可见,我不得不像这样创建自己的:

std::ostream mycout(std::cout.rdbuf());

您没有说明任何想要这样做的理由,但不会print yourvariable更容易?

如果这是绝对必须的,你可以Print在你的类中有一个方法并调用它operator<<,然后Print从 gdb 调用你的对象上的方法。

请注意 stdout 可能在 gdb 中缓冲,因此除非您以某种方式重定向它,否则您将看不到任何输出。

请参阅gdb 的邮件存档中有关问题的讨论。

于 2010-09-30T17:35:40.927 回答
6

您还可以定义如下函数:

define printType
call operator<<(std::ostream&, const $arg0 &)(std::cerr, $arg1)
end

并像这样使用它:

printType ClassX objectOfClassX

于 2016-08-18T09:03:10.440 回答
2

对我来说call operator<<运行没有错误,但没有打印。原来我需要打电话给flush. 这是您可以放入的有用功能.gdbinit

define str
    call (void)operator<<(std::cout, $arg0)
    call (void)std::cout.flush()
    printf "\n"
end
于 2018-02-03T20:03:23.943 回答
1

I have the following in my .gdbinit. The previous answers here did not work for me when the operator<< is a template or required a lot of typing to get the types right. This approach searches the symbol table to find the correct operator<<. This only works if the operators have been instantiated explicitly.

python
import gdb
import re
class LexicalCast(gdb.Command):
    def __init__(self):
        super(LexicalCast, self).__init__("lexical_cast", gdb.COMMAND_DATA)

    def matches(self, symbol, type, exact=True):
        params = symbol.find('('), symbol.find(')')
        if -1 in params: return False
        params = symbol[params[0]+1 : params[1]]
        if re.match("^%s, %s( const)?&?$"%(re.escape("std::ostream&"), re.escape(type)), params): return True
        if not exact and re.match("^%s, .*::%s( const)?&?$"%(re.escape("std::ostream&"), re.escape(type)), params): return True
        return False

    def invoke(self, arg, from_tty):
        value = gdb.parse_and_eval(arg)
        type = str(value.type.strip_typedefs().unqualified())
        # isn't unqualified() supposed to do that already?
        if type.startswith("const "): type = type[6:]
        if type.startswith("struct "): type = type[7:]
        if type.endswith(" &"): type = type[:-2]
        # there's probably a better way to browse the list of symbols ...
        shift_operators = gdb.execute("info functions operator<<", False, True).split('\n')  
        matching_operators = [ op for op in shift_operators if self.matches(op, type)]
        if not matching_operators:
            gdb.write("No operator<<(std::ostream&, const %s&) found in the symbols. Trying to find a match with additional namespace qualifiers.\n"%(type,))
            matching_operators = [ op for op in shift_operators if self.matches(op, type, False)]

        if not matching_operators:
            gdb.write("No operator<<(std::ostream&, const .*::%s&) found in the symbols. Did you forget to explicitly instantiate your operator?\n"%(type,))     
        else:
            if len(matching_operators) > 1:
                gdb.write("Found multiple operator<< matching this expression; trying to call each one of them...\n")                          
            for op in matching_operators:
                try:                     
                    op = op.split('  ', 1)[1][:-4] if op.endswith("@plt") else op.split(':', 1)[1].split('&', 1)[1].strip()[:-1]
                    gdb.execute("call (void)'%s'((std::cout), (%s))"%(op, arg))      
                    gdb.execute("call (void)std::cout.put('\\n')")
                    gdb.execute("call (void)std::cout.flush()")
                    break
                except Exception as e:
                    gdb.write("Could not invoke %s: %s\n"%(op, e))

LexicalCast()
end   

In GDB I use it like this:

(gdb) lex sector[0]
4: 1 ~ ([-3.00170 +/- 3.86e-6], [-1.73303 +/- 7.55e-8])
(gdb) lex 123
No operator<<(std::ostream&, const int&) found in the symbols. Did you explicitly instantiate that operator?

This is mostly a hack of course that likely breaks if you have changed how GDB prints info functions, but it works well for my purposes.

于 2019-04-06T14:36:08.087 回答