如何在 Ubuntu 22.04 LTS Jammy Jellyfish 上的多个 GCC 和 G++ 编译器版本之间切换
GCC编译器用于在Linux系统上编译C程序,G++编译器用于编译C++程序。两者都有多个版本可安装在 Ubuntu 22.04 Jammy Jellyfish 上。
在本教程中,我们将使用 apt install 命令安装多个版本的 GCC 和 G++ 编译器。此外,通过使用 update-alternatives 工具,您将学习如何在多个 GCC 和 G++ 编译器版本之间轻松切换,以及如何在 Ubuntu 22.04 Jammy Jellyfish 上检查当前选择的编译器版本。
在本教程中您将学习:
如何安装多个 GCC 和 G++ 编译器版本
如何创建替代编译器版本列表
如何在 Ubuntu 22.04 上的多个编译器版本之间切换
在 Ubuntu 22.04 上安装 GCC 和 G++ 编译器分步说明
首先打开命令行终端并使用以下 apt 命令在 Ubuntu 22.04 上安装几个不同版本的 GCC 和 G++ 编译器。
$ sudo apt update $ sudo apt install build-essential $ sudo apt -y install gcc-8 g++-8 gcc-9 g++-9 gcc-10 g++-10
使用 update-alternatives 工具创建多个 GCC 和 G++ 编译器替代方案的列表:
$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 $ sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8 $ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 9 $ sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-9 9 $ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 10 $ sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 10
检查 Ubuntu 22.04 系统上可用的 C 和 C++ 编译器列表,并通过输入相关的选择编号来选择所需的版本:
$ sudo update-alternatives --config gcc There are 3 choices for the alternative gcc (providing /usr/bin/gcc). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/bin/gcc-9 9 auto mode 1 /usr/bin/gcc-10 10 manual mode * 2 /usr/bin/gcc-8 8 manual mode 3 /usr/bin/gcc-9 9 manual mode Press to keep the current choice[*], or type selection number:
对于 C++ 编译器执行:
$ sudo update-alternatives --config g++ There are 3 choices for the alternative g++ (providing /usr/bin/g++). Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/bin/g++-9 9 auto mode 1 /usr/bin/g++-10 10 manual mode 2 /usr/bin/g++-8 8 manual mode 3 /usr/bin/g++-9 9 manual mode Press to keep the current choice[*], or type selection number:
每次切换后检查您当前选择的编译器版本:
$ gcc --version $ g++ --version
结束语
在本教程中,您学习了如何在 Ubuntu 22.04 Jammy Jellyfish Linux 上安装并在多个版本的 GCC 和 G++ 编译器之间切换。这使您能够使用不同版本的编译器来编译 C 和 C++ 程序,只需在每次需要切换时执行几个命令即可。