code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>cmake-buildsystem(7) — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cmake.css" />

    <link rel="icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="cmake-commands(7)" href="cmake-commands.7.html" />
    <link rel="prev" title="ccmake(1)" href="ccmake.1.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-buildsystem(7)

cmake-buildsystem(7)¶

Contents

cmake-buildsystem(7)

Introduction

Binary Targets

Binary Executables

Binary Library Types

Normal Libraries

Apple Frameworks

Object Libraries

Build Specification and Usage Requirements

Target Properties

Transitive Usage Requirements

Compatible Interface Properties

Property Origin Debugging

Build Specification with Generator Expressions

Include Directories and Usage Requirements

Link Libraries and Generator Expressions

Output Artifacts

Runtime Output Artifacts

Library Output Artifacts

Archive Output Artifacts

Directory-Scoped Commands

Build Configurations

Case Sensitivity

Default And Custom Configurations

Pseudo Targets

Imported Targets

Alias Targets

Interface Libraries

Introduction¶

A CMake-based buildsystem is organized as a set of high-level logical
targets.  Each target corresponds to an executable or library, or
is a custom target containing custom commands.  Dependencies between the
targets are expressed in the buildsystem to determine the build order
and the rules for regeneration in response to change.

Binary Targets¶

Executables and libraries are defined using the add_executable()
and add_library() commands.  The resulting binary files have
appropriate PREFIX, SUFFIX and extensions for the
platform targeted. Dependencies between binary targets are expressed using
the target_link_libraries() command:

add_library(archive archive.cpp zip.cpp lzma.cpp)
add_executable(zipapp zipapp.cpp)
target_link_libraries(zipapp archive)

archive is defined as a STATIC library -- an archive containing objects
compiled from archive.cpp, zip.cpp, and lzma.cpp.  zipapp
is defined as an executable formed by compiling and linking zipapp.cpp.
When linking the zipapp executable, the archive static library is
linked in.

Binary Executables¶

The add_executable() command defines an executable target:

add_executable(mytool mytool.cpp)

Commands such as add_custom_command(), which generates rules to be
run at build time can transparently use an EXECUTABLE
target as a COMMAND executable.  The buildsystem rules will ensure that
the executable is built before attempting to run the command.

Binary Library Types¶

Normal Libraries¶

By default, the add_library() command defines a STATIC library,
unless a type is specified.  A type may be specified when using the command:

add_library(archive SHARED archive.cpp zip.cpp lzma.cpp)

add_library(archive STATIC archive.cpp zip.cpp lzma.cpp)

The BUILD_SHARED_LIBS variable may be enabled to change the
behavior of add_library() to build shared libraries by default.

In the context of the buildsystem definition as a whole, it is largely
irrelevant whether particular libraries are SHARED or STATIC --
the commands, dependency specifications and other APIs work similarly
regardless of the library type.  The MODULE library type is
dissimilar in that it is generally not linked to -- it is not used in
the right-hand-side of the target_link_libraries() command.
It is a type which is loaded as a plugin using runtime techniques.
If the library does not export any unmanaged symbols (e.g. Windows
resource DLL, C++/CLI DLL), it is required that the library not be a
SHARED library because CMake expects SHARED libraries to export
at least one symbol.

add_library(archive MODULE 7z.cpp)

Apple Frameworks¶

A SHARED library may be marked with the FRAMEWORK
target property to create an macOS or iOS Framework Bundle.
A library with the FRAMEWORK target property should also set the
FRAMEWORK_VERSION target property.  This property is typically
set to the value of "A" by macOS conventions.
The MACOSX_FRAMEWORK_IDENTIFIER sets the CFBundleIdentifier key
and it uniquely identifies the bundle.

add_library(MyFramework SHARED MyFramework.cpp)
set_target_properties(MyFramework PROPERTIES
  FRAMEWORK TRUE
  FRAMEWORK_VERSION A # Version "A" is macOS convention
  MACOSX_FRAMEWORK_IDENTIFIER org.cmake.MyFramework
)

Object Libraries¶

The OBJECT library type defines a non-archival collection of object files
resulting from compiling the given source files.  The object files collection
may be used as source inputs to other targets by using the syntax
$<TARGET_OBJECTS:name>.  This is a
generator expression that can be
used to supply the OBJECT library content to other targets:

add_library(archive OBJECT archive.cpp zip.cpp lzma.cpp)

add_library(archiveExtras STATIC $<TARGET_OBJECTS:archive> extras.cpp)

add_executable(test_exe $<TARGET_OBJECTS:archive> test.cpp)

The link (or archiving) step of those other targets will use the object
files collection in addition to those from their own sources.

Alternatively, object libraries may be linked into other targets:

add_library(archive OBJECT archive.cpp zip.cpp lzma.cpp)

add_library(archiveExtras STATIC extras.cpp)
target_link_libraries(archiveExtras PUBLIC archive)

add_executable(test_exe test.cpp)
target_link_libraries(test_exe archive)

The link (or archiving) step of those other targets will use the object
files from OBJECT libraries that are directly linked.  Additionally,
usage requirements of the OBJECT libraries will be honored when compiling
sources in those other targets.  Furthermore, those usage requirements
will propagate transitively to dependents of those other targets.

Object libraries may not be used as the TARGET in a use of the
add_custom_command(TARGET) command signature.  However,
the list of objects can be used by add_custom_command(OUTPUT)
or file(GENERATE) by using $<TARGET_OBJECTS:objlib>.

Build Specification and Usage Requirements¶

The target_include_directories(), target_compile_definitions()
and target_compile_options() commands specify the build specifications
and the usage requirements of binary targets.  The commands populate the
INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and
COMPILE_OPTIONS target properties respectively, and/or the
INTERFACE_INCLUDE_DIRECTORIES, INTERFACE_COMPILE_DEFINITIONS
and INTERFACE_COMPILE_OPTIONS target properties.

Each of the commands has a PRIVATE, PUBLIC and INTERFACE mode.  The
PRIVATE mode populates only the non-INTERFACE_ variant of the target
property and the INTERFACE mode populates only the INTERFACE_ variants.
The PUBLIC mode populates both variants of the respective target property.
Each command may be invoked with multiple uses of each keyword:

target_compile_definitions(archive
  PRIVATE BUILDING_WITH_LZMA
  INTERFACE USING_ARCHIVE_LIB
)

Note that usage requirements are not designed as a way to make downstreams
use particular COMPILE_OPTIONS or
COMPILE_DEFINITIONS etc for convenience only.  The contents of
the properties must be requirements, not merely recommendations or
convenience.

See the Creating Relocatable Packages section of the
cmake-packages(7) manual for discussion of additional care
that must be taken when specifying usage requirements while creating
packages for redistribution.

Target Properties¶

The contents of the INCLUDE_DIRECTORIES,
COMPILE_DEFINITIONS and COMPILE_OPTIONS target
properties are used appropriately when compiling the source files of a
binary target.

Entries in the INCLUDE_DIRECTORIES are added to the compile line
with -I or -isystem prefixes and in the order of appearance in the
property value.

Entries in the COMPILE_DEFINITIONS are prefixed with -D or
/D and added to the compile line in an unspecified order.  The
DEFINE_SYMBOL target property is also added as a compile
definition as a special convenience case for SHARED and MODULE
library targets.

Entries in the COMPILE_OPTIONS are escaped for the shell and added
in the order of appearance in the property value.  Several compile options have
special separate handling, such as POSITION_INDEPENDENT_CODE.

The contents of the INTERFACE_INCLUDE_DIRECTORIES,
INTERFACE_COMPILE_DEFINITIONS and
INTERFACE_COMPILE_OPTIONS target properties are
Usage Requirements -- they specify content which consumers
must use to correctly compile and link with the target they appear on.
For any binary target, the contents of each INTERFACE_ property on
each target specified in a target_link_libraries() command is
consumed:

set(srcs archive.cpp zip.cpp)
if (LZMA_FOUND)
  list(APPEND srcs lzma.cpp)
endif()
add_library(archive SHARED ${srcs})
if (LZMA_FOUND)
  # The archive library sources are compiled with -DBUILDING_WITH_LZMA
  target_compile_definitions(archive PRIVATE BUILDING_WITH_LZMA)
endif()
target_compile_definitions(archive INTERFACE USING_ARCHIVE_LIB)

add_executable(consumer)
# Link consumer to archive and consume its usage requirements. The consumer
# executable sources are compiled with -DUSING_ARCHIVE_LIB.
target_link_libraries(consumer archive)

Because it is common to require that the source directory and corresponding
build directory are added to the INCLUDE_DIRECTORIES, the
CMAKE_INCLUDE_CURRENT_DIR variable can be enabled to conveniently
add the corresponding directories to the INCLUDE_DIRECTORIES of
all targets.  The variable CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE
can be enabled to add the corresponding directories to the
INTERFACE_INCLUDE_DIRECTORIES of all targets.  This makes use of
targets in multiple different directories convenient through use of the
target_link_libraries() command.

Transitive Usage Requirements¶

The usage requirements of a target can transitively propagate to the dependents.
The target_link_libraries() command has PRIVATE,
INTERFACE and PUBLIC keywords to control the propagation.

add_library(archive archive.cpp)
target_compile_definitions(archive INTERFACE USING_ARCHIVE_LIB)

add_library(serialization serialization.cpp)
target_compile_definitions(serialization INTERFACE USING_SERIALIZATION_LIB)

add_library(archiveExtras extras.cpp)
target_link_libraries(archiveExtras PUBLIC archive)
target_link_libraries(archiveExtras PRIVATE serialization)
# archiveExtras is compiled with -DUSING_ARCHIVE_LIB
# and -DUSING_SERIALIZATION_LIB

add_executable(consumer consumer.cpp)
# consumer is compiled with -DUSING_ARCHIVE_LIB
target_link_libraries(consumer archiveExtras)

Because the archive is a PUBLIC dependency of archiveExtras, the
usage requirements of it are propagated to consumer too.

Because
serialization is a PRIVATE dependency of archiveExtras, the usage
requirements of it are not propagated to consumer.

Generally, a dependency should be specified in a use of
target_link_libraries() with the PRIVATE keyword if it is used by
only the implementation of a library, and not in the header files.  If a
dependency is additionally used in the header files of a library (e.g. for
class inheritance), then it should be specified as a PUBLIC dependency.
A dependency which is not used by the implementation of a library, but only by
its headers should be specified as an INTERFACE dependency.  The
target_link_libraries() command may be invoked with multiple uses of
each keyword:

