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:
-
Start GDB and load the program
bashgdb example -
Set the breakpoint
gdbbreak testFunc -
Define the breakpoint commands
gdbcommands > print a > print b > continue > endHere, the
commandscommand 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 thecommandsblock,print aandprint bare the commands executed when the program stops at this breakpoint, and thecontinuecommand causes the program to automatically continue execution after printing. -
Run the program
gdbrunNow, whenever the program reaches the
testFuncfunction, GDB automatically prints the values of variablesaandb, 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.