Build Your C++ Projects Faster Using Ninja

Ilyas Hamadouche
3 min readSep 20, 2019

In this article, I introduce you to an open-source build system that can help you speed up the compiling time when building C++ projects.

Ninja is a lightweight build system, designed to take advantage of the available CPU cores in your machine, to build executable files and libraries from source code efficiently. The way it works is very similar to GNU Make. That is it takes input files generated by a high-level build system like CMake and turns them into libraries and executables as fast as possible.

The following definition is taken from the official website:

Ninja is a small build system with a focus on speed. It differs from other build systems in two major respects: it is designed to have its input files generated by a higher-level build system, and it is designed to run builds as fast as possible.

Install

You can install Ninja using package managers:

Linux

  • Debian/Ubuntu: apt-get install ninja-build
  • Arch: pacman -S ninja
  • Fedora: dnf install ninja-build

Mac

  • HomeBrew: brew install ninja
  • MacPorts: port install ninja

Or, build the source code by downloading one of the releases from the Github repository. The latest release 1.9.0 contains ready-to-use precompiled binaries for 64-bit Linux, Mac OS X, and Windows.

Hello World!

The difference between Ninja and other build systems is noticeable when building large projects. However, let’s see in the following demonstration how Ninja works with CMake. Let’s create this simple HelloWorld program:

After creating the source code, we go now create a CMakeLists.txt file for it. Let’s give our project the name “HelloWorld”, and set the C++ version to 14. The CMakeLists.txt would look like this:

To generate Ninja build files, we need to run CMake with the flag -G Ninja. Run the following command in the terminal:

$ cmake -G Ninja

CMake will generate its own cache/settings files, build.ninja and rules.ninja. This image shows the output files:

After generating the needed configurations, we can start the build of the project by simply typingninja :

$ ninja

You should see an executable named HelloWorld created in the directory, as shown in this image:

Incremental build

Next time we modify the code, we don’t have to run the command for CMake. All that we need is to type ninja again and a new build is triggered.

Moreover, Ninja uses the incremental build model, that is in projects with multiple source files only the modified files are rebuilt. It doesn’t rebuild things that are already up to date. This optimization greatly decreases the build time.

Liked the story?

Put a clap, follow me on Medium and Twitter, and try Ninja when you have time. Feedback is always welcome!

About me

I am Ilyas Hamadouche, a Senior Software Engineer at Elektrobit Automotive. I am interested in automotive software and embedded systems. Follow me on Twitter and LinkedIn.

--

--