CMAKE-BUILDSYSTEM(7)
π CMake Buildsystem Reference π
Okay bestie, this is cmake-buildsystem(7) β the CMake Buildsystem Reference β and weβre gonna get you comfy with how CMake thinks about targets, libraries, and all the little usage requirements that make everything slay. π«Ά
β¨ 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. No cap. π§
π οΈ Executables π
Executables are binaries created by linking object files together, one of which contains a program entry point, e.g., main.
The add_executable() command defines an executable target:
add_executable(mytool mytool.cpp)
CMake generates build rules to compile the source files into object files and link them into an executable. β¨
Link dependencies of executables may be specified using the target_link_libraries() command. Linkers start with the object files compiled from the executableβs own source files, and then resolve remaining symbol dependencies by searching linked libraries. Literally the main character energy of link steps. π
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. π₯
π¦ Static Libraries π
Static libraries are archives of object files. They are produced by an archiver, not a linker. Executables, Shared Libraries, and Module Libraries may link to static libraries as dependencies. Linkers select subsets of object files from static libraries as needed to resolve symbols and link them into consuming binaries. Each binary that links to a static library gets its own copy of the symbols, and the static library itself is not needed at runtime.
The add_library() command defines a static library target when called with the STATIC library type:
add_library(archive STATIC archive.cpp zip.cpp lzma.cpp)
or, when the BUILD_SHARED_LIBS variable is false, with no type:
add_library(archive archive.cpp zip.cpp lzma.cpp)
CMake generates build rules to compile the source files into object files and archive them into a static library. π
Link dependencies of static libraries may be specified using the target_link_libraries() command. Since static libraries are archives rather than linked binaries, object files from their link dependencies are not included in the libraries themselves (except for Object Libraries specified as direct link dependencies). Instead, CMake records static librariesβ link dependencies for transitive use when linking consuming binaries. Lowkey important, highkey iconic. π
π¦ Shared Libraries π¦
Shared libraries are binaries created by linking object files together. Executables, other shared libraries, and Module Libraries may link to shared libraries as dependencies. Linkers record references to shared libraries in consuming binaries. At runtime, a dynamic loader searches for referenced shared libraries on disk and loads their symbols. π
The add_library() command defines a shared library target when called with the SHARED library type:
add_library(archive SHARED archive.cpp zip.cpp lzma.cpp)
or, when the BUILD_SHARED_LIBS variable is true, with no type:
add_library(archive archive.cpp zip.cpp lzma.cpp)
CMake generates build rules to compile the source files into object files and link them into a shared library. β¨
Link dependencies of shared libraries may be specified using the target_link_libraries() command. Linkers start with the object files compiled from the shared libraryβs own source files, and then resolve remaining symbol dependencies by searching linked libraries. π
β οΈ Note: CMake expects shared libraries to export at least one symbol. If a library does not export any unmanaged symbols, e.g., a Windows resource DLL or C++/CLI DLL, make it a Module Library instead. Bestie, donβt fight this one β itβs giving βjust use MODULE.β π
π Apple Frameworks πΈ
Shared Libraries and Static Libraries may be marked with the FRAMEWORK target property to create a macOS or iOS Framework. 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
)
π§© Module Libraries π§
Module libraries are binaries created by linking object files together. Unlike Shared Libraries, module libraries may not be linked by other binaries as dependencies β do not name them in the right-hand side of the target_link_libraries() command. Instead, module libraries are plugins that an application can dynamically load on-demand at runtime, e.g., by dlopen. πβ¨
The add_library() command defines a module library target when called with the MODULE library type:
add_library(archivePlugin MODULE 7z.cpp)
CMake generates build rules to compile the source files into object files and link them into a module library. π¦
Link dependencies of module libraries may be specified using the target_link_libraries() command. Linkers start with the object files compiled from the module libraryβs own source files, and then resolve remaining symbol dependencies by searching linked libraries. π₯
π§Έ Object Libraries π§Έ
Object libraries are collections of object files created by compiling source files without any archiving or linking. The object files may be used when linking Executables, Shared Libraries, and Module Libraries, or when archiving Static Libraries. Ngl, theyβre the buildsystemβs little collectible objects. π
The add_library() command defines an object library target when called with the OBJECT library type:
add_library(archiveObjs OBJECT archive.cpp zip.cpp lzma.cpp)
CMake generates build rules to compile the source files into object files. β¨
Other targets may specify the object files as source inputs by using the generator expression syntax $<TARGET_OBJECTS:name>:
add_library(archiveExtras STATIC $<TARGET_OBJECTS:archiveObjs> extras.cpp)
add_executable(test_exe $<TARGET_OBJECTS:archiveObjs> test.cpp)
The consuming targets are linked (or archived) using object files both from their own sources and from the named object libraries. π
Alternatively, object libraries may be specified as link dependencies of other targets:
add_library(archiveExtras STATIC extras.cpp)
target_link_libraries(archiveExtras PUBLIC archiveObjs)
add_executable(test_exe test.cpp)
target_link_libraries(test_exe archiveObjs)
The consuming targets are linked (or archived) using object files both from their own sources and from object libraries specified as direct link dependencies by target_link_libraries(). See Linking Object Libraries. π«Ά
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 π οΈ
Targets build according to their own build specification in combination with usage requirements propagated from their link dependencies. Both may be specified using target-specific commands. Periodt. π
For example:
add_library(archive SHARED archive.cpp zip.cpp)
if (LZMA_FOUND)
# Add a source implementing support for lzma.
target_sources(archive PRIVATE lzma.cpp)
# Compile the 'archive' library sources with '-DBUILDING_WITH_LZMA'.
target_compile_definitions(archive PRIVATE BUILDING_WITH_LZMA)
endif()
target_compile_definitions(archive INTERFACE USING_ARCHIVE_LIB)
add_executable(consumer consumer.cpp)
# Link 'consumer' to 'archive'. This also consumes its usage requirements,
# so 'consumer.cpp' is compiled with '-DUSING_ARCHIVE_LIB'.
target_link_libraries(consumer archive)
π― Target Commands π―
Target-specific commands populate the build specification of Binary Targets and usage requirements of Binary Targets, Interface Libraries, and Imported Targets. β¨
Invocations must specify scope keywords, each affecting the visibility of arguments following it. The scopes are:
PUBLICβ Populates both properties for building and properties for using a target.PRIVATEβ Populates only properties for building a target.INTERFACEβ Populates only properties for using a target.
The commands are:
target_compile_definitions()β Populates theCOMPILE_DEFINITIONSbuild specification andINTERFACE_COMPILE_DEFINITIONSusage requirement properties.
For example, the call
target_compile_definitions(archive
PRIVATE BUILDING_WITH_LZMA
INTERFACE USING_ARCHIVE_LIB
)
appends BUILDING_WITH_LZMA to the targetβs COMPILE_DEFINITIONS property and appends USING_ARCHIVE_LIB to the targetβs INTERFACE_COMPILE_DEFINITIONS property. Slay. π
target_compile_options()β fills up theCOMPILE_OPTIONSbuild specification and theINTERFACE_COMPILE_OPTIONSusage requirement properties. πtarget_compile_features()β Added in version 3.1. Fills theCOMPILE_FEATURESbuild specification and theINTERFACE_COMPILE_FEATURESusage requirement properties.target_include_directories()β fills theINCLUDE_DIRECTORIESbuild specification and theINTERFACE_INCLUDE_DIRECTORIESusage requirement properties. Throw in theSYSTEMoption and it also fills theINTERFACE_SYSTEM_INCLUDE_DIRECTORIESusage requirement. β¨
Ok so for convenience: you can turn on the CMAKE_INCLUDE_CURRENT_DIR variable to add the source directory and the corresponding build directory as INCLUDE_DIRECTORIES on all targets. Same energy with CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE β enable that one and they get added as INTERFACE_INCLUDE_DIRECTORIES on all targets. Two variables, two vibes, both iconic.
target_sources()β Added in version 3.1. Fills theSOURCESbuild specification and theINTERFACE_SOURCESusage requirement properties. π«Ά
It also supports specifying File Sets, which can add C++ module sources and headers that are not listed in the SOURCES and INTERFACE_SOURCES properties. File sets can also fill the INCLUDE_DIRECTORIES build specification and the INTERFACE_INCLUDE_DIRECTORIES usage requirement properties with the include directories that contain the headers. Literally so handy.
target_precompile_headers()β Added in version 3.16. Fills thePRECOMPILE_HEADERSbuild specification and theINTERFACE_PRECOMPILE_HEADERSusage requirement properties.target_link_libraries()β fills theLINK_LIBRARIESbuild specification and theINTERFACE_LINK_LIBRARIESusage requirement properties. π
This is the primary mechanism by which link dependencies and their usage requirements get transitively propagated to affect compilation and linking of a target. Main character behavior, honestly.
target_link_directories()β Added in version 3.13. Fills theLINK_DIRECTORIESbuild specification and theINTERFACE_LINK_DIRECTORIESusage requirement properties.target_link_options()β Added in version 3.13. Fills theLINK_OPTIONSbuild specification and theINTERFACE_LINK_OPTIONSusage requirement properties.
π§± Target Build Specification
So the build specification of Binary Targets is represented by target properties. For each of the compile and link properties below, compiling and linking the target is affected both by its own value and by the corresponding usage requirement property β the one named with an INTERFACE_ prefix β collected from the transitive closure of link dependencies. Both. Always both. π
πΈ Target Compile Properties
These represent the build specification for compiling a target.
COMPILE_DEFINITIONSβ the list of compile definitions for compiling sources in the target. They get passed to the compiler with-Dflags, or equivalent, in an unspecified order (don't come for the order, it's not that kind of list).
When compiling sources of a SHARED library, a MODULE library, or an EXECUTABLE with ENABLE_EXPORTS enabled, CMake automatically defines a target-specific preprocessor symbol. By default that definition is of the form <target>_EXPORTS, but you can override it with the DEFINE_SYMBOL target property. Why do we care? Because it lets headers detect whether they're included from inside their implementation sources, and correctly set up export/import annotations or visibility of symbols. Slay. β¨
COMPILE_OPTIONSβ the list of compile options for compiling sources in the target. Passed to the compiler as flags, in the order of appearance (this one does care about order, bestie).
Compile options are automatically escaped for the shell.
Some compile options are best specified via dedicated settings instead, like the POSITION_INDEPENDENT_CODE target property. iykyk.
COMPILE_FEATURESβ Added in version 3.1. The list of compile features needed for compiling sources in the target. Typically these make sure the target's sources get compiled using a sufficient language standard level. πINCLUDE_DIRECTORIESβ the list of include directories for compiling sources in the target. Passed to the compiler with-Ior-isystemflags, or equivalent, in the order of appearance.
For convenience, the CMAKE_INCLUDE_CURRENT_DIR variable may be enabled to add the source directory and corresponding build directory as INCLUDE_DIRECTORIES on all targets. π¦
SOURCESβ the list of source files associated with the target. This includes the sources you specified when the target was created by theadd_executable(),add_library(), oradd_custom_target()command. It also includes sources added by thetarget_sources()command β but it does not include File Sets. Noted. πPRECOMPILE_HEADERSβ Added in version 3.16. The list of header files to precompile and include when compiling sources in the target.AUTOMOC_MACRO_NAMESβ Added in version 3.10. The list of macro names used byAUTOMOCto determine if a C++ source in the target needs to be processed by moc. π₯AUTOUIC_OPTIONSβ Added in version 3.0. The list of options used byAUTOUICwhen invoking uic for the target.
π Target Link Properties
These represent the build specification for linking a target.
LINK_LIBRARIESβ the list of link libraries for linking the target, if it's an executable, shared library, or module library. Entries for Static Libraries and Shared Libraries get passed to the linker either via paths to their link artifacts, or with-lflags or equivalent. Entries for Object Libraries get passed to the linker via paths to their object files.
Plus! For compiling and linking the target itself, usage requirements are propagated from LINK_LIBRARIES entries naming Static Libraries, Shared Libraries, Interface Libraries, Object Libraries, and Imported Targets β collected over the transitive closure of their INTERFACE_LINK_LIBRARIES properties. That's the transitive closure, bestie, it goes deep. π
LINK_DIRECTORIESβ Added in version 3.13. The list of link directories for linking the target, if it's an executable, shared library, or module library. The directories get passed to the linker with-Lflags, or equivalent.LINK_OPTIONSβ Added in version 3.13. The list of link options for linking the target, if it's an executable, shared library, or module library. The options get passed to the linker as flags, in the order of appearance.
Link options are automatically escaped for the shell. π
LINK_DEPENDSβ the list of files on which linking the target depends, if it's an executable, shared library, or module library. For example, linker scripts specified viaLINK_OPTIONSmay be listed here, so that changing them causes binaries to be linked again. Understood the assignment. π
π Target Usage Requirements
The usage requirements of a target are the settings that propagate to consumers β the ones that link to the target via target_link_libraries() β so they can correctly compile and link with it. They're represented by transitive compile and link properties.
Ok real talk for a sec: usage requirements are not designed as a way to make downstreams use particularCOMPILE_OPTIONS,COMPILE_DEFINITIONS, etc. for convenience only. The contents of the properties must be requirements, not merely recommendations. No cap. π
See the Creating Relocatable Packages section of the cmake-packages(7) manual for discussion of the additional care that must be taken when specifying usage requirements while creating packages for redistribution.
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. That's the whole group-chat moderation toolkit right there. π«Ά
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, its usage requirements get passed down to consumer too. π«Ά
Because serialization is a PRIVATE dependency of archiveExtras, its usage requirements do not get passed down to consumer. π
So the general vibe check: a dependency should go in a target_link_libraries() call with the PRIVATE keyword if it's only used by the implementation of a library and not in the header files. If a dependency is also used in the header files of a library (think class inheritance, yeah that kind), then it should be marked a PUBLIC dependency. And a dependency that isn't used by the implementation at all, only by the headers? That one's an INTERFACE dependency, periodt. β¨
And bestie, you can hit target_link_libraries() with multiple uses of each keyword β it's literally fine:
target_link_libraries(archiveExtras
PUBLIC archive
PRIVATE serialization
)
Usage requirements get propagated by reading the INTERFACE_-prefixed variants of target properties from your dependencies and appending those values onto the non-INTERFACE_ variants of the operand. Like, for example: the INTERFACE_INCLUDE_DIRECTORIES of dependencies is read and appended to the INCLUDE_DIRECTORIES of the operand. π
Where order matters and is maintained, and the order you get from the target_link_libraries() calls just won't compile right β that's when you use the appropriate command to set the property directly, which can update the order. Easy.
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>)
β οΈ Heads up bestie: be so careful when you're specifying usage requirements for targets that will be exported for installation via the install(EXPORT) command. Go read Creating Packages for more on that. iykyk π
β¨ Transitive Compile Properties β¨
These are the usage requirements for compiling consumers. Ngl, this is the section that makes consumers actually compile, so pay attention π
INTERFACE_COMPILE_DEFINITIONSβ list of compile definitions for compiling sources in the target's consumers. Typically these get used by the target's header files. πINTERFACE_COMPILE_OPTIONSβ list of compile options for compiling sources in the target's consumers.INTERFACE_COMPILE_FEATURESβ Added in version 3.1. List of compile features needed for compiling sources in the target's consumers. Typically these make sure the target's header files get processed when consumers compile using a sufficient language standard level. π¦INTERFACE_INCLUDE_DIRECTORIESβ list of include directories for compiling sources in the target's consumers. Typically these are the locations of the target's header files. πΈINTERFACE_SYSTEM_INCLUDE_DIRECTORIESβ list of directories that, when specified as include directories (like, byINCLUDE_DIRECTORIESorINTERFACE_INCLUDE_DIRECTORIES), should be treated as "system" include directories when compiling sources in the target's consumers. π§INTERFACE_SOURCESβ list of source files to associate with the target's consumers.INTERFACE_PRECOMPILE_HEADERSβ Added in version 3.16. List of header files to precompile and include when compiling sources in the target's consumers. π₯INTERFACE_AUTOMOC_MACRO_NAMESβ Added in version 3.27. List of macro names used byAUTOMOCto figure out if a C++ source in the target's consumers needs to be processed by moc.INTERFACE_AUTOUIC_OPTIONSβ Added in version 3.0. List of options used byAUTOUICwhen it invokes uic for the target's consumers. π
π Transitive Link Properties π
These represent the usage requirements for linking consumers. Linking era fr fr π
INTERFACE_LINK_LIBRARIESβ list of link libraries for linking the target's consumers, for those that are executables, shared libraries, or module libraries. These are the transitive dependencies of the target.
Also, for compiling and linking the target's consumers, usage requirements are collected from the transitive closure of INTERFACE_LINK_LIBRARIES entries naming Static Libraries, Shared Libraries, Interface Libraries, Object Libraries, and Imported Targets.
INTERFACE_LINK_DIRECTORIESβ Added in version 3.13. List of link directories for linking the target's consumers, for those that are executables, shared libraries, or module libraries. πINTERFACE_LINK_OPTIONSβ Added in version 3.13. List of link options for linking the target's consumers, for those that are executables, shared libraries, or module libraries.INTERFACE_LINK_DEPENDSβ Added in version 3.13. List of files on which linking the target's consumers depends, for those that are executables, shared libraries, or module libraries. π
π Custom Transitive Properties π
Added in version 3.30.
Okay so the TARGET_PROPERTY generator expression evaluates all those build specification and usage requirement properties above as builtin transitive properties. Iconic. But it also supports custom transitive properties, defined by the TRANSITIVE_COMPILE_PROPERTIES and TRANSITIVE_LINK_PROPERTIES properties on the target and its link dependencies. Slay. π¦
For example:
add_library(example INTERFACE)
set_target_properties(example PROPERTIES
TRANSITIVE_COMPILE_PROPERTIES "CUSTOM_C"
TRANSITIVE_LINK_PROPERTIES "CUSTOM_L"
INTERFACE_CUSTOM_C "EXAMPLE_CUSTOM_C"
INTERFACE_CUSTOM_L "EXAMPLE_CUSTOM_L"
)
add_library(mylib STATIC mylib.c)
target_link_libraries(mylib PRIVATE example)
set_target_properties(mylib PROPERTIES
CUSTOM_C "MYLIB_PRIVATE_CUSTOM_C"
CUSTOM_L "MYLIB_PRIVATE_CUSTOM_L"
INTERFACE_CUSTOM_C "MYLIB_IFACE_CUSTOM_C"
INTERFACE_CUSTOM_L "MYLIB_IFACE_CUSTOM_L"
)
add_executable(myexe myexe.c)
target_link_libraries(myexe PRIVATE mylib)
set_target_properties(myexe PROPERTIES
CUSTOM_C "MYEXE_CUSTOM_C"
CUSTOM_L "MYEXE_CUSTOM_L"
)
add_custom_target(print ALL VERBATIM
COMMAND ${CMAKE_COMMAND} -E echo
# Prints "MYLIB_PRIVATE_CUSTOM_C;EXAMPLE_CUSTOM_C"
"$<TARGET_PROPERTY:mylib,CUSTOM_C>"
# Prints "MYLIB_PRIVATE_CUSTOM_L;EXAMPLE_CUSTOM_L"
"$<TARGET_PROPERTY:mylib,CUSTOM_L>"
# Prints "MYEXE_CUSTOM_C"
"$<TARGET_PROPERTY:myexe,CUSTOM_C>"
# Prints "MYEXE_CUSTOM_L;MYLIB_IFACE_CUSTOM_L;EXAMPLE_CUSTOM_L"
"$<TARGET_PROPERTY:myexe,CUSTOM_L>"
)
π«Ά Compatible Interface Properties π«Ά
Some target properties are required to be compatible between a target and the interface of each dependency. Like, the POSITION_INDEPENDENT_CODE target property may specify a boolean of whether a target should be compiled as position-independent-code β and that has platform-specific consequences, just so you know. 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 get compiled as position-independent-code. lib1 also gets compiled as position-independent-code because that's the default setting for SHARED libraries. β If dependencies have conflicting, non-compatible requirements, then 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 be built as position-independent-code β so a diagnostic gets issued. π
And the lib1 and lib2 requirements are not "compatible" either. One of them requires consumers to be built as position-independent-code, while the other requires consumers are not built as position-independent-code. Because exe2 links to both and they're in conflict, a CMake error message gets 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 it's set, must be either the same β in a boolean sense β as the INTERFACE_POSITION_INDEPENDENT_CODE property of all the transitively specified dependencies on which that property is set. No cap, that's the whole rule. π
Okay so the <pink>compatible interface requirement</pink> vibe can be extended to other properties too β you just name them in the content of the COMPATIBLE_INTERFACE_BOOL target property. Every property you list there has to be compatible between the consuming target and the matching property with an INTERFACE_ prefix from each dependency. Watch:
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 can also join the "compatible interface" computations, bestie. Anything you list in the COMPATIBLE_INTERFACE_STRING property has to be either unspecified or compare to the same string among all transitively specified dependencies. Super useful for making sure multiple incompatible versions of a library don't get 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 says the content gets evaluated numerically, and the maximum number among everything specified gets calculated. It's giving math class but make it build system:
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)
Same energy, opposite direction: COMPATIBLE_INTERFACE_NUMBER_MIN calculates the numeric minimum value for a property from dependencies. β¨
Every calculated "compatible" property value can be read in the consumer at generate-time using generator expressions. Iconic.
Heads up that actually matters: 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. No overlap, no exceptions. π
π΅οΈ Property Origin Debugging
Okay so build specifications can be determined by dependencies, which means the code that creates a target and the code responsible for setting its build specifications might live in totally different places β and that lack of locality can make your code a struggle to reason about. Not the vibe. So cmake(1) ships a debugging facility that prints the origin of the contents of properties that may be determined by dependencies. The debuggable properties 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)
For properties listed in COMPATIBLE_INTERFACE_BOOL or COMPATIBLE_INTERFACE_STRING, the debug output shows you which target was responsible for setting the property, and which other dependencies also defined it. For COMPATIBLE_INTERFACE_NUMBER_MAX and COMPATIBLE_INTERFACE_NUMBER_MIN, the debug output shows the value of the property from each dependency, and whether that value determines the new extreme. So you can see exactly who did what. π
π Build Specification with Generator Expressions
Build specifications can use generator expressions containing content that's conditional or only known at generate-time. That's the whole point, bestie. For example, the calculated "compatible" value of a property can 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 get compiled with -DCONTAINER_SIZE=200. Slay.
The unary TARGET_PROPERTY generator expression and the TARGET_POLICY generator expression are evaluated with the consuming target context. Which means a usage requirement specification may be evaluated differently depending on who's consuming it. Main character energy honestly:
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:CMP0182>:CONSUMER_CMP0182_NEW>
)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1)
cmake_policy(SET CMP0182 NEW)
add_library(shared_lib shared_lib.cpp)
target_link_libraries(shared_lib lib1)
The exe1 executable gets compiled with -DLIB1_WITH_EXE, while the shared_lib shared library gets compiled with -DLIB1_WITH_SHARED_LIB and -DCONSUMER_CMP0182_NEW β because policy CMP0182 is NEW at the point where the shared_lib target is created. Context is everything, fr fr.
The BUILD_INTERFACE expression wraps requirements that 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 that are only used when consumed from a target that's 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 gets 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, go read the cmake-packages(7) manual. π«Ά
π Include Directories and Usage Requirements
Include directories need some special consideration when they're specified as usage requirements and when they're used with generator expressions. Everybody look alive. 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 get interpreted relative to the source directory where the command appears. But β important β relative paths are not allowed in the INTERFACE_INCLUDE_DIRECTORIES of IMPORTED targets. No cap.
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's a replacement marker that expands to the installation prefix when imported by a consuming project. Cute, right?
Include directories usage requirements commonly differ between the build-tree and the install-tree β obviously β and the BUILD_INTERFACE and INSTALL_INTERFACE generator expressions can describe separate usage requirements based on the usage location. Relative paths are allowed within the INSTALL_INTERFACE expression and get 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. And 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)
...and honestly bestie, that is exactly the same energy as appending ${CMAKE_INSTALL_PREFIX}/include to the INTERFACE_INCLUDE_DIRECTORIES of every single installed IMPORTED target when they get generated by install(EXPORT). like, same thing, periodt. π
So when the INTERFACE_INCLUDE_DIRECTORIES of an imported target gets consumed, the entries in that property may get treated as system include directories. and here's the tea: the actual effects of that are toolchain-dependent π« β but one super common effect is that it just omits compiler warnings for headers found in those directories. The SYSTEM property of the installed target is what determines this behavior (peep the EXPORT_NO_SYSTEM property if you wanna know how to modify the installed value for a target). You can also change how consumers interpret the system behavior of consumed imported targets by setting the NO_SYSTEM_FROM_IMPORTED target property on the consumer. slay, options. β¨
And if a binary target is linked transitively to a macOS FRAMEWORK, the Headers directory of the framework is also treated as a usage requirement. same effect as passing the framework directory as an include directory. iconic behavior tbh. π
π« Link Libraries and Generator Expressions
Okay so like build specifications, LINK_LIBRARIES may be specified with generator expression conditions. BUT β and this is the plot twist π β because consumption of usage requirements is based on collection from linked dependencies, there's an extra limitation: the link dependencies have to 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. no loops bestie, we don't do that here π
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)
So in that lil example: 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 that same POSITION_INDEPENDENT_CODE property. which means the dependency graph above contains a cycle. π and cmake(1) will absolutely issue an error message at you. it's giving "caught in 4k".
π¦ Output Artifacts
The buildsystem targets created by the add_library() and add_executable() commands create rules to create binary outputs. and like, 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. however β these expressions do not work for OBJECT libraries π because there's no single file generated by such libraries that's relevant to the expressions. it's giving "there is no one file, it's a vibe".
There are three kinds of output artifacts that may be built by targets, as detailed in the following sections. Their classification differs between DLL platforms and non-DLL platforms. and PSA: 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 theadd_executable()command. - On DLL platforms: the executable file (e.g.
.dll) of a shared library target created by theadd_library()command with theSHAREDoption.
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.
.dllor.so) of a module library target created by theadd_library()command with theMODULEoption. - On non-DLL platforms: the shared library file (e.g.
.soor.dylib) of a shared library target created by theadd_library()command with theSHAREDoption.
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.
.libor.a) of a static library target created by theadd_library()command with theSTATICoption. - On DLL platforms: the import library file (e.g.
.lib) of a shared library target created by theadd_library()command with theSHAREDoption. β οΈ This file is only guaranteed to exist if the library exports at least one unmanaged symbol. like, only then, fr fr. - On DLL platforms: the import library file (e.g.
.lib) of an executable target created by theadd_executable()command when itsENABLE_EXPORTStarget property is set. - On AIX: the linker import file (e.g.
.imp) of an executable target created by theadd_executable()command when itsENABLE_EXPORTStarget property is set. - On macOS: the linker import file (e.g.
.tbd) of a shared library target created by theadd_library()command with theSHAREDoption and when itsENABLE_EXPORTStarget 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. meanwhile add_compile_definitions(), add_compile_options() and include_directories() have a similar function, but they operate at directory scope instead of target scope β for convenience π. so like, same vibes, different address. iykyk. β¨
β¨ BUILD CONFIGURATIONS β¨
Okay bestie, this one matters so much β like, pay attention π
Configurations are literally just "what kind of build am I doing rn" β think Release or Debug. Iconic. But the way you actually specify it depends on which type of generator you're using, and this is where people get it twisted.
For single configuration generators β like Makefile Generators and Ninja β the configuration gets locked in at configure time via the CMAKE_BUILD_TYPE variable.
For multi-configuration generators β like Visual Studio, Xcode, and Ninja Multi-Config β the user picks the configuration at build time, and CMAKE_BUILD_TYPE is straight-up ignored. π In this multi-config case, the set of available configurations is specified at configure time by the CMAKE_CONFIGURATION_TYPES variable, but the actual configuration being used can't be known until the build stage.
This difference is so often misunderstood and it leads to β¨problematicβ¨ code like the following, no cap:
# 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()
Instead, bestie, use generator expressions to handle configuration-specific logic correctly β regardless of which generator you're rocking. Like this:
# Works correctly for both single and multi-config generators
target_compile_definitions(exe1 PRIVATE
$<$<CONFIG:Debug>:DEBUG_BUILD>
)
And when IMPORTED targets are in the mix, the content of MAP_IMPORTED_CONFIG_DEBUG (which is the MAP_IMPORTED_CONFIG_<CONFIG> property, iykyk) also gets accounted for by that $<CONFIG:Debug> expression. Slay. π
Case Sensitivity π
Okay so CMAKE_BUILD_TYPE and CMAKE_CONFIGURATION_TYPES are literally just like every other variable β any string comparisons you make with their values are case-sensitive. And the $<CONFIG> generator expression preserves the casing of the configuration exactly as set by the user or by CMake's 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()
But here's the plot twist π¦ β CMake itself treats the configuration type case-insensitively when it's using it internally in places that modify behavior based on the configuration. So for example, the $<CONFIG:Debug> generator expression evaluates to 1 for a configuration of not only Debug, but also DEBUG, debug, or even DeBuG. Literally unbothered.
Which means you can write configuration types in CMAKE_BUILD_TYPE and CMAKE_CONFIGURATION_TYPES with any mixture of upper and lowercase β though there are strong conventions (see the next section π). But if you absolutely must test the value in string comparisons, always convert the value to upper or lowercase first and adjust the test accordingly. Periodt. π
Default And Custom Configurations π
By default, CMake defines a bunch of standard configurations:
DebugReleaseRelWithDebInfoMinSizeRel
In multi-config generators, the CMAKE_CONFIGURATION_TYPES variable will be populated with (potentially a subset of) that list above by default, unless the project or the user overrides it. And the actual configuration used is picked 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 standard configurations above β it'll instead be an empty string. And a super common misunderstanding is thinking that empty string is the same as Debug. It is not, bestie, that is simply not the case π. Users should always explicitly specify the build type instead to avoid this very common problem.
The standard configuration types above provide reasonable behavior on most platforms, but they can absolutely be extended to provide other types β main character energy β¨. 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. So when you're defining a custom configuration type, make sure these variables are set appropriately β typically as cache variables. π
π PSEUDO TARGETS π
okay so plot twist: some target types are literally not outputs of the buildsystem at all. they're just inputs β think external dependencies, aliases, or other non-build artifacts. we call these pseudo targets, and the gag is that they're not represented in the generated buildsystem. they're vibes and metadata only, bestie π
π¦ Imported Targets π¦
an IMPORTED target = a pre-existing dependency. lowkey the whole point. usually these get defined by an upstream package, and you should treat them as immutable β like, don't touch, they're not yours β¨
but the second you've declared an IMPORTED target, you can still adjust its target properties with the usual suspects: target_compile_definitions(), target_include_directories(), target_compile_options(), or target_link_libraries() β literally just like any other regular target. no cap.
IMPORTED targets can have the same usage requirement properties populated as binary targets, like:
INTERFACE_INCLUDE_DIRECTORIESINTERFACE_COMPILE_DEFINITIONSINTERFACE_COMPILE_OPTIONSINTERFACE_LINK_LIBRARIESINTERFACE_POSITION_INDEPENDENT_CODE
you can also read the LOCATION from an IMPORTED target, though honestly there's rarely a reason to. and commands like add_custom_command() can transparently use an IMPORTED EXECUTABLE target as a COMMAND executable. iconic behavior π«Ά
now the scope tea β 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. yeah, it's giving cmake variable scope β same energy.
you can also define a GLOBAL IMPORTED target, which is accessible globally in the buildsystem. global girlies rise π
for more on creating packages with IMPORTED targets, go read the cmake-packages(7) manual. iykyk.
πΈ Alias Targets πΈ
an ALIAS target is a name that may be used interchangeably with a binary target name in read-only contexts. that's the whole bit, and it slays.
the primary use-case is, like, example or unit test executables that accompany a library β which may be part of the same buildsystem or built separately based on user configuration. flexible queen π
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)
then 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 it's 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)
important caveat bestie: ALIAS targets are not mutable, installable or exportable. they are entirely local to the buildsystem description. periodt.
you can test whether a name 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's giving ghost β¨
it may specify usage requirements, compatible interface properties, and custom transitive properties. only the INTERFACE modes of these commands may be used with INTERFACE libraries:
target_include_directories()target_compile_definitions()target_compile_options()target_sources()target_link_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 doesn't compile sources, but it may contain custom commands to generate other sources. and bonus: IDEs will show the source files as part of the target for interactive reading and editing. cute π
the 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. those usage requirements get consumed and used when compiling, but have no effect on linking. noted π
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. the way that works?? obsessed π«Ά
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 PUBLIC
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. and the install destination automatically becomes an include directory that is a usage requirement for consumers. slay π
π Properties Allowed on Interface Libraries π
since CMake 3.19, interface libraries allow setting or reading target properties with any name, just like other target kinds always have. finally, equality π
prior to CMake 3.19, interface libraries only allowed setting or reading target properties with a limited set of names:
- properties named with an
INTERFACE_prefix, either builtin usage requirements, or custom names. - built-in properties named with a
COMPATIBLE_INTERFACE_prefix (compatible interface properties). - built-in properties
NAME,EXPORT_NAME,EXPORT_PROPERTIES,MANUALLY_ADDED_DEPENDENCIES,IMPORTED,IMPORTED_LIBNAME_<CONFIG>, andMAP_IMPORTED_CONFIG_<CONFIG>. - added in version 3.11: properties named with a leading underscore (
_) or lowercase ASCII character.
so yeah, if you're on old CMake and your property name doesn't fit that list, it's a no from her π
π Copyright π
2000-2026 Kitware, Inc. and Contributors
and that's a wrap on the whole page, bestie!! π you just read CMAKE-BUILDSYSTEM(7) β source/version 4.4.5, dated Oct 28, 2026 β go build something iconic with it. mwah πβ¨π¦π
π¦ where this page comes from
- arch rolling: cmake 4.4.5-1 Β· BSD-3-Clause
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms