I recently had the need to install a newer version of the g++
compiler on Ubuntu 12.04 LTS. I documented the approach here.
Ubuntu does not typically release new toolchains for their stable versions, instead newer toolchains are made available in a PPA (Personal Package Archive) “https://launchpad.net/~ubuntu-toolchain-r/+archive/test“ to use the repository we can use the add-apt-repository
command:
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.7 g++-4.7
Currently the PPA contains gcc/g++-4.7
and 4.8
. After installing one or multiple of the newer versions we can use update-alternatives
to switch between the different versions. The update-alternatives
tool manages symlinks to the different installed versions and allow us to easily switch between them.
Before we add the new gcc/g++ lets check if we already have any alternatives setup by running:
$ update-alternatives --display gcc
If you don’t have any alternatives installed it will just print:
update-alternatives: error: no alternatives for gcc.
Lets see how to add an alternative:
$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
As a default when we install new alternatives they are added to a group (in this case gcc) in automatic mode. This means that the link with the highest priority will become the default. In the case above we gave gcc-4.7
a priority of 60 and gcc-4.6
a priority of 40, so the default with be gcc-4.7
The –slave options tells update-alternative
that when we change gcc it should also update the g++ links.
To check that everything is ok or to switch between the compilers we can use
$ sudo update-alternatives --config gcc
There are 2 choices for the alternative gcc (providing /usr/bin/gcc).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/gcc-4.7 60 auto mode
1 /usr/bin/gcc-4.6 40 manual mode
2 /usr/bin/gcc-4.7 60 manual mode
Press enter to keep the current choice[*], or type selection number: 0
That is more or less it. Running gcc --version
shows that we are now using the newer version:
gcc (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3
Copyright (C) 2012 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.