Ubuntu 24.04 通过 update-alternatives 切换GCC版本

在 Ubuntu 中编译项目, 会遇到项目依赖于某个特定版本 GCC 的情况, 例如 Ubuntu 24.04 的默认 GCC 版本是 13, 但是有一些项目需要 GCC11才能正常编译, 在 Ubuntu 24.04 默认的环境下编译会报错. 这时候可以通过 update-alternatives 切换GCC版本.

all 展示全部

--all参数会展示现在系统中所有的可替换版本设置(并设置), 这个列表很长

sudo update-alternatives --all

install 创建

首先要用 update-alternatives --install 命令创建一个 gcc 的替换列表, 并把这些可用的版本都加进去.

update-alternatives --install [link] [name] [path] [priority]

priority 数字越大优先级越高, 最高优先级的会成为自动 auto 选择的版本

例如

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 11
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-11 11

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-12 12
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-12 12

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 13
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 13

list, display, query 查看

查看可以通过 --list, --display, --query命令

update-alternatives --list gcc
update-alternatives --display gcc
update-alternatives --query gcc

config, set 选择

通过 config 选择需要的 gcc 版本

sudo update-alternatives --config gcc

会出现选择菜单

There are 2 choices for the alternative gcc (providing /usr/bin/gcc).

  Selection    Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/gcc-13   13        auto mode
  1            /usr/bin/gcc-11   11        manual mode
  2            /usr/bin/gcc-13   13        manual mode

Press <enter> to keep the current choice[*], or type selection number: 

通过 set 直接选择

sudo update-alternatives --set gcc /usr/bin/gcc-12
sudo update-alternatives --set g++ /usr/bin/g++-12

remove, remove-all 删除

# 删除1项
sudo update-alternatives --remove gcc /usr/bin/gcc-7
# 删除整个gcc
sudo update-alternatives --remove-all gcc

posted on 2025-05-03 23:24  Milton  阅读(996)  评论(0)    收藏  举报

导航