Skip to main content

Syntax

Basic​

cmake_minimum_required​

make_minimum_required(VERSION 3.5 FATAL_ERROR)

project​

tip

In CMake, C++ is the default programming language. However, we suggest to always explicitly state the project’s language in the project command using the LANGUAGES option.

project(recipe-01 LANGUAGES CXX)
project(vms_opensource VERSION ${releaseVersion})

message​

Record the specified message text in the log. If more than one message string is given, they are concatenated into a single message with no separator between the strings. For example when you run cmake ../, it will print out

message([mode] "message text" ...)

The optional <mode> keyword determines the type of message, which influences the way the message is handled:

FATAL_ERROR

  • CMake Error, stop processing and generation.
    • The cmake(1) executable will return a non-zero exit code.

SEND_ERROR

  • CMake Error, continue processing, but skip generation.

WARNING

  • CMake Warning, continue processing.

AUTHOR_WARNING

  • CMake Warning (dev), continue processing.

DEPRECATION

  • CMake Deprecation Error or Warning if variable CMAKE_ERROR_DEPRECATED or CMAKE_WARN_DEPRECATED is enabled, respectively, else no message.

(none) or NOTICE

  • Important message printed to stderr to attract user's attention.

STATUS

  • The main interesting messages that project users might be interested in. Ideally these should be concise, no more than a single line, but still informative.

VERBOSE

  • Detailed informational messages intended for project users. These messages should provide additional details that won't be of interest in most cases, but which may be useful to those building the project when they want deeper insight into what's happening.

DEBUG

  • Detailed informational messages intended for developers working on the project itself as opposed to users who just want to build it. These messages will not typically be of interest to other users building the project and will often be closely related to internal implementation details.

TRACE

  • Fine-grained messages with very low-level implementation details. Messages using this log level would normally only be temporary and would expect to be removed before releasing the project, packaging up the files, etc.

include​

Includes CMake file or module into the project. For example: include(your_file.cmake) or include(CMakeModule) (a little bit more about built-in modules later on)

note

Important note: it preserves the scope of the parent project, which effectively means all variables and functions declared before include() invocation are also available in the included script.

set​

To set variable, the value would be:

  • true => 1, ON, YES, TRUE, Y or a non-zero number
  • false => 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, empty string, or it ends in the suffix -NOTFOUND
set(releaseVersion 5.2.0)
set(releaseVersion.full ${releaseVersion}.${buildNumber})

Set environment

set(ENV{<name>} <value>)

Or set in script invocation

${CMAKE_COMMAND} -DNAME:STRING=value -P script.cmake

Will invoke script.cmake with variable NAME set to “value”

  • Passing the PARENT_SCOPE option to set() makes the variable visible in the parent scope.

  • You can also use CACHE STRING, the variables are stored in CMakeCache.txt files

set(ch1_MYVAR foo CACHE STRING "Variable foo that configures     bar")

unset​

Delete variable

unset(releaseVersion)

set_property​

Properties in CMake are values that are attached to a specific object or scope of CMake, such as a file, target, directory, or test case. Properties can be set or changed by using the set_property function

set_property(<Scope> <EntityName>
              [APPEND] [APPEND_STRING]
              PROPERTY <propertyName> [<values>])

Scope:

  • GLOBAL: Global properties that affect the whole build process.
  • DIRECTORY (dir): Properties that are bound to the current directory or the directories specified in (dir). These can also be set directly using the set_directory_properties command.
  • TARGET (target): Properties of specific targets. They can also be set using the set_target_properties function.
  • SOURCE (files): Applies a property to a list of source files. They can also be set directly using set_source_files_properties. Additionally, there are the SOURCE DIRECTORY and SOURCE TARGET_DIRECTORY extended options

list​

To find, get, set an array

list(APPEND _sources Message.hpp Message.cpp)
list(FIND MYLIST abc ABC_INDEX)
list(GET MYLIST ${ABC_INDEX} ABC)

You can use set to set a list (e.g: set(MYLIST a b c))

option​

Add option to cmake command

option(<option_variable> "help string" [initial value])

So you can cmake with option:

cmake -D USE_LIBRARY=ON ..

add_executable​

To create new target: the executable hello-world

add_executable(hello-world hello-world.cpp)

add_subdirectory​

Adds subdirectory to the project. Subdirectory must have its own CMakeLists.txt in it. Effectively it allows you to create sub-modules of the project. However note that in contrast with include() add_subirectory creates its own scope, instead of inheriting parent’s. Basic usage is

add_subdirectory(<path>)

Path can be absolute or relative.

add_library​

This will generate the necessary build tool instructions for compiling the specified sources into a library

add_library(target STATIC file1 file2 ...)
// for example:

add_library(message STATIC Message.hpp Message.cpp)

Whereas:

  • target: is the target name, the actual name of the generated library will be formed by CMake by adding prefix lib in front and the appropriate extension as a suffix
  • CMake accepts other values as valid for the second argument to add_library:
    • STATIC: which we have already encountered, will be used to create static libraries, that is, archives of object files for use when linking other targets, such as executables
    • SHARED: will be used to create shared libraries, that is, libraries that can be linked dynamically and loaded at runtime
    • OBJECT: can be used to compile the sources in the list given to add_library to object files, but then neither archiving them into a static library nor linking them into a shared object. The use of object libraries is particularly useful if one needs to create both static and shared libraries in one go. We will demonstrate this in this recipe.
    • MODULE: libraries are once again DSOs. In contrast to SHARED libraries, they are not linked to any other target within the project, but may be loaded dynamically later on. This is the argument to use when building a runtime plugin

