2

我正在调试一个大型应用程序,我想在将某个字符串写入std::cerr. 我有办法做到这一点吗?

代码中有很多地方都写了这个字符串。字符串并不总是形式

std::cerr << "some error code";

它可能是其他形式,例如

std::cerr << write_error_code();

另请注意,有很多东西被写入,std::cerr所以我不能只是中断std::cerr

我也有同样的问题,std::cout但是如果答案也不适用,我会发布另一个问题。

4

1 回答 1

3

这是我在 Linux 上制作的 С++ 示例。该示例是使用 gcc 4.3 构建的。

#include <iostream>
#include <stdio.h>
#include <setjmp.h>

void write_error_code()
{
  std::cerr << "some error code";
}

int main()
{
  std::cout << "Start, main()\n";
  std::cerr << "some error code" << std::endl;
  std::cerr << "some error code?" << std::endl;
  std::cerr << "some error code?" << std::endl;
  write_error_code();
  std::cout << "End, main()\n";

  return 0;
}

我看了一下 disassemble ,发现这std::cerr << ""是一个带有符号 name 的函数_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
该函数有 2 个参数:__out__s.
所以我创建了一个.gdbinit文件:

host: srv2-x64rh5-02, OS: Linux 2.6.18-238.el5>more .gdbinit
file a.out
b _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
commands
silent
if strcmp(__s, "some error code") == 0
  print "Some error code has been given as an arg"
  bt
  c
else
  c
end
end
r
quit

在这里我测试我的程序:

host: srv2-x64rh5-02, OS: Linux 2.6.18-238.el5>gdb -q ./a.out
Reading symbols from /import/home/sergey.kurenkov/src/linux.x64.5.0/tests/test.br_on_std_cerr/a.out...done.
Breakpoint 1 at 0x400710
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x2aaaaaaab000
Start, main()
$1 = "Some error code has been given as an arg"
#0  std::operator<< <std::char_traits<char> > (__out=..., __s=0x400a4c "some error code")
    at /home/zalex/test/gcc_build/x86_64-unknown-linux-gnu/libstdc++-v3/include/ostream:509
#1  0x0000000000400873 in main () at main.cpp:13
some error code
some error code?
some error code?
$2 = "Some error code has been given as an arg"
#0  std::operator<< <std::char_traits<char> > (__out=..., __s=0x400a4c "some error code")
    at /home/zalex/test/gcc_build/x86_64-unknown-linux-gnu/libstdc++-v3/include/ostream:509
#1  0x000000000040084f in write_error_code () at main.cpp:7
#2  0x00000000004008f5 in main () at main.cpp:18
some error codeEnd, main()

Program exited normally.
于 2012-08-16T07:04:32.100 回答