Selecting compiler versions with update-alternatives

Switch between compilers e.g. g++-7 and g++-8 with simple commands. Note: We suggest NOT using sudo, but rather to make the links under ~/.local/bin, which should already be in your PATH (or start using it as in step 1).

  1. (one-time) Setup your Bash shell to use ~/.local/bin instead of system-wide /usr. This is generally beneficial in any case.

    mkdir ~/.local/bin

    Add to ~/.bashrc:

    export PATH="$HOME/.local/bin:$PATH"
  2. (one-time setup) enable switching

    update-alternatives --install $HOME/.local/bin/g++ g++ /usr/bin/g++-7 20
    update-alternatives --install $HOME/.local/bin/g++ g++ /usr/bin/g++-6 10

and so on for gcc and gfortran 3. At any time, switch compiler versions:

```sh
update-alternatives --config g++
update-alternatives --config gcc
update-alternatives --config gfortran
```

update-alternatives works with virtually any program including Java and Python.

Compiler version priority order

The last number of update-alternatives --install is priority. The highest priority number is used in “automatic” update-alternatives mode.

Troubleshooting

If you accidentally reversed the order of the link and target (particularly if you used sudo in /usr/bin) then you may need to reinstall the compiler.