target_link_libraries(archiveExtras
  PUBLIC archive
  PRIVATE serialization
)

Usage requirements are propagated by reading the INTERFACE_ variants
of target properties from dependencies and appending the values to the
non-INTERFACE_ variants of the operand.  For example, the
INTERFACE_INCLUDE_DIRECTORIES of dependencies is read and
appended to the INCLUDE_DIRECTORIES of the operand.  In cases
where order is relevant and maintained, and the order resulting from the
target_link_libraries() calls does not allow correct compilation,
use of an appropriate command to set the property directly may update the
order.

For example, if the linked libraries for a target must be specified
in the order lib1 lib2 lib3 , but the include directories must
be specified in the order lib3 lib1 lib2:

target_link_libraries(myExe lib1 lib2 lib3)
target_include_directories(myExe
  PRIVATE $<TARGET_PROPERTY:lib3,INTERFACE_INCLUDE_DIRECTORIES>)

Note that care must be taken when specifying usage requirements for targets
which will be exported for installation using the install(EXPORT)
command.  See Creating Packages for more.

Compatible Interface Properties¶

Some target properties are required to be compatible between a target and
the interface of each dependency.  For example, the
POSITION_INDEPENDENT_CODE target property may specify a
boolean value of whether a target should be compiled as
position-independent-code, which has platform-specific consequences.
A target may also specify the usage requirement
INTERFACE_POSITION_INDEPENDENT_CODE to communicate that
consumers must be compiled as position-independent-code.

add_executable(exe1 exe1.cpp)
set_property(TARGET exe1 PROPERTY POSITION_INDEPENDENT_CODE ON)

add_library(lib1 SHARED lib1.cpp)
set_property(TARGET lib1 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)

add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1)

Here, both exe1 and exe2 will be compiled as position-independent-code.
lib1 will also be compiled as position-independent-code because that is the
default setting for SHARED libraries.  If dependencies have conflicting,
non-compatible requirements cmake(1) issues a diagnostic:

add_library(lib1 SHARED lib1.cpp)
set_property(TARGET lib1 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)

add_library(lib2 SHARED lib2.cpp)
set_property(TARGET lib2 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE OFF)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1)
set_property(TARGET exe1 PROPERTY POSITION_INDEPENDENT_CODE OFF)

add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1 lib2)

The lib1 requirement INTERFACE_POSITION_INDEPENDENT_CODE is not
"compatible" with the POSITION_INDEPENDENT_CODE property of
the exe1 target.  The library requires that consumers are built as
position-independent-code, while the executable specifies to not built as
position-independent-code, so a diagnostic is issued.

The lib1 and lib2 requirements are not "compatible".  One of them
requires that consumers are built as position-independent-code, while
the other requires that consumers are not built as position-independent-code.
Because exe2 links to both and they are in conflict, a CMake error message
is issued:

CMake Error: The INTERFACE_POSITION_INDEPENDENT_CODE property of "lib2" does
not agree with the value of POSITION_INDEPENDENT_CODE already determined
for "exe2".

To be "compatible", the POSITION_INDEPENDENT_CODE property,
if set must be either the same, in a boolean sense, as the
INTERFACE_POSITION_INDEPENDENT_CODE property of all transitively
specified dependencies on which that property is set.

This property of "compatible interface requirement" may be extended to other
properties by specifying the property in the content of the
COMPATIBLE_INTERFACE_BOOL target property.  Each specified property
must be compatible between the consuming target and the corresponding property
with an INTERFACE_ prefix from each dependency:

add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY INTERFACE_CUSTOM_PROP ON)
set_property(TARGET lib1Version2 APPEND PROPERTY
  COMPATIBLE_INTERFACE_BOOL CUSTOM_PROP
)

add_library(lib1Version3 SHARED lib1_v3.cpp)
set_property(TARGET lib1Version3 PROPERTY INTERFACE_CUSTOM_PROP OFF)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1Version2) # CUSTOM_PROP will be ON

add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1Version2 lib1Version3) # Diagnostic

Non-boolean properties may also participate in "compatible interface"
computations.  Properties specified in the
COMPATIBLE_INTERFACE_STRING
property must be either unspecified or compare to the same string among
all transitively specified dependencies. This can be useful to ensure
that multiple incompatible versions of a library are not linked together
through transitive requirements of a target:

add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY INTERFACE_LIB_VERSION 2)
set_property(TARGET lib1Version2 APPEND PROPERTY
  COMPATIBLE_INTERFACE_STRING LIB_VERSION
)

add_library(lib1Version3 SHARED lib1_v3.cpp)
set_property(TARGET lib1Version3 PROPERTY INTERFACE_LIB_VERSION 3)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1Version2) # LIB_VERSION will be "2"

add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1Version2 lib1Version3) # Diagnostic

The COMPATIBLE_INTERFACE_NUMBER_MAX target property specifies
that content will be evaluated numerically and the maximum number among all
specified will be calculated:

add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY INTERFACE_CONTAINER_SIZE_REQUIRED 200)
set_property(TARGET lib1Version2 APPEND PROPERTY
  COMPATIBLE_INTERFACE_NUMBER_MAX CONTAINER_SIZE_REQUIRED
)

add_library(lib1Version3 SHARED lib1_v3.cpp)
set_property(TARGET lib1Version3 PROPERTY INTERFACE_CONTAINER_SIZE_REQUIRED 1000)

add_executable(exe1 exe1.cpp)
# CONTAINER_SIZE_REQUIRED will be "200"
target_link_libraries(exe1 lib1Version2)

add_executable(exe2 exe2.cpp)
# CONTAINER_SIZE_REQUIRED will be "1000"
target_link_libraries(exe2 lib1Version2 lib1Version3)

Similarly, the COMPATIBLE_INTERFACE_NUMBER_MIN may be used to
calculate the numeric minimum value for a property from dependencies.

Each calculated "compatible" property value may be read in the consumer at
generate-time using generator expressions.

Note that for each dependee, the set of properties specified in each
compatible interface property must not intersect with the set specified in
any of the other properties.

Property Origin Debugging¶

Because build specifications can be determined by dependencies, the lack of
locality of code which creates a target and code which is responsible for
setting build specifications may make the code more difficult to reason about.
cmake(1) provides a debugging facility to print the origin of the
contents of properties which may be determined by dependencies.  The properties
which can be debugged are listed in the
CMAKE_DEBUG_TARGET_PROPERTIES variable documentation:

set(CMAKE_DEBUG_TARGET_PROPERTIES
  INCLUDE_DIRECTORIES
  COMPILE_DEFINITIONS
  POSITION_INDEPENDENT_CODE
  CONTAINER_SIZE_REQUIRED
  LIB_VERSION
)
add_executable(exe1 exe1.cpp)

In the case of properties listed in COMPATIBLE_INTERFACE_BOOL or
COMPATIBLE_INTERFACE_STRING, the debug output shows which target
was responsible for setting the property, and which other dependencies also
defined the property.  In the case of
COMPATIBLE_INTERFACE_NUMBER_MAX and
COMPATIBLE_INTERFACE_NUMBER_MIN, the debug output shows the
value of the property from each dependency, and whether the value determines
the new extreme.

Build Specification with Generator Expressions¶

Build specifications may use
generator expressions containing
content which may be conditional or known only at generate-time.  For example,
the calculated "compatible" value of a property may be read with the
TARGET_PROPERTY expression:

add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY
  INTERFACE_CONTAINER_SIZE_REQUIRED 200)
set_property(TARGET lib1Version2 APPEND PROPERTY
  COMPATIBLE_INTERFACE_NUMBER_MAX CONTAINER_SIZE_REQUIRED
)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1Version2)
target_compile_definitions(exe1 PRIVATE
    CONTAINER_SIZE=$<TARGET_PROPERTY:CONTAINER_SIZE_REQUIRED>
)

In this case, the exe1 source files will be compiled with
-DCONTAINER_SIZE=200.

The unary TARGET_PROPERTY generator expression and the TARGET_POLICY
generator expression are evaluated with the consuming target context.  This
means that a usage requirement specification may be evaluated differently based
on the consumer:

add_library(lib1 lib1.cpp)
target_compile_definitions(lib1 INTERFACE
  $<$<STREQUAL:$<TARGET_PROPERTY:TYPE>,EXECUTABLE>:LIB1_WITH_EXE>
  $<$<STREQUAL:$<TARGET_PROPERTY:TYPE>,SHARED_LIBRARY>:LIB1_WITH_SHARED_LIB>
  $<$<TARGET_POLICY:CMP0041>:CONSUMER_CMP0041_NEW>
)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1)

cmake_policy(SET CMP0041 NEW)

add_library(shared_lib shared_lib.cpp)
target_link_libraries(shared_lib lib1)

The exe1 executable will be compiled with -DLIB1_WITH_EXE, while the
shared_lib shared library will be compiled with -DLIB1_WITH_SHARED_LIB
and -DCONSUMER_CMP0041_NEW, because policy CMP0041 is
NEW at the point where the shared_lib target is created.

The BUILD_INTERFACE expression wraps requirements which are only used when
consumed from a target in the same buildsystem, or when consumed from a target
exported to the build directory using the export() command.  The
INSTALL_INTERFACE expression wraps requirements which are only used when
consumed from a target which has been installed and exported with the
install(EXPORT) command:

add_library(ClimbingStats climbingstats.cpp)
target_compile_definitions(ClimbingStats INTERFACE
  $<BUILD_INTERFACE:ClimbingStats_FROM_BUILD_LOCATION>
  $<INSTALL_INTERFACE:ClimbingStats_FROM_INSTALLED_LOCATION>
)
install(TARGETS ClimbingStats EXPORT libExport ${InstallArgs})
install(EXPORT libExport NAMESPACE Upstream::
        DESTINATION lib/cmake/ClimbingStats)
export(EXPORT libExport NAMESPACE Upstream::)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 ClimbingStats)

In this case, the exe1 executable will be compiled with
-DClimbingStats_FROM_BUILD_LOCATION.  The exporting commands generate
IMPORTED targets with either the INSTALL_INTERFACE or the
BUILD_INTERFACE omitted, and the *_INTERFACE marker stripped away.
A separate project consuming the ClimbingStats package would contain:

find_package(ClimbingStats REQUIRED)

add_executable(Downstream main.cpp)
target_link_libraries(Downstream Upstream::ClimbingStats)

Depending on whether the ClimbingStats package was used from the build
location or the install location, the Downstream target would be compiled
with either -DClimbingStats_FROM_BUILD_LOCATION or
-DClimbingStats_FROM_INSTALL_LOCATION.  For more about packages and
exporting see the cmake-packages(7) manual.

