在 Ubuntu 下使用 gcc 调试程序,通常配合 gdb(GNU Debugger) 来完成。下面从基础到常用操作给你一个完整说明。
关键:使用 -g 选项
gcc -g -o test test.c
如果是 C++:
g++ -g -o test test.cpp
✅ 不加 -g,gdb 看不到变量名、行号,基本没法调试。
gdb ./test
进入 gdb 后常见命令:
run
或带参数:
run arg1 arg2
break main
break test.c:10
break func_name
查看断点:
info breakpoints
删除断点:
delete 1
next # 步过函数
step # 步入函数
print x
print arr[0]
自动显示:
display x
backtrace
或简写:
bt
continue
quit
gcc -g -o test test.c
gdb ./test core
(需要开启 core dump)
开启 core:
ulimit -c unlimited
再次运行程序,会生成 core 文件。
sudo apt install valgrind
valgrind ./test
sudo apt install cgdb
cgdb ./test
#include <stdio.h>
int main() {
int a = 5;
int b = 0;
printf("%d\n", a / b); // 会崩溃
return 0;
}
gcc -g -o test test.c
gdb ./test
(gdb) run
如果你愿意,可以告诉我:
我可以给你更针对性的调试方案。