GDB - 如何从一开始就进入步进模式

Ale*_*eev 7 c++ debugging gdb

通常,要从C++程序执行的最开始进入步进模式,就可以break main在GDB中使用命令.但这只会在入口处打破程序main().

问题是如何在第一个用户编写的操作(例如,静态定义的类实例的构造函数)上中断程序?

例如,如果我有以下代码,如何在A()不使用break 5命令的情况下中断?

#include <iostream>

struct A {
    A() {
        std::cout << "A()" << std::endl;
    }
};

static A a;

int main() {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

更新:实际上,我调试了其他人编写的非常大的代码.代码中有许多分散在不同源文件中的静态类实例.在每个构造函数上手动设置断点是不可行的.

jxh*_*jxh 3

您可以在构造函数中定义断点。

(gdb) break 'A::A()'
Breakpoint 1 at 0x8048724: file x.cc, line 4.
(gdb) run
Starting program: /.../a.out

Breakpoint 1, A::A (this=0x804a0ce <a>) at x.cc:4
4            std::cout << __func__ << std::endl;
(gdb) bt
#0  A::A (this=0x804a0ce <a>) at x.cc:4
#1  0x08048700 in __static_initialization_and_destruction_0 (__initialize_p=1,
    __priority=65535) at x.cc:8
#2  0x0804871c in _GLOBAL__sub_I_main () at x.cc:10
#3  0x080487a2 in __libc_csu_init ()
#4  0xb7d44a1a in __libc_start_main (main=0x80486ad <main()>, argc=1,
    argv=0xbffff184, init=0x8048750 <__libc_csu_init>,
    fini=0x80487c0 <__libc_csu_fini>, rtld_fini=0xb7fed180 <_dl_fini>,
    stack_end=0xbffff17c) at libc-start.c:246
#5  0x080485d1 in _start ()
(gdb)
Run Code Online (Sandbox Code Playgroud)

请注意使用单引号来指示标识符是 C++ 损坏的。另请注意,堆栈跟踪显示main()尚未调用。

从堆栈跟踪来看,有多种选择可以在调用任何全局构造函数之前设置断点。其中一个断点位于_start

(gdb) break _start
Breakpoint 1 at 0x80485b0
(gdb) run
Starting program: /.../a.out

Breakpoint 1, 0x080485b0 in _start ()
(gdb) bt
#0  0x080485b0 in _start ()
(gdb)
Run Code Online (Sandbox Code Playgroud)