Skip to content

Using CMake + Ninja to Build from Source

Setup

If it's available you can install ninja with your native package manager, e.g., sudo apt install ninja-build. Otherwise you can build from source code and install.

sh
# Get the source code
git clone https://github.com/ninja-build/ninja.git
# Go to the latest release version
git checkout release
# Bootstrap Ninja
./configure.py --bootstrap
# Build Ninja with itself
ninja build.ninja
# Get the source code
git clone https://github.com/ninja-build/ninja.git
# Go to the latest release version
git checkout release
# Bootstrap Ninja
./configure.py --bootstrap
# Build Ninja with itself
ninja build.ninja

Generating Ninja Files with CMake

CMake uses generators to create native build files. See the bottom of cmake --help for generators that are available on your system.

sh
$ cmake --help
...
Generators

The following generators are available on this platform (* marks default):
* Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Ninja Multi-Config           = Generates build-<Config>.ninja files.
  Watcom WMake                 = Generates Watcom WMake makefiles.
...
$ cmake --help
...
Generators

The following generators are available on this platform (* marks default):
* Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Ninja Multi-Config           = Generates build-<Config>.ninja files.
  Watcom WMake                 = Generates Watcom WMake makefiles.
...

When calling CMake, use the -G Ninja option to set the Ninja generator. This will produce a build.ninja file. The Ninja build system requires this file to complete the actual build of your program.

sh
$ mkdir build && cd build
$ cmake -G Ninja ..
-- The C compiler identification is GNU 10.3.0
-- The CXX compiler identification is GNU 10.3.0
...
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/your_program/build
$ ls
build.ninja  cmake_install.cmake  CMakeCache.txt  CMakeFiles
$ mkdir build && cd build
$ cmake -G Ninja ..
-- The C compiler identification is GNU 10.3.0
-- The CXX compiler identification is GNU 10.3.0
...
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/your_program/build
$ ls
build.ninja  cmake_install.cmake  CMakeCache.txt  CMakeFiles

Building your Program

Simply call Ninja in your build directory.

sh
$ ninja
[4/4] Linking CXX executable your_program
$ ninja
[4/4] Linking CXX executable your_program

ADDITIONAL RESOURCES