Include Directories and Usage Requirements¶

Include directories require some special consideration when specified as usage
requirements and when used with generator expressions.  The
target_include_directories() command accepts both relative and
absolute include directories:

add_library(lib1 lib1.cpp)
target_include_directories(lib1 PRIVATE
  /absolute/path
  relative/path
)

Relative paths are interpreted relative to the source directory where the
command appears.  Relative paths are not allowed in the
INTERFACE_INCLUDE_DIRECTORIES of IMPORTED targets.

In cases where a non-trivial generator expression is used, the
INSTALL_PREFIX expression may be used within the argument of an
INSTALL_INTERFACE expression.  It is a replacement marker which
expands to the installation prefix when imported by a consuming project.

Include directories usage requirements commonly differ between the build-tree
and the install-tree.  The BUILD_INTERFACE and INSTALL_INTERFACE
generator expressions can be used to describe separate usage requirements
based on the usage location.  Relative paths are allowed within the
INSTALL_INTERFACE expression and are interpreted relative to the
installation prefix.  For example:

add_library(ClimbingStats climbingstats.cpp)
target_include_directories(ClimbingStats INTERFACE
  $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/generated>
  $<INSTALL_INTERFACE:/absolute/path>
  $<INSTALL_INTERFACE:relative/path>
  $<INSTALL_INTERFACE:$<INSTALL_PREFIX>/$<CONFIG>/generated>
)

Two convenience APIs are provided relating to include directories usage
requirements.  The CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE variable
may be enabled, with an equivalent effect to:

set_property(TARGET tgt APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR};${CMAKE_CURRENT_BINARY_DIR}>
)

for each target affected.  The convenience for installed targets is
an INCLUDES DESTINATION component with the install(TARGETS)
command:

install(TARGETS foo bar bat EXPORT tgts ${dest_args}
  INCLUDES DESTINATION include
)
install(EXPORT tgts ${other_args})
install(FILES ${headers} DESTINATION include)

This is equivalent to appending ${CMAKE_INSTALL_PREFIX}/include to the
INTERFACE_INCLUDE_DIRECTORIES of each of the installed
IMPORTED targets when generated by install(EXPORT).

When the INTERFACE_INCLUDE_DIRECTORIES of an
imported target is consumed, the entries in the
property may be treated as system include directories.  The effects of that
are toolchain-dependent, but one common effect is to omit compiler warnings
for headers found in those directories.  The SYSTEM property of
the installed target determines this behavior (see the
EXPORT_NO_SYSTEM property for how to modify the installed value
for a target).  It is also possible to change how consumers interpret the
system behavior of consumed imported targets by setting the
NO_SYSTEM_FROM_IMPORTED target property on the consumer.

If a binary target is linked transitively to a macOS FRAMEWORK, the
Headers directory of the framework is also treated as a usage requirement.
This has the same effect as passing the framework directory as an include
directory.

Link Libraries and Generator Expressions¶

Like build specifications, link libraries may be
specified with generator expression conditions.  However, as consumption of
usage requirements is based on collection from linked dependencies, there is
an additional limitation that the link dependencies must form a "directed
acyclic graph".  That is, if linking to a target is dependent on the value of
a target property, that target property may not be dependent on the linked
dependencies:

add_library(lib1 lib1.cpp)
add_library(lib2 lib2.cpp)
target_link_libraries(lib1 PUBLIC
  $<$<TARGET_PROPERTY:POSITION_INDEPENDENT_CODE>:lib2>
)
add_library(lib3 lib3.cpp)
set_property(TARGET lib3 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1 lib3)

As the value of the POSITION_INDEPENDENT_CODE property of
the exe1 target is dependent on the linked libraries (lib3), and the
edge of linking exe1 is determined by the same
POSITION_INDEPENDENT_CODE property, the dependency graph above
contains a cycle.  cmake(1) issues an error message.

Output Artifacts¶

The buildsystem targets created by the add_library() and
add_executable() commands create rules to create binary outputs.
The exact output location of the binaries can only be determined at
generate-time because it can depend on the build-configuration and the
link-language of linked dependencies etc.  TARGET_FILE,
TARGET_LINKER_FILE and related expressions can be used to access the
name and location of generated binaries.  These expressions do not work
for OBJECT libraries however, as there is no single file generated
by such libraries which is relevant to the expressions.

There are three kinds of output artifacts that may be build by targets
as detailed in the following sections.  Their classification differs
between DLL platforms and non-DLL platforms.  All Windows-based
systems including Cygwin are DLL platforms.

Runtime Output Artifacts¶

A runtime output artifact of a buildsystem target may be:

The executable file (e.g. .exe) of an executable target
created by the add_executable() command.

On DLL platforms: the executable file (e.g. .dll) of a shared
library target created by the add_library() command
with the SHARED option.

The RUNTIME_OUTPUT_DIRECTORY and RUNTIME_OUTPUT_NAME
target properties may be used to control runtime output artifact locations
and names in the build tree.

Library Output Artifacts¶

A library output artifact of a buildsystem target may be:

The loadable module file (e.g. .dll or .so) of a module
library target created by the add_library() command
with the MODULE option.

On non-DLL platforms: the shared library file (e.g. .so or .dylib)
of a shared library target created by the add_library()
command with the SHARED option.

The LIBRARY_OUTPUT_DIRECTORY and LIBRARY_OUTPUT_NAME
target properties may be used to control library output artifact locations
and names in the build tree.

Archive Output Artifacts¶

An archive output artifact of a buildsystem target may be:

The static library file (e.g. .lib or .a) of a static
library target created by the add_library() command
with the STATIC option.

On DLL platforms: the import library file (e.g. .lib) of a shared
library target created by the add_library() command
with the SHARED option.  This file is only guaranteed to exist if
the library exports at least one unmanaged symbol.

On DLL platforms: the import library file (e.g. .lib) of an
executable target created by the add_executable() command
when its ENABLE_EXPORTS target property is set.

On AIX: the linker import file (e.g. .imp) of an executable target
created by the add_executable() command when its
ENABLE_EXPORTS target property is set.

On macOS: the linker import file (e.g. .tbd) of a shared library target
created by the add_library() command with the SHARED option and
when its ENABLE_EXPORTS target property is set.

The ARCHIVE_OUTPUT_DIRECTORY and ARCHIVE_OUTPUT_NAME
target properties may be used to control archive output artifact locations
and names in the build tree.

Directory-Scoped Commands¶

The target_include_directories(),
target_compile_definitions() and
target_compile_options() commands have an effect on only one
target at a time.  The commands add_compile_definitions(),
add_compile_options() and include_directories() have
a similar function, but operate at directory scope instead of target
scope for convenience.

Build Configurations¶

Configurations determine specifications for a certain type of build, such
as Release or Debug.  The way this is specified depends on the type
of generator being used.  For single
configuration generators like  Makefile Generators and
Ninja, the configuration is specified at configure time by the
CMAKE_BUILD_TYPE variable. For multi-configuration generators
like Visual Studio, Xcode, and
Ninja Multi-Config, the configuration is chosen by the user at
build time and CMAKE_BUILD_TYPE is ignored.  In the
multi-configuration case, the set of available configurations is specified
at configure time by the CMAKE_CONFIGURATION_TYPES variable,
but the actual configuration used cannot be known until the build stage.
This difference is often misunderstood, leading to problematic code like the
following:

# WARNING: This is wrong for multi-config generators because they don't use
#          and typically don't even set CMAKE_BUILD_TYPE
string(TOLOWER ${CMAKE_BUILD_TYPE} build_type)
if (build_type STREQUAL debug)
  target_compile_definitions(exe1 PRIVATE DEBUG_BUILD)
endif()

Generator expressions should be
used instead to handle configuration-specific logic correctly, regardless of
the generator used.  For example:

# Works correctly for both single and multi-config generators
target_compile_definitions(exe1 PRIVATE
  $<$<CONFIG:Debug>:DEBUG_BUILD>
)

In the presence of IMPORTED targets, the content of
MAP_IMPORTED_CONFIG_DEBUG is also
accounted for by the above $<CONFIG:Debug> expression.

Case Sensitivity¶

CMAKE_BUILD_TYPE and CMAKE_CONFIGURATION_TYPES are
just like other variables in that any string comparisons made with their
values will be case-sensitive.  The $<CONFIG> generator expression also
preserves the casing of the configuration as set by the user or CMake defaults.
For example:

# NOTE: Don't use these patterns, they are for illustration purposes only.

set(CMAKE_BUILD_TYPE Debug)
if(CMAKE_BUILD_TYPE STREQUAL DEBUG)
  # ... will never get here, "Debug" != "DEBUG"
endif()
add_custom_target(print_config ALL
  # Prints "Config is Debug" in this single-config case
  COMMAND ${CMAKE_COMMAND} -E echo "Config is $<CONFIG>"
  VERBATIM
)

set(CMAKE_CONFIGURATION_TYPES Debug Release)
if(DEBUG IN_LIST CMAKE_CONFIGURATION_TYPES)
  # ... will never get here, "Debug" != "DEBUG"
endif()

In contrast, CMake treats the configuration type case-insensitively when
using it internally in places that modify behavior based on the configuration.
For example, the $<CONFIG:Debug> generator expression will evaluate to 1
for a configuration of not only Debug, but also DEBUG, debug or
even DeBuG.  Therefore, you can specify configuration types in
CMAKE_BUILD_TYPE and CMAKE_CONFIGURATION_TYPES with
any mixture of upper and lowercase, although there are strong conventions
(see the next section).  If you must test the value in string comparisons,
always convert the value to upper or lowercase first and adjust the test
accordingly.

Default And Custom Configurations¶

By default, CMake defines a number of standard configurations:

Debug

Release

RelWithDebInfo

MinSizeRel

In multi-config generators, the CMAKE_CONFIGURATION_TYPES variable
will be populated with (potentially a subset of) the above list by default,
unless overridden by the project or user.  The actual configuration used is
selected by the user at build time.

For single-config generators, the configuration is specified with the
CMAKE_BUILD_TYPE variable at configure time and cannot be changed
at build time.  The default value will often be none of the above standard
configurations and will instead be an empty string.  A common misunderstanding
is that this is the same as Debug, but that is not the case.  Users should
always explicitly specify the build type instead to avoid this common problem.

The above standard configuration types provide reasonable behavior on most
platforms, but they can be extended to provide other types.  Each configuration
defines a set of compiler and linker flag variables for the language in use.
These variables follow the convention CMAKE_<LANG>_FLAGS_<CONFIG>,
where <CONFIG> is always the uppercase configuration name.  When defining
a custom configuration type, make sure these variables are set appropriately,
typically as cache variables.

