温馨提示×

ubuntu gcc怎么看错误信息

小樊
56
2026-10-01 04:14:05
栏目: 智能运维

在 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: 是补充说明

二、常见 gcc 错误信息类型

1. 语法错误(syntax error)

int main() {
    int a = 10
    return 0;
}

报错:

error: expected ‘;’ before ‘return’

2. 未声明标识符

error: ‘x’ undeclared

通常是:

  • 变量没定义
  • 头文件没包含(如 stdio.h)

3. 类型错误

error: incompatible types when assigning to type ‘int’ from type ‘char *’

4. 链接错误(link error)

undefined reference to ‘foo’

原因:

  • 函数没实现
  • 没链接对应 .c 或库

三、让错误信息更友好(推荐选项)

1. 显示列号(默认已有)

gcc -Wall test.c

2. 打开所有警告

gcc -Wall -Wextra test.c

3. 把错误显示得更清楚

gcc -fdiagnostics-color=always test.c

4. 显示“为什么会这样”

gcc -Wall -Wextra -Wshadow test.c

四、多条错误时怎么看?

原则:

  1. 从第一个 error 开始看
  2. 修一个重新编译
  3. 后面的错误可能是“连锁反应”

例如:

error: ‘i’ undeclared
error: ‘j’ undeclared

很可能只是 i 没定义。


五、调试用(进阶)

1. 看预处理结果

gcc -E test.c

2. 看汇编(理解底层)

gcc -S test.c

3. 用 gdb 看运行错误

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 报错原文贴出来,我可以直接帮你逐行解释并改好。

0 踩