在 Ubuntu 上安装 GCC(GNU Compiler Collection)非常简单,下面是几种常见方法,按推荐程度排序:
apt 安装(最推荐)sudo apt update
sudo apt install gcc
如果你还需要 g++(C++ 编译器),可以一起安装:
sudo apt install gcc g++
gcc --version
g++ --version
这个方式会一次性安装 GCC、G++、make 等常用工具:
sudo apt install build-essential
安装完成后验证:
gcc --version
make --version
Ubuntu 仓库中可能有多个 GCC 版本,例如:
sudo apt install gcc-11 g++-11
查看已安装版本:
ls /usr/bin/gcc*
设置默认版本(示例):
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 100
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-11 100
切换版本:
sudo update-alternatives --config gcc
确认是否安装成功:
which gcc
如果是 Ubuntu 18.04 / 20.04 / 22.04 / 24.04,以上方法都适用。
创建测试文件:
nano hello.c
内容:
#include <stdio.h>
int main() {
printf("Hello, GCC!\n");
return 0;
}
编译并运行:
gcc hello.c -o hello
./hello
如果你告诉我 Ubuntu 版本(如 20.04 / 22.04)或 使用场景(内核开发、RISC-V、交叉编译等),我可以给你更精确的安装方案。