Pseudo Targets¶

Some target types do not represent outputs of the buildsystem, but only inputs
such as external dependencies, aliases or other non-build artifacts.  Pseudo
targets are not represented in the generated buildsystem.

Imported Targets¶

An IMPORTED target represents a pre-existing dependency.  Usually
such targets are defined by an upstream package and should be treated as
immutable. After declaring an IMPORTED target one can adjust its
target properties by using the customary commands such as
target_compile_definitions(), target_include_directories(),
target_compile_options() or target_link_libraries() just like
with any other regular target.

IMPORTED targets may have the same usage requirement properties
populated as binary targets, such as
INTERFACE_INCLUDE_DIRECTORIES,
INTERFACE_COMPILE_DEFINITIONS,
INTERFACE_COMPILE_OPTIONS,
INTERFACE_LINK_LIBRARIES, and
INTERFACE_POSITION_INDEPENDENT_CODE.

The LOCATION may also be read from an IMPORTED target, though there
is rarely reason to do so.  Commands such as add_custom_command() can
transparently use an IMPORTED EXECUTABLE target
as a COMMAND executable.

The scope of the definition of an IMPORTED target is the directory
where it was defined.  It may be accessed and used from subdirectories, but
not from parent directories or sibling directories.  The scope is similar to
the scope of a cmake variable.

It is also possible to define a GLOBAL IMPORTED target which is
accessible globally in the buildsystem.

See the cmake-packages(7) manual for more on creating packages
with IMPORTED targets.

Alias Targets¶

An ALIAS target is a name which may be used interchangeably with
a binary target name in read-only contexts.  A primary use-case for ALIAS
targets is for example or unit test executables accompanying a library, which
may be part of the same buildsystem or built separately based on user
configuration.

add_library(lib1 lib1.cpp)
install(TARGETS lib1 EXPORT lib1Export ${dest_args})
install(EXPORT lib1Export NAMESPACE Upstream:: ${other_args})

add_library(Upstream::lib1 ALIAS lib1)

In another directory, we can link unconditionally to the Upstream::lib1
target, which may be an IMPORTED target from a package, or an
ALIAS target if built as part of the same buildsystem.

if (NOT TARGET Upstream::lib1)
  find_package(lib1 REQUIRED)
endif()
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 Upstream::lib1)

ALIAS targets are not mutable, installable or exportable.  They are
entirely local to the buildsystem description.  A name can be tested for
whether it is an ALIAS name by reading the ALIASED_TARGET
property from it:

get_target_property(_aliased Upstream::lib1 ALIASED_TARGET)
if(_aliased)
  message(STATUS "The name Upstream::lib1 is an ALIAS for ${_aliased}.")
endif()

Interface Libraries¶

An INTERFACE library target does not compile sources and does not
produce a library artifact on disk, so it has no LOCATION.

It may specify usage requirements such as
INTERFACE_INCLUDE_DIRECTORIES,
INTERFACE_COMPILE_DEFINITIONS,
INTERFACE_COMPILE_OPTIONS,
INTERFACE_LINK_LIBRARIES,
INTERFACE_SOURCES,
and INTERFACE_POSITION_INDEPENDENT_CODE.
Only the INTERFACE modes of the target_include_directories(),
target_compile_definitions(), target_compile_options(),
target_sources(), and target_link_libraries() commands
may be used with INTERFACE libraries.

Since CMake 3.19, an INTERFACE library target may optionally contain
source files.  An interface library that contains source files will be
included as a build target in the generated buildsystem.  It does not
compile sources, but may contain custom commands to generate other sources.
Additionally, IDEs will show the source files as part of the target for
interactive reading and editing.

A primary use-case for INTERFACE libraries is header-only libraries.
Since CMake 3.23, header files may be associated with a library by adding
them to a header set using the target_sources() command:

add_library(Eigen INTERFACE)

target_sources(Eigen PUBLIC
  FILE_SET HEADERS
    BASE_DIRS src
    FILES src/eigen.h src/vector.h src/matrix.h
)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 Eigen)

When we specify the FILE_SET here, the BASE_DIRS we define automatically
become include directories in the usage requirements for the target Eigen.
The usage requirements from the target are consumed and used when compiling, but
have no effect on linking.

Another use-case is to employ an entirely target-focussed design for usage
requirements:

add_library(pic_on INTERFACE)
set_property(TARGET pic_on PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)
add_library(pic_off INTERFACE)
set_property(TARGET pic_off PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE OFF)

add_library(enable_rtti INTERFACE)
target_compile_options(enable_rtti INTERFACE
  $<$<OR:$<COMPILER_ID:GNU>,$<COMPILER_ID:Clang>>:-rtti>
)

add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 pic_on enable_rtti)

This way, the build specification of exe1 is expressed entirely as linked
targets, and the complexity of compiler-specific flags is encapsulated in an
INTERFACE library target.

INTERFACE libraries may be installed and exported. We can install the
default header set along with the target:

add_library(Eigen INTERFACE)

target_sources(Eigen INTERFACE
  FILE_SET HEADERS
    BASE_DIRS src
    FILES src/eigen.h src/vector.h src/matrix.h
)

install(TARGETS Eigen EXPORT eigenExport
  FILE_SET HEADERS DESTINATION include/Eigen)
install(EXPORT eigenExport NAMESPACE Upstream::
  DESTINATION lib/cmake/Eigen
)

Here, the headers defined in the header set are installed to include/Eigen.
The install destination automatically becomes an include directory that is a
usage requirement for consumers.

Table of Contents

cmake-buildsystem(7)

Introduction

Binary Targets

Binary Executables

Binary Library Types

Normal Libraries

Apple Frameworks

Object Libraries

Build Specification and Usage Requirements

Target Properties

Transitive Usage Requirements

Compatible Interface Properties

Property Origin Debugging

Build Specification with Generator Expressions

Include Directories and Usage Requirements

Link Libraries and Generator Expressions

Output Artifacts

Runtime Output Artifacts

Library Output Artifacts

Archive Output Artifacts

Directory-Scoped Commands

Build Configurations

Case Sensitivity

Default And Custom Configurations

Pseudo Targets

Imported Targets

Alias Targets

Interface Libraries

Previous topic

ccmake(1)

Next topic

cmake-commands(7)

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-buildsystem(7)

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>cmake-commands(7) — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cmake.css" />

    <link rel="icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="block" href="../command/block.html" />
    <link rel="prev" title="cmake-buildsystem(7)" href="cmake-buildsystem.7.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-commands(7)

cmake-commands(7)¶

Contents

cmake-commands(7)

Scripting Commands

Project Commands

CTest Commands

Deprecated Commands

Scripting Commands¶

These commands are always available.

block

break

cmake_host_system_information

cmake_language

cmake_minimum_required

cmake_parse_arguments

cmake_path

cmake_policy

configure_file

continue

else

elseif

endblock

endforeach

endfunction

endif

endmacro

endwhile

execute_process

file

find_file

find_library

find_package

find_path

find_program

foreach

function

get_cmake_property

get_directory_property

get_filename_component

get_property

if

include

include_guard

list

macro

mark_as_advanced

math

message

option

return

separate_arguments

set

set_directory_properties

set_property

site_name

string

unset

variable_watch

while

Project Commands¶

These commands are available only in CMake projects.

add_compile_definitions

add_compile_options

add_custom_command

add_custom_target

add_definitions

add_dependencies

add_executable

add_library

add_link_options

add_subdirectory

add_test

aux_source_directory

build_command

cmake_file_api

create_test_sourcelist

define_property

enable_language

enable_testing

export

fltk_wrap_ui

get_source_file_property

get_target_property

get_test_property

include_directories

include_external_msproject

include_regular_expression

install

link_directories

link_libraries

load_cache

project

remove_definitions

set_source_files_properties

set_target_properties

set_tests_properties

source_group

target_compile_definitions

target_compile_features

target_compile_options

target_include_directories

target_link_directories

target_link_libraries

target_link_options

target_precompile_headers

target_sources

try_compile

try_run

CTest Commands¶

These commands are available only in CTest scripts.

ctest_build

ctest_configure

ctest_coverage

ctest_empty_binary_directory

ctest_memcheck

ctest_read_custom_files

ctest_run_script

ctest_sleep

ctest_start

ctest_submit

ctest_test

ctest_update

ctest_upload

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

exec_program

export_library_dependencies

install_files

install_programs

install_targets

load_command

make_directory

output_required_files

qt_wrap_cpp

qt_wrap_ui

remove

subdir_depends

subdirs

use_mangled_mesa

utility_source

variable_requires

write_file

Table of Contents

cmake-commands(7)

Scripting Commands

Project Commands

CTest Commands

Deprecated Commands

Previous topic

cmake-buildsystem(7)

Next topic

block

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-commands(7)

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.

repo_name: lazytadpole/codenamesilverfish

license: mit


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>cmake-compile-features(7) — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cmake.css" />

    <link rel="icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="cmake-configure-log(7)" href="cmake-configure-log.7.html" />
    <link rel="prev" title="write_file" href="../command/write_file.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-compile-features(7)

cmake-compile-features(7)¶

Contents

cmake-compile-features(7)

Introduction

Compile Feature Requirements

Requiring Language Standards

Availability of Compiler Extensions

Optional Compile Features

Conditional Compilation Options

Supported Compilers

Language Standard Flags

Introduction¶

Project source code may depend on, or be conditional on, the availability
of certain features of the compiler.  There are three use-cases which arise:
Compile Feature Requirements, Optional Compile Features
and Conditional Compilation Options.

While features are typically specified in programming language standards,
CMake provides a primary user interface based on granular handling of
the features, not the language standard that introduced the feature.

The CMAKE_C_KNOWN_FEATURES, CMAKE_CUDA_KNOWN_FEATURES,
and CMAKE_CXX_KNOWN_FEATURES global properties contain all the
features known to CMake, regardless of compiler support for the feature.
The CMAKE_C_COMPILE_FEATURES, CMAKE_CUDA_COMPILE_FEATURES
, and CMAKE_CXX_COMPILE_FEATURES variables contain all features
CMake knows are known to the compiler, regardless of language standard
or compile flags needed to use them.

Features known to CMake are named mostly following the same convention
as the Clang feature test macros.  There are some exceptions, such as
CMake using cxx_final and cxx_override instead of the single
cxx_override_control used by Clang.

