2

我使用 qt-creator 作为 gdb 的 IDE 和前端。如何在 std::cerr 变量上调用 operator<< 时设置断点?是否可以从 qt-creator 或我必须独立运行 gdb?

4

1 回答 1

2

如何在 std::cerr 设置断点

你的问题没有意义:std::cerr是一个全局变量。您只能在函数上设置断点。您还可以在变量上设置观察点,因此 GDB 会在变量被修改时停止,但这也可能不是您想要的。

可能STDERR_FILENO要问的是:“当某些内容写入文件描述符时,我该如何停止?”。

如果是这种情况,catch syscall write可能就是答案(但真正的答案取决于您的操作系统,您没有透露)。

更新:

我相信捕获系统调用写入不是一个选项,因为我经常写入文件

您可以使系统调用捕获点以写入为条件STDERR_FILENO(在 Linux 上为 2)。示例(这将适用于 Linux/x86_64,但需要针对 Linux/ix86 进行调整):

cat t.cc
#include <iostream>
using namespace std;

int main()
{
   cout << "Hello,";
   cerr << "error 1" << endl;
   cout << " World!" << endl;
   cerr << "error 2" << endl;
}

gcc -g t.cc
gdb -q ./a.out
Reading symbols from /tmp/a.out...done.

(gdb) catch syscall write
Catchpoint 2 (syscall 'write' [1])

# Make the catchpoint conditional on writing to stderr:
(gdb) cond 2 $rdi == 2

# By default, "catch syscall" will stop both before and after the actual syscall
# Ignoring the catchpoint once will skip past the "after" stop.
(gdb) command 2 
Type commands for breakpoint(s) 2, one per line.
End with a line saying just "end".
>ignore 2 1
>end

(gdb) r
Starting program: /tmp/a.out 
Hello,
Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  ../sysdeps/unix/syscall-template.S: No such file or directory.
(gdb) x/s $rsi
0x400a83:   "error 1"    # Good: we caught our first write to std::cerr

(gdb) c
Continuing.
error 1
Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  in ../sysdeps/unix/syscall-template.S
(gdb) x/s $rsi
0x7ffff76298e3 <_IO_2_1_stderr_+131>:   "\n"  # I didn't know endl gets a separate write syscall.
(gdb) c
Continuing.

 World!

Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  in ../sysdeps/unix/syscall-template.S
(gdb) x/s $rsi
0x400a93:   "error 2"
(gdb) c
Continuing.
error 2
Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  in ../sysdeps/unix/syscall-template.S
(gdb) x/s $rsi
0x7ffff76298e3 <_IO_2_1_stderr_+131>:   "\n"
(gdb) c
Continuing.

[Inferior 1 (process 17291) exited normally]
于 2013-01-13T16:49:22.740 回答