如何使用 gdb 调试函数

How to debug a function with gdb

使用 gdb,我可以在调用函数的任何地方放置一个断点,然后单步执行函数求值。我还可以使用 print 命令评估函数。当在任何断点处停止时,我想通过使用不同的参数逐步执行来调试特定函数。但是,当我尝试在函数处设置断点并为 gdb 提供合适的打印命令时,gdb 对象显示消息 "The program being debugged stopped while in a function called by gdb. Evaluation of the expression containing the function MyClass::mysize(int,int) will be abandoned"。有什么办法可以不重启程序实现吗?

您错过了来自 GDB 的部分消息。这是我的示例程序:

int
foo (int arg)
{
  return arg + 3;
}

int
main ()
{
  return foo (-3);
}

这是我的 GDB 会话:

(gdb) start
Temporary breakpoint 1 at 0x401119: file eval.c, line 10.
Starting program: eval.x 

Temporary breakpoint 1, main () at eval.c:10
10    return foo (-3);
(gdb) break foo
Breakpoint 2 at 0x40110d: file eval.c, line 4.
(gdb) print foo (2)

Breakpoint 2, foo (arg=2) at eval.c:4
4     return arg + 3;
The program being debugged stopped while in a function called from GDB.
Evaluation of the expression containing the function
(foo) will be abandoned.
When the function is done executing, GDB will silently stop.
(gdb) bt
#0  foo (arg=2) at eval.c:4
#1  <function called from gdb>
#2  main () at eval.c:10
(gdb) 

注意来自 GDB 的消息的最后一行:When the function is done executing, GDB will silently stop. 所以 GDB 仍然在带有您传递的参数的被调用函数中。可以在 <function called from GDB>.

的回溯中看到

因此您可以继续单步执行该函数以查看其行为方式。你没有得到的是当函数 returns 时结果的打印,GDB 已经忘记了这就是你想要的事实,所以相反,当函数 returns GDB 将只是让你回到提示。这意味着您应该在 returns.

之前检查函数内部的 return 值