Note that there are no separate compile features properties or variables for
the OBJC or OBJCXX languages.  These are based off C or C++
respectively, so the properties and variables for their corresponding base
language should be used instead.

Compile Feature Requirements¶

Compile feature requirements may be specified with the
target_compile_features() command.  For example, if a target must
be compiled with compiler support for the
cxx_constexpr feature:

add_library(mylib requires_constexpr.cpp)
target_compile_features(mylib PRIVATE cxx_constexpr)

In processing the requirement for the cxx_constexpr feature,
cmake(1) will ensure that the in-use C++ compiler is capable
of the feature, and will add any necessary flags such as -std=gnu++11
to the compile lines of C++ files in the mylib target.  A
FATAL_ERROR is issued if the compiler is not capable of the
feature.

The exact compile flags and language standard are deliberately not part
of the user interface for this use-case.  CMake will compute the
appropriate compile flags to use by considering the features specified
for each target.

Such compile flags are added even if the compiler supports the
particular feature without the flag. For example, the GNU compiler
supports variadic templates (with a warning) even if -std=gnu++98 is
used.  CMake adds the -std=gnu++11 flag if cxx_variadic_templates
is specified as a requirement.

In the above example, mylib requires cxx_constexpr when it
is built itself, but consumers of mylib are not required to use a
compiler which supports cxx_constexpr.  If the interface of
mylib does require the cxx_constexpr feature (or any other
known feature), that may be specified with the PUBLIC or
INTERFACE signatures of target_compile_features():

add_library(mylib requires_constexpr.cpp)
# cxx_constexpr is a usage-requirement
target_compile_features(mylib PUBLIC cxx_constexpr)

# main.cpp will be compiled with -std=gnu++11 on GNU for cxx_constexpr.
add_executable(myexe main.cpp)
target_link_libraries(myexe mylib)

Feature requirements are evaluated transitively by consuming the link
implementation.  See cmake-buildsystem(7) for more on
transitive behavior of build properties and usage requirements.

Requiring Language Standards¶

In projects that use a large number of commonly available features from
a particular language standard (e.g. C++ 11) one may specify a
meta-feature (e.g. cxx_std_11) that requires use of a compiler mode
that is at minimum aware of that standard, but could be greater.
This is simpler than specifying all the features individually, but does
not guarantee the existence of any particular feature.
Diagnosis of use of unsupported features will be delayed until compile time.

For example, if C++ 11 features are used extensively in a project's
header files, then clients must use a compiler mode that is no less
than C++ 11.  This can be requested with the code:

target_compile_features(mylib PUBLIC cxx_std_11)

In this example, CMake will ensure the compiler is invoked in a mode
of at-least C++ 11 (or C++ 14, C++ 17, ...), adding flags such as
-std=gnu++11 if necessary.  This applies to sources within mylib
as well as any dependents (that may include headers from mylib).

Note

If the compiler's default standard level is at least that
of the requested feature, CMake may omit the -std= flag.
The flag may still be added if the compiler's default extensions mode
does not match the <LANG>_EXTENSIONS target property,
or if the <LANG>_STANDARD target property is set.

Availability of Compiler Extensions¶

The <LANG>_EXTENSIONS target property defaults to the compiler's
default (see CMAKE_<LANG>_EXTENSIONS_DEFAULT). Note that because
most compilers enable extensions by default, this may expose portability bugs
in user code or in the headers of third-party dependencies.

<LANG>_EXTENSIONS used to default to ON. See CMP0128.

Optional Compile Features¶

Compile features may be preferred if available, without creating a hard
requirement.   This can be achieved by not specifying features with
target_compile_features() and instead checking the compiler
capabilities with preprocessor conditions in project code.

In this use-case, the project may wish to establish a particular language
standard if available from the compiler, and use preprocessor conditions
to detect the features actually available.  A language standard may be
established by Requiring Language Standards using
target_compile_features() with meta-features like cxx_std_11,
or by setting the CXX_STANDARD target property or
CMAKE_CXX_STANDARD variable.

See also policy CMP0120 and legacy documentation on
Example Usage of the deprecated
WriteCompilerDetectionHeader module.

Conditional Compilation Options¶

Libraries may provide entirely different header files depending on
requested compiler features.

For example, a header at with_variadics/interface.h may contain:

template<int I, int... Is>
struct Interface;

template<int I>
struct Interface<I>
{
  static int accumulate()
  {
    return I;
  }
};

template<int I, int... Is>
struct Interface
{
  static int accumulate()
  {
    return I + Interface<Is...>::accumulate();
  }
};

while a header at no_variadics/interface.h may contain:

template<int I1, int I2 = 0, int I3 = 0, int I4 = 0>
struct Interface
{
  static int accumulate() { return I1 + I2 + I3 + I4; }
};

It may be possible to write an abstraction interface.h header
containing something like:

#ifdef HAVE_CXX_VARIADIC_TEMPLATES
#include "with_variadics/interface.h"
#else
#include "no_variadics/interface.h"
#endif

However this could be unmaintainable if there are many files to
abstract. What is needed is to use alternative include directories
depending on the compiler capabilities.

CMake provides a COMPILE_FEATURES
generator expression to implement
such conditions.  This may be used with the build-property commands such as
target_include_directories() and target_link_libraries()
to set the appropriate buildsystem
properties:

add_library(foo INTERFACE)
set(with_variadics ${CMAKE_CURRENT_SOURCE_DIR}/with_variadics)
set(no_variadics ${CMAKE_CURRENT_SOURCE_DIR}/no_variadics)
target_include_directories(foo
  INTERFACE
    "$<$<COMPILE_FEATURES:cxx_variadic_templates>:${with_variadics}>"
    "$<$<NOT:$<COMPILE_FEATURES:cxx_variadic_templates>>:${no_variadics}>"
  )

Consuming code then simply links to the foo target as usual and uses
the feature-appropriate include directory

add_executable(consumer_with consumer_with.cpp)
target_link_libraries(consumer_with foo)
set_property(TARGET consumer_with CXX_STANDARD 11)

add_executable(consumer_no consumer_no.cpp)
target_link_libraries(consumer_no foo)

Supported Compilers¶

CMake is currently aware of the C++ standards
and compile features available from
the following compiler ids as of the
versions specified for each:

AppleClang: Apple Clang for Xcode versions 4.4+.

Clang: Clang compiler versions 2.9+.

GNU: GNU compiler versions 4.4+.

MSVC: Microsoft Visual Studio versions 2010+.

SunPro: Oracle SolarisStudio versions 12.4+.

Intel: Intel compiler versions 12.1+.

CMake is currently aware of the C standards
and compile features available from
the following compiler ids as of the
versions specified for each:

all compilers and versions listed above for C++.

GNU: GNU compiler versions 3.4+

CMake is currently aware of the C++ standards and
their associated meta-features (e.g. cxx_std_11) available from the
following compiler ids as of the
versions specified for each:

Cray: Cray Compiler Environment version 8.1+.

Fujitsu: Fujitsu HPC compiler 4.0+.

PGI: PGI version 12.10+.

NVHPC: NVIDIA HPC compilers version 11.0+.

TI: Texas Instruments compiler.

TIClang: Texas Instruments Clang-based compilers.

XL: IBM XL version 10.1+.

CMake is currently aware of the C standards and
their associated meta-features (e.g. c_std_99) available from the
following compiler ids as of the
versions specified for each:

all compilers and versions listed above with only meta-features for C++.

CMake is currently aware of the CUDA standards and
their associated meta-features (e.g. cuda_std_11) available from the
following compiler ids as of the
versions specified for each:

Clang: Clang compiler 5.0+.

NVIDIA: NVIDIA nvcc compiler 7.5+.

Language Standard Flags¶

In order to satisfy requirements specified by the
target_compile_features() command or the
CMAKE_<LANG>_STANDARD variable, CMake may pass a
language standard flag to the compiler, such as -std=c++11.

For Visual Studio Generators, CMake cannot precisely control
the placement of the language standard flag on the compiler command line.
For Ninja Generators, Makefile Generators, and
Xcode, CMake places the language standard flag just after
the language-wide flags from CMAKE_<LANG>_FLAGS
and CMAKE_<LANG>_FLAGS_<CONFIG>.

Changed in version 3.26: The language standard flag is placed before flags specified by other
abstractions such as the target_compile_options() command.
Prior to CMake 3.26, the language standard flag was placed after them.

Table of Contents

cmake-compile-features(7)

Introduction

Compile Feature Requirements

Requiring Language Standards

Availability of Compiler Extensions

Optional Compile Features

Conditional Compilation Options

Supported Compilers

Language Standard Flags

Previous topic

write_file

Next topic

cmake-configure-log(7)

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-compile-features(7)

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>cmake-configure-log(7) — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cmake.css" />

    <link rel="icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="cmake-cxxmodules(7)" href="cmake-cxxmodules.7.html" />
    <link rel="prev" title="cmake-compile-features(7)" href="cmake-compile-features.7.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-configure-log(7)

cmake-configure-log(7)¶

New in version 3.26.

Contents

cmake-configure-log(7)

Introduction

Log Structure

Log Versioning

Text Block Encoding

Event Kinds

Event Kind message

message-v1 Event

Event Kind try_compile

try_compile-v1 Event

Event Kind try_run

try_run-v1 Event

Introduction¶

CMake writes a running log, known as the configure log,
of certain events that occur during the Configure step.
The configure log does not contain a log of all output, errors,
or messages printed while configuring a project.  It is a log of
detailed information about specific events, such as toolchain inspection
by try_compile(), meant for use in debugging the configuration
of a build tree.

For human use, this version of CMake writes the configure log to the file:

${CMAKE_BINARY_DIR}/CMakeFiles/CMakeConfigureLog.yaml

However, the location and name of the log file may change in future
versions of CMake.  Tools that read the configure log should get its
location using a configureLog query to
the cmake-file-api(7).
See the Log Versioning section below for details.

Log Structure¶

The configure log is designed to be both machine- and human-readable.

The log file is a YAML document stream containing zero or more YAML
documents separated by document markers.  Each document begins
with a --- document marker line, contains a single YAML mapping
that logs events from one CMake "configure" step, and, if the configure
step finished normally, ends with a ... document marker line:

---
events:
  -
    kind: "try_compile-v1"
    # (other fields omitted)
  -
    kind: "try_compile-v1"
    # (other fields omitted)
...

A new document is appended to the log every time CMake configures
the build tree and logs new events.

The keys of the each document root mapping are:

events

A YAML block sequence of nodes corresponding to events logged during
one CMake "configure" step.  Each event is a YAML node containing one
of the Event Kinds documented below.

