CMAKE-COMMANDS(7) | CMake | CMAKE-COMMANDS(7) |
cmake-commands - CMake Language Command Reference
These commands are always available.
Break from an enclosing foreach or while loop.
break()
Breaks from an enclosing foreach() or while() loop.
See also the continue() command.
Query host system specific information.
cmake_host_system_information(RESULT <variable> QUERY <key> ...)
Queries system information of the host system on which cmake runs. One or more <key> can be provided to select the information to be queried. The list of queried values is stored in <variable>.
<key> can be one of the following values:
Key | Description |
NUMBER_OF_LOGICAL_CORES | Number of logical cores |
NUMBER_OF_PHYSICAL_CORES | Number of physical cores |
HOSTNAME | Hostname |
FQDN | Fully qualified domain name |
TOTAL_VIRTUAL_MEMORY | Total virtual memory in MiB [1] |
AVAILABLE_VIRTUAL_MEMORY | Available virtual memory in MiB [1] |
TOTAL_PHYSICAL_MEMORY | Total physical memory in MiB [1] |
AVAILABLE_PHYSICAL_MEMORY | Available physical memory in MiB [1] |
IS_64BIT | One if processor is 64Bit |
HAS_FPU | One if processor has floating point unit |
HAS_MMX | One if processor supports MMX instructions |
HAS_MMX_PLUS | One if processor supports Ext. MMX instructions |
HAS_SSE | One if processor supports SSE instructions |
HAS_SSE2 | One if processor supports SSE2 instructions |
HAS_SSE_FP | One if processor supports SSE FP instructions |
HAS_SSE_MMX | One if processor supports SSE MMX instructions |
HAS_AMD_3DNOW | One if processor supports 3DNow instructions |
HAS_AMD_3DNOW_PLUS | One if processor supports 3DNow+ instructions |
HAS_IA64 | One if IA64 processor emulating x86 |
HAS_SERIAL_NUMBER | One if processor has serial number |
PROCESSOR_SERIAL_NUMBER | Processor serial number |
PROCESSOR_NAME | Human readable processor name |
PROCESSOR_DESCRIPTION | Human readable full processor description |
OS_NAME | See CMAKE_HOST_SYSTEM_NAME |
OS_RELEASE | The OS sub-type e.g. on Windows Professional |
OS_VERSION | The OS build ID |
OS_PLATFORM | See CMAKE_HOST_SYSTEM_PROCESSOR |
Call meta-operations on CMake commands.
cmake_language(CALL <command> [<args>...]) cmake_language(EVAL CODE <code>...)
This command will call meta-operations on built-in CMake commands or those created via the macro() or function() commands.
cmake_language does not introduce a new variable or policy scope.
cmake_language(CALL <command> [<args>...])
Calls the named <command> with the given arguments (if any). For example, the code:
set(message_command "message") cmake_language(CALL ${message_command} STATUS "Hello World!")
is equivalent to
message(STATUS "Hello World!")
NOTE:
cmake_language(EVAL CODE <code>...)
Evaluates the <code>... as CMake code.
For example, the code:
set(A TRUE) set(B TRUE) set(C TRUE) set(condition "(A AND B) OR C") cmake_language(EVAL CODE "
if (${condition})
message(STATUS TRUE)
else()
message(STATUS FALSE)
endif()" )
is equivalent to
set(A TRUE) set(B TRUE) set(C TRUE) set(condition "(A AND B) OR C") file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/eval.cmake "
if (${condition})
message(STATUS TRUE)
else()
message(STATUS FALSE)
endif()" ) include(${CMAKE_CURRENT_BINARY_DIR}/eval.cmake)
Require a minimum version of cmake.
cmake_minimum_required(VERSION <min>[...<max>] [FATAL_ERROR])
Sets the minimum required version of cmake for a project. Also updates the policy settings as explained below.
<min> and the optional <max> are each CMake versions of the form major.minor[.patch[.tweak]], and the ... is literal.
If the running version of CMake is lower than the <min> required version it will stop processing the project and report an error. The optional <max> version, if specified, must be at least the <min> version and affects policy settings as described below. If the running version of CMake is older than 3.12, the extra ... dots will be seen as version component separators, resulting in the ...<max> part being ignored and preserving the pre-3.12 behavior of basing policies on <min>.
The FATAL_ERROR option is accepted but ignored by CMake 2.6 and higher. It should be specified so CMake versions 2.4 and lower fail with an error instead of just a warning.
NOTE:
Calling cmake_minimum_required() inside a function() limits some effects to the function scope when invoked. Such calls should not be made with the intention of having global effects.
The cmake_minimum_required(VERSION) command implicitly invokes the cmake_policy(VERSION) command to specify that the current project code is written for the given range of CMake versions. All policies known to the running version of CMake and introduced in the <min> (or <max>, if specified) version or earlier will be set to use NEW behavior. All policies introduced in later versions will be unset. This effectively requests behavior preferred as of a given CMake version and tells newer CMake versions to warn about their new policies.
When a <min> version higher than 2.4 is specified the command implicitly invokes
cmake_policy(VERSION <min>[...<max>])
which sets CMake policies based on the range of versions specified. When a <min> version 2.4 or lower is given the command implicitly invokes
cmake_policy(VERSION 2.4[...<max>])
which enables compatibility features for CMake 2.4 and lower.
Parse function or macro arguments.
cmake_parse_arguments(<prefix> <options> <one_value_keywords>
<multi_value_keywords> <args>...) cmake_parse_arguments(PARSE_ARGV <N> <prefix> <options>
<one_value_keywords> <multi_value_keywords>)
This command is for use in macros or functions. It processes the arguments given to that macro or function, and defines a set of variables which hold the values of the respective options.
The first signature reads processes arguments passed in the <args>.... This may be used in either a macro() or a function().
The PARSE_ARGV signature is only for use in a function() body. In this case the arguments that are parsed come from the ARGV# variables of the calling function. The parsing starts with the <N>-th argument, where <N> is an unsigned integer. This allows for the values to have special characters like ; in them.
The <options> argument contains all options for the respective macro, i.e. keywords which can be used when calling the macro without any value following, like e.g. the OPTIONAL keyword of the install() command.
The <one_value_keywords> argument contains all keywords for this macro which are followed by one value, like e.g. DESTINATION keyword of the install() command.
The <multi_value_keywords> argument contains all keywords for this macro which can be followed by more than one value, like e.g. the TARGETS or FILES keywords of the install() command.
NOTE:
When done, cmake_parse_arguments will consider for each of the keywords listed in <options>, <one_value_keywords> and <multi_value_keywords> a variable composed of the given <prefix> followed by "_" and the name of the respective keyword. These variables will then hold the respective value from the argument list or be undefined if the associated option could not be found. For the <options> keywords, these will always be defined, to TRUE or FALSE, whether the option is in the argument list or not.
All remaining arguments are collected in a variable <prefix>_UNPARSED_ARGUMENTS that will be undefined if all arguments were recognized. This can be checked afterwards to see whether your macro was called with unrecognized parameters.
<one_value_keywords> and <multi_value_keywords> that were given no values at all are collected in a variable <prefix>_KEYWORDS_MISSING_VALUES that will be undefined if all keywords received values. This can be checked to see if there were keywords without any values given.
Consider the following example macro, my_install(), which takes similar arguments to the real install() command:
macro(my_install)
set(options OPTIONAL FAST)
set(oneValueArgs DESTINATION RENAME)
set(multiValueArgs TARGETS CONFIGURATIONS)
cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}"
"${multiValueArgs}" ${ARGN} )
# ...
Assume my_install() has been called like this:
my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub CONFIGURATIONS)
After the cmake_parse_arguments call the macro will have set or undefined the following variables:
MY_INSTALL_OPTIONAL = TRUE MY_INSTALL_FAST = FALSE # was not used in call to my_install MY_INSTALL_DESTINATION = "bin" MY_INSTALL_RENAME <UNDEFINED> # was not used MY_INSTALL_TARGETS = "foo;bar" MY_INSTALL_CONFIGURATIONS <UNDEFINED> # was not used MY_INSTALL_UNPARSED_ARGUMENTS = "blub" # nothing expected after "OPTIONAL" MY_INSTALL_KEYWORDS_MISSING_VALUES = "CONFIGURATIONS"
# No value for "CONFIGURATIONS" given
You can then continue and process these variables.
Keywords terminate lists of values, e.g. if directly after a one_value_keyword another recognized keyword follows, this is interpreted as the beginning of the new option. E.g. my_install(TARGETS foo DESTINATION OPTIONAL) would result in MY_INSTALL_DESTINATION set to "OPTIONAL", but as OPTIONAL is a keyword itself MY_INSTALL_DESTINATION will be empty (but added to MY_INSTALL_KEYWORDS_MISSING_VALUES) and MY_INSTALL_OPTIONAL will therefore be set to TRUE.
Manage CMake Policy settings. See the cmake-policies(7) manual for defined policies.
As CMake evolves it is sometimes necessary to change existing behavior in order to fix bugs or improve implementations of existing features. The CMake Policy mechanism is designed to help keep existing projects building as new versions of CMake introduce changes in behavior. Each new policy (behavioral change) is given an identifier of the form CMP<NNNN> where <NNNN> is an integer index. Documentation associated with each policy describes the OLD and NEW behavior and the reason the policy was introduced. Projects may set each policy to select the desired behavior. When CMake needs to know which behavior to use it checks for a setting specified by the project. If no setting is available the OLD behavior is assumed and a warning is produced requesting that the policy be set.
The cmake_policy command is used to set policies to OLD or NEW behavior. While setting policies individually is supported, we encourage projects to set policies based on CMake versions:
cmake_policy(VERSION <min>[...<max>])
<min> and the optional <max> are each CMake versions of the form major.minor[.patch[.tweak]], and the ... is literal. The <min> version must be at least 2.4 and at most the running version of CMake. The <max> version, if specified, must be at least the <min> version but may exceed the running version of CMake. If the running version of CMake is older than 3.12, the extra ... dots will be seen as version component separators, resulting in the ...<max> part being ignored and preserving the pre-3.12 behavior of basing policies on <min>.
This specifies that the current CMake code is written for the given range of CMake versions. All policies known to the running version of CMake and introduced in the <min> (or <max>, if specified) version or earlier will be set to use NEW behavior. All policies introduced in later versions will be unset (unless the CMAKE_POLICY_DEFAULT_CMP<NNNN> variable sets a default). This effectively requests behavior preferred as of a given CMake version and tells newer CMake versions to warn about their new policies.
Note that the cmake_minimum_required(VERSION) command implicitly calls cmake_policy(VERSION) too.
cmake_policy(SET CMP<NNNN> NEW) cmake_policy(SET CMP<NNNN> OLD)
Tell CMake to use the OLD or NEW behavior for a given policy. Projects depending on the old behavior of a given policy may silence a policy warning by setting the policy state to OLD. Alternatively one may fix the project to work with the new behavior and set the policy state to NEW.
NOTE:
cmake_policy(GET CMP<NNNN> <variable>)
Check whether a given policy is set to OLD or NEW behavior. The output <variable> value will be OLD or NEW if the policy is set, and empty otherwise.
CMake keeps policy settings on a stack, so changes made by the cmake_policy command affect only the top of the stack. A new entry on the policy stack is managed automatically for each subdirectory to protect its parents and siblings. CMake also manages a new entry for scripts loaded by include() and find_package() commands except when invoked with the NO_POLICY_SCOPE option (see also policy CMP0011). The cmake_policy command provides an interface to manage custom entries on the policy stack:
cmake_policy(PUSH) cmake_policy(POP)
Each PUSH must have a matching POP to erase any changes. This is useful to make temporary changes to policy settings. Calls to the cmake_minimum_required(VERSION), cmake_policy(VERSION), or cmake_policy(SET) commands influence only the current top of the policy stack.
Commands created by the function() and macro() commands record policy settings when they are created and use the pre-record policies when they are invoked. If the function or macro implementation sets policies, the changes automatically propagate up through callers until they reach the closest nested policy stack entry.
Copy a file to another location and modify its contents.
configure_file(<input> <output>
[COPYONLY] [ESCAPE_QUOTES] [@ONLY]
[NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
Copies an <input> file to an <output> file and substitutes variable values referenced as @VAR@ or ${VAR} in the input file content. Each variable reference will be replaced with the current value of the variable, or the empty string if the variable is not defined. Furthermore, input lines of the form
#cmakedefine VAR ...
will be replaced with either
#define VAR ...
or
/* #undef VAR */
depending on whether VAR is set in CMake to any value not considered a false constant by the if() command. The “…” content on the line after the variable name, if any, is processed as above. Input file lines of the form #cmakedefine01 VAR will be replaced with either #define VAR 1 or #define VAR 0 similarly. The result lines (with the exception of the #undef comments) can be indented using spaces and/or tabs between the # character and the cmakedefine or cmakedefine01 words. This whitespace indentation will be preserved in the output lines:
# cmakedefine VAR # cmakedefine01 VAR
will be replaced, if VAR is defined, with
# define VAR # define VAR 1
If the input file is modified the build system will re-run CMake to re-configure the file and generate the build system again. The generated file is modified and its timestamp updated on subsequent cmake runs only if its content is changed.
The arguments are:
Consider a source tree containing a foo.h.in file:
#cmakedefine FOO_ENABLE #cmakedefine FOO_STRING "@FOO_STRING@"
An adjacent CMakeLists.txt may use configure_file to configure the header:
option(FOO_ENABLE "Enable Foo" ON) if(FOO_ENABLE)
set(FOO_STRING "foo") endif() configure_file(foo.h.in foo.h @ONLY)
This creates a foo.h in the build directory corresponding to this source directory. If the FOO_ENABLE option is on, the configured file will contain:
#define FOO_ENABLE #define FOO_STRING "foo"
Otherwise it will contain:
/* #undef FOO_ENABLE */ /* #undef FOO_STRING */
One may then use the include_directories() command to specify the output directory as an include directory:
include_directories(${CMAKE_CURRENT_BINARY_DIR})
so that sources may include the header as #include <foo.h>.
Continue to the top of enclosing foreach or while loop.
continue()
The continue command allows a cmake script to abort the rest of a block in a foreach() or while() loop, and start at the top of the next iteration.
See also the break() command.
Starts the else portion of an if block.
else([<condition>])
See the if() command.
Starts an elseif portion of an if block.
elseif(<condition>)
See the if() command, especially for the syntax and logic of the <condition>.
Ends a list of commands in a foreach block.
endforeach([<loop_var>])
See the foreach() command.
The optional <loop_var> argument is supported for backward compatibility only. If used it must be a verbatim repeat of the <loop_var> argument of the opening foreach clause.
Ends a list of commands in a function block.
endfunction([<name>])
See the function() command.
The optional <name> argument is supported for backward compatibility only. If used it must be a verbatim repeat of the <name> argument of the opening function command.
Ends a list of commands in an if block.
endif([<condition>])
See the if() command.
The optional <condition> argument is supported for backward compatibility only. If used it must be a verbatim repeat of the argument of the opening if clause.
Ends a list of commands in a macro block.
endmacro([<name>])
See the macro() command.
The optional <name> argument is supported for backward compatibility only. If used it must be a verbatim repeat of the <name> argument of the opening macro command.
Ends a list of commands in a while block.
endwhile([<condition>])
See the while() command.
The optional <condition> argument is supported for backward compatibility only. If used it must be a verbatim repeat of the argument of the opening while clause.
Execute one or more child processes.
execute_process(COMMAND <cmd1> [<arguments>]
[COMMAND <cmd2> [<arguments>]]...
[WORKING_DIRECTORY <directory>]
[TIMEOUT <seconds>]
[RESULT_VARIABLE <variable>]
[RESULTS_VARIABLE <variable>]
[OUTPUT_VARIABLE <variable>]
[ERROR_VARIABLE <variable>]
[INPUT_FILE <file>]
[OUTPUT_FILE <file>]
[ERROR_FILE <file>]
[OUTPUT_QUIET]
[ERROR_QUIET]
[COMMAND_ECHO <where>]
[OUTPUT_STRIP_TRAILING_WHITESPACE]
[ERROR_STRIP_TRAILING_WHITESPACE]
[ENCODING <name>]
[ECHO_OUTPUT_VARIABLE]
[ECHO_ERROR_VARIABLE])
Runs the given sequence of one or more commands.
Commands are executed concurrently as a pipeline, with the standard output of each process piped to the standard input of the next. A single standard error pipe is used for all processes.
Options:
CMake executes the child process using operating system APIs directly. All arguments are passed VERBATIM to the child process. No intermediate shell is used, so shell operators such as > are treated as normal arguments. (Use the INPUT_*, OUTPUT_*, and ERROR_* options to redirect stdin, stdout, and stderr.)
If a sequential execution of multiple commands is required, use multiple execute_process() calls with a single COMMAND argument.
The output will be duplicated, it will be sent into the configured variables and also on standard output or standard error.
This is analogous to the tee Unix command.
If more than one OUTPUT_* or ERROR_* option is given for the same pipe the precedence is not specified. If no OUTPUT_* or ERROR_* options are given the output will be shared with the corresponding pipes of the CMake process itself.
The execute_process() command is a newer more powerful version of exec_program(), but the old command has been kept for compatibility. Both commands run while CMake is processing the project prior to build system generation. Use add_custom_target() and add_custom_command() to create custom commands that run at build time.
File manipulation command.
Reading
file(READ <filename> <out-var> [...])
file(STRINGS <filename> <out-var> [...])
file(<HASH> <filename> <out-var>)
file(TIMESTAMP <filename> <out-var> [...])
file(GET_RUNTIME_DEPENDENCIES [...]) Writing
file({WRITE | APPEND} <filename> <content>...)
file({TOUCH | TOUCH_NOCREATE} [<file>...])
file(GENERATE OUTPUT <output-file> [...])
file(CONFIGURE OUTPUT <output-file> CONTENT <content> [...]) Filesystem
file({GLOB | GLOB_RECURSE} <out-var> [...] [<globbing-expr>...])
file(RENAME <oldname> <newname>)
file({REMOVE | REMOVE_RECURSE } [<files>...])
file(MAKE_DIRECTORY [<dir>...])
file({COPY | INSTALL} <file>... DESTINATION <dir> [...])
file(SIZE <filename> <out-var>)
file(READ_SYMLINK <linkname> <out-var>)
file(CREATE_LINK <original> <linkname> [...]) Path Conversion
file(RELATIVE_PATH <out-var> <directory> <file>)
file({TO_CMAKE_PATH | TO_NATIVE_PATH} <path> <out-var>) Transfer
file(DOWNLOAD <url> <file> [...])
file(UPLOAD <file> <url> [...]) Locking
file(LOCK <path> [...]) Archiving
file(ARCHIVE_CREATE OUTPUT <archive> PATHS <paths>... [...])
file(ARCHIVE_EXTRACT INPUT <archive> [...])
file(READ <filename> <variable>
[OFFSET <offset>] [LIMIT <max-in>] [HEX])
Read content from a file called <filename> and store it in a <variable>. Optionally start from the given <offset> and read at most <max-in> bytes. The HEX option causes data to be converted to a hexadecimal representation (useful for binary data). If the HEX option is specified, letters in the output (a through f) are in lowercase.
file(STRINGS <filename> <variable> [<options>...])
Parse a list of ASCII strings from <filename> and store it in <variable>. Binary data in the file are ignored. Carriage return (\r, CR) characters are ignored. The options are:
For example, the code
file(STRINGS myfile.txt myfile)
stores a list in the variable myfile in which each item is a line from the input file.
file(<HASH> <filename> <variable>)
Compute a cryptographic hash of the content of <filename> and store it in a <variable>. The supported <HASH> algorithm names are those listed by the string(<HASH>) command.
file(TIMESTAMP <filename> <variable> [<format>] [UTC])
Compute a string representation of the modification time of <filename> and store it in <variable>. Should the command be unable to obtain a timestamp variable will be set to the empty string (“”).
See the string(TIMESTAMP) command for documentation of the <format> and UTC options.
file(GET_RUNTIME_DEPENDENCIES
[RESOLVED_DEPENDENCIES_VAR <deps_var>]
[UNRESOLVED_DEPENDENCIES_VAR <unresolved_deps_var>]
[CONFLICTING_DEPENDENCIES_PREFIX <conflicting_deps_prefix>]
[EXECUTABLES [<executable_files>...]]
[LIBRARIES [<library_files>...]]
[MODULES [<module_files>...]]
[DIRECTORIES [<directories>...]]
[BUNDLE_EXECUTABLE <bundle_executable_file>]
[PRE_INCLUDE_REGEXES [<regexes>...]]
[PRE_EXCLUDE_REGEXES [<regexes>...]]
[POST_INCLUDE_REGEXES [<regexes>...]]
[POST_EXCLUDE_REGEXES [<regexes>...]]
)
Recursively get the list of libraries depended on by the given files.
Please note that this sub-command is not intended to be used in project mode. Instead, use it in an install(CODE) or install(SCRIPT) block. For example:
install(CODE [[
file(GET_RUNTIME_DEPENDENCIES
# ...
)
]])
The arguments are as follows:
The following arguments specify filters for including or excluding libraries to be resolved. See below for a full description of how they work.
These arguments can be used to exclude unwanted system libraries when resolving the dependencies, or to include libraries from a specific directory. The filtering works as follows:
Different platforms have different rules for how dependencies are resolved. These specifics are described here.
On Linux platforms, library resolution works as follows:
On Windows platforms, library resolution works as follows:
file(GET_RUNTIME_DEPENDENCIES
# ...
PRE_INCLUDE_REGEXES "^[Mm][Yy][Ll][Ii][Bb][Rr][Aa][Rr][Yy]\\.[Dd][Ll][Ll]$"
)
Converting the DLL name to lowercase allows the regexes to only match lowercase names, thus simplifying the regex. For example:
file(GET_RUNTIME_DEPENDENCIES
# ...
PRE_INCLUDE_REGEXES "^mylibrary\\.dll$"
)
This regex will match mylibrary.dll regardless of how it is cased, either on disk or in the depending file. (For example, it will match mylibrary.dll, MyLibrary.dll, and MYLIBRARY.DLL.)
Please note that the directory portion of any resolved DLLs retains its casing and is not converted to lowercase. Only the filename portion is converted.
On Apple platforms, library resolution works as follows:
This function accepts several variables that determine which tool is used for dependency resolution:
If this variable is not specified, it is determined automatically by system introspection.
CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM | CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL |
linux+elf | objdump |
windows+pe | dumpbin |
windows+pe | objdump |
macos+macho | otool |
If this variable is not specified, it is determined automatically by system introspection.
If this variable is not specified, it is determined by the value of CMAKE_OBJDUMP if set, else by system introspection.
file(WRITE <filename> <content>...) file(APPEND <filename> <content>...)
Write <content> into a file called <filename>. If the file does not exist, it will be created. If the file already exists, WRITE mode will overwrite it and APPEND mode will append to the end. Any directories in the path specified by <filename> that do not exist will be created.
If the file is a build input, use the configure_file() command to update the file only when its content changes.
file(TOUCH [<files>...]) file(TOUCH_NOCREATE [<files>...])
Create a file with no content if it does not yet exist. If the file already exists, its access and/or modification will be updated to the time when the function call is executed.
Use TOUCH_NOCREATE to touch a file if it exists but not create it. If a file does not exist it will be silently ignored.
With TOUCH and TOUCH_NOCREATE the contents of an existing file will not be modified.
file(GENERATE OUTPUT output-file
<INPUT input-file|CONTENT content>
[CONDITION expression])
Generate an output file for each build configuration supported by the current CMake Generator. Evaluate generator expressions from the input content to produce the output content. The options are:
Exactly one CONTENT or INPUT option must be given. A specific OUTPUT file may be named by at most one invocation of file(GENERATE). Generated files are modified and their timestamp updated on subsequent cmake runs only if their content is changed.
Note also that file(GENERATE) does not create the output file until the generation phase. The output file will not yet have been written when the file(GENERATE) command returns, it is written only after processing all of a project’s CMakeLists.txt files.
file(CONFIGURE OUTPUT output-file
CONTENT content
[ESCAPE_QUOTES] [@ONLY]
[NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
Generate an output file using the input given by CONTENT and substitute variable values referenced as @VAR@ or ${VAR} contained therein. The substitution rules behave the same as the configure_file() command. In order to match configure_file()’s behavior, generator expressions are not supported for both OUTPUT and CONTENT.
The arguments are:
file(GLOB <variable>
[LIST_DIRECTORIES true|false] [RELATIVE <path>] [CONFIGURE_DEPENDS]
[<globbing-expressions>...]) file(GLOB_RECURSE <variable> [FOLLOW_SYMLINKS]
[LIST_DIRECTORIES true|false] [RELATIVE <path>] [CONFIGURE_DEPENDS]
[<globbing-expressions>...])
Generate a list of files that match the <globbing-expressions> and store it into the <variable>. Globbing expressions are similar to regular expressions, but much simpler. If RELATIVE flag is specified, the results will be returned as relative paths to the given path. The results will be ordered lexicographically.
On Windows and macOS, globbing is case-insensitive even if the underlying filesystem is case-sensitive (both filenames and globbing expressions are converted to lowercase before matching). On other platforms, globbing is case-sensitive.
If the CONFIGURE_DEPENDS flag is specified, CMake will add logic to the main build system check target to rerun the flagged GLOB commands at build time. If any of the outputs change, CMake will regenerate the build system.
By default GLOB lists directories - directories are omitted in result if LIST_DIRECTORIES is set to false.
NOTE:
Examples of globbing expressions include:
*.cxx - match all files with extension cxx *.vt? - match all files with extension vta,...,vtz f[3-5].txt - match files f3.txt, f4.txt, f5.txt
The GLOB_RECURSE mode will traverse all the subdirectories of the matched directory and match the files. Subdirectories that are symlinks are only traversed if FOLLOW_SYMLINKS is given or policy CMP0009 is not set to NEW.
By default GLOB_RECURSE omits directories from result list - setting LIST_DIRECTORIES to true adds directories to result list. If FOLLOW_SYMLINKS is given or policy CMP0009 is not set to NEW then LIST_DIRECTORIES treats symlinks as directories.
Examples of recursive globbing include:
/dir/*.py - match all python files in /dir and subdirectories
file(RENAME <oldname> <newname>)
Move a file or directory within a filesystem from <oldname> to <newname>, replacing the destination atomically.
file(REMOVE [<files>...]) file(REMOVE_RECURSE [<files>...])
Remove the given files. The REMOVE_RECURSE mode will remove the given files and directories, also non-empty directories. No error is emitted if a given file does not exist. Relative input paths are evaluated with respect to the current source directory. Empty input paths are ignored with a warning.
file(MAKE_DIRECTORY [<directories>...])
Create the given directories and their parents as needed.
file(<COPY|INSTALL> <files>... DESTINATION <dir>
[FILE_PERMISSIONS <permissions>...]
[DIRECTORY_PERMISSIONS <permissions>...]
[NO_SOURCE_PERMISSIONS] [USE_SOURCE_PERMISSIONS]
[FOLLOW_SYMLINK_CHAIN]
[FILES_MATCHING]
[[PATTERN <pattern> | REGEX <regex>]
[EXCLUDE] [PERMISSIONS <permissions>...]] [...])
The COPY signature copies files, directories, and symlinks to a destination folder. Relative input paths are evaluated with respect to the current source directory, and a relative destination is evaluated with respect to the current build directory. Copying preserves input file timestamps, and optimizes out a file if it exists at the destination with the same timestamp. Copying preserves input permissions unless explicit permissions or NO_SOURCE_PERMISSIONS are given (default is USE_SOURCE_PERMISSIONS).
If FOLLOW_SYMLINK_CHAIN is specified, COPY will recursively resolve the symlinks at the paths given until a real file is found, and install a corresponding symlink in the destination for each symlink encountered. For each symlink that is installed, the resolution is stripped of the directory, leaving only the filename, meaning that the new symlink points to a file in the same directory as the symlink. This feature is useful on some Unix systems, where libraries are installed as a chain of symlinks with version numbers, with less specific versions pointing to more specific versions. FOLLOW_SYMLINK_CHAIN will install all of these symlinks and the library itself into the destination directory. For example, if you have the following directory structure:
and you do:
file(COPY /opt/foo/lib/libfoo.so DESTINATION lib FOLLOW_SYMLINK_CHAIN)
This will install all of the symlinks and libfoo.so.1.2.3 itself into lib.
See the install(DIRECTORY) command for documentation of permissions, FILES_MATCHING, PATTERN, REGEX, and EXCLUDE options. Copying directories preserves the structure of their content even if options are used to select a subset of files.
The INSTALL signature differs slightly from COPY: it prints status messages (subject to the CMAKE_INSTALL_MESSAGE variable), and NO_SOURCE_PERMISSIONS is default. Installation scripts generated by the install() command use this signature (with some undocumented options for internal use).
file(SIZE <filename> <variable>)
Determine the file size of the <filename> and put the result in <variable> variable. Requires that <filename> is a valid path pointing to a file and is readable.
file(READ_SYMLINK <linkname> <variable>)
This subcommand queries the symlink <linkname> and stores the path it points to in the result <variable>. If <linkname> does not exist or is not a symlink, CMake issues a fatal error.
Note that this command returns the raw symlink path and does not resolve a relative path. The following is an example of how to ensure that an absolute path is obtained:
set(linkname "/path/to/foo.sym") file(READ_SYMLINK "${linkname}" result) if(NOT IS_ABSOLUTE "${result}")
get_filename_component(dir "${linkname}" DIRECTORY)
set(result "${dir}/${result}") endif()
file(CREATE_LINK <original> <linkname>
[RESULT <result>] [COPY_ON_ERROR] [SYMBOLIC])
Create a link <linkname> that points to <original>. It will be a hard link by default, but providing the SYMBOLIC option results in a symbolic link instead. Hard links require that original exists and is a file, not a directory. If <linkname> already exists, it will be overwritten.
The <result> variable, if specified, receives the status of the operation. It is set to 0 upon success or an error message otherwise. If RESULT is not specified and the operation fails, a fatal error is emitted.
Specifying COPY_ON_ERROR enables copying the file as a fallback if creating the link fails. It can be useful for handling situations such as <original> and <linkname> being on different drives or mount points, which would make them unable to support a hard link.
file(RELATIVE_PATH <variable> <directory> <file>)
Compute the relative path from a <directory> to a <file> and store it in the <variable>.
file(TO_CMAKE_PATH "<path>" <variable>) file(TO_NATIVE_PATH "<path>" <variable>)
The TO_CMAKE_PATH mode converts a native <path> into a cmake-style path with forward-slashes (/). The input can be a single path or a system search path like $ENV{PATH}. A search path will be converted to a cmake-style list separated by ; characters.
The TO_NATIVE_PATH mode converts a cmake-style <path> into a native path with platform-specific slashes (\ on Windows and / elsewhere).
Always use double quotes around the <path> to be sure it is treated as a single argument to this command.
file(DOWNLOAD <url> <file> [<options>...]) file(UPLOAD <file> <url> [<options>...])
The DOWNLOAD mode downloads the given <url> to a local <file>. The UPLOAD mode uploads a local <file> to a given <url>.
Options to both DOWNLOAD and UPLOAD are:
If neither NETRC option is given CMake will check variables CMAKE_NETRC and CMAKE_NETRC_FILE, respectively.
For https:// URLs CMake must be built with OpenSSL support. TLS/SSL certificates are not checked by default. Set TLS_VERIFY to ON to check certificates. If neither TLS option is given CMake will check variables CMAKE_TLS_VERIFY and CMAKE_TLS_CAINFO, respectively.
Additional options to DOWNLOAD are:
EXPECTED_HASH ALGO=<value>
file(LOCK <path> [DIRECTORY] [RELEASE]
[GUARD <FUNCTION|FILE|PROCESS>]
[RESULT_VARIABLE <variable>]
[TIMEOUT <seconds>])
Lock a file specified by <path> if no DIRECTORY option present and file <path>/cmake.lock otherwise. File will be locked for scope defined by GUARD option (default value is PROCESS). RELEASE option can be used to unlock file explicitly. If option TIMEOUT is not specified CMake will wait until lock succeed or until fatal error occurs. If TIMEOUT is set to 0 lock will be tried once and result will be reported immediately. If TIMEOUT is not 0 CMake will try to lock file for the period specified by <seconds> value. Any errors will be interpreted as fatal if there is no RESULT_VARIABLE option. Otherwise result will be stored in <variable> and will be 0 on success or error message on failure.
Note that lock is advisory - there is no guarantee that other processes will respect this lock, i.e. lock synchronize two or more CMake instances sharing some modifiable resources. Similar logic applied to DIRECTORY option - locking parent directory doesn’t prevent other LOCK commands to lock any child directory or file.
Trying to lock file twice is not allowed. Any intermediate directories and file itself will be created if they not exist. GUARD and TIMEOUT options ignored on RELEASE operation.
file(ARCHIVE_CREATE OUTPUT <archive>
PATHS <paths>...
[FORMAT <format>]
[COMPRESSION <compression>]
[MTIME <mtime>]
[VERBOSE])
Creates the specified <archive> file with the files and directories listed in <paths>. Note that <paths> must list actual files or directories, wildcards are not supported.
Use the FORMAT option to specify the archive format. Supported values for <format> are 7zip, gnutar, pax, paxr, raw and zip. If FORMAT is not given, the default format is paxr.
Some archive formats allow the type of compression to be specified. The 7zip and zip archive formats already imply a specific type of compression. The other formats use no compression by default, but can be directed to do so with the COMPRESSION option. Valid values for <compression> are None, BZip2, GZip, XZ, and Zstd.
NOTE:
The VERBOSE option enables verbose output for the archive operation.
To specify the modification time recorded in tarball entries, use the MTIME option.
file(ARCHIVE_EXTRACT INPUT <archive>
[DESTINATION <dir>]
[PATTERNS <patterns>...]
[LIST_ONLY]
[VERBOSE])
Extracts or lists the content of the specified <archive>.
The directory where the content of the archive will be extracted to can be specified using the DESTINATION option. If the directory does not exist, it will be created. If DESTINATION is not given, the current binary directory will be used.
If required, you may select which files and directories to list or extract from the archive using the specified <patterns>. Wildcards are supported. If the PATTERNS option is not given, the entire archive will be listed or extracted.
LIST_ONLY will list the files in the archive rather than extract them.
With VERBOSE, the command will produce verbose output.
A short-hand signature is:
find_file (<VAR> name1 [path1 path2 ...])
The general signature is:
find_file (
<VAR>
name | NAMES name1 [name2 ...]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[REQUIRED]
[NO_DEFAULT_PATH]
[NO_PACKAGE_ROOT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
This command is used to find a full path to named file. A cache entry named by <VAR> is created to store the result of this command. If the full path to a file is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND. The REQUIRED option stops processing with an error message if nothing is found, otherwise the search will be attempted again the next time find_file is invoked with the same variable.
Options include:
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:
The platform paths that these variables contain are locations that typically include installed software. An example being /usr/local for UNIX based platforms.
On macOS the CMAKE_FIND_FRAMEWORK and CMAKE_FIND_APPBUNDLE variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the CMAKE_STAGING_PREFIX are excluded from this re-rooting, because that variable is always a path on the host system. By default the CMAKE_FIND_ROOT_PATH is empty.
The CMAKE_SYSROOT variable can also be used to specify exactly one directory to use as a prefix. Setting CMAKE_SYSROOT also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH are searched, then the CMAKE_SYSROOT directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_INCLUDE. This behavior can be manually overridden on a per-call basis using options:
The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:
find_file (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_file (<VAR> NAMES name)
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
A short-hand signature is:
find_library (<VAR> name1 [path1 path2 ...])
The general signature is:
find_library (
<VAR>
name | NAMES name1 [name2 ...] [NAMES_PER_DIR]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[REQUIRED]
[NO_DEFAULT_PATH]
[NO_PACKAGE_ROOT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
This command is used to find a library. A cache entry named by <VAR> is created to store the result of this command. If the library is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND. The REQUIRED option stops processing with an error message if nothing is found, otherwise the search will be attempted again the next time find_library is invoked with the same variable.
Options include:
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:
The platform paths that these variables contain are locations that typically include installed software. An example being /usr/local for UNIX based platforms.
On macOS the CMAKE_FIND_FRAMEWORK and CMAKE_FIND_APPBUNDLE variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the CMAKE_STAGING_PREFIX are excluded from this re-rooting, because that variable is always a path on the host system. By default the CMAKE_FIND_ROOT_PATH is empty.
The CMAKE_SYSROOT variable can also be used to specify exactly one directory to use as a prefix. Setting CMAKE_SYSROOT also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH are searched, then the CMAKE_SYSROOT directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_LIBRARY. This behavior can be manually overridden on a per-call basis using options:
The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:
find_library (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_library (<VAR> NAMES name)
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
When more than one value is given to the NAMES option this command by default will consider one name at a time and search every directory for it. The NAMES_PER_DIR option tells this command to consider one directory at a time and search for all names in it.
Each library name given to the NAMES option is first considered as a library file name and then considered with platform-specific prefixes (e.g. lib) and suffixes (e.g. .so). Therefore one may specify library file names such as libfoo.a directly. This can be used to locate static libraries on UNIX-like systems.
If the library found is a framework, then <VAR> will be set to the full path to the framework <fullPath>/A.framework. When a full path to a framework is used as a library, CMake will use a -framework A, and a -F<fullPath> to link the framework to the target.
If the CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX variable is set all search paths will be tested as normal, with the suffix appended, and with all matches of lib/ replaced with lib${CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX}/. This variable overrides the FIND_LIBRARY_USE_LIB32_PATHS, FIND_LIBRARY_USE_LIBX32_PATHS, and FIND_LIBRARY_USE_LIB64_PATHS global properties.
If the FIND_LIBRARY_USE_LIB32_PATHS global property is set all search paths will be tested as normal, with 32/ appended, and with all matches of lib/ replaced with lib32/. This property is automatically set for the platforms that are known to need it if at least one of the languages supported by the project() command is enabled.
If the FIND_LIBRARY_USE_LIBX32_PATHS global property is set all search paths will be tested as normal, with x32/ appended, and with all matches of lib/ replaced with libx32/. This property is automatically set for the platforms that are known to need it if at least one of the languages supported by the project() command is enabled.
If the FIND_LIBRARY_USE_LIB64_PATHS global property is set all search paths will be tested as normal, with 64/ appended, and with all matches of lib/ replaced with lib64/. This property is automatically set for the platforms that are known to need it if at least one of the languages supported by the project() command is enabled.
Find an external project, and load its settings.
find_package(<PackageName> [version] [EXACT] [QUIET] [MODULE]
[REQUIRED] [[COMPONENTS] [components...]]
[OPTIONAL_COMPONENTS components...]
[NO_POLICY_SCOPE])
Finds and loads settings from an external project. <PackageName>_FOUND will be set to indicate whether the package was found. When the package is found package-specific information is provided through variables and Imported Targets documented by the package itself. The QUIET option disables informational messages, including those indicating that the package cannot be found if it is not REQUIRED. The REQUIRED option stops processing with an error message if the package cannot be found.
A package-specific list of required components may be listed after the COMPONENTS option (or after the REQUIRED option if present). Additional optional components may be listed after OPTIONAL_COMPONENTS. Available components and their influence on whether a package is considered to be found are defined by the target package.
The [version] argument requests a version with which the package found should be compatible (format is major[.minor[.patch[.tweak]]]). The EXACT option requests that the version be matched exactly. If no [version] and/or component list is given to a recursive invocation inside a find-module, the corresponding arguments are forwarded automatically from the outer call (including the EXACT flag for [version]). Version support is currently provided only on a package-by-package basis (see the Version Selection section below).
See the cmake_policy() command documentation for discussion of the NO_POLICY_SCOPE option.
The command has two modes by which it searches for packages: “Module” mode and “Config” mode. The above signature selects Module mode. If no module is found the command falls back to Config mode, described below. This fall back is disabled if the MODULE option is given.
In Module mode, CMake searches for a file called Find<PackageName>.cmake. The file is first searched in the CMAKE_MODULE_PATH, then among the Find Modules provided by the CMake installation. If the file is found, it is read and processed by CMake. It is responsible for finding the package, checking the version, and producing any needed messages. Some find-modules provide limited or no support for versioning; check the module documentation.
If the MODULE option is not specified in the above signature, CMake first searches for the package using Module mode. Then, if the package is not found, it searches again using Config mode. A user may set the variable CMAKE_FIND_PACKAGE_PREFER_CONFIG to TRUE to direct CMake first search using Config mode before falling back to Module mode.
User code should generally look for packages using the above basic signature. The remainder of this command documentation specifies the full command signature and details of the search process. Project maintainers wishing to provide a package to be found by this command are encouraged to read on.
The complete Config mode command signature is
find_package(<PackageName> [version] [EXACT] [QUIET]
[REQUIRED] [[COMPONENTS] [components...]]
[OPTIONAL_COMPONENTS components...]
[CONFIG|NO_MODULE]
[NO_POLICY_SCOPE]
[NAMES name1 [name2 ...]]
[CONFIGS config1 [config2 ...]]
[HINTS path1 [path2 ... ]]
[PATHS path1 [path2 ... ]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[NO_DEFAULT_PATH]
[NO_PACKAGE_ROOT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_PACKAGE_REGISTRY]
[NO_CMAKE_BUILDS_PATH] # Deprecated; does nothing.
[NO_CMAKE_SYSTEM_PATH]
[NO_CMAKE_SYSTEM_PACKAGE_REGISTRY]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH])
The CONFIG option, the synonymous NO_MODULE option, or the use of options not specified in the basic signature all enforce pure Config mode. In pure Config mode, the command skips Module mode search and proceeds at once with Config mode search.
Config mode search attempts to locate a configuration file provided by the package to be found. A cache entry called <PackageName>_DIR is created to hold the directory containing the file. By default the command searches for a package with the name <PackageName>. If the NAMES option is given the names following it are used instead of <PackageName>. The command searches for a file called <PackageName>Config.cmake or <lower-case-package-name>-config.cmake for each name specified. A replacement set of possible configuration file names may be given using the CONFIGS option. The search procedure is specified below. Once found, the configuration file is read and processed by CMake. Since the file is provided by the package it already knows the location of package contents. The full path to the configuration file is stored in the cmake variable <PackageName>_CONFIG.
All configuration files which have been considered by CMake while searching for an installation of the package with an appropriate version are stored in the cmake variable <PackageName>_CONSIDERED_CONFIGS, the associated versions in <PackageName>_CONSIDERED_VERSIONS.
If the package configuration file cannot be found CMake will generate an error describing the problem unless the QUIET argument is specified. If REQUIRED is specified and the package is not found a fatal error is generated and the configure step stops executing. If <PackageName>_DIR has been set to a directory not containing a configuration file CMake will ignore it and search from scratch.
Package maintainers providing CMake package configuration files are encouraged to name and install them such that the Search Procedure outlined below will find them without requiring use of additional options.
When the [version] argument is given Config mode will only find a version of the package that claims compatibility with the requested version (format is major[.minor[.patch[.tweak]]]). If the EXACT option is given only a version of the package claiming an exact match of the requested version may be found. CMake does not establish any convention for the meaning of version numbers. Package version numbers are checked by “version” files provided by the packages themselves. For a candidate package configuration file <config-file>.cmake the corresponding version file is located next to it and named either <config-file>-version.cmake or <config-file>Version.cmake. If no such version file is available then the configuration file is assumed to not be compatible with any requested version. A basic version file containing generic version matching code can be created using the CMakePackageConfigHelpers module. When a version file is found it is loaded to check the requested version number. The version file is loaded in a nested scope in which the following variables have been defined:
The version file checks whether it satisfies the requested version and sets these variables:
These variables are checked by the find_package command to determine whether the configuration file provides an acceptable version. They are not available after the find_package call returns. If the version is acceptable the following variables are set:
and the corresponding package configuration file is loaded. When multiple package configuration files are available whose version files claim compatibility with the version requested it is unspecified which one is chosen: unless the variable CMAKE_FIND_PACKAGE_SORT_ORDER is set no attempt is made to choose a highest or closest version number.
To control the order in which find_package checks for compatibility use the two variables CMAKE_FIND_PACKAGE_SORT_ORDER and CMAKE_FIND_PACKAGE_SORT_DIRECTION. For instance in order to select the highest version one can set
SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL) SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
before calling find_package.
CMake constructs a set of possible installation prefixes for the package. Under each prefix several directories are searched for a configuration file. The tables below show the directories searched. Each entry is meant for installation trees following Windows (W), UNIX (U), or Apple (A) conventions:
<prefix>/ (W) <prefix>/(cmake|CMake)/ (W) <prefix>/<name>*/ (W) <prefix>/<name>*/(cmake|CMake)/ (W) <prefix>/(lib/<arch>|lib*|share)/cmake/<name>*/ (U) <prefix>/(lib/<arch>|lib*|share)/<name>*/ (U) <prefix>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (U) <prefix>/<name>*/(lib/<arch>|lib*|share)/cmake/<name>*/ (W/U) <prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/ (W/U) <prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (W/U)
On systems supporting macOS FRAMEWORK and BUNDLE, the following directories are searched for Frameworks or Application Bundles containing a configuration file:
<prefix>/<name>.framework/Resources/ (A) <prefix>/<name>.framework/Resources/CMake/ (A) <prefix>/<name>.framework/Versions/*/Resources/ (A) <prefix>/<name>.framework/Versions/*/Resources/CMake/ (A) <prefix>/<name>.app/Contents/Resources/ (A) <prefix>/<name>.app/Contents/Resources/CMake/ (A)
In all cases the <name> is treated as case-insensitive and corresponds to any of the names specified (<PackageName> or names given by NAMES).
Paths with lib/<arch> are enabled if the CMAKE_LIBRARY_ARCHITECTURE variable is set. lib* includes one or more of the values lib64, lib32, libx32 or lib (searched in that order).
If PATH_SUFFIXES is specified, the suffixes are appended to each (W) or (U) directory entry one-by-one.
This set of directories is intended to work in cooperation with projects that provide configuration files in their installation trees. Directories above marked with (W) are intended for installations on Windows where the prefix may point at the top of an application’s installation directory. Those marked with (U) are intended for installations on UNIX platforms where the prefix is shared by multiple packages. This is merely a convention, so all (W) and (U) directories are still searched on all platforms. Directories marked with (A) are intended for installations on Apple platforms. The CMAKE_FIND_FRAMEWORK and CMAKE_FIND_APPBUNDLE variables determine the order of preference.
The set of installation prefixes is constructed using the following steps. If NO_DEFAULT_PATH is specified all NO_* options are enabled.
See the cmake-packages(7) manual for details on the user package registry.
The platform paths that these variables contain are locations that typically include installed software. An example being /usr/local for UNIX based platforms.
See the cmake-packages(7) manual for details on the system package registry.
The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the CMAKE_STAGING_PREFIX are excluded from this re-rooting, because that variable is always a path on the host system. By default the CMAKE_FIND_ROOT_PATH is empty.
The CMAKE_SYSROOT variable can also be used to specify exactly one directory to use as a prefix. Setting CMAKE_SYSROOT also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH are searched, then the CMAKE_SYSROOT directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_PACKAGE. This behavior can be manually overridden on a per-call basis using options:
The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:
find_package (<PackageName> PATHS paths... NO_DEFAULT_PATH) find_package (<PackageName>)
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
By default the value stored in the result variable will be the path at which the file is found. The CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS variable may be set to TRUE before calling find_package in order to resolve symbolic links and store the real path to the file.
Every non-REQUIRED find_package call can be disabled by setting the CMAKE_DISABLE_FIND_PACKAGE_<PackageName> variable to TRUE.
When loading a find module or package configuration file find_package defines variables to provide information about the call arguments (and restores their original state before returning):
In Module mode the loaded find module is responsible to honor the request detailed by these variables; see the find module for details. In Config mode find_package handles REQUIRED, QUIET, and [version] options automatically but leaves it to the package configuration file to handle components in a way that makes sense for the package. The package configuration file may set <PackageName>_FOUND to false to tell find_package that component requirements are not satisfied.
A short-hand signature is:
find_path (<VAR> name1 [path1 path2 ...])
The general signature is:
find_path (
<VAR>
name | NAMES name1 [name2 ...]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[REQUIRED]
[NO_DEFAULT_PATH]
[NO_PACKAGE_ROOT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
This command is used to find a directory containing the named file. A cache entry named by <VAR> is created to store the result of this command. If the file in a directory is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND. The REQUIRED option stops processing with an error message if nothing is found, otherwise the search will be attempted again the next time find_path is invoked with the same variable.
Options include:
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:
The platform paths that these variables contain are locations that typically include installed software. An example being /usr/local for UNIX based platforms.
On macOS the CMAKE_FIND_FRAMEWORK and CMAKE_FIND_APPBUNDLE variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the CMAKE_STAGING_PREFIX are excluded from this re-rooting, because that variable is always a path on the host system. By default the CMAKE_FIND_ROOT_PATH is empty.
The CMAKE_SYSROOT variable can also be used to specify exactly one directory to use as a prefix. Setting CMAKE_SYSROOT also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH are searched, then the CMAKE_SYSROOT directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_INCLUDE. This behavior can be manually overridden on a per-call basis using options:
The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:
find_path (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_path (<VAR> NAMES name)
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
When searching for frameworks, if the file is specified as A/b.h, then the framework search will look for A.framework/Headers/b.h. If that is found the path will be set to the path to the framework. CMake will convert this to the correct -F option to include the file.
A short-hand signature is:
find_program (<VAR> name1 [path1 path2 ...])
The general signature is:
find_program (
<VAR>
name | NAMES name1 [name2 ...] [NAMES_PER_DIR]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[REQUIRED]
[NO_DEFAULT_PATH]
[NO_PACKAGE_ROOT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
This command is used to find a program. A cache entry named by <VAR> is created to store the result of this command. If the program is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND. The REQUIRED option stops processing with an error message if nothing is found, otherwise the search will be attempted again the next time find_program is invoked with the same variable.
Options include:
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:
The platform paths that these variables contain are locations that typically include installed software. An example being /usr/local for UNIX based platforms.
On macOS the CMAKE_FIND_FRAMEWORK and CMAKE_FIND_APPBUNDLE variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the CMAKE_STAGING_PREFIX are excluded from this re-rooting, because that variable is always a path on the host system. By default the CMAKE_FIND_ROOT_PATH is empty.
The CMAKE_SYSROOT variable can also be used to specify exactly one directory to use as a prefix. Setting CMAKE_SYSROOT also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH are searched, then the CMAKE_SYSROOT directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_PROGRAM. This behavior can be manually overridden on a per-call basis using options:
The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:
find_program (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_program (<VAR> NAMES name)
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
When more than one value is given to the NAMES option this command by default will consider one name at a time and search every directory for it. The NAMES_PER_DIR option tells this command to consider one directory at a time and search for all names in it.
Evaluate a group of commands for each value in a list.
foreach(<loop_var> <items>)
<commands> endforeach()
where <items> is a list of items that are separated by semicolon or whitespace. All commands between foreach and the matching endforeach are recorded without being invoked. Once the endforeach is evaluated, the recorded list of commands is invoked once for each item in <items>. At the beginning of each iteration the variable loop_var will be set to the value of the current item.
The commands break() and continue() provide means to escape from the normal control flow.
Per legacy, the endforeach() command admits an optional <loop_var> argument. If used, it must be a verbatim repeat of the argument of the opening foreach command.
foreach(<loop_var> RANGE <stop>)
In this variant, foreach iterates over the numbers 0, 1, … up to (and including) the nonnegative integer <stop>.
foreach(<loop_var> RANGE <start> <stop> [<step>])
In this variant, foreach iterates over the numbers from <start> up to at most <stop> in steps of <step>. If <step> is not specified, then the step size is 1. The three arguments <start> <stop> <step> must all be nonnegative integers, and <stop> must not be smaller than <start>; otherwise you enter the danger zone of undocumented behavior that may change in future releases.
foreach(<loop_var> IN [LISTS [<lists>]] [ITEMS [<items>]])
In this variant, <lists> is a whitespace or semicolon separated list of list-valued variables. The foreach command iterates over each item in each given list. The <items> following the ITEMS keyword are processed as in the first variant of the foreach command. The forms LISTS A and ITEMS ${A} are equivalent.
The following example shows how the LISTS option is processed:
set(A 0;1) set(B 2 3) set(C "4 5") set(D 6;7 8) set(E "") foreach(X IN LISTS A B C D E)
message(STATUS "X=${X}") endforeach()
yields
-- X=0 -- X=1 -- X=2 -- X=3 -- X=4 5 -- X=6 -- X=7 -- X=8
foreach(<loop_var>... IN ZIP_LISTS <lists>)
In this variant, <lists> is a whitespace or semicolon separated list of list-valued variables. The foreach command iterates over each list simultaneously setting the iteration variables as follows:
list(APPEND English one two three four) list(APPEND Bahasa satu dua tiga) foreach(num IN ZIP_LISTS English Bahasa)
message(STATUS "num_0=${num_0}, num_1=${num_1}") endforeach() foreach(en ba IN ZIP_LISTS English Bahasa)
message(STATUS "en=${en}, ba=${ba}") endforeach()
yields
-- num_0=one, num_1=satu -- num_0=two, num_1=dua -- num_0=three, num_1=tiga -- num_0=four, num_1= -- en=one, ba=satu -- en=two, ba=dua -- en=three, ba=tiga -- en=four, ba=
Start recording a function for later invocation as a command.
function(<name> [<arg1> ...])
<commands> endfunction()
Defines a function named <name> that takes arguments named <arg1>, … The <commands> in the function definition are recorded; they are not executed until the function is invoked.
Per legacy, the endfunction() command admits an optional <name> argument. If used, it must be a verbatim repeat of the argument of the opening function command.
A function opens a new scope: see set(var PARENT_SCOPE) for details.
See the cmake_policy() command documentation for the behavior of policies inside functions.
See the macro() command documentation for differences between CMake functions and macros.
The function invocation is case-insensitive. A function defined as
function(foo)
<commands> endfunction()
can be invoked through any of
foo() Foo() FOO() cmake_language(CALL foo)
and so on. However, it is strongly recommended to stay with the case chosen in the function definition. Typically functions use all-lowercase names.
The cmake_language(CALL ...) command can also be used to invoke the function.
When the function is invoked, the recorded <commands> are first modified by replacing formal parameters (${arg1}, …) with the arguments passed, and then invoked as normal commands.
In addition to referencing the formal parameters you can reference the ARGC variable which will be set to the number of arguments passed into the function as well as ARGV0, ARGV1, ARGV2, … which will have the actual values of the arguments passed in. This facilitates creating functions with optional arguments.
Furthermore, ARGV holds the list of all arguments given to the function and ARGN holds the list of arguments past the last expected argument. Referencing to ARGV# arguments beyond ARGC have undefined behavior. Checking that ARGC is greater than # is the only way to ensure that ARGV# was passed to the function as an extra argument.
Get a global property of the CMake instance.
get_cmake_property(<var> <property>)
Gets a global property from the CMake instance. The value of the <property> is stored in the variable <var>. If the property is not found, <var> will be set to NOTFOUND. See the cmake-properties(7) manual for available properties.
See also the get_property() command GLOBAL option.
In addition to global properties, this command (for historical reasons) also supports the VARIABLES and MACROS directory properties. It also supports a special COMPONENTS global property that lists the components given to the install() command.
Get a property of DIRECTORY scope.
get_directory_property(<variable> [DIRECTORY <dir>] <prop-name>)
Stores a property of directory scope in the named <variable>. The DIRECTORY argument specifies another directory from which to retrieve the property value instead of the current directory. The specified directory must have already been traversed by CMake.
If the property is not defined for the nominated directory scope, an empty string is returned. In the case of INHERITED properties, if the property is not found for the nominated directory scope, the search will chain to a parent scope as described for the define_property() command.
get_directory_property(<variable> [DIRECTORY <dir>]
DEFINITION <var-name>)
Get a variable definition from a directory. This form is useful to get a variable definition from another directory.
See also the more general get_property() command.
Get a specific component of a full filename.
get_filename_component(<var> <FileName> <mode> [CACHE])
Sets <var> to a component of <FileName>, where <mode> is one of:
DIRECTORY = Directory without file name NAME = File name without directory EXT = File name longest extension (.b.c from d/a.b.c) NAME_WE = File name without directory or longest extension LAST_EXT = File name last extension (.c from d/a.b.c) NAME_WLE = File name without directory or last extension PATH = Legacy alias for DIRECTORY (use for CMake <= 2.8.11)
Paths are returned with forward slashes and have no trailing slashes. If the optional CACHE argument is specified, the result variable is added to the cache.
get_filename_component(<var> <FileName> <mode> [BASE_DIR <dir>] [CACHE])
Sets <var> to the absolute path of <FileName>, where <mode> is one of:
ABSOLUTE = Full path to file REALPATH = Full path to existing file with symlinks resolved
If the provided <FileName> is a relative path, it is evaluated relative to the given base directory <dir>. If no base directory is provided, the default base directory will be CMAKE_CURRENT_SOURCE_DIR.
Paths are returned with forward slashes and have no trailing slashes. If the optional CACHE argument is specified, the result variable is added to the cache.
get_filename_component(<var> <FileName> PROGRAM [PROGRAM_ARGS <arg_var>] [CACHE])
The program in <FileName> will be found in the system search path or left as a full path. If PROGRAM_ARGS is present with PROGRAM, then any command-line arguments present in the <FileName> string are split from the program name and stored in <arg_var>. This is used to separate a program name from its arguments in a command line string.
Get a property.
get_property(<variable>
<GLOBAL |
DIRECTORY [<dir>] |
TARGET <target> |
SOURCE <source> |
[DIRECTORY <dir> | TARGET_DIRECTORY <target>] |
INSTALL <file> |
TEST <test> |
CACHE <entry> |
VARIABLE >
PROPERTY <name>
[SET | DEFINED | BRIEF_DOCS | FULL_DOCS])
Gets one property from one object in a scope.
The first argument specifies the variable in which to store the result. The second argument determines the scope from which to get the property. It must be one of the following:
See also the get_source_file_property() command.
The required PROPERTY option is immediately followed by the name of the property to get. If the property is not set an empty value is returned, although some properties support inheriting from a parent scope if defined to behave that way (see define_property()).
If the SET option is given the variable is set to a boolean value indicating whether the property has been set. If the DEFINED option is given the variable is set to a boolean value indicating whether the property has been defined such as with the define_property() command.
If BRIEF_DOCS or FULL_DOCS is given then the variable is set to a string containing documentation for the requested property. If documentation is requested for a property that has not been defined NOTFOUND is returned.
Conditionally execute a group of commands.
if(<condition>)
<commands> elseif(<condition>) # optional block, can be repeated
<commands> else() # optional block
<commands> endif()
Evaluates the condition argument of the if clause according to the Condition syntax described below. If the result is true, then the commands in the if block are executed. Otherwise, optional elseif blocks are processed in the same way. Finally, if no condition is true, commands in the optional else block are executed.
Per legacy, the else() and endif() commands admit an optional <condition> argument. If used, it must be a verbatim repeat of the argument of the opening if command.
The following syntax applies to the condition argument of the if, elseif and while() clauses.
Compound conditions are evaluated in the following order of precedence: Innermost parentheses are evaluated first. Next come unary tests such as EXISTS, COMMAND, and DEFINED. Then binary tests such as EQUAL, LESS, LESS_EQUAL, GREATER, GREATER_EQUAL, STREQUAL, STRLESS, STRLESS_EQUAL, STRGREATER, STRGREATER_EQUAL, VERSION_EQUAL, VERSION_LESS, VERSION_LESS_EQUAL, VERSION_GREATER, VERSION_GREATER_EQUAL, and MATCHES. Then the boolean operators in the order NOT, AND, and finally OR.
Possible conditions are:
The if command was written very early in CMake’s history, predating the ${} variable evaluation syntax, and for convenience evaluates variables named by its arguments as shown in the above signatures. Note that normal variable evaluation with ${} applies before the if command even receives the arguments. Therefore code like
set(var1 OFF) set(var2 "var1") if(${var2})
appears to the if command as
if(var1)
and is evaluated according to the if(<variable>) case documented above. The result is OFF which is false. However, if we remove the ${} from the example then the command sees
if(var2)
which is true because var2 is defined to var1 which is not a false constant.
Automatic evaluation applies in the other cases whenever the above-documented condition syntax accepts <variable|string>:
To prevent ambiguity, potential variable or keyword names can be specified in a Quoted Argument or a Bracket Argument. A quoted or bracketed variable or keyword will be interpreted as a string and not dereferenced or interpreted. See policy CMP0054.
There is no automatic evaluation for environment or cache Variable References. Their values must be referenced as $ENV{<name>} or $CACHE{<name>} wherever the above-documented condition syntax accepts <variable|string>.
Load and run CMake code from a file or module.
include(<file|module> [OPTIONAL] [RESULT_VARIABLE <var>]
[NO_POLICY_SCOPE])
Loads and runs CMake code from the file given. Variable reads and writes access the scope of the caller (dynamic scoping). If OPTIONAL is present, then no error is raised if the file does not exist. If RESULT_VARIABLE is given the variable <var> will be set to the full filename which has been included or NOTFOUND if it failed.
If a module is specified instead of a file, the file with name <modulename>.cmake is searched first in CMAKE_MODULE_PATH, then in the CMake module directory. There is one exception to this: if the file which calls include() is located itself in the CMake builtin module directory, then first the CMake builtin module directory is searched and CMAKE_MODULE_PATH afterwards. See also policy CMP0017.
See the cmake_policy() command documentation for discussion of the NO_POLICY_SCOPE option.
Provides an include guard for the file currently being processed by CMake.
include_guard([DIRECTORY|GLOBAL])
Sets up an include guard for the current CMake file (see the CMAKE_CURRENT_LIST_FILE variable documentation).
CMake will end its processing of the current file at the location of the include_guard() command if the current file has already been processed for the applicable scope (see below). This provides functionality similar to the include guards commonly used in source headers or to the #pragma once directive. If the current file has been processed previously for the applicable scope, the effect is as though return() had been called. Do not call this command from inside a function being defined within the current file.
An optional argument specifying the scope of the guard may be provided. Possible values for the option are:
If no arguments given, include_guard has the same scope as a variable, meaning that the include guard effect is isolated by the most recent function scope or current directory if no inner function scopes exist. In this case the command behavior is the same as:
if(__CURRENT_FILE_VAR__)
return() endif() set(__CURRENT_FILE_VAR__ TRUE)
List operations.
Reading
list(LENGTH <list> <out-var>)
list(GET <list> <element index> [<index> ...] <out-var>)
list(JOIN <list> <glue> <out-var>)
list(SUBLIST <list> <begin> <length> <out-var>) Search
list(FIND <list> <value> <out-var>) Modification
list(APPEND <list> [<element>...])
list(FILTER <list> {INCLUDE | EXCLUDE} REGEX <regex>)
list(INSERT <list> <index> [<element>...])
list(POP_BACK <list> [<out-var>...])
list(POP_FRONT <list> [<out-var>...])
list(PREPEND <list> [<element>...])
list(REMOVE_ITEM <list> <value>...)
list(REMOVE_AT <list> <index>...)
list(REMOVE_DUPLICATES <list>)
list(TRANSFORM <list> <ACTION> [...]) Ordering
list(REVERSE <list>)
list(SORT <list> [...])
The list subcommands APPEND, INSERT, FILTER, PREPEND, POP_BACK, POP_FRONT, REMOVE_AT, REMOVE_ITEM, REMOVE_DUPLICATES, REVERSE and SORT may create new values for the list within the current CMake variable scope. Similar to the set() command, the LIST command creates new variable values in the current scope, even if the list itself is actually defined in a parent scope. To propagate the results of these operations upwards, use set() with PARENT_SCOPE, set() with CACHE INTERNAL, or some other means of value propagation.
NOTE:
NOTE:
list(LENGTH <list> <output variable>)
Returns the list’s length.
list(GET <list> <element index> [<element index> ...] <output variable>)
Returns the list of elements specified by indices from the list.
list(JOIN <list> <glue> <output variable>)
Returns a string joining all list’s elements using the glue string. To join multiple strings, which are not part of a list, use JOIN operator from string() command.
list(SUBLIST <list> <begin> <length> <output variable>)
Returns a sublist of the given list. If <length> is 0, an empty list will be returned. If <length> is -1 or the list is smaller than <begin>+<length> then the remaining elements of the list starting at <begin> will be returned.
list(FIND <list> <value> <output variable>)
Returns the index of the element specified in the list or -1 if it wasn’t found.
list(APPEND <list> [<element> ...])
Appends elements to the list.
list(FILTER <list> <INCLUDE|EXCLUDE> REGEX <regular_expression>)
Includes or removes items from the list that match the mode’s pattern. In REGEX mode, items will be matched against the given regular expression.
For more information on regular expressions see also the string() command.
list(INSERT <list> <element_index> <element> [<element> ...])
Inserts elements to the list to the specified location.
list(POP_BACK <list> [<out-var>...])
If no variable name is given, removes exactly one element. Otherwise, assign the last element’s value to the given variable and removes it, up to the last variable name given.
list(POP_FRONT <list> [<out-var>...])
If no variable name is given, removes exactly one element. Otherwise, assign the first element’s value to the given variable and removes it, up to the last variable name given.
list(PREPEND <list> [<element> ...])
Insert elements to the 0th position in the list.
list(REMOVE_ITEM <list> <value> [<value> ...])
Removes all instances of the given items from the list.
list(REMOVE_AT <list> <index> [<index> ...])
Removes items at given indices from the list.
list(REMOVE_DUPLICATES <list>)
Removes duplicated items in the list. The relative order of items is preserved, but if duplicates are encountered, only the first instance is preserved.
list(TRANSFORM <list> <ACTION> [<SELECTOR>]
[OUTPUT_VARIABLE <output variable>])
Transforms the list by applying an action to all or, by specifying a <SELECTOR>, to the selected elements of the list, storing the result in-place or in the specified output variable.
NOTE:
<ACTION> specifies the action to apply to the elements of the list. The actions have exactly the same semantics as sub-commands of the string() command. <ACTION> must be one of the following:
APPEND, PREPEND: Append, prepend specified value to each element of the list.
list(TRANSFORM <list> <APPEND|PREPEND> <value> ...)
TOUPPER, TOLOWER: Convert each element of the list to upper, lower characters.
list(TRANSFORM <list> <TOLOWER|TOUPPER> ...)
STRIP: Remove leading and trailing spaces from each element of the list.
list(TRANSFORM <list> STRIP ...)
GENEX_STRIP: Strip any generator expressions from each element of the list.
list(TRANSFORM <list> GENEX_STRIP ...)
REPLACE: Match the regular expression as many times as possible and substitute the replacement expression for the match for each element of the list (Same semantic as REGEX REPLACE from string() command).
list(TRANSFORM <list> REPLACE <regular_expression>
<replace_expression> ...)
<SELECTOR> determines which elements of the list will be transformed. Only one type of selector can be specified at a time. When given, <SELECTOR> must be one of the following:
AT: Specify a list of indexes.
list(TRANSFORM <list> <ACTION> AT <index> [<index> ...] ...)
FOR: Specify a range with, optionally, an increment used to iterate over the range.
list(TRANSFORM <list> <ACTION> FOR <start> <stop> [<step>] ...)
REGEX: Specify a regular expression. Only elements matching the regular expression will be transformed.
list(TRANSFORM <list> <ACTION> REGEX <regular_expression> ...)
list(REVERSE <list>)
Reverses the contents of the list in-place.
list(SORT <list> [COMPARE <compare>] [CASE <case>] [ORDER <order>])
Sorts the list in-place alphabetically. Use the COMPARE keyword to select the comparison method for sorting. The <compare> option should be one of:
Use the CASE keyword to select a case sensitive or case insensitive sort mode. The <case> option should be one of:
To control the sort order, the ORDER keyword can be given. The <order> option should be one of:
Start recording a macro for later invocation as a command
macro(<name> [<arg1> ...])
<commands> endmacro()
Defines a macro named <name> that takes arguments named <arg1>, … Commands listed after macro, but before the matching endmacro(), are not executed until the macro is invoked.
Per legacy, the endmacro() command admits an optional <name> argument. If used, it must be a verbatim repeat of the argument of the opening macro command.
See the cmake_policy() command documentation for the behavior of policies inside macros.
See the Macro vs Function section below for differences between CMake macros and functions.
The macro invocation is case-insensitive. A macro defined as
macro(foo)
<commands> endmacro()
can be invoked through any of
foo() Foo() FOO() cmake_language(CALL foo)
and so on. However, it is strongly recommended to stay with the case chosen in the macro definition. Typically macros use all-lowercase names.
The cmake_language(CALL ...) command can also be used to invoke the macro.
When a macro is invoked, the commands recorded in the macro are first modified by replacing formal parameters (${arg1}, …) with the arguments passed, and then invoked as normal commands.
In addition to referencing the formal parameters you can reference the values ${ARGC} which will be set to the number of arguments passed into the function as well as ${ARGV0}, ${ARGV1}, ${ARGV2}, … which will have the actual values of the arguments passed in. This facilitates creating macros with optional arguments.
Furthermore, ${ARGV} holds the list of all arguments given to the macro and ${ARGN} holds the list of arguments past the last expected argument. Referencing to ${ARGV#} arguments beyond ${ARGC} have undefined behavior. Checking that ${ARGC} is greater than # is the only way to ensure that ${ARGV#} was passed to the function as an extra argument.
The macro command is very similar to the function() command. Nonetheless, there are a few important differences.
In a function, ARGN, ARGC, ARGV and ARGV0, ARGV1, … are true variables in the usual CMake sense. In a macro, they are not, they are string replacements much like the C preprocessor would do with a macro. This has a number of consequences, as explained in the Argument Caveats section below.
Another difference between macros and functions is the control flow. A function is executed by transferring control from the calling statement to the function body. A macro is executed as if the macro body were pasted in place of the calling statement. This has the consequence that a return() in a macro body does not just terminate execution of the macro; rather, control is returned from the scope of the macro call. To avoid confusion, it is recommended to avoid return() in macros altogether.
Unlike a function, the CMAKE_CURRENT_FUNCTION, CMAKE_CURRENT_FUNCTION_LIST_DIR, CMAKE_CURRENT_FUNCTION_LIST_FILE, CMAKE_CURRENT_FUNCTION_LIST_LINE variables are not set for a macro.
Since ARGN, ARGC, ARGV, ARGV0 etc. are not variables, you will NOT be able to use commands like
if(ARGV1) # ARGV1 is not a variable if(DEFINED ARGV2) # ARGV2 is not a variable if(ARGC GREATER 2) # ARGC is not a variable foreach(loop_var IN LISTS ARGN) # ARGN is not a variable
In the first case, you can use if(${ARGV1}). In the second and third case, the proper way to check if an optional variable was passed to the macro is to use if(${ARGC} GREATER 2). In the last case, you can use foreach(loop_var ${ARGN}) but this will skip empty arguments. If you need to include them, you can use
set(list_var "${ARGN}") foreach(loop_var IN LISTS list_var)
Note that if you have a variable with the same name in the scope from which the macro is called, using unreferenced names will use the existing variable instead of the arguments. For example:
macro(bar)
foreach(arg IN LISTS ARGN)
<commands>
endforeach() endmacro() function(foo)
bar(x y z) endfunction() foo(a b c)
Will loop over a;b;c and not over x;y;z as one might have expected. If you want true CMake variables and/or better CMake scope control you should look at the function command.
Mark cmake cached variables as advanced.
mark_as_advanced([CLEAR|FORCE] <var1> ...)
Sets the advanced/non-advanced state of the named cached variables.
An advanced variable will not be displayed in any of the cmake GUIs unless the show advanced option is on. In script mode, the advanced/non-advanced state has no effect.
If the keyword CLEAR is given then advanced variables are changed back to unadvanced. If the keyword FORCE is given then the variables are made advanced. If neither FORCE nor CLEAR is specified, new values will be marked as advanced, but if a variable already has an advanced/non-advanced state, it will not be changed.
NOTE:
Evaluate a mathematical expression.
math(EXPR <variable> "<expression>" [OUTPUT_FORMAT <format>])
Evaluates a mathematical <expression> and sets <variable> to the resulting value. The result of the expression must be representable as a 64-bit signed integer.
The mathematical expression must be given as a string (i.e. enclosed in double quotation marks). An example is "5 * (10 + 13)". Supported operators are +, -, *, /, %, |, &, ^, ~, <<, >>, and (...); they have the same meaning as in C code.
Hexadecimal numbers are recognized when prefixed with 0x, as in C code.
The result is formatted according to the option OUTPUT_FORMAT, where <format> is one of
For example
math(EXPR value "100 * 0xA" OUTPUT_FORMAT DECIMAL) # value is set to "1000" math(EXPR value "100 * 0xA" OUTPUT_FORMAT HEXADECIMAL) # value is set to "0x3e8"
Log a message.
General messages
message([<mode>] "message text" ...) Reporting checks
message(<checkState> "message text" ...)
message([<mode>] "message text" ...)
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.
The optional <mode> keyword determines the type of message, which influences the way the message is handled:
The CMake command-line tool displays STATUS to TRACE messages on stdout with the message preceded by two hyphens and a space. All other message types are sent to stderr and are not prefixed with hyphens. The CMake GUI displays all messages in its log area. The curses interface shows STATUS to TRACE messages one at a time on a status line and other messages in an interactive pop-up box. The --log-level command-line option to each of these tools can be used to control which messages will be shown. To make a log level persist between CMake runs, the CMAKE_MESSAGE_LOG_LEVEL variable can be set instead. Note that the command line option takes precedence over the cache variable.
Messages of log levels NOTICE and below will have each line preceded by the content of the CMAKE_MESSAGE_INDENT variable (converted to a single string by concatenating its list items). For STATUS to TRACE messages, this indenting content will be inserted after the hyphens.
Messages of log levels NOTICE and below can also have each line preceded with context of the form [some.context.example]. The content between the square brackets is obtained by converting the CMAKE_MESSAGE_CONTEXT list variable to a dot-separated string. The message context will always appear before any indenting content but after any automatically added leading hyphens. By default, message context is not shown, it has to be explicitly enabled by giving the cmake --log-context command-line option or by setting the CMAKE_MESSAGE_CONTEXT_SHOW variable to true. See the CMAKE_MESSAGE_CONTEXT documentation for usage examples.
CMake Warning and Error message text displays using a simple markup language. Non-indented text is formatted in line-wrapped paragraphs delimited by newlines. Indented text is considered pre-formatted.
A common pattern in CMake output is a message indicating the start of some sort of check, followed by another message reporting the result of that check. For example:
message(STATUS "Looking for someheader.h") #... do the checks, set checkSuccess with the result if(checkSuccess)
message(STATUS "Looking for someheader.h - found") else()
message(STATUS "Looking for someheader.h - not found") endif()
This can be more robustly and conveniently expressed using the CHECK_... keyword form of the message() command:
message(<checkState> "message" ...)
where <checkState> must be one of the following:
When recording a check result, the command repeats the message from the most recently started check for which no result has yet been reported, then some separator characters and then the message text provided after the CHECK_PASS or CHECK_FAIL keyword. Check messages are always reported at STATUS log level.
Checks may be nested and every CHECK_START should have exactly one matching CHECK_PASS or CHECK_FAIL. The CMAKE_MESSAGE_INDENT variable can also be used to add indenting to nested checks if desired. For example:
message(CHECK_START "Finding my things") list(APPEND CMAKE_MESSAGE_INDENT " ") unset(missingComponents) message(CHECK_START "Finding partA") # ... do check, assume we find A message(CHECK_PASS "found") message(CHECK_START "Finding partB") # ... do check, assume we don't find B list(APPEND missingComponents B) message(CHECK_FAIL "not found") list(POP_BACK CMAKE_MESSAGE_INDENT) if(missingComponents)
message(CHECK_FAIL "missing components: ${missingComponents}") else()
message(CHECK_PASS "all components found") endif()
Output from the above would appear something like the following:
-- Finding my things -- Finding partA -- Finding partA - found -- Finding partB -- Finding partB - not found -- Finding my things - missing components: B
Provide an option that the user can optionally select.
option(<variable> "<help_text>" [value])
Provides an option for the user to select as ON or OFF. If no initial <value> is provided, OFF is used. If <variable> is already set as a normal or cache variable, then the command does nothing (see policy CMP0077).
If you have options that depend on the values of other options, see the module help for CMakeDependentOption.
Return from a file, directory or function.
return()
Returns from a file, directory or function. When this command is encountered in an included file (via include() or find_package()), it causes processing of the current file to stop and control is returned to the including file. If it is encountered in a file which is not included by another file, e.g. a CMakeLists.txt, control is returned to the parent directory if there is one. If return is called in a function, control is returned to the caller of the function.
Note that a macro, unlike a function, is expanded in place and therefore cannot handle return().
Parse command-line arguments into a semicolon-separated list.
separate_arguments(<variable> <mode> <args>)
Parses a space-separated string <args> into a list of items, and stores this list in semicolon-separated standard form in <variable>.
This function is intended for parsing command-line arguments. The entire command line must be passed as one string in the argument <args>.
The exact parsing rules depend on the operating system. They are specified by the <mode> argument which must be one of the following keywords:
separate_arguments(<var>)
Convert the value of <var> to a semi-colon separated list. All spaces are replaced with ‘;’. This helps with generating command lines.
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.
Signatures of this command that specify a <value>... placeholder expect zero or more arguments. Multiple arguments will be joined as a semicolon-separated list to form the actual variable value to be set. Zero arguments will cause normal variables to be unset. See the unset() command to unset variables explicitly.
set(<variable> <value>... [PARENT_SCOPE])
Sets the given <variable> in the current function or directory scope.
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. This command will set the value of a variable into the parent directory or calling function (whichever is applicable to the case at hand). The previous state of the variable’s value stays the same in the current scope (e.g., if it was undefined before, it is still undefined and if it had a value, it is still that value).
set(<variable> <value>... CACHE <type> <docstring> [FORCE])
Sets the given cache <variable> (cache entry). Since cache entries are meant to provide user-settable values this does not overwrite existing cache entries by default. Use the FORCE option to overwrite existing entries.
The <type> must be specified as one of:
The <docstring> must be specified as a line of text providing a quick summary of the option for presentation to cmake-gui(1) users.
If the cache entry does not exist prior to the call or the FORCE option is given then the cache entry will be set to the given value. Furthermore, any normal variable binding in the current scope will be removed to expose the newly cached value to any immediately following evaluation.
It is possible for the cache entry to exist prior to the call but have no type set if it was created on the cmake(1) command line by a user through the -D<var>=<value> option without specifying a type. In this case the set command will add the type. Furthermore, if the <type> is PATH or FILEPATH and the <value> provided on the command line is a relative path, then the set command will treat the path as relative to the current working directory and convert it to an absolute path.
set(ENV{<variable>} [<value>])
Sets an Environment Variable to the given value. Subsequent calls of $ENV{<variable>} will return this new value.
This command affects only the current CMake process, not the process from which CMake was called, nor the system environment at large, nor the environment of subsequent build or test processes.
If no argument is given after ENV{<variable>} or if <value> is an empty string, then this command will clear any existing value of the environment variable.
Arguments after <value> are ignored. If extra arguments are found, then an author warning is issued.
Set properties of the current directory and subdirectories.
set_directory_properties(PROPERTIES prop1 value1 [prop2 value2] ...)
Sets properties of the current directory and its subdirectories in key-value pairs.
See also the set_property(DIRECTORY) command.
See Directory Properties for the list of properties known to CMake and their individual documentation for the behavior of each property.
Set a named property in a given scope.
set_property(<GLOBAL |
DIRECTORY [<dir>] |
TARGET [<target1> ...] |
SOURCE [<src1> ...]
[DIRECTORY <dirs> ...] |
[TARGET_DIRECTORY <targets> ...]
INSTALL [<file1> ...] |
TEST [<test1> ...] |
CACHE [<entry1> ...] >
[APPEND] [APPEND_STRING]
PROPERTY <name> [<value1> ...])
Sets one property on zero or more objects of a scope.
The first argument determines the scope in which the property is set. It must be one of the following:
See also the set_source_files_properties() command.
Both the property key and value may use generator expressions. Specific properties may apply to installed files and/or directories.
Path components have to be separated by forward slashes, must be normalized and are case sensitive.
To reference the installation prefix itself with a relative path use ..
Currently installed file properties are only defined for the WIX generator where the given paths are relative to the installation prefix.
The required PROPERTY option is immediately followed by the name of the property to set. Remaining arguments are used to compose the property value in the form of a semicolon-separated list.
If the APPEND option is given the list is appended to any existing property value (except that empty values are ignored and not appended). If the APPEND_STRING option is given the string is appended to any existing property value as string, i.e. it results in a longer string and not a list of strings. When using APPEND or APPEND_STRING with a property defined to support INHERITED behavior (see define_property()), no inheriting occurs when finding the initial value to append to. If the property is not already directly set in the nominated scope, the command will behave as though APPEND or APPEND_STRING had not been given.
See the cmake-properties(7) manual for a list of properties in each scope.
Set the given variable to the name of the computer.
site_name(variable)
String operations.
Search and Replace
string(FIND <string> <substring> <out-var> [...])
string(REPLACE <match-string> <replace-string> <out-var> <input>...)
string(REGEX MATCH <match-regex> <out-var> <input>...)
string(REGEX MATCHALL <match-regex> <out-var> <input>...)
string(REGEX REPLACE <match-regex> <replace-expr> <out-var> <input>...) Manipulation
string(APPEND <string-var> [<input>...])
string(PREPEND <string-var> [<input>...])
string(CONCAT <out-var> [<input>...])
string(JOIN <glue> <out-var> [<input>...])
string(TOLOWER <string> <out-var>)
string(TOUPPER <string> <out-var>)
string(LENGTH <string> <out-var>)
string(SUBSTRING <string> <begin> <length> <out-var>)
string(STRIP <string> <out-var>)
string(GENEX_STRIP <string> <out-var>)
string(REPEAT <string> <count> <out-var>) Comparison
string(COMPARE <op> <string1> <string2> <out-var>) Hashing
string(<HASH> <out-var> <input>) Generation
string(ASCII <number>... <out-var>)
string(HEX <string> <out-var>)
string(CONFIGURE <string> <out-var> [...])
string(MAKE_C_IDENTIFIER <string> <out-var>)
string(RANDOM [<option>...] <out-var>)
string(TIMESTAMP <out-var> [<format string>] [UTC])
string(UUID <out-var> ...)
string(FIND <string> <substring> <output_variable> [REVERSE])
Return the position where the given <substring> was found in the supplied <string>. If the REVERSE flag was used, the command will search for the position of the last occurrence of the specified <substring>. If the <substring> is not found, a position of -1 is returned.
The string(FIND) subcommand treats all strings as ASCII-only characters. The index stored in <output_variable> will also be counted in bytes, so strings containing multi-byte characters may lead to unexpected results.
string(REPLACE <match_string>
<replace_string> <output_variable>
<input> [<input>...])
Replace all occurrences of <match_string> in the <input> with <replace_string> and store the result in the <output_variable>.
string(REGEX MATCH <regular_expression>
<output_variable> <input> [<input>...])
Match the <regular_expression> once and store the match in the <output_variable>. All <input> arguments are concatenated before matching. Regular expressions are specified in the subsection just below.
string(REGEX MATCHALL <regular_expression>
<output_variable> <input> [<input>...])
Match the <regular_expression> as many times as possible and store the matches in the <output_variable> as a list. All <input> arguments are concatenated before matching.
string(REGEX REPLACE <regular_expression>
<replacement_expression> <output_variable>
<input> [<input>...])
Match the <regular_expression> as many times as possible and substitute the <replacement_expression> for the match in the output. All <input> arguments are concatenated before matching.
The <replacement_expression> may refer to parenthesis-delimited subexpressions of the match using \1, \2, …, \9. Note that two backslashes (\\1) are required in CMake code to get a backslash through argument parsing.
The following characters have special meaning in regular expressions:
*, + and ? have higher precedence than concatenation. | has lower precedence than concatenation. This means that the regular expression ^ab+d$ matches abbd but not ababd, and the regular expression ^(ab|cd)$ matches ab but not abd.
CMake language Escape Sequences such as \t, \r, \n, and \\ may be used to construct literal tabs, carriage returns, newlines, and backslashes (respectively) to pass in a regex. For example:
string(APPEND <string_variable> [<input>...])
Append all the <input> arguments to the string.
string(PREPEND <string_variable> [<input>...])
Prepend all the <input> arguments to the string.
string(CONCAT <output_variable> [<input>...])
Concatenate all the <input> arguments together and store the result in the named <output_variable>.
string(JOIN <glue> <output_variable> [<input>...])
Join all the <input> arguments together using the <glue> string and store the result in the named <output_variable>.
To join a list’s elements, prefer to use the JOIN operator from the list() command. This allows for the elements to have special characters like ; in them.
string(TOLOWER <string> <output_variable>)
Convert <string> to lower characters.
string(TOUPPER <string> <output_variable>)
Convert <string> to upper characters.
string(LENGTH <string> <output_variable>)
Store in an <output_variable> a given string’s length in bytes. Note that this means if <string> contains multi-byte characters, the result stored in <output_variable> will not be the number of characters.
string(SUBSTRING <string> <begin> <length> <output_variable>)
Store in an <output_variable> a substring of a given <string>. If <length> is -1 the remainder of the string starting at <begin> will be returned. If <string> is shorter than <length> then the end of the string is used instead.
Both <begin> and <length> are counted in bytes, so care must be exercised if <string> could contain multi-byte characters.
NOTE:
string(STRIP <string> <output_variable>)
Store in an <output_variable> a substring of a given <string> with leading and trailing spaces removed.
string(GENEX_STRIP <string> <output_variable>)
Strip any generator expressions from the input <string> and store the result in the <output_variable>.
string(REPEAT <string> <count> <output_variable>)
Produce the output string as the input <string> repeated <count> times.
string(COMPARE LESS <string1> <string2> <output_variable>) string(COMPARE GREATER <string1> <string2> <output_variable>) string(COMPARE EQUAL <string1> <string2> <output_variable>) string(COMPARE NOTEQUAL <string1> <string2> <output_variable>) string(COMPARE LESS_EQUAL <string1> <string2> <output_variable>) string(COMPARE GREATER_EQUAL <string1> <string2> <output_variable>)
Compare the strings and store true or false in the <output_variable>.
string(<HASH> <output_variable> <input>)
Compute a cryptographic hash of the <input> string. The supported <HASH> algorithm names are:
string(ASCII <number> [<number> ...] <output_variable>)
Convert all numbers into corresponding ASCII characters.
string(HEX <string> <output_variable>)
Convert each byte in the input <string> to its hexadecimal representation and store the concatenated hex digits in the <output_variable>. Letters in the output (a through f) are in lowercase.
string(CONFIGURE <string> <output_variable>
[@ONLY] [ESCAPE_QUOTES])
Transform a <string> like configure_file() transforms a file.
string(MAKE_C_IDENTIFIER <string> <output_variable>)
Convert each non-alphanumeric character in the input <string> to an underscore and store the result in the <output_variable>. If the first character of the <string> is a digit, an underscore will also be prepended to the result.
string(RANDOM [LENGTH <length>] [ALPHABET <alphabet>]
[RANDOM_SEED <seed>] <output_variable>)
Return a random string of given <length> consisting of characters from the given <alphabet>. Default length is 5 characters and default alphabet is all numbers and upper and lower case letters. If an integer RANDOM_SEED is given, its value will be used to seed the random number generator.
string(TIMESTAMP <output_variable> [<format_string>] [UTC])
Write a string representation of the current date and/or time to the <output_variable>.
If the command is unable to obtain a timestamp, the <output_variable> will be set to the empty string "".
The optional UTC flag requests the current date/time representation to be in Coordinated Universal Time (UTC) rather than local time.
The optional <format_string> may contain the following format specifiers:
%% A literal percent sign (%). %d The day of the current month (01-31). %H The hour on a 24-hour clock (00-23). %I The hour on a 12-hour clock (01-12). %j The day of the current year (001-366). %m The month of the current year (01-12). %b Abbreviated month name (e.g. Oct). %B Full month name (e.g. October). %M The minute of the current hour (00-59). %s Seconds since midnight (UTC) 1-Jan-1970 (UNIX time). %S The second of the current minute.
60 represents a leap second. (00-60) %U The week number of the current year (00-53). %w The day of the current week. 0 is Sunday. (0-6) %a Abbreviated weekday name (e.g. Fri). %A Full weekday name (e.g. Friday). %y The last two digits of the current year (00-99) %Y The current year.
Unknown format specifiers will be ignored and copied to the output as-is.
If no explicit <format_string> is given, it will default to:
%Y-%m-%dT%H:%M:%S for local time. %Y-%m-%dT%H:%M:%SZ for UTC.
NOTE:
string(UUID <output_variable> NAMESPACE <namespace> NAME <name>
TYPE <MD5|SHA1> [UPPER])
Create a universally unique identifier (aka GUID) as per RFC4122 based on the hash of the combined values of <namespace> (which itself has to be a valid UUID) and <name>. The hash algorithm can be either MD5 (Version 3 UUID) or SHA1 (Version 5 UUID). A UUID has the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where each x represents a lower case hexadecimal character. Where required, an uppercase representation can be requested with the optional UPPER flag.
Unset a variable, cache variable, or environment variable.
unset(<variable> [CACHE | PARENT_SCOPE])
Removes a normal variable from the current scope, causing it to become undefined. If CACHE is present, then a cache variable is removed instead of a normal variable. Note that when evaluating Variable References of the form ${VAR}, CMake first searches for a normal variable with that name. If no such normal variable exists, CMake will then search for a cache entry with that name. Because of this unsetting a normal variable can expose a cache variable that was previously hidden. To force a variable reference of the form ${VAR} to return an empty string, use set(<variable> ""), which clears the normal variable but leaves it defined.
If PARENT_SCOPE is present then the variable is removed from the scope above the current scope. See the same option in the set() command for further details.
unset(ENV{<variable>})
Removes <variable> from the currently available Environment Variables. Subsequent calls of $ENV{<variable>} will return the empty string.
This command affects only the current CMake process, not the process from which CMake was called, nor the system environment at large, nor the environment of subsequent build or test processes.
Watch the CMake variable for change.
variable_watch(<variable> [<command>])
If the specified <variable> changes, a message will be printed to inform about the change.
Additionally, if <command> is given, this command will be executed. The command will receive the following arguments: COMMAND(<variable> <access> <value> <current_list_file> <stack>)
Evaluate a group of commands while a condition is true
while(<condition>)
<commands> endwhile()
All commands between while and the matching endwhile() are recorded without being invoked. Once the endwhile() is evaluated, the recorded list of commands is invoked as long as the <condition> is true.
The <condition> has the same syntax and is evaluated using the same logic as described at length for the if() command.
The commands break() and continue() provide means to escape from the normal control flow.
Per legacy, the endwhile() command admits an optional <condition> argument. If used, it must be a verbatim repeat of the argument of the opening while command.
These commands are available only in CMake projects.
Add preprocessor definitions to the compilation of source files.
add_compile_definitions(<definition> ...)
Adds preprocessor definitions to the compiler command line.
The preprocessor definitions are added to the COMPILE_DEFINITIONS directory property for the current CMakeLists file. They are also added to the COMPILE_DEFINITIONS target property for each target in the current CMakeLists file.
Definitions are specified using the syntax VAR or VAR=value. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values).
Arguments to add_compile_definitions may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
Add options to the compilation of source files.
add_compile_options(<option> ...)
Adds options to the COMPILE_OPTIONS directory property. These options are used when compiling targets from the current directory and below.
Arguments to add_compile_options may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
The final set of compile or link options used for a target is constructed by accumulating options from the current target and the usage requirements of its dependencies. The set of options is de-duplicated to avoid repetition. While beneficial for individual options, the de-duplication step can break up option groups. For example, -D A -D B becomes -D A B. One may specify a group of options using shell-like quoting along with a SHELL: prefix. The SHELL: prefix is dropped, and the rest of the option string is parsed using the separate_arguments() UNIX_COMMAND mode. For example, "SHELL:-D A" "SHELL:-D B" becomes -D A -D B.
Since different compilers support different options, a typical use of this command is in a compiler-specific conditional clause:
if (MSVC)
# warning level 4 and all warnings as errors
add_compile_options(/W4 /WX) else()
# lots of warnings and all warnings as errors
add_compile_options(-Wall -Wextra -pedantic -Werror) endif()
This command can be used to add any options. However, for adding preprocessor definitions and include directories it is recommended to use the more specific commands add_compile_definitions() and include_directories().
The command target_compile_options() adds target-specific options.
The source file property COMPILE_OPTIONS adds options to one source file.
Add a custom build rule to the generated build system.
There are two main signatures for add_custom_command.
The first signature is for adding a custom command to produce an output:
add_custom_command(OUTPUT output1 [output2 ...]
COMMAND command1 [ARGS] [args1...]
[COMMAND command2 [ARGS] [args2...] ...]
[MAIN_DEPENDENCY depend]
[DEPENDS [depends...]]
[BYPRODUCTS [files...]]
[IMPLICIT_DEPENDS <lang1> depend1
[<lang2> depend2] ...]
[WORKING_DIRECTORY dir]
[COMMENT comment]
[DEPFILE depfile]
[JOB_POOL job_pool]
[VERBATIM] [APPEND] [USES_TERMINAL]
[COMMAND_EXPAND_LISTS])
This defines a command to generate specified OUTPUT file(s). A target created in the same directory (CMakeLists.txt file) that specifies any output of the custom command as a source file is given a rule to generate the file using the command at build time. Do not list the output in more than one independent target that may build in parallel or the two instances of the rule may conflict (instead use the add_custom_target() command to drive the command and make the other targets depend on that one). In makefile terms this creates a new target in the following form:
OUTPUT: MAIN_DEPENDENCY DEPENDS
COMMAND
The options are:
Explicit specification of byproducts is supported by the Ninja generator to tell the ninja build tool how to regenerate byproducts when they are missing. It is also useful when other build rules (e.g. custom commands) depend on the byproducts. Ninja requires a build rule for any generated file on which another rule depends even if there are order-only dependencies to ensure the byproducts will be available before their dependents build.
The Makefile Generators will remove BYPRODUCTS and other GENERATED files during make clean.
If COMMAND specifies an executable target name (created by the add_executable() command), it will automatically be replaced by the location of the executable created at build time if either of the following is true:
If neither of the above conditions are met, it is assumed that the command name is a program to be found on the PATH at build time.
Arguments to COMMAND may use generator expressions. Use the TARGET_FILE generator expression to refer to the location of a target later in the command line (i.e. as a command argument rather than as the command to execute).
Whenever a target is used as a command to execute or is mentioned in a generator expression as a command argument, a target-level dependency will be added automatically so that the mentioned target will be built before any target using this custom command. However this does NOT add a file-level dependency that would cause the custom command to re-run whenever the executable is recompiled. List target names with the DEPENDS option to add such file-level dependencies.
If any dependency is an OUTPUT of another custom command in the same directory (CMakeLists.txt file), CMake automatically brings the other custom command into the target in which this command is built. A target-level dependency is added if any dependency is listed as BYPRODUCTS of a target or any of its build events in the same directory to ensure the byproducts will be available.
If DEPENDS is not specified, the command will run whenever the OUTPUT is missing; if the command does not actually create the OUTPUT, the rule will always run.
Arguments to DEPENDS may use generator expressions.
Arguments to WORKING_DIRECTORY may use generator expressions.
The second signature adds a custom command to a target such as a library or executable. This is useful for performing an operation before or after building the target. The command becomes part of the target and will only execute when the target itself is built. If the target is already built, the command will not execute.
add_custom_command(TARGET <target>
PRE_BUILD | PRE_LINK | POST_BUILD
COMMAND command1 [ARGS] [args1...]
[COMMAND command2 [ARGS] [args2...] ...]
[BYPRODUCTS [files...]]
[WORKING_DIRECTORY dir]
[COMMENT comment]
[VERBATIM] [USES_TERMINAL]
[COMMAND_EXPAND_LISTS])
This defines a new command that will be associated with building the specified <target>. The <target> must be defined in the current directory; targets defined in other directories may not be specified.
When the command will happen is determined by which of the following is specified:
NOTE:
This allows to add individual build events for every configuration.
Add a target with no output so it will always be built.
add_custom_target(Name [ALL] [command1 [args1...]]
[COMMAND command2 [args2...] ...]
[DEPENDS depend depend depend ... ]
[BYPRODUCTS [files...]]
[WORKING_DIRECTORY dir]
[COMMENT comment]
[JOB_POOL job_pool]
[VERBATIM] [USES_TERMINAL]
[COMMAND_EXPAND_LISTS]
[SOURCES src1 [src2...]])
Adds a target with the given name that executes the given commands. The target has no output file and is always considered out of date even if the commands try to create a file with the name of the target. Use the add_custom_command() command to generate a file with dependencies. By default nothing depends on the custom target. Use the add_dependencies() command to add dependencies to or from other targets.
The options are:
Explicit specification of byproducts is supported by the Ninja generator to tell the ninja build tool how to regenerate byproducts when they are missing. It is also useful when other build rules (e.g. custom commands) depend on the byproducts. Ninja requires a build rule for any generated file on which another rule depends even if there are order-only dependencies to ensure the byproducts will be available before their dependents build.
The Makefile Generators will remove BYPRODUCTS and other GENERATED files during make clean.
If COMMAND specifies an executable target name (created by the add_executable() command), it will automatically be replaced by the location of the executable created at build time if either of the following is true:
If neither of the above conditions are met, it is assumed that the command name is a program to be found on the PATH at build time.
Arguments to COMMAND may use generator expressions. Use the TARGET_FILE generator expression to refer to the location of a target later in the command line (i.e. as a command argument rather than as the command to execute).
Whenever a target is used as a command to execute or is mentioned in a generator expression as a command argument, a target-level dependency will be added automatically so that the mentioned target will be built before this custom target.
The command and arguments are optional and if not specified an empty target will be created.
Use the add_dependencies() command to add dependencies on other targets.
Arguments to WORKING_DIRECTORY may use generator expressions.
Add -D define flags to the compilation of source files.
add_definitions(-DFOO -DBAR ...)
Adds definitions to the compiler command line for targets in the current directory, whether added before or after this command is invoked, and for the ones in sub-directories added after. This command can be used to add any flags, but it is intended to add preprocessor definitions.
NOTE:
Flags beginning in -D or /D that look like preprocessor definitions are automatically added to the COMPILE_DEFINITIONS directory property for the current directory. Definitions with non-trivial values may be left in the set of flags instead of being converted for reasons of backwards compatibility. See documentation of the directory, target, source file COMPILE_DEFINITIONS properties for details on adding preprocessor definitions to specific scopes and configurations.
See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
Add a dependency between top-level targets.
add_dependencies(<target> [<target-dependency>]...)
Makes a top-level <target> depend on other top-level targets to ensure that they build before <target> does. A top-level target is one created by one of the add_executable(), add_library(), or add_custom_target() commands (but not targets generated by CMake like install).
Dependencies added to an imported target or an interface library are followed transitively in its place since the target itself does not build.
See the DEPENDS option of add_custom_target() and add_custom_command() commands for adding file-level dependencies in custom rules. See the OBJECT_DEPENDS source file property to add file-level dependencies to object files.
Add an executable to the project using the specified source files.
add_executable(<name> [WIN32] [MACOSX_BUNDLE]
[EXCLUDE_FROM_ALL]
[source1] [source2 ...])
Adds an executable target called <name> to be built from the source files listed in the command invocation. (The source files can be omitted here if they are added later using target_sources().) 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>).
By default the executable file will be created in the build tree directory corresponding to the source tree directory in which the command was invoked. See documentation of the RUNTIME_OUTPUT_DIRECTORY target property to change this location. See documentation of the OUTPUT_NAME target property to change the <name> part of the final file name.
If WIN32 is given the property WIN32_EXECUTABLE will be set on the target created. See documentation of that target property for details.
If MACOSX_BUNDLE is given the corresponding property will be set on the created target. See documentation of the MACOSX_BUNDLE target property for details.
If EXCLUDE_FROM_ALL is given the corresponding property will be set on the created target. See documentation of the EXCLUDE_FROM_ALL target property for details.
Source arguments to add_executable may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
See also HEADER_FILE_ONLY on what to do if some sources are pre-processed, and you want to have the original sources reachable from within IDE.
add_executable(<name> IMPORTED [GLOBAL])
An IMPORTED executable target references an executable file located outside the project. No rules are generated to build it, and the IMPORTED target property is True. The target name has scope in the directory in which it is created and below, but the GLOBAL option extends visibility. It may be referenced like any target built within the project. IMPORTED executables are useful for convenient reference from commands like add_custom_command(). Details about the imported executable are specified by setting properties whose names begin in IMPORTED_. The most important such property is IMPORTED_LOCATION (and its per-configuration version IMPORTED_LOCATION_<CONFIG>) which specifies the location of the main executable file on disk. See documentation of the IMPORTED_* properties for more information.
add_executable(<name> ALIAS <target>)
Creates an Alias Target, such that <name> can be used to refer to <target> in subsequent commands. The <name> does not appear in the generated buildsystem as a make target. The <target> may not be an ALIAS.
An ALIAS to a non-GLOBAL Imported Target has scope in the directory in which the alias is created and below. The ALIAS_GLOBAL target property can be used to check if the alias is global or not.
ALIAS targets can be used as targets to read properties from, executables for custom commands and custom targets. They can also be tested for existence with the regular if(TARGET) subcommand. The <name> may not be used to modify properties of <target>, that is, it may not be used as the operand of set_property(), set_target_properties(), target_link_libraries() etc. An ALIAS target may not be installed or exported.
Add a library to the project using the specified source files.
add_library(<name> [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
[source1] [source2 ...])
Adds a library target called <name> to be built from the source files listed in the command invocation. (The source files can be omitted here if they are added later using target_sources().) 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).
STATIC, SHARED, or MODULE may be given to specify the type of library to be created. STATIC libraries are archives of object files for use when linking other targets. SHARED libraries are linked dynamically and loaded at runtime. MODULE libraries are plugins that are not linked into other targets but may be loaded dynamically at runtime using dlopen-like functionality. If no type is given explicitly the type is STATIC or SHARED based on whether the current value of the variable BUILD_SHARED_LIBS is ON. For SHARED and MODULE libraries the POSITION_INDEPENDENT_CODE target property is set to ON automatically. A SHARED or STATIC library may be marked with the FRAMEWORK target property to create an macOS Framework.
If a library does not export any symbols, it must not be declared as a SHARED library. For example, a Windows resource DLL or a managed C++/CLI DLL that exports no unmanaged symbols would need to be a MODULE library. This is because CMake expects a SHARED library to always have an associated import library on Windows.
By default the library file will be created in the build tree directory corresponding to the source tree directory in which the command was invoked. See documentation of the ARCHIVE_OUTPUT_DIRECTORY, LIBRARY_OUTPUT_DIRECTORY, and RUNTIME_OUTPUT_DIRECTORY target properties to change this location. See documentation of the OUTPUT_NAME target property to change the <name> part of the final file name.
If EXCLUDE_FROM_ALL is given the corresponding property will be set on the created target. See documentation of the EXCLUDE_FROM_ALL target property for details.
Source arguments to add_library may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
See also HEADER_FILE_ONLY on what to do if some sources are pre-processed, and you want to have the original sources reachable from within IDE.
add_library(<name> <SHARED|STATIC|MODULE|OBJECT|UNKNOWN> IMPORTED
[GLOBAL])
An IMPORTED library target references a library file located outside the project. No rules are generated to build it, and the IMPORTED target property is True. The target name has scope in the directory in which it is created and below, but the GLOBAL option extends visibility. It may be referenced like any target built within the project. IMPORTED libraries are useful for convenient reference from commands like target_link_libraries(). Details about the imported library are specified by setting properties whose names begin in IMPORTED_ and INTERFACE_.
The most important properties are:
See documentation of the IMPORTED_* and INTERFACE_* properties for more information.
An UNKNOWN library type is typically only used in the implementation of Find Modules. It allows the path to an imported library (often found using the find_library() command) to be used without having to know what type of library it is. This is especially useful on Windows where a static library and a DLL’s import library both have the same file extension.
add_library(<name> OBJECT <src>...)
Creates an Object Library. An object library compiles source files but does not archive or link their object files into a library. Instead other targets created by add_library() or add_executable() may reference the objects using an expression of the form $<TARGET_OBJECTS:objlib> as a source, where objlib is the object library name. For example:
add_library(... $<TARGET_OBJECTS:objlib> ...) add_executable(... $<TARGET_OBJECTS:objlib> ...)
will include objlib’s object files in a library and an executable along with those compiled from their own sources. Object libraries may contain only sources that compile, header files, and other files that would not affect linking of a normal library (e.g. .txt). They may contain custom commands generating such sources, but not PRE_BUILD, PRE_LINK, or POST_BUILD commands. Some native build systems (such as Xcode) may not like targets that have only object files, so consider adding at least one real source file to any target that references $<TARGET_OBJECTS:objlib>.
add_library(<name> ALIAS <target>)
Creates an Alias Target, such that <name> can be used to refer to <target> in subsequent commands. The <name> does not appear in the generated buildsystem as a make target. The <target> may not be an ALIAS.
An ALIAS to a non-GLOBAL Imported Target has scope in the directory in which the alias is created and below. The ALIAS_GLOBAL target property can be used to check if the alias is global or not.
ALIAS targets can be used as linkable targets and as targets to read properties from. They can also be tested for existence with the regular if(TARGET) subcommand. The <name> may not be used to modify properties of <target>, that is, it may not be used as the operand of set_property(), set_target_properties(), target_link_libraries() etc. An ALIAS target may not be installed or exported.
add_library(<name> INTERFACE [IMPORTED [GLOBAL]])
Creates an Interface Library. An INTERFACE library target does not directly create build output, though it may have properties set on it and it may be installed, exported and imported. Typically the INTERFACE_* properties are populated on the interface target using the commands:
and then it is used as an argument to target_link_libraries() like any other target.
An INTERFACE Imported Target may also be created with this signature. An IMPORTED library target references a library defined outside the project. The target name has scope in the directory in which it is created and below, but the GLOBAL option extends visibility. It may be referenced like any target built within the project. IMPORTED libraries are useful for convenient reference from commands like target_link_libraries().
Add options to the link step for executable, shared library or module library targets in the current directory and below that are added after this command is invoked.
add_link_options(<option> ...)
This command can be used to add any link options, but alternative commands exist to add libraries (target_link_libraries() or link_libraries()). See documentation of the directory and target LINK_OPTIONS properties.
NOTE:
Arguments to add_link_options may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
When a device link step is involved, which is controlled by CUDA_SEPARABLE_COMPILATION and CUDA_RESOLVE_DEVICE_SYMBOLS properties and policy CMP0105, the raw options will be delivered to the host and device link steps (wrapped in -Xcompiler or equivalent for device link). Options wrapped with $<DEVICE_LINK:...> generator expression will be used only for the device link step. Options wrapped with $<HOST_LINK:...> generator expression will be used only for the host link step.
The final set of compile or link options used for a target is constructed by accumulating options from the current target and the usage requirements of its dependencies. The set of options is de-duplicated to avoid repetition. While beneficial for individual options, the de-duplication step can break up option groups. For example, -D A -D B becomes -D A B. One may specify a group of options using shell-like quoting along with a SHELL: prefix. The SHELL: prefix is dropped, and the rest of the option string is parsed using the separate_arguments() UNIX_COMMAND mode. For example, "SHELL:-D A" "SHELL:-D B" becomes -D A -D B.
To pass options to the linker tool, each compiler driver has its own syntax. The LINKER: prefix and , separator can be used to specify, in a portable way, options to pass to the linker tool. LINKER: is replaced by the appropriate driver option and , by the appropriate driver separator. The driver prefix and driver separator are given by the values of the CMAKE_<LANG>_LINKER_WRAPPER_FLAG and CMAKE_<LANG>_LINKER_WRAPPER_FLAG_SEP variables.
For example, "LINKER:-z,defs" becomes -Xlinker -z -Xlinker defs for Clang and -Wl,-z,defs for GNU GCC.
The LINKER: prefix can be specified as part of a SHELL: prefix expression.
The LINKER: prefix supports, as an alternative syntax, specification of arguments using the SHELL: prefix and space as separator. The previous example then becomes "LINKER:SHELL:-z defs".
NOTE:
Add a subdirectory to the build.
add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL])
Adds a subdirectory to the build. The source_dir specifies the directory in which the source CMakeLists.txt and code files are located. If it is a relative path it will be evaluated with respect to the current directory (the typical usage), but it may also be an absolute path. The binary_dir specifies the directory in which to place the output files. If it is a relative path it will be evaluated with respect to the current output directory, but it may also be an absolute path. If binary_dir is not specified, the value of source_dir, before expanding any relative path, will be used (the typical usage). The CMakeLists.txt file in the specified source directory will be processed immediately by CMake before processing in the current input file continues beyond this command.
If the EXCLUDE_FROM_ALL argument is provided then targets in the subdirectory will not be included in the ALL target of the parent directory by default, and will be excluded from IDE project files. Users must explicitly build targets in the subdirectory. This is meant for use when the subdirectory contains a separate part of the project that is useful but not necessary, such as a set of examples. Typically the subdirectory should contain its own project() command invocation so that a full build system will be generated in the subdirectory (such as a VS IDE solution file). Note that inter-target dependencies supersede this exclusion. If a target built by the parent project depends on a target in the subdirectory, the dependee target will be included in the parent project build system to satisfy the dependency.
Add a test to the project to be run by ctest(1).
add_test(NAME <name> COMMAND <command> [<arg>...]
[CONFIGURATIONS <config>...]
[WORKING_DIRECTORY <dir>]
[COMMAND_EXPAND_LISTS])
Adds a test called <name>. The test name may not contain spaces, quotes, or other characters special in CMake syntax. The options are:
The given test command is expected to exit with code 0 to pass and non-zero to fail, or vice-versa if the WILL_FAIL test property is set. Any output written to stdout or stderr will be captured by ctest(1) but does not affect the pass/fail status unless the PASS_REGULAR_EXPRESSION, FAIL_REGULAR_EXPRESSION or SKIP_REGULAR_EXPRESSION test property is used.
The COMMAND and WORKING_DIRECTORY options may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions.
Example usage:
add_test(NAME mytest
COMMAND testDriver --config $<CONFIGURATION>
--exe $<TARGET_FILE:myexe>)
This creates a test mytest whose command runs a testDriver tool passing the configuration name and the full path to the executable file produced by target myexe.
NOTE:
----
add_test(<name> <command> [<arg>...])
Add a test called <name> with the given command-line. Unlike the above NAME signature no transformation is performed on the command-line to support target names or generator expressions.
Find all source files in a directory.
aux_source_directory(<dir> <variable>)
Collects the names of all the source files in the specified directory and stores the list in the <variable> provided. This command is intended to be used by projects that use explicit template instantiation. Template instantiation files can be stored in a Templates subdirectory and collected automatically using this command to avoid manually listing all instantiations.
It is tempting to use this command to avoid writing the list of source files for a library or executable target. While this seems to work, there is no way for CMake to generate a build system that knows when a new source file has been added. Normally the generated build system knows when it needs to rerun CMake because the CMakeLists.txt file is modified to add a new source. When the source is just added to the directory without modifying this file, one would have to manually rerun CMake to generate a build system incorporating the new file.
Get a command line to build the current project. This is mainly intended for internal use by the CTest module.
build_command(<variable>
[CONFIGURATION <config>]
[TARGET <target>]
[PROJECT_NAME <projname>] # legacy, causes warning
)
Sets the given <variable> to a command-line string of the form:
<cmake> --build . [--config <config>] [--target <target>...] [-- -i]
where <cmake> is the location of the cmake(1) command-line tool, and <config> and <target> are the values provided to the CONFIGURATION and TARGET options, if any. The trailing -- -i option is added for Makefile Generators if policy CMP0061 is not set to NEW.
When invoked, this cmake --build command line will launch the underlying build system tool.
build_command(<cachevariable> <makecommand>)
This second signature is deprecated, but still available for backwards compatibility. Use the first signature instead.
It sets the given <cachevariable> to a command-line string as above but without the --target option. The <makecommand> is ignored but should be the full path to devenv, nmake, make or one of the end user build tools for legacy invocations.
NOTE:
Create a test driver and source list for building test programs.
create_test_sourcelist(sourceListName driverName
test1 test2 test3
EXTRA_INCLUDE include.h
FUNCTION function)
A test driver is a program that links together many small tests into a single executable. This is useful when building static executables with large libraries to shrink the total required size. The list of source files needed to build the test driver will be in sourceListName. driverName is the name of the test driver program. The rest of the arguments consist of a list of test source files, can be semicolon separated. Each test source file should have a function in it that is the same name as the file with no extension (foo.cxx should have int foo(int, char*[]);) driverName will be able to call each of the tests by name on the command line. If EXTRA_INCLUDE is specified, then the next argument is included into the generated file. If FUNCTION is specified, then the next argument is taken as a function name that is passed a pointer to ac and av. This can be used to add extra command line processing to each test. The CMAKE_TESTDRIVER_BEFORE_TESTMAIN cmake variable can be set to have code that will be placed directly before calling the test main function. CMAKE_TESTDRIVER_AFTER_TESTMAIN can be set to have code that will be placed directly after the call to the test main function.
Define and document custom properties.
define_property(<GLOBAL | DIRECTORY | TARGET | SOURCE |
TEST | VARIABLE | CACHED_VARIABLE>
PROPERTY <name> [INHERITED]
BRIEF_DOCS <brief-doc> [docs...]
FULL_DOCS <full-doc> [docs...])
Defines one property in a scope for use with the set_property() and get_property() commands. This is primarily useful to associate documentation with property names that may be retrieved with the get_property() command. The first argument determines the kind of scope in which the property should be used. It must be one of the following:
GLOBAL = associated with the global namespace DIRECTORY = associated with one directory TARGET = associated with one target SOURCE = associated with one source file TEST = associated with a test named with add_test VARIABLE = documents a CMake language variable CACHED_VARIABLE = documents a CMake cache variable
Note that unlike set_property() and get_property() no actual scope needs to be given; only the kind of scope is important.
The required PROPERTY option is immediately followed by the name of the property being defined.
If the INHERITED option is given, then the get_property() command will chain up to the next higher scope when the requested property is not set in the scope given to the command.
Note that this scope chaining behavior only applies to calls to get_property(), get_directory_property(), get_target_property(), get_source_file_property() and get_test_property(). There is no inheriting behavior when setting properties, so using APPEND or APPEND_STRING with the set_property() command will not consider inherited values when working out the contents to append to.
The BRIEF_DOCS and FULL_DOCS options are followed by strings to be associated with the property as its brief and full documentation. Corresponding options to the get_property() command will retrieve the documentation.
Enable a language (CXX/C/OBJC/OBJCXX/Fortran/etc)
enable_language(<lang> [OPTIONAL] )
Enables support for the named language in CMake. This is the same as the project() command but does not create any of the extra variables that are created by the project command. Example languages are CXX, C, CUDA, OBJC, OBJCXX, Fortran, and ASM.
If enabling ASM, enable it last so that CMake can check whether compilers for other languages like C work for assembly too.
This command must be called in file scope, not in a function call. Furthermore, it must be called in the highest directory common to all targets using the named language directly for compiling sources or indirectly through link dependencies. It is simplest to enable all needed languages in the top-level directory of a project.
The OPTIONAL keyword is a placeholder for future implementation and does not currently work. Instead you can use the CheckLanguage module to verify support before enabling.
Enable testing for current directory and below.
enable_testing()
Enables testing for this directory and below.
This command should be in the source directory root because ctest expects to find a test file in the build directory root.
This command is automatically invoked when the CTest module is included, except if the BUILD_TESTING option is turned off.
See also the add_test() command.
Export targets from the build tree for use by outside projects.
export(EXPORT <export-name> [NAMESPACE <namespace>] [FILE <filename>])
Creates a file <filename> that may be included by outside projects to import targets from the current project’s build tree. This is useful during cross-compiling to build utility executables that can run on the host platform in one project and then import them into another project being compiled for the target platform. If the NAMESPACE option is given the <namespace> string will be prepended to all target names written to the file.
Target installations are associated with the export <export-name> using the EXPORT option of the install(TARGETS) command.
The file created by this command is specific to the build tree and should never be installed. See the install(EXPORT) command to export targets from an installation tree.
The properties set on the generated IMPORTED targets will have the same values as the final values of the input TARGETS.
export(TARGETS [target1 [target2 [...]]] [NAMESPACE <namespace>]
[APPEND] FILE <filename> [EXPORT_LINK_INTERFACE_LIBRARIES])
This signature is similar to the EXPORT signature, but targets are listed explicitly rather than specified as an export-name. If the APPEND option is given the generated code will be appended to the file instead of overwriting it. The EXPORT_LINK_INTERFACE_LIBRARIES keyword, if present, causes the contents of the properties matching (IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)? to be exported, when policy CMP0022 is NEW. If a library target is included in the export but a target to which it links is not included the behavior is unspecified.
NOTE:
export(PACKAGE <PackageName>)
Store the current build directory in the CMake user package registry for package <PackageName>. The find_package() command may consider the directory while searching for package <PackageName>. This helps dependent projects find and use a package from the current project’s build tree without help from the user. Note that the entry in the package registry that this command creates works only in conjunction with a package configuration file (<PackageName>Config.cmake) that works with the build tree. In some cases, for example for packaging and for system wide installations, it is not desirable to write the user package registry.
By default the export(PACKAGE) command does nothing (see policy CMP0090) because populating the user package registry has effects outside the source and build trees. Set the CMAKE_EXPORT_PACKAGE_REGISTRY variable to add build directories to the CMake user package registry.
export(TARGETS [target1 [target2 [...]]] [ANDROID_MK <filename>])
This signature exports cmake built targets to the android ndk build system by creating an Android.mk file that references the prebuilt targets. The Android NDK supports the use of prebuilt libraries, both static and shared. This allows cmake to build the libraries of a project and make them available to an ndk build system complete with transitive dependencies, include flags and defines required to use the libraries. The signature takes a list of targets and puts them in the Android.mk file specified by the <filename> given. This signature can only be used if policy CMP0022 is NEW for all targets given. A error will be issued if that policy is set to OLD for one of the targets.
Create FLTK user interfaces Wrappers.
fltk_wrap_ui(resultingLibraryName source1
source2 ... sourceN )
Produce .h and .cxx files for all the .fl and .fld files listed. The resulting .h and .cxx files will be added to a variable named resultingLibraryName_FLTK_UI_SRCS which should be added to your library.
Get a property for a source file.
get_source_file_property(<variable> <file>
[DIRECTORY <dir> | TARGET_DIRECTORY <target>]
<property>)
Gets a property from a source file. The value of the property is stored in the specified <variable>. If the source property is not found, the behavior depends on whether it has been defined to be an INHERITED property or not (see define_property()). Non-inherited properties will set variable to NOTFOUND, whereas inherited properties will search the relevant parent scope as described for the define_property() command and if still unable to find the property, variable will be set to an empty string.
By default, the source file’s property will be read from the current source directory’s scope, but this can be overridden with one of the following sub-options:
Use set_source_files_properties() to set property values. Source file properties usually control how the file is built. One property that is always there is LOCATION.
See also the more general get_property() command.
Get a property from a target.
get_target_property(<VAR> target property)
Get a property from a target. The value of the property is stored in the variable <VAR>. If the target property is not found, the behavior depends on whether it has been defined to be an INHERITED property or not (see define_property()). Non-inherited properties will set <VAR> to <VAR>-NOTFOUND, whereas inherited properties will search the relevant parent scope as described for the define_property() command and if still unable to find the property, <VAR> will be set to an empty string.
Use set_target_properties() to set target property values. Properties are usually used to control how a target is built, but some query the target instead. This command can get properties for any target so far created. The targets do not need to be in the current CMakeLists.txt file.
See also the more general get_property() command.
See Target Properties for the list of properties known to CMake.
Get a property of the test.
get_test_property(test property VAR)
Get a property from the test. The value of the property is stored in the variable VAR. If the test property is not found, the behavior depends on whether it has been defined to be an INHERITED property or not (see define_property()). Non-inherited properties will set VAR to “NOTFOUND”, whereas inherited properties will search the relevant parent scope as described for the define_property() command and if still unable to find the property, VAR will be set to an empty string.
For a list of standard properties you can type cmake --help-property-list.
See also the more general get_property() command.
Add include directories to the build.
include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])
Add the given directories to those the compiler uses to search for include files. Relative paths are interpreted as relative to the current source directory.
The include directories are added to the INCLUDE_DIRECTORIES directory property for the current CMakeLists file. They are also added to the INCLUDE_DIRECTORIES target property for each target in the current CMakeLists file. The target property values are the ones used by the generators.
By default the directories specified are appended onto the current list of directories. This default behavior can be changed by setting CMAKE_INCLUDE_DIRECTORIES_BEFORE to ON. By using AFTER or BEFORE explicitly, you can select between appending and prepending, independent of the default.
If the SYSTEM option is given, the compiler will be told the directories are meant as system include directories on some platforms. Signalling this setting might achieve effects such as the compiler skipping warnings, or these fixed-install system files not being considered in dependency calculations - see compiler docs.
Arguments to include_directories may use “generator expressions” with the syntax “$<…>”. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
NOTE:
Include an external Microsoft project file in a workspace.
include_external_msproject(projectname location
[TYPE projectTypeGUID]
[GUID projectGUID]
[PLATFORM platformName]
dep1 dep2 ...)
Includes an external Microsoft project in the generated workspace file. Currently does nothing on UNIX. This will create a target named [projectname]. This can be used in the add_dependencies() command to make things depend on the external project.
TYPE, GUID and PLATFORM are optional parameters that allow one to specify the type of project, id (GUID) of the project and the name of the target platform. This is useful for projects requiring values other than the default (e.g. WIX projects).
If the imported project has different configuration names than the current project, set the MAP_IMPORTED_CONFIG_<CONFIG> target property to specify the mapping.
Set the regular expression used for dependency checking.
include_regular_expression(regex_match [regex_complain])
Sets the regular expressions used in dependency checking. Only files matching regex_match will be traced as dependencies. Only files matching regex_complain will generate warnings if they cannot be found (standard header paths are not searched). The defaults are:
regex_match = "^.*$" (match everything) regex_complain = "^$" (match empty string only)
Specify rules to run at install time.
install(TARGETS <target>... [...]) install({FILES | PROGRAMS} <file>... [...]) install(DIRECTORY <dir>... [...]) install(SCRIPT <file> [...]) install(CODE <code> [...]) install(EXPORT <export-name> [...])
This command generates installation rules for a project. Install rules specified by calls to the install() command within a source directory are executed in order during installation. Install rules in subdirectories added by calls to the add_subdirectory() command are interleaved with those in the parent directory to run in the order declared (see policy CMP0082).
There are multiple signatures for this command. Some of them define installation options for files and targets. Options common to multiple signatures are covered here but they are valid only for signatures that specify them. The common options are:
If a relative path is given it is interpreted relative to the value of the CMAKE_INSTALL_PREFIX variable. The prefix can be relocated at install time using the DESTDIR mechanism explained in the CMAKE_INSTALL_PREFIX variable documentation.
If an absolute path (with a leading slash or drive letter) is given it is used verbatim.
As absolute paths are not supported by cpack installer generators, it is preferable to use relative paths throughout.
install(TARGETS target
CONFIGURATIONS Debug
RUNTIME DESTINATION Debug/bin) install(TARGETS target
CONFIGURATIONS Release
RUNTIME DESTINATION Release/bin)
Note that CONFIGURATIONS appears BEFORE RUNTIME DESTINATION.
Command signatures that install files may print messages during installation. Use the CMAKE_INSTALL_MESSAGE variable to control which messages are printed.
Many of the install() variants implicitly create the directories containing the installed files. If CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS is set, these directories will be created with the permissions specified. Otherwise, they will be created according to the uname rules on Unix-like platforms. Windows platforms are unaffected.
install(TARGETS targets... [EXPORT <export-name>]
[[ARCHIVE|LIBRARY|RUNTIME|OBJECTS|FRAMEWORK|BUNDLE|
PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE]
[DESTINATION <dir>]
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>]
[NAMELINK_COMPONENT <component>]
[OPTIONAL] [EXCLUDE_FROM_ALL]
[NAMELINK_ONLY|NAMELINK_SKIP]
] [...]
[INCLUDES DESTINATION [<dir> ...]]
)
The TARGETS form specifies rules for installing targets from a project. There are several kinds of target Output Artifacts that may be installed:
For each of these arguments given, the arguments following them only apply to the target or file type specified in the argument. If none is given, the installation properties apply to all target types. If only one is given then only targets of that type will be installed (which can be used to install just a DLL or just an import library.)
For regular executables, static libraries and shared libraries, the DESTINATION argument is not required. For these target types, when DESTINATION is omitted, a default destination will be taken from the appropriate variable from GNUInstallDirs, or set to a built-in default value if that variable is not defined. The same is true for the public and private headers associated with the installed targets through the PUBLIC_HEADER and PRIVATE_HEADER target properties. A destination must always be provided for module libraries, Apple bundles and frameworks. A destination can be omitted for interface and object libraries, but they are handled differently (see the discussion of this topic toward the end of this section).
The following table shows the target types with their associated variables and built-in defaults that apply when no destination is given:
Target Type | GNUInstallDirs Variable | Built-In Default |
RUNTIME | ${CMAKE_INSTALL_BINDIR} | bin |
LIBRARY | ${CMAKE_INSTALL_LIBDIR} | lib |
ARCHIVE | ${CMAKE_INSTALL_LIBDIR} | lib |
PRIVATE_HEADER | ${CMAKE_INSTALL_INCLUDEDIR} | include |
PUBLIC_HEADER | ${CMAKE_INSTALL_INCLUDEDIR} | include |
Projects wishing to follow the common practice of installing headers into a project-specific subdirectory will need to provide a destination rather than rely on the above.
To make packages compliant with distribution filesystem layout policies, if projects must specify a DESTINATION, it is recommended that they use a path that begins with the appropriate GNUInstallDirs variable. This allows package maintainers to control the install destination by setting the appropriate cache variables. The following example shows a static library being installed to the default destination provided by GNUInstallDirs, but with its headers installed to a project-specific subdirectory that follows the above recommendation:
add_library(mylib STATIC ...) set_target_properties(mylib PROPERTIES PUBLIC_HEADER mylib.h) include(GNUInstallDirs) install(TARGETS mylib
PUBLIC_HEADER
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/myproj )
In addition to the common options listed above, each target can accept the following additional arguments:
lib<name>.so -> lib<name>.so.1
where lib<name>.so.1 is the soname of the library and lib<name>.so is a “namelink” allowing linkers to find the library when given -l<name>. The NAMELINK_COMPONENT option is similar to the COMPONENT option, but it changes the installation component of a shared library namelink if one is generated. If not specified, this defaults to the value of COMPONENT. It is an error to use this parameter outside of a LIBRARY block.
Consider the following example:
install(TARGETS mylib
LIBRARY
COMPONENT Libraries
NAMELINK_COMPONENT Development
PUBLIC_HEADER
COMPONENT Development
)
In this scenario, if you choose to install only the Development component, both the headers and namelink will be installed without the library. (If you don’t also install the Libraries component, the namelink will be a dangling symlink, and projects that link to the library will have build errors.) If you install only the Libraries component, only the library will be installed, without the headers and namelink.
This option is typically used for package managers that have separate runtime and development packages. For example, on Debian systems, the library is expected to be in the runtime package, and the headers and namelink are expected to be in the development package.
See the VERSION and SOVERSION target properties for details on creating versioned shared libraries.
When NAMELINK_ONLY is given, either NAMELINK_COMPONENT or COMPONENT may be used to specify the installation component of the namelink, but COMPONENT should generally be preferred.
If NAMELINK_SKIP is specified, NAMELINK_COMPONENT has no effect. It is not recommended to use NAMELINK_SKIP in conjunction with NAMELINK_COMPONENT.
The install(TARGETS) command can also accept the following options at the top level:
One or more groups of properties may be specified in a single call to the TARGETS form of this command. A target may be installed more than once to different locations. Consider hypothetical targets myExe, mySharedLib, and myStaticLib. The code:
install(TARGETS myExe mySharedLib myStaticLib
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib/static) install(TARGETS mySharedLib DESTINATION /some/full/path)
will install myExe to <prefix>/bin and myStaticLib to <prefix>/lib/static. On non-DLL platforms mySharedLib will be installed to <prefix>/lib and /some/full/path. On DLL platforms the mySharedLib DLL will be installed to <prefix>/bin and /some/full/path and its import library will be installed to <prefix>/lib/static and /some/full/path.
Interface Libraries may be listed among the targets to install. They install no artifacts but will be included in an associated EXPORT. If Object Libraries are listed but given no destination for their object files, they will be exported as Interface Libraries. This is sufficient to satisfy transitive usage requirements of other targets that link to the object libraries in their implementation.
Installing a target with the EXCLUDE_FROM_ALL target property set to TRUE has undefined behavior.
install(TARGETS) can install targets that were created in other directories. When using such cross-directory install rules, running make install (or similar) from a subdirectory will not guarantee that targets from other directories are up-to-date. You can use target_link_libraries() or add_dependencies() to ensure that such out-of-directory targets are built before the subdirectory-specific install rules are run.
An install destination given as a DESTINATION argument may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions.
install(<FILES|PROGRAMS> files...
TYPE <type> | DESTINATION <dir>
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>]
[RENAME <name>] [OPTIONAL] [EXCLUDE_FROM_ALL])
The FILES form specifies rules for installing files for a project. File names given as relative paths are interpreted with respect to the current source directory. Files installed by this form are by default given permissions OWNER_WRITE, OWNER_READ, GROUP_READ, and WORLD_READ if no PERMISSIONS argument is given.
The PROGRAMS form is identical to the FILES form except that the default permissions for the installed file also include OWNER_EXECUTE, GROUP_EXECUTE, and WORLD_EXECUTE. This form is intended to install programs that are not targets, such as shell scripts. Use the TARGETS form to install targets built within the project.
The list of files... given to FILES or PROGRAMS may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. However, if any item begins in a generator expression it must evaluate to a full path.
Either a TYPE or a DESTINATION must be provided, but not both. A TYPE argument specifies the generic file type of the files being installed. A destination will then be set automatically by taking the corresponding variable from GNUInstallDirs, or by using a built-in default if that variable is not defined. See the table below for the supported file types and their corresponding variables and built-in defaults. Projects can provide a DESTINATION argument instead of a file type if they wish to explicitly define the install destination.
TYPE Argument | GNUInstallDirs Variable | Built-In Default |
BIN | ${CMAKE_INSTALL_BINDIR} | bin |
SBIN | ${CMAKE_INSTALL_SBINDIR} | sbin |
LIB | ${CMAKE_INSTALL_LIBDIR} | lib |
INCLUDE | ${CMAKE_INSTALL_INCLUDEDIR} | include |
SYSCONF | ${CMAKE_INSTALL_SYSCONFDIR} | etc |
SHAREDSTATE | ${CMAKE_INSTALL_SHARESTATEDIR} | com |
LOCALSTATE | ${CMAKE_INSTALL_LOCALSTATEDIR} | var |
RUNSTATE | ${CMAKE_INSTALL_RUNSTATEDIR} | <LOCALSTATE dir>/run |
DATA | ${CMAKE_INSTALL_DATADIR} | <DATAROOT dir> |
INFO | ${CMAKE_INSTALL_INFODIR} | <DATAROOT dir>/info |
LOCALE | ${CMAKE_INSTALL_LOCALEDIR} | <DATAROOT dir>/locale |
MAN | ${CMAKE_INSTALL_MANDIR} | <DATAROOT dir>/man |
DOC | ${CMAKE_INSTALL_DOCDIR} | <DATAROOT dir>/doc |
Projects wishing to follow the common practice of installing headers into a project-specific subdirectory will need to provide a destination rather than rely on the above.
Note that some of the types’ built-in defaults use the DATAROOT directory as a prefix. The DATAROOT prefix is calculated similarly to the types, with CMAKE_INSTALL_DATAROOTDIR as the variable and share as the built-in default. You cannot use DATAROOT as a TYPE parameter; please use DATA instead.
To make packages compliant with distribution filesystem layout policies, if projects must specify a DESTINATION, it is recommended that they use a path that begins with the appropriate GNUInstallDirs variable. This allows package maintainers to control the install destination by setting the appropriate cache variables. The following example shows how to follow this advice while installing headers to a project-specific subdirectory:
include(GNUInstallDirs) install(FILES mylib.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/myproj )
An install destination given as a DESTINATION argument may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions.
install(DIRECTORY dirs...
TYPE <type> | DESTINATION <dir>
[FILE_PERMISSIONS permissions...]
[DIRECTORY_PERMISSIONS permissions...]
[USE_SOURCE_PERMISSIONS] [OPTIONAL] [MESSAGE_NEVER]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>] [EXCLUDE_FROM_ALL]
[FILES_MATCHING]
[[PATTERN <pattern> | REGEX <regex>]
[EXCLUDE] [PERMISSIONS permissions...]] [...])
The DIRECTORY form installs contents of one or more directories to a given destination. The directory structure is copied verbatim to the destination. The last component of each directory name is appended to the destination directory but a trailing slash may be used to avoid this because it leaves the last component empty. Directory names given as relative paths are interpreted with respect to the current source directory. If no input directory names are given the destination directory will be created but nothing will be installed into it. The FILE_PERMISSIONS and DIRECTORY_PERMISSIONS options specify permissions given to files and directories in the destination. If USE_SOURCE_PERMISSIONS is specified and FILE_PERMISSIONS is not, file permissions will be copied from the source directory structure. If no permissions are specified files will be given the default permissions specified in the FILES form of the command, and the directories will be given the default permissions specified in the PROGRAMS form of the command.
The MESSAGE_NEVER option disables file installation status output.
Installation of directories may be controlled with fine granularity using the PATTERN or REGEX options. These “match” options specify a globbing pattern or regular expression to match directories or files encountered within input directories. They may be used to apply certain options (see below) to a subset of the files and directories encountered. The full path to each input file or directory (with forward slashes) is matched against the expression. A PATTERN will match only complete file names: the portion of the full path matching the pattern must occur at the end of the file name and be preceded by a slash. A REGEX will match any portion of the full path but it may use / and $ to simulate the PATTERN behavior. By default all files and directories are installed whether or not they are matched. The FILES_MATCHING option may be given before the first match option to disable installation of files (but not directories) not matched by any expression. For example, the code
install(DIRECTORY src/ DESTINATION include/myproj
FILES_MATCHING PATTERN "*.h")
will extract and install header files from a source tree.
Some options may follow a PATTERN or REGEX expression and are applied only to files or directories matching them. The EXCLUDE option will skip the matched file or directory. The PERMISSIONS option overrides the permissions setting for the matched file or directory. For example the code
install(DIRECTORY icons scripts/ DESTINATION share/myproj
PATTERN "CVS" EXCLUDE
PATTERN "scripts/*"
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
GROUP_EXECUTE GROUP_READ)
will install the icons directory to share/myproj/icons and the scripts directory to share/myproj. The icons will get default file permissions, the scripts will be given specific permissions, and any CVS directories will be excluded.
Either a TYPE or a DESTINATION must be provided, but not both. A TYPE argument specifies the generic file type of the files within the listed directories being installed. A destination will then be set automatically by taking the corresponding variable from GNUInstallDirs, or by using a built-in default if that variable is not defined. See the table below for the supported file types and their corresponding variables and built-in defaults. Projects can provide a DESTINATION argument instead of a file type if they wish to explicitly define the install destination.
TYPE Argument | GNUInstallDirs Variable | Built-In Default |
BIN | ${CMAKE_INSTALL_BINDIR} | bin |
SBIN | ${CMAKE_INSTALL_SBINDIR} | sbin |
LIB | ${CMAKE_INSTALL_LIBDIR} | lib |
INCLUDE | ${CMAKE_INSTALL_INCLUDEDIR} | include |
SYSCONF | ${CMAKE_INSTALL_SYSCONFDIR} | etc |
SHAREDSTATE | ${CMAKE_INSTALL_SHARESTATEDIR} | com |
LOCALSTATE | ${CMAKE_INSTALL_LOCALSTATEDIR} | var |
RUNSTATE | ${CMAKE_INSTALL_RUNSTATEDIR} | <LOCALSTATE dir>/run |
DATA | ${CMAKE_INSTALL_DATADIR} | <DATAROOT dir> |
INFO | ${CMAKE_INSTALL_INFODIR} | <DATAROOT dir>/info |
LOCALE | ${CMAKE_INSTALL_LOCALEDIR} | <DATAROOT dir>/locale |
MAN | ${CMAKE_INSTALL_MANDIR} | <DATAROOT dir>/man |
DOC | ${CMAKE_INSTALL_DOCDIR} | <DATAROOT dir>/doc |
Note that some of the types’ built-in defaults use the DATAROOT directory as a prefix. The DATAROOT prefix is calculated similarly to the types, with CMAKE_INSTALL_DATAROOTDIR as the variable and share as the built-in default. You cannot use DATAROOT as a TYPE parameter; please use DATA instead.
To make packages compliant with distribution filesystem layout policies, if projects must specify a DESTINATION, it is recommended that they use a path that begins with the appropriate GNUInstallDirs variable. This allows package maintainers to control the install destination by setting the appropriate cache variables.
The list of dirs... given to DIRECTORY and an install destination given as a DESTINATION argument may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions.
install([[SCRIPT <file>] [CODE <code>]]
[COMPONENT <component>] [EXCLUDE_FROM_ALL] [...])
The SCRIPT form will invoke the given CMake script files during installation. If the script file name is a relative path it will be interpreted with respect to the current source directory. The CODE form will invoke the given CMake code during installation. Code is specified as a single argument inside a double-quoted string. For example, the code
install(CODE "MESSAGE(\"Sample install message.\")")
will print a message during installation.
<file> or <code> may use “generator expressions” with the syntax $<...> (in the case of <file>, this refers to their use in the file name, not the file’s contents). See the cmake-generator-expressions(7) manual for available expressions.
install(EXPORT <export-name> DESTINATION <dir>
[NAMESPACE <namespace>] [[FILE <name>.cmake]|
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[EXPORT_LINK_INTERFACE_LIBRARIES]
[COMPONENT <component>]
[EXCLUDE_FROM_ALL]) install(EXPORT_ANDROID_MK <export-name> DESTINATION <dir> [...])
The EXPORT form generates and installs a CMake file containing code to import targets from the installation tree into another project. Target installations are associated with the export <export-name> using the EXPORT option of the install(TARGETS) signature documented above. The NAMESPACE option will prepend <namespace> to the target names as they are written to the import file. By default the generated file will be called <export-name>.cmake but the FILE option may be used to specify a different name. The value given to the FILE option must be a file name with the .cmake extension. If a CONFIGURATIONS option is given then the file will only be installed when one of the named configurations is installed. Additionally, the generated import file will reference only the matching target configurations. The EXPORT_LINK_INTERFACE_LIBRARIES keyword, if present, causes the contents of the properties matching (IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)? to be exported, when policy CMP0022 is NEW.
NOTE:
When a COMPONENT option is given, the listed <component> implicitly depends on all components mentioned in the export set. The exported <name>.cmake file will require each of the exported components to be present in order for dependent projects to build properly. For example, a project may define components Runtime and Development, with shared libraries going into the Runtime component and static libraries and headers going into the Development component. The export set would also typically be part of the Development component, but it would export targets from both the Runtime and Development components. Therefore, the Runtime component would need to be installed if the Development component was installed, but not vice versa. If the Development component was installed without the Runtime component, dependent projects that try to link against it would have build errors. Package managers, such as APT and RPM, typically handle this by listing the Runtime component as a dependency of the Development component in the package metadata, ensuring that the library is always installed if the headers and CMake export file are present.
In addition to cmake language files, the EXPORT_ANDROID_MK mode maybe used to specify an export to the android ndk build system. This mode accepts the same options as the normal export mode. The Android NDK supports the use of prebuilt libraries, both static and shared. This allows cmake to build the libraries of a project and make them available to an ndk build system complete with transitive dependencies, include flags and defines required to use the libraries.
The EXPORT form is useful to help outside projects use targets built and installed by the current project. For example, the code
install(TARGETS myexe EXPORT myproj DESTINATION bin) install(EXPORT myproj NAMESPACE mp_ DESTINATION lib/myproj) install(EXPORT_ANDROID_MK myproj DESTINATION share/ndk-modules)
will install the executable myexe to <prefix>/bin and code to import it in the file <prefix>/lib/myproj/myproj.cmake and <prefix>/share/ndk-modules/Android.mk. An outside project may load this file with the include command and reference the myexe executable from the installation tree using the imported target name mp_myexe as if the target were built in its own tree.
NOTE:
NOTE:
The install() command generates a file, cmake_install.cmake, inside the build directory, which is used internally by the generated install target and by CPack. You can also invoke this script manually with cmake -P. This script accepts several variables:
Add directories in which the linker will look for libraries.
link_directories([AFTER|BEFORE] directory1 [directory2 ...])
Adds the paths in which the linker should search for libraries. Relative paths given to this command are interpreted as relative to the current source directory, see CMP0015.
The directories are added to the LINK_DIRECTORIES directory property for the current CMakeLists.txt file, converting relative paths to absolute as needed. The command will apply only to targets created after it is called.
By default the directories specified are appended onto the current list of directories. This default behavior can be changed by setting CMAKE_LINK_DIRECTORIES_BEFORE to ON. By using AFTER or BEFORE explicitly, you can select between appending and prepending, independent of the default.
Arguments to link_directories may use “generator expressions” with the syntax “$<…>”. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
NOTE:
If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.
Link libraries to all targets added later.
link_libraries([item1 [item2 [...]]]
[[debug|optimized|general] <item>] ...)
Specify libraries or flags to use when linking any targets created later in the current directory or below by commands such as add_executable() or add_library(). See the target_link_libraries() command for meaning of arguments.
NOTE:
Load in the values from another project’s CMake cache.
load_cache(pathToBuildDirectory READ_WITH_PREFIX prefix entry1...)
Reads the cache and store the requested entries in variables with their name prefixed with the given prefix. This only reads the values, and does not create entries in the local project’s cache.
load_cache(pathToBuildDirectory [EXCLUDE entry1...]
[INCLUDE_INTERNALS entry1...])
Loads in the values from another cache and store them in the local project’s cache as internal entries. This is useful for a project that depends on another project built in a different tree. EXCLUDE option can be used to provide a list of entries to be excluded. INCLUDE_INTERNALS can be used to provide a list of internal entries to be included. Normally, no internal entries are brought in. Use of this form of the command is strongly discouraged, but it is provided for backward compatibility.
Set the name of the 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>...])
Sets the name of the project, and stores it in the variable PROJECT_NAME. When called from the top-level CMakeLists.txt also stores the project name in the variable CMAKE_PROJECT_NAME.
Also sets the variables
Further variables are set by the optional arguments described in the following. If any of these arguments is not used, then the corresponding variables are set to the empty string.
The options are:
Takes a <version> argument composed of non-negative integer components, i.e. <major>[.<minor>[.<patch>[.<tweak>]]], and sets the variables
When the project() command is called from the top-level CMakeLists.txt, then the version is also stored in the variable CMAKE_PROJECT_VERSION.
to <project-description-string>. It is recommended that this description is a relatively short string, usually no more than a few words.
When the project() command is called from the top-level CMakeLists.txt, then the description is also stored in the variable CMAKE_PROJECT_DESCRIPTION.
to <url-string>, which should be the canonical home URL for the project.
When the project() command is called from the top-level CMakeLists.txt, then the URL also is stored in the variable CMAKE_PROJECT_HOMEPAGE_URL.
Selects which programming languages are needed to build the project. Supported languages include C, CXX (i.e. C++), CUDA, OBJC (i.e. Objective-C), OBJCXX, Fortran, and ASM. By default C and CXX are enabled if no language options are given. Specify language NONE, or use the LANGUAGES keyword and list no languages, to skip enabling any languages.
If enabling ASM, list it last so that CMake can check whether compilers for other languages like C work for assembly too.
The variables set through the VERSION, DESCRIPTION and HOMEPAGE_URL options are intended for use as default values in package metadata and documentation.
If the CMAKE_PROJECT_INCLUDE_BEFORE or CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE_BEFORE variables are set, the files they point to will be included as the first step of the project() command. If both are set, then CMAKE_PROJECT_INCLUDE_BEFORE will be included before CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE_BEFORE.
If the CMAKE_PROJECT_INCLUDE or CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE variables are set, the files they point to will be included as the last step of the project() command. If both are set, then CMAKE_PROJECT_INCLUDE will be included before CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE.
The top-level CMakeLists.txt file for a project must contain a literal, direct call to the project() command; loading one through the include() command is not sufficient. If no such call exists, CMake will issue a warning and pretend there is a project(Project) at the top to enable the default languages (C and CXX).
NOTE:
Remove -D define flags added by add_definitions().
remove_definitions(-DFOO -DBAR ...)
Removes flags (added by add_definitions()) from the compiler command line for sources in the current directory and below.
Source files can have properties that affect how they are built.
set_source_files_properties(<files> ...
[DIRECTORY <dirs> ...]
[TARGET_DIRECTORY <targets> ...]
PROPERTIES <prop1> <value1>
[<prop2> <value2>] ...)
Sets properties associated with source files using a key/value paired list.
By default, source file properties are only visible to targets added in the same directory (CMakeLists.txt). Visibility can be set in other directory scopes using one or both of the following options:
Use get_source_file_property() to get property values. See also the set_property(SOURCE) command.
See Source File Properties for the list of properties known to CMake.
Targets can have properties that affect how they are built.
set_target_properties(target1 target2 ...
PROPERTIES prop1 value1
prop2 value2 ...)
Sets properties on targets. The syntax for the command is to list all the targets you want to change, and then provide the values you want to set next. You can use any prop value pair you want and extract it later with the get_property() or get_target_property() command.
See also the set_property(TARGET) command.
See Target Properties for the list of properties known to CMake.
Set a property of the tests.
set_tests_properties(test1 [test2...] PROPERTIES prop1 value1 prop2 value2)
Sets a property for the tests. If the test is not found, CMake will report an error. Generator expressions will be expanded the same as supported by the test’s add_test() call.
See also the set_property(TEST) command.
See Test Properties for the list of properties known to CMake.
Define a grouping for source files in IDE project generation. There are two different signatures to create source groups.
source_group(<name> [FILES <src>...] [REGULAR_EXPRESSION <regex>]) source_group(TREE <root> [PREFIX <prefix>] [FILES <src>...])
Defines a group into which sources will be placed in project files. This is intended to set up file tabs in Visual Studio. The options are:
If a source file matches multiple groups, the last group that explicitly lists the file with FILES will be favored, if any. If no group explicitly lists the file, the last group whose regular expression matches the file will be favored.
The <name> of the group and <prefix> argument may contain forward slashes or backslashes to specify subgroups. Backslashes need to be escaped appropriately:
source_group(base/subdir ...) source_group(outer\\inner ...) source_group(TREE <root> PREFIX sources\\inc ...)
For backwards compatibility, the short-hand signature
source_group(<name> <regex>)
is equivalent to
source_group(<name> REGULAR_EXPRESSION <regex>)
Add compile definitions to a target.
target_compile_definitions(<target>
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
Specifies compile definitions to use when compiling a given <target>. The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments. PRIVATE and PUBLIC items will populate the COMPILE_DEFINITIONS property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_COMPILE_DEFINITIONS property of <target>. (IMPORTED targets only support INTERFACE items.) The following arguments specify compile definitions. Repeated calls for the same <target> append items in the order called.
Arguments to target_compile_definitions may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
Any leading -D on an item will be removed. Empty items are ignored. For example, the following are all equivalent:
target_compile_definitions(foo PUBLIC FOO) target_compile_definitions(foo PUBLIC -DFOO) # -D removed target_compile_definitions(foo PUBLIC "" FOO) # "" ignored target_compile_definitions(foo PUBLIC -D FOO) # -D becomes "", then ignored
Add expected compiler features to a target.
target_compile_features(<target> <PRIVATE|PUBLIC|INTERFACE> <feature> [...])
Specifies compiler features required when compiling a given target. If the feature is not listed in the CMAKE_C_COMPILE_FEATURES, CMAKE_CUDA_COMPILE_FEATURES, or CMAKE_CXX_COMPILE_FEATURES variables, then an error will be reported by CMake. If the use of the feature requires an additional compiler flag, such as -std=gnu++11, the flag will be added automatically.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the features. PRIVATE and PUBLIC items will populate the COMPILE_FEATURES property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_COMPILE_FEATURES property of <target>. (IMPORTED targets only support INTERFACE items.) Repeated calls for the same <target> append items.
The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target.
Arguments to target_compile_features may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-compile-features(7) manual for information on compile features and a list of supported compilers.
Add compile options to a target.
target_compile_options(<target> [BEFORE]
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
Adds options to the COMPILE_OPTIONS or INTERFACE_COMPILE_OPTIONS target properties. These options are used when compiling the given <target>, which must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target.
If BEFORE is specified, the content will be prepended to the property instead of being appended.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments. PRIVATE and PUBLIC items will populate the COMPILE_OPTIONS property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_COMPILE_OPTIONS property of <target>. (IMPORTED targets only support INTERFACE items.) The following arguments specify compile options. Repeated calls for the same <target> append items in the order called.
Arguments to target_compile_options may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
The final set of compile or link options used for a target is constructed by accumulating options from the current target and the usage requirements of its dependencies. The set of options is de-duplicated to avoid repetition. While beneficial for individual options, the de-duplication step can break up option groups. For example, -D A -D B becomes -D A B. One may specify a group of options using shell-like quoting along with a SHELL: prefix. The SHELL: prefix is dropped, and the rest of the option string is parsed using the separate_arguments() UNIX_COMMAND mode. For example, "SHELL:-D A" "SHELL:-D B" becomes -D A -D B.
This command can be used to add any options. However, for adding preprocessor definitions and include directories it is recommended to use the more specific commands target_compile_definitions() and target_include_directories().
For directory-wide settings, there is the command add_compile_options().
For file-specific settings, there is the source file property COMPILE_OPTIONS.
Add include directories to a target.
target_include_directories(<target> [SYSTEM] [BEFORE]
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
Specifies include directories to use when compiling a given target. 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 BEFORE is specified, the content will be prepended to the property instead of being appended.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments. PRIVATE and PUBLIC items will populate the INCLUDE_DIRECTORIES property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_INCLUDE_DIRECTORIES property of <target>. (IMPORTED targets only support INTERFACE items.) The following arguments specify include directories.
Specified include directories may be absolute paths or relative paths. Repeated calls for the same <target> append items in the order called. If SYSTEM is specified, the compiler will be told the directories are meant as system include directories on some platforms (signalling this setting might achieve effects such as the compiler skipping warnings, or these fixed-install system files not being considered in dependency calculations - see compiler docs). If SYSTEM is used together with PUBLIC or INTERFACE, the INTERFACE_SYSTEM_INCLUDE_DIRECTORIES target property will be populated with the specified directories.
Arguments to target_include_directories may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
Include directories usage requirements commonly differ between the build-tree and the install-tree. The BUILD_INTERFACE and INSTALL_INTERFACE generator expressions can be used to describe separate usage requirements based on the usage location. Relative paths are allowed within the INSTALL_INTERFACE expression and are interpreted relative to the installation prefix. For example:
target_include_directories(mylib PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/mylib>
$<INSTALL_INTERFACE:include/mylib> # <prefix>/include/mylib )
Note that it is not advisable to populate the INSTALL_INTERFACE of the INTERFACE_INCLUDE_DIRECTORIES of a target with absolute paths to the include directories of dependencies. That would hard-code into installed packages the include directory paths for dependencies as found on the machine the package was made on.
The INSTALL_INTERFACE of the INTERFACE_INCLUDE_DIRECTORIES is only suitable for specifying the required include directories for headers provided with the target itself, not those provided by the transitive dependencies listed in its INTERFACE_LINK_LIBRARIES target property. Those dependencies should themselves be targets that specify their own header locations in INTERFACE_INCLUDE_DIRECTORIES.
See the Creating Relocatable Packages section of the cmake-packages(7) manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
Add link directories to a target.
target_link_directories(<target> [BEFORE]
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
Specifies the paths in which the linker should search for libraries when linking a given target. Each item can be an absolute or relative path, with the latter being interpreted as relative to the current source directory. These items will be added to the link command.
The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the items that follow them. PRIVATE and PUBLIC items will populate the LINK_DIRECTORIES property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_LINK_DIRECTORIES property of <target> (IMPORTED targets only support INTERFACE items). Each item specifies a link directory and will be converted to an absolute path if necessary before adding it to the relevant property. Repeated calls for the same <target> append items in the order called.
If BEFORE is specified, the content will be prepended to the relevant property instead of being appended.
Arguments to target_link_directories may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
NOTE:
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.
This command has several signatures as detailed in subsections below. All of them have the general form
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.
Each <item> may be:
The named target must be created by add_library() within the project or as an IMPORTED library. If it is created within the project an ordering dependency will automatically be added in the build system to make sure the named library target is up-to-date before the <target> links.
If an imported library has the IMPORTED_NO_SONAME target property set, CMake may ask the linker to search for the library instead of using the full path (e.g. /usr/lib/libfoo.so becomes -lfoo).
The full path to the target’s artifact will be quoted/escaped for the shell automatically.
There are some cases where CMake may ask the linker to search for the library (e.g. /usr/lib/libfoo.so becomes -lfoo), such as when a shared library is detected to have no SONAME field. See policy CMP0060 for discussion of another case.
If the library file is in a macOS framework, the Headers directory of the framework will also be processed as a usage requirement. This has the same effect as passing the framework directory as an include directory.
On Visual Studio Generators for VS 2010 and above, library files ending in .targets will be treated as MSBuild targets files and imported into generated project files. This is not supported by other generators.
The full path to the library file will be quoted/escaped for the shell automatically.
The library name/flag is treated as a command-line string fragment and will be used with no extra quoting or escaping.
Link flags specified here are inserted into the link command in the same place as the link libraries. This might not be correct, depending on the linker. Use the LINK_OPTIONS target property or target_link_options() command to add link flags explicitly. The flags will then be placed at the toolchain-defined flag position in the link command.
The link flag is treated as a command-line string fragment and will be used with no extra quoting or escaping.
Additionally, a generator expression may be used as a fragment of any of the above items, e.g. foo$<1:_d>.
Note that generator expressions will not be used in OLD handling of policy CMP0003 or policy CMP0004.
Items containing ::, such as Foo::Bar, are assumed to be IMPORTED or ALIAS library target names and will cause an error if no such target exists. See policy CMP0028.
See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
target_link_libraries(<target>
<PRIVATE|PUBLIC|INTERFACE> <item>...
[<PRIVATE|PUBLIC|INTERFACE> <item>...]...)
The PUBLIC, PRIVATE and INTERFACE keywords can be used to specify both the link dependencies and the link interface in one command. Libraries and targets following PUBLIC are linked to, and are made part of the link interface. Libraries and targets following PRIVATE are linked to, but are not made part of the link interface. Libraries following INTERFACE are appended to the link interface and are not used for linking <target>.
target_link_libraries(<target> <item>...)
Library dependencies are transitive by default with this signature. When this target is linked into another target then the libraries linked to this target will appear on the link line for the other target too. This transitive “link interface” is stored in the INTERFACE_LINK_LIBRARIES target property and may be overridden by setting the property directly. When CMP0022 is not set to NEW, transitive linking is built in but may be overridden by the LINK_INTERFACE_LIBRARIES property. Calls to other signatures of this command may set the property making any libraries linked exclusively by this signature private.
target_link_libraries(<target>
<LINK_PRIVATE|LINK_PUBLIC> <lib>...
[<LINK_PRIVATE|LINK_PUBLIC> <lib>...]...)
The LINK_PUBLIC and LINK_PRIVATE modes can be used to specify both the link dependencies and the link interface in one command.
This signature is for compatibility only. Prefer the PUBLIC or PRIVATE keywords instead.
Libraries and targets following LINK_PUBLIC are linked to, and are made part of the INTERFACE_LINK_LIBRARIES. If policy CMP0022 is not NEW, they are also made part of the LINK_INTERFACE_LIBRARIES. Libraries and targets following LINK_PRIVATE are linked to, but are not made part of the INTERFACE_LINK_LIBRARIES (or LINK_INTERFACE_LIBRARIES).
target_link_libraries(<target> LINK_INTERFACE_LIBRARIES <item>...)
The LINK_INTERFACE_LIBRARIES mode appends the libraries to the INTERFACE_LINK_LIBRARIES target property instead of using them for linking. If policy CMP0022 is not NEW, then this mode also appends libraries to the LINK_INTERFACE_LIBRARIES and its per-configuration equivalent.
This signature is for compatibility only. Prefer the INTERFACE mode instead.
Libraries specified as debug are wrapped in a generator expression to correspond to debug builds. If policy CMP0022 is not NEW, the libraries are also appended to the LINK_INTERFACE_LIBRARIES_DEBUG property (or to the properties corresponding to configurations listed in the DEBUG_CONFIGURATIONS global property if it is set). Libraries specified as optimized are appended to the INTERFACE_LINK_LIBRARIES property. If policy CMP0022 is not NEW, they are also appended to the LINK_INTERFACE_LIBRARIES property. Libraries specified as general (or without any keyword) are treated as if specified for both debug and optimized.
Object Libraries may be used as the <target> (first) argument of target_link_libraries to specify dependencies of their sources on other libraries. For example, the code
add_library(A SHARED a.c) target_compile_definitions(A PUBLIC A) add_library(obj OBJECT obj.c) target_compile_definitions(obj PUBLIC OBJ) target_link_libraries(obj PUBLIC A)
compiles obj.c with -DA -DOBJ and establishes usage requirements for obj that propagate to its dependents.
Normal libraries and executables may link to Object Libraries to get their objects and usage requirements. Continuing the above example, the code
add_library(B SHARED b.c) target_link_libraries(B PUBLIC obj)
compiles b.c with -DA -DOBJ, creates shared library B with object files from b.c and obj.c, and links B to A. Furthermore, the code
add_executable(main main.c) target_link_libraries(main B)
compiles main.c with -DA -DOBJ and links executable main to B and A. The object library’s usage requirements are propagated transitively through B, but its object files are not.
Object Libraries may “link” to other object libraries to get usage requirements, but since they do not have a link step nothing is done with their object files. Continuing from the above example, the code:
add_library(obj2 OBJECT obj2.c) target_link_libraries(obj2 PUBLIC obj) add_executable(main2 main2.c) target_link_libraries(main2 obj2)
compiles obj2.c with -DA -DOBJ, creates executable main2 with object files from main2.c and obj2.c, and links main2 to A.
In other words, when Object Libraries appear in a target’s INTERFACE_LINK_LIBRARIES property they will be treated as Interface Libraries, but when they appear in a target’s LINK_LIBRARIES property their object files will be included in the link too.
The library dependency graph is normally acyclic (a DAG), but in the case of mutually-dependent STATIC libraries CMake allows the graph to contain cycles (strongly connected components). When another target links to one of the libraries, CMake repeats the entire connected component. For example, the code
add_library(A STATIC a.c) add_library(B STATIC b.c) target_link_libraries(A B) target_link_libraries(B A) add_executable(main main.c) target_link_libraries(main A)
links main to A B A B. While one repetition is usually sufficient, pathological object file and symbol arrangements can require more. One may handle such cases by using the LINK_INTERFACE_MULTIPLICITY target property or by manually repeating the component in the last target_link_libraries call. However, if two archives are really so interdependent they should probably be combined into a single archive, perhaps by using Object Libraries.
Note that it is not advisable to populate the INTERFACE_LINK_LIBRARIES of a target with absolute paths to dependencies. That would hard-code into installed packages the library file paths for dependencies as found on the machine the package was made on.
See the Creating Relocatable Packages section of the cmake-packages(7) manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
Add options to the link step for an executable, shared library or module library target.
target_link_options(<target> [BEFORE]
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target.
This command can be used to add any link options, but alternative commands exist to add libraries (target_link_libraries() or link_libraries()). See documentation of the directory and target LINK_OPTIONS properties.
NOTE:
If BEFORE is specified, the content will be prepended to the property instead of being appended.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments. PRIVATE and PUBLIC items will populate the LINK_OPTIONS property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_LINK_OPTIONS property of <target>. (IMPORTED targets only support INTERFACE items.) The following arguments specify link options. Repeated calls for the same <target> append items in the order called.
Arguments to target_link_options may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
When a device link step is involved, which is controlled by CUDA_SEPARABLE_COMPILATION and CUDA_RESOLVE_DEVICE_SYMBOLS properties and policy CMP0105, the raw options will be delivered to the host and device link steps (wrapped in -Xcompiler or equivalent for device link). Options wrapped with $<DEVICE_LINK:...> generator expression will be used only for the device link step. Options wrapped with $<HOST_LINK:...> generator expression will be used only for the host link step.
The final set of compile or link options used for a target is constructed by accumulating options from the current target and the usage requirements of its dependencies. The set of options is de-duplicated to avoid repetition. While beneficial for individual options, the de-duplication step can break up option groups. For example, -D A -D B becomes -D A B. One may specify a group of options using shell-like quoting along with a SHELL: prefix. The SHELL: prefix is dropped, and the rest of the option string is parsed using the separate_arguments() UNIX_COMMAND mode. For example, "SHELL:-D A" "SHELL:-D B" becomes -D A -D B.
To pass options to the linker tool, each compiler driver has its own syntax. The LINKER: prefix and , separator can be used to specify, in a portable way, options to pass to the linker tool. LINKER: is replaced by the appropriate driver option and , by the appropriate driver separator. The driver prefix and driver separator are given by the values of the CMAKE_<LANG>_LINKER_WRAPPER_FLAG and CMAKE_<LANG>_LINKER_WRAPPER_FLAG_SEP variables.
For example, "LINKER:-z,defs" becomes -Xlinker -z -Xlinker defs for Clang and -Wl,-z,defs for GNU GCC.
The LINKER: prefix can be specified as part of a SHELL: prefix expression.
The LINKER: prefix supports, as an alternative syntax, specification of arguments using the SHELL: prefix and space as separator. The previous example then becomes "LINKER:SHELL:-z defs".
NOTE:
Add a list of header files to precompile.
Precompiling header files can speed up compilation by creating a partially processed version of some header files, and then using that version during compilations rather than repeatedly parsing the original headers.
target_precompile_headers(<target>
<INTERFACE|PUBLIC|PRIVATE> [header1...]
[<INTERFACE|PUBLIC|PRIVATE> [header2...] ...])
The command adds header files to the PRECOMPILE_HEADERS and/or INTERFACE_PRECOMPILE_HEADERS target properties of <target>. The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments. PRIVATE and PUBLIC items will populate the PRECOMPILE_HEADERS property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_PRECOMPILE_HEADERS property of <target> (IMPORTED targets only support INTERFACE items). Repeated calls for the same <target> will append items in the order called.
Projects should generally avoid using PUBLIC or INTERFACE for targets that will be exported, or they should at least use the $<BUILD_INTERFACE:...> generator expression to prevent precompile headers from appearing in an installed exported target. Consumers of a target should typically be in control of what precompile headers they use, not have precompile headers forced on them by the targets being consumed (since precompile headers are not typically usage requirements). A notable exception to this is where an interface library is created to define a commonly used set of precompile headers in one place and then other targets link to that interface library privately. In this case, the interface library exists specifically to propagate the precompile headers to its consumers and the consumer is effectively still in control, since it decides whether to link to the interface library or not.
The list of header files is used to generate a header file named cmake_pch.h|xx which is used to generate the precompiled header file (.pch, .gch, .pchi) artifact. The cmake_pch.h|xx header file will be force included (-include for GCC, /FI for MSVC) to all source files, so sources do not need to have #include "pch.h".
Header file names specified with angle brackets (e.g. <unordered_map>) or explicit double quotes (escaped for the cmake-language(7), e.g. [["other_header.h"]]) will be treated as is, and include directories must be available for the compiler to find them. Other header file names (e.g. project_header.h) are interpreted as being relative to the current source directory (e.g. CMAKE_CURRENT_SOURCE_DIR) and will be included by absolute path. For example:
target_precompile_headers(myTarget
PUBLIC
project_header.h
PRIVATE
[["other_header.h"]]
<unordered_map> )
Arguments to target_precompile_headers() may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. The $<COMPILE_LANGUAGE:...> generator expression is particularly useful for specifying a language-specific header to precompile for only one language (e.g. CXX and not C). In this case, header file names that are not explicitly in double quotes or angle brackets must be specified by absolute path. Also, when specifying angle brackets inside a generator expression, be sure to encode the closing > as $<ANGLE-R>. For example:
target_precompile_headers(mylib PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:${CMAKE_CURRENT_SOURCE_DIR}/cxx_only.h>"
"$<$<COMPILE_LANGUAGE:C>:<stddef.h$<ANGLE-R>>"
"$<$<COMPILE_LANGUAGE:CXX>:<cstddef$<ANGLE-R>>" )
The command also supports a second signature which can be used to specify that one target re-uses a precompiled header file artifact from another target instead of generating its own:
target_precompile_headers(<target> REUSE_FROM <other_target>)
This form sets the PRECOMPILE_HEADERS_REUSE_FROM property to <other_target> and adds a dependency such that <target> will depend on <other_target>. CMake will halt with an error if the PRECOMPILE_HEADERS property of <target> is already set when the REUSE_FROM form is used.
NOTE:
To disable precompile headers for specific targets, see the DISABLE_PRECOMPILE_HEADERS target property.
To prevent precompile headers from being used when compiling a specific source file, see the SKIP_PRECOMPILE_HEADERS source file property.
Add sources to a target.
target_sources(<target>
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
Specifies sources to use when compiling a given target. Relative source file paths are interpreted as being relative to the current source directory (i.e. CMAKE_CURRENT_SOURCE_DIR). The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target.
The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments. PRIVATE and PUBLIC items will populate the SOURCES property of <target>. PUBLIC and INTERFACE items will populate the INTERFACE_SOURCES property of <target>. (IMPORTED targets only support INTERFACE items.) The following arguments specify sources. Repeated calls for the same <target> append items in the order called.
Arguments to target_sources may use “generator expressions” with the syntax $<...>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.
See also the CMP0076 policy for older behavior related to the handling of relative source file paths.
Try building some code.
try_compile(<resultVar> <bindir> <srcdir>
<projectName> [<targetName>] [CMAKE_FLAGS <flags>...]
[OUTPUT_VARIABLE <var>])
Try building a project. The success or failure of the try_compile, i.e. TRUE or FALSE respectively, is returned in <resultVar>.
In this form, <srcdir> should contain a complete CMake project with a CMakeLists.txt file and all sources. The <bindir> and <srcdir> will not be deleted after this command is run. Specify <targetName> to build a specific target instead of the all or ALL_BUILD target. See below for the meaning of other options.
try_compile(<resultVar> <bindir> <srcfile|SOURCES srcfile...>
[CMAKE_FLAGS <flags>...]
[COMPILE_DEFINITIONS <defs>...]
[LINK_OPTIONS <options>...]
[LINK_LIBRARIES <libs>...]
[OUTPUT_VARIABLE <var>]
[COPY_FILE <fileName> [COPY_FILE_ERROR <var>]]
[<LANG>_STANDARD <std>]
[<LANG>_STANDARD_REQUIRED <bool>]
[<LANG>_EXTENSIONS <bool>]
)
Try building an executable or static library from one or more source files (which one is determined by the CMAKE_TRY_COMPILE_TARGET_TYPE variable). The success or failure of the try_compile, i.e. TRUE or FALSE respectively, is returned in <resultVar>.
In this form, one or more source files must be provided. If CMAKE_TRY_COMPILE_TARGET_TYPE is unset or is set to EXECUTABLE, the sources must include a definition for main and CMake will create a CMakeLists.txt file to build the source(s) as an executable. If CMAKE_TRY_COMPILE_TARGET_TYPE is set to STATIC_LIBRARY, a static library will be built instead and no definition for main is required. For an executable, the generated CMakeLists.txt file would contain something like the following:
add_definitions(<expanded COMPILE_DEFINITIONS from caller>) include_directories(${INCLUDE_DIRECTORIES}) link_directories(${LINK_DIRECTORIES}) add_executable(cmTryCompileExec <srcfile>...) target_link_options(cmTryCompileExec PRIVATE <LINK_OPTIONS from caller>) target_link_libraries(cmTryCompileExec ${LINK_LIBRARIES})
The options are:
If this option is specified, any -DLINK_LIBRARIES=... value given to the CMAKE_FLAGS option will be ignored.
In this version all files in <bindir>/CMakeFiles/CMakeTmp will be cleaned automatically. For debugging, --debug-trycompile can be passed to cmake to avoid this clean. However, multiple sequential try_compile operations reuse this single output directory. If you use --debug-trycompile, you can only debug one try_compile call at a time. The recommended procedure is to protect all try_compile calls in your project by if(NOT DEFINED <resultVar>) logic, configure with cmake all the way through once, then delete the cache entry associated with the try_compile call of interest, and then re-run cmake again with --debug-trycompile.
If set, the following variables are passed in to the generated try_compile CMakeLists.txt to initialize compile target properties with default values:
If CMP0056 is set to NEW, then CMAKE_EXE_LINKER_FLAGS is passed in as well.
If CMP0083 is set to NEW, then in order to obtain correct behavior at link time, the check_pie_supported() command from the CheckPIESupported module must be called before using the try_compile() command.
The current settings of CMP0065 and CMP0083 are propagated through to the generated test project.
Set the CMAKE_TRY_COMPILE_CONFIGURATION variable to choose a build configuration.
Set the CMAKE_TRY_COMPILE_TARGET_TYPE variable to specify the type of target used for the source file signature.
Set the CMAKE_TRY_COMPILE_PLATFORM_VARIABLES variable to specify variables that must be propagated into the test project. This variable is meant for use only in toolchain files and is only honored by the try_compile() command for the source files form, not when given a whole project.
If CMP0067 is set to NEW, or any of the <LANG>_STANDARD, <LANG>_STANDARD_REQUIRED, or <LANG>_EXTENSIONS options are used, then the language standard variables are honored:
Their values are used to set the corresponding target properties in the generated project (unless overridden by an explicit option).
For the Green Hills MULTI generator the GHS toolset and target system customization cache variables are also propagated into the test project.
Try compiling and then running some code.
try_run(<runResultVar> <compileResultVar>
<bindir> <srcfile> [CMAKE_FLAGS <flags>...]
[COMPILE_DEFINITIONS <defs>...]
[LINK_OPTIONS <options>...]
[LINK_LIBRARIES <libs>...]
[COMPILE_OUTPUT_VARIABLE <var>]
[RUN_OUTPUT_VARIABLE <var>]
[OUTPUT_VARIABLE <var>]
[ARGS <args>...])
Try compiling a <srcfile>. Returns TRUE or FALSE for success or failure in <compileResultVar>. If the compile succeeded, runs the executable and returns its exit code in <runResultVar>. If the executable was built, but failed to run, then <runResultVar> will be set to FAILED_TO_RUN. See the try_compile() command for information on how the test project is constructed to build the source file.
The options are:
If this option is specified, any -DLINK_LIBRARIES=... value given to the CMAKE_FLAGS option will be ignored.
Set the CMAKE_TRY_COMPILE_CONFIGURATION variable to choose a build configuration.
When cross compiling, the executable compiled in the first step usually cannot be run on the build host. The try_run command checks the CMAKE_CROSSCOMPILING variable to detect whether CMake is in cross-compiling mode. If that is the case, it will still try to compile the executable, but it will not try to run the executable unless the CMAKE_CROSSCOMPILING_EMULATOR variable is set. Instead it will create cache variables which must be filled by the user or by presetting them in some CMake script file to the values the executable would have produced if it had been run on its actual target platform. These cache entries are:
In order to make cross compiling your project easier, use try_run only if really required. If you use try_run, use the RUN_OUTPUT_VARIABLE or OUTPUT_VARIABLE options only if really required. Using them will require that when cross-compiling, the cache variables will have to be set manually to the output of the executable. You can also “guard” the calls to try_run with an if() block checking the CMAKE_CROSSCOMPILING variable and provide an easy-to-preset alternative for this case.
These commands are available only in CTest scripts.
Perform the CTest Build Step as a Dashboard Client.
ctest_build([BUILD <build-dir>] [APPEND]
[CONFIGURATION <config>]
[FLAGS <flags>]
[PROJECT_NAME <project-name>]
[TARGET <target-name>]
[NUMBER_ERRORS <num-err-var>]
[NUMBER_WARNINGS <num-warn-var>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
)
Build the project and store results in Build.xml for submission with the ctest_submit() command.
The CTEST_BUILD_COMMAND variable may be set to explicitly specify the build command line. Otherwise the build command line is computed automatically based on the options given.
The options are:
Perform the CTest Configure Step as a Dashboard Client.
ctest_configure([BUILD <build-dir>] [SOURCE <source-dir>] [APPEND]
[OPTIONS <options>] [RETURN_VALUE <result-var>] [QUIET]
[CAPTURE_CMAKE_ERROR <result-var>])
Configure the project build tree and record results in Configure.xml for submission with the ctest_submit() command.
The options are:
Perform the CTest Coverage Step as a Dashboard Client.
ctest_coverage([BUILD <build-dir>] [APPEND]
[LABELS <label>...]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[QUIET]
)
Collect coverage tool results and stores them in Coverage.xml for submission with the ctest_submit() command.
The options are:
empties the binary directory
ctest_empty_binary_directory( directory )
Removes a binary directory. This command will perform some checks prior to deleting the directory in an attempt to avoid malicious or accidental directory deletion.
Perform the CTest MemCheck Step as a Dashboard Client.
ctest_memcheck([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL <level>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[DEFECT_COUNT <defect-count-var>]
[QUIET]
)
Run tests with a dynamic analysis tool and store results in MemCheck.xml for submission with the ctest_submit() command.
Most options are the same as those for the ctest_test() command.
The options unique to this command are:
read CTestCustom files.
ctest_read_custom_files( directory ... )
Read all the CTestCustom.ctest or CTestCustom.cmake files from the given directory.
By default, invoking ctest(1) without a script will read custom files from the binary directory.
runs a ctest -S script
ctest_run_script([NEW_PROCESS] script_file_name script_file_name1
script_file_name2 ... [RETURN_VALUE var])
Runs a script or scripts much like if it was run from ctest -S. If no argument is provided then the current script is run using the current settings of the variables. If NEW_PROCESS is specified then each script will be run in a separate process.If RETURN_VALUE is specified the return value of the last script run will be put into var.
sleeps for some amount of time
ctest_sleep(<seconds>)
Sleep for given number of seconds.
ctest_sleep(<time1> <duration> <time2>)
Sleep for t=(time1 + duration - time2) seconds if t > 0.
Starts the testing for a given model
ctest_start(<model> [<source> [<binary>]] [GROUP <group>] [QUIET]) ctest_start([<model> [<source> [<binary>]]] [GROUP <group>] APPEND [QUIET])
Starts the testing for a given model. The command should be called after the binary directory is initialized.
The parameters are as follows:
ctest_start(Experimental GROUP GroupExperimental)
Later, in another ctest -S script:
ctest_start(APPEND)
When the second script runs ctest_start(APPEND), it will read the Experimental model and GroupExperimental group from the TAG file generated by the first ctest_start() command. Please note that if you call ctest_start(APPEND) and specify a different model or group than in the first ctest_start() command, a warning will be issued, and the new model and group will be used.
The parameters for ctest_start() can be issued in any order, with the exception that <model>, <source>, and <binary> have to appear in that order with respect to each other. The following are all valid and equivalent:
ctest_start(Experimental path/to/source path/to/binary GROUP SomeGroup QUIET APPEND) ctest_start(GROUP SomeGroup Experimental QUIET path/to/source APPEND path/to/binary) ctest_start(APPEND QUIET Experimental path/to/source GROUP SomeGroup path/to/binary)
However, for the sake of readability, it is recommended that you order your parameters in the order listed at the top of this page.
If the CTEST_CHECKOUT_COMMAND variable (or the CTEST_CVS_CHECKOUT variable) is set, its content is treated as command-line. The command is invoked with the current working directory set to the parent of the source directory, even if the source directory already exists. This can be used to create the source tree from a version control repository.
Perform the CTest Submit Step as a Dashboard Client.
ctest_submit([PARTS <part>...] [FILES <file>...]
[SUBMIT_URL <url>]
[BUILD_ID <result-var>]
[HTTPHEADER <header>]
[RETRY_COUNT <count>]
[RETRY_DELAY <delay>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[QUIET]
)
Submit results to a dashboard server. By default all available parts are submitted.
The options are:
Start = nothing Update = ctest_update results, in Update.xml Configure = ctest_configure results, in Configure.xml Build = ctest_build results, in Build.xml Test = ctest_test results, in Test.xml Coverage = ctest_coverage results, in Coverage.xml MemCheck = ctest_memcheck results, in DynamicAnalysis.xml Notes = Files listed by CTEST_NOTES_FILES, in Notes.xml ExtraFiles = Files listed by CTEST_EXTRA_SUBMIT_FILES Upload = Files prepared for upload by ctest_upload(), in Upload.xml Submit = nothing Done = Build is complete, in Done.xml
ctest_submit(HTTPHEADER "Authorization: Bearer <auth-token>")
This suboption can be repeated several times for multiple headers.
ctest_submit(CDASH_UPLOAD <file> [CDASH_UPLOAD_TYPE <type>]
[SUBMIT_URL <url>]
[HTTPHEADER <header>]
[RETRY_COUNT <count>]
[RETRY_DELAY <delay>]
[RETURN_VALUE <result-var>]
[QUIET])
This second signature is used to upload files to CDash via the CDash file upload API. The API first sends a request to upload to CDash along with a content hash of the file. If CDash does not already have the file, then it is uploaded. Along with the file, a CDash type string is specified to tell CDash which handler to use to process the data.
This signature accepts the SUBMIT_URL, BUILD_ID, HTTPHEADER, RETRY_COUNT, RETRY_DELAY, RETURN_VALUE and QUIET options as described above.
Perform the CTest Test Step as a Dashboard Client.
ctest_test([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL <level>]
[RESOURCE_SPEC_FILE <file>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_ON_FAILURE]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[REPEAT <mode>:<n>]
[QUIET]
)
Run tests in the project build tree and store results in Test.xml for submission with the ctest_submit() command.
The options are:
See also the CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE and CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE variables.
Perform the CTest Update Step as a Dashboard Client.
ctest_update([SOURCE <source-dir>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[QUIET])
Update the source tree from version control and record results in Update.xml for submission with the ctest_submit() command.
The options are:
The update always follows the version control branch currently checked out in the source directory. See the CTest Update Step documentation for information about variables that change the behavior of ctest_update().
Upload files to a dashboard server as a Dashboard Client.
ctest_upload(FILES <file>... [QUIET] [CAPTURE_CMAKE_ERROR <result-var>])
The options are:
These commands are deprecated and are only made available to maintain backward compatibility. The documentation of each command states the CMake version in which it was deprecated. Do not use these commands in new code.
Disallowed since version 3.0. See CMake Policy CMP0036.
Use ${CMAKE_SYSTEM} and ${CMAKE_CXX_COMPILER} instead.
build_name(variable)
Sets the specified variable to a string representing the platform and compiler settings. These values are now available through the CMAKE_SYSTEM and CMAKE_CXX_COMPILER variables.
Deprecated since version 3.0: Use the execute_process() command instead.
Run an executable program during the processing of the CMakeList.txt file.
exec_program(Executable [directory in which to run]
[ARGS <arguments to executable>]
[OUTPUT_VARIABLE <var>]
[RETURN_VALUE <var>])
The executable is run in the optionally specified directory. The executable can include arguments if it is double quoted, but it is better to use the optional ARGS argument to specify arguments to the program. This is because cmake will then be able to escape spaces in the executable path. An optional argument OUTPUT_VARIABLE specifies a variable in which to store the output. To capture the return value of the execution, provide a RETURN_VALUE. If OUTPUT_VARIABLE is specified, then no output will go to the stdout/stderr of the console running cmake.
Disallowed since version 3.0. See CMake Policy CMP0033.
Use install(EXPORT) or export() command.
This command generates an old-style library dependencies file. Projects requiring CMake 2.6 or later should not use the command. Use instead the install(EXPORT) command to help export targets from an installation tree and the export() command to export targets from a build tree.
The old-style library dependencies file does not take into account per-configuration names of libraries or the LINK_INTERFACE_LIBRARIES target property.
export_library_dependencies(<file> [APPEND])
Create a file named <file> that can be included into a CMake listfile with the INCLUDE command. The file will contain a number of SET commands that will set all the variables needed for library dependency information. This should be the last command in the top level CMakeLists.txt file of the project. If the APPEND option is specified, the SET commands will be appended to the given file instead of replacing it.
Deprecated since version 3.0: Use the install(FILES) command instead.
This command has been superceded by the install() command. It is provided for compatibility with older CMake code. The FILES form is directly replaced by the FILES form of the install() command. The regexp form can be expressed more clearly using the GLOB form of the file() command.
install_files(<dir> extension file file ...)
Create rules to install the listed files with the given extension into the given directory. Only files existing in the current source tree or its corresponding location in the binary tree may be listed. If a file specified already has an extension, that extension will be removed first. This is useful for providing lists of source files such as foo.cxx when you want the corresponding foo.h to be installed. A typical extension is .h.
install_files(<dir> regexp)
Any files in the current source directory that match the regular expression will be installed.
install_files(<dir> FILES file file ...)
Any files listed after the FILES keyword will be installed explicitly from the names given. Full paths are allowed in this form.
The directory <dir> is relative to the installation prefix, which is stored in the variable CMAKE_INSTALL_PREFIX.
Deprecated since version 3.0: Use the install(PROGRAMS) command instead.
This command has been superceded by the install() command. It is provided for compatibility with older CMake code. The FILES form is directly replaced by the PROGRAMS form of the install() command. The regexp form can be expressed more clearly using the GLOB form of the file() command.
install_programs(<dir> file1 file2 [file3 ...]) install_programs(<dir> FILES file1 [file2 ...])
Create rules to install the listed programs into the given directory. Use the FILES argument to guarantee that the file list version of the command will be used even when there is only one argument.
install_programs(<dir> regexp)
In the second form any program in the current source directory that matches the regular expression will be installed.
This command is intended to install programs that are not built by cmake, such as shell scripts. See the TARGETS form of the install() command to create installation rules for targets built by cmake.
The directory <dir> is relative to the installation prefix, which is stored in the variable CMAKE_INSTALL_PREFIX.
Deprecated since version 3.0: Use the install(TARGETS) command instead.
This command has been superceded by the install() command. It is provided for compatibility with older CMake code.
install_targets(<dir> [RUNTIME_DIRECTORY dir] target target)
Create rules to install the listed targets into the given directory. The directory <dir> is relative to the installation prefix, which is stored in the variable CMAKE_INSTALL_PREFIX. If RUNTIME_DIRECTORY is specified, then on systems with special runtime files (Windows DLL), the files will be copied to that directory.
Disallowed since version 3.0. See CMake Policy CMP0031.
Load a command into a running CMake.
load_command(COMMAND_NAME <loc1> [loc2 ...])
The given locations are searched for a library whose name is cmCOMMAND_NAME. If found, it is loaded as a module and the command is added to the set of available CMake commands. Usually, try_compile() is used before this command to compile the module. If the command is successfully loaded a variable named
CMAKE_LOADED_COMMAND_<COMMAND_NAME>
will be set to the full path of the module that was loaded. Otherwise the variable will not be set.
Deprecated since version 3.0: Use the file(MAKE_DIRECTORY) command instead.
make_directory(directory)
Creates the specified directory. Full paths should be given. Any parent directories that do not exist will also be created. Use with care.
Disallowed since version 3.0. See CMake Policy CMP0032.
Approximate C preprocessor dependency scanning.
This command exists only because ancient CMake versions provided it. CMake handles preprocessor dependency scanning automatically using a more advanced scanner.
output_required_files(srcfile outputfile)
Outputs a list of all the source files that are required by the specified srcfile. This list is written into outputfile. This is similar to writing out the dependencies for srcfile except that it jumps from .h files into .cxx, .c and .cpp files if possible.
Deprecated since version 3.14: This command was originally added to support Qt 3 before the add_custom_command() command was sufficiently mature. The FindQt4 module provides the qt4_wrap_cpp() macro, which should be used instead for Qt 4 projects. For projects using Qt 5 or later, use the equivalent macro provided by Qt itself (e.g. Qt 5 provides qt5_wrap_cpp()).
Manually create Qt Wrappers.
qt_wrap_cpp(resultingLibraryName DestName SourceLists ...)
Produces moc files for all the .h files listed in the SourceLists. The moc files will be added to the library using the DestName source list.
Consider updating the project to use the AUTOMOC target property instead for a more automated way of invoking the moc tool.
Deprecated since version 3.14: This command was originally added to support Qt 3 before the add_custom_command() command was sufficiently mature. The FindQt4 module provides the qt4_wrap_ui() macro, which should be used instead for Qt 4 projects. For projects using Qt 5 or later, use the equivalent macro provided by Qt itself (e.g. Qt 5 provides qt5_wrap_ui()).
Manually create Qt user interfaces Wrappers.
qt_wrap_ui(resultingLibraryName HeadersDestName
SourcesDestName SourceLists ...)
Produces .h and .cxx files for all the .ui files listed in the SourceLists. The .h files will be added to the library using the HeadersDestNamesource list. The .cxx files will be added to the library using the SourcesDestNamesource list.
Consider updating the project to use the AUTOUIC target property instead for a more automated way of invoking the uic tool.
Deprecated since version 3.0: Use the list(REMOVE_ITEM) command instead.
remove(VAR VALUE VALUE ...)
Removes VALUE from the variable VAR. This is typically used to remove entries from a vector (e.g. semicolon separated list). VALUE is expanded.
Disallowed since version 3.0. See CMake Policy CMP0029.
Does nothing.
subdir_depends(subdir dep1 dep2 ...)
Does not do anything. This command used to help projects order parallel builds correctly. This functionality is now automatic.
Deprecated since version 3.0: Use the add_subdirectory() command instead.
Add a list of subdirectories to the build.
subdirs(dir1 dir2 ...[EXCLUDE_FROM_ALL exclude_dir1 exclude_dir2 ...]
[PREORDER] )
Add a list of subdirectories to the build. The add_subdirectory() command should be used instead of subdirs although subdirs will still work. This will cause any CMakeLists.txt files in the sub directories to be processed by CMake. Any directories after the PREORDER flag are traversed first by makefile builds, the PREORDER flag has no effect on IDE projects. Any directories after the EXCLUDE_FROM_ALL marker will not be included in the top level makefile or project file. This is useful for having CMake create makefiles or projects for a set of examples in a project. You would want CMake to generate makefiles or project files for all the examples at the same time, but you would not want them to show up in the top level project or be built each time make is run from the top.
Disallowed since version 3.0. See CMake Policy CMP0030.
Copy mesa headers for use in combination with system GL.
use_mangled_mesa(PATH_TO_MESA OUTPUT_DIRECTORY)
The path to mesa includes, should contain gl_mangle.h. The mesa headers are copied to the specified output directory. This allows mangled mesa headers to override other GL headers by being added to the include directory path earlier.
Disallowed since version 3.0. See CMake Policy CMP0034.
Specify the source tree of a third-party utility.
utility_source(cache_entry executable_name
path_to_source [file1 file2 ...])
When a third-party utility’s source is included in the distribution, this command specifies its location and name. The cache entry will not be set unless the path_to_source and all listed files exist. It is assumed that the source tree of the utility will have been built before it is needed.
When cross compiling CMake will print a warning if a utility_source() command is executed, because in many cases it is used to build an executable which is executed later on. This doesn’t work when cross compiling, since the executable can run only on their target platform. So in this case the cache entry has to be adjusted manually so it points to an executable which is runnable on the build host.
Disallowed since version 3.0. See CMake Policy CMP0035.
Use the if() command instead.
Assert satisfaction of an option’s required variables.
variable_requires(TEST_VARIABLE RESULT_VARIABLE
REQUIRED_VARIABLE1
REQUIRED_VARIABLE2 ...)
The first argument (TEST_VARIABLE) is the name of the variable to be tested, if that variable is false nothing else is done. If TEST_VARIABLE is true, then the next argument (RESULT_VARIABLE) is a variable that is set to true if all the required variables are set. The rest of the arguments are variables that must be true or not set to NOTFOUND to avoid an error. If any are not true, an error is reported.
Deprecated since version 3.0: Use the file(WRITE) command instead.
write_file(filename "message to write"... [APPEND])
The first argument is the file name, the rest of the arguments are messages to write. If the argument APPEND is specified, then the message will be appended.
NOTE 1: file(WRITE) and file(APPEND) do exactly the same as this one but add some more functionality.
NOTE 2: When using write_file the produced file cannot be used as an input to CMake (CONFIGURE_FILE, source file …) because it will lead to an infinite loop. Use configure_file() if you want to generate input files to CMake.
2000-2021 Kitware, Inc. and Contributors
September 13, 2021 | 3.18.4 |