Debugging with GDB¶
Core GDB workflows for inspecting program state, backtraces, threads, and failures.
This English edition retains the original diagrams and examples for direct use.



Commands and examples¶
# 添加断点
break main
break factorial
# 多文件设置断点 < 设置my_program.c第10行设置断点 >
break my_program.c:10
# 查询断点
info b
# 删除某处断点 < 删除my_program.c第10行设置断点 >
d my_program.c:10
# 删除某个断点,根据编号 < n 序号(info b中的序号)>
d n
# 删除所有断点
d breakpoints
# 关闭所有断点,使它无效,n可以代表编号,不带n表示所有
disable b [n]
# 使所有断点有效, n可以代表编号,不带n表示所有
enable b [n]
# 执行当前行代码,并跳过函数调用。n或者next(类似F10)
n(next)
# 当前行代码,并且如果当前行包含函数调用,step 会进入该函数内部,逐行调试该函数内部的代码s 或者step (类似F11)
s(step)
# 查看变量
p(print) var
# 查看当前作用域内的所有局部变量。
info locals
# 修改变量
set var
# 跟踪某个变量,每次停下都打印值
display <var>
# 取消跟踪
undisplay n # 取消编号为 n 的跟踪
(gdb) step # 进入当前行的函数内部
(gdb) next # 跳过函数调用,执行下一行
(gdb) continue # 继续执行程序,直到遇到下一个断点
(gdb) until n # 跳转至行号
#include <stdio.h>
int global_sum = 0;
unsigned long long factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int add(int a, int b) {
return a + b;
}
int add_multiple(int a, int b, int c, int d) {
int temp_sum = a + b;
int final_sum = temp_sum + c + d;
return final_sum;
}
int main() {
int num;
int x = 5, y = 8, z = 12, w = 20;
printf("Enter a number(0~19): ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
return 1;
} else if (num > 20) {
printf("Input too large to compute factorial!\n");
return 1;
}
unsigned long long result = factorial(num);
printf("Factorial of %d is: %llu\n", num, result);
int sum = add(5, 8);
printf("5 + 8 sum is : %d\n", sum);
global_sum = add_multiple(x, y, z, w);
printf("%d + %d + %d + %d sum is : %d\n", x, y, z, w, global_sum);
return 0;
}
Practical notes¶
Adapt the commands and configuration to the version, distribution, and target hardware being used.