Log Versioning¶

Each of the Event Kinds is versioned independently.  The set of
keys an event's log entry provides is specific to its major version.
When an event is logged, the latest version of its event kind that is
known to the running version of CMake is always written to the log.

Tools reading the configure log must ignore event kinds and versions
they do not understand:

A future version of CMake may introduce a new event kind or version.

If an existing build tree is re-configured with a different version of
CMake, the log may contain different versions of the same event kind.

If cmake-file-api(7) queries request one or more
configureLog object versions,
the log may contain multiple entries for the same event, each
with a different version of its event kind.

IDEs should write a cmake-file-api(7) query requesting a
specific configureLog object version,
before running CMake, and then read the configure log only as described
by the file-api reply.

Text Block Encoding¶

In order to make the log human-readable, text blocks are always
represented using YAML literal block scalars (|).
Since literal block scalars do not support escaping, backslashes
and non-printable characters are encoded at the application layer:

\\ encodes a backslash.

\xXX encodes a byte using two hexadecimal digits, XX.

Event Kinds¶

Every event kind is represented by a YAML mapping of the form:

kind: "<kind>-v<major>"
backtrace:
  - "<file>:<line> (<function>)"
checks:
  - "Checking for something"
#...event-specific keys...

The keys common to all events are:

kind

A string identifying the event kind and major version.

backtrace

A YAML block sequence reporting the call stack of CMake source
locations at which the event occurred, from most-recent to
least-recent.  Each node is a string specifying one location
formatted as <file>:<line> (<function>).

checks

An optional key that is present when the event occurred with
at least one pending message(CHECK_START).  Its value
is a YAML block sequence reporting the stack of pending checks,
from most-recent to least-recent.  Each node is a string containing
a pending check message.

Additional mapping keys are specific to each (versioned) event kind,
described below.

Event Kind message¶

The message(CONFIGURE_LOG) command logs message events.

There is only one message event major version, version 1.

message-v1 Event¶

A message-v1 event is a YAML mapping:

kind: "message-v1"
backtrace:
  - "CMakeLists.txt:123 (message)"
checks:
  - "Checking for something"
message: |
  # ...

The keys specific to message-v1 mappings are:

message

A YAML literal block scalar containing the message text,
represented using our Text Block Encoding.

Event Kind try_compile¶

The try_compile() command logs try_compile events.

There is only one try_compile event major version, version 1.

try_compile-v1 Event¶

A try_compile-v1 event is a YAML mapping:

kind: "try_compile-v1"
backtrace:
  - "CMakeLists.txt:123 (try_compile)"
checks:
  - "Checking for something"
description: "Explicit LOG_DESCRIPTION"
directories:
  source: "/path/to/.../TryCompile-01234"
  binary: "/path/to/.../TryCompile-01234"
cmakeVariables:
  SOME_VARIABLE: "Some Value"
buildResult:
  variable: "COMPILE_RESULT"
  cached: true
  stdout: |
    # ...
  exitCode: 0

The keys specific to try_compile-v1 mappings are:

description

An optional key that is present when the LOG_DESCRIPTION <text> option
was used.  Its value is a string containing the description <text>.

directories

A mapping describing the directories associated with the
compilation attempt.  It has the following keys:

source

String specifying the source directory of the
try_compile() project.

binary

String specifying the binary directory of the
try_compile() project.
For non-project invocations, this is often the same as
the source directory.

cmakeVariables

An optional key that is present when CMake propagates variables
into the test project, either automatically or due to the
CMAKE_TRY_COMPILE_PLATFORM_VARIABLES variable.
Its value is a mapping from variable names to their values.

buildResult

A mapping describing the result of compiling the test code.
It has the following keys:

variable

A string specifying the name of the CMake variable
storing the result of trying to build the test project.

cached

A boolean indicating whether the above result variable
is stored in the CMake cache.

stdout

A YAML literal block scalar containing the output from building
the test project, represented using our Text Block Encoding.
This contains build output from both stdout and stderr.

exitCode

An integer specifying the build tool exit code from trying
to build the test project.

Event Kind try_run¶

The try_run() command logs try_run events.

There is only one try_run event major version, version 1.

try_run-v1 Event¶

A try_run-v1 event is a YAML mapping:

kind: "try_run-v1"
backtrace:
  - "CMakeLists.txt:456 (try_run)"
checks:
  - "Checking for something"
description: "Explicit LOG_DESCRIPTION"
directories:
  source: "/path/to/.../TryCompile-56789"
  binary: "/path/to/.../TryCompile-56789"
buildResult:
  variable: "COMPILE_RESULT"
  cached: true
  stdout: |
    # ...
  exitCode: 0
runResult:
  variable: "RUN_RESULT"
  cached: true
  stdout: |
    # ...
  stderr: |
    # ...
  exitCode: 0

The keys specific to try_run-v1 mappings include those
documented by the try_compile-v1 event, plus:

runResult

A mapping describing the result of running the test code.
It has the following keys:

variable

A string specifying the name of the CMake variable
storing the result of trying to run the test executable.

cached

A boolean indicating whether the above result variable
is stored in the CMake cache.

stdout

An optional key that is present when the test project built successfully.
Its value is a YAML literal block scalar containing output from running
the test executable, represented using our Text Block Encoding.

If RUN_OUTPUT_VARIABLE was used, stdout and stderr are captured
together, so this will contain both.  Otherwise, this will contain
only the stdout output.

stderr

An optional key that is present when the test project built successfully
and the RUN_OUTPUT_VARIABLE option was not used.
Its value is a YAML literal block scalar containing output from running
the test executable, represented using our Text Block Encoding.

If RUN_OUTPUT_VARIABLE was used, stdout and stderr are captured
together in the stdout key, and this key will not be present.
Otherwise, this will contain the stderr output.

exitCode

An optional key that is present when the test project built successfully.
Its value is an integer specifying the exit code, or a string containing
an error message, from trying to run the test executable.

Table of Contents

cmake-configure-log(7)

Introduction

Log Structure

Log Versioning

Text Block Encoding

Event Kinds

Event Kind message

message-v1 Event

Event Kind try_compile

try_compile-v1 Event

Event Kind try_run

try_run-v1 Event

Previous topic

cmake-compile-features(7)

Next topic

cmake-cxxmodules(7)

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-configure-log(7)

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>cmake-cxxmodules(7) — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cmake.css" />

    <link rel="icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="cmake-developer(7)" href="cmake-developer.7.html" />
    <link rel="prev" title="cmake-configure-log(7)" href="cmake-configure-log.7.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-cxxmodules(7)

cmake-cxxmodules(7)¶

New in version 3.28.

C++ 20 introduced the concept of "modules" to the language.  The design
requires build systems to order compilations among each other to satisfy
import statements reliably.  CMake's implementation asks the compiler
to scan source files for module dependencies during the build, collates
scanning results to infer ordering constraints, and tells the build tool
how to dynamically update the build graph.

Scanning Control¶

Whether or not sources get scanned for C++ module usage is dependent on the
following queries. The first query that provides a yes/no answer is used.

If the source file belongs to a file set of type CXX_MODULES, it will
be scanned.

If the target does not use at least C++ 20, it will not be scanned.

If the source file is not the language CXX, it will not be scanned.

If the CXX_SCAN_FOR_MODULES source file property is set, its
value will be used.

If the CXX_SCAN_FOR_MODULES target property is set, its value
will be used.  Set the CMAKE_CXX_SCAN_FOR_MODULES variable
to initialize this property on all targets as they are created.

Otherwise, the source file will be scanned if the compiler and generator
support scanning.  See policy CMP0155.

Note that any scanned source will be excluded from any unity build (see
UNITY_BUILD) because module-related statements can only happen at
one place within a C++ translation unit.

Compiler Support¶

Compilers which CMake natively supports module dependency scanning include:

MSVC toolset 14.34 and newer (provided with Visual Studio 17.4 and newer)

LLVM/Clang 16.0 and newer

GCC 14 (for the in-development branch, after 2023-09-20) and newer

Generator Support¶

The list of generators which support scanning sources for C++ modules include:

Ninja

Ninja Multi-Config

Visual Studio 17 2022

Limitations¶

There are a number of known limitations of the current C++ module support in
CMake.  This does not document known limitations or bugs in compilers as these
can change over time.

For all generators:

Header units are not supported.

No builtin support for import std; or other compiler-provided modules.

For the Ninja Generators:

ninja 1.11 or newer is required.

For the Visual Studio Generators:

Only Visual Studio 2022 and MSVC toolsets 14.34 (Visual Studio
17.4) and newer.

No support for exporting or installing BMI or module information.

No support for compiling BMIs from IMPORTED targets with C++ modules.

No diagnosis of using modules provided by PRIVATE sources from
PUBLIC module sources.

Table of Contents

cmake-cxxmodules(7)

Scanning Control

Compiler Support

Generator Support

Limitations

Previous topic

cmake-configure-log(7)

Next topic

cmake-developer(7)

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-cxxmodules(7)

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>cmake-developer(7) — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cmake.css" />

    <link rel="icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="cmake-env-variables(7)" href="cmake-env-variables.7.html" />
    <link rel="prev" title="cmake-cxxmodules(7)" href="cmake-cxxmodules.7.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-developer(7)

cmake-developer(7)¶

Contents

cmake-developer(7)

Introduction

Accessing Windows Registry

Query Windows Registry

Find Using Windows Registry

Find Modules

Standard Variable Names

A Sample Find Module

Introduction¶

This manual is intended for reference by developers working with
cmake-language(7) code, whether writing their own modules,
authoring their own build systems, or working on CMake itself.

See https://cmake.org/get-involved/ to get involved in development of
CMake upstream.  It includes links to contribution instructions, which
in turn link to developer guides for CMake itself.

Accessing Windows Registry¶

CMake offers some facilities to access the registry on Windows platforms.

Query Windows Registry¶

New in version 3.24.

The cmake_host_system_information() command offers the possibility to
query the registry on the local computer. See
cmake_host_system(QUERY_WINDOWS_REGISTRY) for
more information.

Find Using Windows Registry¶

Changed in version 3.24.

Options HINTS and PATHS of find_file(),
find_library(), find_path(), find_program(), and
find_package() commands offer the possibility, on Windows
platform, to query the registry.

The formal syntax, as specified using
BNF notation with
the regular extensions, for registry query is the following:

registry_query  ::=  '[' sep_definition? root_key
                         ((key_separator sub_key)? (value_separator value_name_)?)? ']'
