在 Ubuntu 下使用 gcc 编译 C/C++ 程序时,查错误主要分几个层次:编译错误、链接错误、运行时错误、逻辑错误。下面系统地给你讲一下常见方法和技巧。
gcc test.c -o test
如果有错误,gcc 会直接输出,例如:
test.c:5:10: error: expected ‘;’ before ‘}’ token
重点看:
error: 是必须改的warning: 也要注意(可能是隐患)gcc -Wall -Wextra test.c -o test
常用选项:
-Wall:常见警告-Wextra:额外警告-Werror:把警告当错误(适合学习/严格项目)undefined reference to `sqrt'
原因:没链接库
解决:
gcc test.c -o test -lm
数学库 -lm
线程库 -lpthread
-g 配合 gdb 查运行错误gcc -g test.c -o test
gdb ./test
常用 gdb 命令:
run
bt # 查看调用栈(崩溃时最重要)
list # 查看代码
print x # 打印变量
quit
gdb ./test
run
bt
ulimit -c unlimited
./test
gdb ./test core
sudo apt install valgrind
valgrind ./test
可以查:
如果是 C++:
g++ test.cpp -Wall -Wextra -g -o test
| 错误 | 原因 |
|---|---|
undefined reference |
没加库 |
command not found |
没装 gcc |
No such file |
路径错 |
Segmentation fault |
指针/数组越界 |
warning: unused variable |
定义了没用 |
如果你愿意,可以把 具体的 gcc 报错信息贴出来,我可以直接帮你逐行分析。