在 Ubuntu 下使用 gcc 编译程序时,查看和理解错误信息主要可以从终端输出、常用选项、错误类型、定位方法几个方面入手。下面给你一份实用指南。
用 gcc 编译时,错误信息会直接打印在终端,例如:
gcc test.c -o test
常见输出形式:
test.c: In function ‘main’:
test.c:8:5: error: ‘printf’ undeclared (first use in this function)
8 | printf("hello\n");
| ^~~~~~
test.c:8:5: note: ‘printf’ is defined in header ‘<stdio.h>’
要点:
test.c:8:5 → 文件名:行号:列号error: 是必须修的错误warning: 是警告(不致命但建议修)note: 是补充说明int main() {
int a = 10
return 0;
}
报错:
error: expected ‘;’ before ‘return’
error: ‘x’ undeclared
通常是:
stdio.h)error: incompatible types when assigning to type ‘int’ from type ‘char *’
undefined reference to ‘foo’
原因:
.c 或库gcc -Wall test.c
gcc -Wall -Wextra test.c
gcc -fdiagnostics-color=always test.c
gcc -Wall -Wextra -Wshadow test.c
原则:
例如:
error: ‘i’ undeclared
error: ‘j’ undeclared
很可能只是 i 没定义。
gcc -E test.c
gcc -S test.c
gcc -g test.c -o test
gdb ./test
❌ 错误代码:
#include <stdio.h>
int main() {
pritnf("hi\n");
}
✅ 编译:
gcc test.c
✅ 输出:
error: ‘pritnf’ undeclared
✅ 修正:
printf("hi\n");
如果你愿意,可以把你的 gcc 报错原文贴出来,我可以直接帮你逐行解释并改好。