Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to switch GCC version using update-alternatives

📅 2015-Feb-26 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ gcc, update, update-alternatives, version ⬩ 📚 Archive

Multiple versions of GCC can be installed and used on Ubuntu as described here. The update-alternatives tool makes it easy to switch between multiple versions of GCC.

On Ubuntu, gcc and g++ are just symbolic links to the actual binaries of a specific version of GCC. By switching the version, invoking gcc will execute the particular version of the compiler binary that you wish. You can make any of these version as the default at any time effortlessly.

As an example, I had installed GCC version 4.8 from the Ubuntu repositories. This was the default version of GCC, so gcc was a symlink to gcc-4.8 binary. Wanting to use some new C++11 features I installed version 4.9 of GCC. This compiler can be invoked using gcc-4.9. I now want to switch the default gcc to invoke gcc-4.9. I also want the freedom to switch back 4.8 as the default whenever I want. You can switch the symlinks yourself manually, but using this tool makes it easy and clean.

Let us begin:

$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 100 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8

Here, we have provided the gcc as the master and g++ as slave. Multiple slaves can be appended along with master. When master symbolic link is changed, the slaves will be changed too.

$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 50 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9 
$ sudo update-alternatives --config gcc

Tried with: Ubuntu 14.04