Thursday, 23 May 2013

Installing and switching gcc/g++ versions in Debian

Installing newer gcc/g++ versions is easy:
sudo apt-get install gcc-4.7 g++-4.7
If your system does not provide the new versions, you might still be able to get them via a different repository. Add the toolchain repository to your system and update your sources:
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
Now you should be able to install gcc/g++. The real problem comes after that. How to make use of the newer versions?

Option #1 - Uninstall older versions

This is sometimes not an option, because lots of dependencies will be uninstalled which you might need, or you want to keep those versions around for compiling stuff that still uses them.

Option #2 - Use update-alternatives to switch versions

This informative post describes it pretty well. I'll sum it up here. First remove all update-alternatives:
sudo update-alternatives --remove-all gcc
sudo update-alternatives --remove-all g++
Now add update-alternatives for 4.6 and 4.7 and make the g++ configuration a slave of the gcc configuration, so that when you switch the gcc version, the g++ version is automagically switched too:
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
You can now switch compiler versions with:
sudo update-alternatives --config gcc

Option #3 - Use a script to switch versions

This script by Jeff Carr-3 can switch compiler versions for you:
usage() {
        echo Sets the default version of gcc, g++, etc
        echo Usage:
        echo "    gcc-set-default-version <VERSION>"
cd /usr/bin
if [ -z $1 ] ; then 
set_default() {
        if [ -e "$1-$2" ] ; then 
                echo $1-$2 is now the default
                ln -sf $1-$2 $1
                echo $1-$2 is not installed
for i in gcc cpp g++ gcov gccbug ; do 
        set_default $i $1
Download it and make it executable:
chmod 755 gcc-set-default-version
You can  now switch compiler versions with it:
sudo sh gcc-set-default-version 4.7
Voila. Works on Raspberry Pi too. Happy compiling!

1 comment:

N@NEEN said...

Thank you.
You saved quite considerable time for me with this post.

Post a Comment