[Linux][Bash] Manage Gcc/G++ versions with smart links using update-alternatives

This tool is a must know application. It lets manage different versions of a program very easily.
However, some people still do not know about it, mainly because there are a lot of by-hand solutions proposed in various forums.

Imagine, you installed Gcc 4.9 with synaptic (apt-get) and now decide to install 5.1.
If you ask Gcc version you will see that “gcc –version” is pointing to 4.9 and if you ask using “which gcc” that it points to /usr/bin/gcc which is a link to the real binary /usr/bin/gcc-4.9.

What you can do, it is to change the link /usr/bin/gcc to make it points to your new gcc /usr/bin/gcc-5.
But what if you want to use 4.9 again, and what will happen with the next gcc versions?
This is not very clean, and update-alternatives helps to manage that.

The idea is to tell to update-alternatives what versions a link can point to.
And later how to switch from one version to another.

Distinct Gcc/G++

Let see an example for both Gcc and G++.
First, it is usual to start from a clean link map:

sudo update-alternatives --remove-all gcc 
sudo update-alternatives --remove-all g++ 

Then tell the version and link and binary relations using

# sudo update-alternatives  --install  genname  symlink  altern  priority
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 48 
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 49 
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 50 

I have only two versions of G++

sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.9 49 
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 50 

Then you can switch from one version or the other using:

sudo update-alternatives --config gcc 

The last digit is the priority of the version (and by default the higher is used).

Same Gcc/G++

In the previous part, we can set gcc to 4.9 and g++ to 5 but in the real life it is not appropriate.
It is recommended to have the same version for both.

sudo update-alternatives --remove-all gcc 
sudo update-alternatives --remove-all g++ 
sudo update-alternatives --remove-all gfortran 

Then set the alternative only for gcc but tell how it impacts other links:

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 46 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9 --slave /usr/bin/gfortran gfortran /usr/bin/gfortran-4.9 
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 50 --slave /usr/bin/g++ g++ /usr/bin/g++-5 --slave /usr/bin/gfortran gfortran /usr/bin/gfortran-5 

Then you can switch all binaries with a single command:

sudo update-alternatives --config gcc