Select compiler versions 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).

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

mkdir ~/.local/bin

Add to ~/.profile:

export PATH="$HOME/.local/bin:$PATH"

(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

At any time, switch compiler versions:

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

update-alternatives works with virtually any program including Python.

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

Troubleshooting: If accidentally reversed the order of the link and target or if used sudo in /usr/bin then may need to reinstall the compiler.