Baduit

A young French developper who really likes (modern) C++

About me
16 October 2022

CMake cheat sheet!

by Baduit

Article::Article

This is just a reminder of some commands I often use and why not share it if it can help someone.

The basics

Generate

Generate the project into path_to_build_directory (the base CMakeLists.txt must is in the current path)

cmake -B path_to_build_directory

Build

Build the project in path_to_build_directory

cmake --build path_to_build_directory

Test

Launch the tests with the root in path_to_build_directory

ctest --test-dir path_to_build_directory

Common stuff

Toolchain integration

cmake -DCMAKE_TOOLCHAIN_FILE=path_to_the_toolchain .

Specify the generator

# Example with Ninja
cmake -GNinja .

Override an option/variable

Now MY_VAR will have the value : ON (ON/OFF can be used for boolean value with CMake)

cmake -DMY_VAR=ON

Vcpkg

On all example there is an env variable named VCPKG_ROOT with path where you can find vcpkg.

Simple use of vcpkg

With Powershell

The quotes are meaningful

cmake -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" .

With Bash

cmake -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" .

Specify additionnal toolchain

cmake -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=my_path_to_my_other_toolchain .

Specify the triplet

With the triplet for emscripten

cmake -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=wasm32-emscripten .

Use Both

cmake -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=my_path_to_my_other_toolchain -DVCPKG_TARGET_TRIPLET=wasm32-emscripten .

An example with emscripten for one of my projects

cmake -GNinja -B em_build -DCMAKE_TOOLCHAIN_FILE="$env:HOMEPATH/vcpkg/scripts/buildsystems/vcpkg.cmake" -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$env:EMSCRIPTEN_UPSTREAM_ROOT/emscripten/cmake/Modules/Platform:Emscripten.cmake" -DEMSCRIPTEN=ON

Article::~Article

I hope theses commands will improve your daily life with cmake, or you can just use an IDE that launch the build by just pressing ctrl+b.

Sources

tags: cpp - cmake