sep_definition  ::=  '{' value_separator '}'
root_key        ::=  'HKLM' | 'HKEY_LOCAL_MACHINE' | 'HKCU' | 'HKEY_CURRENT_USER' |
                     'HKCR' | 'HKEY_CLASSES_ROOT' | 'HKCC' | 'HKEY_CURRENT_CONFIG' |
                     'HKU' | 'HKEY_USERS'
sub_key         ::=  element (key_separator element)*
key_separator   ::=  '/' | '\\'
value_separator ::=  element | ';'
value_name      ::=  element | '(default)'
element         ::=  character\+
character       ::=  <any character except key_separator and value_separator>

The sep_definition optional item offers the possibility to specify
the string used to separate the sub_key from the value_name
item. If not specified, the character ; is used. Multiple
registry_query items can be specified as part of a path.

# example using default separator
find_file(... PATHS "/root/[HKLM/Stuff;InstallDir]/lib[HKLM\\\\Stuff;Architecture]")

# example using different specified separators
find_library(... HINTS "/root/[{|}HKCU/Stuff|InstallDir]/lib[{@@}HKCU\\\\Stuff@@Architecture]")

If the value_name item is not specified or has the special name
(default), the content of the default value, if any, will be returned. The
supported types for the value_name are:

REG_SZ.

REG_EXPAND_SZ. The returned data is expanded.

REG_DWORD.

REG_QWORD.

When the registry query failed, typically because the key does not exist or
the data type is not supported, the string /REGISTRY-NOTFOUND is substituted
to the [] query expression.

Find Modules¶

A "find module" is a Find<PackageName>.cmake file to be loaded by the
find_package() command when invoked for <PackageName>.

The primary task of a find module is to determine whether a package is
available, set the <PackageName>_FOUND variable to reflect this and
provide any variables, macros and imported targets required to use the
package.  A find module is useful in cases where an upstream library does
not provide a config file package.

The traditional approach is to use variables for everything, including
libraries and executables: see the Standard Variable Names section
below.  This is what most of the existing find modules provided by CMake
do.

The more modern approach is to behave as much like
config file packages files as possible, by
providing imported target.  This has the advantage
of propagating Transitive Usage Requirements to consumers.

In either case (or even when providing both variables and imported
targets), find modules should provide backwards compatibility with old
versions that had the same name.

A FindFoo.cmake module will typically be loaded by the command:

find_package(Foo [major[.minor[.patch[.tweak]]]]
             [EXACT] [QUIET] [REQUIRED]
             [[COMPONENTS] [components...]]
             [OPTIONAL_COMPONENTS components...]
             [NO_POLICY_SCOPE])

See the find_package() documentation for details on what
variables are set for the find module.  Most of these are dealt with by
using FindPackageHandleStandardArgs.

Briefly, the module should only locate versions of the package
compatible with the requested version, as described by the
Foo_FIND_VERSION family of variables.  If Foo_FIND_QUIETLY is
set to true, it should avoid printing messages, including anything
complaining about the package not being found.  If Foo_FIND_REQUIRED
is set to true, the module should issue a FATAL_ERROR if the package
cannot be found.  If neither are set to true, it should print a
non-fatal message if it cannot find the package.

Packages that find multiple semi-independent parts (like bundles of
libraries) should search for the components listed in
Foo_FIND_COMPONENTS if it is set , and only set Foo_FOUND to
true if for each searched-for component <c> that was not found,
Foo_FIND_REQUIRED_<c> is not set to true.  The HANDLE_COMPONENTS
argument of find_package_handle_standard_args() can be used to
implement this.

If Foo_FIND_COMPONENTS is not set, which modules are searched for
and required is up to the find module, but should be documented.

For internal implementation, it is a generally accepted convention that
variables starting with underscore are for temporary use only.

Standard Variable Names¶

For a FindXxx.cmake module that takes the approach of setting
variables (either instead of or in addition to creating imported
targets), the following variable names should be used to keep things
consistent between Find modules.  Note that all variables start with
Xxx_, which (unless otherwise noted) must match exactly the name
of the FindXxx.cmake file, including upper/lowercase.
This prefix on the variable names ensures that they do not conflict with
variables of other Find modules.  The same pattern should also be followed
for any macros, functions and imported targets defined by the Find module.

Xxx_INCLUDE_DIRS

The final set of include directories listed in one variable for use by
client code. This should not be a cache entry (note that this also means
this variable should not be used as the result variable of a
find_path() command - see Xxx_INCLUDE_DIR below for that).

Xxx_LIBRARIES

The libraries to use with the module.  These may be CMake targets, full
absolute paths to a library binary or the name of a library that the
linker must find in its search path.  This should not be a cache entry
(note that this also means this variable should not be used as the
result variable of a find_library() command - see
Xxx_LIBRARY below for that).

Xxx_DEFINITIONS

The compile definitions to use when compiling code that uses the module.
This really shouldn't include options such as -DHAS_JPEG that a client
source-code file uses to decide whether to #include <jpeg.h>

Xxx_EXECUTABLE

The full absolute path to an executable.  In this case, Xxx might not
be the name of the module, it might be the name of the tool (usually
converted to all uppercase), assuming that tool has such a well-known name
that it is unlikely that another tool with the same name exists.  It would
be appropriate to use this as the result variable of a
find_program() command.

Xxx_YYY_EXECUTABLE

Similar to Xxx_EXECUTABLE except here the Xxx is always the module
name and YYY is the tool name (again, usually fully uppercase).
Prefer this form if the tool name is not very widely known or has the
potential  to clash with another tool.  For greater consistency, also
prefer this form if the module provides more than one executable.

Xxx_LIBRARY_DIRS

Optionally, the final set of library directories listed in one
variable for use by client code. This should not be a cache entry.

Xxx_ROOT_DIR

Where to find the base directory of the module.

Xxx_VERSION_VV

Variables of this form specify whether the Xxx module being provided
is version VV of the module.  There should not be more than one
variable of this form set to true for a given module.  For example, a
module Barry might have evolved over many years and gone through a
number of different major versions.  Version 3 of the Barry module
might set the variable Barry_VERSION_3 to true, whereas an older
version of the module might set Barry_VERSION_2 to true instead.
It would be an error for both Barry_VERSION_3 and Barry_VERSION_2
to both be set to true.

Xxx_WRAP_YY

When a variable of this form is set to false, it indicates that the
relevant wrapping command should not be used.  The wrapping command
depends on the module, it may be implied by the module name or it might
be specified by the YY part of the variable.

Xxx_Yy_FOUND

For variables of this form, Yy is the name of a component for the
module.  It should match exactly one of the valid component names that
may be passed to the find_package() command for the module.
If a variable of this form is set to false, it means that the Yy
component of module Xxx was not found or is not available.
Variables of this form would typically be used for optional components
so that the caller can check whether an optional component is available.

Xxx_FOUND

When the find_package() command returns to the caller, this
variable will be set to true if the module was deemed to have been found
successfully.

Xxx_NOT_FOUND_MESSAGE

Should be set by config-files in the case that it has set
Xxx_FOUND to FALSE.  The contained message will be printed by the
find_package() command and by
find_package_handle_standard_args() to inform the user about the
problem.  Use this instead of calling message() directly to
report a reason for failing to find the module or package.

Xxx_RUNTIME_LIBRARY_DIRS

Optionally, the runtime library search path for use when running an
executable linked to shared libraries.  The list should be used by
user code to create the PATH on windows or LD_LIBRARY_PATH on
UNIX.  This should not be a cache entry.

Xxx_VERSION

The full version string of the package found, if any.  Note that many
existing modules provide Xxx_VERSION_STRING instead.

Xxx_VERSION_MAJOR

The major version of the package found, if any.

Xxx_VERSION_MINOR

The minor version of the package found, if any.

Xxx_VERSION_PATCH

The patch version of the package found, if any.

The following names should not usually be used in CMakeLists.txt files.
They are intended for use by Find modules to specify and cache the locations
of specific files or directories.  Users are typically able to set and edit
these variables to control the behavior of Find modules (like entering the
path to a library manually):

Xxx_LIBRARY

The path of the library.  Use this form only when the module provides a
single library.  It is appropriate to use this as the result variable
in a find_library() command.

Xxx_Yy_LIBRARY

The path of library Yy provided by the module Xxx.  Use this form
when the module provides more than one library or where other modules may
also provide a library of the same name. It is also appropriate to use
this form as the result variable in a find_library() command.

Xxx_INCLUDE_DIR

When the module provides only a single library, this variable can be used
to specify where to find headers for using the library (or more accurately,
the path that consumers of the library should add to their header search
path).  It would be appropriate to use this as the result variable in a
find_path() command.

Xxx_Yy_INCLUDE_DIR

If the module provides more than one library or where other modules may
also provide a library of the same name, this form is recommended for
specifying where to find headers for using library Yy provided by
the module.  Again, it would be appropriate to use this as the result
variable in a find_path() command.

To prevent users being overwhelmed with settings to configure, try to
keep as many options as possible out of the cache, leaving at least one
option which can be used to disable use of the module, or locate a
not-found library (e.g. Xxx_ROOT_DIR).  For the same reason, mark
most cache options as advanced.  For packages which provide both debug
and release binaries, it is common to create cache variables with a
_LIBRARY_<CONFIG> suffix, such as Foo_LIBRARY_RELEASE and
Foo_LIBRARY_DEBUG.  The SelectLibraryConfigurations module
can be helpful for such cases.

While these are the standard variable names, you should provide
backwards compatibility for any old names that were actually in use.
Make sure you comment them as deprecated, so that no-one starts using
them.

A Sample Find Module¶

We will describe how to create a simple find module for a library Foo.

The top of the module should begin with a license notice, followed by
a blank line, and then followed by a Bracket Comment.  The comment
should begin with .rst: to indicate that the rest of its content is
reStructuredText-format documentation.  For example:

# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindFoo
-------

Finds the Foo library.

Imported Targets
^^^^^^^^^^^^^^^^

This module provides the following imported targets, if found:

``Foo::Foo``
  The Foo library

Result Variables
^^^^^^^^^^^^^^^^

This will define the following variables:

``Foo_FOUND``
  True if the system has the Foo library.
``Foo_VERSION``
  The version of the Foo library which was found.
``Foo_INCLUDE_DIRS``
  Include directories needed to use Foo.
``Foo_LIBRARIES``
  Libraries needed to link to Foo.

Cache Variables
^^^^^^^^^^^^^^^

The following cache variables may also be set:

``Foo_INCLUDE_DIR``
  The directory containing ``foo.h``.
