Ubuntu – How to choose the default gcc and g++ version


So I have installed gcc-4.4 and gcc-4.3 (same for g++). Now as far as I remember there is a tool in Ubuntu which sets the symlinks for you if you just tell it which version you want. However it does not seem to work in the newest version, which I find disappointing.

root@nexus:~# update-alternatives --config gcc
update-alternatives: error: no alternatives for gcc.
root@nexus:~# update-alternatives --config cc
There is only one alternative in link group cc: /usr/bin/gcc
Nothing to configure.

root@nexus:~# dpkg -l | grep gcc | awk '{print $2}'

Any ideas?

Best Answer

  • First erase the current update-alternatives setup for gcc and g++:

    sudo update-alternatives --remove-all gcc 
    sudo update-alternatives --remove-all g++

    Install Packages

    It seems that both gcc-4.3 and gcc-4.4 are installed after install build-essential. However, we can explicitly install the following packages:

    sudo apt-get install gcc-4.3 gcc-4.4 g++-4.3 g++-4.4

    Install Alternatives

    Symbolic links cc and c++ are installed by default. We will install symbol links for gcc and g++, then link cc and c++ to gcc and g++ respectively. (Note that the 10, 20 and 30 options are the priorities for each alternative, where a bigger number is a higher priority.)

    sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.3 10
    sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.4 20
    sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.3 10
    sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.4 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++

    Configure Alternatives

    The last step is configuring the default commands for gcc, g++. It's easy to switch between 4.3 and 4.4 interactively:

    sudo update-alternatives --config gcc
    sudo update-alternatives --config g++

    Or switch using script:

    if [ -z "$1" ]; then
        echo "usage: $0 version" 1>&2
        exit 1
    if [ ! -f "/usr/bin/gcc-$1" ] || [ ! -f "/usr/bin/g++-$1" ]; then
        echo "no such version gcc/g++ installed" 1>&2
        exit 1
    update-alternatives --set gcc "/usr/bin/gcc-$1"
    update-alternatives --set g++ "/usr/bin/g++-$1"
  • Related Question