How to install the newest gcc/g++ compiler on Ubuntu

When compiling newer versions of OpenFOAM, using newer compilers might bring benefits because of the newer standard, e.g. move semantics.

Step-by-step guide

Here is an example for gcc or rather gcc/g++ 9:

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install g++-9
$ sudo apt-get install g++-9
$ sudo update-alternatives --remove-all gcc
$ sudo update-alternatives --remove-all g++
$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 1
$ sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-9 1

Now g++/gcc are aliases (alternatives) for gcc/g++-9 on the system and can be used as system compilers for OpenFOAM, which is easier than using makeGcc in ‘ThirdParty’' to build a local version of gcc/g++.

See also