``Foo_LIBRARY``
  The path to the Foo library.

#]=======================================================================]

The module documentation consists of:

An underlined heading specifying the module name.

A simple description of what the module finds.
More description may be required for some packages.  If there are
caveats or other details users of the module should be aware of,
specify them here.

A section listing imported targets provided by the module, if any.

A section listing result variables provided by the module.

Optionally a section listing cache variables used by the module, if any.

If the package provides any macros or functions, they should be listed in
an additional section, but can be documented by additional .rst:
comment blocks immediately above where those macros or functions are defined.

The find module implementation may begin below the documentation block.
Now the actual libraries and so on have to be found.  The code here will
obviously vary from module to module (dealing with that, after all, is the
point of find modules), but there tends to be a common pattern for libraries.

First, we try to use pkg-config to find the library.  Note that we
cannot rely on this, as it may not be available, but it provides a good
starting point.

find_package(PkgConfig)
pkg_check_modules(PC_Foo QUIET Foo)

This should define some variables starting PC_Foo_ that contain the
information from the Foo.pc file.

Now we need to find the libraries and include files; we use the
information from pkg-config to provide hints to CMake about where to
look.

find_path(Foo_INCLUDE_DIR
  NAMES foo.h
  PATHS ${PC_Foo_INCLUDE_DIRS}
  PATH_SUFFIXES Foo
)
find_library(Foo_LIBRARY
  NAMES foo
  PATHS ${PC_Foo_LIBRARY_DIRS}
)

Alternatively, if the library is available with multiple configurations, you can
use SelectLibraryConfigurations to automatically set the
Foo_LIBRARY variable instead:

find_library(Foo_LIBRARY_RELEASE
  NAMES foo
  PATHS ${PC_Foo_LIBRARY_DIRS}/Release
)
find_library(Foo_LIBRARY_DEBUG
  NAMES foo
  PATHS ${PC_Foo_LIBRARY_DIRS}/Debug
)

include(SelectLibraryConfigurations)
select_library_configurations(Foo)

If you have a good way of getting the version (from a header file, for
example), you can use that information to set Foo_VERSION (although
note that find modules have traditionally used Foo_VERSION_STRING,
so you may want to set both).  Otherwise, attempt to use the information
from pkg-config

set(Foo_VERSION ${PC_Foo_VERSION})

Now we can use FindPackageHandleStandardArgs to do most of the
rest of the work for us

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo
  FOUND_VAR Foo_FOUND
  REQUIRED_VARS
    Foo_LIBRARY
    Foo_INCLUDE_DIR
  VERSION_VAR Foo_VERSION
)

This will check that the REQUIRED_VARS contain values (that do not
end in -NOTFOUND) and set Foo_FOUND appropriately.  It will also
cache those values.  If Foo_VERSION is set, and a required version
was passed to find_package(), it will check the requested version
against the one in Foo_VERSION.  It will also print messages as
appropriate; note that if the package was found, it will print the
contents of the first required variable to indicate where it was found.

At this point, we have to provide a way for users of the find module to
link to the library or libraries that were found.  There are two
approaches, as discussed in the Find Modules section above.  The
traditional variable approach looks like

if(Foo_FOUND)
  set(Foo_LIBRARIES ${Foo_LIBRARY})
  set(Foo_INCLUDE_DIRS ${Foo_INCLUDE_DIR})
  set(Foo_DEFINITIONS ${PC_Foo_CFLAGS_OTHER})
endif()

If more than one library was found, all of them should be included in
these variables (see the Standard Variable Names section for more
information).

When providing imported targets, these should be namespaced (hence the
Foo:: prefix); CMake will recognize that values passed to
target_link_libraries() that contain :: in their name are
supposed to be imported targets (rather than just library names), and
will produce appropriate diagnostic messages if that target does not
exist (see policy CMP0028).

if(Foo_FOUND AND NOT TARGET Foo::Foo)
  add_library(Foo::Foo UNKNOWN IMPORTED)
  set_target_properties(Foo::Foo PROPERTIES
    IMPORTED_LOCATION "${Foo_LIBRARY}"
    INTERFACE_COMPILE_OPTIONS "${PC_Foo_CFLAGS_OTHER}"
    INTERFACE_INCLUDE_DIRECTORIES "${Foo_INCLUDE_DIR}"
  )
endif()

One thing to note about this is that the INTERFACE_INCLUDE_DIRECTORIES and
similar properties should only contain information about the target itself, and
not any of its dependencies.  Instead, those dependencies should also be
targets, and CMake should be told that they are dependencies of this target.
CMake will then combine all the necessary information automatically.

The type of the IMPORTED target created in the
add_library() command can always be specified as UNKNOWN
type.  This simplifies the code in cases where static or shared variants may
be found, and CMake will determine the type by inspecting the files.

If the library is available with multiple configurations, the
IMPORTED_CONFIGURATIONS target property should also be
populated:

if(Foo_FOUND)
  if (NOT TARGET Foo::Foo)
    add_library(Foo::Foo UNKNOWN IMPORTED)
  endif()
  if (Foo_LIBRARY_RELEASE)
    set_property(TARGET Foo::Foo APPEND PROPERTY
      IMPORTED_CONFIGURATIONS RELEASE
    )
    set_target_properties(Foo::Foo PROPERTIES
      IMPORTED_LOCATION_RELEASE "${Foo_LIBRARY_RELEASE}"
    )
  endif()
  if (Foo_LIBRARY_DEBUG)
    set_property(TARGET Foo::Foo APPEND PROPERTY
      IMPORTED_CONFIGURATIONS DEBUG
    )
    set_target_properties(Foo::Foo PROPERTIES
      IMPORTED_LOCATION_DEBUG "${Foo_LIBRARY_DEBUG}"
    )
  endif()
  set_target_properties(Foo::Foo PROPERTIES
    INTERFACE_COMPILE_OPTIONS "${PC_Foo_CFLAGS_OTHER}"
    INTERFACE_INCLUDE_DIRECTORIES "${Foo_INCLUDE_DIR}"
  )
endif()

The RELEASE variant should be listed first in the property
so that the variant is chosen if the user uses a configuration which is
not an exact match for any listed IMPORTED_CONFIGURATIONS.

Most of the cache variables should be hidden in the ccmake interface unless
the user explicitly asks to edit them.

mark_as_advanced(
  Foo_INCLUDE_DIR
  Foo_LIBRARY
)

If this module replaces an older version, you should set compatibility variables
to cause the least disruption possible.

# compatibility variables
set(Foo_VERSION_STRING ${Foo_VERSION})

Table of Contents

cmake-developer(7)

Introduction

Accessing Windows Registry

Query Windows Registry

Find Using Windows Registry

Find Modules

Standard Variable Names

A Sample Find Module

Previous topic

cmake-cxxmodules(7)

Next topic

cmake-env-variables(7)

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-developer(7)

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>cmake-env-variables(7) — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cmake.css" />

    <link rel="icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="CMAKE_APPBUNDLE_PATH" href="../envvar/CMAKE_APPBUNDLE_PATH.html" />
    <link rel="prev" title="cmake-developer(7)" href="cmake-developer.7.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-env-variables(7)

cmake-env-variables(7)¶

Contents

cmake-env-variables(7)

Environment Variables that Change Behavior

Environment Variables that Control the Build

Environment Variables for Languages

Environment Variables for CTest

Environment Variables for the CMake curses interface

This page lists environment variables that have special
meaning to CMake.

For general information on environment variables, see the
Environment Variables
section in the cmake-language manual.

Environment Variables that Change Behavior¶

CMAKE_APPBUNDLE_PATH

CMAKE_FRAMEWORK_PATH

CMAKE_INCLUDE_PATH

CMAKE_LIBRARY_PATH

CMAKE_MAXIMUM_RECURSION_DEPTH

CMAKE_PREFIX_PATH

CMAKE_PROGRAM_PATH

SSL_CERT_DIR

SSL_CERT_FILE

Environment Variables that Control the Build¶

ADSP_ROOT

CMAKE_APPLE_SILICON_PROCESSOR

CMAKE_BUILD_PARALLEL_LEVEL

CMAKE_BUILD_TYPE

CMAKE_COLOR_DIAGNOSTICS

CMAKE_CONFIGURATION_TYPES

CMAKE_CONFIG_TYPE

CMAKE_CROSSCOMPILING_EMULATOR

CMAKE_EXPORT_COMPILE_COMMANDS

CMAKE_GENERATOR

CMAKE_GENERATOR_INSTANCE

CMAKE_GENERATOR_PLATFORM

CMAKE_GENERATOR_TOOLSET

CMAKE_INSTALL_MODE

CMAKE_INSTALL_PREFIX

CMAKE_<LANG>_COMPILER_LAUNCHER

CMAKE_<LANG>_IMPLICIT_LINK_DIRECTORIES_EXCLUDE

CMAKE_<LANG>_LINKER_LAUNCHER

CMAKE_MSVCIDE_RUN_PATH

CMAKE_NO_VERBOSE

CMAKE_OSX_ARCHITECTURES

CMAKE_TEST_LAUNCHER

CMAKE_TOOLCHAIN_FILE

DESTDIR

LDFLAGS

MACOSX_DEPLOYMENT_TARGET

<PackageName>_ROOT

VERBOSE

Environment Variables for Languages¶

ASM<DIALECT>

ASM<DIALECT>FLAGS

CC

CFLAGS

CSFLAGS

CUDAARCHS

CUDACXX

CUDAFLAGS

CUDAHOSTCXX

CXX

CXXFLAGS

FC

FFLAGS

HIPCXX

HIPFLAGS

HIPHOSTCXX

ISPC

ISPCFLAGS

OBJC

OBJCXX

RC

RCFLAGS

SWIFTC

Environment Variables for CTest¶

CMAKE_CONFIG_TYPE

CTEST_INTERACTIVE_DEBUG_MODE

CTEST_NO_TESTS_ACTION

CTEST_OUTPUT_ON_FAILURE

CTEST_PARALLEL_LEVEL

CTEST_PROGRESS_OUTPUT

CTEST_USE_LAUNCHERS_DEFAULT

DASHBOARD_TEST_FROM_CTEST

Environment Variables for the CMake curses interface¶

CCMAKE_COLORS

Table of Contents

cmake-env-variables(7)

Environment Variables that Change Behavior

Environment Variables that Control the Build

Environment Variables for Languages

Environment Variables for CTest

Environment Variables for the CMake curses interface

Previous topic

cmake-developer(7)

Next topic

CMAKE_APPBUNDLE_PATH

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

cmake-env-variables(7)

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.