Setting alternate GCC on Ubuntu without removing previous versions

You might want to install multiple softwares in your computer that work with different versions of GCC/G++. Uninstalling and reinstalling GCC is niether optimal solution nor safe. If you keep uninstalling and reinstalling GCC it will not only hectic but can also mess up with your computer. The most basic and most important packages that are needed by your computer to work and respond properly will be gone with GCC and you might have to reinstall a new OS.

So, NEVER uninstall your GCC.

What is the other option?

The correct way is to install alternate versions of GCC/G++ and select the one you need for your software.


1. Install GCC/G++ versions you need:

sudo apt-get install gcc-4.8 gcc-5 gcc-6 g++-4.8 g++-5 g++-6

2. Once installed, add them to alternatives:

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 10
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 20
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 30 
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 10
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 20
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-6 30 

3. Select the required version:

sudo update-alternatives --config gcc
 
sudo update-alternatives --config g++ 

[10,20 and 30 are priorities assigned to each version]