Skip to content

CMake Notes

CMake API

cmake_minimum_required

Sets the minimum required version of cmake for a project. Also updates the policy settings as explained below. <min> and the optional <policy_max> are each CMake versions of the form major.minor[.patch[.tweak]], and the … is literal.

cmake_minimum_required(VERSION <min>[...<policy_max>] [FATAL_ERROR])
cmake_minimum_required(VERSION 3.21)

project

project(<PROJECT-NAME> [<language-name>...])
project(<PROJECT-NAME>
[VERSION <major>[.<minor>[.<patch>[.<tweak>]]]]
[DESCRIPTION <project-description-string>]
[HOMEPAGE_URL <url-string>]
[LANGUAGES <language-name>...])
project(HelloWorld)

set

Set a normal, cache, or environment variable to a given value. See the cmake-language(7) variables documentation for the scopes and interaction of normal variables and cache entries. If the PARENT_SCOPE option is given the variable will be set in the scope above the current scope. Each new directory or function creates a new scope.

# Set Normal Variable
set(<variable> <value>... [PARENT_SCOPE])
# Set Cache Entry
set(<variable> <value>... CACHE <type> <docstring> [FORCE])

add_executable

Adds an executable target called <name> to be built from the source files listed in the command invocation. The <name> corresponds to the logical target name and must be globally unique within a project. The actual file name of the executable built is constructed based on conventions of the native platform (such as <name>.exe or just <name>).

add_executable(<name> [WIN32] [MACOSX_BUNDLE]
[EXCLUDE_FROM_ALL]
[source1] [source2 ...])
add_executable(HelloWorld main.cpp Foo.cpp Foo.h Bar.cpp Bar.h)

add_library

Adds a library target called <name> to be built from the source files listed in the command invocation. The <name> corresponds to the logical target name and must be globally unique within a project. The actual file name of the library built is constructed based on conventions of the native platform (such as lib<name>.a or <name>.lib).

add_library(<name> [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
[<source>...])

Specify libraries or flags to use when linking a given target and/or its dependents. Usage requirements from linked library targets will be propagated. Usage requirements of a target’s dependencies affect compilation of its own sources.

target_link_libraries(<target> ... <item>... ...)

The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target. If policy CMP0079 is not set to NEW then the target must have been created in the current directory. Repeated calls for the same <target> append items in the order called.

<item> type:

  • A library target name.
  • A full path to a library file.
  • A plain library name.
  • A link flag.
  • A generator expression.
  • A debug, optimized, or general keyword immediately followed by another <item>.