How to switch GCC version using update-alternatives

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:

  • Decide which set of symbolic links you want to group together as one unit. I like to switch /usr/bin/gcc and /usr/bin/g++ together.

  • Pass update-alternatives the first version of these symbolic links. Here I will inform about the 4.8 version of these tools and links:

$ 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.

  • Pass the second version of these tools to be recorded:
$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 50 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9 
  • Now you can switch between these versions by using:
$ sudo update-alternatives --config gcc

Tried with: Ubuntu 14.04

One thought on “How to switch GCC version using update-alternatives”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s