Managing multiple versions of gcc
and g++
on Ubuntu can be essential for developers working with different projects that require specific compiler versions. Here’s a step-by-step guide on how to install and switch between different versions of these compilers:
Step 1: Install the Required gcc
and g++
Versions
Ubuntu repositories provide multiple versions of gcc
and g++
. You can install specific versions using apt
:
-
First, update your package list:
sudo apt update
-
Install the versions of
gcc
andg++
that you need. For example, to installgcc-7
andg++-7
:sudo apt install gcc-7 g++-7
Replace
7
with any other version number available in the repository. -
You can check which versions are installed by listing them:
gcc --version g++ --version
Step 2: Install and Configure update-alternatives
Ubuntu’s update-alternatives
system provides a way to manage multiple versions of a program through symbolic links. Here’s how to set it up for gcc
and g++
:
-
Set up alternatives for each version. You need to do this for both
gcc
andg++
. Here’s how to set upgcc
:sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 10
/usr/bin/gcc
is the generic command./usr/bin/gcc-7
is the specific version.10
is the priority (higher means higher priority).
Repeat this for each version of
gcc
you have installed, changinggcc-7
and the priority accordingly. -
Do the same for
g++
:sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-7 10
Again, replace
g++-7
and the priority based on your installed versions and preferences.
Step 3: Switch Between Versions
After setting up update-alternatives
, you can switch between the installed versions using the update-alternatives
config command:
-
To switch versions of
gcc
:sudo update-alternatives --config gcc
-
To switch versions of
g++
:sudo update-alternatives --config g++
You will be prompted to choose from the list of installed versions. Select the version by typing the selection number.
Step 4: Verify the Active Compiler Version
After switching versions, you can verify which compiler version is currently active:
gcc --version
g++ --version
These commands will display the version of the compilers currently in use.
Additional Tips
-
Using Specific Compilers Directly: If you prefer not to change the default compiler globally, you can invoke a specific compiler directly in your build scripts or Makefiles, for example,
/usr/bin/gcc-7
or/usr/bin/g++-7
. -
Environment Management Tools: For complex projects, consider using environment management tools like Docker, which can provide more controlled environments with specific versions of compilers and other dependencies.
By following these steps, you can manage multiple versions of gcc
and g++
on your Ubuntu system, allowing you to compile projects with different requirements easily.