Extra: IMPORTED, INTERFACE, ALIAS

Allows you to link specific library to the target. Note that generally command is quite complex, but in most basic and common form it looks like

target_link_libraries(app target)
// for example

target_link_libraries(hello-world message)

Whereas:

  • app: is the name of the app
  • target: is the name of the library target

target_sources​

target_sources(
MyLibrary
PUBLIC include/api.cpp
PRIVATE src/internals.cpp src/foo.cpp
)

Whereas:

  • PUBLIC, PRIVATE: denote the visibility of the files when they're linked against this library and serve as delimiters between the lists of files.

file​

Reference

File is a very useful command that allows you to manipulate local and remote file systems. I’ll give general outline of available subcommands that I find the most useful

  • file(READ <path> <variable>) – reads file at path to the variable.
  • file(WRITE|APPEND <path> <content>) – writes/appends content to file.
  • file(GLOB <variable> <expr>) – collects files matching expr into variable in specified folder.
  • file(GLOB_RECURSE <variable> <expr>) – collects files matching expr into variable in specified folder and all subfolders.
  • file(TO_CMAKE_PATH <path> <variable>) – converts path to internal CMake format. Helpful on Windows which has backslashes in the path.
  • file(DOWNLOAD <url> <path>) – download file from url to path.

Finding files, programs, and paths​

find_file​

Locate a single file

find_path​

Find a directory contain a specific file

find_library​

Find library files (to link against)

It will run search through PATH and CMake search locations and if the library/program is found its path will be put into variable

find_program​

Find executable programs (to use)

find_program (<VAR> name1 [path1 path2 ...])

find_package​

Find completed sets of packages

Advanced​

function​

Functions are defined by function()/endfunction().

Functions open a new scope for variables, so all the variables that are defined inside are not accessible from the outside unless the PARENT_SCOPE option is passed to set().

function(foo ARG1) 
# do something
endfunction()
# invoke foo with parameter bar
foo("bar")

macro​

CMake macros are defined using the macro()/endmacro() commands. They are a bit like functions, with the difference that in functions, the arguments are true variables, whereas in macros, they are string replacements. This means that all the arguments of a macro must be accessed using curly brackets.

Another difference is that by calling a function, control is transferred to the functions. Macros are executed as if the body of the macro had been pasted into the place of the calling state. This means that macros are not creating scopes regarding variables and control flow. Consequently, it is highly recommended to avoid calling return() in macros as this would stop the scope from executing where the macro is called

targets​

The build system of CMake is organized as a set of logical targets that correspond to an executable, library, or custom command or artifact, such as documentation or similar.

There are three major ways to create a target in CMake – add_executable, add_library, and add_custom_target. The first two are used to create executables and static or shared libraries, while the third can contain almost any custom command to be executed.

It is good practice to work with targets instead of global variables when you're setting properties for build configurations or compiler options. Some of the target properties have visibility modifiers such as PRIVATE, PUBLIC, or INTERFACE to denote which requirements are transitive – that is, which properties have to be "inherited" by a dependent target.

generator expressions​

Generator expressions are small statements that are evaluated during the configuration phase of the build. Most functions allow generator expressions to be used, with a few exceptions. They take the form of $<OPERATOR:VALUE>, where OPERATOR is applied or compared to VALUE. You can think of generator expressions as small inline if-statements.

In the following example, a generator expression is being used to enable the –Wall compiler flag for my_target if the compiler is either GCC, Clang, or Apple Clang. Note that GCC is identified as COMPILER_ID "GNU":

target_compile_options(my_target PRIVATE 
  "$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-Wall>")

built-in modules​

A module is essentially a collection of commands (or library if you will), which simplifies certain tasks. You can check the reference for a full list of available modules

Commands​

Create Makefile​

mkdir build
cd build
cmake ../ # Point to the location of `CMakeLists.txt`

To build​

cmake --build .

On GNU/Linux, CMake will by default generate Unix Makefiles to build the project

  • Makefile: The set of instructions that make will run to build the project.
  • CMakeFiles: Directory which contains temporary files, used by CMake for detecting the operating system, compiler, and so on. In addition, depending on the chosen generator, it also contains project-specific files.
  • cmake_install.cmake: A CMake script handling install rules, which is used at install time.
  • CMakeCache.txt: The CMake cache, as the filename suggests. This file is used by CMake when re-running the configuration.

To configure an Android build​

cmake -S . -B build --toolchain <NDK_DIR>/build/cmake/android.toolchain.cmake -DANDROID_ABI=armeabi-v7a -DANDROID_PLATFORM=23
cmake --system-information information.txt

Tool chain​

cmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake -S <SourceDir> -B   <BuildDir>
<!-- or -->
cmake  --toolchain toolchain.cmake -S <SourceDir> -B <BuildDir>

These calls are equivalent. If CMAKE_TOOLCHAIN_FILE is set as an environment variable, CMake will interpret this as well.

If using CMake presets, the configure presets may configure a toolchain file with the toolchainFile option, like this

{
"name": "arm64-build-debug",
"generator" : "ninja",
"displayName": "Arm 64 Debug",
"toolchainFile": "/path/to/toolchain.cmake",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
},

Switches​

-H and -B​

  • -H Search for the root CMakeLists.txt file in the current directory
  • -Bbuild tells CMake to generate all of its files in a directory called build
cmake -H. -Bbuild

-G​

For switch generator, for example, to switch to ninja

cmake -G Ninja

-D​

CMake is aware of the environment and many options can either be set via the -D switch of its CLI or via an environment variable