When debugging recursive functions in C++, it can be helpful to trace every entry and exit of a function. With GDB (GNU Debugger) and a custom Python script, we can automate this process.
We first compile our program with debugging symbols enabled and without optimization:
g++ -g -O0 sample.cpp -o sampleThis ensures that GDB can read source-level information.
Next, we launch GDB and load a Python script (trace.py) that sets breakpoints automatically:
gdb -ex "source trace.py" ./sampleThis script parses all functions from the program and sets breakpoints to monitor their execution.
Here is a simple recursive program (sample.cpp):
#include <cstdio>
void func(int value) {
fprintf(stderr, "value=%d\n", value);
if (value==0) return;
return func(value-1);
}
int main() {
func(10);
return 0;
}The func function calls itself until the value reaches zero.
The trace.py script uses GDB’s Python API. It sets a breakpoint at every function (except main) and prints messages when entering and exiting:
>> Entering func>> Exiting func
It does this by using Breakpoint and FinishBreakpoint classes to hook into function calls.
When we run the program under GDB, we get the following trace:
>> Entering func
value=10
>> Entering func
value=9
...
>> Entering func
value=0
>> Exiting func
>> Exiting func
...
>> Exiting func
This shows each recursive call entering and leaving in order.
By combining GDB with a Python script, we can automatically trace all function calls in a C++ program. This approach is especially useful for debugging recursive functions, as it provides a clear view of the call stack in action.