Switch between GCC/G++ versions

From time to time, you may want to change the default version of gcc/g++ (CUDA compatibility for example) on your Ubuntu OS.

  1. Install Different versions (in practice, you can install only whatever version you want.)
sudo apt -y install gcc-8 g++-8 gcc-9 g++-9 gcc-10 g++-10
  1. Create linkage between different versions to system version
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 9
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-9 9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 10
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 10

The last number is not necessarily the same with the versions. It is a priority number, the system will choose the highest one as the default.

  1. Setup the default gcc/g++ version
    According to the rules mentioned above, you can simply assign the default gcc/g++ by giving them the highest priority number.

But, when the time gets old, you may forget what’s the number you set in the first place.
You can run:

sudo update-alternatives --config gcc

and

sudo update-alternatives --config g++

to check.

You should separately set gcc and g++. When you setup one, don’t forget another.