How to set Clang 9 as the default C++ compiler on Ubuntu 19.10?

  1. Install clang version 9 from the default Ubuntu repositories in Ubuntu 19.10 and later.

    sudo apt install clang-9
    
  2. /usr/bin/c++ is actually a symbolic link to:

    /etc/alternatives/c++
    

    which in turn is also a symbolic link to:

    /usr/bin/g++
    

    so on Ubuntu c++ is g++ and g++ is g++ explicitly.

    Set Clang 9 as the default C++ compiler using c++ so that build processes can still use g++ explicitly if they want to.

    sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/c++ 40
    sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/clang++-9 60
    sudo update-alternatives --config c++
    

After running sudo update-alternatives --config c++ a menu of c++ versions will appear and you will be asked to select the default c++ version as follows:

Press <enter> to keep the current choice[*], or type selection number:

Input a selection number from the menu and press Enter.

clang-9 can also be installed in Ubuntu 18.04 if the bionic-proposed/universe repository ( deb http://XX.archive.ubuntu.com/ubuntu/ bionic-proposed universe ) is added to the Ubuntu 18.04 software sources. Replace XX in deb http://XX.archive.ubuntu.com/ubuntu/ bionic-proposed universe with your country code.


Step 1: Install prerequisites

sudo apt-get install build-essential xz-utils curl

Step 2: Download the necessary binaries and extract them.

curl -SL http://releases.llvm.org/9.0.0/clang+llvm-9.0.0-x86_64-pc-linux-gnu.tar.xz | tar -xJC

Step 3: Renaming & moving the binaries.

mv clang+llvm-9.0.0-x86_64-pc-linux-gnu clang_9.0.0
sudo mv clang_9.0.0 /usr/local

Step 4: Tell our system where clang-9 is

export PATH=/usr/local/clang_9.0.0/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/clang_9.0.0/lib:$LD_LIBRARY_PATH

Step 5: Test the installation

clang++ -stdlib=libc++ -std=c++2a -Wall example.cpp -o example

Note

Clang is not a version of GCC, so it cannot be set as an alternative for /usr/bin/gcc. Never try it, you may break some packages which require GCC-specific features not available in Clang.