This guide explains how to install a modern C++ compiler (g++-9 or newer) on an older Ubuntu 16.04 LTS system. This is necessary to compile C++17 code that uses features like <optional>
, which are not fully supported by the default compiler available in the 16.04 repositories.
When you try to install a newer compiler directly on a fresh Ubuntu 16.04 system, you will encounter an error:
sudo apt install g++-9
E: Unable to locate package g++-9
This happens because the default software sources for this older operating system are "frozen" and do not contain packages from newer releases.
The standard and safest way to resolve this is to add a **PPA (Personal Package Archive)**. A PPA is a software repository for Ubuntu users that allows them to get newer software than what is available in the official Ubuntu repositories. We will use the official Ubuntu "Toolchain Test" PPA.
Run the following command to add the repository to your system's software sources. This will give `apt` a new place to look for packages.
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
After adding the new repository, you must tell your system to refresh its list of available packages.
sudo apt-get update
Now that your system knows about the new repository, you can install `g++-9` successfully.
sudo apt-get install g++-9
Finally, to ensure your project uses the newly installed compiler, you must explicitly tell `make` which one to use. Open your `Makefile` and change the `CXX` variable:
Change this line:
CXX = g++
To this:
CXX = g++-9
After the installation is complete, you can verify that the new compiler is installed and working correctly by checking its version:
g++-9 --version
You should see output indicating that you have GCC version 9 or higher. Your project should now compile without errors.