Raspberry Pi - Install Clang 9 and compile C++17 and C++20 programs
Posted on April 22, 2018 by Paul
Updated 24 September 2019
In this article I will show you how to install Clang 9 on your Raspberry Pi system and how to compile C++17 programs. At the time of this writing Raspbian is based on Debian Buster, which comes with the stable but slightly outdated GCC 8.3 as the default C and C++ compiler. If you prefer to use GCC 9 I wrote an article about installing GCC 9 on Raspberry Pi.
There is also a video version of this tutorial:
Let’s start the installation process. Open a Terminal and download the official binary of Clang 9 for Raspberry Pi (works only for RPi2 and up, doesn’t work for RPi Zero):
Next, extract the archive and move the extracted folder to /usr/local:
At this point, all you need to do is to add Clang 9 and his libraries to your system search paths:
the above will, temporarily, modify your paths. If you want to make the change permanent, you need to add the above line at the end of your .bashrc file:
You can check if everything is properly setup by printing the version of the installed compiler:
This is what I see on my Pi:
If, at some point in the future, you’ll want to get rid of Clang 9 from your system, all you have to do is to remove the clang_9.0.0 folder from /usr/local, example:
Let’s try to compile and run a C++17 code that uses an if block with init-statement (the example is a bit silly, but it will show you how to compile C++17 programs):
Save the above code in a file named if_test.cpp and compile it with:
This is what I see on my Pi:
Next, let’s try to compile a program that uses the C++17 Filesystem:
Save the above file as test_fs.cpp, you can compile and run the code with:
Clang 9 has experimental support for the new C++20 standard, at this time you’ll need to use std=c++2a in order to enforce the C++20 standard. Here is an example of using the new C++20 std::span:
This is what I see if I build and run the above code:
For an overview of C++20 support in Clang see https://clang.llvm.org/cxx_status.html. You can also check the status of the C++20 support in libc++.
If you are interested to learn more about modern C++, I recommend A Tour of C++ by Bjarne Stroustroup:
or Effective Modern C++ by Scott Meyers.