I recently had some trouble compiling source code from the net which would not run under Ubuntu’s default gcc version, which is 5.4.0 for Xenial. The first thing to know is where to get the most recent gcc version, the second problem is how to tell Ubuntu (and the IDEs you are running) which of the gcc versions installed should be used.
Getting the latest gcc
You can read how to get the latest gcc in this post. The good news is: You don’t have to build it yourself, there is a ppa. Just type
1 2 |
ilek@i7:~$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test ilek@i7:~$ sudo apt-get install gcc-6 g++-6 |
In my case, this triggered a whopping 500 MB download. So lean back and let apt do its work.
Setting the default version for gcc
Installing the gcc compiler alone won’t get you far. The reason is that unlike with updating some standard application like VirtualBox, the installation does not replace the old version by the new one but it installs the new version along the existing one(s). This however means that even if you have a more recent version installed, Ubuntu and your IDE will revert to the old version as your existing one.
You can easily see that Ubuntu still reverts to the old 5.4.0 version after the installation:
1 2 3 4 5 |
ilek@i7:~$ g++ --version g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609 Copyright (C) 2015 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
As you can see, Ubuntu still invokes its default 5.4.0 version although the latest version 6 compiler is already installed. You can set the new default version with the update-alternatives command as described in this post.
We start with removing any alternative instructions:
1 2 |
sudo update-alternatives --remove-all gcc sudo update-alternatives --remove-all g++ |
We now establish a new update-alternatives “hierarchy”:
1 2 3 4 5 6 7 8 9 10 11 |
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 10 sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 20 sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 10 sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-6 20 sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc 30 sudo update-alternatives --set cc /usr/bin/gcc sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++ 30 sudo update-alternatives --set c++ /usr/bin/g++ |
When installing cc and c++ you may get an warning saying that update-alternatives is forcing the installation of /usr/bin/g++
because link group c++ is broken (or equivalent for cc). Don’t worry, it just means that update-alternatives has so far not produced any corresponding symlink into /usr/bin/
and it will produce that symlink now.