使用GDB打印C ++类对象

问题描述 投票:3回答:3

在我们调试C ++应用程序时,是否有一些“默认函数”在GDB上打印像字符串这样的对象?像:toString();

或者我的班级必须实施类似的东西?

c++ debugging gdb
3个回答
3
投票

您可以使用std::string命令始终打印print(或其他任何内容)。但是,与C ++模板容器内部的挣扎可能并不令人愉快。在最新版本的工具链(GDB + Python + Pretty Printers,它们通常作为大多数用户友好的Linux发行版的开发包的一部分一起安装)中,这些工具链会被自动识别和打印(非常好!)。例如:

$ 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) 

正如@ 111111指出的那样,请查看http://sourceware.org/gdb/wiki/STLSupport,了解如何自行安装。


2
投票

您可以在调试会话期间使用标准库中的call any member functions或您自己的数据类型。这有时是在gdb中输出对象状态的最简单方法。对于std::string你可以称之为c_str()成员返回const char*

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

虽然这只适用于调试实时进程,但不适用于核心转储调试。


1
投票

gdb有一个内置的print命令,你可以在gdb中调用任何变量或表达式来查看它的值。您应该查看gdb文档以获取详细信息。你可以找到完整的手册here和一个体面的介绍指南可以找到here

© www.soinside.com 2019 - 2024. All rights reserved.