在 Debian 上用 GCC 调试代码,通常配合 GDB(GNU Debugger)使用。下面从安装、编译、调试到常用命令一步步说明。
sudo apt update
sudo apt install build-essential gdb
build-essential:包含 gcc、g++、makegdb:调试器检查版本:
gcc --version
gdb --version
关键:使用 -g 选项
gcc -g -Wall -o test test.c
说明:
-g:生成调试信息(必须)-Wall:显示警告(推荐)-O0:关闭优化(调试时推荐)示例:
gcc -g -O0 -Wall -o test test.c
gdb ./test
| 命令 | 作用 |
|---|---|
run / r |
运行程序 |
break main |
在 main 函数设断点 |
break test.c:10 |
在第 10 行设断点 |
next / n |
单步执行(不进入函数) |
step / s |
单步进入函数 |
continue / c |
继续执行 |
print x / p x |
打印变量 |
backtrace / bt |
查看调用栈 |
list / l |
查看源码 |
quit / q |
退出 GDB |
示例:
(gdb) break main
(gdb) run
(gdb) next
(gdb) print a
gdb ./test
(gdb) run
崩溃后:
(gdb) backtrace
可定位是哪一行导致段错误。
ulimit -c unlimited
./test
gdb ./test core
如果你不喜欢命令行:
sudo apt install cgdb
cgdb ./test
sudo apt install ddd
ddd ./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
如果你愿意,可以告诉我:
我可以给你更具体的调试方法。