Using CMakeToolchain with different generators: Ninja example

This guide demonstrates how to use CMakeToolchain with predefined generators like Ninja and how to configure it to use different generators.

Note

We assume you have already installed Ninja in your system. In case you do not have Ninja installed in your system, you can use the Ninja Conan package in your profile (default or custom) by adding tool-requires.

Understanding CMake generators

The CMake client offers a variety of generators to create build system files. If you want to use a generator other than the default chosen by CMake, you can configure tools.cmake.cmaketoolchain:generator.

Note

Please, note that CMake client is not the same as the Conan CMake helper.

To see which generators are available on your system, run:

  1. $ cmake --help

You can set this configuration in your profile, directly in the command line, or even in your global configuration.

Using the Ninja generator by default in a profile

First, let’s create a profile file name my_custom_profile, so we can set the Ninja generator as the default for all Conan packages built with this profile.

  1. $ conan profile detect --name=my_custom_profile

To set the Ninja generator as the default in my_custom_profile profile, add the entry [conf] with the generator value in the file:

  1. [settings]
  2. os=Linux
  3. arch=x86_64
  4. compiler=gcc
  5. compiler.version=13
  6. compiler.libcxx=libstdc++11
  7. compiler.cppstd=20
  8. build_type=Release
  9. [conf]
  10. tools.cmake.cmaketoolchain:generator=Ninja

Now, we will create a basic project based on the cmake_exe template as an example of a C++ project:

  1. $ conan new cmake_exe -d name=foo -d version=0.1.0

Then, we can build your project using the profile we just created:

  1. $ conan create . -pr=my_custom_profile

This configuration will be passed to the conan_toolchain.cmake file, generated by CMakeToolchain, then the Ninja generator will be used. You should see the following output snippet indicating the Ninja generator is being used:

  1. Profile host:
  2. [settings]
  3. ...
  4. [conf]
  5. tools.cmake.cmaketoolchain:generator=Ninja
  6. ...
  7. foo/0.1.0: Calling build()
  8. foo/0.1.0: Running CMake.configure()
  9. foo/0.1.0: RUN: cmake -G "Ninja" ...

Note that same configuration can be passed to the default profile, and used for all Conan packages built with that profile.

In case passing the generator configuration by command line, the same will override the profile configuration.