Ubuntu gcc/g++默认版本切换

ubuntu系统中可能安装了多个版本的gcc/g++ 如gcc-5,gcc-7, gcc-9等等,在使用时,我们可以在命令直接指定gcc/g++版本来确定使用哪个编译器

g++-5 ./test.cpp -o test
g++-7 ./test.cpp -o test

此外,我们还可以通过包管理工具update-alternatives来设置默认gcc/g++版本

1 默认情况

在默认情况下,安装的gcc和g++各自都是master状态,可以分别用update-alternatives设置优先级,具体方法如下

# 设置gcc优先级,最后的数字代表优先程度,数值越大,优先程度越高,可自行调整各版本的优先级
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 50
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 70
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 90
# 设置g++优先级
sudo update-alternatives  --install /usr/bin/g++ g++ /usr/bin/g++-5 50
sudo update-alternatives  --install /usr/bin/g++ g++ /usr/bin/g++-7 70
sudo update-alternatives  --install /usr/bin/g++ g++ /usr/bin/g++-9 90

# 查看gcc各版本优先级,可以手动调整默认版本
sudo update-alternatives --config gcc
# 查看g++各版本优先级
sudo update-alternatives --config g++

如上的命令后,如何不手动选择默认版本时,gcc-9和g++-9的优先级设为最高,如需检查默认gcc/g++版本,使用如下命令

gcc -v
g++ -v

2 特殊情况

有时候,由于一些奇奇怪怪的原因(可能是Ubuntu系统版本问题,或者安装gcc,g++的问题)导致g++依赖于gcc,此时如果使用sudo update-alternatives --install ....... 设置g++的优先级时,会报错:

update-alternatives: error: alternative g++ can't be master: it is a slave of gcc

此时我们按照其提示,使用如下命令重新设置gcc,并用--slave共同设置g++, 如下:

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 70 --slave /usr/bin/g++ g++ /usr/bin/g++-7

注意,当你重新使用上述语句设置gcc, g++的优先级时,可能你已经按照**默认情况中的方法**设置了gcc,那使用上面语句--slave重新设置时,不能让默认版本为当前设置的版本(即如上设置gcc-7,g++-7, 那就不能让gcc的update-alternatives默认版本为gcc-7,否则你可能会遇到如下警告:

update-alternatives: warning: forcing reinstallation of alternative /usr/bin/gcc-7 because link group gcc is broken

猜你喜欢

转载自blog.csdn.net/weixin_44576482/article/details/128667608