在 CentOS 上用 gcc 调试程序,通常配合 gdb 使用。下面从“编译 → 运行 → 调试”一步步说明。
CentOS 一般默认有 gcc,如果没有:
sudo yum install gcc gcc-c++ gdb -y
验证:
gcc --version
gdb --version
一定要加 -g 参数,否则 gdb 看不到源码和变量。
gcc -g -o test test.c
如果是 C++:
g++ -g -o test test.cpp
✅ 推荐编译选项(更利于调试):
gcc -g -O0 -Wall -o test test.c
-O0:关闭优化(避免变量被优化掉)-Wall:显示警告gdb ./test
或运行并调试:
gdb --args ./test arg1 arg2
| 命令 | 作用 |
|---|---|
run / r |
运行程序 |
break main |
在 main 函数设断点 |
break test.c:10 |
在第10行设断点 |
next / n |
单步(不进入函数) |
step / s |
单步(进入函数) |
print x / p x |
打印变量 |
backtrace / bt |
查看调用栈 |
continue / c |
继续执行 |
quit / q |
退出 gdb |
示例:
(gdb) break main
(gdb) run
(gdb) next
(gdb) print i
gdb ./test
(gdb) run
崩溃后:
(gdb) bt
可以看到是哪一行出错。
ulimit -c unlimited
运行程序产生 core 文件后:
gdb ./test core
(gdb) bt
sudo yum install cgdb -y
cgdb ./test
sudo yum install ddd -y
test.c
#include <stdio.h>
int main() {
int a = 10;
int b = 0;
printf("%d\n", a / b); // 故意除零
return 0;
}
调试:
gcc -g -O0 test.c -o test
gdb ./test
(gdb) run
(gdb) bt
如果你愿意,可以告诉我:
我可以给你更针对性的调试方法。