代码之家  ›  专栏  ›  技术社区  ›  tvaughan

gdb跟踪帮助(或类似)

  •  6
  • tvaughan  · 技术社区  · 15 年前

    我有个申请表。我有源代码(C语言)。我想怎么编译都可以。添加我想要的任何工具。等等。但是,我不想用一堆printf来填充源代码。我想能够生成某种日志,显示某个特定值(例如全局结构的某个成员)何时被写入(其值更改)。我想能够显示源文件和行号,以及新旧值。

    我还希望能够按名称而不是地址指定值。但地址没问题。如果我可以指定一个函数的局部值,就可以获得额外的积分。

    我还在绞尽脑汁想办法找出gdb的跟踪命令。非常感谢您的帮助。谢谢。

    3 回复  |  直到 13 年前
        1
  •  6
  •   derobert    15 年前

    首先,您需要确保使用调试符号编译您的程序,并且可能需要进行w/o优化以使gdb最有用。对于GCC来说 -g -O0 .

    第二,您要寻找的功能不是跟踪,而是监视点。

    (gdb) help watch
    Set a watchpoint for an expression.
    A watchpoint stops execution of your program whenever the value of
    an expression changes.
    

    因此,给出一些示例代码:

    int main() {
        int a;
        a = 1;
        a = 2;
        return 0;
    }
    

    然后您可以在上面运行gdb,并且:

    (gdb) b main
    Breakpoint 1 at 0x80483a5: file test.c, line 4.
    (gdb) run
    Starting program: /tmp/test 
    
    Breakpoint 1, main () at test.c:4
    4               a = 1;
    (gdb) watch a
    Hardware watchpoint 2: a
    (gdb) c
    Continuing.
    Hardware watchpoint 2: a
    
    Old value = -1207552288
    New value = 2
    main () at test.c:8
    8               return 0;
    

    它工作起来有点滑稽,因为它在堆栈上,而不是内存上。如果优化是开着的,它的作用会更小:A会被优化掉。

        2
  •  3
  •   Peter    15 年前

    如前所述,您需要在变量上设置一个观察点。

    您使用“命令”命令

    (gdb) help commands
    Set commands to be executed when a breakpoint is hit.
    Give breakpoint number as argument after "commands".
    With no argument, the targeted breakpoint is the last one set.
    The commands themselves follow starting on the next line.
    Type a line containing "end" to indicate the end of them.
    Give "silent" as the first line to make the breakpoint silent;
    then no output is printed when it is hit, except what the commands print.
    

    所以,从watch命令中找到watchpoint编号,并执行此操作(假设您的表是第二个中断)

    (gdp) commands 2
    > print a
    > cont
    > end
    

    假设a是您想要的变量。如果你对gdb给你的输出满意的话,你可以把打印行去掉。

    还可以使用原始断点中的命令设置观察点并继续。

        3
  •  1
  •   tvaughan    13 年前

    谢谢你们两个@derobert和@peter!我终于回到了这个问题上:

    break main
    commands
            watch somevar
            commands
                    cont
            end
            cont
    end
    run
    

    就这样。当“somevar”是全局的或“main”是本地的时,这是有效的。如果“somevar”是另一个函数的本地变量,只需用上面的函数名替换“main”。

    将这些命令放入一个文件(例如“gdbscript”)并运行gdb,如下所示:

    gdb -x gdbscript a.out