NAME
cmake-commands - CMake Language Command ReferenceSCRIPTING COMMANDS
These commands are always available.block
New in version 3.25.block([SCOPE_FOR [POLICIES] [VARIABLES] ] [PROPAGATE <var-name>...]) <commands> endblock()
- SCOPE_FOR
- Specify which scopes must be created.
- POLICIES
- Create a new policy scope. This is equivalent to cmake_policy(PUSH).
- VARIABLES
- Create a new variable scope.
block(SCOPE_FOR VARIABLES POLICIES)
- PROPAGATE
- When a variable scope is created by the block() command, this option sets or unsets the specified variables in the parent scope. This is equivalent to set(PARENT_SCOPE) or unset(PARENT_SCOPE) commands.
set(var1 "INIT1") set(var2 "INIT2") block(PROPAGATE var1 var2) set(var1 "VALUE1") unset(var2) endblock() # Now var1 holds VALUE1, and var2 is unset
while(TRUE) block() ... # the break() command will terminate the while() command break() endblock() endwhile()
See Also
- •
- endblock()
- •
- return()
- •
- cmake_policy()
break
Break from an enclosing foreach or while loop.break()
cmake_host_system_information
Query various host system information.Synopsis
Query host system specific information cmake_host_system_information(RESULT <variable> QUERY <key> ...) Query Windows registry cmake_host_system_information(RESULT <variable> QUERY WINDOWS_REGISTRY <key> ...)
Query host system specific information
cmake_host_system_information(RESULT <variable> QUERY <key> ...)
- 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
- New in version 3.10. One if processor is 64Bit
- HAS_FPU
- New in version 3.10. One if processor has floating point unit
- HAS_MMX
- New in version 3.10. One if processor supports MMX instructions
- HAS_MMX_PLUS
- New in version 3.10. One if processor supports Ext. MMX instructions
- HAS_SSE
- New in version 3.10. One if processor supports SSE instructions
- HAS_SSE2
- New in version 3.10. One if processor supports SSE2 instructions
- HAS_SSE_FP
- New in version 3.10. One if processor supports SSE FP instructions
- HAS_SSE_MMX
- New in version 3.10. One if processor supports SSE MMX instructions
- HAS_AMD_3DNOW
- New in version 3.10. One if processor supports 3DNow instructions
- HAS_AMD_3DNOW_PLUS
- New in version 3.10. One if processor supports 3DNow+ instructions
- HAS_IA64
- New in version 3.10. One if IA64 processor emulating x86
- HAS_SERIAL_NUMBER
- New in version 3.10. One if processor has serial number
- PROCESSOR_SERIAL_NUMBER
- New in version 3.10. Processor serial number
- PROCESSOR_NAME
- New in version 3.10. Human readable processor name
- PROCESSOR_DESCRIPTION
- New in version 3.10. Human readable full processor description
- OS_NAME
- New in version 3.10. See CMAKE_HOST_SYSTEM_NAME
- OS_RELEASE
- New in version 3.10. The OS sub-type e.g. on Windows Professional
- OS_VERSION
- New in version 3.10. The OS build ID
- OS_PLATFORM
- New in version 3.10. See CMAKE_HOST_SYSTEM_PROCESSOR
- DISTRIB_INFO
- New in version 3.22. Read /etc/os-release file and define the given <variable> into a list of read variables
- DISTRIB_<name>
- New in version 3.22. Get the <name> variable (see man 5 os-release) if it exists in the /etc/os-release file Example:
cmake_host_system_information(RESULT PRETTY_NAME QUERY DISTRIB_PRETTY_NAME) message(STATUS "${PRETTY_NAME}") cmake_host_system_information(RESULT DISTRO QUERY DISTRIB_INFO) foreach(VAR IN LISTS DISTRO) message(STATUS "${VAR}=`${${VAR}}`") endforeach()
-- Ubuntu 20.04.2 LTS -- DISTRO_BUG_REPORT_URL=`https://bugs.launchpad.net/ubuntu/` -- DISTRO_HOME_URL=`https://www.ubuntu.com/` -- DISTRO_ID=`ubuntu` -- DISTRO_ID_LIKE=`debian` -- DISTRO_NAME=`Ubuntu` -- DISTRO_PRETTY_NAME=`Ubuntu 20.04.2 LTS` -- DISTRO_PRIVACY_POLICY_URL=`https://www.ubuntu.com/legal/terms-and-policies/privacy-policy` -- DISTRO_SUPPORT_URL=`https://help.ubuntu.com/` -- DISTRO_UBUNTU_CODENAME=`focal` -- DISTRO_VERSION=`20.04.2 LTS (Focal Fossa)` -- DISTRO_VERSION_CODENAME=`focal` -- DISTRO_VERSION_ID=`20.04`
Fallback Interface Variables
- CMAKE_GET_OS_RELEASE_FALLBACK_SCRIPTS
- In addition to the scripts shipped with CMake, a user may append full paths to his script(s) to the this list. The script filename has the following format: NNN-<name>.cmake, where NNN is three digits used to apply collected scripts in a specific order.
- CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname>
- Variables collected by the user provided fallback script ought to be assigned to CMake variables using this naming convention. Example, the ID variable from the manual becomes CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID.
- CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
- The fallback script ought to store names of all assigned CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname> variables in this list.
# Try to detect some old distribution # See also # - http://linuxmafia.com/faq/Admin/release-files.html # if(NOT EXISTS "${CMAKE_SYSROOT}/etc/foobar-release") return() endif() # Get the first string only file( STRINGS "${CMAKE_SYSROOT}/etc/foobar-release" CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT LIMIT_COUNT 1 ) # # Example: # # Foobar distribution release 1.2.3 (server) # if(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT MATCHES "Foobar distribution release ([0-9\.]+) .*") set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME Foobar) set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME "${CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT}") set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID foobar) set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION ${CMAKE_MATCH_1}) set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID ${CMAKE_MATCH_1}) list( APPEND CMAKE_GET_OS_RELEASE_FALLBACK_RESULT CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID ) endif() unset(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT)
FOOTNOTES
- [1]
- One MiB (mebibyte) is equal to 1024x1024 bytes.
Query Windows registry
New in version 3.24.cmake_host_system_information(RESULT <variable> QUERY WINDOWS_REGISTRY <key> [VALUE_NAMES|SUBKEYS|VALUE <name>] [VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)] [SEPARATOR <separator>] [ERROR_VARIABLE <result>])
Querying registry for any other platforms than
Windows, including CYGWIN, will always returns an empty string
and sets an error message in the variable specified with sub-option
ERROR_VARIABLE.
- •
- HKLM or HKEY_LOCAL_MACHINE
- •
- HKCU or HKEY_CURRENT_USER
- •
- HKCR or HKEY_CLASSES_ROOT
- •
- HKU or HKEY_USERS
- •
- HKCC or HKEY_CURRENT_CONFIG
cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM") cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware") cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKCU\\SOFTWARE\\Kitware")
- VALUE_NAMES
- Request the list of value names defined under <key>. If a default value is defined, it will be identified with the special name (default).
- SUBKEYS
- Request the list of subkeys defined under <key>.
- VALUE <name>
- Request the data stored in value named <name>. If VALUE is not specified or argument is the special name (default), the content of the default value, if any, will be returned.
# query default value for HKLM/SOFTWARE/Kitware key cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware") # query default value for HKLM/SOFTWARE/Kitware key using special value name cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware" VALUE "(default)")
- •
- REG_SZ.
- •
- REG_EXPAND_SZ. The returned data is expanded.
- •
- REG_MULTI_SZ. The returned is expressed as a CMake list. See also SEPARATOR sub-option.
- •
- REG_DWORD.
- •
- REG_QWORD.
- VIEW
- Specify which registry views must be queried. When not specified, BOTH view is used.
- 64
- Query the 64bit registry. On 32bit Windows, returns always an empty string.
- 32
- Query the 32bit registry.
- 64_32
- For VALUE sub-option or default value, query the registry using view 64, and if the request failed, query the registry using view 32. For VALUE_NAMES and SUBKEYS sub-options, query both views ( 64 and 32) and merge the results (sorted and duplicates removed).
- 32_64
- For VALUE sub-option or default value, query the registry using view 32, and if the request failed, query the registry using view 64. For VALUE_NAMES and SUBKEYS sub-options, query both views ( 32 and 64) and merge the results (sorted and duplicates removed).
- HOST
- Query the registry matching the architecture of the host: 64 on 64bit Windows and 32 on 32bit Windows.
- TARGET
- Query the registry matching the architecture specified by CMAKE_SIZEOF_VOID_P variable. If not defined, fallback to HOST view.
- BOTH
- Query both views (32 and 64). The order depends of the following rules: If CMAKE_SIZEOF_VOID_P variable is defined. Use the following view depending of the content of this variable:
- •
- 8: 64_32
- •
- 4: 32_64
- •
- 64bit: 64_32
- •
- 32bit: 32
- SEPARATOR
- Specify the separator character for REG_MULTI_SZ type. When not specified, the character \0 is used.
- ERROR_VARIABLE <result>
- Returns any error raised during query operation. In case of success, the variable holds an empty string.
cmake_language
New in version 3.18.Synopsis
cmake_language( CALL <command> [<arg>...]) cmake_language( EVAL CODE <code>...) cmake_language( DEFER <options>... CALL <command> [<arg>...]) cmake_language( SET_DEPENDENCY_PROVIDER <command> SUPPORTED_METHODS <methods>...) cmake_language( GET_MESSAGE_LOG_LEVEL <out-var>)
Introduction
This command will call meta-operations on built-in CMake commands or those created via the macro() or function() commands.Calling Commands
cmake_language(CALL <command> [<arg>...])
set(message_command "message") cmake_language(CALL ${message_command} STATUS "Hello World!")
message(STATUS "Hello World!")
To ensure consistency of the code, the
following commands are not allowed:
- •
- if / elseif / else / endif
- •
- block / endblock
- •
- while / endwhile
- •
- foreach / endforeach
- •
- function / endfunction
- •
- macro / endmacro
Evaluating Code
cmake_language(EVAL CODE <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()" )
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)
Deferring Calls
New in version 3.19.cmake_language(DEFER <options>... CALL <command> [<arg>...])
- DIRECTORY <dir>
- Schedule the call for the end of the given directory instead of the current directory. The <dir> may reference either a source directory or its corresponding binary directory. Relative paths are treated as relative to the current source directory. The given directory must be known to CMake, being either the top-level directory or one added by add_subdirectory(). Furthermore, the given directory must not yet be finished processing. This means it can be the current directory or one of its ancestors.
- ID <id>
- Specify an identification for the deferred call. The <id> may not be empty and may not begin with a capital letter A-Z. The <id> may begin with an underscore (_) only if it was generated automatically by an earlier call that used ID_VAR to get the id.
- ID_VAR <var>
- Specify a variable in which to store the identification for the deferred call. If ID <id> is not given, a new identification will be generated and the generated id will start with an underscore ( _).
cmake_language(DEFER [DIRECTORY <dir>] GET_CALL_IDS <var>)
cmake_language(DEFER [DIRECTORY <dir>] GET_CALL <id> <var>)
cmake_language(DEFER [DIRECTORY <dir>] CANCEL_CALL <id>...)
Deferred Call Examples
For example, the code:cmake_language(DEFER CALL message "${deferred_message}") cmake_language(DEFER ID_VAR id CALL message "Canceled Message") cmake_language(DEFER CANCEL_CALL ${id}) message("Immediate Message") set(deferred_message "Deferred Message")
Immediate Message Deferred Message
set(deferred_message "Deferred Message 1") set(re_evaluated [[${deferred_message}]]) cmake_language(EVAL CODE " cmake_language(DEFER CALL message [[${deferred_message}]]) cmake_language(DEFER CALL message \"${re_evaluated}\") ") message("Immediate Message") set(deferred_message "Deferred Message 2")
Immediate Message Deferred Message 1 Deferred Message 2
Dependency Providers
New in version 3.24.A high-level introduction to this feature can
be found in the Using Dependencies Guide.
cmake_language(SET_DEPENDENCY_PROVIDER <command> SUPPORTED_METHODS <methods>...)
- FIND_PACKAGE
- The provider command accepts find_package() requests.
- FETCHCONTENT_MAKEAVAILABLE_SERIAL
- The provider command accepts FetchContent_MakeAvailable() requests. It expects each dependency to be fed to the provider command one at a time, not the whole list in one go.
The choice of dependency provider should
always be under the user's control. As a convenience, a project may choose to
provide a file that users can list in their
CMAKE_PROJECT_TOP_LEVEL_INCLUDES variable, but the use of such a file
should always be the user's choice.
Provider commands
Providers define a single <command> to accept requests. The name of the command should be specific to that provider, not something overly generic that another provider might also use. This enables users to compose different providers in their own custom provider. The recommended form is xxx_provide_dependency(), where xxx is the provider-specific part (e.g. vcpkg_provide_dependency(), conan_provide_dependency(), ourcompany_provide_dependency(), and so on).xxx_provide_dependency(<method> [<method-specific-args>...])
- FIND_PACKAGE
- The <method-specific-args> will be everything passed to the find_package() call that requested the dependency. The first of these <method-specific-args> will therefore always be the name of the dependency. Dependency names are case-sensitive for this method because find_package() treats them case-sensitively too. If the provider command fulfills the request, it must set the same variable that find_package() expects to be set. For a dependency named depName, the provider must set depName_FOUND to true if it fulfilled the request. If the provider returns without setting this variable, CMake will assume the request was not fulfilled and will fall back to the built-in implementation. If the provider needs to call the built-in find_package() implementation as part of its processing, it can do so by including the BYPASS_PROVIDER keyword as one of the arguments.
- FETCHCONTENT_MAKEAVAILABE_SERIAL
- The <method-specific-args> will be everything passed to the FetchContent_Declare() call that corresponds to the requested dependency, with the following exceptions:
- •
- If SOURCE_DIR or BINARY_DIR were not part of the original declared arguments, they will be added with their default values.
- •
- If FETCHCONTENT_TRY_FIND_PACKAGE_MODE is set to NEVER, any FIND_PACKAGE_ARGS will be omitted.
- •
- The OVERRIDE_FIND_PACKAGE keyword is always omitted.
Provider Examples
This first example only intercepts find_package() calls. The provider command runs an external tool which copies the relevant artifacts into a provider-specific directory, if that tool knows about the dependency. It then relies on the built-in implementation to then find those artifacts. FetchContent_MakeAvailable() calls would not go through the provider.# Always ensure we have the policy settings this provider expects cmake_minimum_required(VERSION 3.24) set(MYCOMP_PROVIDER_INSTALL_DIR ${CMAKE_BINARY_DIR}/mycomp_packages CACHE PATH "The directory this provider installs packages to" ) # Tell the built-in implementation to look in our area first, unless # the find_package() call uses NO_..._PATH options to exclude it list(APPEND CMAKE_MODULE_PATH ${MYCOMP_PROVIDER_INSTALL_DIR}/cmake) list(APPEND CMAKE_PREFIX_PATH ${MYCOMP_PROVIDER_INSTALL_DIR}) macro(mycomp_provide_dependency method package_name) execute_process( COMMAND some_tool ${package_name} --installdir ${MYCOMP_PROVIDER_INSTALL_DIR} COMMAND_ERROR_IS_FATAL ANY ) endmacro() cmake_language( SET_DEPENDENCY_PROVIDER mycomp_provide_dependency SUPPORTED_METHODS FIND_PACKAGE )
cmake -DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=/path/to/mycomp_provider.cmake ...
cmake_minimum_required(VERSION 3.24) # Because we declare this very early, it will take precedence over any # details the project might declare later for the same thing include(FetchContent) FetchContent_Declare( googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0 ) # Both FIND_PACKAGE and FETCHCONTENT_MAKEAVAILABLE_SERIAL methods provide # the package or dependency name as the first method-specific argument. macro(mycomp_provide_dependency method dep_name) if("${dep_name}" MATCHES "^(gtest|googletest)$") # Save our current command arguments in case we are called recursively list(APPEND mycomp_provider_args ${method} ${dep_name}) # This will forward to the built-in FetchContent implementation, # which detects a recursive call for the same thing and avoids calling # the provider again if dep_name is the same as the current call. FetchContent_MakeAvailable(googletest) # Restore our command arguments list(POP_BACK mycomp_provider_args dep_name method) # Tell the caller we fulfilled the request if("${method}" STREQUAL "FIND_PACKAGE") # We need to set this if we got here from a find_package() call # since we used a different method to fulfill the request. # This example assumes projects only use the gtest targets, # not any of the variables the FindGTest module may define. set(${dep_name}_FOUND TRUE) elseif(NOT "${dep_name}" STREQUAL "googletest") # We used the same method, but were given a different name to the # one we populated with. Tell the caller about the name it used. FetchContent_SetPopulated(${dep_name} SOURCE_DIR "${googletest_SOURCE_DIR}" BINARY_DIR "${googletest_BINARY_DIR}" ) endif() endif() endmacro() cmake_language( SET_DEPENDENCY_PROVIDER mycomp_provide_dependency SUPPORTED_METHODS FIND_PACKAGE FETCHCONTENT_MAKEAVAILABLE_SERIAL )
cmake_minimum_required(VERSION 3.24) macro(mycomp_provide_dependency method) find_package(${ARGN} BYPASS_PROVIDER QUIET) endmacro() cmake_language( SET_DEPENDENCY_PROVIDER mycomp_provide_dependency SUPPORTED_METHODS FIND_PACKAGE )
Getting current message log level
New in version 3.25.cmake_language(GET_MESSAGE_LOG_LEVEL <output_variable>)
cmake_minimum_required
Require a minimum version of cmake.cmake_minimum_required(VERSION <min>[...<policy_max>] [FATAL_ERROR])
Call the cmake_minimum_required()
command at the beginning of the top-level CMakeLists.txt file even
before calling the project() command. It is important to establish
version and policy settings before invoking other commands whose behavior they
may affect. See also policy CMP0000.
Calling cmake_minimum_required() inside a function() limits some
effects to the function scope when invoked. For example, the
CMAKE_MINIMUM_REQUIRED_VERSION variable won't be set in the calling
scope. Functions do not introduce their own policy scope though, so policy
settings of the caller will be affected (see below). Due to this mix of
things that do and do not affect the calling scope, calling
cmake_minimum_required() inside a function is generally
discouraged.
Policy Settings
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.cmake_policy(VERSION <min>[...<max>])
cmake_policy(VERSION 2.4[...<max>])
cmake_parse_arguments
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>)
macro(my_install) set(options OPTIONAL FAST) set(oneValueArgs DESTINATION RENAME) set(multiValueArgs TARGETS CONFIGURATIONS) cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) # ...
my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub CONFIGURATIONS)
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
cmake_path
New in version 3.20.The cmake_path command handles paths in
the format of the build system (i.e. the host platform), not the target
system. When cross-compiling, if the path contains elements that are not
representable on the host platform (e.g. a drive letter when the host is not
Windows), the results will be unpredictable.
Synopsis
Conventions Path Structure And Terminology Normalization Decomposition cmake_path( GET <path-var> ROOT_NAME <out-var>) cmake_path( GET <path-var> ROOT_DIRECTORY <out-var>) cmake_path( GET <path-var> ROOT_PATH <out-var>) cmake_path( GET <path-var> FILENAME <out-var>) cmake_path( GET <path-var> EXTENSION [LAST_ONLY] <out-var>) cmake_path( GET <path-var> STEM [LAST_ONLY] <out-var>) cmake_path( GET <path-var> RELATIVE_PART <out-var>) cmake_path( GET <path-var> PARENT_PATH <out-var>) Query cmake_path( HAS_ROOT_NAME <path-var> <out-var>) cmake_path( HAS_ROOT_DIRECTORY <path-var> <out-var>) cmake_path( HAS_ROOT_PATH <path-var> <out-var>) cmake_path( HAS_FILENAME <path-var> <out-var>) cmake_path( HAS_EXTENSION <path-var> <out-var>) cmake_path( HAS_STEM <path-var> <out-var>) cmake_path( HAS_RELATIVE_PART <path-var> <out-var>) cmake_path( HAS_PARENT_PATH <path-var> <out-var>) cmake_path( IS_ABSOLUTE <path-var> <out-var>) cmake_path( IS_RELATIVE <path-var> <out-var>) cmake_path( IS_PREFIX <path-var> <input> [NORMALIZE] <out-var>) cmake_path( COMPARE <input1> <OP> <input2> <out-var>) Modification cmake_path( SET <path-var> [NORMALIZE] <input>) cmake_path( APPEND <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>]) cmake_path( APPEND_STRING <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>]) cmake_path( REMOVE_FILENAME <path-var> [OUTPUT_VARIABLE <out-var>]) cmake_path( REPLACE_FILENAME <path-var> <input> [OUTPUT_VARIABLE <out-var>]) cmake_path( REMOVE_EXTENSION <path-var> [LAST_ONLY] [OUTPUT_VARIABLE <out-var>]) cmake_path( REPLACE_EXTENSION <path-var> [LAST_ONLY] <input> [OUTPUT_VARIABLE <out-var>]) Generation cmake_path( NORMAL_PATH <path-var> [OUTPUT_VARIABLE <out-var>]) cmake_path( RELATIVE_PATH <path-var> [BASE_DIRECTORY <input>] [OUTPUT_VARIABLE <out-var>]) cmake_path( ABSOLUTE_PATH <path-var> [BASE_DIRECTORY <input>] [NORMALIZE] [OUTPUT_VARIABLE <out-var>]) Native Conversion cmake_path( NATIVE_PATH <path-var> [NORMALIZE] <out-var>) cmake_path( CONVERT <input> TO_CMAKE_PATH_LIST <out-var> [NORMALIZE]) cmake_path( CONVERT <input> TO_NATIVE_PATH_LIST <out-var> [NORMALIZE]) Hashing cmake_path( HASH <path-var> <out-var>)
Conventions
The following conventions are used in this command's documentation:- <path-var>
- Always the name of a variable. For commands that expect a <path-var> as input, the variable must exist and it is expected to hold a single path.
- <input>
- A string literal which may contain a path, path fragment, or multiple paths with a special separator depending on the command. See the description of each command to see how this is interpreted.
- <input>...
- Zero or more string literal arguments.
- <out-var>
- The name of a variable into which the result of a command will be written.
Path Structure And Terminology
A path has the following structure (all components are optional, with some constraints):root-name root-directory-separator (item-name directory-separator)* filename
- root-name
- Identifies the root on a filesystem with multiple roots (such as "C:" or "//myserver"). It is optional.
- root-directory-separator
- A directory separator that, if present, indicates that this path is absolute. If it is missing and the first element other than the root-name is an item-name, then the path is relative.
- item-name
- A sequence of characters that aren't directory separators. This name may identify a file, a hard link, a symbolic link, or a directory. Two special cases are recognized:
- •
- The item name consisting of a single dot character . is a directory name that refers to the current directory.
- •
- The item name consisting of two dot characters .. is a directory name that refers to the parent directory.
- directory-separator
- The only recognized directory separator is a forward slash character /. If this character is repeated, it is treated as a single directory separator. In other words, /usr///////lib is the same as /usr/lib.
- filename
- A path has a filename if it does not end with a directory-separator. The filename is effectively the last item-name of the path, so it can also be a hard link, symbolic link or a directory. A filename can have an extension. By default, the extension is defined as the sub-string beginning at the left-most period (including the period) and until the end of the filename. In commands that accept a LAST_ONLY keyword, LAST_ONLY changes the interpretation to the sub-string beginning at the right-most period. The following exceptions apply to the above interpretation:
- •
- If the first character in the filename is a period, that period is ignored (i.e. a filename like ".profile" is treated as having no extension).
- •
- If the filename is either . or .., it has no extension.
Creating A Path Variable
While a path can be created with care using an ordinary set() command, it is recommended to use cmake_path(SET) instead, as it automatically converts the path to the required form where required. The cmake_path(APPEND) subcommand may be another suitable alternative where a path needs to be constructed by joining fragments. The following example compares the three methods for constructing the same path:set(path1 "${CMAKE_CURRENT_SOURCE_DIR}/data") cmake_path(SET path2 "${CMAKE_CURRENT_SOURCE_DIR}/data") cmake_path(APPEND path3 "${CMAKE_CURRENT_SOURCE_DIR}" "data")
Normalization
Some sub-commands support normalizing a path. The algorithm used to normalize a path is as follows:- 1.
- If the path is empty, stop (the normalized form of an empty path is also an empty path).
- 2.
- Replace each directory-separator, which may consist of multiple separators, with a single / (/a///b --> /a/b).
- 3.
- Remove each solitary period (.) and any immediately following directory-separator (/a/./b/. --> /a/b).
- 4.
- Remove each item-name (other than ..) that is immediately followed by a directory-separator and a .., along with any immediately following directory-separator (/a/b/../c --> a/c).
- 5.
- If there is a root-directory, remove any .. and any directory-separators immediately following them. The parent of the root directory is treated as still the root directory ( /../a --> /a).
- 6.
- If the last item-name is .., remove any trailing directory-separator (../ --> ..).
- 7.
- If the path is empty by this stage, add a dot (normal form of ./ is .).
Decomposition
The following forms of the GET subcommand each retrieve a different component or group of components from a path. See Path Structure And Terminology for the meaning of each path component.cmake_path(GET <path-var> ROOT_NAME <out-var>) cmake_path(GET <path-var> ROOT_DIRECTORY <out-var>) cmake_path(GET <path-var> ROOT_PATH <out-var>) cmake_path(GET <path-var> FILENAME <out-var>) cmake_path(GET <path-var> EXTENSION [LAST_ONLY] <out-var>) cmake_path(GET <path-var> STEM [LAST_ONLY] <out-var>) cmake_path(GET <path-var> RELATIVE_PART <out-var>) cmake_path(GET <path-var> PARENT_PATH <out-var>)
Root examples
set(path "c:/a") cmake_path(GET path ROOT_NAME rootName) cmake_path(GET path ROOT_DIRECTORY rootDir) cmake_path(GET path ROOT_PATH rootPath) message("Root name is \"${rootName}\"") message("Root directory is \"${rootDir}\"") message("Root path is \"${rootPath}\"")
Root name is "c:" Root directory is "/" Root path is "c:/"
Filename examples
set(path "/a/b") cmake_path(GET path FILENAME filename) message("First filename is \"${filename}\"") # Trailing slash means filename is empty set(path "/a/b/") cmake_path(GET path FILENAME filename) message("Second filename is \"${filename}\"")
First filename is "b" Second filename is ""
Extension and stem examples
set(path "name.ext1.ext2") cmake_path(GET path EXTENSION fullExt) cmake_path(GET path STEM fullStem) message("Full extension is \"${fullExt}\"") message("Full stem is \"${fullStem}\"") # Effect of LAST_ONLY cmake_path(GET path EXTENSION LAST_ONLY lastExt) cmake_path(GET path STEM LAST_ONLY lastStem) message("Last extension is \"${lastExt}\"") message("Last stem is \"${lastStem}\"") # Special cases set(dotPath "/a/.") set(dotDotPath "/a/..") set(someMorePath "/a/.some.more") cmake_path(GET dotPath EXTENSION dotExt) cmake_path(GET dotPath STEM dotStem) cmake_path(GET dotDotPath EXTENSION dotDotExt) cmake_path(GET dotDotPath STEM dotDotStem) cmake_path(GET dotMorePath EXTENSION someMoreExt) cmake_path(GET dotMorePath STEM someMoreStem) message("Dot extension is \"${dotExt}\"") message("Dot stem is \"${dotStem}\"") message("Dot-dot extension is \"${dotDotExt}\"") message("Dot-dot stem is \"${dotDotStem}\"") message(".some.more extension is \"${someMoreExt}\"") message(".some.more stem is \"${someMoreStem}\"")
Full extension is ".ext1.ext2" Full stem is "name" Last extension is ".ext2" Last stem is "name.ext1" Dot extension is "" Dot stem is "." Dot-dot extension is "" Dot-dot stem is ".." .some.more extension is ".more" .some.more stem is ".some"
Relative part examples
set(path "c:/a/b") cmake_path(GET path RELATIVE_PART result) message("Relative part is \"${result}\"") set(path "c/d") cmake_path(GET path RELATIVE_PART result) message("Relative part is \"${result}\"") set(path "/") cmake_path(GET path RELATIVE_PART result) message("Relative part is \"${result}\"")
Relative part is "a/b" Relative part is "c/d" Relative part is ""
Path traversal examples
set(path "c:/a/b") cmake_path(GET path PARENT_PATH result) message("Parent path is \"${result}\"") set(path "c:/") cmake_path(GET path PARENT_PATH result) message("Parent path is \"${result}\"")
Parent path is "c:/a" Parent path is "c:/"
Query
Each of the GET subcommands has a corresponding HAS_... subcommand which can be used to discover whether a particular path component is present. See Path Structure And Terminology for the meaning of each path component.cmake_path(HAS_ROOT_NAME <path-var> <out-var>) cmake_path(HAS_ROOT_DIRECTORY <path-var> <out-var>) cmake_path(HAS_ROOT_PATH <path-var> <out-var>) cmake_path(HAS_FILENAME <path-var> <out-var>) cmake_path(HAS_EXTENSION <path-var> <out-var>) cmake_path(HAS_STEM <path-var> <out-var>) cmake_path(HAS_RELATIVE_PART <path-var> <out-var>) cmake_path(HAS_PARENT_PATH <path-var> <out-var>)
- •
- For HAS_ROOT_PATH, a true result will only be returned if at least one of root-name or root-directory is non-empty.
- •
- For HAS_PARENT_PATH, the root directory is also considered to have a parent, which will be itself. The result is true except if the path consists of just a filename.
cmake_path(IS_ABSOLUTE <path-var> <out-var>)
cmake_path(IS_RELATIVE <path-var> <out-var>)
cmake_path(IS_PREFIX <path-var> <input> [NORMALIZE] <out-var>)
set(path "/a/b/c") cmake_path(IS_PREFIX path "/a/b/c/d" result) # result = true cmake_path(IS_PREFIX path "/a/b" result) # result = false cmake_path(IS_PREFIX path "/x/y/z" result) # result = false set(path "/a/b") cmake_path(IS_PREFIX path "/a/c/../b" NORMALIZE result) # result = true
cmake_path(COMPARE <input1> EQUAL <input2> <out-var>) cmake_path(COMPARE <input1> NOT_EQUAL <input2> <out-var>)
if(NOT <input1>.root_name() STREQUAL <input2>.root_name()) return FALSE if(<input1>.has_root_directory() XOR <input2>.has_root_directory()) return FALSE Return FALSE if a relative portion of <input1> is not lexicographically equal to the relative portion of <input2>. This comparison is performed path component-wise. If all of the components compare equal, then return TRUE.
Unlike most other cmake_path()
subcommands, the COMPARE subcommand takes literal strings as input, not
the names of variables.
Modification
cmake_path(SET <path-var> [NORMALIZE] <input>)
set(native_path "c:\\a\\b/..\\c") cmake_path(SET path "${native_path}") message("CMake path is \"${path}\"") cmake_path(SET path NORMALIZE "${native_path}") message("Normalized CMake path is \"${path}\"")
CMake path is "c:/a/b/../c" Normalized CMake path is "c:/a/c"
cmake_path(APPEND <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
# <path> is the contents of <path-var> if(<input>.is_absolute() OR (<input>.has_root_name() AND NOT <input>.root_name() STREQUAL <path>.root_name())) replace <path> with <input> return() endif() if(<input>.has_root_directory()) remove any root-directory and the entire relative path from <path> elseif(<path>.has_filename() OR (NOT <path-var>.has_root_directory() OR <path>.is_absolute())) append directory-separator to <path> endif() append <input> omitting any root-name to <path>
cmake_path(APPEND_STRING <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
cmake_path(REMOVE_FILENAME <path-var> [OUTPUT_VARIABLE <out-var>])
set(path "/a/b") cmake_path(REMOVE_FILENAME path) message("First path is \"${path}\"") # filename is now already empty, the following removes nothing cmake_path(REMOVE_FILENAME path) message("Second path is \"${result}\"")
First path is "/a/" Second path is "/a/"
cmake_path(REPLACE_FILENAME <path-var> <input> [OUTPUT_VARIABLE <out-var>])
cmake_path(HAS_FILENAME path has_filename) if(has_filename) cmake_path(REMOVE_FILENAME path) cmake_path(APPEND path input); endif()
cmake_path(REMOVE_EXTENSION <path-var> [LAST_ONLY] [OUTPUT_VARIABLE <out-var>])
cmake_path(REPLACE_EXTENSION <path-var> [LAST_ONLY] <input> [OUTPUT_VARIABLE <out-var>])
cmake_path(REMOVE_EXTENSION path) if(NOT "input" MATCHES "^\\.") cmake_path(APPEND_STRING path ".") endif() cmake_path(APPEND_STRING path "input")
Generation
cmake_path(NORMAL_PATH <path-var> [OUTPUT_VARIABLE <out-var>])
cmake_path(RELATIVE_PATH <path-var> [BASE_DIRECTORY <input>] [OUTPUT_VARIABLE <out-var>])
cmake_path(ABSOLUTE_PATH <path-var> [BASE_DIRECTORY <input>] [NORMALIZE] [OUTPUT_VARIABLE <out-var>])
Native Conversion
For commands in this section, native refers to the host platform, not the target platform when cross-compiling.cmake_path(NATIVE_PATH <path-var> [NORMALIZE] <out-var>)
cmake_path(CONVERT <input> TO_CMAKE_PATH_LIST <out-var> [NORMALIZE])
Unlike most other cmake_path()
subcommands, the CONVERT subcommand takes a literal string as input,
not the name of a variable.
cmake_path(CONVERT <input> TO_NATIVE_PATH_LIST <out-var> [NORMALIZE])
Unlike most other cmake_path()
subcommands, the CONVERT subcommand takes a literal string as input,
not the name of a variable.
set(paths "/a/b/c" "/x/y/z") cmake_path(CONVERT "${paths}" TO_NATIVE_PATH_LIST native_paths) message("Native path list is \"${native_paths}\"")
Native path list is "\a\b\c;\x\y\z"
Native path list is "/a/b/c:/x/y/z"
Hashing
cmake_path(HASH <path-var> <out-var>)
cmake_policy
Manage CMake Policy settings. See the cmake-policies(7) manual for defined policies.Setting Policies by CMake Version
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>])
Setting Policies Explicitly
cmake_policy(SET CMP<NNNN> NEW) cmake_policy(SET CMP<NNNN> OLD)
The OLD behavior of a policy is
deprecated by definition and may be removed in a future version of
CMake.
Checking Policy Settings
cmake_policy(GET CMP<NNNN> <variable>)
CMake Policy Stack
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)
# stack management with cmake_policy() function(my_func) cmake_policy(PUSH) cmake_policy(SET ...) if (<cond1>) ... cmake_policy(POP) return() elseif(<cond2>) ... cmake_policy(POP) return() endif() ... cmake_policy(POP) endfunction() # stack management with block()/endblock() function(my_func) block(SCOPE_FOR POLICIES) cmake_policy(SET ...) if (<cond1>) ... return() elseif(<cond2>) ... return() endif() ... endblock() endfunction()
configure_file
Copy a file to another location and modify its contents.configure_file(<input> <output> [NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS | FILE_PERMISSIONS <permissions>...] [COPYONLY] [ESCAPE_QUOTES] [@ONLY] [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
#cmakedefine VAR ...
#define VAR ...
/* #undef VAR */
#cmakedefine01 VAR
#define VAR 0
#define VAR 1
# cmakedefine VAR # cmakedefine01 VAR
# define VAR # define VAR 1
- <input>
- Path to the input file. A relative path is treated with respect to the value of CMAKE_CURRENT_SOURCE_DIR. The input path must be a file, not a directory.
- <output>
- Path to the output file or directory. A relative path is treated with respect to the value of CMAKE_CURRENT_BINARY_DIR. If the path names an existing directory the output file is placed in that directory with the same file name as the input file. If the path contains non-existent directories, they are created.
- NO_SOURCE_PERMISSIONS
- New in version 3.19. Do not transfer the permissions of the input file to the output file. The copied file permissions default to the standard 644 value (-rw-r--r--).
- USE_SOURCE_PERMISSIONS
- New in version 3.20. Transfer the permissions of the input file to the output file. This is already the default behavior if none of the three permissions-related keywords are given ( NO_SOURCE_PERMISSIONS, USE_SOURCE_PERMISSIONS or FILE_PERMISSIONS). The USE_SOURCE_PERMISSIONS keyword mostly serves as a way of making the intended behavior clearer at the call site.
- FILE_PERMISSIONS <permissions>...
- New in version 3.20. Ignore the input file's permissions and use the specified <permissions> for the output file instead.
- COPYONLY
- Copy the file without replacing any variable references or other content. This option may not be used with NEWLINE_STYLE.
- ESCAPE_QUOTES
- Escape any substituted quotes with backslashes (C-style).
- @ONLY
- Restrict variable replacement to references of the form @VAR@. This is useful for configuring scripts that use ${VAR} syntax.
- NEWLINE_STYLE <style>
- Specify the newline style for the output file. Specify UNIX or LF for \n newlines, or specify DOS, WIN32, or CRLF for \r\n newlines. This option may not be used with COPYONLY.
Example
Consider a source tree containing a foo.h.in file:#cmakedefine FOO_ENABLE #cmakedefine FOO_STRING "@FOO_STRING@"
option(FOO_ENABLE "Enable Foo" ON) if(FOO_ENABLE) set(FOO_STRING "foo") endif() configure_file(foo.h.in foo.h @ONLY)
#define FOO_ENABLE #define FOO_STRING "foo"
/* #undef FOO_ENABLE */ /* #undef FOO_STRING */
include_directories(${CMAKE_CURRENT_BINARY_DIR})
continue
New in version 3.2.continue()
else
Starts the else portion of an if block.else([<condition>])
elseif
Starts an elseif portion of an if block.elseif(<condition>)
endblock
New in version 3.25.endblock()
endforeach
Ends a list of commands in a foreach block.endforeach([<loop_var>])
endfunction
Ends a list of commands in a function block.endfunction([<name>])
endif
Ends a list of commands in an if block.endif([<condition>])
endmacro
Ends a list of commands in a macro block.endmacro([<name>])
endwhile
Ends a list of commands in a while block.endwhile([<condition>])
execute_process
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] [COMMAND_ERROR_IS_FATAL <ANY|LAST>])
- COMMAND
- A child process command line. CMake executes the child process using operating system APIs directly:
- •
- On POSIX platforms, the command line is passed to the child process in an argv[] style array.
- •
- On Windows platforms, the command line is encoded as a string such that child processes using CommandLineToArgvW will decode the original arguments.
- WORKING_DIRECTORY
- The named directory will be set as the current working directory of the child processes.
- TIMEOUT
- After the specified number of seconds (fractions allowed), all unfinished child processes will be terminated, and the RESULT_VARIABLE will be set to a string mentioning the "timeout".
- RESULT_VARIABLE
- The variable will be set to contain the result of last child process. This will be an integer return code from the last child or a string describing an error condition.
- RESULTS_VARIABLE <variable>
- New in version 3.10. The variable will be set to contain the result of all processes as a semicolon-separated list, in order of the given COMMAND arguments. Each entry will be an integer return code from the corresponding child or a string describing an error condition.
- OUTPUT_VARIABLE, ERROR_VARIABLE
- The variable named will be set with the contents of the standard output and standard error pipes, respectively. If the same variable is named for both pipes their output will be merged in the order produced.
- INPUT_FILE, OUTPUT_FILE, ERROR_FILE
- The file named will be attached to the standard input of the first process, standard output of the last process, or standard error of all processes, respectively. New in version 3.3: If the same file is named for both output and error then it will be used for both.
- OUTPUT_QUIET, ERROR_QUIET
- The standard output or standard error results will be quietly ignored.
- COMMAND_ECHO <where>
- New in version 3.15. The command being run will be echo'ed to <where> with <where> being set to one of STDERR, STDOUT or NONE. See the CMAKE_EXECUTE_PROCESS_COMMAND_ECHO variable for a way to control the default behavior when this option is not present.
- ENCODING <name>
- New in version 3.8. On Windows, the encoding that is used to decode output from the process. Ignored on other platforms. Valid encoding names are:
- NONE
- Perform no decoding. This assumes that the process output is encoded in the same way as CMake's internal encoding (UTF-8). This is the default.
- AUTO
- Use the current active console's codepage or if that isn't available then use ANSI.
- ANSI
- Use the ANSI codepage.
- OEM
- Use the original equipment manufacturer (OEM) code page.
- UTF8 or UTF-8
- Use the UTF-8 codepage. New in version 3.11: Accept UTF-8 spelling for consistency with the UTF-8 RFC naming convention.
- ECHO_OUTPUT_VARIABLE, ECHO_ERROR_VARIABLE
- New in version 3.18. The standard output or standard error will not be exclusively redirected to the configured variables. 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.
- COMMAND_ERROR_IS_FATAL <ANY|LAST>
- New in version 3.19. The option following COMMAND_ERROR_IS_FATAL determines the behavior when an error is encountered:
ANY If any of the commands in the list
of commands fail, the execute_process() command halts with an error.
LAST If the last command in the list of commands fails, the
execute_process() command halts with an error. Commands earlier in the
list will not cause a fatal error.
file
File manipulation command.The sub-commands RELATIVE_PATH,
TO_CMAKE_PATH and TO_NATIVE_PATH has been superseded,
respectively, by sub-commands RELATIVE_PATH, CONVERT ...
TO_CMAKE_PATH_LIST and CONVERT ... TO_NATIVE_PATH_LIST of
cmake_path() command.
Synopsis
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( MAKE_DIRECTORY [<dir>...]) file({ REMOVE | REMOVE_RECURSE } [<files>...]) file( RENAME <oldname> <newname> [...]) file( COPY_FILE <oldname> <newname> [...]) file({ COPY | INSTALL} <file>... DESTINATION <dir> [...]) file( SIZE <filename> <out-var>) file( READ_SYMLINK <linkname> <out-var>) file( CREATE_LINK <original> <linkname> [...]) file( CHMOD <files>... <directories>... PERMISSIONS <permissions>... [...]) file( CHMOD_RECURSE <files>... <directories>... PERMISSIONS <permissions>... [...]) Path Conversion file( REAL_PATH <path> <out-var> [BASE_DIRECTORY <dir>] [EXPAND_TILDE]) 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> [...])
Reading
file(READ <filename> <variable> [OFFSET <offset>] [LIMIT <max-in>] [HEX])
file(STRINGS <filename> <variable> [<options>...])
- LENGTH_MAXIMUM <max-len>
- Consider only strings of at most a given length.
- LENGTH_MINIMUM <min-len>
- Consider only strings of at least a given length.
- LIMIT_COUNT <max-num>
- Limit the number of distinct strings to be extracted.
- LIMIT_INPUT <max-in>
- Limit the number of input bytes to read from the file.
- LIMIT_OUTPUT <max-out>
- Limit the number of total bytes to store in the <variable>.
- NEWLINE_CONSUME
- Treat newline characters (\n, LF) as part of string content instead of terminating at them.
- NO_HEX_CONVERSION
- Intel Hex and Motorola S-record files are automatically converted to binary while reading unless this option is given.
- REGEX <regex>
- Consider only strings that match the given regular expression, as described under string(REGEX).
- ENCODING <encoding-type>
- New in version 3.1. Consider strings of a given encoding. Currently supported encodings are: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. If the ENCODING option is not provided and the file has a Byte Order Mark, the ENCODING option will be defaulted to respect the Byte Order Mark. New in version 3.2: Added the UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE encodings.
file(STRINGS myfile.txt myfile)
file(<HASH> <filename> <variable>)
file(TIMESTAMP <filename> <variable> [<format>] [UTC])
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>...]] [POST_INCLUDE_FILES [<files>...]] [POST_EXCLUDE_FILES [<files>...]] )
install(CODE [[ file(GET_RUNTIME_DEPENDENCIES # ... ) ]])
- RESOLVED_DEPENDENCIES_VAR <deps_var>
- Name of the variable in which to store the list of resolved dependencies.
- UNRESOLVED_DEPENDENCIES_VAR <unresolved_deps_var>
- Name of the variable in which to store the list of unresolved dependencies. If this variable is not specified, and there are any unresolved dependencies, an error is issued.
- CONFLICTING_DEPENDENCIES_PREFIX <conflicting_deps_prefix>
- Variable prefix in which to store conflicting dependency information. Dependencies are conflicting if two files with the same name are found in two different directories. The list of filenames that conflict are stored in <conflicting_deps_prefix>_FILENAMES. For each filename, the list of paths that were found for that filename are stored in <conflicting_deps_prefix>_<filename>.
- EXECUTABLES <executable_files>
- List of executable files to read for dependencies. These are executables that are typically created with add_executable(), but they do not have to be created by CMake. On Apple platforms, the paths to these files determine the value of @executable_path when recursively resolving the libraries. Specifying any kind of library ( STATIC, MODULE, or SHARED) here will result in undefined behavior.
- LIBRARIES <library_files>
- List of library files to read for dependencies. These are libraries that are typically created with add_library(SHARED), but they do not have to be created by CMake. Specifying STATIC libraries, MODULE libraries, or executables here will result in undefined behavior.
- MODULES <module_files>
- List of loadable module files to read for dependencies. These are modules that are typically created with add_library(MODULE), but they do not have to be created by CMake. They are typically used by calling dlopen() at runtime rather than linked at link time with ld -l. Specifying STATIC libraries, SHARED libraries, or executables here will result in undefined behavior.
- DIRECTORIES <directories>
- List of additional directories to search for dependencies. On Linux platforms, these directories are searched if the dependency is not found in any of the other usual paths. If it is found in such a directory, a warning is issued, because it means that the file is incomplete (it does not list all of the directories that contain its dependencies). On Windows platforms, these directories are searched if the dependency is not found in any of the other search paths, but no warning is issued, because searching other paths is a normal part of Windows dependency resolution. On Apple platforms, this argument has no effect.
- BUNDLE_EXECUTABLE <bundle_executable_file>
- Executable to treat as the "bundle executable" when resolving libraries. On Apple platforms, this argument determines the value of @executable_path when recursively resolving libraries for LIBRARIES and MODULES files. It has no effect on EXECUTABLES files. On other platforms, it has no effect. This is typically (but not always) one of the executables in the EXECUTABLES argument which designates the "main" executable of the package.
- PRE_INCLUDE_REGEXES <regexes>
- List of pre-include regexes through which to filter the names of not-yet-resolved dependencies.
- PRE_EXCLUDE_REGEXES <regexes>
- List of pre-exclude regexes through which to filter the names of not-yet-resolved dependencies.
- POST_INCLUDE_REGEXES <regexes>
- List of post-include regexes through which to filter the names of resolved dependencies.
- POST_EXCLUDE_REGEXES <regexes>
- List of post-exclude regexes through which to filter the names of resolved dependencies.
- POST_INCLUDE_FILES <files>
- New in version 3.21. List of post-include filenames through which to filter the names of resolved dependencies. Symlinks are resolved when attempting to match these filenames.
- POST_EXCLUDE_FILES <files>
- New in version 3.21. List of post-exclude filenames through which to filter the names of resolved dependencies. Symlinks are resolved when attempting to match these filenames.
- 1.
- If the not-yet-resolved dependency matches any of the PRE_INCLUDE_REGEXES, steps 2 and 3 are skipped, and the dependency resolution proceeds to step 4.
- 2.
- If the not-yet-resolved dependency matches any of the PRE_EXCLUDE_REGEXES, dependency resolution stops for that dependency.
- 3.
- Otherwise, dependency resolution proceeds.
- 4.
- file(GET_RUNTIME_DEPENDENCIES) searches for the dependency according to the linking rules of the platform (see below).
- 5.
- If the dependency is found, and its full path matches one of the POST_INCLUDE_REGEXES or POST_INCLUDE_FILES, the full path is added to the resolved dependencies, and file(GET_RUNTIME_DEPENDENCIES) recursively resolves that library's own dependencies. Otherwise, resolution proceeds to step 6.
- 6.
- If the dependency is found, but its full path matches one of the POST_EXCLUDE_REGEXES or POST_EXCLUDE_FILES, it is not added to the resolved dependencies, and dependency resolution stops for that dependency.
- 7.
- If the dependency is found, and its full path does not match either POST_INCLUDE_REGEXES, POST_INCLUDE_FILES, POST_EXCLUDE_REGEXES, or POST_EXCLUDE_FILES, the full path is added to the resolved dependencies, and file(GET_RUNTIME_DEPENDENCIES) recursively resolves that library's own dependencies.
- 1.
- If the depending file does not have any RUNPATH entries, and the library exists in one of the depending file's RPATH entries, or its parents', in that order, the dependency is resolved to that file.
- 2.
- Otherwise, if the depending file has any RUNPATH entries, and the library exists in one of those entries, the dependency is resolved to that file.
- 3.
- Otherwise, if the library exists in one of the directories listed by ldconfig, the dependency is resolved to that file.
- 4.
- Otherwise, if the library exists in one of the DIRECTORIES entries, the dependency is resolved to that file. In this case, a warning is issued, because finding a file in one of the DIRECTORIES means that the depending file is not complete (it does not list all the directories from which it pulls dependencies).
- 5.
- Otherwise, the dependency is unresolved.
- 1.
- The dependent DLL name is converted to lowercase. Windows DLL names are case-insensitive, and some linkers mangle the case of the DLL dependency names. However, this makes it more difficult for PRE_INCLUDE_REGEXES, PRE_EXCLUDE_REGEXES, POST_INCLUDE_REGEXES, and POST_EXCLUDE_REGEXES to properly filter DLL names - every regex would have to check for both uppercase and lowercase letters. For example:
file(GET_RUNTIME_DEPENDENCIES # ... PRE_INCLUDE_REGEXES "^[Mm][Yy][Ll][Ii][Bb][Rr][Aa][Rr][Yy]\\.[Dd][Ll][Ll]$" )
file(GET_RUNTIME_DEPENDENCIES # ... PRE_INCLUDE_REGEXES "^mylibrary\\.dll$" )
- 2.
- (Not yet implemented) If the depending file is a Windows Store app, and the dependency is listed as a dependency in the application's package manifest, the dependency is resolved to that file.
- 3.
- Otherwise, if the library exists in the same directory as the depending file, the dependency is resolved to that file.
- 4.
- Otherwise, if the library exists in either the operating system's system32 directory or the Windows directory, in that order, the dependency is resolved to that file.
- 5.
- Otherwise, if the library exists in one of the directories specified by DIRECTORIES, in the order they are listed, the dependency is resolved to that file. In this case, a warning is not issued, because searching other directories is a normal part of Windows library resolution.
- 6.
- Otherwise, the dependency is unresolved.
- 1.
- If the dependency starts with @executable_path/, and an EXECUTABLES argument is in the process of being resolved, and replacing @executable_path/ with the directory of the executable yields an existing file, the dependency is resolved to that file.
- 2.
- Otherwise, if the dependency starts with @executable_path/, and there is a BUNDLE_EXECUTABLE argument, and replacing @executable_path/ with the directory of the bundle executable yields an existing file, the dependency is resolved to that file.
- 3.
- Otherwise, if the dependency starts with @loader_path/, and replacing @loader_path/ with the directory of the depending file yields an existing file, the dependency is resolved to that file.
- 4.
- Otherwise, if the dependency starts with @rpath/, and replacing @rpath/ with one of the RPATH entries of the depending file yields an existing file, the dependency is resolved to that file. Note that RPATH entries that start with @executable_path/ or @loader_path/ also have these items replaced with the appropriate path.
- 5.
- Otherwise, if the dependency is an absolute file that exists, the dependency is resolved to that file.
- 6.
- Otherwise, the dependency is unresolved.
- CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM
- Determines which operating system and executable format the files are built for. This could be one of several values:
- •
- linux+elf
- •
- windows+pe
- •
- macos+macho
- CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL
- Determines the tool to use for dependency resolution. It
could be one of several values, depending on the value of
CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM:
CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL linux+elf objdump windows+pe dumpbin windows+pe objdump macos+macho otool
- CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND
- Determines the path to the tool to use for dependency resolution. This is the actual path to objdump, dumpbin, or otool. If this variable is not specified, it is determined by the value of CMAKE_OBJDUMP if set, else by system introspection. New in version 3.18: Use CMAKE_OBJDUMP if set.
Writing
file(WRITE <filename> <content>...) file(APPEND <filename> <content>...)
file(TOUCH [<files>...]) file(TOUCH_NOCREATE [<files>...])
file(GENERATE OUTPUT output-file <INPUT input-file|CONTENT content> [CONDITION expression] [TARGET target] [NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS | FILE_PERMISSIONS <permissions>...] [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
- CONDITION <condition>
- Generate the output file for a particular configuration only if the condition is true. The condition must be either 0 or 1 after evaluating generator expressions.
- CONTENT <content>
- Use the content given explicitly as input.
- INPUT <input-file>
- Use the content from a given file as input. Changed in version 3.10: A relative path is treated with respect to the value of CMAKE_CURRENT_SOURCE_DIR. See policy CMP0070.
- OUTPUT <output-file>
- Specify the output file name to generate. Use generator expressions such as $<CONFIG> to specify a configuration-specific output file name. Multiple configurations may generate the same output file only if the generated content is identical. Otherwise, the <output-file> must evaluate to an unique name for each configuration. Changed in version 3.10: A relative path (after evaluating generator expressions) is treated with respect to the value of CMAKE_CURRENT_BINARY_DIR. See policy CMP0070.
- TARGET <target>
- New in version 3.19. Specify which target to use when evaluating generator expressions that require a target for evaluation (e.g. $<COMPILE_FEATURES:...>, $<TARGET_PROPERTY:prop>).
- NO_SOURCE_PERMISSIONS
- New in version 3.20. The generated file permissions default to the standard 644 value (-rw-r--r--).
- USE_SOURCE_PERMISSIONS
- New in version 3.20. Transfer the file permissions of the INPUT file to the generated file. This is already the default behavior if none of the three permissions-related keywords are given ( NO_SOURCE_PERMISSIONS, USE_SOURCE_PERMISSIONS or FILE_PERMISSIONS). The USE_SOURCE_PERMISSIONS keyword mostly serves as a way of making the intended behavior clearer at the call site. It is an error to specify this option without INPUT.
- FILE_PERMISSIONS <permissions>...
- New in version 3.20. Use the specified permissions for the generated file.
- NEWLINE_STYLE <style>
- New in version 3.20. Specify the newline style for the generated file. Specify UNIX or LF for \n newlines, or specify DOS, WIN32, or CRLF for \r\n newlines.
file(CONFIGURE OUTPUT output-file CONTENT content [ESCAPE_QUOTES] [@ONLY] [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
- OUTPUT <output-file>
- Specify the output file name to generate. A relative path is treated with respect to the value of CMAKE_CURRENT_BINARY_DIR. <output-file> does not support generator expressions.
- CONTENT <content>
- Use the content given explicitly as input. <content> does not support generator expressions.
- ESCAPE_QUOTES
- Escape any substituted quotes with backslashes (C-style).
- @ONLY
- Restrict variable replacement to references of the form @VAR@. This is useful for configuring scripts that use ${VAR} syntax.
- NEWLINE_STYLE <style>
- Specify the newline style for the output file. Specify UNIX or LF for \n newlines, or specify DOS, WIN32, or CRLF for \r\n newlines.
Filesystem
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>...])
We do not recommend using GLOB to collect a
list of source files from your source tree. If no CMakeLists.txt file changes
when a source is added or removed then the generated build system cannot know
when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not
work reliably on all generators, or if a new generator is added in the future
that cannot support it, projects using it will be stuck. Even if
CONFIGURE_DEPENDS works reliably, there is still a cost to perform the
check on every rebuild.
*.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
/dir/*.py - match all python files in /dir and subdirectories
file(MAKE_DIRECTORY [<directories>...])
file(REMOVE [<files>...]) file(REMOVE_RECURSE [<files>...])
file(RENAME <oldname> <newname> [RESULT <result>] [NO_REPLACE])
- RESULT <result>
- New in version 3.21. Set <result> variable to 0 on success or an error message otherwise. If RESULT is not specified and the operation fails, an error is emitted.
- NO_REPLACE
- New in version 3.21. If the <newname> path already exists, do not replace it. If RESULT <result> is used, the result variable will be set to NO_REPLACE. Otherwise, an error is emitted.
file(COPY_FILE <oldname> <newname> [RESULT <result>] [ONLY_IF_DIFFERENT])
- RESULT <result>
- Set <result> variable to 0 on success or an error message otherwise. If RESULT is not specified and the operation fails, an error is emitted.
- ONLY_IF_DIFFERENT
- If the <newname> path already exists, do not replace it if the file's contents are already the same as <oldname> (this avoids updating <newname>'s timestamp).
file(<COPY|INSTALL> <files>... DESTINATION <dir> [NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS] [FILE_PERMISSIONS <permissions>...] [DIRECTORY_PERMISSIONS <permissions>...] [FOLLOW_SYMLINK_CHAIN] [FILES_MATCHING] [[PATTERN <pattern> | REGEX <regex>] [EXCLUDE] [PERMISSIONS <permissions>...]] [...])
For a simple file copying operation, the
file(COPY_FILE) sub-command just above may be easier to use.
- •
- /opt/foo/lib/libfoo.so.1.2.3
- •
- /opt/foo/lib/libfoo.so.1.2 -> libfoo.so.1.2.3
- •
- /opt/foo/lib/libfoo.so.1 -> libfoo.so.1.2
- •
- /opt/foo/lib/libfoo.so -> libfoo.so.1
file(COPY /opt/foo/lib/libfoo.so DESTINATION lib FOLLOW_SYMLINK_CHAIN)
file(SIZE <filename> <variable>)
file(READ_SYMLINK <linkname> <variable>)
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])
file(CHMOD <files>... <directories>... [PERMISSIONS <permissions>...] [FILE_PERMISSIONS <permissions>...] [DIRECTORY_PERMISSIONS <permissions>...])
- PERMISSIONS
- All items are changed.
- FILE_PERMISSIONS
- Only files are changed.
- DIRECTORY_PERMISSIONS
- Only directories are changed.
- PERMISSIONS and FILE_PERMISSIONS
- FILE_PERMISSIONS overrides PERMISSIONS for files.
- PERMISSIONS and DIRECTORY_PERMISSIONS
- DIRECTORY_PERMISSIONS overrides PERMISSIONS for directories.
- FILE_PERMISSIONS and DIRECTORY_PERMISSIONS
- Use FILE_PERMISSIONS for files and DIRECTORY_PERMISSIONS for directories.
file(CHMOD_RECURSE <files>... <directories>... [PERMISSIONS <permissions>...] [FILE_PERMISSIONS <permissions>...] [DIRECTORY_PERMISSIONS <permissions>...])
Path Conversion
file(REAL_PATH <path> <out-var> [BASE_DIRECTORY <dir>] [EXPAND_TILDE])
- BASE_DIRECTORY <dir>
- If the provided <path> 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.
- EXPAND_TILDE
- New in version 3.21. If the <path> is ~ or starts with ~/, the ~ is replaced by the user's home directory. The path to the home directory is obtained from environment variables. On Windows, the USERPROFILE environment variable is used, falling back to the HOME environment variable if USERPROFILE is not defined. On all other platforms, only HOME is used.
file(RELATIVE_PATH <variable> <directory> <file>)
file(TO_CMAKE_PATH "<path>" <variable>) file(TO_NATIVE_PATH "<path>" <variable>)
Transfer
file(DOWNLOAD <url> [<file>] [<options>...]) file(UPLOAD <file> <url> [<options>...])
- INACTIVITY_TIMEOUT <seconds>
- Terminate the operation after a period of inactivity.
- LOG <variable>
- Store a human-readable log of the operation in a variable.
- SHOW_PROGRESS
- Print progress information as status messages until the operation is complete.
- STATUS <variable>
- Store the resulting status of the operation in a variable. The status is a ; separated list of length 2. The first element is the numeric return value for the operation, and the second element is a string value for the error. A 0 numeric error means no error in the operation.
- TIMEOUT <seconds>
- Terminate the operation after a given total time has elapsed.
- USERPWD <username>:<password>
- New in version 3.7. Set username and password for operation.
- HTTPHEADER <HTTP-header>
- New in version 3.7. HTTP header for operation. Suboption can be repeated several times.
- NETRC <level>
- New in version 3.11. Specify whether the .netrc file is to be used for operation. If this option is not specified, the value of the CMAKE_NETRC variable will be used instead. Valid levels are:
- IGNORED
- The .netrc file is ignored. This is the default.
- OPTIONAL
- The .netrc file is optional, and information in the URL is preferred. The file will be scanned to find which ever information is not specified in the URL.
- REQUIRED
- The .netrc file is required, and information in the URL is ignored.
- NETRC_FILE <file>
- New in version 3.11. Specify an alternative .netrc file to the one in your home directory, if the NETRC level is OPTIONAL or REQUIRED. If this option is not specified, the value of the CMAKE_NETRC_FILE variable will be used instead.
- TLS_VERIFY <ON|OFF>
- Specify whether to verify the server certificate for https:// URLs. The default is to not verify. If this option is not specified, the value of the CMAKE_TLS_VERIFY variable will be used instead. New in version 3.18: Added support to file(UPLOAD).
- TLS_CAINFO <file>
- Specify a custom Certificate Authority file for https:// URLs. If this option is not specified, the value of the CMAKE_TLS_CAINFO variable will be used instead. New in version 3.18: Added support to file(UPLOAD).
Verify that the downloaded content hash
matches the expected value, where ALGO is one of the algorithms
supported by file(<HASH>). If the file already exists and matches
the hash, the download is skipped. If the file already exists and does not
match the hash, the file is downloaded again. If after download the file does
not match the hash, the operation fails with an error. It is an error to
specify this option if DOWNLOAD is not given a
<file>.
- EXPECTED_MD5 <value>
- Historical short-hand for EXPECTED_HASH MD5=<value>. It is an error to specify this if DOWNLOAD is not given a <file>.
- RANGE_START <value>
- New in version 3.24. Offset of the start of the range in file in bytes. Could be omitted to download up to the specified RANGE_END.
- RANGE_END <value>
- New in version 3.24. Offset of the end of the range in file in bytes. Could be omitted to download everything from the specified RANGE_START to the end of file.
Locking
file(LOCK <path> [DIRECTORY] [RELEASE] [GUARD <FUNCTION|FILE|PROCESS>] [RESULT_VARIABLE <variable>] [TIMEOUT <seconds>])
Archiving
file(ARCHIVE_CREATE OUTPUT <archive> PATHS <paths>... [FORMAT <format>] [COMPRESSION <compression> [COMPRESSION_LEVEL <compression-level>]] [MTIME <mtime>] [VERBOSE])
With FORMAT set to raw only one
file will be compressed with the compression type specified by
COMPRESSION.
file(ARCHIVE_EXTRACT INPUT <archive> [DESTINATION <dir>] [PATTERNS <patterns>...] [LIST_ONLY] [VERBOSE] [TOUCH])
find_file
A short-hand signature is:find_file (<VAR> name1 [path1 path2 ...])
find_file ( <VAR> name | NAMES name1 [name2 ...] [HINTS [path | ENV var]... ] [PATHS [path | ENV var]... ] [REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)] [PATH_SUFFIXES suffix1 [suffix2 ...]] [VALIDATOR function] [DOC "cache documentation string"] [NO_CACHE] [REQUIRED] [NO_DEFAULT_PATH] [NO_PACKAGE_ROOT_PATH] [NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH] [NO_SYSTEM_ENVIRONMENT_PATH] [NO_CMAKE_SYSTEM_PATH] [NO_CMAKE_INSTALL_PREFIX] [CMAKE_FIND_ROOT_PATH_BOTH | ONLY_CMAKE_FIND_ROOT_PATH | NO_CMAKE_FIND_ROOT_PATH] )
- NAMES
- Specify one or more possible names for the full path to a file. 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.
- HINTS, PATHS
- Specify directories to search in addition to the default locations. The ENV var sub-option reads paths from a system environment variable. Changed in version 3.24: On Windows platform, it is possible to include registry queries as part of the directories, using a dedicated syntax. Such specifications will be ignored on all other platforms.
- REGISTRY_VIEW
- New in version 3.24. Specify which registry views must be queried. This option is only meaningful on Windows platforms and will be ignored on other ones. When not specified, the TARGET view is used when the CMP0134 policy is NEW. Refer to CMP0134 for the default view when the policy is OLD.
- 64
- Query the 64-bit registry. On 32-bit Windows, it always returns the string /REGISTRY-NOTFOUND.
- 32
- Query the 32-bit registry.
- 64_32
- Query both views (64 and 32) and generate a path for each.
- 32_64
- Query both views (32 and 64) and generate a path for each.
- HOST
- Query the registry matching the architecture of the host: 64 on 64-bit Windows and 32 on 32-bit Windows.
- TARGET
- Query the registry matching the architecture specified by the CMAKE_SIZEOF_VOID_P variable. If not defined, fall back to HOST view.
- BOTH
- Query both views (32 and 64). The order depends on the following rules: If the CMAKE_SIZEOF_VOID_P variable is defined, use the following view depending on the content of this variable:
- •
- 8: 64_32
- •
- 4: 32_64
- •
- 64-bit: 64_32
- •
- 32-bit: 32
- PATH_SUFFIXES
- Specify additional subdirectories to check below each directory location otherwise considered.
- VALIDATOR
- New in version 3.25. Specify a function() to be called for each candidate item found (a macro() cannot be provided, that will result in an error). Two arguments will be passed to the validator function: the name of a result variable, and the absolute path to the candidate item. The item will be accepted and the search will end unless the function sets the value in the result variable to false in the calling scope. The result variable will hold a true value when the validator function is entered.
function(my_check validator_result_var item) if(NOT item MATCHES ...) set(${validator_result_var} FALSE PARENT_SCOPE) endif() endfunction() find_file (result NAMES ... VALIDATOR my_check)
- DOC
- Specify the documentation string for the <VAR> cache entry.
- NO_CACHE
- New in version 3.21. The result of the search will be stored in a normal variable rather than a cache entry. NOTE:
If the variable is already set before the call
(as a normal or cache variable) then the search will not occur.
This option should be used with caution
because it can greatly increase the cost of repeated configure steps.
- REQUIRED
- New in version 3.18. Stop 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.
- 1.
- New in version 3.12: If called from within a find module or any other script loaded by a call to find_package(<PackageName>), search prefixes unique to the current package being found. Specifically, look in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable. The package root variables are maintained as a stack, so if called from nested find modules or config packages, root paths from the parent's find module or config package will be searched after paths from the current module or package. In other words, the search order would be <CurrentPackage>_ROOT, ENV{<CurrentPackage>_ROOT}, <ParentPackage>_ROOT, ENV{<ParentPackage>_ROOT}, etc. This can be skipped if NO_PACKAGE_ROOT_PATH is passed or by setting the CMAKE_FIND_USE_PACKAGE_ROOT_PATH to FALSE. See policy CMP0074.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable if called from within a find module loaded by find_package(<PackageName>)
- 2.
- Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. The values are interpreted as semicolon-separated lists. This can be skipped if NO_CMAKE_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_PATH to FALSE.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_INCLUDE_PATH
- •
- CMAKE_FRAMEWORK_PATH
- 3.
- Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration, and therefore use the host's native path separator ( ; on Windows and : on UNIX). This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH to FALSE.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_INCLUDE_PATH
- •
- CMAKE_FRAMEWORK_PATH
- 4.
- Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.
- 5.
- Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH to FALSE.
- •
- The directories in INCLUDE and PATH.
- •
- On Windows hosts: <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix>/[s]bin in PATH, and <entry>/include for other entries in PATH.
- 6.
- Search cmake variables defined in the Platform files for the current system. The searching of CMAKE_INSTALL_PREFIX and CMAKE_STAGING_PREFIX can be skipped if NO_CMAKE_INSTALL_PREFIX is passed or by setting the CMAKE_FIND_USE_INSTALL_PREFIX to FALSE. All these locations can be skipped if NO_CMAKE_SYSTEM_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_SYSTEM_PATH to FALSE.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
- •
- CMAKE_SYSTEM_INCLUDE_PATH
- •
- CMAKE_SYSTEM_FRAMEWORK_PATH
- 7.
- Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
- CMAKE_FIND_ROOT_PATH_BOTH
- Search in the order described above.
- NO_CMAKE_FIND_ROOT_PATH
- Do not use the CMAKE_FIND_ROOT_PATH variable.
- ONLY_CMAKE_FIND_ROOT_PATH
- Search only the re-rooted directories and directories below CMAKE_STAGING_PREFIX.
find_file (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_file (<VAR> NAMES name)
find_library
A short-hand signature is:find_library (<VAR> name1 [path1 path2 ...])
find_library ( <VAR> name | NAMES name1 [name2 ...] [NAMES_PER_DIR] [HINTS [path | ENV var]... ] [PATHS [path | ENV var]... ] [REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)] [PATH_SUFFIXES suffix1 [suffix2 ...]] [VALIDATOR function] [DOC "cache documentation string"] [NO_CACHE] [REQUIRED] [NO_DEFAULT_PATH] [NO_PACKAGE_ROOT_PATH] [NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH] [NO_SYSTEM_ENVIRONMENT_PATH] [NO_CMAKE_SYSTEM_PATH] [NO_CMAKE_INSTALL_PREFIX] [CMAKE_FIND_ROOT_PATH_BOTH | ONLY_CMAKE_FIND_ROOT_PATH | NO_CMAKE_FIND_ROOT_PATH] )
- NAMES
- Specify one or more possible names for the library. 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.
- HINTS, PATHS
- Specify directories to search in addition to the default locations. The ENV var sub-option reads paths from a system environment variable. Changed in version 3.24: On Windows platform, it is possible to include registry queries as part of the directories, using a dedicated syntax. Such specifications will be ignored on all other platforms.
- REGISTRY_VIEW
- New in version 3.24. Specify which registry views must be queried. This option is only meaningful on Windows platforms and will be ignored on other ones. When not specified, the TARGET view is used when the CMP0134 policy is NEW. Refer to CMP0134 for the default view when the policy is OLD.
- 64
- Query the 64-bit registry. On 32-bit Windows, it always returns the string /REGISTRY-NOTFOUND.
- 32
- Query the 32-bit registry.
- 64_32
- Query both views (64 and 32) and generate a path for each.
- 32_64
- Query both views (32 and 64) and generate a path for each.
- HOST
- Query the registry matching the architecture of the host: 64 on 64-bit Windows and 32 on 32-bit Windows.
- TARGET
- Query the registry matching the architecture specified by the CMAKE_SIZEOF_VOID_P variable. If not defined, fall back to HOST view.
- BOTH
- Query both views (32 and 64). The order depends on the following rules: If the CMAKE_SIZEOF_VOID_P variable is defined, use the following view depending on the content of this variable:
- •
- 8: 64_32
- •
- 4: 32_64
- •
- 64-bit: 64_32
- •
- 32-bit: 32
- PATH_SUFFIXES
- Specify additional subdirectories to check below each directory location otherwise considered.
- VALIDATOR
- New in version 3.25. Specify a function() to be called for each candidate item found (a macro() cannot be provided, that will result in an error). Two arguments will be passed to the validator function: the name of a result variable, and the absolute path to the candidate item. The item will be accepted and the search will end unless the function sets the value in the result variable to false in the calling scope. The result variable will hold a true value when the validator function is entered.
function(my_check validator_result_var item) if(NOT item MATCHES ...) set(${validator_result_var} FALSE PARENT_SCOPE) endif() endfunction() find_library (result NAMES ... VALIDATOR my_check)
- DOC
- Specify the documentation string for the <VAR> cache entry.
- NO_CACHE
- New in version 3.21. The result of the search will be stored in a normal variable rather than a cache entry. NOTE:
If the variable is already set before the call
(as a normal or cache variable) then the search will not occur.
This option should be used with caution
because it can greatly increase the cost of repeated configure steps.
- REQUIRED
- New in version 3.18. Stop 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.
- 1.
- New in version 3.12: If called from within a find module or any other script loaded by a call to find_package(<PackageName>), search prefixes unique to the current package being found. Specifically, look in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable. The package root variables are maintained as a stack, so if called from nested find modules or config packages, root paths from the parent's find module or config package will be searched after paths from the current module or package. In other words, the search order would be <CurrentPackage>_ROOT, ENV{<CurrentPackage>_ROOT}, <ParentPackage>_ROOT, ENV{<ParentPackage>_ROOT}, etc. This can be skipped if NO_PACKAGE_ROOT_PATH is passed or by setting the CMAKE_FIND_USE_PACKAGE_ROOT_PATH to FALSE. See policy CMP0074.
- •
- <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/lib for each <prefix> in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable if called from within a find module loaded by find_package(<PackageName>)
- 2.
- Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. The values are interpreted as semicolon-separated lists. This can be skipped if NO_CMAKE_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_PATH to FALSE.
- •
- <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/lib for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_LIBRARY_PATH
- •
- CMAKE_FRAMEWORK_PATH
- 3.
- Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration, and therefore use the host's native path separator ( ; on Windows and : on UNIX). This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH to FALSE.
- •
- <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/lib for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_LIBRARY_PATH
- •
- CMAKE_FRAMEWORK_PATH
- 4.
- Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.
- 5.
- Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH to FALSE.
- •
- The directories in LIB and PATH.
- •
- On Windows hosts: <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/lib for each <prefix>/[s]bin in PATH, and <entry>/lib for other entries in PATH.
- 6.
- Search cmake variables defined in the Platform files for the current system. The searching of CMAKE_INSTALL_PREFIX and CMAKE_STAGING_PREFIX can be skipped if NO_CMAKE_INSTALL_PREFIX is passed or by setting the CMAKE_FIND_USE_INSTALL_PREFIX to FALSE. All these locations can be skipped if NO_CMAKE_SYSTEM_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_SYSTEM_PATH to FALSE.
- •
- <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/lib for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
- •
- CMAKE_SYSTEM_LIBRARY_PATH
- •
- CMAKE_SYSTEM_FRAMEWORK_PATH
- 7.
- Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
- CMAKE_FIND_ROOT_PATH_BOTH
- Search in the order described above.
- NO_CMAKE_FIND_ROOT_PATH
- Do not use the CMAKE_FIND_ROOT_PATH variable.
- ONLY_CMAKE_FIND_ROOT_PATH
- Search only the re-rooted directories and directories below CMAKE_STAGING_PREFIX.
find_library (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_library (<VAR> NAMES name)
find_package
NOTE:The Using Dependencies Guide provides a
high-level introduction to this general topic. It provides a broader overview
of where the find_package() command fits into the bigger picture,
including its relationship to the FetchContent module. The guide is
recommended pre-reading before moving on to the details below.
Search Modes
The command has a few modes by which it searches for packages:- Module mode
- In this mode, CMake searches for a file called Find<PackageName>.cmake, looking first in the locations listed 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 Find module's documentation. The Find<PackageName>.cmake file is not typically provided by the package itself. Rather, it is normally provided by something external to the package, such as the operating system, CMake itself, or even the project from which the find_package() command was called. Being externally provided, Find Modules tend to be heuristic in nature and are susceptible to becoming out-of-date. They typically search for certain libraries, files and other package artifacts. Module mode is only supported by the basic command signature.
- Config mode
- In this mode, CMake searches for a file called <lowercasePackageName>-config.cmake or <PackageName>Config.cmake. It will also look for <lowercasePackageName>-config-version.cmake or <PackageName>ConfigVersion.cmake if version details were specified (see Config Mode Version Selection for an explanation of how these separate version files are used). In config mode, the command can be given a list of names to search for as package names. The locations where CMake searches for the config and version files is considerably more complicated than for Module mode (see Config Mode Search Procedure). The config and version files are typically installed as part of the package, so they tend to be more reliable than Find modules. They usually contain direct knowledge of the package contents, so no searching or heuristics are needed within the config or version files themselves. Config mode is supported by both the basic and full command signatures.
- FetchContent redirection mode
- New in version 3.24: A call to find_package() can be redirected internally to a package provided by the FetchContent module. To the caller, the behavior will appear similar to Config mode, except that the search logic is by-passed and the component information is not used. See FetchContent_Declare() and FetchContent_MakeAvailable() for further details.
Basic Signature
find_package(<PackageName> [version] [EXACT] [QUIET] [MODULE] [REQUIRED] [[COMPONENTS] [components...]] [OPTIONAL_COMPONENTS components...] [REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)] [GLOBAL] [NO_POLICY_SCOPE] [BYPASS_PROVIDER])
- •
- A single version with the format major[.minor[.patch[.tweak]]], where each component is a numeric value.
- •
- A version range with the format versionMin...[<]versionMax where versionMin and versionMax have the same format and constraints on components being integers as the single version. By default, both end points are included. By specifying <, the upper end point will be excluded. Version ranges are only supported with CMake 3.19 or later.
Full Signature
find_package(<PackageName> [version] [EXACT] [QUIET] [REQUIRED] [[COMPONENTS] [components...]] [OPTIONAL_COMPONENTS components...] [CONFIG|NO_MODULE] [GLOBAL] [NO_POLICY_SCOPE] [BYPASS_PROVIDER] [NAMES name1 [name2 ...]] [CONFIGS config1 [config2 ...]] [HINTS path1 [path2 ... ]] [PATHS path1 [path2 ... ]] [REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)] [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_INSTALL_PREFIX] [NO_CMAKE_SYSTEM_PACKAGE_REGISTRY] [CMAKE_FIND_ROOT_PATH_BOTH | ONLY_CMAKE_FIND_ROOT_PATH | NO_CMAKE_FIND_ROOT_PATH])
Config Mode Search Procedure
NOTE:When Config mode is used, this search
procedure is applied regardless of whether the full or basic
signature was given.
Entry | Convention |
<prefix>/ | W |
<prefix>/(cmake|CMake)/ | W |
<prefix>/<name>*/ | W |
<prefix>/<name>*/(cmake|CMake)/ | W |
<prefix>/<name>*/(cmake|CMake)/<name>*/ [1] | 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 |
- [1]
- New in version 3.25.
On systems supporting macOS FRAMEWORK and BUNDLE, the
following directories are searched for Frameworks or Application Bundles
containing a configuration file:
Entry Convention <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
- •
- Paths with lib64 are searched on 64 bit platforms if the FIND_LIBRARY_USE_LIB64_PATHS property is set to TRUE.
- •
- Paths with lib32 are searched on 32 bit platforms if the FIND_LIBRARY_USE_LIB32_PATHS property is set to TRUE.
- •
- Paths with libx32 are searched on platforms using the x32 ABI if the FIND_LIBRARY_USE_LIBX32_PATHS property is set to TRUE.
- •
- The lib path is always searched.
- 64
- Query the 64-bit registry. On 32-bit Windows, it always returns the string /REGISTRY-NOTFOUND.
- 32
- Query the 32-bit registry.
- 64_32
- Query both views (64 and 32) and generate a path for each.
- 32_64
- Query both views (32 and 64) and generate a path for each.
- HOST
- Query the registry matching the architecture of the host: 64 on 64-bit Windows and 32 on 32-bit Windows.
- TARGET
- Query the registry matching the architecture specified by the CMAKE_SIZEOF_VOID_P variable. If not defined, fall back to HOST view.
- BOTH
- Query both views (32 and 64). The order depends on the following rules: If the CMAKE_SIZEOF_VOID_P variable is defined, use the following view depending on the content of this variable:
- •
- 8: 64_32
- •
- 4: 32_64
- •
- 64-bit: 64_32
- •
- 32-bit: 32
- 1.
- New in version 3.12: Search paths specified in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable, where <PackageName> is the package to be found. The package root variables are maintained as a stack so if called from within a find module, root paths from the parent's find module will also be searched after paths for the current package. This can be skipped if NO_PACKAGE_ROOT_PATH is passed or by setting the CMAKE_FIND_USE_PACKAGE_ROOT_PATH to FALSE. See policy CMP0074.
- 2.
- Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=VALUE. The values are interpreted as semicolon-separated lists. This can be skipped if NO_CMAKE_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_PATH to FALSE:
- •
- CMAKE_PREFIX_PATH
- •
- CMAKE_FRAMEWORK_PATH
- •
- CMAKE_APPBUNDLE_PATH
- 3.
- Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration, and therefore use the host's native path separator ( ; on Windows and : on UNIX). This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH to FALSE:
- •
- <PackageName>_DIR
- •
- CMAKE_PREFIX_PATH
- •
- CMAKE_FRAMEWORK_PATH
- •
- CMAKE_APPBUNDLE_PATH
- 4.
- Search paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.
- 5.
- Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH to FALSE. Path entries ending in /bin or /sbin are automatically converted to their parent directories:
- •
- PATH
- 6.
- Search paths stored in the CMake User Package Registry. This can be skipped if NO_CMAKE_PACKAGE_REGISTRY is passed or by setting the variable CMAKE_FIND_USE_PACKAGE_REGISTRY to FALSE or the deprecated variable CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY to TRUE. See the cmake-packages(7) manual for details on the user package registry.
- 7.
- Search cmake variables defined in the Platform files for the current system. The searching of CMAKE_INSTALL_PREFIX and CMAKE_STAGING_PREFIX can be skipped if NO_CMAKE_INSTALL_PREFIX is passed or by setting the CMAKE_FIND_USE_INSTALL_PREFIX to FALSE. All these locations can be skipped if NO_CMAKE_SYSTEM_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_SYSTEM_PATH to FALSE:
- •
- CMAKE_SYSTEM_PREFIX_PATH
- •
- CMAKE_SYSTEM_FRAMEWORK_PATH
- •
- CMAKE_SYSTEM_APPBUNDLE_PATH
- 8.
- Search paths stored in the CMake System Package Registry. This can be skipped if NO_CMAKE_SYSTEM_PACKAGE_REGISTRY is passed or by setting the CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY variable to FALSE or the deprecated variable CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY to TRUE. See the cmake-packages(7) manual for details on the system package registry.
- 9.
- Search paths specified by the PATHS option. These are typically hard-coded guesses.
- CMAKE_FIND_ROOT_PATH_BOTH
- Search in the order described above.
- NO_CMAKE_FIND_ROOT_PATH
- Do not use the CMAKE_FIND_ROOT_PATH variable.
- ONLY_CMAKE_FIND_ROOT_PATH
- Search only the re-rooted directories and directories below CMAKE_STAGING_PREFIX.
find_package (<PackageName> PATHS paths... NO_DEFAULT_PATH) find_package (<PackageName>)
- •
- Setting the CMAKE_DISABLE_FIND_PACKAGE_<PackageName> variable to TRUE disables the package. This also disables redirection to a package provided by FetchContent.
- •
- Setting the CMAKE_REQUIRE_FIND_PACKAGE_<PackageName> variable to TRUE makes the package REQUIRED.
Config Mode Version Selection
NOTE:When Config mode is used, this version
selection process is applied regardless of whether the full or
basic signature was given.
- PACKAGE_FIND_NAME
- The <PackageName>
- PACKAGE_FIND_VERSION
- Full requested version string
- PACKAGE_FIND_VERSION_MAJOR
- Major version if requested, else 0
- PACKAGE_FIND_VERSION_MINOR
- Minor version if requested, else 0
- PACKAGE_FIND_VERSION_PATCH
- Patch version if requested, else 0
- PACKAGE_FIND_VERSION_TWEAK
- Tweak version if requested, else 0
- PACKAGE_FIND_VERSION_COUNT
- Number of version components, 0 to 4
- PACKAGE_FIND_VERSION_RANGE
- Full requested version range string
- PACKAGE_FIND_VERSION_RANGE_MIN
- This specifies whether the lower end point of the version range should be included or excluded. Currently, the only supported value for this variable is INCLUDE.
- PACKAGE_FIND_VERSION_RANGE_MAX
- This specifies whether the upper end point of the version range should be included or excluded. The supported values for this variable are INCLUDE and EXCLUDE.
- PACKAGE_FIND_VERSION_MIN
- Full requested version string of the lower end point of the range
- PACKAGE_FIND_VERSION_MIN_MAJOR
- Major version of the lower end point if requested, else 0
- PACKAGE_FIND_VERSION_MIN_MINOR
- Minor version of the lower end point if requested, else 0
- PACKAGE_FIND_VERSION_MIN_PATCH
- Patch version of the lower end point if requested, else 0
- PACKAGE_FIND_VERSION_MIN_TWEAK
- Tweak version of the lower end point if requested, else 0
- PACKAGE_FIND_VERSION_MIN_COUNT
- Number of version components of the lower end point, 0 to 4
- PACKAGE_FIND_VERSION_MAX
- Full requested version string of the upper end point of the range
- PACKAGE_FIND_VERSION_MAX_MAJOR
- Major version of the upper end point if requested, else 0
- PACKAGE_FIND_VERSION_MAX_MINOR
- Minor version of the upper end point if requested, else 0
- PACKAGE_FIND_VERSION_MAX_PATCH
- Patch version of the upper end point if requested, else 0
- PACKAGE_FIND_VERSION_MAX_TWEAK
- Tweak version of the upper end point if requested, else 0
- PACKAGE_FIND_VERSION_MAX_COUNT
- Number of version components of the upper end point, 0 to 4
- PACKAGE_VERSION
- Full provided version string
- PACKAGE_VERSION_EXACT
- True if version is exact match
- PACKAGE_VERSION_COMPATIBLE
- True if version is compatible
- PACKAGE_VERSION_UNSUITABLE
- True if unsuitable as any version
- <PackageName>_VERSION
- Full provided version string
- <PackageName>_VERSION_MAJOR
- Major version if provided, else 0
- <PackageName>_VERSION_MINOR
- Minor version if provided, else 0
- <PackageName>_VERSION_PATCH
- Patch version if provided, else 0
- <PackageName>_VERSION_TWEAK
- Tweak version if provided, else 0
- <PackageName>_VERSION_COUNT
- Number of version components, 0 to 4
SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL) SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
Package File Interface Variables
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):- CMAKE_FIND_PACKAGE_NAME
- The <PackageName> which is searched for
- <PackageName>_FIND_REQUIRED
- True if REQUIRED option was given
- <PackageName>_FIND_QUIETLY
- True if QUIET option was given
- <PackageName>_FIND_REGISTRY_VIEW
- The requested view if REGISTRY_VIEW option was given
- <PackageName>_FIND_VERSION
- Full requested version string
- <PackageName>_FIND_VERSION_MAJOR
- Major version if requested, else 0
- <PackageName>_FIND_VERSION_MINOR
- Minor version if requested, else 0
- <PackageName>_FIND_VERSION_PATCH
- Patch version if requested, else 0
- <PackageName>_FIND_VERSION_TWEAK
- Tweak version if requested, else 0
- <PackageName>_FIND_VERSION_COUNT
- Number of version components, 0 to 4
- <PackageName>_FIND_VERSION_EXACT
- True if EXACT option was given
- <PackageName>_FIND_COMPONENTS
- List of specified components (required and optional)
- <PackageName>_FIND_REQUIRED_<c>
- True if component <c> is required, false if component <c> is optional
- <PackageName>_FIND_VERSION_RANGE
- Full requested version range string
- <PackageName>_FIND_VERSION_RANGE_MIN
- This specifies whether the lower end point of the version range is included or excluded. Currently, INCLUDE is the only supported value.
- <PackageName>_FIND_VERSION_RANGE_MAX
- This specifies whether the upper end point of the version range is included or excluded. The possible values for this variable are INCLUDE or EXCLUDE.
- <PackageName>_FIND_VERSION_MIN
- Full requested version string of the lower end point of the range
- <PackageName>_FIND_VERSION_MIN_MAJOR
- Major version of the lower end point if requested, else 0
- <PackageName>_FIND_VERSION_MIN_MINOR
- Minor version of the lower end point if requested, else 0
- <PackageName>_FIND_VERSION_MIN_PATCH
- Patch version of the lower end point if requested, else 0
- <PackageName>_FIND_VERSION_MIN_TWEAK
- Tweak version of the lower end point if requested, else 0
- <PackageName>_FIND_VERSION_MIN_COUNT
- Number of version components of the lower end point, 0 to 4
- <PackageName>_FIND_VERSION_MAX
- Full requested version string of the upper end point of the range
- <PackageName>_FIND_VERSION_MAX_MAJOR
- Major version of the upper end point if requested, else 0
- <PackageName>_FIND_VERSION_MAX_MINOR
- Minor version of the upper end point if requested, else 0
- <PackageName>_FIND_VERSION_MAX_PATCH
- Patch version of the upper end point if requested, else 0
- <PackageName>_FIND_VERSION_MAX_TWEAK
- Tweak version of the upper end point if requested, else 0
- <PackageName>_FIND_VERSION_MAX_COUNT
- Number of version components of the upper end point, 0 to 4
find_path
A short-hand signature is:find_path (<VAR> name1 [path1 path2 ...])
find_path ( <VAR> name | NAMES name1 [name2 ...] [HINTS [path | ENV var]... ] [PATHS [path | ENV var]... ] [REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)] [PATH_SUFFIXES suffix1 [suffix2 ...]] [VALIDATOR function] [DOC "cache documentation string"] [NO_CACHE] [REQUIRED] [NO_DEFAULT_PATH] [NO_PACKAGE_ROOT_PATH] [NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH] [NO_SYSTEM_ENVIRONMENT_PATH] [NO_CMAKE_SYSTEM_PATH] [NO_CMAKE_INSTALL_PREFIX] [CMAKE_FIND_ROOT_PATH_BOTH | ONLY_CMAKE_FIND_ROOT_PATH | NO_CMAKE_FIND_ROOT_PATH] )
- NAMES
- Specify one or more possible names for the file in a directory. 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.
- HINTS, PATHS
- Specify directories to search in addition to the default locations. The ENV var sub-option reads paths from a system environment variable. Changed in version 3.24: On Windows platform, it is possible to include registry queries as part of the directories, using a dedicated syntax. Such specifications will be ignored on all other platforms.
- REGISTRY_VIEW
- New in version 3.24. Specify which registry views must be queried. This option is only meaningful on Windows platforms and will be ignored on other ones. When not specified, the TARGET view is used when the CMP0134 policy is NEW. Refer to CMP0134 for the default view when the policy is OLD.
- 64
- Query the 64-bit registry. On 32-bit Windows, it always returns the string /REGISTRY-NOTFOUND.
- 32
- Query the 32-bit registry.
- 64_32
- Query both views (64 and 32) and generate a path for each.
- 32_64
- Query both views (32 and 64) and generate a path for each.
- HOST
- Query the registry matching the architecture of the host: 64 on 64-bit Windows and 32 on 32-bit Windows.
- TARGET
- Query the registry matching the architecture specified by the CMAKE_SIZEOF_VOID_P variable. If not defined, fall back to HOST view.
- BOTH
- Query both views (32 and 64). The order depends on the following rules: If the CMAKE_SIZEOF_VOID_P variable is defined, use the following view depending on the content of this variable:
- •
- 8: 64_32
- •
- 4: 32_64
- •
- 64-bit: 64_32
- •
- 32-bit: 32
- PATH_SUFFIXES
- Specify additional subdirectories to check below each directory location otherwise considered.
- VALIDATOR
- New in version 3.25. Specify a function() to be called for each candidate item found (a macro() cannot be provided, that will result in an error). Two arguments will be passed to the validator function: the name of a result variable, and the absolute path to the candidate item. The item will be accepted and the search will end unless the function sets the value in the result variable to false in the calling scope. The result variable will hold a true value when the validator function is entered.
function(my_check validator_result_var item) if(NOT item MATCHES ...) set(${validator_result_var} FALSE PARENT_SCOPE) endif() endfunction() find_path (result NAMES ... VALIDATOR my_check)
- DOC
- Specify the documentation string for the <VAR> cache entry.
- NO_CACHE
- New in version 3.21. The result of the search will be stored in a normal variable rather than a cache entry. NOTE:
If the variable is already set before the call
(as a normal or cache variable) then the search will not occur.
This option should be used with caution
because it can greatly increase the cost of repeated configure steps.
- REQUIRED
- New in version 3.18. Stop 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.
- 1.
- New in version 3.12: If called from within a find module or any other script loaded by a call to find_package(<PackageName>), search prefixes unique to the current package being found. Specifically, look in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable. The package root variables are maintained as a stack, so if called from nested find modules or config packages, root paths from the parent's find module or config package will be searched after paths from the current module or package. In other words, the search order would be <CurrentPackage>_ROOT, ENV{<CurrentPackage>_ROOT}, <ParentPackage>_ROOT, ENV{<ParentPackage>_ROOT}, etc. This can be skipped if NO_PACKAGE_ROOT_PATH is passed or by setting the CMAKE_FIND_USE_PACKAGE_ROOT_PATH to FALSE. See policy CMP0074.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable if called from within a find module loaded by find_package(<PackageName>)
- 2.
- Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. The values are interpreted as semicolon-separated lists. This can be skipped if NO_CMAKE_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_PATH to FALSE.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_INCLUDE_PATH
- •
- CMAKE_FRAMEWORK_PATH
- 3.
- Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration, and therefore use the host's native path separator ( ; on Windows and : on UNIX). This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH to FALSE.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_INCLUDE_PATH
- •
- CMAKE_FRAMEWORK_PATH
- 4.
- Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.
- 5.
- Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH to FALSE.
- •
- The directories in INCLUDE and PATH.
- •
- On Windows hosts: <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix>/[s]bin in PATH, and <entry>/include for other entries in PATH.
- 6.
- Search cmake variables defined in the Platform files for the current system. The searching of CMAKE_INSTALL_PREFIX and CMAKE_STAGING_PREFIX can be skipped if NO_CMAKE_INSTALL_PREFIX is passed or by setting the CMAKE_FIND_USE_INSTALL_PREFIX to FALSE. All these locations can be skipped if NO_CMAKE_SYSTEM_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_SYSTEM_PATH to FALSE.
- •
- <prefix>/include/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and <prefix>/include for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
- •
- CMAKE_SYSTEM_INCLUDE_PATH
- •
- CMAKE_SYSTEM_FRAMEWORK_PATH
- 7.
- Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
- CMAKE_FIND_ROOT_PATH_BOTH
- Search in the order described above.
- NO_CMAKE_FIND_ROOT_PATH
- Do not use the CMAKE_FIND_ROOT_PATH variable.
- ONLY_CMAKE_FIND_ROOT_PATH
- Search only the re-rooted directories and directories below CMAKE_STAGING_PREFIX.
find_path (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_path (<VAR> NAMES name)
find_program
A short-hand signature is:find_program (<VAR> name1 [path1 path2 ...])
find_program ( <VAR> name | NAMES name1 [name2 ...] [NAMES_PER_DIR] [HINTS [path | ENV var]... ] [PATHS [path | ENV var]... ] [REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)] [PATH_SUFFIXES suffix1 [suffix2 ...]] [VALIDATOR function] [DOC "cache documentation string"] [NO_CACHE] [REQUIRED] [NO_DEFAULT_PATH] [NO_PACKAGE_ROOT_PATH] [NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH] [NO_SYSTEM_ENVIRONMENT_PATH] [NO_CMAKE_SYSTEM_PATH] [NO_CMAKE_INSTALL_PREFIX] [CMAKE_FIND_ROOT_PATH_BOTH | ONLY_CMAKE_FIND_ROOT_PATH | NO_CMAKE_FIND_ROOT_PATH] )
- NAMES
- Specify one or more possible names for the program. 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.
- HINTS, PATHS
- Specify directories to search in addition to the default locations. The ENV var sub-option reads paths from a system environment variable. Changed in version 3.24: On Windows platform, it is possible to include registry queries as part of the directories, using a dedicated syntax. Such specifications will be ignored on all other platforms.
- REGISTRY_VIEW
- New in version 3.24. Specify which registry views must be queried. This option is only meaningful on Windows platforms and will be ignored on other ones. When not specified, the BOTH view is used when the CMP0134 policy is NEW. Refer to CMP0134 for the default view when the policy is OLD.
- 64
- Query the 64-bit registry. On 32-bit Windows, it always returns the string /REGISTRY-NOTFOUND.
- 32
- Query the 32-bit registry.
- 64_32
- Query both views (64 and 32) and generate a path for each.
- 32_64
- Query both views (32 and 64) and generate a path for each.
- HOST
- Query the registry matching the architecture of the host: 64 on 64-bit Windows and 32 on 32-bit Windows.
- TARGET
- Query the registry matching the architecture specified by the CMAKE_SIZEOF_VOID_P variable. If not defined, fall back to HOST view.
- BOTH
- Query both views (32 and 64). The order depends on the following rules: If the CMAKE_SIZEOF_VOID_P variable is defined, use the following view depending on the content of this variable:
- •
- 8: 64_32
- •
- 4: 32_64
- •
- 64-bit: 64_32
- •
- 32-bit: 32
- PATH_SUFFIXES
- Specify additional subdirectories to check below each directory location otherwise considered.
- VALIDATOR
- New in version 3.25. Specify a function() to be called for each candidate item found (a macro() cannot be provided, that will result in an error). Two arguments will be passed to the validator function: the name of a result variable, and the absolute path to the candidate item. The item will be accepted and the search will end unless the function sets the value in the result variable to false in the calling scope. The result variable will hold a true value when the validator function is entered.
function(my_check validator_result_var item) if(NOT item MATCHES ...) set(${validator_result_var} FALSE PARENT_SCOPE) endif() endfunction() find_program (result NAMES ... VALIDATOR my_check)
- DOC
- Specify the documentation string for the <VAR> cache entry.
- NO_CACHE
- New in version 3.21. The result of the search will be stored in a normal variable rather than a cache entry. NOTE:
If the variable is already set before the call
(as a normal or cache variable) then the search will not occur.
This option should be used with caution
because it can greatly increase the cost of repeated configure steps.
- REQUIRED
- New in version 3.18. Stop 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.
- 1.
- New in version 3.12: If called from within a find module or any other script loaded by a call to find_package(<PackageName>), search prefixes unique to the current package being found. Specifically, look in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable. The package root variables are maintained as a stack, so if called from nested find modules or config packages, root paths from the parent's find module or config package will be searched after paths from the current module or package. In other words, the search order would be <CurrentPackage>_ROOT, ENV{<CurrentPackage>_ROOT}, <ParentPackage>_ROOT, ENV{<ParentPackage>_ROOT}, etc. This can be skipped if NO_PACKAGE_ROOT_PATH is passed or by setting the CMAKE_FIND_USE_PACKAGE_ROOT_PATH to FALSE. See policy CMP0074.
- •
- <prefix>/[s]bin for each <prefix> in the <PackageName>_ROOT CMake variable and the <PackageName>_ROOT environment variable if called from within a find module loaded by find_package(<PackageName>)
- 2.
- Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. The values are interpreted as semicolon-separated lists. This can be skipped if NO_CMAKE_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_PATH to FALSE.
- •
- <prefix>/[s]bin for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_PROGRAM_PATH
- •
- CMAKE_APPBUNDLE_PATH
- 3.
- Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration, and therefore use the host's native path separator ( ; on Windows and : on UNIX). This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH to FALSE.
- •
- <prefix>/[s]bin for each <prefix> in CMAKE_PREFIX_PATH
- •
- CMAKE_PROGRAM_PATH
- •
- CMAKE_APPBUNDLE_PATH
- 4.
- Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.
- 5.
- Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed or by setting the CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH to FALSE.
- •
- The directories in PATH itself.
- •
- On Windows hosts no extra search paths are included
- 6.
- Search cmake variables defined in the Platform files for the current system. The searching of CMAKE_INSTALL_PREFIX and CMAKE_STAGING_PREFIX can be skipped if NO_CMAKE_INSTALL_PREFIX is passed or by setting the CMAKE_FIND_USE_INSTALL_PREFIX to FALSE. All these locations can be skipped if NO_CMAKE_SYSTEM_PATH is passed or by setting the CMAKE_FIND_USE_CMAKE_SYSTEM_PATH to FALSE.
- •
- <prefix>/[s]bin for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
- •
- CMAKE_SYSTEM_PROGRAM_PATH
- •
- CMAKE_SYSTEM_APPBUNDLE_PATH
- 7.
- Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
- CMAKE_FIND_ROOT_PATH_BOTH
- Search in the order described above.
- NO_CMAKE_FIND_ROOT_PATH
- Do not use the CMAKE_FIND_ROOT_PATH variable.
- ONLY_CMAKE_FIND_ROOT_PATH
- Search only the re-rooted directories and directories below CMAKE_STAGING_PREFIX.
find_program (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) find_program (<VAR> NAMES name)
foreach
Evaluate a group of commands for each value in a list.foreach(<loop_var> <items>) <commands> endforeach()
foreach(<loop_var> RANGE <stop>)
foreach(<loop_var> RANGE <start> <stop> [<step>])
foreach(<loop_var> IN [LISTS [<lists>]] [ITEMS [<items>]])
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()
-- X=0 -- X=1 -- X=2 -- X=3 -- X=4 5 -- X=6 -- X=7 -- X=8
foreach(<loop_var>... IN ZIP_LISTS <lists>)
- •
- if the only loop_var given, then it sets a series of loop_var_N variables to the current item from the corresponding list;
- •
- if multiple variable names passed, their count should match the lists variables count;
- •
- if any of the lists are shorter, the corresponding iteration variable is not defined for the current iteration.
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()
-- 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=
See Also
- •
- break()
- •
- continue()
- •
- endforeach()
- •
- while()
function
Start recording a function for later invocation as a command.function(<name> [<arg1> ...]) <commands> endfunction()
Invocation
The function invocation is case-insensitive. A function defined asfunction(foo) <commands> endfunction()
foo() Foo() FOO() cmake_language(CALL foo)
Arguments
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.See Also
- •
- endfunction()
- •
- return()
get_cmake_property
Get a global property of the CMake instance.get_cmake_property(<var> <property>)
get_directory_property
Get a property of DIRECTORY scope.get_directory_property(<variable> [DIRECTORY <dir>] <prop-name>)
get_directory_property(<variable> [DIRECTORY <dir>] DEFINITION <var-name>)
get_filename_component
Get a specific component of a full filename.get_filename_component(<var> <FileName> <mode> [CACHE])
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 with neither the directory nor the longest extension LAST_EXT = File name last extension (.c from d/a.b.c) NAME_WLE = File name with neither the directory nor the last extension PATH = Legacy alias for DIRECTORY (use for CMake <= 2.8.11)
get_filename_component(<var> <FileName> <mode> [BASE_DIR <dir>] [CACHE])
ABSOLUTE = Full path to file REALPATH = Full path to existing file with symlinks resolved
get_filename_component(<var> <FileName> PROGRAM [PROGRAM_ARGS <arg_var>] [CACHE])
get_property
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])
- GLOBAL
- Scope is unique and does not accept a name.
- DIRECTORY
- Scope defaults to the current directory but another directory (already processed by CMake) may be named by the full or relative path <dir>. Relative paths are treated as relative to the current source directory. See also the get_directory_property() command. New in version 3.19: <dir> may reference a binary directory.
- TARGET
- Scope must name one existing target. See also the get_target_property() command.
- SOURCE
- Scope must name one source file. By default, the source file's property will be read from the current source directory's scope. New in version 3.18: Directory scope can be overridden with one of the following sub-options:
- DIRECTORY <dir>
- The source file property will be read from the <dir> directory's scope. CMake must already know about the directory, either by having added it through a call to add_subdirectory() or <dir> being the top level directory. Relative paths are treated as relative to the current source directory. New in version 3.19: <dir> may reference a binary directory.
- TARGET_DIRECTORY <target>
- The source file property will be read from the directory scope in which <target> was created (<target> must therefore already exist).
- INSTALL
- New in version 3.1. Scope must name one installed file path.
- TEST
- Scope must name one existing test. See also the get_test_property() command.
- CACHE
- Scope must name one cache entry.
- VARIABLE
- Scope is unique and does not accept a name.
The GENERATED source file property may
be globally visible. See its documentation for details.
if
Conditionally execute a group of commands.Synopsis
if(<condition>) <commands> elseif(<condition>) # optional block, can be repeated <commands> else() # optional block <commands> endif()
Condition Syntax
The following syntax applies to the condition argument of the if, elseif and while() clauses.- 1.
- Parentheses.
- 2.
- Unary tests such as EXISTS, COMMAND, and DEFINED.
- 3.
- 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, PATH_EQUAL, and MATCHES.
- 4.
- Unary logical operator NOT.
- 5.
- Binary logical operators AND and OR, from left to right, without any short-circuit.
Basic Expressions
- if(<constant>)
- True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number (including floating point numbers). False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND. Named boolean constants are case-insensitive. If the argument is not one of these specific constants, it is treated as a variable or string (see Variable Expansion further below) and one of the following two forms applies.
- if(<variable>)
- True if given a variable that is defined to a value that is not a false constant. False otherwise, including if the variable is undefined. Note that macro arguments are not variables. Environment Variables also cannot be tested this way, e.g. if(ENV{some_var}) will always evaluate to false.
- if(<string>)
- A quoted string always evaluates to false unless:
- •
- The string's value is one of the true constants, or
- •
- Policy CMP0054 is not set to NEW and the string's value happens to be a variable name that is affected by CMP0054's behavior.
Logic Operators
- if(NOT <condition>)
- True if the condition is not true.
- if(<cond1> AND <cond2>)
- True if both conditions would be considered true individually.
- if(<cond1> OR <cond2>)
- True if either condition would be considered true individually.
- if((condition) AND (condition OR (condition)))
- The conditions inside the parenthesis are evaluated first and then the remaining condition is evaluated as in the other examples. Where there are nested parenthesis the innermost are evaluated as part of evaluating the condition that contains them.
Existence Checks
- if(COMMAND command-name)
- True if the given name is a command, macro or function that can be invoked.
- if(POLICY policy-id)
- True if the given name is an existing policy (of the form CMP<NNNN>).
- if(TARGET target-name)
- True if the given name is an existing logical target name created by a call to the add_executable(), add_library(), or add_custom_target() command that has already been invoked (in any directory).
- if(TEST test-name)
- New in version 3.3: True if the given name is an existing test name created by the add_test() command.
- if(DEFINED <name>|CACHE{<name>}|ENV{<name>})
- True if a variable, cache variable or environment variable with given <name> is defined. The value of the variable does not matter. Note the following caveats:
- •
- Macro arguments are not variables.
- •
- It is not possible to test directly whether a <name> is a non-cache variable. The expression if(DEFINED someName) will evaluate to true if either a cache or non-cache variable someName exists. In comparison, the expression if(DEFINED CACHE{someName}) will only evaluate to true if a cache variable someName exists. Both expressions need to be tested if you need to know whether a non-cache variable exists: if(DEFINED someName AND NOT DEFINED CACHE{someName}).
- if(<variable|string> IN_LIST <variable>)
- New in version 3.3: True if the given element is contained in the named list variable.
File Operations
- if(EXISTS path-to-file-or-directory)
- True if the named file or directory exists. Behavior is well-defined only for explicit full paths (a leading ~/ is not expanded as a home directory and is considered a relative path). Resolves symbolic links, i.e. if the named file or directory is a symbolic link, returns true if the target of the symbolic link exists.
- if(file1 IS_NEWER_THAN file2)
- True if file1 is newer than file2 or if one of the two files doesn't exist. Behavior is well-defined only for full paths. If the file time stamps are exactly the same, an IS_NEWER_THAN comparison returns true, so that any dependent build operations will occur in the event of a tie. This includes the case of passing the same file name for both file1 and file2.
- if(IS_DIRECTORY path-to-directory)
- True if the given name is a directory. Behavior is well-defined only for full paths.
- if(IS_SYMLINK file-name)
- True if the given name is a symbolic link. Behavior is well-defined only for full paths.
- if(IS_ABSOLUTE path)
- True if the given path is an absolute path. Note the following special cases:
- •
- An empty path evaluates to false.
- •
- On Windows hosts, any path that begins with a drive letter and colon (e.g. C:), a forward slash or a backslash will evaluate to true. This means a path like C:no\base\dir will evaluate to true, even though the non-drive part of the path is relative.
- •
- On non-Windows hosts, any path that begins with a tilde ( ~) evaluates to true.
Comparisons
- if(<variable|string> MATCHES regex)
- True if the given string or variable's value matches the given regular expression. See Regex Specification for regex format. New in version 3.9: () groups are captured in CMAKE_MATCH_<n> variables.
- if(<variable|string> LESS <variable|string>)
- True if the given string or variable's value is a valid number and less than that on the right.
- if(<variable|string> GREATER <variable|string>)
- True if the given string or variable's value is a valid number and greater than that on the right.
- if(<variable|string> EQUAL <variable|string>)
- True if the given string or variable's value is a valid number and equal to that on the right.
- if(<variable|string> LESS_EQUAL <variable|string>)
- New in version 3.7: True if the given string or variable's value is a valid number and less than or equal to that on the right.
- if(<variable|string> GREATER_EQUAL <variable|string>)
- New in version 3.7: True if the given string or variable's value is a valid number and greater than or equal to that on the right.
- if(<variable|string> STRLESS <variable|string>)
- True if the given string or variable's value is lexicographically less than the string or variable on the right.
- if(<variable|string> STRGREATER <variable|string>)
- True if the given string or variable's value is lexicographically greater than the string or variable on the right.
- if(<variable|string> STREQUAL <variable|string>)
- True if the given string or variable's value is lexicographically equal to the string or variable on the right.
- if(<variable|string> STRLESS_EQUAL <variable|string>)
- New in version 3.7: True if the given string or variable's value is lexicographically less than or equal to the string or variable on the right.
- if(<variable|string> STRGREATER_EQUAL <variable|string>)
- New in version 3.7: True if the given string or variable's value is lexicographically greater than or equal to the string or variable on the right.
Version Comparisons
- if(<variable|string> VERSION_LESS <variable|string>)
- Component-wise integer version number comparison (version format is major[.minor[.patch[.tweak]]], omitted components are treated as zero). Any non-integer version component or non-integer trailing part of a version component effectively truncates the string at that point.
- if(<variable|string> VERSION_GREATER <variable|string>)
- Component-wise integer version number comparison (version format is major[.minor[.patch[.tweak]]], omitted components are treated as zero). Any non-integer version component or non-integer trailing part of a version component effectively truncates the string at that point.
- if(<variable|string> VERSION_EQUAL <variable|string>)
- Component-wise integer version number comparison (version format is major[.minor[.patch[.tweak]]], omitted components are treated as zero). Any non-integer version component or non-integer trailing part of a version component effectively truncates the string at that point.
- if(<variable|string> VERSION_LESS_EQUAL <variable|string>)
- New in version 3.7: Component-wise integer version number comparison (version format is major[.minor[.patch[.tweak]]], omitted components are treated as zero). Any non-integer version component or non-integer trailing part of a version component effectively truncates the string at that point.
- if(<variable|string> VERSION_GREATER_EQUAL <variable|string>)
- New in version 3.7: Component-wise integer version number comparison (version format is major[.minor[.patch[.tweak]]], omitted components are treated as zero). Any non-integer version component or non-integer trailing part of a version component effectively truncates the string at that point.
Path Comparisons
- if(<variable|string> PATH_EQUAL <variable|string>)
- New in version 3.24. Compares the two paths component-by-component. Only if every component of both paths match will the two paths compare equal. Multiple path separators are effectively collapsed into a single separator, but note that backslashes are not converted to forward slashes. No other path normalization is performed. Component-wise comparison is superior to string-based comparison due to the handling of multiple path separators. In the following example, the expression evaluates to true using PATH_EQUAL, but false with STREQUAL:
# comparison is TRUE if ("/a//b/c" PATH_EQUAL "/a/b/c") ... endif() # comparison is FALSE if ("/a//b/c" STREQUAL "/a/b/c") ... endif()
Variable Expansion
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 likeset(var1 OFF) set(var2 "var1") if(${var2})
if(var1)
if(var2)
- •
- The left hand argument to MATCHES is first checked to see if it is a defined variable, if so the variable's value is used, otherwise the original value is used.
- •
- If the left hand argument to MATCHES is missing it returns false without error
- •
- Both left and right hand arguments to LESS, GREATER, EQUAL, LESS_EQUAL, and GREATER_EQUAL, are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.
- •
- Both left and right hand arguments to STRLESS, STRGREATER, STREQUAL, STRLESS_EQUAL, and STRGREATER_EQUAL are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.
- •
- Both left and right hand arguments to VERSION_LESS, VERSION_GREATER, VERSION_EQUAL, VERSION_LESS_EQUAL, and VERSION_GREATER_EQUAL are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.
- •
- The right hand argument to NOT is tested to see if it is a boolean constant, if so the value is used, otherwise it is assumed to be a variable and it is dereferenced.
- •
- The left and right hand arguments to AND and OR are independently tested to see if they are boolean constants, if so they are used as such, otherwise they are assumed to be variables and are dereferenced.
See also
- •
- else()
- •
- elseif()
- •
- endif()
include
Load and run CMake code from a file or module.include(<file|module> [OPTIONAL] [RESULT_VARIABLE <var>] [NO_POLICY_SCOPE])
include_guard
New in version 3.10.include_guard([DIRECTORY|GLOBAL])
- DIRECTORY
- The include guard applies within the current directory and below. The file will only be included once within this directory scope, but may be included again by other files outside of this directory (i.e. a parent directory or another directory not pulled in by add_subdirectory() or include() from the current file or its children).
- GLOBAL
- The include guard applies globally to the whole build. The current file will only be included once regardless of the scope.
if(__CURRENT_FILE_VAR__) return() endif() set(__CURRENT_FILE_VAR__ TRUE)
list
List operations.Synopsis
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> [...])
Introduction
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.A list in cmake is a ; separated group
of strings. To create a list the set command can be used. For example,
set(var a b c d e) creates a list with a;b;c;d;e, and set(var
"a b c d e") creates a string or a list with one item in it.
(Note macro arguments are not variables, and therefore cannot be used in LIST
commands.)
When specifying index values, if
<element index> is 0 or greater, it is indexed from the beginning
of the list, with 0 representing the first list element. If <element
index> is -1 or lesser, it is indexed from the end of the list, with -1
representing the last list element. Be careful when counting with negative
indices: they do not start from 0. -0 is equivalent to 0, the first list
element.
Reading
list(LENGTH <list> <output variable>)
list(GET <list> <element index> [<element index> ...] <output variable>)
list(JOIN <list> <glue> <output variable>)
list(SUBLIST <list> <begin> <length> <output variable>)
Search
list(FIND <list> <value> <output variable>)
Modification
list(APPEND <list> [<element> ...])
list(FILTER <list> <INCLUDE|EXCLUDE> REGEX <regular_expression>)
list(INSERT <list> <element_index> <element> [<element> ...])
list(POP_BACK <list> [<out-var>...])
list(POP_FRONT <list> [<out-var>...])
list(PREPEND <list> [<element> ...])
list(REMOVE_ITEM <list> <value> [<value> ...])
list(REMOVE_AT <list> <index> [<index> ...])
list(REMOVE_DUPLICATES <list>)
list(TRANSFORM <list> <ACTION> [<SELECTOR>] [OUTPUT_VARIABLE <output variable>])
The TRANSFORM sub-command does not
change the number of elements in the list. If a <SELECTOR> is
specified, only some elements will be changed, the other ones will remain the
same as before the transformation.
list(TRANSFORM <list> <APPEND|PREPEND> <value> ...)
list(TRANSFORM <list> <TOLOWER|TOUPPER> ...)
list(TRANSFORM <list> STRIP ...)
list(TRANSFORM <list> GENEX_STRIP ...)
list(TRANSFORM <list> REPLACE <regular_expression> <replace_expression> ...)
list(TRANSFORM <list> <ACTION> AT <index> [<index> ...] ...)
list(TRANSFORM <list> <ACTION> FOR <start> <stop> [<step>] ...)
list(TRANSFORM <list> <ACTION> REGEX <regular_expression> ...)
Ordering
list(REVERSE <list>)
list(SORT <list> [COMPARE <compare>] [CASE <case>] [ORDER <order>])
- •
- STRING: Sorts a list of strings alphabetically. This is the default behavior if the COMPARE option is not given.
- •
- FILE_BASENAME: Sorts a list of pathnames of files by their basenames.
- •
- NATURAL: Sorts a list of strings using natural order (see strverscmp(3) manual), i.e. such that contiguous digits are compared as whole numbers. For example: the following list 10.0 1.1 2.1 8.0 2.0 3.1 will be sorted as 1.1 2.0 2.1 3.1 8.0 10.0 if the NATURAL comparison is selected where it will be sorted as 1.1 10.0 2.0 2.1 3.1 8.0 with the STRING comparison.
- •
- SENSITIVE: List items are sorted in a case-sensitive manner. This is the default behavior if the CASE option is not given.
- •
- INSENSITIVE: List items are sorted case insensitively. The order of items which differ only by upper/lowercase is not specified.
- •
- ASCENDING: Sorts the list in ascending order. This is the default behavior when the ORDER option is not given.
- •
- DESCENDING: Sorts the list in descending order.
macro
Start recording a macro for later invocation as a commandmacro(<name> [<arg1> ...]) <commands> endmacro()
Invocation
The macro invocation is case-insensitive. A macro defined asmacro(foo) <commands> endmacro()
foo() Foo() FOO() cmake_language(CALL foo)
Arguments
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.Macro vs Function
The macro command is very similar to the function() command. Nonetheless, there are a few important differences.Argument Caveats
Since ARGN, ARGC, ARGV, ARGV0 etc. are not variables, you will NOT be able to use commands likeif(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
set(list_var "${ARGN}") foreach(loop_var IN LISTS list_var)
macro(bar) foreach(arg IN LISTS ARGN) <commands> endforeach() endmacro() function(foo) bar(x y z) endfunction() foo(a b c)
mark_as_advanced
Mark cmake cached variables as advanced.mark_as_advanced([CLEAR|FORCE] <var1> ...)
math
Evaluate a mathematical expression.math(EXPR <variable> "<expression>" [OUTPUT_FORMAT <format>])
- HEXADECIMAL
- Hexadecimal notation as in C code, i. e. starting with "0x".
- DECIMAL
- Decimal notation. Which is also used if no OUTPUT_FORMAT option is specified.
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"
message
Log a message.Synopsis
General messages message([<mode>] "message text" ...) Reporting checks message(<checkState> "message text" ...)
General messages
message([<mode>] "message text" ...)
- FATAL_ERROR
- CMake Error, stop processing and generation. The cmake(1) executable will return a non-zero exit code.
- SEND_ERROR
- CMake Error, continue processing, but skip generation.
- WARNING
- CMake Warning, continue processing.
- AUTHOR_WARNING
- CMake Warning (dev), continue processing.
- DEPRECATION
- CMake Deprecation Error or Warning if variable CMAKE_ERROR_DEPRECATED or CMAKE_WARN_DEPRECATED is enabled, respectively, else no message.
- (none) or NOTICE
- Important message printed to stderr to attract user's attention.
- STATUS
- The main interesting messages that project users might be interested in. Ideally these should be concise, no more than a single line, but still informative.
- VERBOSE
- Detailed informational messages intended for project users. These messages should provide additional details that won't be of interest in most cases, but which may be useful to those building the project when they want deeper insight into what's happening.
- DEBUG
- Detailed informational messages intended for developers working on the project itself as opposed to users who just want to build it. These messages will not typically be of interest to other users building the project and will often be closely related to internal implementation details.
- TRACE
- Fine-grained messages with very low-level implementation details. Messages using this log level would normally only be temporary and would expect to be removed before releasing the project, packaging up the files, etc.
Reporting checks
New in version 3.17.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()
message(<checkState> "message" ...)
- CHECK_START
- Record a concise message about the check about to be performed.
- CHECK_PASS
- Record a successful result for a check.
- CHECK_FAIL
- Record an unsuccessful result for a check.
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()
-- Finding my things -- Finding partA -- Finding partA - found -- Finding partB -- Finding partB - not found -- Finding my things - missing components: B
option
Provide a boolean option that the user can optionally select.option(<variable> "<help_text>" [value])
return
Return from a file, directory or function.return([PROPAGATE <var-name>...])
- PROPAGATE
- New in version 3.25. This option sets or unsets the specified variables in the parent directory or function caller scope. This is equivalent to set(PARENT_SCOPE) or unset(PARENT_SCOPE) commands, except for the way it interacts with the block() command, as described below. The PROPAGATE option can be very useful in conjunction with the block() command. A return() will propagate the specified variables through any enclosing block scopes created by the block() commands. Inside a function, this ensures the variables are propagated to the function's caller, regardless of any blocks within the function. If not inside a function, it ensures the variables are propagated to the parent file or directory scope. For example: CMakeLists.txt
cmake_version_required(VERSION 3.25) project(example) set(var1 "top-value") block(SCOPE_FOR VARIABLES) add_subdirectory(subDir) # var1 has the value "block-nested" endblock() # var1 has the value "top-value"
function(multi_scopes result_var1 result_var2) block(SCOPE_FOR VARIABLES) # This would only propagate out of the immediate block, not to # the caller of the function. #set(${result_var1} "new-value" PARENT_SCOPE) #unset(${result_var2} PARENT_SCOPE) # This propagates the variables through the enclosing block and # out to the caller of the function. set(${result_var1} "new-value") unset(${result_var2}) return(PROPAGATE ${result_var1} ${result_var2}) endblock() endfunction() set(var1 "some-value") set(var2 "another-value") multi_scopes(var1 var2) # Now var1 will hold "new-value" and var2 will be unset block(SCOPE_FOR VARIABLES) # This return() will set var1 in the directory scope that included us # via add_subdirectory(). The surrounding block() here does not limit # propagation to the current file, but the block() in the parent # directory scope does prevent propagation going any further. set(var1 "block-nested") return(PROPAGATE var1) endblock()
See Also
- •
- block()
separate_arguments
Parse command-line arguments into a semicolon-separated list.separate_arguments(<variable> <mode> [PROGRAM [SEPARATE_ARGS]] <args>)
- UNIX_COMMAND
- Arguments are separated by unquoted whitespace. Both single-quote and double-quote pairs are respected. A backslash escapes the next literal character ( \" is "); there are no special escapes ( \n is just n).
- WINDOWS_COMMAND
- A Windows command-line is parsed using the same syntax the runtime library uses to construct argv at startup. It separates arguments by whitespace that is not double-quoted. Backslashes are literal unless they precede double-quotes. See the MSDN article Parsing C Command-Line Arguments for details.
- NATIVE_COMMAND
- New in version 3.9. Proceeds as in WINDOWS_COMMAND mode if the host system is Windows. Otherwise proceeds as in UNIX_COMMAND mode.
- PROGRAM
- New in version 3.19. The first item in <args> is assumed to be an executable and will be searched in the system search path or left as a full path. If not found, <variable> will be empty. Otherwise, <variable> is a list of 2 elements:
- 0.
- Absolute path of the program
- 1.
- Any command-line arguments present in <args> as a string
separate_arguments (out UNIX_COMMAND PROGRAM "cc -c main.c")
- •
- First element of the list: /path/to/cc
- •
- Second element of the list: " -c main.c"
- SEPARATE_ARGS
- When this sub-option of PROGRAM option is specified, command-line arguments will be split as well and stored in <variable>. For example:
separate_arguments (out UNIX_COMMAND PROGRAM SEPARATE_ARGS "cc -c main.c")
separate_arguments(<var>)
set
Set a normal, cache, or environment variable to a given value. See the cmake-language(7) variables documentation for the scopes and interaction of normal variables and cache entries.Set Normal Variable
set(<variable> <value>... [PARENT_SCOPE])
Set Cache Entry
set(<variable> <value>... CACHE <type> <docstring> [FORCE])
- BOOL
- Boolean ON/OFF value. cmake-gui(1) offers a checkbox.
- FILEPATH
- Path to a file on disk. cmake-gui(1) offers a file dialog.
- PATH
- Path to a directory on disk. cmake-gui(1) offers a file dialog.
- STRING
- A line of text. cmake-gui(1) offers a text field or a drop-down selection if the STRINGS cache entry property is set.
- INTERNAL
- A line of text. cmake-gui(1) does not show internal entries. They may be used to store variables persistently across runs. Use of this type implies FORCE.
The content of the cache variable will not be
directly accessible if a normal variable of the same name already exists (see
rules of variable evaluation). If policy CMP0126 is set
to OLD, any normal variable binding in the current scope will be
removed.
Set Environment Variable
set(ENV{<variable>} [<value>])
set_directory_properties
Set properties of the current directory and subdirectories.set_directory_properties(PROPERTIES prop1 value1 [prop2 value2] ...)
set_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> ...])
- GLOBAL
- Scope is unique and does not accept a name.
- DIRECTORY
- Scope defaults to the current directory but other directories (already processed by CMake) may be named by full or relative path. Relative paths are treated as relative to the current source directory. See also the set_directory_properties() command. New in version 3.19: <dir> may reference a binary directory.
- TARGET
- Scope may name zero or more existing targets. See also the set_target_properties() command.
- SOURCE
- Scope may name zero or more source files. By default, source file properties are only visible to targets added in the same directory ( CMakeLists.txt). New in version 3.18: Visibility can be set in other directory scopes using one or both of the following sub-options:
- DIRECTORY <dirs>...
- The source file property will be set in each of the <dirs> directories' scopes. CMake must already know about each of these directories, either by having added them through a call to add_subdirectory() or it being the top level source directory. Relative paths are treated as relative to the current source directory. New in version 3.19: <dirs> may reference a binary directory.
- TARGET_DIRECTORY <targets>...
- The source file property will be set in each of the directory scopes where any of the specified <targets> were created (the <targets> must therefore already exist).
- INSTALL
- New in version 3.1. Scope may name zero or more installed file paths. These are made available to CPack to influence deployment. 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.
- TEST
- Scope may name zero or more existing tests. See also the set_tests_properties() command. Test property values may be specified using generator expressions for tests created by the add_test(NAME) signature.
- CACHE
- Scope must name zero or more cache existing entries.
The GENERATED source file property may
be globally visible. See its documentation for details.
site_name
Set the given variable to the name of the computer.site_name(variable)
string
String operations.Synopsis
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> ...) JSON string(JSON <out-var> [ERROR_VARIABLE <error-var>] { GET | TYPE | LENGTH | REMOVE} <json-string> <member|index> [<member|index> ...]) string(JSON <out-var> [ERROR_VARIABLE <error-var>] MEMBER <json-string> [<member|index> ...] <index>) string(JSON <out-var> [ERROR_VARIABLE <error-var>] SET <json-string> <member|index> [<member|index> ...] <value>) string(JSON <out-var> [ERROR_VARIABLE <error-var>] EQUAL <json-string1> <json-string2>)
Search and Replace
Search and Replace With Plain Strings
string(FIND <string> <substring> <output_variable> [REVERSE])
string(REPLACE <match_string> <replace_string> <output_variable> <input> [<input>...])
Search and Replace With Regular Expressions
string(REGEX MATCH <regular_expression> <output_variable> <input> [<input>...])
string(REGEX MATCHALL <regular_expression> <output_variable> <input> [<input>...])
string(REGEX REPLACE <regular_expression> <replacement_expression> <output_variable> <input> [<input>...])
Regex Specification
The following characters have special meaning in regular expressions:- ^
- Matches at beginning of input
- $
- Matches at end of input
- .
- Matches any single character
- \<char>
- Matches the single character specified by <char>. Use this to match special regex characters, e.g. \. for a literal . or \\ for a literal backslash \. Escaping a non-special character is unnecessary but allowed, e.g. \a matches a.
- [ ]
- Matches any character(s) inside the brackets
- [^ ]
- Matches any character(s) not inside the brackets
- -
- Inside brackets, specifies an inclusive range between characters on either side e.g. [a-f] is [abcdef] To match a literal - using brackets, make it the first or the last character e.g. [+*/-] matches basic mathematical operators.
- *
- Matches preceding pattern zero or more times
- +
- Matches preceding pattern one or more times
- ?
- Matches preceding pattern zero or once only
- |
- Matches a pattern on either side of the |
- ()
- Saves a matched subexpression, which can be referenced in the REGEX REPLACE operation. New in version 3.9: All regular expression-related commands, including e.g. if(MATCHES), save subgroup matches in the variables CMAKE_MATCH_<n> for <n> 0..9.
- •
- The quoted argument "[ \t\r\n]" specifies a regex that matches any single whitespace character.
- •
- The quoted argument "[/\\]" specifies a regex that matches a single forward slash / or backslash \.
- •
- The quoted argument "[A-Za-z0-9_]" specifies a regex that matches any single "word" character in the C locale.
- •
- The quoted argument "\\(\\a\\+b\\)" specifies a regex that matches the exact string (a+b). Each \\ is parsed in a quoted argument as just \, so the regex itself is actually \(\a\+\b\). This can alternatively be specified in a Bracket Argument without having to escape the backslashes, e.g. [[\(\a\+\b\)]].
Manipulation
string(APPEND <string_variable> [<input>...])
string(PREPEND <string_variable> [<input>...])
string(CONCAT <output_variable> [<input>...])
string(JOIN <glue> <output_variable> [<input>...])
string(TOLOWER <string> <output_variable>)
string(TOUPPER <string> <output_variable>)
string(LENGTH <string> <output_variable>)
string(SUBSTRING <string> <begin> <length> <output_variable>)
string(STRIP <string> <output_variable>)
string(GENEX_STRIP <string> <output_variable>)
string(REPEAT <string> <count> <output_variable>)
Comparison
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>)
Hashing
string(<HASH> <output_variable> <input>)
- MD5
- Message-Digest Algorithm 5, RFC 1321.
- SHA1
- US Secure Hash Algorithm 1, RFC 3174.
- SHA224
- US Secure Hash Algorithms, RFC 4634.
- SHA256
- US Secure Hash Algorithms, RFC 4634.
- SHA384
- US Secure Hash Algorithms, RFC 4634.
- SHA512
- US Secure Hash Algorithms, RFC 4634.
- SHA3_224
- Keccak SHA-3.
- SHA3_256
- Keccak SHA-3.
- SHA3_384
- Keccak SHA-3.
- SHA3_512
- Keccak SHA-3.
Generation
string(ASCII <number> [<number> ...] <output_variable>)
string(HEX <string> <output_variable>)
string(CONFIGURE <string> <output_variable> [@ONLY] [ESCAPE_QUOTES])
string(MAKE_C_IDENTIFIER <string> <output_variable>)
string(RANDOM [LENGTH <length>] [ALPHABET <alphabet>] [RANDOM_SEED <seed>] <output_variable>)
string(TIMESTAMP <output_variable> [<format_string>] [UTC])
- %%
- New in version 3.8. 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
- New in version 3.7. Abbreviated month name (e.g. Oct).
- %B
- New in version 3.10. Full month name (e.g. October).
- %M
- The minute of the current hour (00-59).
- %s
- New in version 3.6. Seconds since midnight (UTC) 1-Jan-1970 (UNIX time).
- %S
- The second of the current minute. 60 represents a leap second. (00-60)
- %f
- New in version 3.23. The microsecond of the current second (000000-999999).
- %U
- The week number of the current year (00-53).
- %V
- New in version 3.22. The ISO 8601 week number of the current year (01-53).
- %w
- The day of the current week. 0 is Sunday. (0-6)
- %a
- New in version 3.7. Abbreviated weekday name (e.g. Fri).
- %A
- New in version 3.10. Full weekday name (e.g. Friday).
- %y
- The last two digits of the current year (00-99).
- %Y
- The current year.
%Y-%m-%dT%H:%M:%S for local time. %Y-%m-%dT%H:%M:%SZ for UTC.
string(UUID <output_variable> NAMESPACE <namespace> NAME <name> TYPE <MD5|SHA1> [UPPER])
JSON
New in version 3.19.In each of the following JSON-related
subcommands, if the optional ERROR_VARIABLE argument is given, errors
will be reported in <error-variable> and the
<out-var> will be set to
<member|index>-[<member|index>...]-NOTFOUND with the path
elements up to the point where the error occurred, or just NOTFOUND if
there is no relevant path. If an error occurs but the ERROR_VARIABLE
option is not present, a fatal error message is generated. If no error occurs,
the <error-variable> will be set to NOTFOUND.
string(JSON <out-var> [ERROR_VARIABLE <error-variable>] GET <json-string> <member|index> [<member|index> ...])
string(JSON <out-var> [ERROR_VARIABLE <error-variable>] TYPE <json-string> <member|index> [<member|index> ...])
string(JSON <out-var> [ERROR_VARIABLE <error-var>] MEMBER <json-string> [<member|index> ...] <index>)
string(JSON <out-var> [ERROR_VARIABLE <error-variable>] LENGTH <json-string> [<member|index> ...])
string(JSON <out-var> [ERROR_VARIABLE <error-variable>] REMOVE <json-string> <member|index> [<member|index> ...])
string(JSON <out-var> [ERROR_VARIABLE <error-variable>] SET <json-string> <member|index> [<member|index> ...] <value>)
string(JSON <out-var> [ERROR_VARIABLE <error-var>] EQUAL <json-string1> <json-string2>)
unset
Unset a variable, cache variable, or environment variable.Unset Normal Variable or Cache Entry
unset(<variable> [CACHE | PARENT_SCOPE])
Unset Environment Variable
unset(ENV{<variable>})
variable_watch
Watch the CMake variable for change.variable_watch(<variable> [<command>])
- <variable>
- Name of the variable being accessed.
- <access>
- One of READ_ACCESS, UNKNOWN_READ_ACCESS, MODIFIED_ACCESS, UNKNOWN_MODIFIED_ACCESS, or REMOVED_ACCESS. The UNKNOWN_ values are only used when the variable has never been set. Once set, they are never used again during the same CMake run, even if the variable is later unset.
- <value>
- The value of the variable. On a modification, this is the new (modified) value of the variable. On removal, the value is empty.
- <current_list_file>
- Full path to the file doing the access.
- <stack>
- List of absolute paths of all files currently on the stack of file inclusion, with the bottom-most file first and the currently processed file (that is, current_list_file) last.
while
Evaluate a group of commands while a condition is truewhile(<condition>) <commands> endwhile()
See Also
- •
- break()
- •
- continue()
- •
- foreach()
- •
- endwhile()
PROJECT COMMANDS
These commands are available only in CMake projects.add_compile_definitions
New in version 3.12.add_compile_definitions(<definition> ...)
add_compile_options
Add options to the compilation of source files.add_compile_options(<option> ...)
Arguments
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.Option De-duplication
The final set of 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.Example
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()
See Also
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().add_custom_command
Add a custom build rule to the generated build system.Generating Files
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])
OUTPUT: MAIN_DEPENDENCY DEPENDS COMMAND
- APPEND
- Append the COMMAND and DEPENDS option values to the custom command for the first output specified. There must have already been a previous call to this command with the same output. If the previous call specified the output via a generator expression, the output specified by the current call must match in at least one configuration after evaluating generator expressions. In this case, the appended commands and dependencies apply to all configurations. The COMMENT, MAIN_DEPENDENCY, and WORKING_DIRECTORY options are currently ignored when APPEND is given, but may be used in the future.
- BYPRODUCTS
- New in version 3.2. Specify the files the command is expected to produce but whose modification time may or may not be newer than the dependencies. If a byproduct name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. Each byproduct file will be marked with the GENERATED source file property automatically. See policy CMP0058 for the motivation behind this feature. 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. New in version 3.20: Arguments to BYPRODUCTS may use a restricted set of generator expressions. Target-dependent expressions are not permitted.
- COMMAND
- Specify the command-line(s) to execute at build time. If more than one COMMAND is specified they will be executed in order, but not necessarily composed into a stateful shell or batch script. (To run a full script, use the configure_file() command or the file(GENERATE) command to create it, and then specify a COMMAND to launch it.) The optional ARGS argument is for backward compatibility and will be ignored. 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:
- •
- The target is not being cross-compiled (i.e. the CMAKE_CROSSCOMPILING variable is not set to true).
- •
- New in version 3.6: The target is being cross-compiled and an emulator is provided (i.e. its CROSSCOMPILING_EMULATOR target property is set). In this case, the contents of CROSSCOMPILING_EMULATOR will be prepended to the command before the location of the target executable.
- •
- TARGET_FILE
- •
- TARGET_LINKER_FILE
- •
- TARGET_SONAME_FILE
- •
- TARGET_PDB_FILE
- COMMENT
- Display the given message before the commands are executed at build time.
- DEPENDS
- Specify files on which the command depends. Each argument is converted to a dependency as follows:
- 1.
- If the argument is the name of a target (created by the add_custom_target(), add_executable(), or add_library() command) a target-level dependency is created to make sure the target is built before any target using this custom command. Additionally, if the target is an executable or library, a file-level dependency is created to cause the custom command to re-run whenever the target is recompiled.
- 2.
- If the argument is an absolute path, a file-level dependency is created on that path.
- 3.
- If the argument is the name of a source file that has been added to a target or on which a source file property has been set, a file-level dependency is created on that source file.
- 4.
- If the argument is a relative path and it exists in the current source directory, a file-level dependency is created on that file in the current source directory.
- 5.
- Otherwise, a file-level dependency is created on that path relative to the current binary directory.
- COMMAND_EXPAND_LISTS
- New in version 3.8. Lists in COMMAND arguments will be expanded, including those created with generator expressions, allowing COMMAND arguments such as ${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc to be properly expanded.
- IMPLICIT_DEPENDS
- Request scanning of implicit dependencies of an input file. The language given specifies the programming language whose corresponding dependency scanner should be used. Currently only C and CXX language scanners are supported. The language has to be specified for every file in the IMPLICIT_DEPENDS list. Dependencies discovered from the scanning are added to those of the custom command at build time. Note that the IMPLICIT_DEPENDS option is currently supported only for Makefile generators and will be ignored by other generators. NOTE:
This option cannot be specified at the same
time as DEPFILE option.
- JOB_POOL
- New in version 3.15. Specify a pool for the Ninja generator. Incompatible with USES_TERMINAL, which implies the console pool. Using a pool that is not defined by JOB_POOLS causes an error by ninja at build time.
- MAIN_DEPENDENCY
- Specify the primary input source file to the command. This is treated just like any value given to the DEPENDS option but also suggests to Visual Studio generators where to hang the custom command. Each source file may have at most one command specifying it as its main dependency. A compile command (i.e. for a library or an executable) counts as an implicit main dependency which gets silently overwritten by a custom command specification.
- OUTPUT
- Specify the output files the command is expected to produce. If an output name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. Each output file will be marked with the GENERATED source file property automatically. If the output of the custom command is not actually created as a file on disk it should be marked with the SYMBOLIC source file property. New in version 3.20: Arguments to OUTPUT may use a restricted set of generator expressions. Target-dependent expressions are not permitted.
- USES_TERMINAL
- New in version 3.2. The command will be given direct access to the terminal if possible. With the Ninja generator, this places the command in the console pool.
- VERBATIM
- All arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before add_custom_command even sees the arguments. Use of VERBATIM is recommended as it enables correct behavior. When VERBATIM is not given the behavior is platform specific because there is no protection of tool-specific special characters.
- WORKING_DIRECTORY
- Execute the command with the given current working directory. If it is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. New in version 3.13: Arguments to WORKING_DIRECTORY may use generator expressions.
- DEPFILE
- New in version 3.7.
Specify a depfile which holds dependencies for the custom command. It is
usually emitted by the custom command itself. This keyword may only be
used if the generator supports it, as detailed below.
The expected format, compatible with what is generated by gcc with
the option -M, is independent of the generator or platform.
The formal syntax, as specified using BNF notation with the regular
extensions, is the following:
depfile ::= rule* rule ::= targets (':' (separator dependencies?)?)? eol targets ::= target (separator target)* separator* target ::= pathname dependencies ::= dependency (separator dependency)* separator* dependency ::= pathname separator ::= (space | line_continue)+ line_continue ::= '\' eol space ::= ' ' | '\t' pathname ::= character+ character ::= std_character | dollar | hash | whitespace std_character ::= <any character except '$', '#' or ' '> dollar ::= '$$' hash ::= '\#' whitespace ::= '\ ' eol ::= '\r'? '\n'
NOTE:
As part of pathname, any slash and
backslash is interpreted as a directory separator.
DEPFILE cannot be specified at the same
time as the IMPLICIT_DEPENDS option for Makefile
Generators.
Examples: Generating Files
Custom commands may be used to generate source files. For example, the code:add_custom_command( OUTPUT out.c COMMAND someTool -i ${CMAKE_CURRENT_SOURCE_DIR}/in.txt -o out.c DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/in.txt VERBATIM) add_library(myLib out.c)
add_custom_command( OUTPUT "out-$<CONFIG>.c" COMMAND someTool -i ${CMAKE_CURRENT_SOURCE_DIR}/in.txt -o "out-$<CONFIG>.c" -c "$<CONFIG>" DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/in.txt VERBATIM) add_library(myLib "out-$<CONFIG>.c")
Build Events
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])
- PRE_BUILD
- On Visual Studio Generators, run before any other rules are executed within the target. On other generators, run just before PRE_LINK commands.
- PRE_LINK
- Run after sources have been compiled but before linking the binary or running the librarian or archiver tool of a static library. This is not defined for targets created by the add_custom_target() command.
- POST_BUILD
- Run after all other rules within the target have been executed.
Because generator expressions can be used in
custom commands, it is possible to define COMMAND lines or whole custom
commands which evaluate to empty strings for certain configurations. For
Visual Studio 11 2012 (and newer) generators these command lines or
custom commands will be omitted for the specific configuration and no
"empty-string-command" will be added.
This allows to add individual build events for every configuration.
Examples: Build Events
A POST_BUILD event may be used to post-process a binary after linking. For example, the code:add_executable(myExe myExe.c) add_custom_command( TARGET myExe POST_BUILD COMMAND someHasher -i "$<TARGET_FILE:myExe>" -o "$<TARGET_FILE:myExe>.hash" VERBATIM)
add_library(myPlugin MODULE myPlugin.c) add_custom_command( TARGET myPlugin POST_BUILD COMMAND someHasher -i "$<TARGET_FILE:myPlugin>" --as-code "myPlugin-hash-$<CONFIG>.c" BYPRODUCTS "myPlugin-hash-$<CONFIG>.c" VERBATIM) add_executable(myExe myExe.c "myPlugin-hash-$<CONFIG>.c")
Ninja Multi-Config
New in version 3.20: add_custom_command supports the Ninja Multi-Config generator's cross-config capabilities. See the generator documentation for more information.add_custom_target
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...]])
- ALL
- Indicate that this target should be added to the default build target so that it will be run every time (the command cannot be called ALL).
- BYPRODUCTS
- New in version 3.2. Specify the files the command is expected to produce but whose modification time may or may not be updated on subsequent builds. If a byproduct name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. Each byproduct file will be marked with the GENERATED source file property automatically. See policy CMP0058 for the motivation behind this feature. 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. New in version 3.20: Arguments to BYPRODUCTS may use a restricted set of generator expressions. Target-dependent expressions are not permitted.
- COMMAND
- Specify the command-line(s) to execute at build time. If more than one COMMAND is specified they will be executed in order, but not necessarily composed into a stateful shell or batch script. (To run a full script, use the configure_file() command or the file(GENERATE) command to create it, and then specify a COMMAND to launch it.) 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:
- •
- The target is not being cross-compiled (i.e. the CMAKE_CROSSCOMPILING variable is not set to true).
- •
- New in version 3.6: The target is being cross-compiled and an emulator is provided (i.e. its CROSSCOMPILING_EMULATOR target property is set). In this case, the contents of CROSSCOMPILING_EMULATOR will be prepended to the command before the location of the target executable.
- •
- TARGET_FILE
- •
- TARGET_LINKER_FILE
- •
- TARGET_SONAME_FILE
- •
- TARGET_PDB_FILE
- COMMENT
- Display the given message before the commands are executed at build time.
- DEPENDS
- Reference files and outputs of custom commands created with add_custom_command() command calls in the same directory ( CMakeLists.txt file). They will be brought up to date when the target is built. Changed in version 3.16: A target-level dependency is added if any dependency is a byproduct of a target or any of its build events in the same directory to ensure the byproducts will be available before this target is built. Use the add_dependencies() command to add dependencies on other targets.
- COMMAND_EXPAND_LISTS
- New in version 3.8. Lists in COMMAND arguments will be expanded, including those created with generator expressions, allowing COMMAND arguments such as ${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc to be properly expanded.
- JOB_POOL
- New in version 3.15. Specify a pool for the Ninja generator. Incompatible with USES_TERMINAL, which implies the console pool. Using a pool that is not defined by JOB_POOLS causes an error by ninja at build time.
- SOURCES
- Specify additional source files to be included in the custom target. Specified source files will be added to IDE project files for convenience in editing even if they have no build rules.
- VERBATIM
- All arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before add_custom_target even sees the arguments. Use of VERBATIM is recommended as it enables correct behavior. When VERBATIM is not given the behavior is platform specific because there is no protection of tool-specific special characters.
- USES_TERMINAL
- New in version 3.2. The command will be given direct access to the terminal if possible. With the Ninja generator, this places the command in the console pool.
- WORKING_DIRECTORY
- Execute the command with the given current working directory. If it is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. New in version 3.13: Arguments to WORKING_DIRECTORY may use generator expressions.
Ninja Multi-Config
New in version 3.20: add_custom_target supports the Ninja Multi-Config generator's cross-config capabilities. See the generator documentation for more information.add_definitions
Add -D define flags to the compilation of source files.add_definitions(-DFOO -DBAR ...)
This command has been superseded by
alternatives:
- •
- Use add_compile_definitions() to add preprocessor definitions.
- •
- Use include_directories() to add include directories.
- •
- Use add_compile_options() to add other options.
add_dependencies
Add a dependency between top-level targets.add_dependencies(<target> [<target-dependency>]...)
add_executable
Add an executable to the project using the specified source files.Normal Executables
add_executable(<name> [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [source1] [source2 ...])
Imported Executables
add_executable(<name> IMPORTED [GLOBAL])
Alias Executables
add_executable(<name> ALIAS <target>)
add_library
Add a library to the project using the specified source files.Normal Libraries
add_library(<name> [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [<source>...])
Object Libraries
add_library(<name> OBJECT [<source>...])
add_library(... $<TARGET_OBJECTS:objlib> ...) add_executable(... $<TARGET_OBJECTS:objlib> ...)
Interface Libraries
add_library(<name> INTERFACE)
- •
- set_property(),
- •
- target_link_libraries(INTERFACE),
- •
- target_link_options(INTERFACE),
- •
- target_include_directories(INTERFACE),
- •
- target_compile_options(INTERFACE),
- •
- target_compile_definitions(INTERFACE), and
- •
- target_sources(INTERFACE),
add_library(<name> INTERFACE [<source>...] [EXCLUDE_FROM_ALL])
In most command signatures where the
INTERFACE keyword appears, the items listed after it only become part
of that target's usage requirements and are not part of the target's own
settings. However, in this signature of add_library, the
INTERFACE keyword refers to the library type only. Sources listed after
it in the add_library call are PRIVATE to the interface library
and do not appear in its INTERFACE_SOURCES target property.
Imported Libraries
add_library(<name> <type> IMPORTED [GLOBAL])
- STATIC, SHARED, MODULE, UNKNOWN
- References a library file located outside the project. The IMPORTED_LOCATION target property (or its per-configuration variant IMPORTED_LOCATION_<CONFIG>) specifies the location of the main library file on disk:
- •
- For a SHARED library on most non-Windows platforms, the main library file is the .so or .dylib file used by both linkers and dynamic loaders. If the referenced library file has a SONAME (or on macOS, has a LC_ID_DYLIB starting in @rpath/), the value of that field should be set in the IMPORTED_SONAME target property. If the referenced library file does not have a SONAME, but the platform supports it, then the IMPORTED_NO_SONAME target property should be set.
- •
- For a SHARED library on Windows, the IMPORTED_IMPLIB target property (or its per-configuration variant IMPORTED_IMPLIB_<CONFIG>) specifies the location of the DLL import library file ( .lib or .dll.a) on disk, and the IMPORTED_LOCATION is the location of the .dll runtime library (and is optional, but needed by the TARGET_RUNTIME_DLLS generator expression).
- OBJECT
- References a set of object files located outside the project. The IMPORTED_OBJECTS target property (or its per-configuration variant IMPORTED_OBJECTS_<CONFIG>) specifies the locations of object files on disk. Additional usage requirements may be specified in INTERFACE_* properties.
- INTERFACE
- Does not reference any library or object files on disk, but may specify usage requirements in INTERFACE_* properties.
Alias Libraries
add_library(<name> ALIAS <target>)
add_link_options
New in version 3.13.add_link_options(<option> ...)
This command cannot be used to add options for
static library targets, since they do not use a linker. To add archiver or
MSVC librarian flags, see the STATIC_LIBRARY_OPTIONS target
property.
Host And Device Specific Link Options
New in version 3.18: 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.Option De-duplication
The final set of 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.Handling Compiler Driver Differences
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.Specifying the SHELL: prefix anywhere
other than at the beginning of the LINKER: prefix is not
supported.
add_subdirectory
Add a subdirectory to the build.add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL] [SYSTEM])
add_test
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])
- COMMAND
- Specify the test command-line. If <command> specifies an executable target (created by add_executable()) it will automatically be replaced by the location of the executable created at build time. The command may be specified using generator expressions.
- CONFIGURATIONS
- Restrict execution of the test only to the named configurations.
- WORKING_DIRECTORY
- Set the WORKING_DIRECTORY test property to specify the working directory in which to execute the test. If not specified the test will be run with the current working directory set to the build directory corresponding to the current source directory. The working directory may be specified using generator expressions.
- COMMAND_EXPAND_LISTS
- New in version 3.16. Lists in COMMAND arguments will be expanded, including those created with generator expressions.
add_test(NAME mytest COMMAND testDriver --config $<CONFIG> --exe $<TARGET_FILE:myexe>)
CMake will generate tests only if the
enable_testing() command has been invoked. The CTest module
invokes the command automatically unless the BUILD_TESTING option is
turned OFF.
add_test(<name> <command> [<arg>...])
aux_source_directory
Find all source files in a directory.aux_source_directory(<dir> <variable>)
build_command
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>] [PARALLEL_LEVEL <parallel>] [TARGET <target>] [PROJECT_NAME <projname>] # legacy, causes warning )
<cmake> --build . [--config <config>] [--parallel <parallel>] [--target <target>...] [-- -i]
build_command(<cachevariable> <makecommand>)
In CMake versions prior to 3.0 this command
returned a command line that directly invokes the native build tool for the
current generator. Their implementation of the PROJECT_NAME option had
no useful effects, so CMake now warns on use of the option.
create_test_sourcelist
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)
define_property
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...]] [INITIALIZE_FROM_VARIABLE <variable>])
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
- •
- DIRECTORY scope chains to its parent directory's scope, continuing the walk up parent directories until a directory has the property set or there are no more parents. If still not found at the top level directory, it chains to the GLOBAL scope.
- •
- TARGET, SOURCE and TEST properties chain to DIRECTORY scope, including further chaining up the directories, etc. as needed.
enable_language
Enable languages (CXX/C/OBJC/OBJCXX/Fortran/etc)enable_language(<lang>... [OPTIONAL])
enable_testing
Enable testing for current directory and below.enable_testing()
export
Export targets or packages for outside projects to use them directly from the current project's build tree, without installation.Synopsis
export( TARGETS <target>... [...]) export( EXPORT <export-name> [...]) export( PACKAGE <PackageName>)
Exporting Targets
export(TARGETS <target>... [NAMESPACE <namespace>] [APPEND] FILE <filename> [EXPORT_LINK_INTERFACE_LIBRARIES] [CXX_MODULES_DIRECTORY <directory>])
- NAMESPACE <namespace>
- Prepend the <namespace> string to all target names written to the file.
- APPEND
- Append to the file instead of overwriting it. This can be used to incrementally export multiple targets to the same file.
- EXPORT_LINK_INTERFACE_LIBRARIES
- Include the contents of the properties named with the pattern (IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)? in the export, even when policy CMP0022 is NEW. This is useful to support consumers using CMake versions older than 2.8.12.
Experimental. Gated by
CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API
Object Libraries under Xcode
have special handling if multiple architectures are listed in
CMAKE_OSX_ARCHITECTURES. In this case they will be exported as
Interface Libraries with no object files available to clients. This is
sufficient to satisfy transitive usage requirements of other targets that link
to the object libraries in their implementation.
Exporting Targets to Android.mk
export(TARGETS <target>... ANDROID_MK <filename>)
Exporting Targets matching install(EXPORT)
export(EXPORT <export-name> [NAMESPACE <namespace>] [FILE <filename>] [CXX_MODULES_DIRECTORY <directory>])
Exporting Packages
export(PACKAGE <PackageName>)
fltk_wrap_ui
Create FLTK user interfaces Wrappers.fltk_wrap_ui(resultingLibraryName source1 source2 ... sourceN )
get_source_file_property
Get a property for a source file.get_source_file_property(<variable> <file> [DIRECTORY <dir> | TARGET_DIRECTORY <target>] <property>)
- DIRECTORY <dir>
- The source file property will be read from the <dir> directory's scope. CMake must already know about that source directory, either by having added it through a call to add_subdirectory() or <dir> being the top level source directory. Relative paths are treated as relative to the current source directory.
- TARGET_DIRECTORY <target>
- The source file property will be read from the directory scope in which <target> was created (<target> must therefore already exist).
The GENERATED source file property may
be globally visible. See its documentation for details.
get_target_property
Get a property from a target.get_target_property(<VAR> target property)
get_test_property
Get a property of the test.get_test_property(test property VAR)
include_directories
Add include directories to the build.include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])
Prefer the target_include_directories()
command to add include directories to individual targets and optionally
propagate/export them to dependents.
include_external_msproject
Include an external Microsoft project file in a workspace.include_external_msproject(projectname location [TYPE projectTypeGUID] [GUID projectGUID] [PLATFORM platformName] dep1 dep2 ...)
include_regular_expression
Set the regular expression used for dependency checking.include_regular_expression(regex_match [regex_complain])
regex_match = "^.*$" (match everything) regex_complain = "^$" (match empty string only)
install
Specify rules to run at install time.Synopsis
install( TARGETS <target>... [...]) install( IMPORTED_RUNTIME_ARTIFACTS <target>... [...]) install({ FILES | PROGRAMS} <file>... [...]) install( DIRECTORY <dir>... [...]) install( SCRIPT <file> [...]) install( CODE <code> [...]) install( EXPORT <export-name> [...]) install( RUNTIME_DEPENDENCY_SET <set-name> [...])
Introduction
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.- DESTINATION
- Specify the directory on disk to which a file will be installed. Arguments can be relative or absolute paths. 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. In particular, there is no need to make paths absolute by prepending CMAKE_INSTALL_PREFIX; this prefix is used by default if the DESTINATION is a relative path.
- PERMISSIONS
- Specify permissions for installed files. Valid permissions are OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_WRITE, GROUP_EXECUTE, WORLD_READ, WORLD_WRITE, WORLD_EXECUTE, SETUID, and SETGID. Permissions that do not make sense on certain platforms are ignored on those platforms.
- CONFIGURATIONS
- Specify a list of build configurations for which the install rule applies (Debug, Release, etc.). Note that the values specified for this option only apply to options listed AFTER the CONFIGURATIONS option. For example, to set separate install paths for the Debug and Release configurations, do the following:
install(TARGETS target CONFIGURATIONS Debug RUNTIME DESTINATION Debug/bin) install(TARGETS target CONFIGURATIONS Release RUNTIME DESTINATION Release/bin)
- COMPONENT
- Specify an installation component name with which the install rule is associated, such as Runtime or Development. During component-specific installation only install rules associated with the given component name will be executed. During a full installation all components are installed unless marked with EXCLUDE_FROM_ALL. If COMPONENT is not provided a default component "Unspecified" is created. The default component name may be controlled with the CMAKE_INSTALL_DEFAULT_COMPONENT_NAME variable.
- EXCLUDE_FROM_ALL
- New in version 3.6. Specify that the file is excluded from a full installation and only installed as part of a component-specific installation
- RENAME
- Specify a name for an installed file that may be different from the original file. Renaming is allowed only when a single file is installed by the command.
- OPTIONAL
- Specify that it is not an error if the file to be installed does not exist.
Installing Targets
install(TARGETS targets... [EXPORT <export-name>] [RUNTIME_DEPENDENCIES args...|RUNTIME_DEPENDENCY_SET <set-name>] [[ARCHIVE|LIBRARY|RUNTIME|OBJECTS|FRAMEWORK|BUNDLE| PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE|FILE_SET <set-name>|CXX_MODULES_BMI] [DESTINATION <dir>] [PERMISSIONS permissions...] [CONFIGURATIONS [Debug|Release|...]] [COMPONENT <component>] [NAMELINK_COMPONENT <component>] [OPTIONAL] [EXCLUDE_FROM_ALL] [NAMELINK_ONLY|NAMELINK_SKIP] ] [...] [INCLUDES DESTINATION [<dir> ...]] )
- ARCHIVE
- Target artifacts of this kind include:
- •
- Static libraries (except on macOS when marked as FRAMEWORK, see below);
- •
- DLL import libraries (on all Windows-based systems including Cygwin; they have extension .lib, in contrast to the .dll libraries that go to RUNTIME);
- •
- On AIX, the linker import file created for executables with ENABLE_EXPORTS enabled.
- LIBRARY
- Target artifacts of this kind include:
- •
- Shared libraries, except
- •
- DLLs (these go to RUNTIME, see below),
- •
- on macOS when marked as FRAMEWORK (see below).
- RUNTIME
- Target artifacts of this kind include:
- •
- Executables (except on macOS when marked as MACOSX_BUNDLE, see BUNDLE below);
- •
- DLLs (on all Windows-based systems including Cygwin; note that the accompanying import libraries are of kind ARCHIVE).
- OBJECTS
- New in version 3.9. Object files associated with object libraries.
- FRAMEWORK
- Both static and shared libraries marked with the FRAMEWORK property are treated as FRAMEWORK targets on macOS.
- BUNDLE
- Executables marked with the MACOSX_BUNDLE property are treated as BUNDLE targets on macOS.
- PUBLIC_HEADER
- Any PUBLIC_HEADER files associated with a library are installed in the destination specified by the PUBLIC_HEADER argument on non-Apple platforms. Rules defined by this argument are ignored for FRAMEWORK libraries on Apple platforms because the associated files are installed into the appropriate locations inside the framework folder. See PUBLIC_HEADER for details.
- PRIVATE_HEADER
- Similar to PUBLIC_HEADER, but for PRIVATE_HEADER files. See PRIVATE_HEADER for details.
- RESOURCE
- Similar to PUBLIC_HEADER and PRIVATE_HEADER, but for RESOURCE files. See RESOURCE for details.
- FILE_SET <set>
- New in version 3.23. File sets are defined by the target_sources(FILE_SET) command. If the file set <set> exists and is PUBLIC or INTERFACE, any files in the set are installed under the destination (see below). The directory structure relative to the file set's base directories is preserved. For example, a file added to the file set as /blah/include/myproj/here.h with a base directory /blah/include would be installed to myproj/here.h below the destination.
Experimental. Gated by
CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API
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 |
FILE_SET (type HEADERS) | ${CMAKE_INSTALL_INCLUDEDIR} | include |
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 )
- NAMELINK_COMPONENT
- New in version 3.12. On some platforms a versioned shared library has a symbolic link such as:
lib<name>.so -> lib<name>.so.1
install(TARGETS mylib LIBRARY COMPONENT Libraries NAMELINK_COMPONENT Development PUBLIC_HEADER COMPONENT Development )
- NAMELINK_ONLY
- This option causes the installation of only the namelink when a library target is installed. On platforms where versioned shared libraries do not have namelinks or when a library is not versioned, the NAMELINK_ONLY option installs nothing. It is an error to use this parameter outside of a LIBRARY block. 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.
- NAMELINK_SKIP
- Similar to NAMELINK_ONLY, but it has the opposite effect: it causes the installation of library files other than the namelink when a library target is installed. When neither NAMELINK_ONLY or NAMELINK_SKIP are given, both portions are installed. On platforms where versioned shared libraries do not have symlinks or when a library is not versioned, NAMELINK_SKIP installs the library. It is an error to use this parameter outside of a LIBRARY block. If NAMELINK_SKIP is specified, NAMELINK_COMPONENT has no effect. It is not recommended to use NAMELINK_SKIP in conjunction with NAMELINK_COMPONENT.
- EXPORT
- This option associates the installed target files with an export called <export-name>. It must appear before any target options. To actually install the export file itself, call install(EXPORT), documented below. See documentation of the EXPORT_NAME target property to change the name of the exported target. If EXPORT is used and the targets include PUBLIC or INTERFACE file sets, all of them must be specified with FILE_SET arguments. All PUBLIC or INTERFACE file sets associated with a target are included in the export.
- INCLUDES DESTINATION
- This option specifies a list of directories which will be added to the INTERFACE_INCLUDE_DIRECTORIES target property of the <targets> when exported by the install(EXPORT) command. If a relative path is specified, it is treated as relative to the $<INSTALL_PREFIX>.
- RUNTIME_DEPENDENCY_SET
- New in version 3.21. This option causes all runtime dependencies of installed executable, shared library, and module targets to be added to the specified runtime dependency set. This set can then be installed with an install(RUNTIME_DEPENDENCY_SET) command. This keyword and the RUNTIME_DEPENDENCIES keyword are mutually exclusive.
- RUNTIME_DEPENDENCIES
- New in version 3.21. This option causes all runtime dependencies of installed executable, shared library, and module targets to be installed along with the targets themselves. The RUNTIME, LIBRARY, FRAMEWORK, and generic arguments are used to determine the properties ( DESTINATION, COMPONENT, etc.) of the installation of these dependencies. RUNTIME_DEPENDENCIES is semantically equivalent to the following pair of calls:
install(TARGETS ... RUNTIME_DEPENDENCY_SET <set-name>) install(RUNTIME_DEPENDENCY_SET <set-name> args...)
- •
- DIRECTORIES
- •
- PRE_INCLUDE_REGEXES
- •
- PRE_EXCLUDE_REGEXES
- •
- POST_INCLUDE_REGEXES
- •
- POST_EXCLUDE_REGEXES
- •
- POST_INCLUDE_FILES
- •
- POST_EXCLUDE_FILES
install(TARGETS myExe mySharedLib myStaticLib RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib/static) install(TARGETS mySharedLib DESTINATION /some/full/path)
Installing Imported Runtime Artifacts
New in version 3.21.install(IMPORTED_RUNTIME_ARTIFACTS targets... [RUNTIME_DEPENDENCY_SET <set-name>] [[LIBRARY|RUNTIME|FRAMEWORK|BUNDLE] [DESTINATION <dir>] [PERMISSIONS permissions...] [CONFIGURATIONS [Debug|Release|...]] [COMPONENT <component>] [OPTIONAL] [EXCLUDE_FROM_ALL] ] [...] )
Installing Files
NOTE:If installing header files, consider using
file sets defined by target_sources(FILE_SET) instead. File sets
associate headers with a target and they install as part of the target.
install(<FILES|PROGRAMS> files... TYPE <type> | DESTINATION <dir> [PERMISSIONS permissions...] [CONFIGURATIONS [Debug|Release|...]] [COMPONENT <component>] [RENAME <name>] [OPTIONAL] [EXCLUDE_FROM_ALL])
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 |
include(GNUInstallDirs) install(FILES logo.png DESTINATION ${CMAKE_INSTALL_DOCDIR}/myproj )
Installing Directories
NOTE:To install a directory sub-tree of headers,
consider using file sets defined by target_sources(FILE_SET) instead.
File sets not only preserve directory structure, they also associate headers
with a target and install as part of the target.
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...]] [...])
install(DIRECTORY src/ DESTINATION doc/myproj FILES_MATCHING PATTERN "*.png")
install(DIRECTORY icons scripts/ DESTINATION share/myproj PATTERN "CVS" EXCLUDE PATTERN "scripts/*" PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_EXECUTE GROUP_READ)
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 |
Custom Installation Logic
install([[SCRIPT <file>] [CODE <code>]] [ALL_COMPONENTS | COMPONENT <component>] [EXCLUDE_FROM_ALL] [...])
install(CODE "MESSAGE(\"Sample install message.\")")
Installing Exports
install(EXPORT <export-name> DESTINATION <dir> [NAMESPACE <namespace>] [FILE <name>.cmake] [PERMISSIONS permissions...] [CONFIGURATIONS [Debug|Release|...] [CXX_MODULES_DIRECTORY <directory>] [EXPORT_LINK_INTERFACE_LIBRARIES] [COMPONENT <component>] [EXCLUDE_FROM_ALL]) install(EXPORT_ANDROID_MK <export-name> DESTINATION <dir> [...])
The installed <export-name>.cmake
file may come with additional per-configuration
<export-name>-*.cmake files to be loaded by globbing. Do not use
an export name that is the same as the package name in combination with
installing a <package-name>-config.cmake file or the latter may
be incorrectly matched by the glob and loaded.
Experimental. Gated by
CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API
install(TARGETS myexe EXPORT myproj DESTINATION bin) install(EXPORT myproj NAMESPACE mp_ DESTINATION lib/myproj) install(EXPORT_ANDROID_MK myproj DESTINATION share/ndk-modules)
This command supersedes the
install_targets() command and the PRE_INSTALL_SCRIPT and
POST_INSTALL_SCRIPT target properties. It also replaces the
FILES forms of the install_files() and install_programs()
commands. The processing order of these install rules relative to those
generated by install_targets(), install_files(), and
install_programs() commands is not defined.
Installing Runtime Dependencies
New in version 3.21.install(RUNTIME_DEPENDENCY_SET <set-name> [[LIBRARY|RUNTIME|FRAMEWORK] [DESTINATION <dir>] [PERMISSIONS permissions...] [CONFIGURATIONS [Debug|Release|...]] [COMPONENT <component>] [NAMELINK_COMPONENT <component>] [OPTIONAL] [EXCLUDE_FROM_ALL] ] [...] [PRE_INCLUDE_REGEXES regexes...] [PRE_EXCLUDE_REGEXES regexes...] [POST_INCLUDE_REGEXES regexes...] [POST_EXCLUDE_REGEXES regexes...] [POST_INCLUDE_FILES files...] [POST_EXCLUDE_FILES files...] [DIRECTORIES directories...] )
- •
- DIRECTORIES <directories>
- •
- PRE_INCLUDE_REGEXES <regexes>
- •
- PRE_EXCLUDE_REGEXES <regexes>
- •
- POST_INCLUDE_REGEXES <regexes>
- •
- POST_EXCLUDE_REGEXES <regexes>
- •
- POST_INCLUDE_FILES <files>
- •
- POST_EXCLUDE_FILES <files>
Generated Installation Script
NOTE:Use of this feature is not recommended. Please
consider using the cmake --install instead.
- COMPONENT
- Set this variable to install only a single CPack component as opposed to all of them. For example, if you only want to install the Development component, run cmake -DCOMPONENT=Development -P cmake_install.cmake.
- BUILD_TYPE
- Set this variable to change the build type if you are using a multi-config generator. For example, to install with the Debug configuration, run cmake -DBUILD_TYPE=Debug -P cmake_install.cmake.
- DESTDIR
- This is an environment variable rather than a CMake variable. It allows you to change the installation prefix on UNIX systems. See DESTDIR for details.
link_directories
Add directories in which the linker will look for libraries.link_directories([AFTER|BEFORE] directory1 [directory2 ...])
This command is rarely necessary and should be
avoided where there are other choices. Prefer to pass full absolute paths to
libraries where possible, since this ensures the correct library will always
be linked. The find_library() command provides the full path, which can
generally be used directly in calls to target_link_libraries().
Situations where a library search path may be needed include:
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.
- •
- Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).
- •
- Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).
link_libraries
Link libraries to all targets added later.link_libraries([item1 [item2 [...]]] [[debug|optimized|general] <item>] ...)
The target_link_libraries() command
should be preferred whenever possible. Library dependencies are chained
automatically, so directory-wide specification of link libraries is rarely
needed.
load_cache
Load in the values from another project's CMake cache.load_cache(pathToBuildDirectory READ_WITH_PREFIX prefix entry1...)
load_cache(pathToBuildDirectory [EXCLUDE entry1...] [INCLUDE_INTERNALS entry1...])
project
Set the name of the project.Synopsis
project(<PROJECT-NAME> [<language-name>...]) project(<PROJECT-NAME> [VERSION <major>[.<minor>[.<patch>[.<tweak>]]]] [DESCRIPTION <project-description-string>] [HOMEPAGE_URL <url-string>] [LANGUAGES <language-name>...])
- PROJECT_SOURCE_DIR, <PROJECT-NAME>_SOURCE_DIR
- Absolute path to the source directory for the project.
- PROJECT_BINARY_DIR, <PROJECT-NAME>_BINARY_DIR
- Absolute path to the binary directory for the project.
- PROJECT_IS_TOP_LEVEL, <PROJECT-NAME>_IS_TOP_LEVEL
- New in version 3.21. Boolean value indicating whether the project is top-level.
Options
The options are:- VERSION <version>
- Optional; may not be used unless policy CMP0048 is set to NEW. Takes a <version> argument composed of non-negative integer components, i.e. <major>[.<minor>[.<patch>[.<tweak>]]], and sets the variables
- •
- PROJECT_VERSION, <PROJECT-NAME>_VERSION
- •
- PROJECT_VERSION_MAJOR, <PROJECT-NAME>_VERSION_MAJOR
- •
- PROJECT_VERSION_MINOR, <PROJECT-NAME>_VERSION_MINOR
- •
- PROJECT_VERSION_PATCH, <PROJECT-NAME>_VERSION_PATCH
- •
- PROJECT_VERSION_TWEAK, <PROJECT-NAME>_VERSION_TWEAK.
- DESCRIPTION <project-description-string>
- New in version 3.9. Optional. Sets the variables
- •
- PROJECT_DESCRIPTION, <PROJECT-NAME>_DESCRIPTION
- HOMEPAGE_URL <url-string>
- New in version 3.12. Optional. Sets the variables
- •
- PROJECT_HOMEPAGE_URL, <PROJECT-NAME>_HOMEPAGE_URL
- LANGUAGES <language-name>...
- Optional. Can also be specified without LANGUAGES keyword per the first, short signature. 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, HIP, ISPC, 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. New in version 3.8: Added CUDA support. New in version 3.16: Added OBJC and OBJCXX support. New in version 3.18: Added ISPC support. If enabling ASM, list it last so that CMake can check whether compilers for other languages like C work for assembly too.
Code Injection
A number of variables can be defined by the user to specify files to include at different points during the execution of the project() command. The following outlines the steps performed during a project() call:- •
- New in version 3.15: For every project() call regardless of the project name, include the file named by CMAKE_PROJECT_INCLUDE_BEFORE, if set.
- •
- New in version 3.17: If the project() command specifies <PROJECT-NAME> as its project name, include the file named by CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE_BEFORE, if set.
- •
- Set the various project-specific variables detailed in the Synopsis and Options sections above.
- •
- For the very first project() call only:
- •
- If CMAKE_TOOLCHAIN_FILE is set, read it at least once. It may be read multiple times and it may also be read again when enabling languages later (see below).
- •
- Set the variables describing the host and target platforms. Language-specific variables might or might not be set at this point. On the first run, the only language-specific variables that might be defined are those a toolchain file may have set. On subsequent runs, language-specific variables cached from a previous run may be set.
- •
- New in version 3.24: Include each file listed in CMAKE_PROJECT_TOP_LEVEL_INCLUDES, if set. The variable is ignored by CMake thereafter.
- •
- Enable any languages specified in the call, or the default languages if none were provided. The toolchain file may be re-read when enabling a language for the first time.
- •
- New in version 3.15: For every project() call regardless of the project name, include the file named by CMAKE_PROJECT_INCLUDE, if set.
- •
- If the project() command specifies <PROJECT-NAME> as its project name, include the file named by CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE, if set.
Usage
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).Call the project() command near the top
of the top-level CMakeLists.txt, but after calling
cmake_minimum_required(). It is important to establish version and
policy settings before invoking other commands whose behavior they may affect.
See also policy CMP0000.
remove_definitions
Remove -D define flags added by add_definitions().remove_definitions(-DFOO -DBAR ...)
set_source_files_properties
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>] ...)
- DIRECTORY <dirs>...
- The source file properties will be set in each of the <dirs> directories' scopes. CMake must already know about each of these source directories, either by having added them through a call to add_subdirectory() or it being the top level source directory. Relative paths are treated as relative to the current source directory.
- TARGET_DIRECTORY <targets>...
- The source file properties will be set in each of the directory scopes where any of the specified <targets> were created (the <targets> must therefore already exist).
The GENERATED source file property may
be globally visible. See its documentation for details.
set_target_properties
Targets can have properties that affect how they are built.set_target_properties(target1 target2 ... PROPERTIES prop1 value1 prop2 value2 ...)
set_tests_properties
Set a property of the tests.set_tests_properties(test1 [test2...] PROPERTIES prop1 value1 prop2 value2)
source_group
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>...])
- TREE
- New in version 3.8. CMake will automatically detect, from <src> files paths, source groups it needs to create, to keep structure of source groups analogically to the actual files and directories structure in the project. Paths of <src> files will be cut to be relative to <root>. The command fails if the paths within src do not start with root.
- PREFIX
- New in version 3.8. Source group and files located directly in <root> path, will be placed in <prefix> source groups.
- FILES
- Any source file specified explicitly will be placed in group <name>. Relative paths are interpreted with respect to the current source directory.
- REGULAR_EXPRESSION
- Any source file whose name matches the regular expression will be placed in group <name>.
source_group(base/subdir ...) source_group(outer\\inner ...) source_group(TREE <root> PREFIX sources\\inc ...)
source_group(<name> <regex>)
source_group(<name> REGULAR_EXPRESSION <regex>)
target_compile_definitions
Add compile definitions to a target.target_compile_definitions(<target> <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
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
target_compile_definitions(foo PUBLIC FOO=1)
target_compile_features
New in version 3.1.target_compile_features(<target> <PRIVATE|PUBLIC|INTERFACE> <feature> [...])
target_compile_options
Add compile options to a target.target_compile_options(<target> [BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
Arguments
If BEFORE is specified, the content will be prepended to the property instead of being appended.Option De-duplication
The final set of 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.See Also
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().target_include_directories
Add include directories to a target.target_include_directories(<target> [SYSTEM] [AFTER|BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
target_include_directories(mylib PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/mylib> $<INSTALL_INTERFACE:include/mylib> # <prefix>/include/mylib )
Creating Relocatable Packages
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.target_link_directories
New in version 3.13.target_link_directories(<target> [BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
This command is rarely necessary and should be
avoided where there are other choices. Prefer to pass full absolute paths to
libraries where possible, since this ensures the correct library will always
be linked. The find_library() command provides the full path, which can
generally be used directly in calls to target_link_libraries().
Situations where a library search path may be needed include:
- •
- Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).
- •
- Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).
target_link_libraries
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.Overview
This command has several signatures as detailed in subsections below. All of them have the general formtarget_link_libraries(<target> ... <item>... ...)
- •
- A library target name: The generated link line will have the full path to the linkable library file associated with the target. The buildsystem will have a dependency to re-link <target> if the library file changes. 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.
- •
- A full path to a library file: The generated link line will normally preserve the full path to the file. The buildsystem will have a dependency to re-link <target> if the library file changes. 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. New in version 3.8: 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.
- •
- A plain library name: The generated link line will ask the linker to search for the library (e.g. foo becomes -lfoo or foo.lib). The library name/flag is treated as a command-line string fragment and will be used with no extra quoting or escaping.
- •
- A link flag: Item names starting with -, but not -l or -framework, are treated as linker flags. Note that such flags will be treated like any other library link item for purposes of transitive dependencies, so they are generally safe to specify only as private link items that will not propagate to dependents. 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. New in version 3.13: LINK_OPTIONS target property and target_link_options() command. For earlier versions of CMake, use LINK_FLAGS property instead. The link flag is treated as a command-line string fragment and will be used with no extra quoting or escaping.
- •
- A generator expression: A $<...> generator expression may evaluate to any of the above items or to a semicolon-separated list of them. If the ... contains any ; characters, e.g. after evaluation of a ${list} variable, be sure to use an explicitly quoted argument "$<...>" so that this command receives it as a single <item>. 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.
- •
- A debug, optimized, or general keyword immediately followed by another <item>. The item following such a keyword will be used only for the corresponding build configuration. The debug keyword corresponds to the Debug configuration (or to configurations named in the DEBUG_CONFIGURATIONS global property if it is set). The optimized keyword corresponds to all other configurations. The general keyword corresponds to all configurations, and is purely optional. Higher granularity may be achieved for per-configuration rules by creating and linking to IMPORTED library targets. These keywords are interpreted immediately by this command and therefore have no special meaning when produced by a generator expression.
Libraries for a Target and/or its Dependents
target_link_libraries(<target> <PRIVATE|PUBLIC|INTERFACE> <item>... [<PRIVATE|PUBLIC|INTERFACE> <item>...]...)
Libraries for both a Target and its Dependents
target_link_libraries(<target> <item>...)
Libraries for a Target and/or its Dependents (Legacy)
target_link_libraries(<target> <LINK_PRIVATE|LINK_PUBLIC> <lib>... [<LINK_PRIVATE|LINK_PUBLIC> <lib>...]...)
Libraries for Dependents Only (Legacy)
target_link_libraries(<target> LINK_INTERFACE_LIBRARIES <item>...)
Linking Object Libraries
New in version 3.12.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)
add_library(B SHARED b.c) target_link_libraries(B PUBLIC obj)
add_executable(main main.c) target_link_libraries(main B)
add_library(obj2 OBJECT obj2.c) target_link_libraries(obj2 PUBLIC obj) add_executable(main2 main2.c) target_link_libraries(main2 obj2)
Linking Object Libraries via $<TARGET_OBJECTS>
New in version 3.21.add_library(obj3 OBJECT obj3.c) target_compile_definitions(obj3 PUBLIC OBJ3) add_executable(main3 main3.c) target_link_libraries(main3 PRIVATE a3 $<TARGET_OBJECTS:obj3> b3)
add_library(iface_obj3 INTERFACE) target_link_libraries(iface_obj3 INTERFACE obj3 $<TARGET_OBJECTS:obj3>)
add_executable(use_obj3 use_obj3.c) target_link_libraries(use_obj3 PRIVATE iface_obj3)
add_library(static3 STATIC static3.c) target_link_libraries(static3 PRIVATE iface_obj3) add_executable(use_static3 use_static3.c) target_link_libraries(use_static3 PRIVATE static3)
Referencing $<TARGET_OBJECTS> in
target_link_libraries calls worked in versions of CMake prior to 3.21
for some cases, but was not fully supported:
- •
- It did not place the object files before libraries on link lines.
- •
- It did not add an ordering dependency on the object library.
- •
- It did not work in Xcode with multiple architectures.
Cyclic Dependencies of Static Libraries
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 codeadd_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)
Creating Relocatable Packages
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.target_link_options
New in version 3.13.target_link_options(<target> [BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
This command cannot be used to add options for
static library targets, since they do not use a linker. To add archiver or
MSVC librarian flags, see the STATIC_LIBRARY_OPTIONS target
property.
IMPORTED targets only support
INTERFACE items.
Host And Device Specific Link Options
New in version 3.18: 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.Option De-duplication
The final set of 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.Handling Compiler Driver Differences
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.Specifying the SHELL: prefix anywhere
other than at the beginning of the LINKER: prefix is not
supported.
target_precompile_headers
New in version 3.16.Main Form
target_precompile_headers(<target> <INTERFACE|PUBLIC|PRIVATE> [header1...] [<INTERFACE|PUBLIC|PRIVATE> [header2...] ...])
target_precompile_headers(myTarget PUBLIC project_header.h PRIVATE [["other_header.h"]] <unordered_map> )
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>>" )
Reusing Precompile Headers
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>)
The REUSE_FROM form requires the same
set of compiler options, compiler flags and compiler definitions for both
<target> and <other_target>. Some compilers (e.g.
GCC) may issue a warning if the precompiled header file cannot be used (
-Winvalid-pch).
See Also
To disable precompile headers for specific targets, see the DISABLE_PRECOMPILE_HEADERS target property.target_sources
New in version 3.1.target_sources(<target> <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
# WRONG: starts with generator expression, but relative path used target_sources(MyTarget PRIVATE "$<$<CONFIG:Debug>:dbgsrc.cpp>") # CORRECT: absolute path used inside the generator expression target_sources(MyTarget PRIVATE "$<$<CONFIG:Debug>:${CMAKE_CURRENT_SOURCE_DIR}/dbgsrc.cpp>")
File Sets
New in version 3.23.target_sources(<target> [<INTERFACE|PUBLIC|PRIVATE> [FILE_SET <set> [TYPE <type>] [BASE_DIRS <dirs>...] [FILES <files>...]]... ]...)
Sources intended to be used via a language's
#include mechanism.
Experimental. Gated by
CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API
Experimental. Gated by
CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API
The name of the file set to create or add to.
It must contain only letters, numbers and underscores. Names starting with a
capital letter are reserved for built-in file sets predefined by CMake. The
only predefined set names are those matching the acceptable types. All other
set names must not start with a capital letter or underscore.
Every file set is associated with a particular
type of file. Only types specified above may be used and it is an error to
specify anything else. As a special case, if the name of the file set is one
of the types, the type does not need to be specified and the TYPE
<type> arguments can be omitted. For all other file set names,
TYPE is required.
An optional list of base directories of the
file set. Any relative path is treated as relative to the current source
directory (i.e. CMAKE_CURRENT_SOURCE_DIR). If no BASE_DIRS are
specified when the file set is first created, the value of
CMAKE_CURRENT_SOURCE_DIR is added. This argument supports generator
expressions.
No two base directories for a file set may be sub-directories of each other.
This requirement must be met across all base directories added to a file set,
not just those within a single call to target_sources().
An optional list of files to add to the file
set. Each file must be in one of the base directories, or a subdirectory of
one of the base directories. This argument supports generator
expressions.
If relative paths are specified, they are considered relative to
CMAKE_CURRENT_SOURCE_DIR at the time target_sources() is called.
An exception to this is a path starting with $<. Such paths are
treated as relative to the target's source directory after evaluation of
generator expressions.
- •
- HEADER_SETS
- •
- INTERFACE_HEADER_SETS
- •
- HEADER_SET
- •
- HEADER_SET_<NAME>
- •
- HEADER_DIRS
- •
- HEADER_DIRS_<NAME>
- •
- CXX_MODULE_SETS
- •
- INTERFACE_CXX_MODULE_SETS
- •
- CXX_MODULE_SET
- •
- CXX_MODULE_SET_<NAME>
- •
- CXX_MODULE_DIRS
- •
- CXX_MODULE_DIRS_<NAME>
- •
- CXX_MODULE_HEADER_UNIT_SETS
- •
- INTERFACE_CXX_MODULE_HEADER_UNIT_SETS
- •
- CXX_MODULE_HEADER_UNIT_SET
- •
- CXX_MODULE_HEADER_UNIT_SET_<NAME>
- •
- CXX_MODULE_HEADER_UNIT_DIRS
- •
- CXX_MODULE_HEADER_UNIT_DIRS_<NAME>
If the TYPE is HEADERS or
CXX_MODULE_HEADER_UNITS, and the scope of the file set is
PRIVATE or PUBLIC, all of the BASE_DIRS of the file set
are wrapped in $<BUILD_INTERFACE> and appended to this
property.
If the TYPE is HEADERS or
CXX_MODULE_HEADER_UNITS, and the scope of the file set is
INTERFACE or PUBLIC, all of the BASE_DIRS of the file set
are wrapped in $<BUILD_INTERFACE> and appended to this
property.
try_compile
Try building some code.Try Compiling Whole Projects
try_compile(<resultVar> PROJECT <projectName> SOURCE_DIR <srcdir> [BINARY_DIR <bindir>] [TARGET <targetName>] [NO_CACHE] [CMAKE_FLAGS <flags>...] [OUTPUT_VARIABLE <var>])
try_compile(<resultVar> <bindir> <srcdir> <projectName> [<targetName>] [NO_CACHE] [CMAKE_FLAGS <flags>...] [OUTPUT_VARIABLE <var>])
Try Compiling Source Files
try_compile(<resultVar> <SOURCES <srcfile...> | SOURCE_FROM_CONTENT <name> <content> | SOURCE_FROM_VAR <name> <var> | SOURCE_FROM_FILE <name> <path> >... [NO_CACHE] [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>] )
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})
try_compile(<resultVar> <bindir> <srcfile|SOURCES srcfile...> [NO_CACHE] [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>] )
- CMAKE_FLAGS <flags>...
- Specify flags of the form -DVAR:TYPE=VALUE to be passed to the cmake(1) command-line used to drive the test build. The above example shows how values for variables INCLUDE_DIRECTORIES, LINK_DIRECTORIES, and LINK_LIBRARIES are used.
- COMPILE_DEFINITIONS <defs>...
- Specify -Ddefinition arguments to pass to add_definitions() in the generated test project.
- COPY_FILE <fileName>
- Copy the built executable or static library to the given <fileName>.
- COPY_FILE_ERROR <var>
- Use after COPY_FILE to capture into variable <var> any error message encountered while trying to copy the file.
- LINK_LIBRARIES <libs>...
- Specify libraries to be linked in the generated project. The list of libraries may refer to system libraries and to Imported Targets from the calling project. If this option is specified, any -DLINK_LIBRARIES=... value given to the CMAKE_FLAGS option will be ignored.
- LINK_OPTIONS <options>...
- New in version 3.14. Specify link step options to pass to target_link_options() or to set the STATIC_LIBRARY_OPTIONS target property in the generated project, depending on the CMAKE_TRY_COMPILE_TARGET_TYPE variable.
- NO_CACHE
- New in version 3.25. The result will be stored in a normal variable rather than a cache entry. The result variable is normally cached so that a simple pattern can be used to avoid repeating the test on subsequent executions of CMake:
if(NOT DEFINED RESULTVAR) # ...(check-specific setup code)... try_compile(RESULTVAR ...) # ...(check-specific logging and cleanup code)... endif()
- OUTPUT_VARIABLE <var>
- Store the output from the build process in the given variable.
- SOURCE_FROM_CONTENT <name> <content>
- New in version 3.25. Write <content> to a file named <name> in the operation directory. This can be used to bypass the need to separately write a source file when the contents of the file are dynamically specified. The specified <name> is not allowed to contain path components. SOURCE_FROM_CONTENT may be specified multiple times.
- SOURCE_FROM_FILE <name> <path>
- New in version 3.25. Copy <path> to a file named <name> in the operation directory. This can be used to consolidate files into the operation directory, which may be useful if a source which already exists (i.e. as a stand-alone file in a project's source repository) needs to refer to other file(s) created by SOURCE_FROM_*. (Otherwise, SOURCES is usually more convenient.) The specified <name> is not allowed to contain path components.
- SOURCE_FROM_VAR <name> <var>
- New in version 3.25. Write the contents of <var> to a file named <name> in the operation directory. This is the same as SOURCE_FROM_CONTENT, but takes the contents from the specified CMake variable, rather than directly, which may be useful when passing arguments through a function which wraps try_compile. The specified <name> is not allowed to contain path components. SOURCE_FROM_VAR may be specified multiple times.
- <LANG>_STANDARD <std>
- New in version 3.8. Specify the C_STANDARD, CXX_STANDARD, OBJC_STANDARD, OBJCXX_STANDARD, or CUDA_STANDARD target property of the generated project.
- <LANG>_STANDARD_REQUIRED <bool>
- New in version 3.8. Specify the C_STANDARD_REQUIRED, CXX_STANDARD_REQUIRED, OBJC_STANDARD_REQUIRED, OBJCXX_STANDARD_REQUIRED,or CUDA_STANDARD_REQUIRED target property of the generated project.
- <LANG>_EXTENSIONS <bool>
- New in version 3.8. Specify the C_EXTENSIONS, CXX_EXTENSIONS, OBJC_EXTENSIONS, OBJCXX_EXTENSIONS, or CUDA_EXTENSIONS target property of the generated project.
Other Behavior Settings
New in version 3.4: If set, the following variables are passed in to the generated try_compile CMakeLists.txt to initialize compile target properties with default values:- •
- CMAKE_CUDA_RUNTIME_LIBRARY
- •
- CMAKE_ENABLE_EXPORTS
- •
- CMAKE_LINK_SEARCH_START_STATIC
- •
- CMAKE_LINK_SEARCH_END_STATIC
- •
- CMAKE_MSVC_RUNTIME_LIBRARY
- •
- CMAKE_POSITION_INDEPENDENT_CODE
- •
- CMAKE_WATCOM_RUNTIME_LIBRARY
- •
- CMAKE_C_STANDARD
- •
- CMAKE_C_STANDARD_REQUIRED
- •
- CMAKE_C_EXTENSIONS
- •
- CMAKE_CXX_STANDARD
- •
- CMAKE_CXX_STANDARD_REQUIRED
- •
- CMAKE_CXX_EXTENSIONS
- •
- CMAKE_OBJC_STANDARD
- •
- CMAKE_OBJC_STANDARD_REQUIRED
- •
- CMAKE_OBJC_EXTENSIONS
- •
- CMAKE_OBJCXX_STANDARD
- •
- CMAKE_OBJCXX_STANDARD_REQUIRED
- •
- CMAKE_OBJCXX_EXTENSIONS
- •
- CMAKE_CUDA_STANDARD
- •
- CMAKE_CUDA_STANDARD_REQUIRED
- •
- CMAKE_CUDA_EXTENSIONS
try_run
Try compiling and then running some code.Try Compiling and Running Source Files
try_run(<runResultVar> <compileResultVar> <SOURCES <srcfile...> | SOURCE_FROM_CONTENT <name> <content> | SOURCE_FROM_VAR <name> <var> | SOURCE_FROM_FILE <name> <path> >... [NO_CACHE] [CMAKE_FLAGS <flags>...] [COMPILE_DEFINITIONS <defs>...] [LINK_OPTIONS <options>...] [LINK_LIBRARIES <libs>...] [COMPILE_OUTPUT_VARIABLE <var>] [COPY_FILE <fileName> [COPY_FILE_ERROR <var>]] [<LANG>_STANDARD <std>] [<LANG>_STANDARD_REQUIRED <bool>] [<LANG>_EXTENSIONS <bool>] [RUN_OUTPUT_VARIABLE <var>] [RUN_OUTPUT_STDOUT_VARIABLE <var>] [RUN_OUTPUT_STDERR_VARIABLE <var>] [OUTPUT_VARIABLE <var>] [WORKING_DIRECTORY <var>] [ARGS <args>...] )
try_run(<runResultVar> <compileResultVar> <bindir> <srcfile|SOURCES srcfile...> [NO_CACHE] [CMAKE_FLAGS <flags>...] [COMPILE_DEFINITIONS <defs>...] [LINK_OPTIONS <options>...] [LINK_LIBRARIES <libs>...] [COMPILE_OUTPUT_VARIABLE <var>] [COPY_FILE <fileName> [COPY_FILE_ERROR <var>]] [<LANG>_STANDARD <std>] [<LANG>_STANDARD_REQUIRED <bool>] [<LANG>_EXTENSIONS <bool>] [RUN_OUTPUT_VARIABLE <var>] [RUN_OUTPUT_STDOUT_VARIABLE <var>] [RUN_OUTPUT_STDERR_VARIABLE <var>] [OUTPUT_VARIABLE <var>] [WORKING_DIRECTORY <var>] [ARGS <args>...] )
- COMPILE_OUTPUT_VARIABLE <var>
- Report the compile step build output in a given variable.
- OUTPUT_VARIABLE <var>
- Report the compile build output and the output from running the executable in the given variable. This option exists for legacy reasons and is only supported by the old try_run signature. Prefer COMPILE_OUTPUT_VARIABLE and RUN_OUTPUT_VARIABLE instead.
- RUN_OUTPUT_VARIABLE <var>
- Report the output from running the executable in a given variable.
- RUN_OUTPUT_STDOUT_VARIABLE <var>
- New in version 3.25. Report the output of stdout from running the executable in a given variable.
- RUN_OUTPUT_STDERR_VARIABLE <var>
- New in version 3.25. Report the output of stderr from running the executable in a given variable.
- WORKING_DIRECTORY <var>
- New in version 3.20. Run the executable in the given directory. If no WORKING_DIRECTORY is specified, the executable will run in <bindir> or the current build directory.
- ARGS <args>...
- Additional arguments to pass to the executable when running it.
Other Behavior Settings
Set the CMAKE_TRY_COMPILE_CONFIGURATION variable to choose a build configuration.Behavior when Cross Compiling
New in version 3.3: Use CMAKE_CROSSCOMPILING_EMULATOR when running cross-compiled binaries.- <runResultVar>
- Exit code if the executable were to be run on the target platform.
- <runResultVar>__TRYRUN_OUTPUT
- Output from stdout and stderr if the executable were to be run on the target platform. This is created only if the RUN_OUTPUT_VARIABLE or OUTPUT_VARIABLE option was used.
CTEST COMMANDS
These commands are available only in CTest scripts.ctest_build
Perform the CTest Build Step as a Dashboard Client.ctest_build([BUILD <build-dir>] [APPEND] [CONFIGURATION <config>] [PARALLEL_LEVEL <parallel>] [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 <build-dir>
- Specify the top-level build directory. If not given, the CTEST_BINARY_DIRECTORY variable is used.
- APPEND
- Mark Build.xml for append to results previously submitted to a dashboard server since the last ctest_start() call. Append semantics are defined by the dashboard server in use. This does not cause results to be appended to a .xml file produced by a previous call to this command.
- CONFIGURATION <config>
- Specify the build configuration (e.g. Debug). If not specified the CTEST_BUILD_CONFIGURATION variable will be checked. Otherwise the -C <cfg> option given to the ctest(1) command will be used, if any.
- PARALLEL_LEVEL <parallel>
- New in version 3.21. Specify the parallel level of the underlying build system. If not specified, the CMAKE_BUILD_PARALLEL_LEVEL environment variable will be checked.
- FLAGS <flags>
- Pass additional arguments to the underlying build command. If not specified the CTEST_BUILD_FLAGS variable will be checked. This can, e.g., be used to trigger a parallel build using the -j option of make. See the ProcessorCount module for an example.
- PROJECT_NAME <project-name>
- Ignored since CMake 3.0. Changed in version 3.14: This value is no longer required.
- TARGET <target-name>
- Specify the name of a target to build. If not specified the CTEST_BUILD_TARGET variable will be checked. Otherwise the default target will be built. This is the "all" target (called ALL_BUILD in Visual Studio Generators).
- NUMBER_ERRORS <num-err-var>
- Store the number of build errors detected in the given variable.
- NUMBER_WARNINGS <num-warn-var>
- Store the number of build warnings detected in the given variable.
- RETURN_VALUE <result-var>
- Store the return value of the native build tool in the given variable.
- CAPTURE_CMAKE_ERROR <result-var>
- New in version 3.7. Store in the <result-var> variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
- QUIET
- New in version 3.3. Suppress any CTest-specific non-error output that would have been printed to the console otherwise. The summary of warnings / errors, as well as the output from the native build tool is unaffected by this option.
ctest_configure
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>])
- BUILD <build-dir>
- Specify the top-level build directory. If not given, the CTEST_BINARY_DIRECTORY variable is used.
- SOURCE <source-dir>
- Specify the source directory. If not given, the CTEST_SOURCE_DIRECTORY variable is used.
- APPEND
- Mark Configure.xml for append to results previously submitted to a dashboard server since the last ctest_start() call. Append semantics are defined by the dashboard server in use. This does not cause results to be appended to a .xml file produced by a previous call to this command.
- OPTIONS <options>
- Specify command-line arguments to pass to the configuration tool.
- RETURN_VALUE <result-var>
- Store in the <result-var> variable the return value of the native configuration tool.
- CAPTURE_CMAKE_ERROR <result-var>
- New in version 3.7. Store in the <result-var> variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
- QUIET
- New in version 3.3. Suppress any CTest-specific non-error messages that would have otherwise been printed to the console. Output from the underlying configure command is not affected.
ctest_coverage
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] )
- BUILD <build-dir>
- Specify the top-level build directory. If not given, the CTEST_BINARY_DIRECTORY variable is used.
- APPEND
- Mark Coverage.xml for append to results previously submitted to a dashboard server since the last ctest_start() call. Append semantics are defined by the dashboard server in use. This does not cause results to be appended to a .xml file produced by a previous call to this command.
- LABELS
- Filter the coverage report to include only source files labeled with at least one of the labels specified.
- RETURN_VALUE <result-var>
- Store in the <result-var> variable 0 if coverage tools ran without error and non-zero otherwise.
- CAPTURE_CMAKE_ERROR <result-var>
- New in version 3.7. Store in the <result-var> variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
- QUIET
- New in version 3.3. Suppress any CTest-specific non-error output that would have been printed to the console otherwise. The summary indicating how many lines of code were covered is unaffected by this option.
ctest_empty_binary_directory
empties the binary directoryctest_empty_binary_directory( directory )
ctest_memcheck
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>] [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>] [OUTPUT_JUNIT <file>] [DEFECT_COUNT <defect-count-var>] [QUIET] )
- DEFECT_COUNT <defect-count-var>
- New in version 3.8. Store in the <defect-count-var> the number of defects found.
ctest_read_custom_files
read CTestCustom files.ctest_read_custom_files( directory ... )
ctest_run_script
runs a ctest -S scriptctest_run_script([NEW_PROCESS] script_file_name script_file_name1 script_file_name2 ... [RETURN_VALUE var])
ctest_sleep
sleeps for some amount of timectest_sleep(<seconds>)
ctest_sleep(<time1> <duration> <time2>)
ctest_start
Starts the testing for a given modelctest_start(<model> [<source> [<binary>]] [GROUP <group>] [QUIET]) ctest_start([<model> [<source> [<binary>]]] [GROUP <group>] APPEND [QUIET])
- <model>
- Set the dashboard model. Must be one of Experimental, Continuous, or Nightly. This parameter is required unless APPEND is specified.
- <source>
- Set the source directory. If not specified, the value of CTEST_SOURCE_DIRECTORY is used instead.
- <binary>
- Set the binary directory. If not specified, the value of CTEST_BINARY_DIRECTORY is used instead.
- GROUP <group>
- If GROUP is used, the submissions will go to the specified group on the CDash server. If no GROUP is specified, the name of the model is used by default. Changed in version 3.16: This replaces the deprecated option TRACK. Despite the name change its behavior is unchanged.
- APPEND
- If APPEND is used, the existing TAG is used rather than creating a new one based on the current time stamp. If you use APPEND, you can omit the <model> and GROUP <group> parameters, because they will be read from the generated TAG file. For example:
ctest_start(Experimental GROUP GroupExperimental)
ctest_start(APPEND)
- QUIET
- New in version 3.3. If QUIET is used, CTest will suppress any non-error messages that it otherwise would have printed to the console.
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)
ctest_submit
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] )
- PARTS <part>...
- Specify a subset of parts to submit. Valid part names 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 and DynamicAnalysis-Test.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
- FILES <file>...
- Specify an explicit list of specific files to be submitted. Each individual file must exist at the time of the call.
- SUBMIT_URL <url>
- New in version 3.14. The http or https URL of the dashboard server to send the submission to. If not given, the CTEST_SUBMIT_URL variable is used.
- BUILD_ID <result-var>
- New in version 3.15. Store in the <result-var> variable the ID assigned to this build by CDash.
- HTTPHEADER <HTTP-header>
- New in version 3.9. Specify HTTP header to be included in the request to CDash during submission. For example, CDash can be configured to only accept submissions from authenticated clients. In this case, you should provide a bearer token in your header:
ctest_submit(HTTPHEADER "Authorization: Bearer <auth-token>")
- RETRY_COUNT <count>
- Specify how many times to retry a timed-out submission.
- RETRY_DELAY <delay>
- Specify how long (in seconds) to wait after a timed-out submission before attempting to re-submit.
- RETURN_VALUE <result-var>
- Store in the <result-var> variable 0 for success and non-zero on failure.
- CAPTURE_CMAKE_ERROR <result-var>
- New in version 3.13. Store in the <result-var> variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
- QUIET
- New in version 3.3. Suppress all non-error messages that would have otherwise been printed to the console.
Submit to CDash Upload API
New in version 3.2.ctest_submit(CDASH_UPLOAD <file> [CDASH_UPLOAD_TYPE <type>] [SUBMIT_URL <url>] [BUILD_ID <result-var>] [HTTPHEADER <header>] [RETRY_COUNT <count>] [RETRY_DELAY <delay>] [RETURN_VALUE <result-var>] [QUIET])
ctest_test
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>] [OUTPUT_JUNIT <file>] [QUIET] )
- BUILD <build-dir>
- Specify the top-level build directory. If not given, the CTEST_BINARY_DIRECTORY variable is used.
- APPEND
- Mark Test.xml for append to results previously submitted to a dashboard server since the last ctest_start() call. Append semantics are defined by the dashboard server in use. This does not cause results to be appended to a .xml file produced by a previous call to this command.
- START <start-number>
- Specify the beginning of a range of test numbers.
- END <end-number>
- Specify the end of a range of test numbers.
- STRIDE <stride-number>
- Specify the stride by which to step across a range of test numbers.
- EXCLUDE <exclude-regex>
- Specify a regular expression matching test names to exclude.
- INCLUDE <include-regex>
- Specify a regular expression matching test names to include. Tests not matching this expression are excluded.
- EXCLUDE_LABEL <label-exclude-regex>
- Specify a regular expression matching test labels to exclude.
- INCLUDE_LABEL <label-include-regex>
- Specify a regular expression matching test labels to include. Tests not matching this expression are excluded.
- EXCLUDE_FIXTURE <regex>
- New in version 3.7. If a test in the set of tests to be executed requires a particular fixture, that fixture's setup and cleanup tests would normally be added to the test set automatically. This option prevents adding setup or cleanup tests for fixtures matching the <regex>. Note that all other fixture behavior is retained, including test dependencies and skipping tests that have fixture setup tests that fail.
- EXCLUDE_FIXTURE_SETUP <regex>
- New in version 3.7. Same as EXCLUDE_FIXTURE except only matching setup tests are excluded.
- EXCLUDE_FIXTURE_CLEANUP <regex>
- New in version 3.7. Same as EXCLUDE_FIXTURE except only matching cleanup tests are excluded.
- PARALLEL_LEVEL <level>
- Specify a positive number representing the number of tests to be run in parallel.
- RESOURCE_SPEC_FILE <file>
- New in version 3.16. Specify a resource specification file. See Resource Allocation for more information.
- TEST_LOAD <threshold>
- New in version 3.4. While running tests in parallel, try not to start tests when they may cause the CPU load to pass above a given threshold. If not specified the CTEST_TEST_LOAD variable will be checked, and then the --test-load command-line argument to ctest(1). See also the TestLoad setting in the CTest Test Step.
- REPEAT <mode>:<n>
- New in version 3.17. Run tests repeatedly based on the given <mode> up to <n> times. The modes are:
- UNTIL_FAIL
- Require each test to run <n> times without failing in order to pass. This is useful in finding sporadic failures in test cases.
- UNTIL_PASS
- Allow each test to run up to <n> times in order to pass. Repeats tests if they fail for any reason. This is useful in tolerating sporadic failures in test cases.
- AFTER_TIMEOUT
- Allow each test to run up to <n> times in order to pass. Repeats tests only if they timeout. This is useful in tolerating sporadic timeouts in test cases on busy machines.
- SCHEDULE_RANDOM <ON|OFF>
- Launch tests in a random order. This may be useful for detecting implicit test dependencies.
- STOP_ON_FAILURE
- New in version 3.18. Stop the execution of the tests once one has failed.
- STOP_TIME <time-of-day>
- Specify a time of day at which the tests should all stop running.
- RETURN_VALUE <result-var>
- Store in the <result-var> variable 0 if all tests passed. Store non-zero if anything went wrong.
- CAPTURE_CMAKE_ERROR <result-var>
- New in version 3.7. Store in the <result-var> variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
- OUTPUT_JUNIT <file>
- New in version 3.21. Write test results to <file> in JUnit XML format. If <file> is a relative path, it will be placed in the build directory. If <file> already exists, it will be overwritten. Note that the resulting JUnit XML file is not uploaded to CDash because it would be redundant with CTest's Test.xml file.
- QUIET
- New in version 3.3. Suppress any CTest-specific non-error messages that would have otherwise been printed to the console. Output from the underlying test command is not affected. Summary info detailing the percentage of passing tests is also unaffected by the QUIET option.
Additional Test Measurements
CTest can parse the output of your tests for extra measurements to report to CDash.std::cout << "<CTestMeasurement type=\"numeric/double\" name=\"score\">28.3</CTestMeasurement>" << std::endl; std::cout << "<CTestMeasurement type=\"text/string\" name=\"color\">red</CTestMeasurement>" << std::endl; std::cout << "<CTestMeasurement type=\"text/link\" name=\"CMake URL\">https://cmake.org</CTestMeasurement>" << std::endl; std::cout << "<CTestMeasurement type=\"text/preformatted\" name=\"Console Output\">" << "line 1.\n" << " \033[31;1m line 2. Bold red, and indented!\033[0;0ml\n" << "line 3. Not bold or indented...\n" << "</CTestMeasurement>" << std::endl;
Image Measurements
The following example demonstrates how to upload test images to CDash.std::cout << "<CTestMeasurementFile type=\"image/jpg\" name=\"TestImage\">" << "/dir/to/test_img.jpg</CTestMeasurementFile>" << std::endl; std::cout << "<CTestMeasurementFile type=\"image/gif\" name=\"ValidImage\">" << "/dir/to/valid_img.gif</CTestMeasurementFile>" << std::endl; std::cout << "<CTestMeasurementFile type=\"image/png\" name=\"AlgoResult\">" << "/dir/to/img.png</CTestMeasurementFile>" << std::endl;
- •
- TestImage
- •
- ValidImage
- •
- BaselineImage
- •
- DifferenceImage2
Attached Files
New in version 3.21.std::cout << "<CTestMeasurementFile type=\"file\" name=\"TestInputData1\">" << "/dir/to/data1.csv</CTestMeasurementFile>\n" << "<CTestMeasurementFile type=\"file\" name=\"TestInputData2\">" << "/dir/to/data2.csv</CTestMeasurementFile>" << std::endl;
Custom Details
New in version 3.21.std::cout << "<CTestDetails>My Custom Details Value</CTestDetails>" << std::endl;
Additional Labels
New in version 3.22.std::cout << "<CTestLabel>Custom Label 1</CTestLabel>\n" << "<CTestLabel>Custom Label 2</CTestLabel>" << std::endl;
ctest_update
Perform the CTest Update Step as a Dashboard Client.ctest_update([SOURCE <source-dir>] [RETURN_VALUE <result-var>] [CAPTURE_CMAKE_ERROR <result-var>] [QUIET])
- SOURCE <source-dir>
- Specify the source directory. If not given, the CTEST_SOURCE_DIRECTORY variable is used.
- RETURN_VALUE <result-var>
- Store in the <result-var> variable the number of files updated or -1 on error.
- CAPTURE_CMAKE_ERROR <result-var>
- New in version 3.13. Store in the <result-var> variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
- QUIET
- New in version 3.3. Tell CTest to suppress most non-error messages that it would have otherwise printed to the console. CTest will still report the new revision of the repository and any conflicting files that were found.
ctest_upload
Upload files to a dashboard server as a Dashboard Client.ctest_upload(FILES <file>... [QUIET] [CAPTURE_CMAKE_ERROR <result-var>])
- FILES <file>...
- Specify a list of files to be sent along with the build results to the dashboard server.
- QUIET
- New in version 3.3. Suppress any CTest-specific non-error output that would have been printed to the console otherwise.
- CAPTURE_CMAKE_ERROR <result-var>
- New in version 3.7. Store in the <result-var> variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
DEPRECATED COMMANDS
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.build_name
Disallowed since version 3.0. See CMake Policy CMP0036.build_name(variable)
exec_program
Deprecated since version 3.0: Use the execute_process() command instead.exec_program(Executable [directory in which to run] [ARGS <arguments to executable>] [OUTPUT_VARIABLE <var>] [RETURN_VALUE <var>])
export_library_dependencies
Disallowed since version 3.0. See CMake Policy CMP0033.export_library_dependencies(<file> [APPEND])
install_files
Deprecated since version 3.0: Use the install(FILES) command instead.install_files(<dir> extension file file ...)
install_files(<dir> regexp)
install_files(<dir> FILES file file ...)
install_programs
Deprecated since version 3.0: Use the install(PROGRAMS) command instead.install_programs(<dir> file1 file2 [file3 ...]) install_programs(<dir> FILES file1 [file2 ...])
install_programs(<dir> regexp)
install_targets
Deprecated since version 3.0: Use the install(TARGETS) command instead.install_targets(<dir> [RUNTIME_DIRECTORY dir] target target)
load_command
Disallowed since version 3.0. See CMake Policy CMP0031.load_command(COMMAND_NAME <loc1> [loc2 ...])
CMAKE_LOADED_COMMAND_<COMMAND_NAME>
make_directory
Deprecated since version 3.0: Use the file(MAKE_DIRECTORY) command instead.make_directory(directory)
output_required_files
Disallowed since version 3.0. See CMake Policy CMP0032.output_required_files(srcfile outputfile)
qt_wrap_cpp
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()).qt_wrap_cpp(resultingLibraryName DestName SourceLists ...)
qt_wrap_ui
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()).qt_wrap_ui(resultingLibraryName HeadersDestName SourcesDestName SourceLists ...)
remove
Deprecated since version 3.0: Use the list(REMOVE_ITEM) command instead.remove(VAR VALUE VALUE ...)
subdir_depends
Disallowed since version 3.0. See CMake Policy CMP0029.subdir_depends(subdir dep1 dep2 ...)
subdirs
Deprecated since version 3.0: Use the add_subdirectory() command instead.subdirs(dir1 dir2 ...[EXCLUDE_FROM_ALL exclude_dir1 exclude_dir2 ...] [PREORDER] )
use_mangled_mesa
Disallowed since version 3.0. See CMake Policy CMP0030.use_mangled_mesa(PATH_TO_MESA OUTPUT_DIRECTORY)
utility_source
Disallowed since version 3.0. See CMake Policy CMP0034.utility_source(cache_entry executable_name path_to_source [file1 file2 ...])
variable_requires
Disallowed since version 3.0. See CMake Policy CMP0035.variable_requires(TEST_VARIABLE RESULT_VARIABLE REQUIRED_VARIABLE1 REQUIRED_VARIABLE2 ...)
write_file
Deprecated since version 3.0: Use the file(WRITE) command instead.write_file(filename "message to write"... [APPEND])
COPYRIGHT
2000-2022 Kitware, Inc. and ContributorsNovember 30, 2022 | 3.25.1 |