cmake-commands (7) Linux Manual Page
cmake-commands – CMake Language Command Reference
Scripting Commands
These commands are always available.
break
Break from an enclosing foreach or while loop.
break()
Breaks from an enclosing foreach() or while() loop.
See also the continue() command.
cmake_host_system_information
Query host system specific information.
cmake_host_system_information(RESULT <variable> QUERY <key> ...)
Queries system information of the host system on which cmake runs. One or more <key> can be provided to select the information to be queried. The list of queried values is stored in <variable>.
<key> can be one of the following values:
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-releasefile 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-releasefileExample:
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()Output:
-- 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`
If
/etc/os-releasefile is not found, the command tries to gather OS identification via fallback scripts. The fallback script can use various distribution-specific files to collect OS identification data and map it into man 5 os-release variables.
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, whereNNNis 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
IDvariable from the manual becomesCMAKE_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.Example:
# 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 1024×1024 bytes.
cmake_language
New in version 3.18.
Call meta-operations on CMake commands.
Synopsis
cmake_language(CALL <command> [<arg>...]) cmake_language(EVAL CODE <code>...) cmake_language(DEFER <options>... CALL <command> [<arg>...])
Introduction
This command will call meta-operations on built-in CMake commands or those created via the macro() or function() commands.
cmake_language does not introduce a new variable or policy scope.
Calling Commands
cmake_language(CALL <command> [<arg>...])
Calls the named <command> with the given arguments (if any). For example, the code:
set(message_command "message")
cmake_language(CALL ${message_command} STATUS "Hello World!")
is equivalent to
message(STATUS "Hello World!")
NOTE: To ensure consistency of the code, the following commands are not allowed:
- •
if/elseif/else/endif- •
while/endwhile- •
foreach/endforeach- •
function/endfunction- •
macro/endmacro
Evaluating Code
cmake_language(EVAL CODE <code>...)
Evaluates the <code>… as CMake code.
For example, the code:
set(A TRUE)
set(B TRUE)
set(C TRUE)
set(condition "(A AND B) OR C")
cmake_language(EVAL CODE "
if (${condition})
message(STATUS TRUE)
else()
message(STATUS FALSE)
endif()"
)
is equivalent to
set(A TRUE)
set(B TRUE)
set(C TRUE)
set(condition "(A AND B) OR C")
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/eval.cmake "
if (${condition})
message(STATUS TRUE)
else()
message(STATUS FALSE)
endif()"
)
include(${CMAKE_CURRENT_BINARY_DIR}/eval.cmake)
Deferring Calls
New in version 3.19.
cmake_language(DEFER <options>... CALL <command> [<arg>...])
Schedules a call to the named <command> with the given arguments (if any) to occur at a later time. By default, deferred calls are executed as if written at the end of the current directory’s CMakeLists.txt file, except that they run even after a return() call. Variable references in arguments are evaluated at the time the deferred call is executed.
The options are:
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 letterA-Z. The<id>may begin with an underscore (_) only if it was generated automatically by an earlier call that usedID_VARto 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 (_).The currently scheduled list of deferred calls may be retrieved:
cmake_language(DEFER [DIRECTORY <dir>] GET_CALL_IDS <var>)
This will store in
<var>a semicolon-separated list of deferred call ids. The ids are for the directory scope in which the calls have been deferred to (i.e. where they will be executed), which can be different to the scope in which they were created. TheDIRECTORYoption can be used to specify the scope for which to retrieve the call ids. If that option is not given, the call ids for the current directory scope will be returned.Details of a specific call may be retrieved from its id:
cmake_language(DEFER [DIRECTORY <dir>] GET_CALL <id> <var>)
This will store in
<var>a semicolon-separated list in which the first element is the name of the command to be called, and the remaining elements are its unevaluated arguments (any contained;characters are included literally and cannot be distinguished from multiple arguments). If multiple calls are scheduled with the same id, this retrieves the first one. If no call is scheduled with the given id in the specifiedDIRECTORYscope (or the current directory scope if noDIRECTORYoption is given), this stores an empty string in the variable.Deferred calls may be canceled by their id:
cmake_language(DEFER [DIRECTORY <dir>] CANCEL_CALL <id>...)
This cancels all deferred calls matching any of the given ids in the specified
DIRECTORYscope (or the current directory scope if noDIRECTORYoption is given). Unknown ids are silently ignored.
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")
prints:
Immediate Message Deferred Message
The Cancelled Message is never printed because its command is canceled. The deferred_message variable reference is not evaluated until the call site, so it can be set after the deferred call is scheduled.
In order to evaluate variable references immediately when scheduling a deferred call, wrap it using cmake_language(EVAL). However, note that arguments will be re-evaluated in the deferred call, though that can be avoided by using bracket arguments. For example:
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")
also prints:
Immediate Message Deferred Message 1 Deferred Message 2
cmake_minimum_required
Require a minimum version of cmake.
cmake_minimum_required(VERSION <min>[...<policy_max>] [FATAL_ERROR])
New in version 3.12: The optional <policy_max> version.
Sets the minimum required version of cmake for a project. Also updates the policy settings as explained below.
<min> and the optional <policy_max> are each CMake versions of the form major.minor[.patch[.tweak]], and the … is literal.
If the running version of CMake is lower than the <min> required version it will stop processing the project and report an error. The optional <policy_max> version, if specified, must be at least the <min> version and affects policy settings as described in Policy Settings. If the running version of CMake is older than 3.12, the extra … dots will be seen as version component separators, resulting in the …<max> part being ignored and preserving the pre-3.12 behavior of basing policies on <min>.
This command will set the value of the CMAKE_MINIMUM_REQUIRED_VERSION variable to <min>.
The FATAL_ERROR option is accepted but ignored by CMake 2.6 and higher. It should be specified so CMake versions 2.4 and lower fail with an error instead of just a warning.
NOTE: 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.
When a <min> version higher than 2.4 is specified the command implicitly invokes
cmake_policy(VERSION <min>[...<max>])
which sets CMake policies based on the range of versions specified. When a <min> version 2.4 or lower is given the command implicitly invokes
cmake_policy(VERSION 2.4[...<max>])
which enables compatibility features for CMake 2.4 and lower.
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>)
New in version 3.5: This command is implemented natively. Previously, it has been defined in the module CMakeParseArguments.
This command is for use in macros or functions. It processes the arguments given to that macro or function, and defines a set of variables which hold the values of the respective options.
The first signature reads processes arguments passed in the <args>…. This may be used in either a macro() or a function().
New in version 3.7: The PARSE_ARGV signature is only for use in a function() body. In this case the arguments that are parsed come from the ARGV# variables of the calling function. The parsing starts with the <N>-th argument, where <N> is an unsigned integer. This allows for the values to have special characters like ; in them.
The <options> argument contains all options for the respective macro, i.e. keywords which can be used when calling the macro without any value following, like e.g. the OPTIONAL keyword of the install() command.
The <one_value_keywords> argument contains all keywords for this macro which are followed by one value, like e.g. DESTINATION keyword of the install() command.
The <multi_value_keywords> argument contains all keywords for this macro which can be followed by more than one value, like e.g. the TARGETS or FILES keywords of the install() command.
Changed in version 3.5: All keywords shall be unique. I.e. every keyword shall only be specified once in either <options>, <one_value_keywords> or <multi_value_keywords>. A warning will be emitted if uniqueness is violated.
When done, cmake_parse_arguments will consider for each of the keywords listed in <options>, <one_value_keywords> and <multi_value_keywords> a variable composed of the given <prefix> followed by "_" and the name of the respective keyword. These variables will then hold the respective value from the argument list or be undefined if the associated option could not be found. For the <options> keywords, these will always be defined, to TRUE or FALSE, whether the option is in the argument list or not.
All remaining arguments are collected in a variable <prefix>_UNPARSED_ARGUMENTS that will be undefined if all arguments were recognized. This can be checked afterwards to see whether your macro was called with unrecognized parameters.
New in version 3.15: <one_value_keywords> and <multi_value_keywords> that were given no values at all are collected in a variable <prefix>_KEYWORDS_MISSING_VALUES that will be undefined if all keywords received values. This can be checked to see if there were keywords without any values given.
Consider the following example macro, my_install(), which takes similar arguments to the real install() command:
macro(my_install)
set(options OPTIONAL FAST)
set(oneValueArgs DESTINATION RENAME)
set(multiValueArgs TARGETS CONFIGURATIONS)
cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}"
"${multiValueArgs}" ${ARGN} )
# ...
Assume my_install() has been called like this:
my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub CONFIGURATIONS)
After the cmake_parse_arguments call the macro will have set or undefined the following variables:
MY_INSTALL_OPTIONAL = TRUE MY_INSTALL_FAST = FALSE # was not used in call to my_install MY_INSTALL_DESTINATION = "bin" MY_INSTALL_RENAME <UNDEFINED> # was not used MY_INSTALL_TARGETS = "foo;bar" MY_INSTALL_CONFIGURATIONS <UNDEFINED> # was not used MY_INSTALL_UNPARSED_ARGUMENTS = "blub" # nothing expected after "OPTIONAL" MY_INSTALL_KEYWORDS_MISSING_VALUES = "CONFIGURATIONS" # No value for "CONFIGURATIONS" given
You can then continue and process these variables.
Keywords terminate lists of values, e.g. if directly after a one_value_keyword another recognized keyword follows, this is interpreted as the beginning of the new option. E.g. my_install(TARGETS foo DESTINATION OPTIONAL) would result in MY_INSTALL_DESTINATION set to "OPTIONAL", but as OPTIONAL is a keyword itself MY_INSTALL_DESTINATION will be empty (but added to MY_INSTALL_KEYWORDS_MISSING_VALUES) and MY_INSTALL_OPTIONAL will therefore be set to TRUE.
cmake_path
New in version 3.20.
This command is for the manipulation of paths. Only syntactic aspects of paths are handled, there is no interaction of any kind with any underlying file system. The path may represent a non-existing path or even one that is not allowed to exist on the current file system or platform. For operations that do interact with the filesystem, see the file() command.
NOTE: 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-nameis anitem-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.The
(…)*pattern shown above is to indicate that there can be zero or more item names, with multiple items separated by adirectory-separator. The()*characters are not part of the path. 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///////libis the same as/usr/lib. filename- A path has a
filenameif it does not end with adirectory-separator. Thefilenameis effectively the lastitem-nameof the path, so it can also be a hard link, symbolic link or a directory.A
filenamecan 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 thefilename. In commands that accept aLAST_ONLYkeyword,LAST_ONLYchanges 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
filenameis a period, that period is ignored (i.e. afilenamelike".profile"is treated as having no extension). - •
- If the
filenameis either.or.., it has no extension.The stem is the part of the
filenamebefore the extension.Some commands refer to a
root-path. This is the concatenation ofroot-nameandroot-directory-separator, either or both of which can be empty. Arelative-partrefers to the full path with anyroot-pathremoved.
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")
Modification and Generation sub-commands can either store the result in-place, or in a separate variable named after an OUTPUT_VARIABLE keyword. All other sub-commands store the result in a mandatory <out-var> variable.
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 followingdirectory-separator(/a/./b/. –> /a/b). - 4.
- Remove each
item-name(other than..) that is immediately followed by adirectory-separatorand a.., along with any immediately followingdirectory-separator(/a/b/../c –> a/c). - 5.
- If there is a
root-directory, remove any..and anydirectory-separatorsimmediately following them. The parent of the root directory is treated as still the root directory (/../a –> /a). - 6.
- If the last
item-nameis.., remove any trailingdirectory-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>)
If a requested component is not present in the path, an empty string will be stored in <out-var>. For example, only Windows systems have the concept of a root-name, so when the host machine is non-Windows, the ROOT_NAME subcommand will always return an empty string.
For PARENT_PATH, if the HAS_RELATIVE_PART subcommand returns false, the result is a copy of <path-var>. Note that this implies that a root directory is considered to have a parent, with that parent being itself. Where HAS_RELATIVE_PART returns true, the result will essentially be <path-var> with one less element.
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>)
Each of the above follows the predictable pattern of setting <out-var> to true if the path has the associated component, or false otherwise. Note the following special cases:
- •
- For
HAS_ROOT_PATH, a true result will only be returned if at least one ofroot-nameorroot-directoryis 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>)
Sets
<out-var>to true if<path-var>is absolute. An absolute path is a path that unambiguously identifies the location of a file without reference to an additional starting location. On Windows, this means the path must have both aroot-nameand aroot-directory-separatorto be considered absolute. On other platforms, just aroot-directory-separatoris sufficient. Note that this means on Windows,IS_ABSOLUTEcan be false whileHAS_ROOT_DIRECTORYcan be true.cmake_path(IS_RELATIVE <path-var> <out-var>)
This will store the opposite of
IS_ABSOLUTEin<out-var>.cmake_path(IS_PREFIX <path-var> <input> [NORMALIZE] <out-var>)
Checks if
<path-var>is the prefix of<input>.When the
NORMALIZEoption is specified,<path-var>and<input>are normalized before the check.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>)
Compares the lexical representations of two paths provided as string literals. No normalization is performed on either path. Equality is determined according to the following pseudo-code logic:
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.
NOTE:Unlike most othercmake_path()subcommands, theCOMPAREsubcommand takes literal strings as input, not the names of variables.
Modification
cmake_path(SET <path-var> [NORMALIZE] <input>)
Assign the <input> path to <path-var>. If <input> is a native path, it is converted into a cmake-style path with forward-slashes (/). On Windows, the long filename marker is taken into account.
When the NORMALIZE option is specified, the path is normalized before the conversion.
For example:
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}\"")
Output:
CMake path is "c:/a/b/../c" Normalized CMake path is "c:/a/c"
cmake_path(APPEND <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
Append all the <input> arguments to the <path-var> using / as the directory-separator. Depending on the <input>, the previous contents of <path-var> may be discarded. For each <input> argument, the following algorithm (pseudo-code) applies:
# <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>])
Append all the <input> arguments to the <path-var> without adding any directory-separator.
cmake_path(REMOVE_FILENAME <path-var> [OUTPUT_VARIABLE <out-var>])
Removes the filename component (as returned by GET … FILENAME) from <path-var>. After removal, any trailing directory-separator is left alone, if present.
If OUTPUT_VARIABLE is not given, then after this function returns, HAS_FILENAME returns false for <path-var>.
For example:
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}\"")
Output:
First path is "/a/" Second path is "/a/"
cmake_path(REPLACE_FILENAME <path-var> <input> [OUTPUT_VARIABLE <out-var>])
Replaces the filename component from <path-var> with <input>. If <path-var> has no filename component (i.e. HAS_FILENAME returns false), the path is unchanged. The operation is equivalent to the following:
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>])
Removes the extension, if any, from <path-var>.
cmake_path(REPLACE_EXTENSION <path-var> [LAST_ONLY] <input> [OUTPUT_VARIABLE <out-var>])
Replaces the extension with <input>. Its effect is equivalent to the following:
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>])
Normalize <path-var> according the steps described in Normalization.
cmake_path(RELATIVE_PATH <path-var> [BASE_DIRECTORY <input>] [OUTPUT_VARIABLE <out-var>])
Modifies <path-var> to make it relative to the BASE_DIRECTORY argument. If BASE_DIRECTORY is not specified, the default base directory will be CMAKE_CURRENT_SOURCE_DIR.
For reference, the algorithm used to compute the relative path is the same as that used by C++ std::filesystem::path::lexically_relative.
cmake_path(ABSOLUTE_PATH <path-var> [BASE_DIRECTORY <input>] [NORMALIZE] [OUTPUT_VARIABLE <out-var>])
If <path-var> is a relative path (IS_RELATIVE is true), it is evaluated relative to the given base directory specified by BASE_DIRECTORY option. If BASE_DIRECTORY is not specified, the default base directory will be CMAKE_CURRENT_SOURCE_DIR.
When the NORMALIZE option is specified, the path is normalized after the path computation.
Because cmake_path() does not access the filesystem, symbolic links are not resolved and any leading tilde is not expanded. To compute a real path with symbolic links resolved and leading tildes expanded, use the file(REAL_PATH) command instead.
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>)
Converts a cmake-style <path-var> into a native path with platform-specific slashes (\ on Windows hosts and / elsewhere).
When the NORMALIZE option is specified, the path is normalized before the conversion.
cmake_path(CONVERT <input> TO_CMAKE_PATH_LIST <out-var> [NORMALIZE])
Converts a native <input> path into a cmake-style path with forward slashes (/). On Windows hosts, the long filename marker is taken into account. The input can be a single path or a system search path like $ENV{PATH}. A search path will be converted to a cmake-style list separated by ; characters (on non-Windows platforms, this essentially means : separators are replaced with ;). The result of the conversion is stored in the <out-var> variable.
When the NORMALIZE option is specified, the path is normalized before the conversion.
NOTE: 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])
Converts a cmake-style <input> path into a native path with platform-specific slashes (\ on Windows hosts and / elsewhere). The input can be a single path or a cmake-style list. A list will be converted into a native search path (;-separated on Windows, :-separated on other platforms). The result of the conversion is stored in the <out-var> variable.
When the NORMALIZE option is specified, the path is normalized before the conversion.
NOTE: Unlike most other cmake_path() subcommands, the CONVERT subcommand takes a literal string as input, not the name of a variable.
For example:
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}\"")
Output on Windows:
Native path list is "
