乐闻世界logo
搜索文章和话题

How to do an specific action when a certain breakpoint is hit in GDB?

1个答案

1

In GDB (GNU Debugger), automatically executing specific actions when the program hits a breakpoint can be achieved by using the commands command after setting a breakpoint. This feature is particularly useful for automating certain debugging tasks, such as printing variable states, evaluating expressions, or calling functions.

Steps Example

Suppose we are debugging a C program named example.c, and we want to set a breakpoint at the entry of the function testFunc, printing the values of variables a and b each time the breakpoint is hit, and then continue execution. Here are the specific steps:

  1. Start GDB and load the program

    bash
    gdb example
  2. Set the breakpoint

    gdb
    break testFunc
  3. Define the breakpoint commands

    gdb
    commands > print a > print b > continue > end

    Here, the commands command is followed by the breakpoint number (if multiple breakpoints exist). If a breakpoint was just set, GDB typically automatically selects the most recent breakpoint. Within the commands block, print a and print b are the commands executed when the program stops at this breakpoint, and the continue command causes the program to automatically continue execution after printing.

  4. Run the program

    gdb
    run

    Now, whenever the program reaches the testFunc function, GDB automatically prints the values of variables a and b, and continues execution without manual intervention.

This method is highly applicable for monitoring the behavior of specific functions or code segments, and facilitates reducing repetitive manual work through automation. It is particularly useful when debugging complex issues or long-running programs.

2024年7月17日 09:22 回复

你的答案