CMAKE-MODULES(7)

๐Ÿ’– NAME ๐Ÿ’–

okay bestie, welcome to cmake-modules(7) โ€” the CMake Modules Reference โ€” and this is the part where we get into the utility modules that ship with CMake itself. โœจ

The modules listed here are part of the CMake distribution. Projects may provide further modules; their location(s) can be specified in the CMAKE_MODULE_PATH variable.


โœจ UTILITY MODULES โœจ

These modules are loaded using the include() command.

๐Ÿค– AndroidTestUtilities ๐Ÿค–

Added in version 3.7.

This module provides a command to create a test that pushes data needed for testing an Android device behavior onto a connected Android device. ๐Ÿซถ

Load this module in a CMake project with:

include(AndroidTestUtilities)

๐Ÿ› ๏ธ Commands ๐Ÿ› ๏ธ

This module provides the following command:

android_add_test_data โ€” Creates a test that automatically loads specified data onto an Android device:

android_add_test_data(
  <test-name>
  [FILES <files>...]
  [FILES_DEST <device-dir>]
  [LIBS <libs>...]
  [LIBS_DEST <device-dir>]
  DEVICE_OBJECT_STORE <device-dir>
  DEVICE_TEST_DIR <device-dir>
  [NO_LINK_REGEX <regexes>...]
)

This command accepts files and libraries needed to run project-specific tests as well as separate destinations for each. It will create a test that loads the files into a device object store and link to them from the specified destination. The files are only uploaded if they are not already in the object store. ๐Ÿ’…

On the host operating system, files and libraries are copied at build time. For on-device testing, the files are loaded onto the device by the manufactured test at run time. ๐Ÿฆ‹

This command accepts the following named parameters:

  • FILES <files>... โ€” Zero or more files needed for testing.
  • FILES_DEST <device-dir> โ€” Absolute path where the data files are expected to be.
  • LIBS <libs>... โ€” Zero or more libraries needed for testing.
  • LIBS_DEST <device-dir> โ€” Absolute path where the libraries are expected to be.
  • DEVICE_OBJECT_STORE <device-dir> โ€” Absolute path to the on-device location where the data files are initially stored.
  • DEVICE_TEST_DIR <device-dir> โ€” Absolute path to the root directory of the on-device test location.
  • NO_LINK_REGEX <regexes>... โ€” A list of regular expression patterns matching file names to be copied from the object store to the test directory, instead of being symlinked.

๐ŸŒธ Examples ๐ŸŒธ

The following example shows how to use this module to create a test named example_setup_test that prepares data during the build phase. This test can then be run using ctest(1) to load the data onto the Android device. ๐Ÿ˜ญ๐Ÿ’–

CMakeLists.txt

include(AndroidTestUtilities)

android_add_test_data(
  example_setup_test
  FILES data/protobuffer.p data/file.txt
  LIBS libs/library_1 libs/library_2
  DEVICE_OBJECT_STORE "/sdcard/.ExternalData/SHA"
  DEVICE_TEST_DIR "/data/local/tests/example"
)

๐ŸŽ€ BundleUtilities ๐ŸŽ€

This module provides utility commands for assembling standalone, bundle-style applications with CMake, such as macOS .app bundles or similar directory-based application bundles on other operating systems. periodt. ๐Ÿ“

Load this module in a CMake installation with:

include(BundleUtilities)
Note: Do not use this module at configure time (from CMakeLists.txt). Instead, include it and invoke its commands from an install(CODE) or install(SCRIPT). ๐Ÿšจ

๐Ÿงฐ Commands ๐Ÿงฐ

This module provides the following commands:

  • fixup_bundle()
  • copy_and_fixup_bundle()
  • verify_app()
  • get_bundle_main_executable()
  • get_dotapp_dir()
  • get_bundle_and_executable()
  • get_bundle_all_executables()
  • get_item_key()
  • get_item_rpaths()
  • clear_bundle_keys()
  • set_bundle_key_values()
  • get_bundle_keys()
  • copy_resolved_item_into_bundle()
  • copy_resolved_framework_into_bundle()
  • fixup_bundle_item()
  • verify_bundle_prerequisites()
  • verify_bundle_symlinks()

fixup_bundle โ€” Prepares a bundle for distribution by fixing up its internal dependencies:

fixup_bundle(<app> <libs> <dirs> [IGNORE_ITEM <files>...])

This command modifies the <app> bundle in-place to make it self-contained and portable, so that it can be drag-n-drop copied to another machine and run there, assuming all of the system libraries are compatible. ๐Ÿ‘‘

This command collects all dependencies (keys) for the executables and libraries in the bundle. For each dependency, it copies the required files into the bundle and adjusts them according to their own prerequisites. Once complete, it clears the collected keys and invokes the verify_app() command to ensure the final bundle is truly standalone. ๐Ÿ”ฅ

The arguments are:

  • <app> โ€” The path to the bundle to fix. This can be an .app directory or direct path to an executable.
  • <libs> โ€” A list of libraries that must be fixed up, but that cannot be automatically determined by the otool output analysis (i.e. plugins). If plugins are passed to this command as this parameter, they should be installed or copied into the bundle before calling this command.
  • <dirs> โ€” A list of paths where libraries might be found. These paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib, etc.
  • IGNORE_ITEM <files>... โ€” Added in version 3.6. Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe").

copy_and_fixup_bundle โ€” Copies the bundle and fixes up the new copied bundle in-place:

copy_and_fixup_bundle(<src> <dst> <libs> <dirs>)

This command makes a copy of the bundle <src> at location <dst> and then fixes up the new copied bundle in-place at <dst>. ๐Ÿ’ซ

The arguments are:

  • <src> โ€” The directory of the bundle being copied.
  • <dst> โ€” The destination directory of the bundle copy.
  • <libs> โ€” A list of libraries that must be fixed up, but that cannot be automatically determined by the otool output analysis (i.e. plugins). If plugins are passed to this command as this parameter, they should be installed or copied into the bundle before calling this command.
  • <dirs> โ€” A list of paths where libraries might be found. These paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib, etc.

verify_app โ€” Verifies that an application bundle appears valid based on running analysis tools on it:

verify_app(<app> [IGNORE_ITEM <files>...])

If the application fails verification, a message(FATAL_ERROR) is issued, halting the installation process. ๐Ÿ’€

The arguments are:

  • <app> โ€” The path to the application to verify. This can be a .app directory or a standalone executable.
  • IGNORE_ITEM <files>... โ€” Added in version 3.6. Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe").

get_bundle_main_executable โ€” Retrieves the main executable within a given application bundle:

get_bundle_main_executable(<bundle> <result-var>)

The result is stored in a <result-var> variable and will contain a full path name of the bundle's main executable file, or an error: prefixed string if it could not be determined. ๐ŸŽฏ

get_dotapp_dir โ€” Locates the enclosing .app directory for the given executable:

get_dotapp_dir(<exe> <dotapp-dir-var>)

This command retrieves the nearest parent dir whose name ends with .app given the full path to an executable and stores it to the <dotapp-dir-var> variable. If there is no such parent dir, then it simply retrieves the directory containing the executable. ๐ŸŒˆ

The retrieved directory may or may not exist.

get_bundle_and_executable โ€” Takes either a .app directory name or the name of an executable nested inside a .app directory and retrieves the path to the .app directory and the path to its main executable:

get_bundle_and_executable(<app> <bundle-var> <executable-var> <valid-var>)

The arguments are:

  • <app> โ€” The name of the application being processed.
  • <bundle-var> โ€” Variable name in which to store the resulting path to the .app directory. In case of any error, this variable will contain an error message prefixed with string error:.
  • <executable-var> โ€” Variable name in which to store the resulting main executable. In case of any error, this variable will contain an error message prefixed with string error:.
  • <valid-var> โ€” Variable name in which the boolean result is stored whether this command was successful or not.

get_bundle_all_executables โ€” Gets all executables of a given bundle:

get_bundle_all_executables(<bundle> <exes-var>)

This command scans <bundle> bundle recursively for all executable files and stores them into a variable <exes-var>. ๐Ÿงš

get_item_key โ€” Generates a unique key for the given item:

get_item_key(<item> <key-var>)

Given <item> file name, this command generates <key-var> key that should be unique considering the set of libraries that need copying or fixing up to make a bundle standalone. This is essentially the file name including extension with . replaced by _. ๐ŸŽ€

This key is used as a prefix for CMake variables so that a set of variables can be associated with a given item based on its key.

get_item_rpaths โ€” Gets RPATHS (run-time search paths) for the given item:

get_item_rpaths(<item> <rpaths-var>)

Okay so this command gets RPATHS of the <item> file name and stores them to the variable with provided name <rpaths-var>. No cap, itโ€™s literally just โ€œgimme those run paths and put โ€™em in a variable.โ€ ๐Ÿ’…

โœจ clear_bundle_keys โœจ

Clears all variables associated with keys:

clear_bundle_keys(<keys-var>)

This command loops over the <keys-var> list of keys, clearing all the variables associated with each key. After the loop, it clears the list of keys itself. This command should be called after the get_bundle_keys() command, when done working with a list of keys. Think of it as the cleanup era: the keys had their moment, now theyโ€™re getting cleared. ๐Ÿงนโœจ

๐ŸŽ€ set_bundle_key_values ๐ŸŽ€

Adds a key to the list of keys:

set_bundle_key_values(
  <keys-var>
  <context>
  <item>
  <exepath>
  <dirs>
  <copyflag>
  [<rpaths>]
)

This command adds the <keys-var> key to the list (if necessary) for the given item. If added, also set all the variables associated with that key. Itโ€™s giving โ€œset the whole vibe for this key,โ€ honestly. ๐Ÿ’–

The arguments are:

  • <keys-var> โ€” Variable name holding the name of the key to be added to the list for the given item.
  • <context> โ€” The path to the top level loading path used for @loader_path replacement on Apple operating systems. When resolving item, @loader_path references will be resolved relative to the directory of the given context value (presumably another library).
  • <item> โ€” The item for which to add the key.
  • <exepath> โ€” The path to the top level executable used for @executable_path replacement on Apple operating systems.
  • <dirs> โ€” A list of paths where libraries might be found. These paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib, etc.
  • <copyflag> โ€” If set to 1 library symlink structure will be preserved.
  • <rpaths> โ€” Optional run-time search paths for an executable file or library to help find files.

๐Ÿฆ‹ get_bundle_keys ๐Ÿฆ‹

Gets bundle keys:

get_bundle_keys(<app> <libs> <dirs> <keys-var> [IGNORE_ITEM <files>...])

This command loops over all the executable and library files within <app> bundle (and given as extra <libs>) and accumulate a list of keys representing them. It sets values associated with each key such that they can be looped over all of them and copies prerequisite libs into the bundle and then does appropriate install_name_tool fixups. Itโ€™s the main-character command of the bundle-fixing saga, fr fr. ๐Ÿ‘‘

The arguments are:

  • <app> โ€” The path to the bundle to fix. This can be an .app directory or direct path to an executable.
  • <libs> โ€” A list of libraries that must be fixed up, but that cannot be automatically determined by the otool output analysis (i.e. plugins). If plugins are passed to this command as this parameter, they should be installed or copied into the bundle before calling this command.
  • <dirs> โ€” A list of paths where libraries might be found. These paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib, etc.
  • <keys-var> โ€” Variable name holding a list of keys that represent all executable and library files within the bundle.
  • IGNORE_ITEM <files>... โ€” Added in version 3.6. Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe"). These files get the โ€œnot invited to the fixup partyโ€ treatment. ๐Ÿ™ˆ

๐ŸŒธ copy_resolved_item_into_bundle ๐ŸŒธ

Copies a resolved item into the bundle if necessary:

copy_resolved_item_into_bundle(<resolved-item> <resolved-embedded-item>)

Copy is not necessary, if the <resolved-item> is โ€œthe same asโ€ the <resolved-embedded-item>. Like, if itโ€™s already the same item, weโ€™re not doing extra work for no reason. Periodt. ๐Ÿ’…

๐ŸŒˆ copy_resolved_framework_into_bundle ๐ŸŒˆ

Copies a resolved framework into the bundle if necessary:

copy_resolved_framework_into_bundle(<resolved-item> <resolved-embedded-item>)

Copy is not necessary, if the <resolved-item> is โ€œthe same asโ€ the <resolved-embedded-item>.

The following variables can be set before invoking this command:

  • BU_COPY_FULL_FRAMEWORK_CONTENTS โ€” By default, this variable is not set. If full frameworks should be embedded in the bundles, set this variable to boolean true before calling the fixup_bundle() command. By default, this command copies the framework dylib itself plus the framework Resources directory.

๐Ÿ”ฅ fixup_bundle_item ๐Ÿ”ฅ

Fixes up bundle item:

fixup_bundle_item(<resolved-embedded-item> <exepath> <dirs>)

This command gets the direct/non-system prerequisites of the <resolved-embedded-item> and for each prerequisite, it changes the way it is referenced to the value of the _EMBEDDED_ITEM keyed variable for that prerequisite. Most likely changing to an @executable_path style reference. Itโ€™s literally rerouting the references so everything knows where home is. ๐Ÿ โœจ

This command requires that the <resolved-embedded-item> be inside the bundle already. In other words, if plugins are passed to fixup_bundle() command as its <libs> parameter, they should be installed or copied into the bundle before calling the fixup_bundle() command. No sneaking in at the last second, bestie. ๐Ÿซถ

Also, it changes the id of the item being fixed up to its own _EMBEDDED_ITEM value.

Changes are accumulated in a local variable and one call is made to install_name_tool command-line tool at the end of this command with all the changes at once. Efficiency slay. ๐Ÿ’…

The arguments are:

  • <resolved-embedded-item> โ€” The bundle item to be fixed up.
  • <exepath> โ€” The path to the top level executable used for @executable_path replacement on Apple operating systems.
  • <dirs> โ€” A list of paths where libraries might be found. These paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib, etc.

The following variables can be set before invoking this command:

  • BU_CHMOD_BUNDLE_ITEMS โ€” If this variable is set to boolean true value then bundle items will be marked writable before install_name_tool tool tries to change them.

๐Ÿ’œ verify_bundle_prerequisites ๐Ÿ’œ

Verifies that the sum of all prerequisites of all files inside the bundle are contained within the bundle or are system libraries, presumed to exist everywhere:

verify_bundle_prerequisites(
  <bundle>
  <result-var>
  <info-var>
  [IGNORE_ITEM <files>...]
)

The arguments are:

  • <bundle> โ€” Name of the bundle being verified.
  • <result-var> โ€” Name of the variable in which to store a boolean result of whether a verification was successful.
  • <info-var> โ€” Name of the variable holding any informational messages produced by the verification.
  • IGNORE_ITEM <files>... โ€” Added in version 3.6. Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe"). Same energy as before: these files are excused from the vibe check. ๐Ÿ˜Œ

Verifies that any symlinks found in the specified bundle point to other files that are already also in the bundle:

verify_bundle_symlinks(<bundle> <result-var> <info-var>)

Anything that points to an external file causes this command to fail the verification. So if a symlink is trying to link to somebody outside the bundle, itโ€™s a no from the verification committee. ๐Ÿ’€

The arguments are:

  • <bundle> โ€” Name of the bundle being verified.
  • <result-var> โ€” Name of the variable in which to store a boolean result of whether a verification was successful.
  • <info-var> โ€” Name of the variable holding any informational messages produced by the verification.

๐Ÿงš Examples ๐Ÿงš

Using this module inside the installation code that is executed at the installation phase:

CMakeLists.txt

# ...

install(CODE "
  include(BundleUtilities)
  set(BU_CHMOD_BUNDLE_ITEMS TRUE)
  fixup_bundle(
    \"${fixup_exe}\"
    \"${plugins}\"
    \"${bin_dir};${library_dir};${binary_dir}\"
  )
")

๐ŸŒŸ CheckCCompilerFlag ๐ŸŒŸ

This module provides a command to check whether the C compiler supports a given flag. Itโ€™s giving โ€œdoes my compiler accept this flag or is it gonna be dramatic about it?โ€ energy. ๐Ÿซถ

Load this module in a CMake project with:

include(CheckCCompilerFlag)

โœจ Commands โœจ

This module provides the following command:

check_c_compiler_flag

Checks once whether the C compiler supports a given flag:

check_c_compiler_flag(<flag> <variable>)

This command checks once that the <flag> is accepted by the C compiler without producing a diagnostic message. Multiple flags can be specified in one argument as a string using a semicolon-separated list <#cmake-language-lists>. Cute little list-in-one-argument moment. ๐ŸŽ€

The result of the check is stored in the internal cache variable specified by <variable>, with boolean true for success and boolean false for failure.

A successful result only indicates that the compiler did not report an error when given the flag. Whether the flag has any effect, or the intended one, is outside the scope of this module. So likeโ€ฆ it passed the vibe check, but that doesnโ€™t mean itโ€™s doing the thing you think itโ€™s doing. ๐Ÿ‘€

Note: Since the underlying try_compile() <#command:try_compile> command also uses flags from variables like CMAKE_<LANG>_FLAGS <#variable:CMAKE_<LANG>_FLAGS>, unknown or unsupported flags in those variables may result in a false negative for this check. So if the check is acting sus, check the surrounding flags too, iykyk. ๐Ÿ˜ญ

๐ŸŒธ Variables Affecting the Check ๐ŸŒธ

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” extra flags you wanna hand the compiler, written as a space-separated string ๐Ÿ’…. A semicolon-separated list will not work here, bestie, I'm so serious. And heads up: the contents of CMAKE_<LANG>_FLAGS and its config-specific sibling CMAKE_<LANG>_FLAGS_<CONFIG> get auto-prepended to the compiler command before whatever you put in this variable. Order matters, always does โœจ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one shaped like -DFOO or -DFOO=bar ๐ŸŽ€. Oh and a definition for the name given by the result variable argument of the check command gets added automatically too, no need to ask.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler ๐ŸŒธ. And likeโ€ฆ these will be the only header search paths used. The contents of the INCLUDE_DIRECTORIES directory property? Ignored. Fully ghosted ๐Ÿ’€
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (peep try_compile() for the deets).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command ๐Ÿ”ฅ. These can be plain old system library names, or they can be Imported Targets (again, try_compile() has the full story).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details) ๐Ÿฆ‹.
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all the status messages tied to the check get suppressed ๐Ÿคซ. Silence is golden, periodt.
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” under the hood the check uses the try_compile() command, and this variable controls what type of target it creates ๐Ÿ‘‘. Set it to EXECUTABLE (that's the default) and the check compiles and links the test source code as an executable program. Set it to STATIC_LIBRARY and the test source gets compiled but not linked. That's it, that's the whole vibe.

Examples

Okay so here's the moment where it all clicks ๐Ÿ’–. This example shows how to use the module to check support for the C compiler flag -fno-optimize-strlen โ€” which, fun fact, disables optimizations related to the strlen() C function in GCC and Clang compilers. The result lands in the internal cache variable HAVE_FNO_OPTIMIZE_STRLEN, and then the flag gets conditionally enabled with the target_compile_options() command. The $<COMPILE_LANGUAGE:...> generator expression is the little icon that makes sure the flag only hits C source files ๐ŸŽฏ

include(CheckCCompilerFlag)
check_c_compiler_flag(-fno-optimize-strlen HAVE_FNO_OPTIMIZE_STRLEN)

if(HAVE_FNO_OPTIMIZE_STRLEN)
  target_compile_options(
    example
    PRIVATE $<$<COMPILE_LANGUAGE:C>:-fno-optimize-strlen>
  )
endif()

See Also

  • The CheckCompilerFlag module ๐Ÿ‘€ โ€” it's the more general command for checking whether a compiler flag is supported. Like, if you want the glow-up version.

CheckCompilerFlag

Added in version 3.19. โœจ

This module gives you a command to check whether the compiler supports a given flag. That's it. That's the whole module. And honestly? Iconic.

Load it into your CMake project like this:

include(CheckCompilerFlag)

Commands

Only one command in the bag:

check_compiler_flag

Checks once whether the compiler supports a given flag:

check_compiler_flag(<lang> <flag> <variable>)

This command checks once that the <flag> is accepted by the <lang> compiler without producing a diagnostic message ๐Ÿฉบ. The result of the check is stored in the internal cache variable named by <variable>. One and done, no re-runs.

The arguments are:

  • <lang> โ€” the language of the compiler used for the check. Supported languages are: C, CXX, CUDA, Fortran, HIP, ISPC, OBJC, and OBJCXX, and Swift. So many options, so little time ๐Ÿ’œ
    • Added in version 3.21: Support for HIP language.
    • Added in version 3.26: Support for Swift language.
  • <flag> โ€” the compiler flag(s) to check ๐Ÿ”ฅ. You can drop multiple flags into one argument as a string using a semicolon-separated list. Slay.
  • <variable> โ€” variable name of an internal cache variable to store the result of the check, with boolean true for success and boolean false for failure ๐Ÿ’ซ. Binary. No nuance. We love a clear answer.

A successful result only indicates that the compiler did not report an error when given the flag. Whether the flag actually does anything, or does the thing you intended it to do โ€” that's outside the scope of this module, babe ๐Ÿ™ˆ. It just checks vibes, not results.

Note: Since the underlying try_compile() command also uses flags from variables like CMAKE_<LANG>_FLAGS, unknown or unsupported flags chilling in those variables may result in a false negative for this check ๐Ÿ˜ญ. Not the flag's fault, not yours, just how the guts work.

Variables Affecting the Check

Set any of these before calling the command and you change how the check runs ๐ŸŽ€

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler ๐Ÿ’…. A semicolon-separated list will not work, I said what I said. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar โœจ. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler ๐Ÿฆ‹. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. Sorry to that property.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command ๐Ÿ‘‘. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details) ๐ŸŒˆ.
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed ๐Ÿค.
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” internally, the try_compile() command is used to perform the check, and this variable controls the type of target it creates ๐ŸŽฏ. If this variable is set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. If set to STATIC_LIBRARY, the test source code is compiled but not linked.

Examples

Same energy, different command ๐Ÿ’–. This one demonstrates using the module to check support for the C compiler flag -fno-optimize-strlen, the flag that disables optimizations related to the strlen() C function in GCC and Clang compilers. The result of the check is stored in the internal cache variable HAVE_FNO_OPTIMIZE_STRLEN, and the flag is conditionally enabled using the target_compile_options() command. And the $<COMPILE_LANGUAGE:...> generator expression makes sure the flag is added only to C source files ๐ŸŒธ

include(CheckCompilerFlag)
check_compiler_flag(C -fno-optimize-strlen HAVE_FNO_OPTIMIZE_STRLEN)

if(HAVE_FNO_OPTIMIZE_STRLEN)
  target_compile_options(
    example
    PRIVATE $<$<COMPILE_LANGUAGE:C>:-fno-optimize-strlen>
  )
endif()

See Also

  • The CheckLinkerFlag module ๐Ÿซถ โ€” for checking whether a linker flag is supported by the compiler. Different body part, same energy.

CheckCSourceCompiles

This module provides a command to check whether a C source can be built ๐Ÿ› ๏ธ. Like, will it actually compile? Let's find out together.

Load this module in a CMake project with:

include(CheckCSourceCompiles)

Commands

This module provides the following command:

check_c_source_compiles

Checks once whether the given C source code can be built:

check_c_source_compiles(<code> <variable> [FAIL_REGEX <regexes>...])

This command checks once that the source supplied in <code> can be compiled (and linked into an executable) ๐Ÿ”ฅ. The result of the check is stored in the internal cache variable specified by <variable>.

The arguments are:

  • <code> โ€” the actual C source code you want checked. Heads up: this has to be a whole entire program, like exactly what'd be sitting in a file containing the body block. Every symbol you use in there is expected to be declared the normal way in its corresponding headers, so don't get cute and skip your includes ๐Ÿ’…
  • <variable> โ€” the name of an internal cache variable where the result gets stashed. true if the check slayed, false if it flopped.
  • FAIL_REGEX <regexes>... โ€” if you toss in one or more regular expression patterns here, then failure gets determined by checking whether anything in the compiler output matches any of the regexes you specified. Basically: if the output smells like one of these patterns, the check is a fail ๐Ÿ™ˆ

โœจ Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to hand to the compiler. Important bestie: a semicolon-separated list will not work here, the semicolons just vibe uselessly. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable. So your flags are literally not first in line, iykyk.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of them looking like -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically, so you don't gotta do that yourself ๐Ÿซถ
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. And listen: these will be the only header search paths used. The contents of the INCLUDE_DIRECTORIES directory property get straight up ignored. Not consulted. Not even a little. ๐Ÿ˜ญ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. Silence. Peace. No crumbs of output ๐Ÿ’€
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” so internally, the try_compile() command is what actually performs the check, and this variable controls the type of target it creates. If this variable is set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. If set to STATIC_LIBRARY, the test source code is compiled but not linked. Different energy entirely.

๐ŸŒธ Examples

Checking whether C source code containing an SSE2 intrinsic can be compiled and linked:

include(CheckCSourceCompiles)

check_c_source_compiles([[
  #include <emmintrin.h>
  int main(void)
  {
    __m128d a = _mm_setzero_pd();
    (void)a;
    return 0;
  }
]] PROJECT_HAVE_SSE2_INTRINSICS)

๐Ÿ” See Also

  • The CheckSourceCompiles module for a more general command to check whether source can be built.
  • The CheckSourceRuns module to check whether source can be built and run.

๐ŸŽ€ CheckCSourceRuns

This module provides a command to check whether a C source can be built and run. Two steps. Both required. No shortcuts ๐Ÿ‘‘

Load this module in a CMake project with:

include(CheckCSourceRuns)

โœจ Commands

This module provides the following command:

check_c_source_runs ๐Ÿฆ‹

Checks once whether the given C source code compiles and links into an executable that can subsequently be run:

check_c_source_runs(<code> <variable>)

The C source supplied in <code> must contain at least a main() function. Non-negotiable, bestie. The result of the check is stored in the internal cache variable specified by <variable>. If the code builds and runs with exit code 0, success is indicated by a boolean true value. Failure to build or run is indicated by a boolean false value, such as an empty string or an error message ๐Ÿซ 

โœจ Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. A semicolon-separated list will not work, bestie, I'm serious. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed ๐Ÿคซ

๐ŸŒธ Examples

The following example demonstrates how to use this module to check whether the C source code is supported and operational at runtime. The result of the check is stored in the internal cache variable HAVE_NORETURN.

include(CheckCSourceRuns)

check_c_source_runs([[
  #include <stdlib.h>
  #include <stdnoreturn.h>
  noreturn void f(){ exit(0); }
  int main(void) { f(); return 1; }
]] HAVE_NORETURN)

๐Ÿ” See Also

  • The CheckSourceRuns module for a more general command syntax.
  • The CheckSourceCompiles module to check whether a source code can be built.

๐Ÿ’œ CheckCXXCompilerFlag

This module provides a command to check whether the C++ compiler supports a given flag. Like, does your compiler even know her? ๐ŸŽค

Load this module in a CMake project with:

include(CheckCXXCompilerFlag)

โœจ Commands

This module provides the following command:

check_cxx_compiler_flag โญ

Checks once whether the C++ compiler supports a given flag:

check_cxx_compiler_flag(<flag> <variable>)

This command checks once that the <flag> is accepted by the CXX compiler without producing a diagnostic message. Multiple flags can be specified in one argument as a string using a semicolon-separated list ๐Ÿซถ

The result of the check is stored in the internal cache variable specified by <variable>, with boolean true for success and boolean false for failure.

Fr fr, a successful result only indicates that the compiler did not report an error when given the flag. Whether the flag has any effect โ€” or the intended one โ€” is outside the scope of this module. We checked if she showed up. We did not check if she did anything ๐Ÿ’€
Note: Since the underlying try_compile() command also uses flags from variables like CMAKE_<LANG>_FLAGS, unknown or unsupported flags sitting in those variables may result in a false negative for this check. So your check can fail for reasons that have nothing to do with the flag you asked about. Rude, honestly ๐Ÿ˜ญ

โœจ Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one shaped like -DFOO or -DFOO=bar. ๐Ÿ’… and bestie, heads up: a definition for the name you passed as the result variable argument of the check command gets added automatically too. no cap.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to hand over to the compiler. ๐Ÿฆ‹ and here's the slay-but-also-be-careful part: these are the only header search paths used. the contents of the INCLUDE_DIRECTORIES directory property get ignored. like, fully ignored. ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. a semicolon-separated list of options to add to the link command (go peek at try_compile() for the further details, iykyk). ๐Ÿ”ฅ
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. these can be plain old names of system libraries, or they can be Imported Targets (again, try_compile() has the further details). ๐Ÿ‘‘
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. a semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details). ๐ŸŽ€
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. if this variable evaluates to a boolean true value, all status messages associated with the check get suppressed. silence. iconic. ๐Ÿคซ
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” internally the try_compile() command is what actually performs the check, and this variable controls the type of target it creates. if it's set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. if it's set to STATIC_LIBRARY, the test source code gets compiled but not linked. ๐Ÿงš

โœจ Examples

okay so the following example demonstrates how to use this module to check the C++ compiler flag -fsycl. ๐Ÿซถ the result of the check gets stored in the internal cache variable HAVE_FSYCL_FLAG, and the flag is conditionally enabled using the target_compile_options() command. and the $<COMPILE_LANGUAGE:...> generator expression is what ensures the flag is added only to CXX source files. so clean.

include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-fsycl HAVE_FSYCL_FLAG)

if(HAVE_FSYCL_FLAG)
  target_compile_options(
    example
    PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-fsycl>
  )
endif()

๐Ÿ’œ See Also

  • the CheckCompilerFlag module, for a more general command to check whether a compiler flag is supported. ๐ŸŒˆ

๐ŸŒธ CheckCXXSourceCompiles ๐ŸŒธ

this module provides a command to check whether a C++ source can be built. ๐ŸŽ€

load this module in a CMake project with:

include(CheckCXXSourceCompiles)

Commands

this module provides the following command:

check_cxx_source_compiles โ€” checks once whether the given C++ source code can be built: ๐Ÿ’…

check_cxx_source_compiles(<code> <variable> [FAIL_REGEX <regexes>...])

this command checks once that the source supplied in <code> can be compiled (and linked into an executable, fr fr). the result of the check gets stored in the internal cache variable specified by <variable>. ๐Ÿฆ‹

the arguments are:

  • <code> โ€” C++ source code to check. this must be an entire program, as written in a file containing the body block. all symbols used in the source code are expected to be declared as usual in their corresponding headers. no shortcuts, bestie. ๐Ÿ“
  • <variable> โ€” variable name of an internal cache variable to store the result of the check, with boolean true for success and boolean false for failure. ๐Ÿ‘‘
  • FAIL_REGEX <regexes>... โ€” if one or more regular expression patterns are provided, then failure is determined by checking if anything in the compiler output matches any of the specified regular expressions. ๐Ÿ’€

Variables Affecting the Check

the following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. โš ๏ธ a semicolon-separated list will not work, periodt. the contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable. ๐Ÿ”ฅ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. a definition for the name specified by the result variable argument of the check command is also added automatically. ๐Ÿ’…
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. these will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. a semicolon-separated list of options to add to the link command (see try_compile() for further details). โœจ
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. these can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details). ๐Ÿ‘‘
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. a semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details). ๐ŸŽ€
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. if this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. ๐Ÿคซ
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” internally, the try_compile() command is used to perform the check, and this variable controls the type of target it creates. if this variable is set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. if set to STATIC_LIBRARY, the test source code is compiled but not linked. ๐Ÿงš

โœจ Examples

the following example demonstrates how to check whether the C++ compiler supports a specific language feature. in this case, the check verifies if the compiler supports C++11 lambda expressions. ๐Ÿฆ‹ the result is stored in the internal cache variable HAVE_CXX11_LAMBDAS:

include(CheckCXXSourceCompiles)

check_cxx_source_compiles([[
  int main()
  {
    auto lambda = []() { return 42; };
    return lambda();
  }
]] HAVE_CXX11_LAMBDAS)

๐Ÿ’œ See Also

  • the CheckSourceCompiles module, for a more general command to check whether source can be built. ๐ŸŒˆ
  • the CheckSourceRuns module, to check whether source can be built and run. ๐Ÿƒโ€โ™€๏ธ

๐Ÿฆ‹ CheckCXXSourceRuns ๐Ÿฆ‹

this module provides a command to check whether a C++ source can be built and run. ๐ŸŽ€

load this module in a CMake project with:

include(CheckCXXSourceRuns)

Commands

this module provides the following command:

check_cxx_source_runs โ€” checks once whether the given C++ source code compiles and links into an executable that can subsequently be run: ๐Ÿ’…

check_cxx_source_runs(<code> <variable>)

the C++ source supplied in <code> must contain at least a main() function, no exceptions bestie. the result of the check is stored in the internal cache variable specified by <variable>. if the code builds and runs with exit code 0, success is indicated by a boolean true value. failure to build or run is indicated by a boolean false value, such as an empty string or an error message. ๐Ÿ˜ญ

Variables Affecting the Check

the following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. โš ๏ธ a semicolon-separated list will not work. the contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable. ๐Ÿ”ฅ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. a definition for the name specified by the result variable argument of the check command is also added automatically. ๐Ÿ’…
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. these will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” added in version 3.14 โœจ. A semicolon-separated list of options you want chucked onto the link command (the try_compile() docs have the deets, iykyk).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can literally just be system library names, or they can be Imported Targets ๐Ÿ’… (again, try_compile() for the full tea).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” added in version 3.31 ๐Ÿฆ‹. A semicolon-separated list of library search paths handed off to the linker (check try_compile() for more).
  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1. If this variable evaluates to a boolean true value, all the status messages tied to the check get suppressed. Silence. Peace. ๐Ÿคซ

Examples

Okay so here's a glow-up of how you'd check whether the C++ standard library is actually functional and whether std::vector works at runtime. If the source compiles, links, and runs successfully, the internal cache variable HAVE_WORKING_STD_VECTOR gets set to a boolean true value. The code is supplied using a Bracket Argument so embedded quotes are way easier to handle ๐ŸŽ€:

include(CheckCXXSourceRuns)

check_cxx_source_runs([[
  #include <iostream>
  #include <vector>

  int main()
  {
    std::vector<int> v = {1, 2, 3};
    if (v.size() != 3) return 1;
    std::cout << "Vector works correctly." << std::endl;
    return 0;
  }
]] HAVE_WORKING_STD_VECTOR)

See Also

  • The CheckSourceRuns module โ€” if you want a more general command syntax, this is your girl ๐Ÿซถ
  • The CheckSourceCompiles module โ€” for checking whether a source code can even be built at all.

CheckCXXSymbolExists ๐Ÿ‘‘

This module hands you a command to check whether a C++ symbol exists. No cap.

Load this module in a CMake project with:

include(CheckCXXSymbolExists)

Commands

This module provides the following command:

check_cxx_symbol_exists

Checks once whether a symbol exists as a function, variable, or preprocessor macro in C++:

check_cxx_symbol_exists(<symbol> <headers> <variable>)

This command checks whether the <symbol> is available after including the specified header file(s) <headers>, and stores the result in the internal cache variable <variable> โœจ. Multiple header files can be specified in one argument as a string using a semicolon-separated list.

If the header files define the symbol as a macro, it's considered available and assumed to work. If the symbol is declared as a function or variable, the check also makes sure it links successfully โ€” meaning the symbol must exist in a linked library or object file. Periodt.

Symbols that are types, enum values, or C++ templates are not recognized ๐Ÿ™ˆ. For those, consider using the CheckTypeSize or CheckSourceCompiles module instead.

This command is intended to check symbols as they appear in C++. For C symbols, use the CheckSymbolExists module instead.

Note: this command is unreliable for symbols that are (potentially) overloaded functions ๐Ÿ˜ญ. Since there's no reliable way to predict whether a given function in the system environment may be defined as an overloaded function, or may be an overloaded function on other systems, or will become so in the future, the general advice is to use the CheckSourceCompiles module for checking any function symbol โ€” unless it's certain the checked function isn't overloaded on other systems and won't be in the future. Fr fr.

Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work ๐Ÿ’€. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically. ๐ŸŽ€
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored ๐Ÿ‘€.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” added in version 3.14 โœจ. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets ๐Ÿ’… (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” added in version 3.31 ๐Ÿฆ‹. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed ๐Ÿคซ.

Examples

This next one demonstrates how to check for the presence of a preprocessor macro SEEK_SET and the C++ function std::fopen() from the <cstdio> header using this module ๐Ÿ“:

include(CheckCXXSymbolExists)

# Check for macro SEEK_SET
check_cxx_symbol_exists(SEEK_SET "cstdio" HAVE_SEEK_SET)

# Check for function std::fopen
check_cxx_symbol_exists(std::fopen "cstdio" HAVE_STD_FOPEN)

See Also

  • The CheckSymbolExists module โ€” for checking whether a C symbol exists ๐ŸŒธ

CheckFortranCompilerFlag ๐Ÿงš

Added in version 3.3 โœจ

This module provides a command to check whether the Fortran compiler supports a given flag. Iconic behaviour honestly.

Load this module in a CMake project with:

include(CheckFortranCompilerFlag)

Commands

This module provides the following command:

check_fortran_compiler_flag

Checks once whether the Fortran compiler supports a given flag:

check_fortran_compiler_flag(<flag> <variable>)

This command checks once that the <flag> is accepted by the Fortran compiler without producing a diagnostic message. Multiple flags can be specified in one argument as a string using a semicolon-separated list.

The result of the check is stored in the internal cache variable specified by <variable>, with boolean true for success and boolean false for failure ๐Ÿ”ฅ.

A successful result only indicates that the compiler didn't report an error when given the flag. Whether the flag has any effect โ€” or the intended one โ€” is outside the scope of this module. Not me checking the vibe instead of the function ๐Ÿ’€.

Note: since the underlying try_compile() command also uses flags from variables like CMAKE_<LANG>_FLAGS, unknown or unsupported flags in those variables may result in a false negative for this check ๐Ÿ˜ญ.

Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable ๐ŸŽ€.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored ๐Ÿ‘‘
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” added in version 3.14 โœจ. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries that get added to the link command. These can be plain system library names, or they can be Imported Targets (peep try_compile() for the full lore).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths that get handed to the linker (again, try_compile() has the deets).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, every status message tied to the check gets suppressed. Silence. Blessed silence. ๐Ÿคซ
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” so internally, try_compile() is what actually runs the check, and this variable decides what kind of target it builds. Set it to EXECUTABLE (the default) and the check compiles and links the test source code as an executable program. Set it to STATIC_LIBRARY and the test source gets compiled but not linked. Choose wisely bestie ๐Ÿ’…

Examples

Okay so this example is literally showing you how to check the Fortran compiler flag -fallow-argument-mismatch. The result of the check gets stashed in the internal cache variable HAVE_FORTRAN_FLAG, and then the flag is conditionally switched on with the target_compile_options() command. The $<COMPILE_LANGUAGE:...> generator expression is the โœจmain characterโœจ here โ€” it makes sure the flag only gets added to Fortran source files. Obsessed.

include(CheckFortranCompilerFlag)
check_fortran_compiler_flag(-fallow-argument-mismatch HAVE_FORTRAN_FLAG)

if(HAVE_FORTRAN_FLAG)
  target_compile_options(
    example
    PRIVATE $<$<COMPILE_LANGUAGE:Fortran>:-fallow-argument-mismatch>
  )
endif()

See Also

  • The CheckCompilerFlag module โ€” a more general command for checking whether a compiler flag is supported. iykyk ๐Ÿฆ‹

CheckFortranFunctionExists

This module hands you a command to check whether a Fortran function exists. That's the whole vibe.

Load it into your CMake project with:

include(CheckFortranFunctionExists)

Commands

This module provides the following command:

check_fortran_function_exists

Checks once whether a Fortran function exists:

check_fortran_function_exists(<function> <variable>)
  • <function> โ€” the name of the Fortran function. ๐Ÿงš
  • <variable> โ€” the name of the variable where the check result gets stored. This variable will be created as an internal cache variable.
Note ๐Ÿซถ: this command does not detect functions provided by Fortran modules. In general, the recommendation is to use CheckSourceCompiles instead to figure out whether a Fortran function or subroutine is available. Not me warning you ahead of time so you don't get caught out ๐Ÿ’€

Variables Affecting the Check

You can set these variables before calling the command to change up the way the check runs:

  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. Can be system library names, or Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).

Examples

Example: Isolated Check With Linked Libraries

In this example, the module teams up with the CMakePushCheckState module to temporarily modify the required linked libraries (via CMAKE_REQUIRED_LIBRARIES) and verify whether the Fortran function dgesv is available for linking. The result lands in the internal cache variable PROJECT_HAVE_DGESV. The way this is such a clean little sandwich of push/pop ๐Ÿ˜ญ๐Ÿ”ฅ

include(CheckFortranFunctionExists)
include(CMakePushCheckState)

find_package(LAPACK)

if(TARGET LAPACK::LAPACK)
  cmake_push_check_state(RESET)

  set(CMAKE_REQUIRED_LIBRARIES LAPACK::LAPACK)
  check_fortran_function_exists(dgesv PROJECT_HAVE_DGESV)

  cmake_pop_check_state()
endif()

See Also

  • The CheckFunctionExists module โ€” for checking whether a C function exists. Different language, same energy ๐Ÿ’œ
  • The CheckSourceCompiles module โ€” for checking whether source code can be compiled.

CheckFortranSourceCompiles

Added in version 3.1.

This module gives you a command to check whether a Fortran source can be built. Slay.

Load this module in a CMake project with:

include(CheckFortranSourceCompiles)

Commands

This module provides the following command:

check_fortran_source_compiles

Checks once whether the given Fortran source code can be built:

check_fortran_source_compiles(
  <code>
  <variable>
  [FAIL_REGEX <regexes>...]
  [SRC_EXT <extension>]
)

This command checks once that the source you supplied in <code> can be compiled (and linked into an executable). The result of the check is stored in the internal cache variable you name with <variable>. Iconic behaviour honestly.

The arguments are:

  • <code> โ€” the Fortran source code to check. This has to be an entire program, like what you'd write in a file containing the body block. All symbols used in the source code are expected to be declared as usual in their corresponding headers.
  • <variable> โ€” variable name of an internal cache variable that stores the result of the check, with boolean true for success and boolean false for failure. ๐ŸŽ€
  • FAIL_REGEX <regexes>... โ€” if you pass this option with one or more regular expressions, then failure is determined by checking whether anything in the compiler output matches any of the specified regular expressions.
  • SRC_EXT <extension> โ€” Added in version 3.7. By default, the test source file used for the check gets a .F file extension. This option overrides that with .<extension> instead โ€” .F90 is a typical choice.

Variables Affecting the Check

Set these before calling the command if you want to modify the way the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work, fr fr. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables get automatically prepended to the compiler command before the contents of this variable. Order matters bestie ๐Ÿ’…
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one in the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command also gets added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. Heads up: these will be the only header search paths used โ€” the contents of the INCLUDE_DIRECTORIES directory property get ignored. ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be system library names, or Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check get suppressed. Quiet mode activated ๐Ÿคซ
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” internally, try_compile() is the command used to perform the check, and this variable controls the type of target it creates. If it's set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. Set it to STATIC_LIBRARY and the test source code gets compiled but not linked. Same deal as before, no cap ๐Ÿงš

Examples

Checking whether the Fortran compiler supports the pure procedure attribute:

include(CheckFortranSourceCompiles)

check_fortran_source_compiles("
  pure subroutine foo()
  end subroutine
  program test
    call foo()
  end
" HAVE_PURE SRC_EXT "F90")

Look at that multi-line string just vibing inside the call. Gorgeous ๐ŸŒธ

See Also ๐Ÿ’ซ

  • The CheckSourceCompiles module โ€” a more general command for checking whether source can be built.
  • The CheckSourceRuns module โ€” to check whether source can be built and run.

CheckFortranSourceRuns ๐Ÿงš

Added in version 3.14.

Okay so this module gives you a command that checks whether a Fortran source can be built and run. Built and run, bestie โ€” like it actually gets executed. Love that for us.

Load it into your CMake project with:

include(CheckFortranSourceRuns)

Commands ๐Ÿ“œ

check_fortran_source_runs โœจ

Checks once whether the given Fortran source compiles and links into an executable that can subsequently be run.

check_fortran_source_runs(<code> <variable> [SRC_EXT <extension>])

The Fortran source you pass in <code> must contain a Fortran program unit โ€” no exceptions, it's giving non-negotiable. The result of the check gets stored in the internal cache variable named by <variable>. If the code builds and runs with exit code 0, success is indicated by a boolean true value. If it fails to build or fails to run, you get a boolean false value, such as an empty string or an error message. ๐Ÿ˜ญ

The options are:

  • SRC_EXT <extension> โ€” by default, the internal test source file used for the check gets a .F90 file extension. This option lets you change the extension to .<extension> instead. Cute.

Variables Affecting the Check ๐Ÿ”ง

These can all be set before you call the command, to modify the way the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. Heads up: a semicolon-separated list will not work here. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables get automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command also gets added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property get ignored. Periodt.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check get suppressed. Silence. ๐Ÿคซ

Examples ๐ŸŒธ

This example shows how to use the module to check whether a Fortran source code runs, and to store the result of the check in an internal cache variable HAVE_COARRAY:

include(CheckFortranSourceRuns)

check_fortran_source_runs([[
  program test
  real :: x[*]
  call co_sum(x)
  end program
]] HAVE_COARRAY)

See Also ๐ŸŒˆ

  • The CheckSourceRuns module โ€” for a more general command syntax.
  • The CheckSourceCompiles module โ€” to check whether a source code can be built.

CheckFunctionExists ๐Ÿฆ‹

This module provides a command to check whether a C function exists. That's it, that's the vibe.

Load this module in a CMake project with:

include(CheckFunctionExists)

Commands ๐Ÿ“œ

check_function_exists โญ

Checks once whether a C function can be linked from system libraries:

check_function_exists(<function> <variable>)

This command checks whether the <function> is provided by libraries on the system, and stores the result in an internal cache variable <variable>.

Note: ๐Ÿ”ฅ Prefer using CheckSymbolExists or CheckSourceCompiles instead of this command, for the following reasons:

  • check_function_exists() can't detect functions that are inlined in headers or defined as preprocessor macros.
  • check_function_exists() can't detect anything in the 32-bit versions of the Win32 API, because of a mismatch in calling conventions.
  • check_function_exists() only verifies linking, it does not verify that the function is declared in system headers.

Variables Affecting the Check ๐Ÿ”ง

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.

Examples ๐Ÿ’–

Example: Basic Usage

In the following example, a check is performed to determine whether the linker sees the C function fopen(), and the result is stored in the HAVE_FOPEN internal cache variable:

include(CheckFunctionExists)

check_function_exists(fopen HAVE_FOPEN)

Example: Missing Declaration

As noted above, the CheckSymbolExists module is preferred for checking C functions, since it also verifies whether the function is declared or defined as a macro. In the following example, this module is used to check an edge case where a function may not be declared in system headers. For instance, on macOS, the fdatasync() function may be available in the C library, but its declaration is not provided in the unistd.h system header. ๐Ÿ™ˆ

CMakeLists.txt

include(CheckFunctionExists)
include(CheckSymbolExists)

check_symbol_exists(fdatasync "unistd.h" HAVE_FDATASYNC)

# Check if fdatasync() is available in the C library.
if(NOT HAVE_FDATASYNC)
  check_function_exists(fdatasync HAVE_FDATASYNC_WITHOUT_DECL)
endif()

In such a case, the project can provide its own declaration if missing:

example.c

#ifdef HAVE_FDATASYNC_WITHOUT_DECL
  extern int fdatasync(int);
#endif

See Also ๐ŸŒˆ

  • The CheckSymbolExists module โ€” to check whether a C symbol exists.
  • The CheckSourceCompiles module โ€” to check whether a source code can be compiled.
  • The CheckFortranFunctionExists module โ€” to check whether a Fortran function exists.

CheckIncludeFile ๐ŸŽ€

This module provides a command to check a C header file. Yup, just the one header, bestie.

Load this module in a CMake project with:

include(CheckIncludeFile)

Commands ๐Ÿ“œ

check_include_file ๐Ÿ‘‘

Checks once whether a header file exists and can be included in C code:

check_include_file(<include> <variable> [<flags>])

The arguments are:

  • <include> โ€” a header file to be checked.
  • <variable> โ€” the name of the variable to store the result of the check. This variable will be created as an internal cache variable.
  • <flags> โ€” (optional) a space-separated string of extra compilation flags you want tacked onto the check. You can also pass flags in through the CMAKE_REQUIRED_FLAGS variable (more on that literally right below ๐Ÿ‘‡).

Variables Affecting the Check

okay bestie, these are the knobs ๐ŸŽ›๏ธ โ€” set any of them before you call this command and they'll change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. ๐Ÿซถ and yes, this one is picky: a semicolon-separated list will not work. Also, the contents of CMAKE_<LANG>_FLAGS and its configuration-specific bestie CMAKE_<LANG>_FLAGS_<CONFIG> get automatically prepended to the compiler command before whatever's sitting in this variable. order matters, periodt.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each shaped like -DFOO or -DFOO=bar. A definition for the name you passed as the result variable argument gets added automatically too (sneaky but helpful ๐Ÿ’…).
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. โš ๏ธ Heads up: these will be the only header search paths used โ€” the contents of the INCLUDE_DIRECTORIES directory property get completely ignored. it's giving "my way or the highway".
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (go peek at try_compile() for the full tea).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (again, try_compile() has the details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, every single status message tied to the check gets suppressed. silence is golden โœจ
Added in version 3.12: the CMAKE_REQUIRED_LIBRARIES variable โ€” but only if policy CMP0075 is set to NEW. no cap.

Examples

Example: Checking C Header ๐ŸŒธ

Checking whether the C header <unistd.h> exists, and storing the check result in the HAVE_UNISTD_H cache variable:

include(CheckIncludeFile)

check_include_file(unistd.h HAVE_UNISTD_H)

Example: Isolated Check ๐Ÿงš

In the following example, this module is used together with the CMakePushCheckState module to temporarily modify the required compile definitions (via CMAKE_REQUIRED_DEFINITIONS) and verify whether the C header <ucontext.h> is available. The result gets stored in the internal cache variable HAVE_UCONTEXT_H.

For example, on macOS the ucontext API is deprecated, and headers may be hidden unless certain feature macros are defined. In particular, defining _XOPEN_SOURCE (without a value) can expose the necessary symbols without enabling broader POSIX or SUS (Single Unix Specification) features (values 500 or greater). iconic behavior honestly.

include(CheckIncludeFile)
include(CMakePushCheckState)

cmake_push_check_state(RESET)
  if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
    set(CMAKE_REQUIRED_DEFINITIONS -D_XOPEN_SOURCE)
  endif()

  check_include_file(ucontext.h HAVE_UCONTEXT_H)
cmake_pop_check_state()

See Also

  • The CheckIncludeFileCXX module, for checking a single C++ header. ๐Ÿ‘‘
  • The CheckIncludeFiles module, for checking one or more C or C++ headers at once. ๐Ÿฆ‹

CheckIncludeFileCXX

This module hands you a command that checks a C++ header file. lowkey essential.

Load this module in a CMake project with:

include(CheckIncludeFileCXX)

Commands

This module provides the following command:

check_include_file_cxx

(okay it's not literally a heading level, but you get it ๐Ÿ’œ)

Checks once whether a header file exists and can be included in C++ code:

check_include_file_cxx(<include> <variable> [<flags>])

The arguments are:

  • <include> โ€” a header file to be checked. ๐ŸŽ€
  • <variable> โ€” the name of the variable that stores the result of the check. This variable gets created as an internal cache variable.
  • <flags> โ€” (optional) a space-separated string of additional compilation flags to add to the check. Alternatively, flags can also be specified with the CMAKE_REQUIRED_FLAGS variable below.

Variables Affecting the Check

same drill as before, bestie โ€” set any of these before calling the command to change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically. ๐Ÿ’…
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. โš ๏ธ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. ๐Ÿคซ
Added in version 3.12: the CMAKE_REQUIRED_LIBRARIES variable, if policy CMP0075 is set to NEW.

Examples

Checking whether the C++23 header <stdfloat> exists and storing the check result in the HAVE_STDFLOAT_HEADER cache variable:

include(CheckIncludeFileCXX)

check_include_file_cxx(stdfloat HAVE_STDFLOAT_HEADER)

See Also

  • The CheckIncludeFile module, for checking a single C header. ๐ŸŒˆ
  • The CheckIncludeFiles module, for checking one or more C or C++ headers at once. ๐ŸŒธ

CheckIncludeFiles

This module provides a command to check one or more C/C++ header files. plural slay ๐Ÿ’…

Load this module in a CMake project with:

include(CheckIncludeFiles)

Commands

This module provides the following command:

check_include_files

Checks once whether one or more header files exist and can be included together in C or C++ code:

check_include_files(<includes> <variable> [LANGUAGE <language>])

The arguments are:

  • <includes> โ€” a semicolon-separated list of header files to be checked. ๐ŸŽ€
  • <variable> โ€” the name of the variable to store the result of the check. This variable will be created as an internal cache variable.
  • LANGUAGE <language> โ€” Added in version 3.11. If set, the specified <language> compiler will be used to perform the check. Acceptable values are C and CXX. If this option is not given, the C compiler will be used if enabled. If the C compiler is not enabled, the C++ compiler will be used if enabled. (it'll figure it out, she's smart like that โœจ)

Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable. ๐Ÿซถ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths you hand to the compiler. And bestie, hear me: these will be the only header search paths used. The contents of the INCLUDE_DIRECTORIES directory property just get ignored entirely. Like, ghosted. ๐Ÿ’…
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” added in version 3.14 โœจ

A semicolon-separated list of options to add to the link command (peep try_compile() for the further details, iykyk).

  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be names of system libraries, or they can be Imported Targets (again, try_compile() has the full tea ๐Ÿซ–).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” added in version 3.31 ๐ŸŒˆ

A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details, always try_compile()).

  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1 ๐Ÿคซ

If this variable evaluates to a boolean true value, all the status messages associated with the check get suppressed. Silence. Iconic.

Added in version 3.12: The CMAKE_REQUIRED_LIBRARIES variable, if policy CMP0075 is set to NEW.


๐Ÿงช Examples

Checking one or more C headers and stashing the check result in cache variables, like a little detective:

include(CheckIncludeFiles)

check_include_files(sys/socket.h HAVE_SYS_SOCKET_H)

if(HAVE_SYS_SOCKET_H)
  # The <net/if.h> header on Darwin and BSD-like systems is not self-contained
  # and also requires <sys/socket.h>
  check_include_files("sys/socket.h;net/if.h" HAVE_NET_IF_H)
else()
  check_include_files(net/if.h HAVE_NET_IF_H)
endif()

The LANGUAGE option is your girl for specifying which compiler to use ๐Ÿ”ฅ For example, checking multiple C++ headers when both C and CXX languages are enabled in the project:

include(CheckIncludeFiles)

check_include_files("header_1.hpp;header_2.hpp" HAVE_HEADERS LANGUAGE CXX)

๐Ÿ‘€ See Also

  • The CheckIncludeFile module, for checking a single C header. One. Uno. ๐ŸŽ€
  • The CheckIncludeFileCXX module, for checking a single C++ header. Same energy, C++ flavoured. ๐Ÿฆ‹

โšก CheckIPOSupported

Added in version 3.9 โœจ

This module hands you a command to check whether the compiler supports interprocedural optimization (IPO/LTO). Slay.

Load it into your CMake project with:

include(CheckIPOSupported)

So what even is interprocedural optimization? It's a compiler technique that performs optimizations across translation units (i.e., across source files), letting the compiler analyze and optimize the entire program as a whole rather than file-by-file. Main character energy, honestly โ€” the whole program, not just one little file. ๐Ÿ’œ This can improve performance by enabling more aggressive inlining and dead code elimination. And when these optimizations get applied at link time, the process is typically referred to as link-time optimization (LTO), which is a common form of IPO. Two names, one vibe.

In CMake, you can enable interprocedural optimization on a per-target basis using the INTERPROCEDURAL_OPTIMIZATION target property, or for all targets in the current scope using the CMAKE_INTERPROCEDURAL_OPTIMIZATION variable.

Use this module before enabling the interprocedural optimization on targets, so you actually know the compiler supports IPO/LTO instead of just hoping and praying ๐Ÿ™

๐Ÿ›  Commands

This module provides the following command:

check_ipo_supported

Checks whether the compiler supports interprocedural optimization (IPO/LTO):

check_ipo_supported(
  [RESULT <result-var>]
  [OUTPUT <output-var>]
  [LANGUAGES <lang>...]
)

Options are:

  • RESULT <result-var> โ€” set the <result-var> variable to YES if IPO is supported by the compiler and NO otherwise. If this option is not given, then the command will issue a fatal error if IPO is not supported. So like, no pressure, but do give it a result var if you're not in the mood for drama ๐Ÿ’€
  • OUTPUT <output-var> โ€” set the <output-var> variable with details about any error. Receipts. ๐Ÿงพ
  • LANGUAGES <lang>... โ€” specify languages whose compilers to check.

The following languages are supported:

  • C
  • CXX
  • CUDA โ€” added in version 3.25 ๐ŸŒˆ
  • Fortran

If this option is not given, the default languages are picked from the current ENABLED_LANGUAGES global property. Vibes-based defaults, but make it official.

Note: to use check_ipo_supported(), policy CMP0069 must be set to NEW โ€” otherwise, a fatal error will occur. Fr fr, it will Not Be Chill about it. ๐Ÿ˜ญ

Added in version 3.13: Support for Visual Studio Generators. ๐ŸŽ€

Added in version 3.24: The check uses the caller's CMAKE_<LANG>_FLAGS and CMAKE_<LANG>_FLAGS_<CONFIG> values. See policy CMP0138.

๐Ÿงช Examples

Checking whether the compiler supports IPO and emitting a fatal error if it isn't supported:

include(CheckIPOSupported)
check_ipo_supported() # fatal error if IPO is not supported
set_property(TARGET foo PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)

The following example demonstrates how to use this module to enable IPO for the target only when it's supported by the compiler, and to issue a warning when it isn't. Additionally, projects may want to provide a configuration option to control when IPO is enabled. For example:

option(FOO_ENABLE_IPO "Enable IPO/LTO")

if(FOO_ENABLE_IPO)
  include(CheckIPOSupported)
  check_ipo_supported(RESULT result OUTPUT output)
  if(result)
    set_property(TARGET foo PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
  else()
    message(WARNING "IPO is not supported: ${output}")
  endif()
endif()

๐ŸŒ CheckLanguage

This module provides a command to check whether a language can be enabled using the enable_language() or project() commands.

Load this module in a CMake project with:

include(CheckLanguage)

This module is genuinely useful when a project doesn't always need a specific language but might need to enable it for certain parts. Lowkey the most relatable module tbh ๐Ÿซถ

๐Ÿ›  Commands

This module provides the following command:

check_language

Checks whether a language can be enabled in a CMake project:

check_language(<lang>)

This command attempts to enable the language <lang> in a test project and records the results in the following cache variables:

  • CMAKE_<LANG>_COMPILER โ€” if the language can be enabled, this variable is set to the compiler that was found. If the language cannot be enabled, this variable is set to NOTFOUND.

If this variable is already set, either explicitly or cached by a previous call, the check is skipped. Already know her, no need to re-introduce her. ๐Ÿ’…

  • CMAKE_<LANG>_HOST_COMPILER โ€” this variable is set when <lang> is CUDA or HIP.

If the check detects an explicit host compiler that is required for compilation, this variable will be set to that compiler. If the check detects that no explicit host compiler is needed, this variable will be cleared.

If this variable is already set, its value is preserved only if CMAKE_<LANG>_COMPILER is also set. Otherwise, the check runs and overwrites CMAKE_<LANG>_HOST_COMPILER with a new result. Note that CMAKE_<LANG>_HOST_COMPILER documents it should not be set without also setting CMAKE_<LANG>_COMPILER to a NVCC compiler. Rules are rules, bestie ๐Ÿ“‹

  • CMAKE_<LANG>_PLATFORM โ€” this variable is set to the detected GPU platform when <lang> is HIP.

If this variable is already set, its value is always preserved. Only compatible values will be considered for CMAKE_<LANG>_COMPILER. Loyalty. ๐Ÿ‘‘

๐Ÿงช Examples

The following example checks for the availability of the Fortran language and enables it if possible:

include(CheckLanguage)
check_language(Fortran)
if(CMAKE_Fortran_COMPILER)
  enable_language(Fortran)
else()
  message(STATUS "No Fortran support")
endif()

๐Ÿ“š CheckLibraryExists

This module provides a command to check whether a C library exists. Does she exist? Let's find out ๐Ÿ”

Load this module in a CMake project with:

include(CheckLibraryExists)

๐Ÿ›  Commands

This module provides the following command:

check_library_exists

Checks once whether a specified library exists and a given C function is available:

check_library_exists(<library> <function> <location> <variable>)

This command attempts to link a test executable that uses the specified C <function> to verify that it's provided by either a system or user-provided <library>. A whole little test build, just for you. Obsessed. ๐Ÿ’–

The arguments are:

  • <library> โ€” the name of the library, a full path to a library file, or an Imported Target. Flexible queen ๐ŸŒธ
  • <function> โ€” the name of a function that should be available in the system or user-provided library <library>. The whole point of the check, honestly.
  • <location> โ€” the directory containing the library file. It is added to the link search path during the check. If this is an empty string, only the default library search paths are used. Empty string = default paths, periodt.
  • <variable> โ€” the name of the variable in which to store the check result. This variable will be created as an internal cache variable. ๐ŸŽ€
Note: this one is for basic sanity checks, bestie โ€” it just confirms your library actually does the thing you think it does, or that CMake found the right library and not some chaotic impostor. But listen: it only checks that a function symbol can be linked successfully. It does not make sure the function is declared in the library headers, and it straight-up cannot detect functions that are inlined or defined as preprocessor macros. ๐Ÿ˜ญ So if you want the robust, no-notes version of function detection, go use CheckSymbolExists or CheckSourceCompiles instead. Periodt.

๐ŸŒธ Variables Affecting the Check ๐ŸŒธ

Set any of these before you call this command to change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. And no, a semicolon-separated list will not work here, that's the whole vibe. The contents of CMAKE_<LANG>_FLAGS and its config-specific bestie CMAKE_<LANG>_FLAGS_<CONFIG> get automatically prepended to the compiler command before whatever's in this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one shaped like -DFOO or -DFOO=bar. A definition for the name you gave as the check command's result variable argument is also added automatically. ๐Ÿซถ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” added in version 3.14. A semicolon-separated list of options to add to the link command (peep try_compile() for the deets).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be system library names, or they can be Imported Targets (again, try_compile() has the full story).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile()).
  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1. If this evaluates to a boolean true value, every status message associated with the check gets suppressed. Silence, iconically. ๐Ÿคซ

โœจ Examples โœจ

Checking if the curl library exists in the default paths and has the curl_easy_perform() function:

include(CheckLibraryExists)
check_library_exists(curl curl_easy_perform "" HAVE_LIBRARY_CURL)

To check if a library exists in a specific non-standard location and has a specified function:

include(CheckLibraryExists)
check_library_exists(curl curl_easy_perform "/opt/curl/lib" HAVE_LIBRARY_CURL)

Also, Imported Targets (like, from a find_package() call) can be used, and honestly? Slay:

find_package(CURL)

# ...

if(TARGET CURL::libcurl)
  include(CheckLibraryExists)
  check_library_exists(CURL::libcurl curl_easy_perform "" HAVE_LIBRARY_CURL)
endif()

๐Ÿฆ‹ See Also ๐Ÿฆ‹

  • The CheckSymbolExists module โ€” for checking whether a C symbol exists. ๐Ÿ’…

๐Ÿ’œ CheckLinkerFlag ๐Ÿ’œ

Added in version 3.18.

This module hands you a command to check whether a given link flag is even supported by your compiler. Vibe check for flags, basically.

Load it into your CMake project with:

include(CheckLinkerFlag)

Commands

This module provides the following command:

  • check_linker_flag(<lang> <flag> <variable>) โ€” checks once whether the compiler supports a given link flag.

This command checks once whether the linker flag <flag> is accepted by the <lang> compiler without producing a diagnostic message. No drama, no warnings, just vibes.

The arguments are:

  • <lang> โ€” the language of the compiler used for the check. Supported languages are C, CXX, CUDA, Fortran, HIP, OBJC, OBJCXX, and Swift.
    • Added in version 3.19: support for CUDA language.
    • Added in version 3.21: support for HIP language.
    • Added in version 3.26: support for Swift language.
  • <flag> โ€” linker flag(s) to check. Multiple flags can be specified in one argument as a string using a semicolon-separated list. ๐ŸŽ€

The underlying implementation uses the LINK_OPTIONS target property to test the specified flag. The LINKER: (and SHELL:) prefixes may be used, as described in the Handling Compiler Driver Differences section below.

  • <variable> โ€” the name of the variable to store the check result. This variable will be created as an internal cache variable.

This command temporarily sets the CMAKE_REQUIRED_LINK_OPTIONS variable and calls the check_source_compiles() command from the CheckSourceCompiles module.

Heads up: a successful result only indicates that the compiler did not report an error when given the link flag. Whether the flag has any effect, or the intended effect, is outside the scope of this module. It's giving "no errors โ‰  did anything". ๐Ÿ™ˆ

Note: since the underlying try_compile() command also uses flags from variables like CMAKE_<LANG>_FLAGS, unknown or unsupported flags hanging out in those variables may result in a false negative for this check. Not me warning you twice. ๐Ÿ’€

๐ŸŒˆ Variables Affecting the Check ๐ŸŒˆ

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used โ€” the contents of the INCLUDE_DIRECTORIES directory property will be ignored. Like, fully ignored. ๐Ÿ‘€
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.

๐Ÿงš Handling Compiler Driver Differences ๐Ÿงš

Okay so to pass options to the linker tool, every compiler driver has its own little syntax situation. The LINKER: prefix and , separator let you specify, in a portable way, options to pass to the linker tool. LINKER: gets replaced by the appropriate driver option and , by the appropriate driver separator. The driver prefix and driver separator are given by the values of the CMAKE_<LANG>_LINKER_WRAPPER_FLAG and CMAKE_<LANG>_LINKER_WRAPPER_FLAG_SEP variables. iykyk.

For example, "LINKER:-z,defs" becomes -Xlinker -z -Xlinker defs for Clang and -Wl,-z,defs for GNU GCC. Same flag, different fits. ๐Ÿ’…

The LINKER: prefix can be specified as part of a SHELL: prefix expression.

The LINKER: prefix also supports, as an alternative syntax, specification of arguments using the SHELL: prefix and space as separator. That previous example then becomes "LINKER:SHELL:-z defs".

Note: specifying the SHELL: prefix anywhere other than at the beginning of the LINKER: prefix is not supported. Don't try it, bestie, it's not going to eat. ๐Ÿ˜ญ

โญ Examples โญ

Example: Checking Linker Flag

The following example shows how to use this module to check the -z relro linker flag, which is supported on many Unix-like systems to enable read-only relocations for improved binary security. If the flag is supported by the linker, it is conditionally added to the executable target using target_link_options(). The LINKER: prefix is used to pass the flag to the linker in a portable and compiler-independent way. Security and portability? We love to see it. ๐Ÿ‘‘

include(CheckLinkerFlag)

check_linker_flag(C "LINKER:-z,relro" HAVE_Z_RELRO)

add_executable(example main.c)

if(HAVE_Z_RELRO)
  target_link_options(example PRIVATE "LINKER:-z,relro")
endif()

Example: Checking Multiple Flags

In the following example, multiple linker flags are checked simultaneously:

include(CheckLinkerFlag)

check_linker_flag(C "LINKER:-z,relro;LINKER:-z,now" HAVE_FLAGS)

add_executable(example main.c)

if(HAVE_FLAGS)
  target_link_options(example PRIVATE LINKER:-z,relro LINKER:-z,now)
endif()

๐ŸŒธ See Also ๐ŸŒธ

  • The CMAKE_LINKER_TYPE variable to specify the linker, which will be used also by this module. ๐Ÿซถ
  • The CheckCompilerFlag module, for checking whether a compiler flag is supported (it's the general-purpose one, and yes she's iconic).

๐Ÿฆ‹ CheckOBJCCompilerFlag ๐Ÿฆ‹

Added in version 3.16.

Okay so this module hands you a whole command whose only job is asking "hey, does the Objective-C compiler actually support this flag?" ๐Ÿ’…

Load it into your CMake project like this, bestie:

include(CheckOBJCCompilerFlag)

โœจ Commands โœจ

This module gives you exactly one command:

  • check_objc_compiler_flag โ€” checks once whether the Objective-C compiler supports the flag you hand it:
check_objc_compiler_flag(<flag> <variable>)

So what it does: it checks once that <flag> is accepted by the OBJC compiler without producing a diagnostic message. You can sneak multiple flags into one argument as a string using a semicolon-separated list. ๐ŸŽ€

The result of the check gets stashed in the internal cache variable you name with <variable> โ€” boolean true if it slayed, boolean false if it flopped.

Heads up though: a successful result only means the compiler didn't report an error when given the flag. Whether the flag actually does anything, or does the thing you wanted โ€” that's lowkey outside the scope of this module. ๐Ÿคทโ€โ™€๏ธ
Note: since the underlying try_compile() command also uses flags from variables like CMAKE_<LANG>_FLAGS, unknown or unsupported flags chilling in those variables can give you a false negative on this check. Not the vibe, but that's the deal. ๐Ÿ’€

๐ŸŒˆ Variables Affecting the Check ๐ŸŒˆ

Set any of these before calling the command and they'll change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. A semicolon-separated list will not work (fr fr, don't do it). The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables get automatically prepended to the compiler command, ahead of whatever's in this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each shaped like -DFOO or -DFOO=bar. A definition for the name you passed as the result variable argument of the check command also gets added automatically. ๐Ÿซถ
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These are the only header search paths used โ€” the contents of the INCLUDE_DIRECTORIES directory property get fully ignored. ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (peep try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be names of system libraries, or they can be Imported Targets (again, try_compile() has further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check get suppressed. Silence. Peace. Zen. ๐Ÿงš
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” internally, try_compile() is what actually performs the check, and this variable controls what type of target it creates. If it's set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. If it's set to STATIC_LIBRARY, the test source code is compiled but not linked.

๐ŸŒธ Examples ๐ŸŒธ

This example is literally showing you how to check the Objective-C compiler flag -fobjc-arc. The result lands in the internal cache variable HAVE_OBJC_ARC, and then the flag gets conditionally enabled with target_compile_options(). The $<COMPILE_LANGUAGE:...> generator expression is the main character here โ€” she makes sure the flag only gets added to OBJC source files. ๐Ÿ‘‘

include(CheckOBJCCompilerFlag)
check_objc_compiler_flag(-fobjc-arc HAVE_OBJC_ARC)

if(HAVE_OBJC_ARC)
  target_compile_options(
    example
    PRIVATE $<$<COMPILE_LANGUAGE:OBJC>:-fobjc-arc>
  )
endif()

โญ See Also โญ

  • The CheckCompilerFlag module โ€” for a more general command to check whether a compiler flag is supported.

๐ŸŽ€ CheckOBJCSourceCompiles ๐ŸŽ€

Added in version 3.16.

This one's the module that gives you a command to check whether an Objective-C source can actually be built. Big "will it compile or will it humiliate me" energy. ๐Ÿ˜ญ

Load it with:

include(CheckOBJCSourceCompiles)

โœจ Commands โœจ

One command, coming right up:

  • check_objc_source_compiles โ€” checks once whether the given Objective-C source code can be built:
check_objc_source_compiles(<code> <variable> [FAIL_REGEX <regexes>...])

It checks once that the source you supplied in <code> can be compiled (and linked into an executable). The result of the check goes into the internal cache variable you name with <variable>. ๐Ÿซถ

The arguments, bestie:

  • <code> โ€” the source code to check. This has to be an entire program, as written in a file containing the body block. All symbols used in the source code are expected to be declared as usual in their corresponding headers. No guessing games. ๐Ÿ’…
  • <variable> โ€” the variable name of an internal cache variable that stores the result of the check, with boolean true for success and boolean false for failure.
  • FAIL_REGEX <regexes>... โ€” if you provide this option with one or more regular expressions, then failure is determined by checking if anything in the compiler output matches any of the specified regular expressions. So even if it "compiles", a match still means fail. Sneaky but fair. ๐Ÿ’€

๐ŸŒˆ Variables Affecting the Check ๐ŸŒˆ

Set these before calling the command to modify how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically. ๐Ÿ“
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. ๐Ÿคซ
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” internally, try_compile() is used to perform the check, and this variable controls the type of target it creates. If this variable is set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. If set to STATIC_LIBRARY, the test source code is compiled but not linked.

๐ŸŒธ Examples ๐ŸŒธ

Down here we're using the module to check whether the provided Objective-C source code compiles and links. The result of the check is stored in the internal cache variable HAVE_WORKING_CODE. Look at her go. โœจ

include(CheckOBJCSourceCompiles)

check_objc_source_compiles("
  #import <Foundation/Foundation.h>
  int main()
  {
    NSObject *foo;
    return 0;
  }
" HAVE_WORKING_CODE)

โญ See Also โญ

  • The CheckSourceCompiles module โ€” for a more general command to check whether source can be built.
  • The CheckSourceRuns module to check whether source can be built and run.

CheckOBJCSourceRuns

Added in version 3.16.

Okay so this module hands you a command that checks whether an Objective-C source can actually be built and run. Like, compile it, link it, execute it, see if it survives. ๐Ÿ’…

Load this module in a CMake project with:

include(CheckOBJCSourceRuns)

Commands

This module provides the following command:

check_objc_source_runs

Checks once whether the given Objective-C source code compiles and links into an executable that can subsequently be run:

check_objc_source_runs(<code> <variable>)

The Objective-C source supplied in <code> must contain at least a main() function โ€” non-negotiable, bestie, it's an executable check so it needs an entry point. The result of the check is stored in the internal cache variable specified by <variable>. If the code builds and runs with exit code 0, success is indicated by a boolean true value. Failure to build or run is indicated by a boolean false value, such as an empty string or an error message. ๐Ÿ˜ญ

Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” A space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work here (fr fr, spaces only). The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” A semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically. โœจ
  • CMAKE_REQUIRED_INCLUDES โ€” A semicolon-separated list of header search paths to pass to the compiler. Heads up: these will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” A semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. ๐Ÿคซ

Examples

In the following example, this module is used to check whether the provided Objective-C source code builds and runs. Result of the check is stored in an internal cache variable HAVE_WORKING_CODE.

include(CheckOBJCSourceRuns)

check_objc_source_runs("
  #import <Foundation/Foundation.h>
  int main()
  {
    NSObject *foo;
    return 0;
  }
" HAVE_WORKING_CODE)

See Also

  • The CheckSourceRuns module for a more general command syntax.
  • The CheckSourceCompiles module to check whether a source code can be built.

CheckOBJCXXCompilerFlag

Added in version 3.16.

This module provides a command to check whether the Objective-C++ compiler supports a given flag. Compiler flag detective work, but make it Objective-C++. ๐Ÿ•ต๏ธโ€โ™€๏ธ

Load this module in a CMake project with:

include(CheckOBJCXXCompilerFlag)

Commands

This module provides the following command:

check_objcxx_compiler_flag

Checks once whether the Objective-C++ compiler supports a given flag:

check_objcxx_compiler_flag(<flag> <variable>)

This command checks once that the <flag> is accepted by the OBJCXX compiler without producing a diagnostic message. Multiple flags can be specified in one argument as a string using a semicolon-separated list. ๐ŸŽ€

The result of the check is stored in the internal cache variable specified by <variable>, with boolean true for success and boolean false for failure.

A successful result only indicates that the compiler did not report an error when given the flag. Whether the flag has any effect, or the intended one, is outside the scope of this module. So likeโ€ฆ it said yes, it didn't say why. ๐Ÿ™ˆ

Note: Since the underlying try_compile() command also uses flags from variables like CMAKE_<LANG>_FLAGS, unknown or unsupported flags in those variables may result in a false negative for this check. Yeah, that's the sneaky one โ€” your own leftover flags can sabotage the vibe check. ๐Ÿ’€

Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” A space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” A semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” A semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” A semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” Internally, the try_compile() command is used to perform the check, and this variable controls the type of target it creates. If this variable is set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. If set to STATIC_LIBRARY, the test source code is compiled but not linked.

Examples

The following example demonstrates how to use this module to check the Objective-C++ compiler flag -fobjc-arc. The result of the check is stored in the internal cache variable HAVE_OBJC_ARC, and the flag is conditionally enabled using the target_compile_options() command. The $<COMPILE_LANGUAGE:...> generator expression ensures that the flag is added only to OBJCXX source files. Slay. ๐Ÿ”ฅ

include(CheckOBJCXXCompilerFlag)
check_objcxx_compiler_flag(-fobjc-arc HAVE_OBJC_ARC)

if(HAVE_OBJC_ARC)
target_compile_options(
    example
    PRIVATE $<$<COMPILE_LANGUAGE:OBJCXX>:-fobjc-arc>
  )
endif()

See Also

  • The CheckCompilerFlag module for a more general command to check whether a compiler flag is supported.

CheckOBJCXXSourceCompiles

Added in version 3.16.

This module provides a command to check whether an Objective-C++ source can be built. Just built, no running required โ€” that's a whole different module's job. ๐Ÿฆ‹

Load this module in a CMake project with:

include(CheckOBJCXXSourceCompiles)

Commands

This module provides the following command:

check_objcxx_source_compiles

Checks once whether the given Objective-C++ source code can be built:

check_objcxx_source_compiles(<code> <variable> [FAIL_REGEX <regexes>...])

This command checks once that the source supplied in <code> can be compiled (and linked into an executable). The result of the check is stored in the internal cache variable specified by <variable>.

The arguments are:

  • <code> โ€” Objective-C++ source code to check. This must be an entire program, as written in a file containing the body block. All symbols used in the source code are expected to be declared as usual in their corresponding headers.
  • <variable> โ€” the name of an internal cache variable where we stash the check result, bestie: boolean true means slay success, boolean false means it flopped ๐Ÿ’”
  • FAIL_REGEX <regexes>... โ€” if you pass one or more regexes here, then failure is decided by checking whether anything in the compiler output matches any of those regexes. It's giving "we're looking for red flags" energy ๐Ÿšฉ

Variables Affecting the Check

The following variables can be set before you call this command to tweak how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. A semicolon-separated list will not work, so don't try it ๐Ÿ’€ The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable. It's giving automatic VIP treatment โœจ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one shaped like -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically. Free bonus definition, no cap ๐ŸŽ
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. So if you're like "why isn't it finding my headers", check this list first, bestie ๐Ÿ˜ญ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details). Linker era, let's go ๐Ÿ”—
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details). Imported Targets are lowkey iconic ๐Ÿ‘‘
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details). Fresh out of 3.31, we love to see it ๐ŸŽ€
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. Silence is golden, periodt ๐Ÿคซ
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” internally, the try_compile() command is used to perform the check, and this variable controls the type of target it creates. If this variable is set to EXECUTABLE (the default), the check compiles and links the test source code as an executable program. If set to STATIC_LIBRARY, the test source code is compiled but not linked. Choose your fighter ๐ŸฅŠ

Examples

In the following example, this module is used to check whether the provided Objective-C++ source code can be compiled and linked. Result of the check is stored in the internal cache variable HAVE_WORKING_CODE.

include(CheckOBJCXXSourceCompiles)

check_objcxx_source_compiles("
  #include <vector>
  #import <Foundation/Foundation.h>
  int main()
  {
    std::vector<int> v;
    NSObject *foo;
    return 0;
  }
" HAVE_WORKING_CODE)

See Also

  • The CheckSourceCompiles <#module:CheckSourceCompiles> module for a more general command to check whether source can be built. It's giving "we made it general purpose" energy ๐ŸŒˆ
  • The CheckSourceRuns <#module:CheckSourceRuns> module to check whether source can be built and run. Because sometimes compiling isn't enough, bestie ๐Ÿƒโ€โ™€๏ธ

CheckOBJCXXSourceRuns ๐Ÿฆ‹

Added in version 3.16.

This module provides a command to check whether an Objective-C++ source can be built and run. It's the "does it actually work when you press play" check โ–ถ๏ธ

Load this module in a CMake project with:

include(CheckOBJCXXSourceRuns)

Commands

This module provides the following command:

check_objcxx_source_runs โ€” checks once whether the given Objective-C++ source code compiles and links into an executable that can subsequently be run:

check_objcxx_source_runs(<code> <variable>)

The Objective-C++ source supplied in <code> must contain at least a main() function. The result of the check is stored in the internal cache variable specified by <variable>. If the code builds and runs with exit code 0, success is indicated by a boolean true value. Failure to build or run is indicated by a boolean false value, such as an empty string or an error message. So basically: exit code zero = slay, anything else = bestie no ๐Ÿ˜ญ

Variables Affecting the Check

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable. Same energy as before, no cap โœจ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically. Automatic add-on, we love her ๐Ÿ’…
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. So don't come for her unless you set these, bestie ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details). Linker girlies rise ๐Ÿ”—
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details). Imported Targets are literally main character energy ๐Ÿ‘‘
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details). New in 3.31, fresh drop ๐ŸŽ€
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. Shhh, we're being quiet ๐Ÿคซ

Examples

In the following example, this module is used to check whether the provided Objective-C++ source code builds and runs. Result of the check is stored in an internal cache variable HAVE_WORKING_CODE.

include(CheckOBJCXXSourceRuns)

check_objcxx_source_runs("
  #include <vector>
  #import <Foundation/Foundation.h>
  int main()
  {
    std::vector<int> v;
    NSObject *foo;
    return 0;
  }
" HAVE_WORKING_CODE)

See Also

  • The CheckSourceRuns <#module:CheckSourceRuns> module for a more general command syntax. General queen ๐Ÿ‘‘
  • The CheckSourceCompiles <#module:CheckSourceCompiles> module to check whether a source code can be built. Compile-only vibes ๐ŸŒธ

CheckPIESupported ๐Ÿ’–

Added in version 3.14.

This module provides a command to check whether the linker supports Position Independent Code (PIE) or No Position Independent Code (NO_PIE) for executables. It's giving "can your linker handle this" realness ๐Ÿ”

Load this module in a CMake project with:

include(CheckPIESupported)

When setting the POSITION_INDEPENDENT_CODE target property, PIC-related compile and link options are added when building library objects, and PIE-related compile options are added when building objects of executable targets, regardless of this module. Use this module to ensure that the POSITION_INDEPENDENT_CODE target property for executables is also honored at link time. So this module is the one that makes sure the link step also gets the memo, bestie ๐Ÿซถ

Commands

This module provides the following command:

check_pie_supported โ€” checks for PIE/NO_PIE support and prepares all executables to have link time PIE options enabled:

check_pie_supported([OUTPUT_VARIABLE <output>] [LANGUAGES <langs>...])

Options are:

  • OUTPUT_VARIABLE <output> โ€” set the <output> variable with details about any error. If the check is bypassed because it uses cached results from a previous call, the output will be empty even if errors were present in the previous call. Cached results said "we already did this", so no new tea ๐Ÿต
  • LANGUAGES <langs>... โ€” check the linkers used for each of the specified languages. If this option is not provided, the command checks all enabled languages. C, CXX, Fortran are supported. Added in version 3.23: OBJC, OBJCXX, CUDA, and HIP are supported. So many languages, so little time ๐ŸŒ
Note: To use check_pie_supported(), policy CMP0083 <#policy:CMP0083> must be set to NEW; otherwise, a fatal error will occur. Do not skip this, bestie โ€” it will literally explode ๐Ÿ’€

Variables

For each language checked, the check_pie_supported() command defines two boolean cache variables:

  • CMAKE_<lang>_LINK_PIE_SUPPORTED โ€” set to true if PIE is supported by the linker and false otherwise. PIE girlies stay winning ๐Ÿฅง
  • CMAKE_<lang>_LINK_NO_PIE_SUPPORTED โ€” set to true if NO_PIE is supported by the linker and false otherwise. NO_PIE also gets a moment, we love inclusivity ๐ŸŽ€

Examples ๐Ÿ’–

okay so bestie, if you wanna actually enable PIE on an executable target at link time too (not just compile time, no cap), you gotta include this module and call check_pie_supported() before you set that POSITION_INDEPENDENT_CODE target property. that call is the whole vibe check โ€” it figures out whether the linker for each checked language actually supports the PIE-related link options. like:

add_executable(foo ...)

include(CheckPIESupported)
check_pie_supported()
set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)

and lowkey, since not every linker even requires or supports PIE-related link options (looking at you, MSVC ๐Ÿ‘€), grabbing any error messages can be super useful for logging. like this:

add_executable(foo ...)

message(CHECK_START "Checking for C linker PIE support")

include(CheckPIESupported)
check_pie_supported(OUTPUT_VARIABLE output LANGUAGES C)
set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)

if(CMAKE_C_LINK_PIE_SUPPORTED)
  message(CHECK_PASS "yes")
else()
  message(CHECK_FAIL "no")
  message(VERBOSE "PIE is not supported at link time:\n${output}"
                  "PIE link options will not be passed to linker.")
endif()

and here's the thing โ€” if you set the POSITION_INDEPENDENT_CODE target property on an executable without using this module, you'll get the PIE-related compile options but not the PIE-related link options. which, bestie, might not be enough in certain cases ๐Ÿ˜ญ. like:

add_executable(foo ...)
set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)

๐Ÿงš CheckPrototypeDefinition

this module gives you a command to check if a C function has the prototype you expect. iconic, honestly.

load it into your CMake project with:

include(CheckPrototypeDefinition)

Commands โœจ

this module provides the following command:

check_prototype_definition

checks whether a C function has the expected prototype:

check_prototype_definition(<function> <prototype> <return> <headers> <variable>)
  • <function> โ€” the name of the function whose prototype is being checked. the main character of the operation ๐Ÿ’….
  • <prototype> โ€” the expected prototype of the function, handed to you as a string.
  • <return> โ€” the return value of the function. this gets used as the return value in the function definition body of the generated test program, so it can verify the function's return type actually matches what you expected. slay.
  • <headers> โ€” a semicolon-separated list <#cmake-language-lists> of header file names required for checking the function prototype.
  • <variable> โ€” the name of the variable that stores the check result. it gets created as an internal cache variable.

so what happens under the hood: this command generates a test program and verifies it builds without errors. the generated test program includes the specified <headers>, defines a function with the given literal <prototype> and <return> value, and then uses the specified <function>. the simplified test program looks like:

#include <headers>
// ...
<prototype> { return <return>; }
int main(...) { ...<function>()... }

Variables Affecting the Check ๐ŸŽ€

you can set these variables before calling the command to change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. a semicolon-separated list <#cmake-language-lists> will not work, bestie โ€” don't try it. the contents of CMAKE_<LANG>_FLAGS <#variable:CMAKE_<LANG>_FLAGS> and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> <#variable:CMAKE_<LANG>_FLAGS_<CONFIG>> variables get automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list <#cmake-language-lists> of compiler definitions, each either -DFOO or -DFOO=bar shaped. a definition for the name specified by the result variable argument of the check command is also added automatically โœจ.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list <#cmake-language-lists> of header search paths to pass to the compiler. heads up: these will be the only header search paths used โ€” the contents of the INCLUDE_DIRECTORIES <#prop_dir:INCLUDE_DIRECTORIES> directory property get ignored. periodt.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. a semicolon-separated list <#cmake-language-lists> of options to add to the link command (peep try_compile() <#command:try_compile> for the deets).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list <#cmake-language-lists> of libraries to add to the link command. these can be system library names, or they can be Imported Targets <#imported-targets> (again, try_compile() <#command:try_compile> has the details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. a semicolon-separated list <#cmake-language-lists> of library search paths to pass to the linker (see try_compile() <#command:try_compile> for more).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. if this variable evaluates to a boolean true value, all the status messages associated with the check get suppressed ๐Ÿคซ.

Examples ๐ŸŒธ

checking whether the getpwent_r() function on Solaris/illumos systems has the expected prototype:

include(CheckPrototypeDefinition)

check_prototype_definition(
  getpwent_r
  "struct passwd *getpwent_r(struct passwd *src, char *buf, int buflen)"
  "NULL"
  "unistd.h;pwd.h"
  HAVE_SOLARIS_GETPWENT_R
)

๐Ÿฆ‹ CheckSourceCompiles

Added in version 3.19.

this module provides a command that checks whether a chunk of source code can actually be built for a given language. extremely useful, ngl.

load it in like:

include(CheckSourceCompiles)

Commands ๐Ÿ‘‘

this module provides the following command:

check_source_compiles

checks once whether the given source code can be built for the given language:

check_source_compiles(
  <lang>
  <code>
  <variable>
  [FAIL_REGEX <regexes>...]
  [SRC_EXT <extension>]
)

this command checks once that the source supplied in <code> can be compiled (and linked into an executable) for the code language <lang>. the result of the check gets stored in an internal cache variable specified by <variable>. love that for us ๐Ÿ’œ.

the arguments are:

  • <lang> โ€” the language of the source code to check. supported languages are: C, CXX, CUDA, Fortran, HIP, ISPC, OBJC, OBJCXX, and Swift.
    • Added in version 3.21: support for the HIP language.
    • Added in version 3.26: support for the Swift language.
  • <code> โ€” the source code to check. this must be an entire program, just like you'd write in a file containing the body block. all symbols used in the source code are expected to be declared as usual in their corresponding headers.
  • <variable> โ€” variable name of an internal cache variable to store the check result, with boolean true for success and boolean false for failure. simple as that โœจ.
  • FAIL_REGEX <regexes>... โ€” if one or more regular expression patterns are provided, then failure is determined by checking whether anything in the compiler output matches any of the specified regular expressions. detective mode ๐Ÿ”.
  • SRC_EXT <extension> โ€” by default, the internal test source file used for the check gets a file extension that matches the requested language (like .c for C, .cxx for C++, .F90 for Fortran, etc.). this option overrides that with .<extension> instead.

Variables Affecting the Check ๐ŸŽ€

you can set these variables before calling the command to change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. a semicolon-separated list <#cmake-language-lists> will not work, bestie. the contents of CMAKE_<LANG>_FLAGS <#variable:CMAKE_<LANG>_FLAGS> and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> <#variable:CMAKE_<LANG>_FLAGS_<CONFIG>> variables get automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list <#cmake-language-lists> of compiler definitions, each of the form -DFOO or -DFOO=bar. a definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list <#cmake-language-lists> of header search paths to pass to the compiler. these will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES <#prop_dir:INCLUDE_DIRECTORIES> directory property get ignored.
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. a semicolon-separated list <#cmake-language-lists> of options to add to the link command (see try_compile() <#command:try_compile> for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list <#cmake-language-lists> of libraries to add to the link command. these can be the names of system libraries, or they can be Imported Targets <#imported-targets> (see try_compile() <#command:try_compile> for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. a semicolon-separated list <#cmake-language-lists> of library search paths to pass to the linker (see try_compile() <#command:try_compile> for further details).
  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1. If this variable evaluates to a boolean true value, literally every status message that'd normally come out of the check gets suppressed. silence, bestie ๐Ÿคซ๐Ÿ’…
  • CMAKE_TRY_COMPILE_TARGET_TYPE โ€” okay so under the hood the whole check is performed by the try_compile() command, and this variable decides what kind of target it makes. Set it to EXECUTABLE (that's the default, no cap) and the check compiles and links your test source into a full executable program. Set it to STATIC_LIBRARY and the test source gets compiled but not linked. that's the whole vibe ๐Ÿซถ

Example: Basic Usage

This one shows you how to use the module to check whether the C++ compiler supports a specific language feature โ€” here the check verifies if the compiler supports C++11 lambda expressions. The result lands in the internal cache variable HAVE_CXX11_LAMBDAS:

include(CheckSourceCompiles)

check_source_compiles(CXX [[
  int main()
  {
    auto lambda = []() { return 42; };
    return lambda();
  }
]] HAVE_CXX11_LAMBDAS)

Example: Checking Code With Bracket Argument

Here we're checking whether the C compiler supports the noreturn attribute. The code is supplied using the Bracket Argument, because it makes handling embedded quotes so much easier ๐Ÿ‘‘

include(CheckSourceCompiles)

check_source_compiles(C [[
  #if !__has_c_attribute(noreturn)
  #  error "No noreturn attribute"
  #endif
  int main(void) { return 0; }
]] HAVE_NORETURN)

Example: Performing a Check Without Linking

In this one the module does a compile-only check of Fortran source code โ€” does the compiler support the pure procedure attribute? Notice the CMAKE_TRY_COMPILE_TARGET_TYPE glow-up inside a block():

include(CheckSourceCompiles)

block()
  set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY")

  check_source_compiles(
    Fortran
    "pure subroutine foo()
    end subroutine"
    HAVE_PURE
  )
endblock()

Example: Isolated Check

This example teams up with the CMakePushCheckState module to swap out the required libraries while checking whether the PostgreSQL PGVerbosity enum contains PQERRORS_SQLSTATE (which is available as of PostgreSQL version 12). isolated check, contained mess, we love to see it ๐Ÿ’–

include(CheckSourceCompiles)
include(CMakePushCheckState)

find_package(PostgreSQL)

if(TARGET PostgreSQL::PostgreSQL)
  cmake_push_check_state(RESET)
    set(CMAKE_REQUIRED_LIBRARIES PostgreSQL::PostgreSQL)

    check_source_compiles(C [[
      #include <libpq-fe.h>
      int main(void)
      {
        PGVerbosity e = PQERRORS_SQLSTATE;
        (void)e;
        return 0;
      }
    ]] HAVE_PQERRORS_SQLSTATE)
  cmake_pop_check_state()
endif()

๐Ÿฆ‹ SEE ALSO ๐Ÿฆ‹

  • The CheckSourceRuns module โ€” for when you need to check whether the source code can be built and also run. ๐Ÿ‘€

๐ŸŒˆ CheckSourceRuns ๐ŸŒˆ

Added in version 3.19 โœจ

This module hands you a command to check whether some source code can be built and run. like, actually executed. icon behavior ngl ๐Ÿ”ฅ

Load this module in a CMake project with:

include(CheckSourceRuns)

๐ŸŽ€ COMMANDS ๐ŸŽ€

This module provides the following command:

  • check_source_runs โ€” checks once whether the given source code compiles and links into an executable that can subsequently be run. one shot, one check, periodt ๐Ÿ’…
check_source_runs(<lang> <code> <variable> [SRC_EXT <extension>])

So this command checks once that the <lang> source code you supplied in <code> can be built, linked as an executable, and then run. The result of the check is stored in the internal cache variable you specify with <variable>.

The arguments are:

  • <lang> โ€” the programming language of the source <code> you're checking. Supported languages are: C, CXX, CUDA, Fortran, HIP, OBJC, and OBJCXX.

Added in version 3.21: support for the HIP language.

  • <code> โ€” the source code to be tested. It must contain a valid source program. For example, it must contain at least a main() function (in C/C++), or a program unit (in Fortran). don't come in empty-handed bestie ๐Ÿ˜ญ
  • <variable> โ€” name of the internal cache variable that holds the result of the check. If the code builds and runs with exit code 0, success is indicated by a boolean true value. Failure to build or run is indicated by a boolean false value, such as an empty string or an error message.
  • SRC_EXT <extension> โ€” by default, the internal test source file used for the check gets a file extension that matches the requested language (e.g., .c for C, .cxx for C++, .F90 for Fortran, etc.). This option lets you override that with .<extension> instead. your file, your rules ๐ŸŽ€

๐ŸŒธ Variables Affecting the Check ๐ŸŒธ

The following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work โ€” fr fr, don't try it ๐Ÿ’€. The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. yeah, ignored-ignored ๐Ÿ™ˆ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” added in version 3.14. A semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1. If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. shhh ๐Ÿคซ

โœจ EXAMPLES โœจ

Example: Basic Usage

This example demonstrates how to use the module to check whether the C source code is supported and operational at runtime. The result of the check is stored in the internal cache variable HAVE_NORETURN:

include(CheckSourceRuns)

check_source_runs(C [[
  #include <stdlib.h>
  #include <stdnoreturn.h>
  noreturn void f(){ exit(0); }
  int main(void) { f(); return 1; }
]] HAVE_NORETURN)

Example: Checking Fortran Code

Checking if Fortran source code runs successfully โ€” coarrays edition ๐Ÿงš:

include(CheckSourceRuns)

check_source_runs(Fortran [[
  program test
  real :: x[*]
  call co_sum(x)
  end program
]] HAVE_COARRAY)

Example: Checking C++ Code With Bracket Argument

This one demonstrates checking whether the C++ standard library is functional and std::vector actually works at runtime. If the source compiles, links, and runs successfully, the internal cache variable HAVE_WORKING_STD_VECTOR gets set to a boolean true value. The code is supplied using the Bracket Argument for easier embedded quotes handling:

include(CheckSourceRuns)

check_source_runs(CXX [[
  #include <iostream>
  #include <vector>

  int main()
  {
    std::vector<int> v = {1, 2, 3};
    if (v.size() != 3) return 1;
    std::cout << "Vector works correctly." << std::endl;
    return 0;
  }
]] HAVE_WORKING_STD_VECTOR)

Example: Isolated Check

Here the module pairs up with the CMakePushCheckState module to modify required compile definitions and libraries while checking whether the C function sched_getcpu() is supported and operational at runtime. Because โ€” plot twist ๐Ÿ˜ญ โ€” on some systems the sched_getcpu() function may be available at compile time but not actually implemented by the kernel. In those cases it returns -1 and sets errno to ENOSYS. This check verifies that sched_getcpu() runs successfully and stores a boolean result in the internal cache variable HAVE_SCHED_GETCPU:

include(CheckSourceRuns)
include(CMakePushCheckState)

cmake_push_check_state(RESET)
  set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)

  if(CMAKE_SYSTEM_NAME STREQUAL "Haiku")
    set(CMAKE_REQUIRED_LIBRARIES gnu)
  endif()

  check_source_runs(C [[
    #include <sched.h>
    int main(void)
    {
      if (sched_getcpu() == -1) {
        return 1;
      }
      return 0;
    }
  ]] HAVE_SCHED_GETCPU)
cmake_pop_check_state()

๐Ÿฆ‹ SEE ALSO ๐Ÿฆ‹

  • The CheckSourceCompiles module โ€” for when you just need to check whether a source code can be built. ๐Ÿ”จ

๐Ÿงš CheckStructHasMember ๐Ÿงš

This module provides a command to check whether a struct or class has a specified member variable. very "do you have this field tho" energy ๐Ÿ‘‘

Load this module in a CMake project with:

include(CheckStructHasMember)

๐Ÿ’… Commands

okay so this module hands you exactly one command, and honestly? it's a good one:

check_struct_has_member

it checks once whether the struct or class you point at has the member variable you're looking for. one and done. no cap:

check_struct_has_member(
  <struct>
  <member>
  <headers>
  <variable>
  [LANGUAGE <language>]
)

so what it does: it checks once whether the struct or class <struct> actually contains the specified <member>, after it includes the header(s) <headers> โ€” the place where the prototype is supposed to be declared, bestie. and like, you can pass multiple header files in one single argument as a string using a semicolon-separated list. the result gets stashed in an internal cache variable <variable>. ๐Ÿซถ

the options are:

  • LANGUAGE <language> โ€” uses the <language> compiler to run the check. acceptable values are C and CXX. if you don't say anything, it defaults to C. no judgment, C is a vibe.

Variables Affecting the Check ๐ŸŽ€

these variables can be set before you call the command to change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to pass to the compiler. real talk: a semicolon-separated list will not work here. the contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables get automatically prepended to the compiler command before the contents of this variable. so your flags are like, second in line. โœจ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one shaped like -DFOO or -DFOO=bar. a definition for the name specified by the result variable argument of the check command also gets added automatically. free of charge. ๐Ÿ’…
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. and listen: these will be the only header search paths used. the contents of the INCLUDE_DIRECTORIES directory property get ignored entirely. it's giving main character energy, honestly. ๐Ÿ‘‘
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. a semicolon-separated list of options to add to the link command (peep try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. these can be the names of system libraries, or they can be Imported Targets (again, try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. a semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. if this variable evaluates to a boolean true value, all status messages associated with the check get suppressed. silence. peace. ๐Ÿคซ

๐ŸŒธ Examples

Example: Checking C Struct Member

in this one, the module checks if the C struct timeval has a member variable tv_sec after including the <sys/select.h> header. the result lands in the internal cache variable HAVE_TIMEVAL_TV_SEC. she ate:

include(CheckStructHasMember)

check_struct_has_member(
  "struct timeval"
  tv_sec
  sys/select.h
  HAVE_TIMEVAL_TV_SEC
)

Example: Checking C++ Struct Member

here we're checking if the C++ struct std::tm has a member variable tm_gmtoff after including the <ctime> header. result goes into HAVE_TM_GMTOFF. note the LANGUAGE CXX โ€” you gotta say it, C is the default remember? ๐Ÿ˜Œ

include(CheckStructHasMember)

check_struct_has_member(
  std::tm
  tm_gmtoff
  ctime
  HAVE_TM_GMTOFF
  LANGUAGE CXX
)

Example: Isolated Check With Compile Definitions

this one does the check with temporarily modified compile definitions, using the CMakePushCheckState module. push, set, check, pop. clean. iconic. ๐Ÿฆ‹

include(CheckStructHasMember)
include(CMakePushCheckState)

cmake_push_check_state(RESET)
  set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)

  check_struct_has_member(
    "struct utsname"
    domainname
    sys/utsname.h
    HAVE_UTSNAME_DOMAINNAME
  )
cmake_pop_check_state()

๐Ÿ’œ CheckSymbolExists

this module provides a command to check whether a C symbol exists. that's literally the whole vibe.

load this module in a CMake project with:

include(CheckSymbolExists)

Commands

this module provides the following command:

check_symbol_exists

checks once whether a symbol exists as a function, variable, or preprocessor macro in C:

check_symbol_exists(<symbol> <headers> <variable>)

so it checks whether <symbol> is available after including the specified header file(s) <headers>, and stores the result in the internal cache variable <variable>. multiple header files can be specified in one argument as a string using a semicolon-separated list. ๐Ÿ’–

here's the nuanced part, don't skip it:

  • if the header files define the symbol as a macro, it's considered available and assumed to work.
  • if the symbol is declared as a function or variable, the check also makes sure it links successfully โ€” like, the symbol must exist in a linked library or object file. fr fr.
  • compiler intrinsics may not be detected, because they're not always linkable or explicitly declared in headers. ๐Ÿ˜ญ

symbols that are types, enum values, or compiler intrinsics are not recognized. for those, consider using the CheckTypeSize or CheckSourceCompiles module instead. consider it a redirect, bestie.

also important: this command is intended to check symbols as they appear in C. for C++ symbols, use the CheckCXXSymbolExists module instead. different language, different module. okurrr.

Variables Affecting the Check

the following variables may be set before calling this command to modify the way the check is run:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. a semicolon-separated list will not work. the contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable. โœจ
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each of the form -DFOO or -DFOO=bar. a definition for the name specified by the result variable argument of the check command is also added automatically.
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. these will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property will be ignored. ๐Ÿซถ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. a semicolon-separated list of options to add to the link command (see try_compile() for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. these can be the names of system libraries, or they can be Imported Targets (see try_compile() for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. a semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. if this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed. ๐Ÿคซ

Examples

this example shows you how to check for a preprocessor macro SEEK_SET and the C function fopen() from the <stdio.h> header, all with this module. two checks, one include, slay:

include(CheckSymbolExists)

# Check for macro SEEK_SET
check_symbol_exists(SEEK_SET "stdio.h" HAVE_SEEK_SET)

# Check for function fopen
check_symbol_exists(fopen "stdio.h" HAVE_FOPEN)

See Also

  • the CheckCXXSymbolExists module โ€” for when you need to check whether a C++ symbol exists. ๐Ÿ’…

๐ŸŽ€ CheckTypeSize

this module provides a command to check the size of a C/C++ type or expression. yes, expression. she's flexible.

load this module in a CMake project with:

include(CheckTypeSize)

Commands

this module provides the following command:

check_type_size

checks once whether the C/C++ type or expression exists, and then determines its size:

check_type_size(
  <type>
  <size-var>
  [RESULT_VARIABLE <result-var>]
  [BUILTIN_TYPES_ONLY]
  [LANGUAGE <language>]
)

the arguments are:

  • <type> โ€” the type or expression being checked. ๐Ÿ‘€
  • <size-var> โ€” the name of the internal cache variable for storing the size of the type or expression <type>. this name is also used as a prefix, as explained below. remember that, it comes back around. ๐Ÿ”ฅ
  • RESULT_VARIABLE <result-var> โ€” Added in version 4.2.
  • RESULT_VARIABLE <result-var> โ€” the name of the internal cache variable that holds a boolean value telling you whether the type or expression <type> exists. If you don't give it, the command just goes ahead and defines an internal cache variable named HAVE_<size-var> by default instead ๐Ÿ’…
  • BUILTIN_TYPES_ONLY โ€” if you pass this, only compiler-builtin types get supported in the check. If you don't pass it, the command also checks for the common headers <sys/types.h>, <stdint.h>, and <stddef.h>, and saves the results in the HAVE_SYS_TYPES_H, HAVE_STDINT_H, and HAVE_STDDEF_H internal cache variables. And for C++ std:: types, <cstdint> and <cstddef> are checked too, with HAVE_CSTDINT and HAVE_CSTDDEF defined respectively. The command automatically includes the available headers in the type size check, which is how it supports checking types that are defined in those headers ๐Ÿซถ
  • LANGUAGE <language> โ€” uses the <language> compiler to run the check. Acceptable values are C and CXX. If you don't specify, it defaults to C, no cap โœจ

๐ŸŽ€ Result Variables ๐ŸŽ€

Results get reported in these variables, bestie:

  • <size-var> โ€” internal cache variable that holds one of the following values:
    • <size> โ€” if the type or expression <type> exists, it'll have a non-zero size <size> in bytes ๐Ÿ’–
    • 0 โ€” when the type has an architecture-dependent size. This can happen when CMAKE_OSX_ARCHITECTURES has multiple architectures. In that case the <size-var>_KEYS variable is also defined, and the <size-var>_CODE variable contains preprocessor tests mapping, as explained down below ๐Ÿ‘‡
    • "" (empty string) โ€” when the type or expression <type> does not exist ๐Ÿ˜ญ
  • HAVE_<size-var> โ€” internal cache variable holding a boolean value indicating whether the type or expression <type> exists. This variable gets defined when the RESULT_VARIABLE argument is not used.
  • <result-var> โ€” added in version 4.2. Internal cache variable defined when the RESULT_VARIABLE argument is used. It holds a boolean value indicating whether the type or expression <type> exists (same value as HAVE_<size-var>). In this case, the HAVE_<size-var> variable is not defined. It's giving "one or the other, never both" ๐Ÿฆ‹
  • <size-var>_CODE โ€” CMake variable that holds preprocessor code to define the macro <size-var> to the size of the type, or to leave the macro undefined if the type doesn't exist.

When the type has an architecture-dependent size (<size-var> value is 0), this variable contains preprocessor tests mapping from each architecture macro to the corresponding type size ๐Ÿ”ฅ

  • <size-var>_KEYS โ€” CMake variable that's defined only when the type has an architecture-dependent size (<size-var> value is 0), and it contains a list of architecture macros. The value for each key is stored in <size-var>-<key> variables.

๐Ÿ” Variables Affecting the Check ๐Ÿ”

You can set these variables before calling this command to change how the check runs:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list will not work, so don't try it ๐Ÿ™ˆ The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> variables are automatically prepended to the compiler command before the contents of this variable, though.
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one in the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command also gets added automatically โœจ
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list of header search paths to pass to the compiler. Heads up: these will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES directory property get ignored ๐Ÿ’€
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” added in version 3.14. A semicolon-separated list of options to add to the link command (peep try_compile() for more deets).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets (again, try_compile() has the full tea โ˜•).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” added in version 3.31. A semicolon-separated list of library search paths to pass to the linker (see try_compile() for further details).
  • CMAKE_REQUIRED_QUIET โ€” added in version 3.1. If this variable evaluates to a boolean true value, all the status messages associated with the check get suppressed ๐Ÿคซ
  • CMAKE_EXTRA_INCLUDE_FILES โ€” a semicolon-separated list of extra header files to include when performing the check.

๐ŸŒธ Examples ๐ŸŒธ

Consider this code, bestie:

include(CheckTypeSize)

# Check for size of long.
check_type_size(long SIZEOF_LONG)

message("HAVE_SIZEOF_LONG: ${HAVE_SIZEOF_LONG}")
message("SIZEOF_LONG: ${SIZEOF_LONG}")
message("SIZEOF_LONG_CODE: ${SIZEOF_LONG_CODE}")

On a 64-bit architecture, the output may look something like this:

HAVE_SIZEOF_LONG: TRUE
SIZEOF_LONG: 8
SIZEOF_LONG_CODE: #define SIZEOF_LONG 8

On Apple platforms, when CMAKE_OSX_ARCHITECTURES has multiple architectures, types may have architecture-dependent sizes. For example, with this code:

include(CheckTypeSize)

check_type_size(long SIZEOF_LONG)

message("HAVE_SIZEOF_LONG: ${HAVE_SIZEOF_LONG}")
message("SIZEOF_LONG: ${SIZEOF_LONG}")
foreach(key IN LISTS SIZEOF_LONG_KEYS)
  message("key: ${key}")
  message("value: ${SIZEOF_LONG-${key}}")
endforeach()
message("SIZEOF_LONG_CODE:\n${SIZEOF_LONG_CODE}")

the result may be:

HAVE_SIZEOF_LONG: TRUE
SIZEOF_LONG: 0
key: __i386
value: 4
key: __x86_64
value: 8
SIZEOF_LONG_CODE:
#if defined(__i386)
# define SIZEOF_LONG 4
#elif defined(__x86_64)
# define SIZEOF_LONG 8
#else
# error SIZEOF_LONG unknown
#endif

Example: Configuration Header ๐ŸŒˆ

The next example demonstrates how the result variables can be used in a configuration header:

include(CheckTypeSize)
check_type_size(long SIZEOF_LONG)

configure_file(config.h.in config.h @ONLY)

config.h.in

/* Define whether the type 'long' exists. */
#cmakedefine HAVE_SIZEOF_LONG

/* The size of 'long', as computed by sizeof. */
@SIZEOF_LONG_CODE@

Example: Checking Complex Expressions ๐Ÿ‘‘

Despite the name of this module, you can also use it to determine the size of more complex expressions. For example, to check the size of a struct member:

include(CheckTypeSize)
check_type_size("((struct something*)0)->member" SIZEOF_MEMBER)

Example: Isolated Check ๐Ÿงš

In the following example, the check is performed with temporarily modified additional headers, using the CMAKE_EXTRA_INCLUDE_FILES variable and the CMakePushCheckState module. The result of the check is stored in HAVE_SIZEOF_UNION_SEMUN, and the size is stored in SIZEOF_UNION_SEMUN internal cache variables.

include(CheckTypeSize)
include(CMakePushCheckState)

cmake_push_check_state(RESET)
  set(CMAKE_EXTRA_INCLUDE_FILES sys/types.h sys/ipc.h sys/sem.h)
  check_type_size("union semun" SIZEOF_UNION_SEMUN)
cmake_pop_check_state()

Example: Customizing Result Variable ๐ŸŽ€

Since CMake 4.2, you can customize the HAVE_<size-var> variable name using the RESULT_VARIABLE argument. In the following example, this module is used to check whether the struct flock exists, and the result is stored in the MyProj_HAVE_STRUCT_FLOCK internal cache variable:

cmake_minimum_required(VERSION 4.2)

# ...

include(CheckTypeSize)
include(CMakePushCheckState)

cmake_push_check_state(RESET)
  set(CMAKE_EXTRA_INCLUDE_FILES "fcntl.h")

  check_type_size(
    "struct flock"
    MyProj_SIZEOF_STRUCT_FLOCK
    RESULT_VARIABLE MyProj_HAVE_STRUCT_FLOCK
  )
cmake_pop_check_state()

๐Ÿ’œ CheckVariableExists ๐Ÿ’œ

This module provides a command to check whether a C variable exists.

Load this module in a CMake project with:

include(CheckVariableExists)

โœจ Commands โœจ

This module provides the following command:

check_variable_exists

Checks once if a C variable exists:

check_variable_exists(<var> <variable>)

This command attempts to compile and link a test C program that references the specified C variable <var>. A boolean result of whether the check was successful gets stored in an internal cache variable <variable> ๐Ÿซถ

Note: prefer using CheckSymbolExists or CheckSourceCompiles instead of this command for more robust detection, ngl. This command performs a link-only check and doesn't detect whether a variable is also declared in system or library headers. Neither can it detect variables that might be defined as preprocessor macros ๐Ÿ˜ญ

๐ŸŒŸ Variables Affecting the Check ๐ŸŒŸ

(the deets keep going from here, bestie โ€” stay with me ๐Ÿ’…)

okay so before you even call this command, you can set any of these variables to change how the check runs โ€” think of them as the settings you tweak first, no cap:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of extra flags to hand to the compiler. โš ๏ธ heads up: a semicolon-separated list will not work, so please don't try it bestie. also the contents of CMAKE_<LANG>_FLAGS and its configuration-specific bestie CMAKE_<LANG>_FLAGS_<CONFIG> get automatically prepended to the compiler command before whatever you put in this variable. it's giving "the compiler already has opinions before you even speak". ๐Ÿ’…
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list of compiler definitions, each one shaped like -DFOO or -DFOO=bar. and yes, a definition for the name given by the result variable argument of the check command also gets added automatically, because the module is an overachiever like that. โœจ
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. a semicolon-separated list of options to add to the link command (peep try_compile() for the further details, iykyk).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list of libraries to add to the link command. these can be the names of system libraries, or they can be Imported Targets (again, try_compile() has the details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31. a semicolon-separated list of library search paths to pass to the linker (details in try_compile(), you know the drill).
  • CMAKE_REQUIRED_QUIET โ€” Added in version 3.1. if this variable evaluates to a boolean true value, all the status messages associated with the check get suppressed. it's giving "mute the group chat while I think". ๐Ÿคซ

โœจ Examples โœจ

Example: Basic Usage

in the following example, a check is performed whether the linker sees the C variable tzname and stores the check result in the PROJECT_HAVE_TZNAME internal cache variable:

include(CheckVariableExists)

check_variable_exists(tzname PROJECT_HAVE_TZNAME)

Example: Isolated Check With Linked Libraries

in the following example, this module is used in combination with the CMakePushCheckState module to link an additional required library using the CMAKE_REQUIRED_LIBRARIES variable. for example, in a find module, to check whether the Net-SNMP library has the usmHMAC192SHA256AuthProtocol array:

include(CheckVariableExists)
include(CMakePushCheckState)

find_library(SNMP_LIBRARY NAMES netsnmp)

if(SNMP_LIBRARY)
  cmake_push_check_state(RESET)

  set(CMAKE_REQUIRED_LIBRARIES ${SNMP_LIBRARY})

  check_variable_exists(usmHMAC192SHA256AuthProtocol SNMP_HAVE_SHA256)

  cmake_pop_check_state()
endif()

๐ŸŒธ See Also ๐ŸŒธ

  • the CheckSymbolExists module, for checking whether a C symbol exists. sibling energy fr.

๐Ÿฆ‹ CMakeAddFortranSubdirectory ๐Ÿฆ‹

this module provides a command to add a Fortran project that lives in a subdirectory. yes, Fortran. it's iconic, it's vintage, it's still running half the scientific world. periodt. ๐Ÿ’œ

load this module in a CMake project with:

include(CMakeAddFortranSubdirectory)

โœจ Commands โœจ

this module provides the following command:

cmake_add_fortran_subdirectory โ€” adds a Fortran-only subproject from subdirectory to the current project:

cmake_add_fortran_subdirectory(
  <subdir>
  PROJECT <project-name>
  ARCHIVE_DIR <dir>
  RUNTIME_DIR <dir>
  LIBRARIES <libs>...
  LINK_LIBRARIES
    [LINK_LIBS <lib> <deps>...]...
  [CMAKE_COMMAND_LINE <flags>...]
  NO_EXTERNAL_INSTALL
)

this command checks whether the current compiler supports Fortran, or attempts to locate a Fortran compiler. if a compatible Fortran compiler is found, the Fortran project located in <subdir> is added as a subdirectory to the current project. slay. ๐ŸŽ€

if no Fortran compiler is found and the compiler is MSVC, it searches for the MinGW gfortran compiler. in this case, the Fortran project is built as an external project using MinGW tools, and Fortran-related imported targets are created. ngl this setup works only if the Fortran code is built as a shared DLL library, so the BUILD_SHARED_LIBS variable is enabled in the external project. additionally, the CMAKE_GNUtoMS variable is set to ON to ensure that Microsoft-compatible .lib files are created. look at it adapting, main character energy honestly.

the options are:

  • PROJECT โ€” the name of the Fortran project as defined in the top-level CMakeLists.txt located in <subdir>.
  • ARCHIVE_DIR โ€” directory where the project places .lib archive files. a relative path is interpreted as relative to CMAKE_CURRENT_BINARY_DIR.
  • RUNTIME_DIR โ€” directory where the project places .dll runtime files. a relative path is interpreted as relative to CMAKE_CURRENT_BINARY_DIR. (yes, same rule as above, they're matching.) ๐Ÿ’…
  • LIBRARIES โ€” names of library targets to create or import into the current project.
  • LINK_LIBRARIES โ€” specifies link interface libraries for LIBRARIES. this option expects a list of LINK_LIBS <lib> <deps>... items, where:
    • LINK_LIBS marks the start of a new pair
    • <lib> is a library target
    • <deps>... represents one or more dependencies required by <lib>
  • CMAKE_COMMAND_LINE โ€” additional command-line flags passed to the cmake(1) command when configuring the Fortran subproject.
  • NO_EXTERNAL_INSTALL โ€” prevents installation of the external project.
note: the NO_EXTERNAL_INSTALL option is required for forward compatibility with a future version that supports installation of the external project binaries during make install. so like, don't skip it, it's future-proofing and it's free. ๐Ÿซถ

๐Ÿ”ฅ Examples ๐Ÿ”ฅ

adding a Fortran subdirectory to a project can be done by including this module and calling the cmake_add_fortran_subdirectory() command. in the following example, a Fortran project provides the hello library and its dependent world library:

include(CMakeAddFortranSubdirectory)

cmake_add_fortran_subdirectory(
  fortran-subdir
  PROJECT FortranHelloWorld
  ARCHIVE_DIR lib
  RUNTIME_DIR bin
  LIBRARIES hello world
  LINK_LIBRARIES
    LINK_LIBS hello world # hello library depends on the world library
  NO_EXTERNAL_INSTALL
)

# The Fortran target can be then linked to the main project target.
add_executable(main main.c)
target_link_libraries(main PRIVATE hello)

the way hello depends on world and it all justโ€ฆ links. we love a functional build. ๐ŸŒˆ

โญ See Also โญ

there are multiple ways to integrate Fortran libraries. alternative approaches include:

  • the add_subdirectory() command, to add the subdirectory directly to the build.
  • the export() command can be used in the subproject to provide Imported Targets or similar for integration with other projects.
  • the FetchContent or ExternalProject modules when working with external dependencies.

๐Ÿ’– CMakeBackwardCompatibilityCXX ๐Ÿ’–

this module defines several backward compatibility cache variables for the CXX language to support early C++ (pre-C++98, ANSI C++). it's giving "digging up the archives", and honestly? respect. ๐ŸŽ€

load this module in a CMake project with:

include(CMakeBackwardCompatibilityCXX)

the following modules are included by this module:

  • TestForANSIForScope
  • TestForANSIStreamHeaders
  • TestForSSTREAM
  • TestForSTDNamespace

additionally, the following cache variable may be defined:

  • CMAKE_ANSI_CXXFLAGS โ€” a space-separated string of compiler options for enabling ANSI C++ mode, if available.
note: this module is intended for C++ code written before C++ 98. as of the C++ 98 standard, these issues have been formally addressed, making such checks obsolete. so likeโ€ฆ it's a museum piece bestie, visit it but don't move in. ๐Ÿ’€

๐ŸŒธ Examples ๐ŸŒธ

including this module provides backward compatibility cache variables, which can be used in C++. for example:

CMakeLists.txt

include(CMakeBackwardCompatibilityCXX)
file(
  CONFIGURE
  OUTPUT config.h
  CONTENT [[
    #cmakedefine CMAKE_NO_ANSI_FOR_SCOPE
    #cmakedefine CMAKE_NO_ANSI_STRING_STREAM
    #cmakedefine CMAKE_NO_ANSI_STREAM_HEADERS
    #cmakedefine CMAKE_NO_STD_NAMESPACE
  ]]
)

๐Ÿฆ‹ CMakeDependentOption ๐Ÿฆ‹

this module provides a command to define boolean options whose availability and default values depend on specified conditions or other options. it helps keep your configuration interface clean by only showing the options that are actually relevant to the current settings. it's giving "curated feed" and honestly the GUI needed it. โœจ

load this module in CMake with:

include(CMakeDependentOption)

โœจ Commands โœจ

this module provides the following command:

cmake_dependent_option โ€” provides a boolean option that depends on a set of conditions:

cmake_dependent_option(<variable> <help> <value> <condition> <else-value>)

this command creates a boolean <variable> and makes it available to the user in the GUI (such as cmake-gui(1) or ccmake(1)), if a set of conditions evaluates to boolean true. conditional visibility? we stan. ๐Ÿ‘‘

the arguments are:

  • <variable> โ€” the name of a variable that stores the option value.
  • <help> โ€” a brief description of the option. this string is typically a short line of text and is displayed in the GUI.
  • <value> โ€” boolean value for the <variable>, when <condition> evaluates to boolean true.

<condition> ๐ŸŒธ โ€” the thing that decides whether <variable> gets set and shows up in the GUI. Basically a vibe check for your option:

  • If <condition> evaluates to boolean false, the option is hidden from the user in the GUI, and a local variable <variable> is set to <else-value>.
  • If <condition> evaluates to boolean true, a boolean cache variable named <variable> is created with default <value>, and the option is shown in the GUI, letting the user enable or disable it. โœจ
  • If <condition> later evaluates to boolean false (on a consecutive configuration run), the option is hidden from the user in the GUI and the <variable> type is changed to an internal cache variable. In that case, a local variable of the same name is set to <else-value>.
  • If <condition> becomes true again in consecutive configuration runs, the user's previously set value is preserved. ๐Ÿ’–

The <condition> argument can be:

  • A single condition (such as a variable name).
  • A semicolon-separated list of multiple conditions.
  • Added in version 3.22: a full Condition Syntax, exactly like the one used in an if(<condition>) clause. See policy CMP0127. This unlocks the whole condition syntax โ€” yes, even grouping conditions with parens and all that cute stuff. ๐ŸŽ€

<else-value> โ€” the value that gets assigned to a local variable named <variable> whenever <condition> evaluates to boolean false.

Ok so important: in CMake project mode, boolean cache variables are created the way we just described. In CMake script mode, boolean variables are just set instead. Different mode, different move. ๐Ÿ’…

Examples

Example: Basic Usage

Using this module in a project to conditionally set an option:

CMakeLists.txt

include(CMakeDependentOption)

cmake_dependent_option(USE_SSL_GNUTLS "Use GnuTLS for SSL" ON USE_SSL OFF)

Example: Enabling/Disabling Dependent Option

Extending the previous example, this shows how the module gives you user-configurable options based on a condition during the configuration phase:

CMakeLists.txt

include(CMakeDependentOption)

option(USE_SSL "Enable SSL in the project" OFF)

cmake_dependent_option(USE_SSL_GNUTLS "Use GnuTLS for SSL" ON USE_SSL OFF)

message(STATUS "USE_SSL: ${USE_SSL}")
message(STATUS "USE_SSL_GNUTLS: ${USE_SSL_GNUTLS}")

On the first configuration run, a boolean cache variable USE_SSL is set to OFF, and a local variable USE_SSL_GNUTLS is set to OFF:

$ cmake -B build-dir

-- USE_SSL: OFF
-- USE_SSL_GNUTLS: OFF

Running CMake with USE_SSL=ON sets both USE_SSL and USE_SSL_GNUTLS boolean cache variables to ON:

$ cmake -B build-dir -D USE_SSL=ON

-- USE_SSL: ON
-- USE_SSL_GNUTLS: ON

On a subsequent configuration run with USE_SSL=OFF, USE_SSL_GNUTLS follows suit. But!! its value is preserved in the internal cache while being overridden locally:

$ cmake -B build-dir -D USE_SSL=OFF

-- USE_SSL: OFF
-- USE_SSL_GNUTLS: OFF

Example: Semicolon-separated List of Conditions

The <condition> argument can also be a semicolon-separated list of conditions. In the example below, if the variable USE_BAR is ON and the variable USE_ZOT is OFF, the option USE_FOO is available and defaults to ON. Otherwise, USE_FOO is set to OFF and hidden from the user.

If the values of USE_BAR or USE_ZOT change in future configuration runs, the previous value of USE_FOO is preserved, so that when it becomes available again it retains its last set value. ๐Ÿซถ

CMakeLists.txt

include(CMakeDependentOption)

cmake_dependent_option(USE_FOO "Use Foo" ON "USE_BAR;NOT USE_ZOT" OFF)

Example: Full Condition Syntax

As of CMake 3.22, cmake_dependent_option() supports full condition syntax. ๐Ÿ‘‘

In the following example, if the condition evaluates to true, the option USE_FOO is available and set to ON. Otherwise, it's set to OFF and hidden in the GUI. The value of USE_FOO is preserved across configuration runs, similar to the previous example.

CMakeLists.txt

include(CMakeDependentOption)

cmake_dependent_option(USE_FOO "Use Foo" ON "USE_A AND (USE_B OR USE_C)" OFF)

Another example showing how an option can be conditionally available based on the target system:

CMakeLists.txt

include(CMakeDependentOption)

cmake_dependent_option(
  ENABLE_FOO
  "Enable feature Foo (this option is available when building for Windows)"
  ON
  [[CMAKE_SYSTEM_NAME STREQUAL "Windows"]]
  OFF
)

See Also

  • The option() command, for providing a boolean option that the user can optionally select.

๐Ÿฆ‹ CMakeFindDependencyMacro

This module hands you a command implemented as a macro that finds a dependency for a package. Iconic behaviour, tbh.

Load this module in a CMake package configuration file with:

FooConfig.cmake or foo-config.cmake:

include(CMakeFindDependencyMacro)
Note: This module is designed to be used in a Package Configuration File (<PackageName>Config.cmake).

Commands

This module provides the following command:

find_dependency

The find_dependency() macro wraps a find_package() call for a package dependency:

find_dependency(<dep> [...])

It's designed to be used in a Package Configuration File (<PackageName>Config.cmake). find_dependency forwards the correct parameters for QUIET and REQUIRED that were passed to the original find_package() call. Any additional arguments you specify get forwarded to find_package() too. โœจ

If the dependency could not be found, it sets an informative diagnostic message and calls return() to end processing of the calling package configuration file and return to the find_package() command that loaded it.

Note: That call to return() is exactly why this macro is not suitable to call from Find Modules. Important!!

Package Dependency Search Optimizations

If find_dependency is called with arguments identical to a previous call in the same directory โ€” maybe because of diamond-shaped package dependencies โ€” the underlying call to find_package() is optimized out. This optimization is lowkey important: it supports large package dependency graphs while avoiding a combinatorial explosion of repeated searches. But the heuristic can't account for ambient variables that affect package behavior, like <PackageName>_USE_STATIC_LIBS, which some packages offer. So package configuration files should avoid setting such variables before their calls to find_dependency. ๐Ÿ’€

Changed in version 3.15: Previously, the underlying call to find_package() was always optimized out if the package had already been found. CMake 3.15 removed that optimization to support cases where find_dependency call arguments request different components.

Changed in version 3.26: The pre-3.15 optimization was restored, but with the above-described heuristic so varying find_dependency call arguments are accounted for. ๐ŸŽ€


๐Ÿ’œ CMakePackageConfigHelpers

This module provides helper commands for creating config files that other projects can include to find and use a package.

Load this module in a CMake project with:

include(CMakePackageConfigHelpers)

Generating a Package Configuration File

configure_package_config_file

Create a config file for a project:

configure_package_config_file(<input> <output>
  INSTALL_DESTINATION <path>
  [PATH_VARS <var1> <var2> ... <varN>]
  [NO_SET_AND_CHECK_MACRO]
  [NO_CHECK_REQUIRED_COMPONENTS_MACRO]
  [INSTALL_PREFIX <path>]
  )

You should use configure_package_config_file() instead of the plain configure_file() command whenever you create the <PackageName>Config.cmake or <PackageName>-config.cmake file for installing a project or library. Why? Because it helps make the resulting package relocatable by avoiding hardcoded paths in the installed <PackageName>Config.cmake file. Slay. ๐ŸŒˆ

In a FooConfig.cmake file there may be code like this to make the install destinations known to the using project:

set(FOO_INCLUDE_DIR   "@CMAKE_INSTALL_FULL_INCLUDEDIR@" )
set(FOO_DATA_DIR   "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" )
set(FOO_ICONS_DIR   "@CMAKE_INSTALL_PREFIX@/share/icons" )
#...logic to determine installedPrefix from the own location...
set(FOO_CONFIG_DIR  "${installedPrefix}/@CONFIG_INSTALL_DIR@" )

All four options shown above are not sufficient. ๐Ÿ˜ญ The first three hardcode the absolute directory locations. The fourth case works only if the logic to determine the installedPrefix is correct, and if CONFIG_INSTALL_DIR contains a relative path โ€” which in general cannot be guaranteed. The effect of all this is that the resulting FooConfig.cmake file would work poorly under Windows and macOS, where users are used to choosing the install location of a binary package at install time, independent from how CMAKE_INSTALL_PREFIX was set at build/cmake time.

Using configure_package_config_file() helps. If used correctly, it makes the resulting FooConfig.cmake file relocatable. Usage:

  1. Write a FooConfig.cmake.in file as you are used to.
  2. Insert a line at the top containing only the string @PACKAGE_INIT@.
  3. Instead of set(FOO_DIR "@SOME_INSTALL_DIR@"), use set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@") (this must be after the @PACKAGE_INIT@ line).
  4. Instead of using the normal configure_file() command, use configure_package_config_file().

The <input> and <output> arguments are the input and output file, the same way as in configure_file(). ๐Ÿ’–

The <path> given to INSTALL_DESTINATION must be the destination where the FooConfig.cmake file will be installed to. This path can either be absolute, or relative to the INSTALL_PREFIX path.

The variables <var1> to <varN> that you hand over as PATH_VARS are the ones holding your install destinations, okay? For each of them the macro spins up a lil helper variable called PACKAGE_<var...> โ€” and those helper variables are literally the whole point, you have to use them in your FooConfig.cmake.in file when you set the installed location. They get calculated by configure_package_config_file() so they're always relative to wherever the package actually landed. Works for relative locations and absolute ones ๐Ÿซถ โ€” but absolute only slays if the absolute location is a subdirectory of INSTALL_PREFIX. That's the catch, bestie.

Added in version 3.30: the variable PACKAGE_PREFIX_DIR is always defined after the @PACKAGE_INIT@ line. It holds the value of the base install location. Generally you should be using the variables defined through the PATH_VARS mechanism instead, but PACKAGE_PREFIX_DIR is there for the cases PATH_VARS can't easily handle โ€” like files installed straight into the base install location instead of some subdirectory of it. ๐Ÿ™ˆ

Note: when consumers of the generated file are on CMake 3.29 or older, the value of PACKAGE_PREFIX_DIR can get changed by a call to find_dependency() or find_package(). So if your project relies on PACKAGE_PREFIX_DIR, it is the project's responsibility to make sure that value is preserved across any such calls โ€” or any other calls that might pull in another file generated by configure_package_config_file(). No cap, guard it. ๐Ÿ’…

Added in version 3.1: if you pass the INSTALL_PREFIX argument, it gets used as the base path for calculating all the relative paths. The <path> argument has to be an absolute path, no exceptions. If you don't pass it, the CMAKE_INSTALL_PREFIX variable is used instead. The default value is a vibe when you're generating a FooConfig.cmake file to use your package from the install tree โ€” but when you're generating one to use your package from the build tree, you should definitely pass this option. โœจ

By default, configure_package_config_file() also generates two helper macros into the FooConfig.cmake file: set_and_check() and check_required_components().

set_and_check() should be used instead of the normal set() command whenever you're setting directories and file locations. Besides setting the variable, it also checks that the file or directory you referenced actually exists and fails with a fatal error if it doesn't ๐Ÿ˜ญ โ€” which is exactly how you keep your generated FooConfig.cmake file from containing wrong references. Add the NO_SET_AND_CHECK_MACRO option to stop the set_and_check() macro from being generated into the FooConfig.cmake file.

check_required_components(<PackageName>) should be called at the end of the FooConfig.cmake file. This macro checks whether all the requested, non-optional components have been found, and if not, it sets the Foo_FOUND variable to FALSE so the package is considered not found. It does that by testing the Foo_<Component>_FOUND variables for all requested required components. Call this macro even if your package doesn't provide any components, so users can't erroneously specify components and get away with it. ๐Ÿšจ Add the NO_CHECK_REQUIRED_COMPONENTS_MACRO option to stop the check_required_components() macro from being generated in the FooConfig.cmake file.

See also Example Generating Package Files. ๐Ÿ‘‘


๐ŸŽ€ Generating a Package Version File ๐ŸŽ€

write_basic_package_version_file โ€” creates a version file for a project, iconic behaviour only:

write_basic_package_version_file(<filename>
  [VERSION <major.minor.patch>]
  COMPATIBILITY <AnyNewerVersion|SameMajorVersion|SameMinorVersion|
                 SamePatchVersion|SameFullVersion|SemanticVersion|
                 ExactVersion>
  [ARCH_INDEPENDENT] )

Writes a file to <filename> for use as a <PackageName>ConfigVersion.cmake file. Check the docs for find_package() if you wanna know the details on files like this. โœจ

<filename> is the output filename, and it should be in the build tree. <major.minor.patch> is the version number of the project you're installing.

If you don't give a VERSION, the PROJECT_VERSION variable gets used. And if that hasn't been set? It errors out. Periodt. ๐Ÿ’€

The COMPATIBILITY modes, from least to most picky โ€” buckle up:

  • The AnyNewerVersion mode means the installed package version is considered compatible if it's newer than or exactly the same as the requested version. Use this one for packages that are fully backward compatible, even across major versions.
  • If SameMajorVersion is used instead, the behavior differs from AnyNewerVersion in that the major version number must be the same as requested โ€” e.g. version 2.0 will not be considered compatible if 1.0 is requested. Use this for packages that guarantee backward compatibility within the same major version.
  • If SameMinorVersion is used, the behavior is the same as SameMajorVersion, but both major and minor version have to be the same as requested โ€” e.g. version 0.2 will not be compatible if 0.1 is requested.
  • If SamePatchVersion is used, the package is only considered compatible if the requested version matches exactly through the patch version, ignoring any tweak version. For example, version 1.2.3.4 of a package is considered compatible with requested version 1.2.3.5, but not with requested version 1.2.4.
  • If SameFullVersion is used, the package is only considered compatible if the requested version matches exactly through all specified version components. For example, version 1.2.3.4 of a package is only considered compatible with requested version 1.2.3.4. Missing version components are not treated as implicit zeroes, so version 1.2.3 is not considered compatible with requested version 1.2.3.0. ๐Ÿซ 
  • If SemanticVersion is used, behavior follows the usual semantic versioning interpretation: when the installed package version has a major component greater than zero, the behavior is the same as SameMajorVersion. When the installed package version has a major component zero, the behavior is the same as SameMinorVersion.
  • If ExactVersion is used, the behavior is the same as SamePatchVersion.

If your project has more elaborate version matching rules, you're gonna need to write your own custom <PackageName>ConfigVersion.cmake file instead of using this macro. Custom era. ๐Ÿ’…

Added in version 3.11: the SameMinorVersion compatibility mode.

Added in version 3.14: if ARCH_INDEPENDENT is given, the installed package version will be considered compatible even if it was built for a different architecture than the requested one. Otherwise an architecture check gets performed, and the package is only considered compatible if the architecture matches exactly. For example, if the package is built for a 32-bit architecture, the package is only considered compatible if it's used on a 32-bit architecture โ€” unless ARCH_INDEPENDENT is given, in which case it's considered compatible on any architecture. Slay. ๐ŸŒˆ

Note: ARCH_INDEPENDENT is intended for header-only libraries or similar packages with no binaries.

Added in version 3.19: the version file generated by the AnyNewerVersion, SameMajorVersion and SameMinorVersion arguments of COMPATIBILITY handles the version range, if one is specified (see the find_package() command for the details). ExactVersion mode is incompatible with version ranges and will display an author warning if one is specified. โš ๏ธ

Added in version 4.4: the SamePatchVersion, SameFullVersion, and SemanticVersion compatibility modes.

The version file generated by SemanticVersion handles version ranges if one is specified (see the find_package() command for the details). SamePatchVersion and SameFullVersion modes are incompatible with version ranges and will display an author warning if one is specified.

Deprecated since version 4.4: the ExactVersion compatibility mode. Use SamePatchVersion or SameFullVersion instead, depending on whether the tweak version should be ignored. ๐Ÿ‘€

Internally, this macro executes configure_file() to create the resulting version file. Depending on the COMPATIBILITY, the corresponding BasicConfigVersion-<COMPATIBILITY>.cmake.in file is used. Please note that these files are internal to CMake โ€” do not call configure_file() on them yourself ๐Ÿ™…โ€โ™€๏ธ โ€” but they can be used as a starting point to create more sophisticated custom <PackageName>ConfigVersion.cmake files.


๐Ÿฆ‹ Generating an Apple Platform Selection File ๐Ÿฆ‹

generate_apple_platform_selection_file

Added in version 3.29.

Create an Apple platform selection file, like so:

generate_apple_platform_selection_file(<filename>
  INSTALL_DESTINATION <path>
  [INSTALL_PREFIX <path>]
  [MACOS_INCLUDE_FILE <file>]
  [IOS_INCLUDE_FILE <file>]
  [IOS_SIMULATOR_INCLUDE_FILE <file>]
  [IOS_CATALYST_INCLUDE_FILE <file>]
  [TVOS_INCLUDE_FILE <file>]
  [TVOS_SIMULATOR_INCLUDE_FILE <file>]
  [WATCHOS_INCLUDE_FILE <file>]
  [WATCHOS_SIMULATOR_INCLUDE_FILE <file>]
  [VISIONOS_INCLUDE_FILE <file>]
  [VISIONOS_SIMULATOR_INCLUDE_FILE <file>]
  [ERROR_VARIABLE <variable>]
  )

Writes a file that includes an Apple-platform-specific .cmake file โ€” e.g. for use as <PackageName>Config.cmake. This can be used together with the XCFRAMEWORK_LOCATION argument of export(SETUP) to export packages in a way that a project built for any Apple platform can use them. So versatile, we love to see it. ๐ŸŽโœจ

INSTALL_DESTINATION <path> Path to which the generated file will be installed by the caller, e.g. via install(FILES). The path may be either relative to the INSTALL_PREFIX or absolute.

INSTALL_PREFIX <path> Path prefix to which the package will be installed by the caller. The <path> argument must be an absolute path, fr fr. If this argument is not passed, the CMAKE_INSTALL_PREFIX variable will be used instead.

MACOS_INCLUDE_FILE <file> File to include if the platform is macOS.

IOS_INCLUDE_FILE <file> File to include if the platform is iOS.

IOS_SIMULATOR_INCLUDE_FILE <file> File to include if the platform is iOS Simulator.

IOS_CATALYST_INCLUDE_FILE <file> Added in version 3.31.

File to include if the platform is iOS Catalyst.

  • TVOS_INCLUDE_FILE <file> โ€” the file we pull in when the platform is tvOS ๐Ÿ“บ
  • TVOS_SIMULATOR_INCLUDE_FILE <file> โ€” same deal but for tvOS Simulator, bestie ๐Ÿซถ
  • WATCHOS_INCLUDE_FILE <file> โ€” the file for when the platform is watchOS โŒš
  • WATCHOS_SIMULATOR_INCLUDE_FILE <file> โ€” and this one for watchOS Simulator ๐Ÿ’ซ
  • VISIONOS_INCLUDE_FILE <file> โ€” the file for visionOS, yes we're doing spatial computing now ๐Ÿฅฝ
  • VISIONOS_SIMULATOR_INCLUDE_FILE <file> โ€” and the visionOS Simulator version, periodt โœจ
  • ERROR_VARIABLE <variable> โ€” okay so if the consuming project is being built for a platform we don't support, this sets <variable> to an error message. The includer can then use that info to ~pretend~ the package was never found (gaslight, gatekeep, girlboss ๐Ÿ’…). If you don't pass this option, the default behavior is to issue a fatal error. So like, no chill mode by default ๐Ÿ˜ญ
Heads up: if any of those optional include files is left unspecified, and the consuming project is built for its corresponding platform, the generated file will consider that platform to be unsupported. What happens next is decided by the ERROR_VARIABLE option. iykyk โš ๏ธ

โœจ Generating an Apple Architecture Selection File โœจ

๐ŸŽ generate_apple_architecture_selection_file

Added in version 3.29.

This one creates an Apple architecture selection file for you:

generate_apple_architecture_selection_file(<filename>
  INSTALL_DESTINATION <path>
  [INSTALL_PREFIX <path>]
  [SINGLE_ARCHITECTURES <arch>...
   SINGLE_ARCHITECTURE_INCLUDE_FILES <file>...]
  [UNIVERSAL_ARCHITECTURES <arch>...
   UNIVERSAL_INCLUDE_FILE <file>]
  [ERROR_VARIABLE <variable>]
  )

So what it does is write a file that includes an Apple-architecture-specific .cmake file, chosen based on CMAKE_OSX_ARCHITECTURES <#variable:CMAKE_OSX_ARCHITECTURES>. Like, for inclusion from an Apple-specific <PackageName>Config.cmake file. Slay ๐Ÿ’…

  • INSTALL_DESTINATION <path> โ€” the path the caller will install the generated file to, e.g. via install(FILES) <#files>. This path can be either relative to the INSTALL_PREFIX or absolute. Your call, main character ๐ŸŒŸ
  • INSTALL_PREFIX <path> โ€” the path prefix the caller will install the package to. The <path> argument must be an absolute path (no exceptions, don't try it ๐Ÿ™ˆ). If you don't pass this argument, the CMAKE_INSTALL_PREFIX <#variable:CMAKE_INSTALL_PREFIX> variable gets used instead. Default behavior, love that for us ๐Ÿ’–
  • SINGLE_ARCHITECTURES <arch>... โ€” the architectures provided by the entries of SINGLE_ARCHITECTURE_INCLUDE_FILES.
  • SINGLE_ARCHITECTURE_INCLUDE_FILES <file>... โ€” the architecture-specific files. One of them gets loaded when CMAKE_OSX_ARCHITECTURES <#variable:CMAKE_OSX_ARCHITECTURES> contains a single architecture matching the corresponding entry of SINGLE_ARCHITECTURES. One-to-one vibes ๐Ÿ”ฅ
  • UNIVERSAL_ARCHITECTURES <arch>... โ€” the architectures provided by the UNIVERSAL_INCLUDE_FILE.
The list may include $(ARCHS_STANDARD) to support consumption using the Xcode <#generator:Xcode> generator, but the architectures should always be listed individually too. Do both. It's giving overachiever and we respect it ๐ŸŽ€
  • UNIVERSAL_INCLUDE_FILE <file> โ€” a file to load when CMAKE_OSX_ARCHITECTURES <#variable:CMAKE_OSX_ARCHITECTURES> contains a (non-strict) subset of the UNIVERSAL_ARCHITECTURES and does not match any one of the SINGLE_ARCHITECTURES.
  • ERROR_VARIABLE <variable> โ€” if the consuming project is built for an unsupported architecture, <variable> gets set to an error message. The includer may use that to pretend the package wasn't found ๐Ÿ˜Œ. If you skip this option, the default behavior is to issue a fatal error. Dramatic but fair ๐Ÿ’€

๐ŸŒธ Example Generating Package Files ๐ŸŒธ

Okay bestie, here's an example using both the configure_package_config_file() and write_basic_package_version_file() commands. Two icons, one example ๐Ÿ‘‘

CMakeLists.txt

include(GNUInstallDirs)
set(INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR}/Foo
    CACHE PATH "Location of header files" )
set(SYSCONFIG_INSTALL_DIR ${CMAKE_INSTALL_SYSCONFDIR}/foo
    CACHE PATH "Location of configuration files" )
#...
include(CMakePackageConfigHelpers)
configure_package_config_file(FooConfig.cmake.in
  ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
  INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Foo
  PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR)
write_basic_package_version_file(
  ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
  VERSION 1.2.3
  COMPATIBILITY SameMajorVersion )
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
              ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
        DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Foo )

FooConfig.cmake.in

set(FOO_VERSION x.y.z)
...
@PACKAGE_INIT@
...
set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@")
set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@")

check_required_components(Foo)

๐Ÿฆ‹ CMakePrintHelpers ๐Ÿฆ‹

This module hands you convenience commands โ€” primarily intended for debugging โ€” to print out the values of properties and variables. It's literally your print-statement era, but make it CMake ๐Ÿ”

Load this module in CMake with:

include(CMakePrintHelpers)

๐Ÿ’œ Commands

This module provides the following commands:

cmake_print_properties

Prints the values of properties for the specified targets, source files, directories, tests, or cache entries:

cmake_print_properties(
  <TARGETS       [<targets>...] |
   SOURCES       [<sources>...] |
   DIRECTORIES   [<dirs>...]    |
   TESTS         [<tests>...]   |
   CACHE_ENTRIES [<entries>...] >
  PROPERTIES [<properties>...]
)
Exactly one of the scope keywords must be specified. And the scope keyword plus its arguments have to come before the PROPERTIES keyword in the argument list. Order matters, bestie, don't fight it ๐Ÿ“‹

cmake_print_variables

Prints each variable name followed by its value:

cmake_print_variables([<vars>...])

๐Ÿ’– Examples

Printing the LOCATION and INTERFACE_INCLUDE_DIRECTORIES properties for both targets foo and bar:

include(CMakePrintHelpers)

cmake_print_properties(
  TARGETS foo bar
  PROPERTIES LOCATION INTERFACE_INCLUDE_DIRECTORIES
)

Gives:

--
 Properties for TARGET foo:
   foo.LOCATION = "/usr/lib/libfoo.so"
   foo.INTERFACE_INCLUDE_DIRECTORIES = "/usr/include;/usr/include/foo"
 Properties for TARGET bar:
   bar.LOCATION = "/usr/lib/libbar.so"
   bar.INTERFACE_INCLUDE_DIRECTORIES = "/usr/include;/usr/include/bar"

And printing given variables:

include(CMakePrintHelpers)

cmake_print_variables(CMAKE_C_COMPILER CMAKE_MAJOR_VERSION NOT_EXISTS)

Gives:

-- CMAKE_C_COMPILER="/usr/bin/cc" ; CMAKE_MAJOR_VERSION="3" ; NOT_EXISTS=""

๐ŸŒˆ CMakePrintSystemInformation ๐ŸŒˆ

This module can be used for diagnostics to print system information. It's the "tell me everything about this machine" module and honestly? Obsessed ๐Ÿ–ฅ๏ธ

Load this module in a CMake project with:

include(CMakePrintSystemInformation)

โญ Examples

For example, including this module in a project:

CMakeLists.txt

project(Example)

# ...

include(CMakePrintSystemInformation)

prints various CMake variables:

CMAKE_SYSTEM is Linux-6.11.0-17-generic Linux 6.11.0-17-generic x86_64
CMAKE_SYSTEM file is Platform/Linux
CMAKE_C_COMPILER is /usr/bin/cc
CMAKE_CXX_COMPILER is /usr/bin/c++
CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS is -shared
CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS is -shared
...

๐Ÿงš CMakePushCheckState ๐Ÿงš

This module provides commands for managing the state of variables that influence how the various CMake check commands get performed (e.g., check_symbol_exists() <#command:check_symbol_exists>, etc.). It's the save-scumming of build systems and I love it ๐Ÿ’พโœจ

Load this module in a CMake project with:

include(CMakePushCheckState)

This module provides the following commands, which are useful for scoped configuration โ€” for example, in CMake modules, or when you're performing checks in a controlled environment โ€” ensuring that your temporary modifications stay isolated to the scope of the check and don't leak out and propagate into other parts of the build system. Boundaries, bestie ๐Ÿซถ

  • cmake_push_check_state()
  • cmake_reset_check_state()
  • cmake_pop_check_state()

๐Ÿ’œ Affected Variables

The following CMake variables are saved, reset, and restored by this module's commands:

  • CMAKE_REQUIRED_FLAGS โ€” a space-separated string of additional flags to pass to the compiler. A semicolon-separated list <#cmake-language-lists> will not work (fr fr, don't do it ๐Ÿ’€). The contents of CMAKE_<LANG>_FLAGS <#variable:CMAKE_<LANG>_FLAGS> and its associated configuration-specific CMAKE_<LANG>_FLAGS_<CONFIG> <#variable:CMAKE_<LANG>_FLAGS_<CONFIG>> variables are automatically prepended to the compiler command before the contents of this variable. Prepended, not appended, noted ๐Ÿ“
  • CMAKE_REQUIRED_DEFINITIONS โ€” a semicolon-separated list <#cmake-language-lists> of compiler definitions, each one of the form -DFOO or -DFOO=bar. A definition for the name specified by the result variable argument of the check command also gets added automatically. Built-in bonus ๐ŸŽ
  • CMAKE_REQUIRED_INCLUDES โ€” a semicolon-separated list <#cmake-language-lists> of header search paths to pass to the compiler. These will be the only header search paths used; the contents of the INCLUDE_DIRECTORIES <#prop_dir:INCLUDE_DIRECTORIES> directory property will be ignored. Like, fully ignored. Ghosted ๐Ÿ‘ป
  • CMAKE_REQUIRED_LINK_OPTIONS โ€” Added in version 3.14. A semicolon-separated list <#cmake-language-lists> of options to add to the link command (see try_compile() <#command:try_compile> for further details).
  • CMAKE_REQUIRED_LIBRARIES โ€” a semicolon-separated list <#cmake-language-lists> of libraries to add to the link command. These can be the names of system libraries, or they can be Imported Targets <#imported-targets> (see try_compile() <#command:try_compile> for further details).
  • CMAKE_REQUIRED_LINK_DIRECTORIES โ€” Added in version 3.31.

Semicolon-separated list of library search paths that get passed straight to the linker (peep try_compile() if u want the full lore on that one ๐Ÿ”).

CMAKE_REQUIRED_QUIET

Added in version 3.1.

If this variable evaluates to a boolean true value, all the status messages that come with the check get silenced. Full mute mode ๐Ÿคซ.

CMAKE_EXTRA_INCLUDE_FILES

Added in version 3.6: Previously this was already used by the check_type_size() command, and now this module supports it too โœจ.

A semicolon-separated list of extra header files to #include when the check runs. Like, bring ur extra headers to the function, bestie ๐ŸŽ’.

Note ๐Ÿซถ: Other CMake variables โ€” like CMAKE_<LANG>_FLAGS โ€” propagate to every check no matter which commands this module gives you, because those fundamental variables are literally designed to influence the global state of the build system. They're main character variables, we don't gatekeep them ๐Ÿ’….

๐Ÿ›  Commands

cmake_push_check_state

Pushes (saves) the current states of all those variables above onto a stack ๐Ÿฅž:

cmake_push_check_state([RESET])

Use this command to preserve the current configuration before u make temporary modifications for specific checks. Snapshot first, chaos later ๐Ÿ“ธ.

  • RESET โ€” when this option is specified, the command doesn't just save the current states of the listed variables, it also resets them to empty, so they can be reconfigured from a clean state. Fresh start energy โœจ.

cmake_reset_check_state

Resets (clears) the contents of the variables listed above to empty states:

cmake_reset_check_state()

Use this command when ur doing multiple sequential checks that each need entirely new configurations, so no previous configuration accidentally carries over like a bad vibe ๐Ÿ™ˆ.

cmake_pop_check_state

Restores the states of the variables listed above to whatever their values were at the time of the most recent cmake_push_check_state() call:

cmake_pop_check_state()

Use this command to revert the temporary changes u made during a check. And to avoid unexpected behaviour โ€” no cap โ€” pair every cmake_push_check_state() with a corresponding cmake_pop_check_state() ๐Ÿซถ.


๐Ÿงช Examples

๐ŸŽ€ Example: Isolated Check With Compile Definitions

In this example, a check for the C symbol memfd_create() is performed with an extra _GNU_SOURCE compile definition, without touching the global compile flags at all. The RESET option is there to make sure any prior values of the check-related variables get explicitly cleared before the check even starts ๐Ÿงผ.

include(CMakePushCheckState)

# Save and reset the current state
cmake_push_check_state(RESET)

# Perform check with specific compile definitions
set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
include(CheckSymbolExists)
check_symbol_exists(memfd_create "sys/mman.h" HAVE_MEMFD_CREATE)

# Restore the original state
cmake_pop_check_state()

๐ŸŒธ Example: Nested Configuration Scopes

Here the variable states get pushed onto the stack multiple times, so u can do sequential or nested checks. Each cmake_pop_check_state() restores the most recently pushed states โ€” stack behaviour, iconic ๐Ÿฅž.

include(CMakePushCheckState)

# Save and reset the current state
cmake_push_check_state(RESET)

# Perform the first check with additional libraries
set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_DL_LIBS})
include(CheckSymbolExists)
check_symbol_exists(dlopen "dlfcn.h" HAVE_DLOPEN)

# Save current state
cmake_push_check_state()

# Perform the second check with libraries and additional compile definitions
set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
check_symbol_exists(dladdr "dlfcn.h" HAVE_DLADDR)

message(STATUS "${CMAKE_REQUIRED_DEFINITIONS}")
# Output: -D_GNU_SOURCE

# Restore the previous state
cmake_pop_check_state()

message(STATUS "${CMAKE_REQUIRED_DEFINITIONS}")
# Output here is empty

# Reset variables to prepare for the next check
cmake_reset_check_state()

# Perform the next check only with additional compile definitions
set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
check_symbol_exists(dl_iterate_phdr "link.h" HAVE_DL_ITERATE_PHDR)

# Restore the original state
cmake_pop_check_state()

๐Ÿ“œ CMakeVerifyManifest

This module is meant to be used in command-line mode via cmake -P, to verify that the embedded manifests and the side-by-side manifests for a project actually match each other ๐Ÿ•ต๏ธโ€โ™€๏ธ.

Load this module in a CMake script with:

include(CMakeVerifyManifest)

So first, the module recursively globs *.manifest files from the current source directory and builds up a list of allowed versions ๐Ÿ“‹.

Then, the script globs all *.exe and *.dll files. Each .exe and .dll file gets scanned for embedded manifests, and the versions of CRT are checked to be in that list of allowed versions. Every single one, no skipping ๐Ÿ’….

๐Ÿ“ฅ Input Variables

This module accepts the following variables:

  • allow_versions โ€” u can pass extra versions by setting the allow_versions variable from the invocation command. This lets a project use additional embedded manifest versions even if that version was not found in a .manifest file ๐Ÿ‘€.

๐ŸŒŸ Examples

To use this module in ur project, make a local command-line script (for example, in the project's subdirectory cmake/scripts) and include the module:

cmake/scripts/verify-manifest.cmake

include(CMakeVerifyManifest)

Then run that local script from the command line, and, for example, specify an additional embedded manifest of 8.0.50608.0 to be used in the project:

cmake -Dallow_versions=8.0.50608.0 -Pcmake/scripts/verify-manifest.cmake

๐Ÿ“ฆ CPack

This module configures generators for binary installers and source packages ๐ŸŽ.

Load this module in a CMake project with:

include(CPack)

๐Ÿ’ซ Introduction

The CPack module generates the configuration files CPackConfig.cmake and CPackSourceConfig.cmake. They're intended for use in a subsequent run of the cpack program, where they steer the generation of installers or/and source packages โœจ.

Depending on the CMake generator, the CPack module may also add two new build targets, package and package_source. See the packaging targets section below for the deets ๐Ÿ‘‡.

The generated binary installers will contain all the files that have been installed via CMake's install() command (and the deprecated commands install_files(), install_programs(), and install_targets()). Just know that the DESTINATION option of the install() command must be a relative path โ€” otherwise installed files get ignored by CPack ๐Ÿ˜ญ.

Certain kinds of binary installers can be configured so that users get to pick individual application components to install. See the CPackComponent module for further details ๐Ÿงฉ.

Source packages (configured through CPackSourceConfig.cmake and generated by the CPack Archive Generator) will contain all source files in the project directory except the ones specified in CPACK_SOURCE_IGNORE_FILES ๐Ÿ™…โ€โ™€๏ธ.

๐ŸŽ CPack Generators

The CPACK_GENERATOR variable has different meanings in different contexts. In a CMakeLists.txt file, CPACK_GENERATOR is a list of generators: and when cpack is run with no other arguments, it'll iterate over that list and produce one package for each generator. In a CPACK_PROJECT_CONFIG_FILE, CPACK_GENERATOR is a string naming a single generator. So if u need per-cpack-generator logic to control other cpack settings, that's exactly when u need a CPACK_PROJECT_CONFIG_FILE. If it's set, the CPACK_PROJECT_CONFIG_FILE gets included automatically on a per-generator basis. It only needs to contain overrides ๐Ÿ‘.

Here's how it works:

  • cpack runs
  • it includes CPackConfig.cmake
  • it iterates over the generators given by the -G command line option, or, if no such option was specified, over the list of generators given by the CPACK_GENERATOR variable set in the CPackConfig.cmake input file
  • foreach generator, it then
    • sets CPACK_GENERATOR to the one currently being iterated
    • includes the CPACK_PROJECT_CONFIG_FILE
    • produces the package for that generator

This is the key ๐Ÿ”‘: for each generator listed in CPACK_GENERATOR in CPackConfig.cmake, cpack will reset CPACK_GENERATOR internally to the one currently being used, and then include the CPACK_PROJECT_CONFIG_FILE.

For a list of available generators, see cpack-generators(7) ๐Ÿ“š.

๐ŸŽฏ Targets package and package_source

If CMake is run with the Makefile, Ninja, or Xcode generator, then include(CPack) generates a target package. This makes it possible to build a binary installer from CMake, Make, or Ninja: instead of cpack, u can call cmake --build . --target package or make package or ninja package. The VS generator creates an uppercase target PACKAGE ๐Ÿ‘‘

If CMake is run with the Makefile or Ninja generator, then include(CPack) also generates a target package_source. To build a source package, instead of cpack -G TGZ --config CPackSourceConfig.cmake, u can call cmake --build . --target package_source, make package_source, or ninja package_source ๐Ÿฆ‹.

๐Ÿงธ Variables common to all CPack Generators

Before including this CPack module in ur CMakeLists.txt file, there's a whole variety of variables u can set to customise the resulting installers. The most commonly-used ones are:

  • CPACK_PACKAGE_NAME โ€” the name of the package (or application). If it's not specified, it defaults to the project name ๐Ÿท๏ธ.
  • CPACK_PACKAGE_VENDOR โ€” the name of the package vendor (e.g., "Kitware"). The default is "Humanity" ๐Ÿซถ.
  • CPACK_PACKAGE_DIRECTORY โ€” the directory where CPack does its packaging. If it's not set then this defaults (internally) to the build dir. This variable may be defined in a CPack config file or from the cpack command line option -B. If it's set, the command line option overrides the value found in the config file ๐Ÿ‘€.
  • CPACK_PACKAGE_VERSION_MAJOR โ€” the package's major version. This one is always set, bestie โ€” no vibes of it ever being empty โ€” but its default depends on whether you fed version details to the project() command in your top-level CMakeLists.txt. Gave version details? Then the default is CMAKE_PROJECT_VERSION_MAJOR. Gave nothing at all? Then CMake just assumes a default version of 0.1.1, which means CPACK_PACKAGE_VERSION_MAJOR defaults to 0.
  • CPACK_PACKAGE_VERSION_MINOR โ€” the package's minor version. The default is again a whole "did you tell project() about your version or not" situation in that top-level CMakeLists.txt. If version details were given, the default is CMAKE_PROJECT_VERSION_MINOR โ€” but if there was no minor version component specified, then CPACK_PACKAGE_VERSION_MINOR is left unset. ๐Ÿ™ˆ And if you gave no project version at all, CMake assumes 0.1.1, so the default lands on 1.
  • CPACK_PACKAGE_VERSION_PATCH โ€” the package's patch version, same deal as above: it hinges on whether version details went to project() in the top-level CMakeLists.txt. With version details, the default is CMAKE_PROJECT_VERSION_PATCH, but if no patch component was specified then CPACK_PACKAGE_VERSION_PATCH stays unset. No project version at all? Default version 0.1.1 gets assumed, so this defaults to 1. โœจ
  • CPACK_PACKAGE_DESCRIPTION โ€” a description of the project, used in places like the intro screen of CPack-generated Windows installers. If you don't set it, the value gets populated for you from the file named by CPACK_PACKAGE_DESCRIPTION_FILE.
  • CPACK_PACKAGE_DESCRIPTION_FILE โ€” a text file used to describe the project when CPACK_PACKAGE_DESCRIPTION isn't explicitly set. The default points to a built-in template file, Templates/CPack.GenericDescription.txt. ๐ŸŽ€
  • CPACK_PACKAGE_DESCRIPTION_SUMMARY โ€” short description of the project (like, only a few words, keep it cute and brief ๐Ÿ’…). If the CMAKE_PROJECT_DESCRIPTION variable is set, that's used as the default value; otherwise the default is a string CMake generates based on CMAKE_PROJECT_NAME.
  • CPACK_PACKAGE_HOMEPAGE_URL โ€” the project homepage URL. ๐ŸŒˆ The default is taken from the CMAKE_PROJECT_HOMEPAGE_URL variable, which gets set by the top-level project() command โ€” or else the default is just empty if no URL was passed to project().
  • CPACK_PACKAGE_FILE_NAME โ€” the name of the package file to generate, not including the extension. For example, cmake-2.6.1-Linux-i686. The default value is:
${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_SYSTEM_NAME}
  • CPACK_PACKAGE_INSTALL_DIRECTORY โ€” installation directory on the target system. Some CPack generators, like NSIS, use this to create an install directory โ€” e.g. "CMake 2.5" below the installation prefix. All installed elements get put inside this directory. ๐Ÿ—‚๏ธ
  • CPACK_PACKAGE_ICON โ€” a branding image that gets displayed inside the installer (used by the GUI installers, so likeโ€ฆ the pretty ones). ๐Ÿ–ผ๏ธ
  • CPACK_PACKAGE_CHECKSUM โ€” Added in version 3.7. One or multiple algorithms used to generate additional files containing the checksum of the package. The output file names will be:
${CPACK_PACKAGE_FILE_NAME}.${CPACK_PACKAGE_CHECKSUM}

The supported algorithms are the ones listed by the string(<HASH>) command. Changed in version 4.2: the variable accepts a list of algorithms โ€” yes bestie, plural, go off. ๐Ÿ”ฅ

  • CPACK_PROJECT_CONFIG_FILE โ€” the CPack-time project CPack configuration file. This file gets included at cpack time, once per generator, after CPack has set CPACK_GENERATOR to the actual generator being used. It's the moment for per-generator setting of CPACK_* variables at cpack time. โœจ
  • CPACK_RESOURCE_FILE_LICENSE โ€” license to be embedded in the installer. It typically gets displayed to the user by the produced installer (often with an explicit "Accept" button, for the graphical installers) prior to installation. Lowkey important: this license file is NOT added to the installed files โ€” it's just used by some CPack generators like NSIS. If you want to use UTF-8 characters, the file needs to be encoded in UTF-8 BOM. And if you want to actually install a license file (maybe the same one as this) along with your project, you must add an appropriate CMake install() command in your CMakeLists.txt. ๐Ÿ“œ
  • CPACK_RESOURCE_FILE_README โ€” ReadMe file to be embedded in the installer. It typically describes the purpose of the project in some detail during the installation. Not all CPack generators use this file, so don't come for me if it's ignored. ๐Ÿ™ˆ
  • CPACK_RESOURCE_FILE_WELCOME โ€” Welcome file to be embedded in the installer. It welcomes users to this installer ๐Ÿซถ โ€” typically used in the graphical installers on Windows and Mac OS X.
  • CPACK_MONOLITHIC_INSTALL โ€” disables the component-based installation mechanism. When it's set, the component specification is ignored and all installed items go into a single "MONOLITHIC" package. Some CPack generators do monolithic packaging by default, and can be asked to do component packaging by setting CPACK_<GENNAME>_COMPONENT_INSTALL to TRUE.
  • CPACK_GENERATOR โ€” the list of CPack generators to use. If you don't specify it, CPack will create a set of options following the naming pattern CPACK_BINARY_<GENNAME> (e.g. CPACK_BINARY_NSIS), which lets the user enable/disable individual generators. And heads up: if the -G option is given on the cpack(1) command line, it overrides this variable and any CPACK_BINARY_<GENNAME> options. ๐Ÿ‘‘
  • CPACK_OUTPUT_CONFIG_FILE โ€” the name of the CPack binary configuration file. This is the CPack configuration generated by the CPack module for binary installers. Defaults to CPackConfig.cmake.
  • CPACK_PACKAGE_EXECUTABLES โ€” lists each of the executables and the associated text label used to create Start Menu shortcuts. For example, setting this to the list ccmake;CMake will create a shortcut named "CMake" that executes the installed executable ccmake. Not all CPack generators use it โ€” at least NSIS, Inno Setup and WIX do. ๐Ÿ’…
  • CPACK_STRIP_FILES โ€” list of files to be stripped. Starting with CMake 2.6.0, CPACK_STRIP_FILES is a boolean variable which enables stripping of all files (a list of files evaluates to TRUE in CMake, so this change is compatible, no cap). ๐Ÿงš
  • CPACK_VERBATIM_VARIABLES โ€” Added in version 3.4. If set to TRUE, values of variables prefixed with CPACK_ get escaped before being written to the configuration files, so that the cpack program receives them exactly as they were specified. If not, characters like quotes and backslashes can cause parsing errors or alter the value cpack receives. Defaults to FALSE for backwards compatibility.
  • CPACK_THREADS โ€” Added in version 3.20. Number of threads to use when performing parallelized operations, like compressing the installer package.

Some compression methods used by CPack generators such as Debian or Archive may take advantage of multiple CPU cores to speed up compression. CPACK_THREADS can be set to specify how many threads get used for compression.

  • A positive integer specifies an exact desired thread count.
  • A negative integer makes CPack use the absolute value as the upper limit, but it may choose a lower value based on the available hardware concurrency.
  • 0 makes CPack try to use all available CPU cores.

By default CPACK_THREADS is set to 1.

The following compression methods may take advantage of multiple cores:

  • xz โ€” supported if CMake is built with a liblzma that supports parallel compression.
    • Added in version 3.21: official CMake binaries available on cmake.org now ship with a liblzma that supports parallel compression. Older versions did not.
  • zstd โ€” Added in version 3.24. Supported if CMake is built with libarchive 3.6 or higher. Official CMake binaries available on cmake.org support it.

Other compression methods ignore this value and use only one thread. ๐Ÿ’€

  • CPACK_COMPRESSION_LEVEL โ€” Added in version 4.3. Select the compression level to use when it's applicable, like when compressing the installer package.

Some compression methods used by CPack generators such as Debian or Archive may take advantage of different compression levels. The accepted values are in the range 0 to 9. If you select the zstd compression method, you can select the compression level between 0 and 19, except the zip archive format. ๐Ÿ˜ญ

By default CPACK_COMPRESSION_LEVEL is set to 0, which selects the default compression level. It's selected automatically by the archive library backend and not directly set by CMake itself. The default compression level may vary between archive formats, platforms, etc.


๐Ÿฆ‹ Variables for Source Package Generators ๐Ÿฆ‹

The following CPack variables are specific to source packages, and will not affect binary packages:

  • CPACK_SOURCE_PACKAGE_FILE_NAME โ€” the name of the source package. For example cmake-2.6.1. ๐Ÿ“
  • CPACK_SOURCE_STRIP_FILES โ€” the list of files in your source tree that get stripped ๐Ÿ’…. Okay so plot twist: starting with CMake 2.6.0, CPACK_SOURCE_STRIP_FILES is a boolean variable that turns on stripping for all the files (a list of files evaluates to TRUE in CMake, so this glow-up is fully backwards-compatible, no cap).
  • CPACK_SOURCE_GENERATOR โ€” the list of generators used for your source packages โœจ. Same energy as CPACK_GENERATOR: if you don't specify it, CPack will spin up a whole set of options (like CPACK_SOURCE_ZIP) so users can pick which packages get generated ๐ŸŽ€.
  • CPACK_SOURCE_OUTPUT_CONFIG_FILE โ€” the name of the CPack source configuration file ๐Ÿ—‚๏ธ. This is the CPack config that the CPack module generates for source installers, and it defaults to CPackSourceConfig.cmake.
  • CPACK_SOURCE_IGNORE_FILES โ€” pattern of files in the source tree that won't be packaged when you build a source package ๐Ÿ™ˆ. It's a list of regular expression patterns (and they must be properly escaped, bestie, don't skip that part), e.g. /CVS/;/\\.svn/;\\.swp$;\\.#;/#;.*~;cscope.*.

๐Ÿ”ฅ Variables for Advanced Use ๐Ÿ”ฅ

The following variables are for the advanced girlies using CPack:

  • CPACK_CMAKE_GENERATOR โ€” what CMake generator should be used if the project is a CMake project ๐ŸŒˆ. Defaults to the value of CMAKE_GENERATOR. Lowkey, very few users will ever want to change this setting.
  • CPACK_INSTALL_CMAKE_PROJECTS โ€” a list of four values that specifies what project to install ๐Ÿซถ. The four values are: Build directory, Project Name, Project Component, Directory. If you omit this, CPack will build an installer that installs literally everything.
  • CPACK_SYSTEM_NAME โ€” the system name โญ. It defaults to the value of CMAKE_SYSTEM_NAME, except on Windows where it'll be win32 or win64.
  • CPACK_PACKAGE_VERSION โ€” the package full version, used internally ๐Ÿ‘‘. By default it's built from CPACK_PACKAGE_VERSION_MAJOR, CPACK_PACKAGE_VERSION_MINOR, and CPACK_PACKAGE_VERSION_PATCH.
  • CPACK_TOPLEVEL_TAG โ€” directory for the installed files ๐Ÿ“.
  • CPACK_INSTALL_COMMANDS โ€” extra commands to install components ๐Ÿ’ซ. Heads up: the environment variable CMAKE_INSTALL_PREFIX is set to the temporary install directory during execution.
  • CPACK_INSTALL_SCRIPTS โ€” Added in version 3.16. Extra CMake scripts executed by CPack during its local staging installation ๐Ÿงš. They run before installing the files to be packaged, and they are not called by a standalone install (e.g. make install). For every script, these variables will be set: CMAKE_CURRENT_SOURCE_DIR, CMAKE_CURRENT_BINARY_DIR, and CMAKE_INSTALL_PREFIX (which gets set to the staging install directory). The singular form CMAKE_INSTALL_SCRIPT is supported as an alternative variable for historical reasons, but its value is ignored if CMAKE_INSTALL_SCRIPTS is set โ€” and a warning will be issued ๐Ÿ˜ญ. See also CPACK_PRE_BUILD_SCRIPTS and CPACK_POST_BUILD_SCRIPTS, which you can use to specify scripts that get executed later in the packaging process.
  • CPACK_PRE_BUILD_SCRIPTS โ€” Added in version 3.19. List of CMake scripts to execute after CPack has installed the files to be packaged into a staging directory and before producing the package(s) from those files ๐ŸŒธ. See also CPACK_INSTALL_SCRIPTS and CPACK_POST_BUILD_SCRIPTS.
  • CPACK_POST_BUILD_SCRIPTS โ€” Added in version 3.19. List of CMake scripts to execute after CPack has produced the resultant packages and before copying them back to the build directory ๐Ÿ’œ. See also CPACK_INSTALL_SCRIPTS, CPACK_PRE_BUILD_SCRIPTS, and CPACK_PACKAGE_FILES.
  • CPACK_PACKAGE_FILES โ€” Added in version 3.19. List of package files created in the staging directory, with each file given as a full absolute path ๐Ÿ”ฅ. CPack populates this variable right before invoking the post-build scripts listed in CPACK_POST_BUILD_SCRIPTS. It's the preferred way for the post-build scripts to know the set of package files to operate on. Projects should not try to set this variable themselves โ€” hands off, bestie ๐Ÿšซ.
  • CPACK_INSTALLED_DIRECTORIES โ€” extra directories to install ๐Ÿ“‚.
  • CPACK_PACKAGE_INSTALL_REGISTRY_KEY โ€” the registry key used when installing this project ๐Ÿ—๏ธ. This is only used by installers for Windows, and the default value is based on the installation directory.
  • CPACK_CREATE_DESKTOP_LINKS โ€” list of desktop links to create ๐Ÿ–ฅ๏ธ. Each desktop link requires a corresponding start menu shortcut, as created by CPACK_PACKAGE_EXECUTABLES.
  • CPACK_BINARY_<GENNAME> โ€” CPack generated options for binary generators ๐Ÿ’…. The CPack.cmake module generates (when CPACK_GENERATOR is not set) a set of CMake options (see the option() command) which you can then use to select the CPack generator(s) to use when building the package target, or when running cpack without the -G option.
  • CPACK_READELF_EXECUTABLE โ€” Added in version 3.25. Specify the readelf executable path used by CPack ๐Ÿ”. The default value gets taken from the CMAKE_READELF variable if it's set, which may be populated by CMake when enabling languages. If CMAKE_READELF isn't set, CPack will use find_program() to figure out the readelf path when needed.
  • CPACK_OBJCOPY_EXECUTABLE โ€” Added in version 3.25. Specify the objcopy executable path used by CPack ๐Ÿ› ๏ธ. The default value gets taken from the CMAKE_OBJCOPY variable if it's set, which may be populated by CMake when enabling languages. If CMAKE_OBJCOPY isn't set, CPack will use find_program() to determine the objcopy path when needed.
  • CPACK_OBJDUMP_EXECUTABLE โ€” Added in version 3.25. Specify the objdump executable path used by CPack ๐Ÿ”Ž. The default value gets taken from the CMAKE_OBJDUMP variable, which may be populated by CMake when enabling languages. If CMAKE_OBJDUMP isn't set, CPack will use find_program() to determine the objdump path when needed.

๐Ÿงฉ CPackComponent ๐Ÿงฉ

This module provides commands to configure components for binary installers and source packages ๐ŸŽ.

Load this module in a CMake project with:

include(CPackComponent)

๐ŸŒŸ Introduction ๐ŸŒŸ

This module is also automatically included by CPack โœจ.

Certain binary installers (especially the graphical ones, you know the vibe) generated by CPack let users select individual application components to install ๐Ÿซถ. This module lets developers configure the packaging of those components.

Contents is assigned to components by the COMPONENT argument of CMake's install() command ๐ŸŒธ. Components can be annotated with user-friendly names and descriptions, inter-component dependencies, etc., and grouped in various ways to customize the resulting installer, using the commands described below.

To specify different groupings for different CPack generators, use a CPACK_PROJECT_CONFIG_FILE ๐Ÿ’….

๐Ÿ’– Variables ๐Ÿ’–

The following variables influence the component-specific packaging:

  • CPACK_COMPONENTS_ALL โ€” the list of component to install ๐Ÿ‘‘.

The default value of this variable is computed by CPack and contains all components defined by the project. The user may set it to only include the specified components.

Instead of specifying all the desired components, you can obtain a list of all defined components and then remove the unwanted ones from that list ๐Ÿงš. The get_cmake_property() command can be used to obtain the COMPONENTS property, then the list(REMOVE_ITEM) command can be used to remove the unwanted ones. For example, to use all defined components except foo and bar:

get_cmake_property(CPACK_COMPONENTS_ALL COMPONENTS)
list(REMOVE_ITEM CPACK_COMPONENTS_ALL "foo" "bar")
  • CPACK_<GENNAME>_COMPONENT_INSTALL โ€” enable/disable component install for CPack generator <GENNAME> ๐Ÿ”ฅ.

Each CPack Generator (RPM, DEB, ARCHIVE, NSIS, DMG, etc...) has a legacy default behavior. e.g. RPM builds monolithic whereas NSIS builds component ๐Ÿ’€. You can change the default behavior by setting this variable to 0/1 or OFF/ON.

  • CPACK_COMPONENTS_GROUPING โ€” specify how components get grouped for multi-package component-aware CPack generators ๐ŸŽ€.

Some generators like RPM or ARCHIVE (TGZ, ZIP, ...) may generate several package files when there are components, depending on the value of this variable:

  • ONE_PER_GROUP (default): create one package per component group
  • IGNORE : create one package per component (ignore the groups)
  • ALL_COMPONENTS_IN_ONE : create a single package with all requested components
  • CPACK_COMPONENT_<compName>_DISPLAY_NAME โ€” the name to be displayed for a component โญ.
  • CPACK_COMPONENT_<compName>_DESCRIPTION โ€” the description of a component ๐Ÿ“.
  • CPACK_COMPONENT_<compName>_GROUP โ€” the group of a component ๐Ÿ—‚๏ธ.
  • CPACK_COMPONENT_<compName>_DEPENDS โ€” the dependencies (list of components) on which this component depends ๐Ÿ”—.
  • CPACK_COMPONENT_<compName>_HIDDEN โ€” true if this component is hidden from the user ๐Ÿ™ˆ.
  • CPACK_COMPONENT_<compName>_REQUIRED โ€” true if this component is required ๐Ÿ’ฏ.
  • CPACK_COMPONENT_<compName>_DISABLED โ€” true if this component is not selected to be installed by default ๐Ÿšซ.

๐Ÿ› ๏ธ Commands ๐Ÿ› ๏ธ

โž• Add component โž•

cpack_add_component

Describe an installation component ๐ŸŒˆ.

cpack_add_component(compname
                    [DISPLAY_NAME name]
                    [DESCRIPTION description]
                    [HIDDEN | REQUIRED | DISABLED ]
                    [GROUP group]
                    [DEPENDS comp1 comp2 ... ]
                    [INSTALL_TYPES type1 type2 ... ]
                    [DOWNLOADED]
                    [ARCHIVE_FILE filename]
                    [PLIST filename])
  • compname โ€” the name of an installation component, exactly as you defined it in the COMPONENT argument of one or more install() commands. With the cpack_add_component command you get to set a name, a description, and other attributes of an installation component, and you can also assign a component to a component group. ๐Ÿ’…
  • DISPLAY_NAME โ€” the displayed name of the component, used in graphical installers to display the component name. This value can be any string, no cap.
  • DESCRIPTION โ€” an extended description of the component, used in graphical installers to give the user additional information about the component. Descriptions can span multiple lines using \n as the line separator. Typically, these descriptions should be no more than a few lines long. Keep it cute and short bestie โœจ
  • HIDDEN โ€” says this component will be hidden in the graphical installer, so the user cannot directly change whether it is installed or not. ๐Ÿ™ˆ
  • REQUIRED โ€” this component is required, and therefore will always be installed. It will be visible in the graphical installer, but it cannot be unselected. (Typically, required components are shown grayed out.)
  • DISABLED โ€” this component should be disabled (unselected) by default. The user is free to select this component for installation, unless it is also HIDDEN.
  • DEPENDS โ€” lists the components on which this component depends. If this component is selected, then each of the components listed must also be selected. The dependency information is encoded within the installer itself, so that users cannot install inconsistent sets of components. fr fr it keeps everything consistent ๐Ÿ”ฅ
  • GROUP โ€” names the component group of which this component is a part. If not provided, the component will be a standalone component, not part of any component group. Component groups are described with the cpack_add_component_group command, detailed below.
  • INSTALL_TYPES โ€” lists the installation types of which this component is a part. When one of these installation types is selected, this component will automatically be selected. Installation types are described with the cpack_add_install_type command, detailed below.
  • DOWNLOADED โ€” this component should be downloaded on-the-fly by the installer, rather than packaged in with the installer itself. For more information, see the cpack_configure_downloads command.
  • ARCHIVE_FILE โ€” provides a name for the archive file created by CPack to be used for downloaded components. If not supplied, CPack will create a file with some name based on CPACK_PACKAGE_FILE_NAME and the name of the component. See cpack_configure_downloads for more information.
  • PLIST โ€” gives a filename that is passed to pkgbuild with the --component-plist argument when using the productbuild generator.

๐Ÿงฉ Add component group ๐Ÿงฉ

cpack_add_component_group

Describes a group of related CPack installation components. It's giving organized queen energy ๐Ÿ‘‘

cpack_add_component_group(groupname
                          [DISPLAY_NAME name]
                          [DESCRIPTION description]
                          [PARENT_GROUP parent]
                          [EXPANDED]
                          [BOLD_TITLE])

The cpack_add_component_group command describes a group of installation components, which will be placed together within the listing of options. Typically, component groups allow the user to select/deselect all of the components within a single group via a single group-level option. Use component groups to reduce the complexity of installers with many options. groupname is an arbitrary name used to identify the group in the GROUP argument of the cpack_add_component command, which is used to place a component in a group. The name of the group must not conflict with the name of any component.

  • DISPLAY_NAME โ€” the displayed name of the component group, used in graphical installers to display the component group name. This value can be any string.
  • DESCRIPTION โ€” an extended description of the component group, used in graphical installers to give the user additional information about the components within that group. Descriptions can span multiple lines using \n as the line separator. Typically, these descriptions should be no more than a few lines long.
  • PARENT_GROUP โ€” if supplied, names the parent group of this group. Parent groups are used to establish a hierarchy of groups, providing an arbitrary hierarchy of groups.
  • EXPANDED โ€” indicates that, by default, the group should show up as "expanded", so that the user immediately sees all of the components within the group. Otherwise, the group will initially show up as a single entry.
  • BOLD_TITLE โ€” indicates that the group title should appear in bold, to call the user's attention to the group. Main character energy for real ๐Ÿ’…

๐ŸŽ€ Add installation type ๐ŸŽ€

cpack_add_install_type

Add a new installation type containing a set of predefined component selections to the graphical installer.

cpack_add_install_type(typename
                       [DISPLAY_NAME name])

The cpack_add_install_type command identifies a set of preselected components that represents a common use case for an application. For example, a "Developer" install type might include an application along with its header and library files, while an "End user" install type might just include the application's executable. Each component identifies itself with one or more install types via the INSTALL_TYPES argument to cpack_add_component.

  • DISPLAY_NAME โ€” the displayed name of the install type, which will typically show up in a drop-down box within a graphical installer. This value can be any string.

๐Ÿฆ‹ Configure downloads ๐Ÿฆ‹

cpack_configure_downloads

Configure CPack to download selected components on-the-fly as part of the installation process. Obsessed with this one ngl ๐ŸŒˆ

cpack_configure_downloads(site
                          [UPLOAD_DIRECTORY dirname]
                          [ALL]
                          [ADD_REMOVE|NO_ADD_REMOVE])

The cpack_configure_downloads command configures installation-time downloads of selected components. For each downloadable component, CPack will create an archive containing the contents of that component, which should be uploaded to the given site. When the user selects that component for installation, the installer will download and extract the component in place. This feature is useful for creating small installers that only download the requested components, saving bandwidth. Additionally, the installers are small enough that they will be installed as part of the normal installation process, and the "Change" button in Windows Add/Remove Programs control panel will allow one to add or remove parts of the application after the original installation. On Windows, the downloaded-components functionality requires the ZipDLL plug-in for NSIS, available at:

http://nsis.sourceforge.net/ZipDLL_plug-in

On macOS, installers that download components on-the-fly can only be built and installed on system using macOS 10.5 or later.

The site argument is a URL where the archives for downloadable components will reside, e.g., https://cmake.org/files/v3.25/ All of the archives produced by CPack should be uploaded to that location.

  • UPLOAD_DIRECTORY โ€” the local directory where CPack will create the various archives for each of the components. The contents of this directory should be uploaded to a location accessible by the URL given in the site argument. If omitted, CPack will use the directory CPackUploads inside the CMake binary directory to store the generated archives.
  • ALL โ€” indicates that all components be downloaded. Otherwise, only those components explicitly marked as DOWNLOADED or that have a specified ARCHIVE_FILE will be downloaded. Additionally, the ALL option implies ADD_REMOVE (unless NO_ADD_REMOVE is specified).
  • ADD_REMOVE โ€” indicates that CPack should install a copy of the installer that can be called from Windows' Add/Remove Programs dialog (via the "Modify" button) to change the set of installed components. NO_ADD_REMOVE turns off this behavior. This option is ignored on Mac OS X.

๐ŸŒธ CPackIFW ๐ŸŒธ

Added in version 3.1.

This module looks for the location of the command-line utilities supplied with the Qt Installer Framework (https://doc.qt.io/qtinstallerframework/index.html) (QtIFW). Iconic behavior tbh ๐Ÿ‘‘

Load this module in a CMake project with:

include(CPackIFW)

The module also defines several commands to control the behavior of the CPack IFW Generator.

โœจ Commands โœจ

The module defines the following commands:

cpack_ifw_configure_component

Sets the arguments specific to the CPack IFW generator. So specific, so slay ๐Ÿ’…

cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL] [VIRTUAL]
                    [FORCED_INSTALLATION] [REQUIRES_ADMIN_RIGHTS]
                    [NAME <name>]
                    [DISPLAY_NAME <display_name>] # Note: Internationalization supported
                    [DESCRIPTION <description>] # Note: Internationalization supported
                    [UPDATE_TEXT <update_text>]
                    [VERSION <version>]
                    [RELEASE_DATE <release_date>]
                    [SCRIPT <script>]
                    [PRIORITY|SORTING_PRIORITY <sorting_priority>] # Note: PRIORITY is deprecated
                    [DEPENDS|DEPENDENCIES <com_id> ...]
                    [AUTO_DEPEND_ON <comp_id> ...]
                    [LICENSES <display_name> <file_path> ...]
                    [DEFAULT <value>]
                    [USER_INTERFACES <file_path> <file_path> ...]
                    [TRANSLATIONS <file_path> <file_path> ...]
                    [REPLACES <comp_id> ...]
                    [CHECKABLE <value>])

This command should be called after the cpack_add_component() command. Order matters bestie โœจ

  • COMMON โ€” if set, then the component will be packaged and installed as part of a group to which it belongs.
  • ESSENTIAL โ€” Added in version 3.6. If set, then the package manager stays disabled until that component is updated.
  • VIRTUAL โ€” Added in version 3.8. If set, then the component will be hidden from the installer. It is a equivalent of the HIDDEN option from the cpack_add_component() command.
  • FORCED_INSTALLATION โ€” Added in version 3.8.

if set, then the component must always be installed โ€” it's literally the equivalent of the REQUIRED option from the cpack_add_component() command. ๐Ÿ’…

  • REQUIRES_ADMIN_RIGHTS โ€” Added in version 3.8. set this if the component needs to be installed with elevated permissions. admin energy only, bestie ๐Ÿ‘‘
  • NAME โ€” used to create a domain-like identification for this component. by default it uses the origin component name ๐Ÿท๏ธ
  • DISPLAY_NAME โ€” Added in version 3.8. set it to rewrite the original name configured by the cpack_add_component() command.
  • DESCRIPTION โ€” Added in version 3.8. set it to rewrite the original description configured by the cpack_add_component() command.
  • UPDATE_TEXT โ€” Added in version 3.8. gets added to the component description if this is an update to the component. โœจ
  • VERSION โ€” the version of the component. by default it uses CPACK_PACKAGE_VERSION.
  • RELEASE_DATE โ€” Added in version 3.8. keep it empty and it auto-generates, iconic ๐ŸŽ€
  • SCRIPT โ€” a relative or absolute path to the operations script for this component.
  • SORTING_PRIORITY โ€” Added in version 3.8. the priority of the component in the tree. ๐ŸŒณ
  • PRIORITY โ€” Deprecated since version 3.8: old name for SORTING_PRIORITY. it's giving legacy, use the new one ๐Ÿ’€
  • DEPENDS, DEPENDENCIES โ€” Added in version 3.8. list of dependency component or component group identifiers in QtIFW style.

Added in version 3.21. component or group names listed as dependencies may contain hyphens. this requires QtIFW 3.1 or later. ๐Ÿซถ

  • AUTO_DEPEND_ON โ€” Added in version 3.8. list of identifiers of a component or component group, in QtIFW style, that this component has an automatic dependency on.
  • LICENSES โ€” a pair of <display_name> and <file_path> of license text for this component. you can specify more then one license, no cap ๐Ÿ“œ
  • DEFAULT โ€” Added in version 3.8. possible values are: TRUE, FALSE, and SCRIPT. set it to FALSE to disable the component in the installer, or to SCRIPT to have it resolved during runtime (don't forget to add the file of the script as a value of the SCRIPT option!). ๐Ÿ™ˆ
  • USER_INTERFACES โ€” Added in version 3.7. a list of <file_path> ('.ui' files) representing pages to load.
  • TRANSLATIONS โ€” Added in version 3.8. a list of <file_path> ('.qm' files) representing translations to load. ๐ŸŒˆ
  • REPLACES โ€” Added in version 3.10. list of identifiers of component or component group to replace.
  • CHECKABLE โ€” Added in version 3.10. possible values are: TRUE, FALSE. set it to FALSE if you want to hide the checkbox for an item. this is useful when only a few subcomponents should be selected instead of all. โœ…

cpack_ifw_configure_component_group ๐Ÿ’–

sets the arguments specific to the CPack IFW generator. it's the group-level twin of the command above, periodt.

cpack_ifw_configure_component_group(<groupname> [VIRTUAL]
                            [FORCED_INSTALLATION] [REQUIRES_ADMIN_RIGHTS]
                            [NAME <name>]
                            [DISPLAY_NAME <display_name>] # Note: Internationalization supported
                            [DESCRIPTION <description>] # Note: Internationalization supported
                            [UPDATE_TEXT <update_text>]
                            [VERSION <version>]
                            [RELEASE_DATE <release_date>]
                            [SCRIPT <script>]
                            [PRIORITY|SORTING_PRIORITY <sorting_priority>] # Note: PRIORITY is deprecated
                            [DEPENDS|DEPENDENCIES <com_id> ...]
                            [AUTO_DEPEND_ON <comp_id> ...]
                            [LICENSES <display_name> <file_path> ...]
                            [DEFAULT <value>]
                            [USER_INTERFACES <file_path> <file_path> ...]
                            [TRANSLATIONS <file_path> <file_path> ...]
                            [REPLACES <comp_id> ...]
                            [CHECKABLE <value>])

this command should be called after the cpack_add_component_group() command. order matters, bestie, don't skip steps ๐Ÿซก

  • VIRTUAL โ€” Added in version 3.8. if set, then the group will be hidden from the installer. note that setting this on a root component does not work โ€” it's giving invisible but not that invisible ๐Ÿ’€
  • FORCED_INSTALLATION โ€” Added in version 3.8. if set, then the group must always be installed. no takebacks โœ‹
  • REQUIRES_ADMIN_RIGHTS โ€” Added in version 3.8. set it if the component group needs to be installed with elevated permissions. ๐Ÿ‘‘
  • NAME โ€” used to create a domain-like identification for this component group. by default it uses the origin component group name.
  • DISPLAY_NAME โ€” Added in version 3.8. set it to rewrite the original name configured by the cpack_add_component_group() command.
  • DESCRIPTION โ€” Added in version 3.8. set it to rewrite the original description configured by the cpack_add_component_group() command.
  • UPDATE_TEXT โ€” Added in version 3.8. gets added to the component group description if this is an update to the component group.
  • VERSION โ€” the version of the component group. by default it uses CPACK_PACKAGE_VERSION.
  • RELEASE_DATE โ€” Added in version 3.8. keep it empty to auto generate ๐ŸŽ€
  • SCRIPT โ€” a relative or absolute path to the operations script for this component group.
  • SORTING_PRIORITY โ€” the priority of the component group in the tree ๐ŸŒณ
  • PRIORITY โ€” Deprecated since version 3.8: old name for SORTING_PRIORITY. yeah it's the same deal as before, don't use it ๐Ÿ™ˆ
  • DEPENDS, DEPENDENCIES โ€” Added in version 3.8. list of dependency component or component group identifiers in QtIFW style.

Added in version 3.21. component or group names listed as dependencies may contain hyphens. this requires QtIFW 3.1 or later. ๐Ÿซถ

  • AUTO_DEPEND_ON โ€” Added in version 3.8. list of identifiers of a component or component group, in QtIFW style, that this component group has an automatic dependency on.
  • LICENSES โ€” a pair of <display_name> and <file_path> of license text for this component group. you can specify more then one license ๐Ÿ“œ
  • DEFAULT โ€” Added in version 3.8. possible values are: TRUE, FALSE, and SCRIPT. set it to TRUE to preselect the group in the installer (this takes effect only on groups that have no visible child components) or to SCRIPT to have it resolved during runtime (don't forget to add the file of the script as a value of the SCRIPT option!). note that this one is TRUE, not FALSE like the component version โ€” read carefully bestie ๐Ÿ‘€
  • USER_INTERFACES โ€” Added in version 3.7. a list of <file_path> ('.ui' files) representing pages to load.
  • TRANSLATIONS โ€” Added in version 3.8. a list of <file_path> ('.qm' files) representing translations to load ๐ŸŒˆ
  • REPLACES โ€” Added in version 3.10. list of identifiers of component or component group to replace.
  • CHECKABLE โ€” Added in version 3.10. possible values are: TRUE, FALSE. set it to FALSE if you want to hide the checkbox for an item. this is useful when only a few subcomponents should be selected instead of all. โœ…

cpack_ifw_add_repository ๐Ÿฆ‹

adds a QtIFW-specific remote repository to the binary installer. remote girlies rise ๐Ÿซถ

cpack_ifw_add_repository(<reponame> [DISABLED]
                            URL <url>
                            [USERNAME <username>]
                            [PASSWORD <password>]
                            [DISPLAY_NAME <display_name>])

this command will also add the <reponame> repository to a variable CPACK_IFW_REPOSITORIES_ALL. sneaky double duty, love that for us โœจ

  • DISABLED โ€” if set, then the repository will be disabled by default.
  • URL โ€” points to a list of available components.
  • USERNAME โ€” used as the user on a protected repository. ๐Ÿ”
  • PASSWORD โ€” the password to use on a protected repository.
  • DISPLAY_NAME โ€” a string to display instead of the URL. so much cuter than raw links ๐Ÿ’…

cpack_ifw_update_repository โญ

Added in version 3.6. updates a QtIFW-specific repository from a remote repository.

cpack_ifw_update_repository(<reponame>
                            [[ADD|REMOVE] URL <url>]|
                             [REPLACE OLD_URL <old_url> NEW_URL <new_url>]]
                            [USERNAME <username>]
                            [PASSWORD <password>]
                            [DISPLAY_NAME <display_name>])

this command will also add the <reponame> repository to a variable CPACK_IFW_REPOSITORIES_ALL. yes, same flex as above ๐Ÿ˜Œ

  • URL โ€” points to a list of available components.
  • OLD_URL โ€” points to a list that will be replaced.
  • NEW_URL โ€” points to a list that will replace it.
  • USERNAME โ€” used as the user on a protected repository. ๐Ÿ”
  • PASSWORD โ€” the password you use on a repository that's password-protected. ๐Ÿ”
  • DISPLAY_NAME โ€” the string that gets shown instead of the URL. so if the URL is giving ugly, this is the glow-up โœจ

  • cpack_ifw_add_package_resources โ€” Added in version 3.8.</p>

bestie this one drops extra resources right into the installer binary ๐Ÿ’…

cpack_ifw_add_package_resources(<file_path> <file_path> ...)

it also tosses the files you listed into a variable called CPACK_IFW_PACKAGE_RESOURCES. two birds, one slay. ๐Ÿฆ

๐ŸŽ€ CPackIFWConfigureFile ๐ŸŽ€

Added in version 3.8.

okay so this module hands you a command that's basically configure_file()'s cooler cousin โ€” it's for configuring file templates that were prepped in QtIFW/SDK/Creator style. ๐Ÿงš

load it into your CMake project like this:

include(CPackIFWConfigureFile)

๐Ÿ’– Commands ๐Ÿ’–

this module gives you exactly one command, and she's iconic:

  • cpack_ifw_configure_file โ€” copies a file template over to the output file, and swaps out variable values that are referenced as %{VAR} or %VAR% from the input file template content:
cpack_ifw_configure_file(<input> <output>)
  • <input> โ€” the input file template. if you hand it a relative path, it's interpreted as relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR). ๐Ÿ“‚
  • <output> โ€” the output file. if you hand it a relative path, it's interpreted as relative to the current binary directory (CMAKE_CURRENT_BINARY_DIR). ๐Ÿ“

so here's the lore: Qt Installer Framework (QtIFW) uses @ characters to embed predefined variables (TargetDir, StartMenuDir, etc.) inside Qt installer scripts, like this:

example.qs

component.addOperation(
  "CreateShortcut",
  "@TargetDir@/example.com.html",
  "@StartMenuDir@/Example Web Site.lnk"
);

the whole reason this command exists is to preserve those QtIFW predefined variables that have the @ characters (@VAR@), and use % characters for the template placeholders instead (%VAR%, %{VAR}) in Qt/IFW/SDK/Creator templates. because the configure_file() command would otherwise go and replace every variable reference that contains @ characters ๐Ÿ˜ญ which is NOT the vibe.

every variable reference gets replaced with the current value of that variable โ€” or, if the variable isn't defined, with an empty string. ๐Ÿซถ

๐ŸŒธ Examples ๐ŸŒธ

in this example the module is used to create an IFW component script from a template file qt.tools.foo.qs.in, where the %FOO_DOC_DIR% variable reference gets replaced by the value of the FOO_DOC_DIR CMake variable. periodt.

CMakeLists.txt

cmake_minimum_required(VERSION 3.8)

project(Foo)

# ...

include(CPackIFWConfigureFile)

set(FOO_DOC_DIR "doc/foo")

cpack_ifw_configure_file(qt.tools.foo.qs.in qt.tools.foo.qs)

qt.tools.foo.qs.in

function Component()
{
}

Component.prototype.createOperations = function()
{
  if (installer.value("os") === "win") {
    component.addOperation(
      "CreateShortcut",
      "@TargetDir@/%FOO_DOC_DIR%/example.com.html",
      "@StartMenuDir@/Example Web Site.lnk"
    );
  }

  component.createOperations();
}

// ...

๐Ÿ’œ See Also ๐Ÿ’œ

  • The CPack IFW Generator. ๐Ÿ”ฅ
  • The CPackIFW module.

๐ŸŒˆ CSharpUtilities ๐ŸŒˆ

Added in version 3.8.

this utility module is literally here to make configuring CSharp/.NET targets easier โ€” it's a whole little collection of commands for managing CSharp targets with Visual Studio Generators, version 2010 and newer. ๐Ÿ’…

load her up in a CMake project with:

include(CSharpUtilities)

โœจ Commands โœจ

this module provides the following commands:

Main Commands ๐Ÿ‘‘

  • csharp_set_windows_forms_properties()
  • csharp_set_designer_cs_properties()
  • csharp_set_xaml_cs_properties()

Helper Commands ๐Ÿ› ๏ธ

  • csharp_get_filename_keys()
  • csharp_get_filename_key_base()
  • csharp_get_dependentupon_name()

๐Ÿ‘‘ Main Commands ๐Ÿ‘‘

  • csharp_set_windows_forms_properties โ€” sets source file properties so you can use Windows Forms:
csharp_set_windows_forms_properties([<files>...])
  • <files>... โ€” a list of zero or more source files that matter for setting the VS_CSHARP_<tagname> source file properties. this typically includes files with .cs, .resx, and .Designer.cs extensions.

use this one when a CSharp target in your project uses Windows Forms. ๐ŸชŸ

it searches the list of files you gave it for pairs of related files ending in .Designer.cs (designer files) or .resx (resource files). for each of those, it looks for a corresponding base .cs file (same base name). when it finds one, the VS_CSHARP_<tagname> source file properties get set like this:

  • For the .cs file:
    • VS_CSHARP_SubType "Form"
  • For the .Designer.cs file (if it exists):
    • VS_CSHARP_DependentUpon <cs-filename>
    • VS_CSHARP_DesignTime "" (the tag gets removed if it was previously defined)
    • VS_CSHARP_AutoGen "" (the tag gets removed if it was previously defined)
  • For the .resx file (if it exists):
    • VS_RESOURCE_GENERATOR "" (the tag gets removed if it was previously defined)
    • VS_CSHARP_DependentUpon <cs-filename>
    • VS_CSHARP_SubType "Designer"
  • csharp_set_designer_cs_properties โ€” sets source file properties for .Designer.cs files, based on their sibling filenames:
csharp_set_designer_cs_properties([<files>...])
  • <files>... โ€” a list of zero or more source files that matter for setting the VS_CSHARP_<tagname> source file properties. this typically includes files with .resx, .settings, and .Designer.cs extensions.

use this command if the CSharp target does not use Windows Forms (for Windows Forms, use csharp_set_windows_forms_properties() instead, bestie, don't mix them up ๐Ÿ™ˆ).

it searches the list you provided for files ending in .Designer.cs (designer files). for each one, it hunts for sibling files with the same base name but different extensions. if it finds a matching file, the right source file properties get set on the corresponding .Designer.cs file, based on which extension matched:

  • If the match is a .resx file:
    • VS_CSHARP_AutoGen "True"
    • VS_CSHARP_DesignTime "True"
    • VS_CSHARP_DependentUpon <resx-filename>
  • If the match is a .cs file:
    • VS_CSHARP_DependentUpon <cs-filename>
  • If the match is a .settings file:
    • VS_CSHARP_AutoGen "True"
    • VS_CSHARP_DesignTimeSharedInput "True"
    • VS_CSHARP_DependentUpon <settings-filename>
Note: because the source file properties of the .Designer.cs file get set according to whatever matches were found โ€” and every single match sets the VS_CSHARP_DependentUpon source file property โ€” there should only be one match for each Designer.cs file. one. not two. not three. one. ๐Ÿ’€
  • csharp_set_xaml_cs_properties โ€” sets source file properties so you can use Windows Presentation Foundation (WPF) and XAML:
csharp_set_xaml_cs_properties([<files>...])

use this command if the CSharp target uses WPF/XAML. ๐Ÿฆ‹

  • <files>... โ€” a list of zero or more source files that matter for setting the VS_CSHARP_<tagname> source file properties. this typically includes files with .cs, .xaml, and .xaml.cs extensions.

it searches the file list you gave it for files ending in .xaml.cs. for each of those XAML code-behind files, it looks for a corresponding .xaml file with the same base name. if it finds one, the following source file property gets set on the .xaml.cs file:

  • VS_CSHARP_DependentUpon <xaml-filename>

๐Ÿ› ๏ธ Helper Commands ๐Ÿ› ๏ธ

these commands get used by the main commands above, so you typically won't reach for them directly โ€” they're the backstage crew, not the main character ๐Ÿ’…

  • csharp_get_filename_keys โ€” computes a normalized list of key values so you can identify source files independently of whether CMake was given relative or absolute paths, and so it stops caring about case sensitivity:
csharp_get_filename_keys(<variable> [<files>...])
  • <variable> โ€” the name of the variable where the list of computed keys gets stored.
  • <files>... โ€” zero or more source file paths, exactly as given to a CSharp target using commands like add_library() or add_executable().

this command canonicalizes file paths so source files get identified consistently. super useful when source files are added to a target using different path forms. because without normalization, CMake may treat paths like myfile.Designer.cs and ${CMAKE_CURRENT_SOURCE_DIR}/myfile.Designer.cs as two different files ๐Ÿ˜ญ which then causes chaos when you're setting source file properties.

for example, the following code will fail to set properties, because the file paths don't match exactly:

add_library(lib myfile.cs ${CMAKE_CURRENT_SOURCE_DIR}/myfile.Designer.cs)

set_source_files_properties(
  myfile.Designer.cs
  PROPERTIES VS_CSHARP_DependentUpon myfile.cs
)
  • csharp_get_filename_key_base โ€” returns the full filepath and name without the extension, for a given key:
csharp_get_filename_key_base(<base> <key>)
  • <base> โ€” the name of the variable holding the computed base value of the <key>, without the file extension.
  • <key> โ€” the key whose base will be computed. it's expected to be an uppercase full filename coming out of csharp_get_filename_keys().
  • csharp_get_dependentupon_name โ€” computes a string that can be used as the value for the source file property VS_CSHARP_<tagname>, where <tagname> is DependentUpon:
  • <variable> โ€” the name of the variable that'll hold the result ๐Ÿ’–. Its value is the name of <file> with the directory part yeeted out.
  • <file> โ€” the filename you're converting so it can be used as the value of the VS_CSHARP_DependentUpon source file property.

๐Ÿงช CTest

Configure a whole project for testing with CTest/CDash โ€” the classic glow-up for your build ๐ŸŽ€

Drop this module into the top CMakeLists.txt file of a project to enable testing with CTest and dashboard submissions to CDash:

project(MyProject)
...
include(CTest)

The module automatically creates this variable:

BUILD_TESTING โ€” an option that selects whether include(CTest) calls enable_testing(). It's ON by default when created by the module. โœจ

After including the module, use code like this:

if(BUILD_TESTING)
  # ... CMake code to create tests ...
endif()

โ€ฆto actually make tests when testing is enabled, bestie. Then to enable submissions to a CDash server, create a CTestConfig.cmake file at the top of the project with content such as:

set(CTEST_NIGHTLY_START_TIME "01:00:00 UTC")
set(CTEST_SUBMIT_URL "http://my.cdash.org/submit.php?project=MyProject")

The CDash server can hand that file to a project administrator who configures MyProject. Settings in the config file are shared by both this CTest module and the ctest(1) command-line Dashboard Client mode (ctest -S). Sharing is caring, fr fr ๐Ÿ’…

While building a project for submission to CDash, CTest scans the build output for errors and warnings and reports them with surrounding context from the build log. This generic approach works for all build tools, but lowkey it does not give details about the command invocation that produced a given problem. You can get more detailed reports by setting the CTEST_USE_LAUNCHERS variable:

set(CTEST_USE_LAUNCHERS 1)

โ€ฆin the CTestConfig.cmake file. Iconic behaviour honestly.


๐Ÿ“Š CTestCoverageCollectGCOV

Added in version 3.2. ๐Ÿฆ‹

This module is intended for use in CTest dashboard scripts and provides a command to generate a tarball containing code coverage reports.

Load this module in a CTest script with:

include(CTestCoverageCollectGCOV)

Commands

This module provides the following command:

ctest_coverage_collect_gcov โ€” runs gcov and packages a tar file for CDash:

ctest_coverage_collect_gcov(
  TARBALL <tar-file>
  [TARBALL_COMPRESSION <compression>]
  [SOURCE <source-dir>]
  [BUILD <build-dir>]
  [GCOV_COMMAND <gcov-command>]
  [GCOV_OPTIONS <options>...]
  [GLOB]
  [DELETE]
  [QUIET]
)

This command runs gcov on all .gcda files found in the binary tree and packages the resulting .gcov files into a tar file, along with the following โœจ:

  • data.json file that defines the source and build directories for use by CDash.
  • Labels.json files that indicate any LABELS that have been set on the source files.
  • The uncovered directory containing any uncovered files found by CTEST_EXTRA_COVERAGE_GLOB.

The resulting tar file can be submitted to CDash for display using the ctest_submit(CDASH_UPLOAD) command. ๐Ÿซถ

The arguments are:

  • TARBALL <tar-file> โ€” specify the location of the .tar file to be created for later upload to CDash. Relative paths will be interpreted with respect to the top-level build directory.
  • TARBALL_COMPRESSION <compression> โ€” Added in version 3.18. Specify a compression algorithm for the TARBALL data file. Using this option reduces the size of the data file before it is submitted to CDash. <compression> should be one of the following:
    • GZIP
    • BZIP2
    • LZMA โ€” Added in version 4.3.
    • LZMA2 โ€” Added in version 4.3. This is an alias for XZ.
    • XZ
    • ZSTD
    • FROM_EXT
    • An expression that CMake evaluates as FALSE

The default value is BZIP2.

If FROM_EXT is specified, the resulting file will be compressed based on the file extension of the <tar-file> (i.e. .tar.gz will use GZIP compression). File extensions that will produce compressed output include:

  • .tar.gz
  • .tgz
  • .tar.bzip2
  • .tbz
  • .tar.xz
  • .txz
  • .tar.lzma โ€” Added in version 4.3.
  • .tlzma โ€” Added in version 4.3.
  • .tar.zst โ€” Added in version 4.3.
  • .tzst โ€” Added in version 4.3.
  • SOURCE <source-dir> โ€” specify the top-level source directory for the build. Default is the value of CTEST_SOURCE_DIRECTORY.
  • BUILD <build-dir> โ€” specify the top-level build directory for the build. Default is the value of CTEST_BINARY_DIRECTORY.
  • GCOV_COMMAND <gcov-command> โ€” specify the full path to the gcov command on the machine. Default is the value of CTEST_COVERAGE_COMMAND.
  • GCOV_OPTIONS <options>... โ€” specify options to be passed to gcov. The gcov command is run as gcov <options>... -o <gcov-dir> <file>.gcda. If not specified, the default option is just -b -x.
  • GLOB โ€” Added in version 3.6. Recursively search for .gcda files in <build-dir> rather than determining search locations by reading CMakeFiles/TargetDirectories.txt (file generated by CMake at the generation phase).
  • DELETE โ€” Added in version 3.6. Delete coverage files after they've been packaged into the .tar.
  • QUIET โ€” suppress non-error messages that otherwise would have been printed out by this command. ๐Ÿคซ
Added in version 3.3: added support for the CTEST_CUSTOM_COVERAGE_EXCLUDE variable.

Examples

Generating code coverage data packaged as a .tar.gz file in a ctest -S script:

script.cmake

include(CTestCoverageCollectGCOV)

ctest_coverage_collect_gcov(
  TARBALL "${CTEST_BINARY_DIRECTORY}/gcov.tar.gz"
  TARBALL_COMPRESSION "GZIP"
)

๐Ÿš€ CTestUseLaunchers

This module sets the RULE_LAUNCH_* global properties when the CTEST_USE_LAUNCHERS variable is set to a true-like value (e.g., ON):

  • RULE_LAUNCH_COMPILE
  • RULE_LAUNCH_CUSTOM
  • RULE_LAUNCH_LINK

Load this module in a CMake project with:

include(CTestUseLaunchers)

The CTestUseLaunchers module is automatically included by the CTest module when include(CTest) is called. However, it's provided as a separate module so that projects can use the CTEST_USE_LAUNCHERS functionality independently. Independence queen ๐Ÿ‘‘

To use launchers, set the CTEST_USE_LAUNCHERS variable to a true-like value in a ctest -S dashboard script, and then also set the CTEST_USE_LAUNCHERS cache variable in the configured project. Both cmake and ctest must be aware of its value for the launchers to function correctly:

  • cmake needs it to generate the appropriate build rules
  • ctest requires it for accurate error and warning analysis

For convenience, the environment variable CTEST_USE_LAUNCHERS_DEFAULT may be set in the ctest -S script. Then, as long as the CMakeLists.txt includes the CTest or CTestUseLaunchers module, it will use the value of the environment variable to initialize a CTEST_USE_LAUNCHERS cache variable. This cache variable initialization only occurs if CTEST_USE_LAUNCHERS is not already defined. ๐ŸŒธ

Added in version 3.8: if CTEST_USE_LAUNCHERS is set to a true-like value in a ctest -S script, the ctest_configure() command will add -DCTEST_USE_LAUNCHERS:BOOL=TRUE to the cmake command when configuring the project.

Examples

set(CTEST_USE_LAUNCHERS ON)
include(CTestUseLaunchers)

๐Ÿงš DeployQt4

Note: this module is for Qt version 4. New code should follow the cmake-qt(7) instead of using this module. It's giving legacy, bestie โ€” retire it gracefully ๐Ÿ’€

This module provides a collection of CMake utility commands useful for assembling and deploying standalone Qt4 executables.

Load this module in a CMake project with:

include(DeployQt4)

Commands

This module provides the following commands:

  • write_qt4_conf()
  • resolve_qt4_paths()
  • fixup_qt4_executable()
  • install_qt4_plugin_path()
  • install_qt4_plugin()
  • install_qt4_executable()

write_qt4_conf โ€” creates a Qt configuration file:

write_qt4_conf(<qt-conf-dir> <qt-conf-contents>)

This command writes a qt.conf file with the <qt-conf-contents> into the <qt-conf-dir> directory. โœจ

resolve_qt4_paths โ€” resolves relative paths to absolute:

resolve_qt4_paths(<paths-var> [<executable-path>])

This command loops through the <paths-var> list and if any path doesn't exist, it resolves them relative to the <executable-path> (if supplied) or the CMAKE_INSTALL_PREFIX. ๐ŸŽ€

fixup_qt4_executable โ€” fixes up a Qt4 executable:

fixup_qt4_executable(
  <executable>
  [<qtplugins> <libs> <dirs> <plugins-dir> <request-qt-conf>]
)

This command is basically the full glow-up routine for a Qt4 executable: it copies your Qt plugins, writes a Qt configuration file (but only if it's actually needed, ngl) and fixes up a Qt4 executable using the BundleUtilities module so it comes out fully standalone โ€” like, drag-and-drop-it-onto-another-machine standalone, as long as all of the system libraries are compatible. โœจ

  • <executable> โ€” point this at the executable getting the fix-up treatment. That's the main character here.
  • <qtplugins> โ€” a list of the names or paths of any Qt plugins you want installed.
  • <libs> โ€” gets passed straight through to the BundleUtilities module, and should be a list of any already-installed plugins, libraries or executables that also need fixing up.
  • <dirs> โ€” also passed to the BundleUtilities module; these are the directories it searches to find library dependencies.
  • <plugins-dir> โ€” lets you use a custom plugins directory if the default one isn't the vibe.
  • <request-qt-conf> โ€” forces a qt.conf file to be written even when it isn't needed.

install_qt4_plugin_path

Installs a resolved Qt4 plugin ๐ŸŽ€

install_qt4_plugin_path(
  <plugin>
  <executable>
  <copy>
  <installed-plugin-path-var>
  [<plugins-dir> <component> <configurations>]
)

So what it does: it installs (or copies, depends) a resolved <plugin> into the default plugins directory โ€” or into <plugins-dir> if you passed one โ€” relative to <executable>, and it stashes the result in the variable named by <installed-plugin-path-var>. ๐Ÿซถ

  • If <copy> is set to TRUE, the plugins get copied instead of installed. That's the whole point โ€” it lets you use this module at CMake time instead of waiting for install time.
  • If <component> is set, anything installed uses that COMPONENT.

install_qt4_plugin

Installs an unresolved Qt4 plugin ๐Ÿ’…

install_qt4_plugin(
  <plugin>
  <executable>
  <copy>
  <installed-plugin-path-var>
  [<plugins-dir> <component>]
)

Same energy as above but for an unresolved <plugin>: it installs (or copies) it to the default plugins directory (or <plugins-dir>) relative to <executable> and stores the result in <installed-plugin-path-var>. For the other arguments, literally just go read install_qt4_plugin_path() โ€” they're the same deal.

install_qt4_executable

Installs Qt plugins, writes a Qt configuration file (if needed) and fixes up a Qt4 executable โ€” the full combo meal ๐Ÿ”ฅ

install_qt4_executable(
  <executable>
  [<qtplugins> <libs> <dirs> <plugins-dir> <request-qt-conf> <component>]
)

This one leans on the BundleUtilities module so the executable ends up standalone and can be drag-and-drop copied to another machine as long as all of the system libraries are compatible. The fix-up happens at install time. The <component> is the COMPONENT used for bundle fixup and plugin installation. For the rest of the arguments, see fixup_qt4_executable() โ€” same cast of characters, no cap.


ExternalData

This module hands you commands to manage data files that live outside the source tree. ๐Ÿฆ‹

Load it into a CMake project like this:

include(ExternalData)

Introduction

Use this module when you want to unambiguously reference data files stored outside the source tree, and then fetch them at build time from arbitrary local and remote content-addressed locations. The functions it gives you recognize arguments written as DATA{<name>}, treat them as references to external data, swap them out for full paths to local copies of that data, and set up build rules to fetch and update those local copies. Iconic behaviour, honestly. โœจ

For example:

include(ExternalData)
set(ExternalData_URL_TEMPLATES "file:///local/%(algo)/%(hash)"
                               "file:////host/share/%(algo)/%(hash)"
                               "http://data.org/%(algo)/%(hash)")
ExternalData_Add_Test(MyData
  NAME MyTest
  COMMAND MyExe DATA{MyInput.png}
  )
ExternalData_Add_Target(MyData)

When the test MyTest runs, that DATA{MyInput.png} argument gets replaced by the full path to a real instance of the data file MyInput.png sitting on disk. And if your source tree contains a content link like MyInput.png.md5, then the MyData target creates a real MyInput.png in the build tree. Slay. ๐Ÿ’…

Module Functions

ExternalData_Expand_Arguments

The ExternalData_Expand_Arguments function evaluates DATA{} references inside its arguments and builds you a brand-new list of arguments:

ExternalData_Expand_Arguments(
  <target>   # Name of data management target
  <outVar>   # Output variable
  [args...]  # Input arguments, DATA{} allowed
  )

It replaces every DATA{} reference in an argument with the full path of a real data file on disk โ€” one that will exist after <target> builds. ๐ŸŽ€

ExternalData_Add_Test

The ExternalData_Add_Test function wraps around the CMake add_test() command, except it actually supports DATA{} references in its arguments:

ExternalData_Add_Test(
  <target>   # Name of data management target
  ...        # Arguments of add_test(), DATA{} allowed
  )

It pushes its arguments through ExternalData_Expand_Arguments and then calls add_test() with the results.

Changed in version 3.31: if the arguments after <target> define a test whose executable is a CMake target, then empty values in that target's TEST_LAUNCHER and CROSSCOMPILING_EMULATOR properties are preserved. See policy CMP0178. ๐Ÿ‘‘

ExternalData_Add_Target

The ExternalData_Add_Target function creates a custom target that manages the local instances of your externally stored data files:

ExternalData_Add_Target(
  <target>                  # Name of data management target
  [SHOW_PROGRESS <ON|OFF>]  # Show progress during the download
  )

It creates custom commands inside the target as needed to make data files available for each DATA{} reference that other functions from this module already evaluated. Data files can be fetched from one of the URL templates listed in the ExternalData_URL_TEMPLATES variable, or they can be found locally in one of the paths listed in the ExternalData_OBJECT_STORES variable. ๐ŸŒˆ

Added in version 3.20: you can pass the SHOW_PROGRESS argument to suppress progress info while objects download. If you don't pass it, it defaults to OFF for the Ninja and Ninja Multi-Config generators, and ON for everything else.

Typically you only need one target to manage all the external data in a project โ€” call this function once, at the end of configuration, after all the data references have been processed. Periodt.

Module Variables

The following variables configure how this thing behaves. Set them before you call any of the functions this module provides. ๐Ÿซถ

ExternalData_BINARY_ROOT

You can set ExternalData_BINARY_ROOT to the directory that holds the real data files named by expanded DATA{} references. Default is CMAKE_BINARY_DIR. The directory layout mirrors the layout of content links under ExternalData_SOURCE_ROOT.

ExternalData_CUSTOM_SCRIPT_<key>

Added in version 3.2.

Give this a full path to a .cmake custom fetch script, identified by <key> in entries of the ExternalData_URL_TEMPLATES list. See Custom Fetch Scripts.

ExternalData_HTTPHEADERS

Added in version 4.0.

Use ExternalData_HTTPHEADERS to supply a list of headers, where each element contains one header in the form Key: Value. See the HTTPHEADER option of the file(DOWNLOAD) command. ๐ŸŒธ

Set ExternalData_LINK_CONTENT to the name of a supported hash algorithm to turn on automatic conversion of real data files referenced by the DATA{} syntax into content links. For each such <file>, a content link named <file><ext> gets created. The original file is renamed to the form .ExternalData_<algo>_<hash> so it's staged for future transmission to one of the locations in the list of URL templates (by means outside the scope of this module, iykyk). The data fetch rule created for the content link will use that staged object if the file can't be found using any URL template.

Added in version 3.3.

On some platforms, the real data files named by expanded DATA{} references may be made available under ExternalData_BINARY_ROOT using symbolic links. Set ExternalData_NO_SYMLINKS to disable symbolic links and use copies instead. ๐Ÿฆ‹

ExternalData_STATE_ROOT

Added in version 4.4.

Set ExternalData_STATE_ROOT to place module-managed metadata outside ExternalData_BINARY_ROOT. When it's set, ExternalData stores its hash records under this directory while still materializing the real data files under ExternalData_BINARY_ROOT. By default, hash records keep being placed right next to the materialized data, just like before.

Added in version 4.4.

ExternalData_LINK_MODE picks how real data files are exposed under ExternalData_BINARY_ROOT. ๐Ÿ’ซ

The value can be one of:

  • auto โ€” try each of the supported modes until one succeeds. The default order is hardlink -> symlink -> copy on Windows, and symlink -> hardlink -> copy on other platforms.
  • hardlink โ€” materialize paths as hard links to the real files.
  • symlink โ€” materialize paths as symbolic links to the real files.
  • copy โ€” materialize paths as copies of the real files.

Or the value can be a semicolon-separated list of hardlink, symlink, and copy โ€” then it tries those modes in the order you specified until one succeeds. โญ

When ExternalData_NO_SYMLINKS is set, the symlink mode gets dropped from automatic selection and you cannot request it explicitly. Not even a little. ๐Ÿ™ˆ

  • ExternalData_OBJECT_STORES โ€” set this to a list of local directories that stash objects using the layout <dir>/%(algo)/%(hash). These get searched first whenever an object is needed. If none of your stores have it, the thing gets fetched remotely through the URL templates and then dropped into the first local store you listed. No stores at all? Then the default is a location inside the build tree. โœจ
  • ExternalData_SERIES_PARSE, ExternalData_SERIES_PARSE_PREFIX, ExternalData_SERIES_PARSE_NUMBER, ExternalData_SERIES_PARSE_SUFFIX, ExternalData_SERIES_MATCH โ€” all five of these legends are explained over in Referencing File Series. Go look ๐Ÿ‘€
  • ExternalData_SOURCE_ROOT โ€” this one you set to the highest source directory that contains any path named by a DATA{} reference. Default is CMAKE_SOURCE_DIR. Heads up though: ExternalData_SOURCE_ROOT and CMAKE_SOURCE_DIR have to refer to directories inside a single source distribution (like, they come together in one tarball) ๐Ÿซถ
  • ExternalData_TIMEOUT_ABSOLUTE โ€” sets the download absolute timeout, in seconds, defaulting to 300 seconds. Set it to 0 to disable enforcement entirely.
  • ExternalData_TIMEOUT_INACTIVITY โ€” sets the download inactivity timeout, in seconds, defaulting to 60 seconds. Set it to 0 to disable enforcement entirely.
  • ExternalData_URL_ALGO_<algo>_<key> โ€” Added in version 3.3.

Use this to specify a custom URL component that gets substituted for URL template placeholders of the form %(algo:<key>), where <key> is a valid C identifier, when you're fetching an object referenced via hash algorithm <algo>. If you don't define it, the default URL component is just <algo> for any <key>. Slay, defaults ๐Ÿ’…

  • ExternalData_URL_TEMPLATES โ€” set this to a list of URL templates, each one using the placeholders %(algo) and %(hash). The data fetch rules try each URL template in order, substituting the hash algorithm name in for %(algo) and the hash value in for %(hash). Alternatively you can use %(algo:<key>) together with the ExternalData_URL_ALGO_<algo>_<key> variables for extra flexibility in your remote URLs. Big brain move ๐Ÿ”ฅ

โœจ Referencing Files

๐ŸŒธ Referencing Single Files

The DATA{} syntax is literal, and the <name> is a full or relative path inside the source tree. That source tree has to contain either a real data file at <name> or a "content link" at <name><ext> holding a hash of the real file, using a hash algorithm that corresponds to <ext>. So like, the argument DATA{img.png} can be satisfied by a real img.png file sitting in the current source directory, or by an img.png.md5 file containing its MD5 sum. Either way she's covered ๐Ÿ’–

Added in version 3.8: multiple content links of the same name with different hash algorithms are supported (think img.png.sha256 and img.png.sha1) as long as they all correspond to the same real file. This is what lets objects be fetched from sources indexed by different hash algorithms. Iconic.

๐Ÿฆ‹ Referencing File Series

You can tell the DATA{} syntax to fetch a whole file series with the form DATA{<name>,:}, where that : is literal. If the source tree has a group of files or content links named like a series, then referencing one member adds rules to fetch all of them. And yes โ€” even though every member of the series gets fetched, only the file originally named by the DATA{} argument is substituted in for it. Ngl that's kind of the whole point ๐Ÿ˜Œ

The default config recognizes file series names ending with #.ext, _#.ext, .#.ext, or -#.ext, where # is a sequence of decimal digits and .ext is any single extension. Configure it with a regex that parses the <number> and <suffix> parts off the end of <name>:

ExternalData_SERIES_PARSE - regex of the form (<number>)(<suffix>)$.

For the more complicated cases, set these:

  • ExternalData_SERIES_PARSE โ€” regex with at least two () groups.
  • ExternalData_SERIES_PARSE_PREFIX โ€” regex group number of the <prefix>, if any.
  • ExternalData_SERIES_PARSE_NUMBER โ€” regex group number of the <number>.
  • ExternalData_SERIES_PARSE_SUFFIX โ€” regex group number of the <suffix>.

Then configure series number matching with a regex that matches the <number> part of series members named <prefix><number><suffix>:

ExternalData_SERIES_MATCH - regex matching <number> in all series members
Quick note bestie: the <suffix> of a series does not include a hash-algorithm extension. Don't get it twisted ๐Ÿ’€

๐ŸŽ€ Referencing Associated Files

The DATA{} syntax can also match files associated with the named file, living in that same directory. Associated files get specified by options using the syntax DATA{<name>,<opt1>,<opt2>,...}. Each option can specify one file by name, or specify a regular expression to match file names using the syntax REGEX:<regex>. For example, these arguments:

DATA{MyData/MyInput.mhd,MyInput.img}                   # File pair
DATA{MyData/MyFrames00.png,REGEX:MyFrames[0-9]+\\.png} # Series

will pass MyInput.mha and MyFrames00.png on the command line, but also make sure the associated files are present right next to them. Best of both worlds, fr fr ๐Ÿซถ

๐ŸŒˆ Referencing Directories

DATA{} can reference a directory too, using a trailing slash plus a list of associated files. The form DATA{<name>/,<opt1>,<opt2>,...} adds rules to fetch any files in the directory that match one of the associated file options. So for example, the argument DATA{MyDataDir/,REGEX:.*} passes the full path to a MyDataDir directory on the command line and ensures that directory contains files corresponding to every file or content link in the MyDataDir source directory. Obsessed with the efficiency ๐Ÿ’…

Added in version 3.3: to match associated files in subdirectories, specify a RECURSE: option, e.g. DATA{MyDataDir/,RECURSE:,REGEX:.*}. It goes deeper. It always goes deeper ๐Ÿงš

๐Ÿ‘‘ Hash Algorithms

These are the hash algorithms that are supported:

  • %(algo) = MD5, <ext> = .md5 โ€” Message-Digest Algorithm 5, RFC 1321
  • %(algo) = SHA1, <ext> = .sha1 โ€” US Secure Hash Algorithm 1, RFC 3174
  • %(algo) = SHA224, <ext> = .sha224 โ€” US Secure Hash Algorithms, RFC 4634
  • %(algo) = SHA256, <ext> = .sha256 โ€” US Secure Hash Algorithms, RFC 4634
  • %(algo) = SHA384, <ext> = .sha384 โ€” US Secure Hash Algorithms, RFC 4634
  • %(algo) = SHA512, <ext> = .sha512 โ€” US Secure Hash Algorithms, RFC 4634
  • %(algo) = SHA3_224, <ext> = .sha3-224 โ€” Keccak SHA-3
  • %(algo) = SHA3_256, <ext> = .sha3-256 โ€” Keccak SHA-3
  • %(algo) = SHA3_384, <ext> = .sha3-384 โ€” Keccak SHA-3
  • %(algo) = SHA3_512, <ext> = .sha3-512 โ€” Keccak SHA-3

Added in version 3.8: the SHA3_* hash algorithms were added โœจ

Keep in mind the hashes are used only for unique data identification and download verification. That's it. They're not doing anything else for you, bestie ๐Ÿ“

โญ Custom Fetch Scripts

Added in version 3.2.

When a data file has to be fetched from one of the URL templates you listed in ExternalData_URL_TEMPLATES, it normally gets downloaded using the file(DOWNLOAD) command. But you can specify a custom fetch script instead, using a URL template of the form ExternalDataCustomScript://<key>/<loc>. The <key> has to be a C identifier, and the <loc> has to contain the %(algo) and %(hash) placeholders. A variable matching that key, ExternalData_CUSTOM_SCRIPT_<key>, must be set to the full path of a .cmake script file. That script gets included to do the actual fetching, and it's handed the following variables:

  • ExternalData_CUSTOM_LOCATION โ€” when a custom fetch script is loaded, this variable is set to the location part of the URL, which contains the substituted hash algorithm name and content hash value.
  • ExternalData_CUSTOM_FILE โ€” when a custom fetch script is loaded, this variable is set to the full path of a file where the script must store the fetched content. The name of that file is unspecified, so don't you dare interpret it in any way ๐Ÿ™ˆ

The custom fetch script is expected to store the fetched content in that file, or set a variable:

  • ExternalData_CUSTOM_ERROR โ€” when a custom fetch script fails to fetch the requested content, it must set this variable to a short one-line message describing why it failed. Keep it cute, keep it one line.

๐Ÿ’œ ExternalProject

This module gives you commands to download and build external projects as part of the CMake build phase. Real main character energy for your dependencies ๐Ÿ”ฅ

Load this module in a CMake project with:

include(ExternalProject)

๐ŸŒŸ External Project Definition ๐ŸŒŸ

โœจ ExternalProject_Add โœจ

Okay bestie, so ExternalProject_Add() is literally the main character here โ€” it creates a custom target that drives the whole life of an external project: download, update/patch, configure, build, install, and test. Every step. The whole glow-up.

ExternalProject_Add(<name> [<option>...])

And the vibe? If you need to, the individual steps within the process can be driven independently (like for CDash submission, iykyk), plus you can define extra custom steps and control the step dependencies. The directory structure used for managing the external project is customizable too. This function supports a huge number of options so you can tailor the external project behavior however you want. Obsessed.


๐Ÿ“ Directory Options ๐Ÿ“

Most of the time the default directory layout is perfectly fine and you don't need to touch it โ€” it's largely an implementation detail that the main project usually doesn't need to change. But in some circumstances, control over the directory layout is useful or even necessary. And honestly these options are potentially more useful from the angle that the main build can use ExternalProject_Get_Property() to grab their values โ€” which lets the main project refer to build artifacts of the external project. Slay.

  • PREFIX <dir> โ€” root directory for the external project. Unless noted otherwise below, all the other directories associated with the external project get created under here.
  • TMP_DIR <dir> โ€” directory where temporary files live.
  • STAMP_DIR <dir> โ€” directory where the timestamps of each step are stored. Log files from individual steps also get created in here unless overridden by LOG_DIR (see Logging Options below).
  • LOG_DIR <dir> โ€” Added in version 3.14. Directory where the logs of each step are stored.
  • DOWNLOAD_DIR <dir> โ€” directory where downloaded files go before they're unpacked. This directory is only used by the URL download method; all other download methods use SOURCE_DIR directly instead.
  • SOURCE_DIR <dir> โ€” source directory into which downloaded contents get unpacked, or, for non-URL download methods, the directory where the repository should be checked out, cloned, etc. If no download method is specified, this has to point to an existing directory where the external project has already been unpacked or cloned/checked out.
Note: if a download method is specified, any existing contents of the source directory may be deleted ๐Ÿ’€. Only the URL download method checks whether this directory is either missing or empty before initiating the download, and it stops with an error if it's not empty. All the other download methods silently discard any previous contents of the source directory. No cap.
  • BINARY_DIR <dir> โ€” specifies the build directory location. This option is ignored if BUILD_IN_SOURCE is enabled.
  • INSTALL_DIR <dir> โ€” installation prefix to be placed in the <INSTALL_DIR> placeholder. This does not actually configure the external project to install to the given prefix โ€” you have to do that by passing appropriate arguments to the external project configuration step, e.g. using <INSTALL_DIR>.

If any of the above ..._DIR options aren't specified, their defaults get computed like this. If the PREFIX option is given or the EP_PREFIX directory property is set, then an external project is built and installed under the specified prefix:

TMP_DIR      = <prefix>/tmp
STAMP_DIR    = <prefix>/src/<name>-stamp
DOWNLOAD_DIR = <prefix>/src
SOURCE_DIR   = <prefix>/src/<name>
BINARY_DIR   = <prefix>/src/<name>-build
INSTALL_DIR  = <prefix>
LOG_DIR      = <STAMP_DIR>

Otherwise, if the EP_BASE directory property is set, then components of an external project are stored under the specified base:

TMP_DIR      = <base>/tmp/<name>
STAMP_DIR    = <base>/Stamp/<name>
DOWNLOAD_DIR = <base>/Download/<name>
SOURCE_DIR   = <base>/Source/<name>
BINARY_DIR   = <base>/Build/<name>
INSTALL_DIR  = <base>/Install/<name>
LOG_DIR      = <STAMP_DIR>

If no PREFIX, EP_PREFIX, or EP_BASE is specified, then the default is to set PREFIX to <name>-prefix. Relative paths are interpreted with respect to CMAKE_CURRENT_BINARY_DIR at the point where ExternalProject_Add() is called. Iconic.


๐Ÿ“ฅ Download Step Options ๐Ÿ“ฅ

A download method can be omitted if the SOURCE_DIR option is used to point to an existing non-empty directory. Otherwise, one of the download methods below must be specified (multiple download methods should not be given) or a custom DOWNLOAD_COMMAND provided.

  • DOWNLOAD_COMMAND <cmd>... โ€” overrides the command used for the download step (generator expressions are supported โœจ). If this option is specified, all other download options will be ignored. Providing an empty string for <cmd> effectively disables the download step.

๐Ÿฆ‹ URL ๐Ÿฆ‹

  • URL <url1> [<url2>...] โ€” list of paths and/or URL(s) of the external project's source. When more than one URL is given, they're tried in turn until one succeeds. A URL may be an ordinary path in the local file system (in which case it must be the only URL provided) or any downloadable URL supported by the file(DOWNLOAD) command. A local filesystem path may refer to either an existing directory or to an archive file, whereas a URL is expected to point to a file which can be treated as an archive. When an archive is used, it will be unpacked automatically unless the DOWNLOAD_NO_EXTRACT option is set to prevent it. The archive type is determined by inspecting the actual content rather than using logic based on the file extension. Changed in version 3.7: multiple URLs are allowed.
  • URL_HASH <algo>=<hashValue> โ€” hash of the archive file to be downloaded. The argument should be of the form <algo>=<hashValue> where algo can be any of the hashing algorithms supported by the file() command. Specifying this option is strongly recommended for URL downloads, because it ensures the integrity of the downloaded content. It's also used as a check for a previously downloaded file, letting the connection to the remote location be avoided altogether if the local directory already has a file from an earlier download that matches the specified hash. Protect your peace ๐Ÿ’….
  • URL_MD5 <md5> โ€” equivalent to URL_HASH MD5=<md5>.
  • DOWNLOAD_NAME <fname> โ€” file name to use for the downloaded file. If not given, the end of the URL is used to determine the file name. This option is rarely needed โ€” the default name is generally suitable and isn't normally used outside of code internal to the ExternalProject module.
  • DOWNLOAD_EXTRACT_TIMESTAMP <bool> โ€” Added in version 3.24. When specified with a true value, the timestamps of the extracted files will match those in the archive. When false, the timestamps of the extracted files will reflect the time at which the extraction was performed. If the download URL changes, timestamps based off those in the archive can result in dependent targets not being rebuilt when they potentially should have been. So unless the file timestamps are significant to the project in some way, use a false value for this option. If DOWNLOAD_EXTRACT_TIMESTAMP isn't given, the default is false. See policy CMP0135.
  • DOWNLOAD_NO_EXTRACT <bool> โ€” Added in version 3.6. Lets you disable the extraction part of the download step by passing a boolean true value for this option. If this option isn't given, the downloaded contents get unpacked automatically if required. If extraction has been disabled, the full path to the downloaded file is available as <DOWNLOADED_FILE> in subsequent steps, or as the property DOWNLOADED_FILE with the ExternalProject_Get_Property() command.
  • DOWNLOAD_NO_PROGRESS <bool> โ€” can be used to disable logging the download progress. If this option isn't given, download progress messages will be logged.
  • TIMEOUT <seconds> โ€” maximum time allowed for file download operations.
  • INACTIVITY_TIMEOUT <seconds> โ€” Added in version 3.19. Terminate the operation after a period of inactivity.
  • HTTP_USERNAME <username> โ€” Added in version 3.7. Username for the download operation if authentication is required.
  • HTTP_PASSWORD <password> โ€” Added in version 3.7. Password for the download operation if authentication is required.
  • HTTP_HEADER <header1> [<header2>...] โ€” Added in version 3.7. Provides an arbitrary list of HTTP headers for the download operation. This can be useful for accessing content in systems like AWS, etc.
  • TLS_VERSION <min> โ€” Added in version 3.30. Specify minimum TLS version for https:// URLs. If this option isn't provided, the value of the CMAKE_TLS_VERSION variable or the CMAKE_TLS_VERSION environment variable will be used instead (see file(DOWNLOAD)).

This option also applies to git clone invocations, although the default behavior is different. If none of the TLS_VERSION option, CMAKE_TLS_VERSION variable, or CMAKE_TLS_VERSION environment variable is specified, the behavior will be determined by git's default or a http.sslVersion git config option the user may have set at a global level.

  • TLS_VERIFY <bool> โ€” specifies whether certificate verification should be performed for https:// URLs. If this option isn't provided, the value of the CMAKE_TLS_VERIFY variable or the CMAKE_TLS_VERIFY environment variable will be used instead (see file(DOWNLOAD)). If neither of those is set, certificate verification will not be performed. In situations where URL_HASH cannot be provided, this option can be an alternative verification measure ๐Ÿซถ.

This option also applies to git clone invocations, ngl the default behavior is a little different there. If none of the TLS_VERIFY option, the CMAKE_TLS_VERIFY variable, or the CMAKE_TLS_VERIFY environment variable is specified, then the behavior gets decided by git's own default (which is true) or by a http.sslVerify git config option the user might have set at a global level. iykyk ๐Ÿ’…

Changed in version 3.6 (๐Ÿ’ซ glow-up alert): back in the day, this option did not apply to git clone invocations. Now it does.
Changed in version 3.30 (another glow-up โœจ): previously the CMAKE_TLS_VERIFY environment variable was not checked at all. Now it is, bestie.
  • TLS_CAINFO <file> โ€” drop a custom certificate authority file here, but only if TLS_VERIFY is enabled ๐ŸŽ€. If you don't specify this option, the value of the CMAKE_TLS_CAINFO variable gets used instead (peep file(DOWNLOAD) for the deets).
  • NETRC <level> โ€” Added in version 3.11. Tells CMake whether the .netrc file should be used for the operation ๐Ÿ”ฅ. If you don't specify this option, the value of the CMAKE_NETRC variable is used instead (again, see file(DOWNLOAD)). The valid levels are, in order:
    • IGNORED โ€” the .netrc file is ignored. This is literally the default, periodt.
    • OPTIONAL โ€” the .netrc file is optional, and info in the URL is preferred ๐Ÿ’–. The file gets scanned to find whichever info isn't already in the URL.
    • REQUIRED โ€” the .netrc file is required, and info in the URL is ignored. No file, no deal ๐Ÿ™ˆ.
  • NETRC_FILE <file> โ€” Added in version 3.11. Use this to point at an alternative .netrc file instead of the one chillin' in your home directory, but only if the NETRC level is OPTIONAL or REQUIRED ๐Ÿฆ‹. If you don't specify this option, the value of the CMAKE_NETRC_FILE variable is used instead (see file(DOWNLOAD)).

Added in version 3.1: support for tbz2, .tar.xz, .txz, and .7z extensions got added, slay ๐Ÿ’….

Added in version 4.1: literally every archive type that cmake -E tar can extract is supported now, regardless of the file extension. No cap, the extension doesn't even matter anymore ๐Ÿ‘‘


๐Ÿงš Git

NOTE: you need a git version of 1.6.5 or later if you're using this download method. older than that? not today, bestie ๐Ÿ’€
  • GIT_REPOSITORY <url> โ€” the URL of the git repository. Any URL that the git command understands is fair game ๐Ÿซถ.
Changed in version 3.27: a relative URL will be resolved based on the parent project's remote, subject to CMP0150 ๐Ÿค“. Go read the policy documentation for how the remote gets selected โ€” including the conditions where the remote selection can just fail. And listen: local filesystem remotes should always use absolute paths. always. ๐Ÿ’€
  • GIT_TAG <tag> โ€” a git branch name, tag, or commit hash ๐ŸŒธ. Heads up: branch names and tags should generally be specified as remote names (i.e. origin/myBranch rather than just myBranch). Why? Because this ensures that if the remote end has its tag moved or its branch rebased or its history rewritten, your local clone still gets updated correctly ๐Ÿ’–. In general, though, specifying a commit hash should be preferred, for a bunch of reasons:
    • If the local clone already has the commit corresponding to the hash, no git fetch needs to happen to check for changes each time CMake is re-run ๐Ÿƒโ€โ™€๏ธ. This can result in a significant speed up if lots of external projects are being used. iconic.
    • Using a specific git hash ensures that the main project's own history is fully traceable to a specific point in the external project's evolution ๐Ÿ‘‘. If a branch or tag name is used instead, then checking out a specific commit of the main project doesn't necessarily pin the whole build to a specific point in the life of the external project. The lack of such deterministic behavior makes the main project lose traceability and repeatability. and we hate losing traceability ๐Ÿ˜ญ

If GIT_SHALLOW is enabled then GIT_TAG works only with branch names and tags โ€” a commit hash is not allowed ๐Ÿšซ.

Also note: if not provided, GIT_TAG defaults to master, not the default Git branch name. yeah. it's giving legacy vibes ๐Ÿ’€

  • GIT_REMOTE_NAME <name> โ€” the optional name of the remote ๐ŸŽ€. If you don't specify it, it defaults to origin.
  • GIT_SUBMODULES <module>... โ€” the specific git submodules that should also be updated ๐Ÿฆ‹. If you don't provide this option, all git submodules get updated.
Changed in version 3.16: when CMP0097 is set to NEW, if this value is set to an empty string then no submodules are initialized or updated. zero. none. zip. โœจ
  • GIT_SUBMODULES_RECURSE <bool> โ€” Added in version 3.17. Specify whether git submodules (if there are any) should update recursively by passing the --recursive flag to git submodule update ๐Ÿ”. If not specified, the default is on.
  • GIT_SHALLOW <bool> โ€” Added in version 3.6. When this option is enabled, the git clone operation gets handed the --depth 1 option ๐ŸŠโ€โ™€๏ธ. This performs a shallow clone, which avoids downloading the whole entire history and instead retrieves just the commit denoted by the GIT_TAG option. so efficient. so demure.
  • GIT_PROGRESS <bool> โ€” Added in version 3.8. When enabled, this option instructs the git clone operation to report its progress by passing it the --progress option ๐Ÿ“Š. Without this option, the clone step for large projects may appear to make the build stall, since nothing gets logged until the clone operation finishes ๐Ÿ˜ด. While this option can be used to provide progress and prevent that "is it frozen??" appearance, it may also make the build overly noisy if lots of external projects are used. pick your fighter ๐Ÿ’…
  • GIT_CONFIG <option1> [<option2>...] โ€” Added in version 3.8. Specify a list of config options to pass to git clone ๐ŸŽ€. Each option listed gets transformed into its own --config <option> on the git clone command line, and each option is required to be in the form key=value.
  • GIT_REMOTE_UPDATE_STRATEGY <strategy> โ€” Added in version 3.18. When GIT_TAG refers to a remote branch, this option lets you specify how the update step behaves ๐Ÿค”. The <strategy> must be one of the following:
    • CHECKOUT โ€” ignore the local branch and always checkout the branch specified by GIT_TAG. simple. clean. โœจ
    • REBASE โ€” try to rebase the current branch onto the one specified by GIT_TAG ๐Ÿ”. If there are local uncommitted changes, they will be stashed first and popped again after rebasing. If rebasing or popping the stashed changes fails, abort the rebase and halt with an error ๐Ÿ’€. When GIT_REMOTE_UPDATE_STRATEGY is not present, this is the default strategy โ€” unless the default has been overridden with CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY (see below). Note that if the branch specified in GIT_TAG is different from the upstream branch currently being tracked, it is not safe to perform a rebase. In that situation, REBASE will silently be treated as CHECKOUT instead. sneaky but ok ๐Ÿ™ˆ
    • REBASE_CHECKOUT โ€” same as REBASE, except if the rebase fails, an annotated tag will be created at the original HEAD position from before the rebase, and then it'll checkout GIT_TAG just like the CHECKOUT strategy ๐ŸŽ€. The message stored on the annotated tag gives information about what was attempted and the tag name will include a timestamp so that each failed run adds a new tag โฐ. This strategy ensures no changes will be lost, but updates should always succeed if GIT_TAG refers to a valid ref โ€” unless there are uncommitted changes that cannot be popped successfully ๐Ÿ˜ญ.

The variable CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY can be set to override the default strategy. This variable should not be set by a project โ€” it's intended for the user to set ๐Ÿ™‹โ€โ™€๏ธ. It's primarily intended for use in continuous integration scripts, to ensure that when history is rewritten on a remote branch, the build doesn't end up with unintended changes or failed builds resulting from conflicts during rebase operations. protect the pipeline at all costs ๐Ÿ”ฅ

The following variables can be set to control the retry behavior for git clone operations:

  • CMAKE_EP_GIT_CLONE_RETRY_COUNT โ€” Added in version 4.4. Specifies the number of times to retry a git clone operation if it fails ๐Ÿซถ. The default is 2 retries. The first attempt is not counted as a retry, so the total number of attempts is the retry count plus one ๐Ÿงฎ. This variable should not be set by a project โ€” it's intended for the user to set. It's primarily useful when dealing with intermittent network issues or rate limiting from git hosting services. (looking at you, every git host ever ๐Ÿ’€)
  • CMAKE_EP_GIT_CLONE_RETRY_DELAY โ€” Added in version 4.4. Specifies the delay in seconds between retry attempts for git clone operations โณ. The default is 0 seconds (no delay between retries). This variable should not be set by a project โ€” it's intended for the user to set. Setting a delay can be helpful when dealing with rate limiting from git hosting services, where immediate retries would also get rejected ๐Ÿšซ. be patient, bestie ๐Ÿง˜โ€โ™€๏ธ

๐ŸŒˆ Subversion

  • SVN_REPOSITORY <url> โ€” the URL of the Subversion repository ๐ŸŽ€.
  • SVN_REVISION -r<rev> โ€” the revision to checkout from the Subversion repository ๐Ÿ”–.
  • SVN_USERNAME <username> โ€” username for the Subversion checkout and update ๐Ÿ™‹โ€โ™€๏ธ.
  • SVN_PASSWORD <password> โ€” password for the Subversion checkout and update ๐Ÿ”.
  • SVN_TRUST_CERT <bool> โ€” specifies whether to trust the Subversion server site certificate ๐Ÿ›ก๏ธ. If enabled, the --trust-server-cert option gets passed to the svn checkout and update commands.

๐Ÿฆ‹ Mercurial

  • HG_REPOSITORY <url> โ€” the URL of the mercurial repository ๐Ÿ’œ.
  • HG_TAG <tag> โ€” mercurial branch name, tag, or commit id ๐Ÿท๏ธ.

๐ŸŽ€ CVS

  • CVS_REPOSITORY <cvsroot> โ€” the CVSROOT of the CVS repository ๐ŸŒธ.
  • CVS_MODULE <mod> โ€” the module to checkout from the CVS repository ๐Ÿ“ฆ.
  • CVS_TAG <tag> โ€” the tag to checkout from the CVS repository ๐Ÿท๏ธ.

๐ŸŒธ Update Step Options ๐ŸŒธ

ok so every time CMake gets re-run, bestie, the external project's sources get updated by default โ€” but only if the download method actually supports updates (think: a git repo gets checked, as long as the GIT_TAG doesn't point at one specific commit). Slay.

  • UPDATE_COMMAND <cmd>... โ€” swaps out the download method's update step for a custom command of your own. The command can use generator expressions <#manual:cmake-generator-expressions(7)>.
  • UPDATE_DISCONNECTED <bool> โ€” Added in version 3.2.

turn this on and the update step gets skipped entirely (tho see below, because there's a whole "changed behavior where this is not the case" situation going on ๐Ÿ™ˆ). It does not stop the download step. The update step can still be added as a step target (see ExternalProject_Add_StepTargets()) and called manually. This is lowkey the move if you want devs to be able to build when they're off the network (the network might still be needed for the download step tho, no cap).

Changed in version 3.27: when UPDATE_DISCONNECTED is true, the update step will be executed if any details about the update or download step change. Also, if you're using the git download/update method, the update logic gets modified to skip attempts to contact the remote. And if the GIT_TAG mentions a ref that isn't known locally, the update step just halts with a fatal error. ๐Ÿ’€

When this option is present, it's generally advisable to make the value a cache variable under the developer's control rather than hard-coding it. If the option isn't present, the default value comes from the EP_UPDATE_DISCONNECTED directory property. If that's also not defined, updates are performed as normal. The EP_UPDATE_DISCONNECTED directory property is intended as a convenience for controlling the UPDATE_DISCONNECTED behavior for an entire section of a project's directory hierarchy, and it may be a more convenient way to give developers control over whether or not to perform updates (assuming the project also provides a cache variable or some other convenient method for setting the directory property).

heads up: this may cause a step target to be created automatically for the download step. See policy CMP0114 <#policy:CMP0114>.

๐ŸŽ€ Patch Step Options ๐ŸŽ€

  • PATCH_COMMAND <cmd>... โ€” gives you a custom command to patch the sources after an update. By default, no patch command is defined. But ngl, it can be genuinely difficult to define an appropriate patch command that performs robustly โ€” especially for download methods like git, where changing the GIT_TAG won't discard changes from a previous patch, but the patch command will get called again after updating to the new tag. ๐Ÿ˜ญ so like, be careful with this one.

โœจ Configure Step Options โœจ

The configure step runs after the download and update steps. By default, the external project is assumed to be a CMake project, but you can override that if you need to.

  • CONFIGURE_COMMAND <cmd>... โ€” the default configure command runs CMake with a few options based on the main project. The options added are typically only those needed to use the same generator as the main project, but the CMAKE_GENERATOR option can be given to override this. The project is responsible for adding any toolchain details, flags or other settings it wants to reuse from the main project or otherwise specify (see CMAKE_ARGS, CMAKE_CACHE_ARGS and CMAKE_CACHE_DEFAULT_ARGS below).

For non-CMake external projects, you must use CONFIGURE_COMMAND to override the default configure command (generator expressions <#manual:cmake-generator-expressions(7)> are supported). And for projects that need no configure step at all? Just specify this option with an empty string as the command to execute. iconic.

  • CMAKE_COMMAND /.../cmake โ€” specify an alternative cmake executable for the configure step (use an absolute path, bestie). This is generally not recommended, since it's usually desirable to use the same CMake version throughout the whole build. Ignored if a custom configure command was specified with CONFIGURE_COMMAND.
  • CMAKE_GENERATOR <gen> โ€” override the CMake generator used for the configure step. Without this option, the same generator as the main build is used. Ignored if a custom configure command was specified with the CONFIGURE_COMMAND option.
  • CMAKE_GENERATOR_PLATFORM <platform> โ€” Added in version 3.1.

passes a generator-specific platform name to the CMake command (see CMAKE_GENERATOR_PLATFORM <#variable:CMAKE_GENERATOR_PLATFORM>). It is an error to provide this option without the CMAKE_GENERATOR option. periodt.

  • CMAKE_GENERATOR_TOOLSET <toolset> โ€” passes a generator-specific toolset name to the CMake command (see CMAKE_GENERATOR_TOOLSET <#variable:CMAKE_GENERATOR_TOOLSET>). It is an error to provide this option without the CMAKE_GENERATOR option.
  • CMAKE_GENERATOR_INSTANCE <instance> โ€” Added in version 3.11.

passes a generator-specific instance selection to the CMake command (see CMAKE_GENERATOR_INSTANCE <#variable:CMAKE_GENERATOR_INSTANCE>). It is an error to provide this option without the CMAKE_GENERATOR option.

  • CMAKE_ARGS <arg>... โ€” the arguments you specify get passed to the cmake command line. They can be any argument the cmake command understands, not just cache values defined by -D... arguments (see also CMake Options <#manual:cmake(1)>).

Added in version 3.3: arguments may use generator expressions <#manual:cmake-generator-expressions(7)>.

  • CMAKE_CACHE_ARGS <arg>... โ€” an alternate way of specifying cache variables for when command line length issues might become a problem. The arguments are expected to be in the form -Dvar:STRING=value, which are then transformed into CMake set() <#command:set> commands with the FORCE option used. These set() commands are written to a pre-load script, which is then applied using the cmake -C <#manual:cmake(1)> command line option.

Added in version 3.3: arguments may use generator expressions <#manual:cmake-generator-expressions(7)>.

  • CMAKE_CACHE_DEFAULT_ARGS <arg>... โ€” Added in version 3.2.

same as the CMAKE_CACHE_ARGS option, except the set() commands do not include the FORCE keyword. That means the values act as initial defaults only and will not override any variables already set from a previous run. Use this option with care, bestie โ€” it can lead to different behavior depending on whether the build starts from a fresh build directory or reuses previous build contents. ๐Ÿซถ

Added in version 3.15: if the CMake generator is the Green Hills MULTI and not overridden, the original project's settings for the GHS toolset and target system customization cache variables are propagated into the external project.

  • SOURCE_SUBDIR <dir> โ€” Added in version 3.7.

when no CONFIGURE_COMMAND option is specified, the configure step assumes the external project has a CMakeLists.txt file at the top of its source tree (i.e. in SOURCE_DIR). The SOURCE_SUBDIR option points to an alternative directory within the source tree to use as the top of the CMake source tree instead. This must be a relative path, and it'll be interpreted as being relative to SOURCE_DIR.

Added in version 3.14: when the BUILD_IN_SOURCE option is enabled, the BUILD_COMMAND is used to point to an alternative directory within the source tree.

  • CONFIGURE_HANDLED_BY_BUILD <bool> โ€” Added in version 3.20.

enabling this relaxes the configure step's dependencies on other external projects to order-only. Meaning: the configure step will be executed after its external project dependencies are built, but it will not be marked dirty when one of its external project dependencies is rebuilt. Enable this when the build step is smart enough to figure out if the configure step needs to be rerun. CMake and Meson are examples of build systems whose build step is smart enough to know if the configure step needs to be rerun. big brain energy honestly.

  • CONFIGURE_ENVIRONMENT_MODIFICATION <modification>... โ€” Added in version 4.2.

specifies environment variables that should be modified for the configure step.

set a semicolon-separated list <#cmake-language-lists> of environment variables and values of the form MYVAR=OP:VALUE, where MYVAR is the case-sensitive name of an environment variable to be modified. Entries are considered in the order specified in the property's value. The OP may be one of:

  • reset: reset to the unmodified value, ignoring all modifications to MYVAR prior to this entry. Note that this will reset the variable to the value set by ENVIRONMENT <#prop_test:ENVIRONMENT>, if it was set, and otherwise to its state from the rest of the CTest execution.
  • set: replaces the current value of MYVAR with VALUE.
  • unset: unsets the current value of MYVAR.
  • string_append: appends singular VALUE to the current value of MYVAR.
  • string_prepend: prepends singular VALUE to the current value of MYVAR.
  • path_list_append: appends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • path_list_prepend: prepends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • cmake_list_append: appends singular VALUE to the current value of MYVAR using ; as the separator.
  • cmake_list_prepend: prepends singular VALUE to the current value of MYVAR using ; as the separator.

like, for example:

ExternalProject_Add(example
  ... # Download options, etc...
  CONFIGURE_ENVIRONMENT_MODIFICATION
    SDKROOT=set:macosx
    PKG_CONFIG_PATH=set:$ENV{PKG_CONFIG_PATH}
)

cute, right? ๐Ÿ’…

This snippet is doing the absolute most in the best way: it defines two environment variables when configuring the example project. SDKROOT gets set to macosx, and the value of PKG_CONFIG_PATH gets forwarded to the external project. ๐Ÿซถ

Environment modifications team up with LIST_SEPARATOR to swap that separator for a ; inside the environment variable:

ExternalProject_Add(example
  ... # Download options, etc...
  LIST_SEPARATOR ,
  CONFIGURE_ENVIRONMENT_MODIFICATION
    LIST_VAR=set:a,b,c
)

So this snippet means the environment variable LIST_VAR is passed to the configure command invocation with the value a;b;c. iconic behavior tbh ๐Ÿ’…

โœจ Build Step Options โœจ

If the configure step assumed the external project uses CMake as its build system, then the build step assumes that too. Otherwise, the build step assumes a Makefile-based build and just runs make with no arguments as the default build step. You can override that with custom build commands if you need to.

If both the main project and the external project use make as their build tool, the external project's build step gets invoked as a recursive make using $(MAKE). That passes some build tool settings from the main project over to the external project. But if either the main project or the external project isn't using make, then no build tool settings get passed to the external project other than the ones established by the configure step. Like, running ninja -v in the main project will not pass -v to the external project's build step, even if the external project also uses ninja as its build tool. no cap ๐Ÿ˜ญ

  • BUILD_COMMAND <cmd>... โ€” overrides the default build command (generator expressions from cmake-generator-expressions(7) are supported). If you don't give this option, the default build command gets picked to integrate with the main build in the most appropriate way (e.g. recursive make for Makefile generators, or cmake --build if the project uses a CMake build). You can also pass an empty string as the command to make the build step do absolutely nothing. ๐Ÿ’€
  • BUILD_IN_SOURCE <bool> โ€” when this is enabled, the build happens directly inside the external project's source tree. Generally you should avoid this โ€” a separate build directory is usually preferred โ€” but it's lowkey useful when the external project assumes an in-source build. Don't specify the BINARY_DIR option if you're building in-source, bestie.
  • BUILD_ALWAYS <bool> โ€” enabling this forces the build step to always run. Honestly this can be the easiest way to robustly make sure the external project's own build dependencies get evaluated, instead of relying on the default success timestamp-based method. You don't normally need it unless developers are expected to modify something the external project's build depends on in a way that isn't detectable through the step target dependencies (e.g. SOURCE_DIR is used without a download method and developers might modify the sources in SOURCE_DIR). ๐Ÿงš
  • BUILD_BYPRODUCTS <file>... โ€” added in version 3.2. Specifies files that will be generated by the build command but which might or might not have their modification time updated by subsequent builds. This may also be required to explicitly declare dependencies when you're using the Ninja generator. These ultimately get passed through as BYPRODUCTS to the build step's own underlying call to add_custom_command(), which has additional documentation. โญ
  • BUILD_JOB_SERVER_AWARE <bool> โ€” added in version 3.28. Specifies that the build step is aware of the GNU Make job server. See the add_custom_command() documentation of its JOB_SERVER_AWARE option for the details. This option is relevant only when an explicit BUILD_COMMAND is specified. ๐Ÿ‘‘
  • BUILD_ENVIRONMENT_MODIFICATION <modification>... โ€” added in version 4.2. Specify environment variables that should be modified for the build step.

Set a semicolon-separated list of environment variables and values of the form MYVAR=OP:VALUE, where MYVAR is the case-sensitive name of an environment variable to be modified. Entries are considered in the order specified in the property's value. OP may be one of:

  • reset: Reset to the unmodified value, ignoring all modifications to MYVAR prior to this entry. Note that this will reset the variable to the value set by ENVIRONMENT, if it was set, and otherwise to its state from the rest of the CTest execution.
  • set: Replaces the current value of MYVAR with VALUE.
  • unset: Unsets the current value of MYVAR.
  • string_append: Appends singular VALUE to the current value of MYVAR.
  • string_prepend: Prepends singular VALUE to the current value of MYVAR.
  • path_list_append: Appends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • path_list_prepend: Prepends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • cmake_list_append: Appends singular VALUE to the current value of MYVAR using ; as the separator.
  • cmake_list_prepend: Prepends singular VALUE to the current value of MYVAR using ; as the separator.

๐ŸŽ€ Install Step Options ๐ŸŽ€

If the configure step assumed the external project uses CMake as its build system, the install step will too. Otherwise, the install step assumes a Makefile-based build and just runs make install as the default build step. You can override that with custom install commands if you need to. ๐Ÿ’–

  • INSTALL_COMMAND <cmd>... โ€” the external project's own install step is invoked as part of the main project's build. It happens after the external project's build step and may be before or after the external project's test step (see the TEST_BEFORE_INSTALL option below). The external project's install rules are not part of the main project's install rules, so if anything from the external project should be installed as part of the main build, you need to specify those in the main build as additional install() commands. The default install step builds the install target of the external project, but you can override it with a custom command using this option (generator expressions from cmake-generator-expressions(7) are supported). Passing an empty string as the <cmd> makes the install step do nothing. ๐Ÿ™ˆ
  • INSTALL_BYPRODUCTS <file>... โ€” added in version 3.26. Specifies files that will be generated by the install command but which might or might not have their modification time updated by subsequent installs. This may also be required to explicitly declare dependencies when using the Ninja generator. These ultimately get passed through as BYPRODUCTS to the install step's own underlying call to add_custom_command(), which has additional documentation. ๐ŸŒธ
  • INSTALL_JOB_SERVER_AWARE <bool> โ€” added in version 4.0. Specifies that the install step is aware of the GNU Make job server. See the add_custom_command() documentation of its JOB_SERVER_AWARE option for details. This option is relevant only when an explicit INSTALL_COMMAND is specified. ๐Ÿ”ฅ
Note: If the CMAKE_INSTALL_MODE environment variable is set when the main project is built, it will only have an effect if these conditions are met: - The main project's configure step assumed the external project uses CMake as its build system. - The external project's install command actually runs. Note that because of the way ExternalProject may use timestamps internally, if nothing the install step depends on needs to be re-executed, the install command might also not need to run. Also note that ExternalProject does not check whether the CMAKE_INSTALL_MODE environment variable changes from one run to another. ๐Ÿ˜ฌ
  • INSTALL_ENVIRONMENT_MODIFICATION <modification>... โ€” added in version 4.2. Specify environment variables that should be modified for the install step.

Set a semicolon-separated list of environment variables and values of the form MYVAR=OP:VALUE, where MYVAR is the case-sensitive name of an environment variable to be modified. Entries are considered in the order specified in the property's value. OP may be one of:

  • reset: Reset to the unmodified value, ignoring all modifications to MYVAR prior to this entry. Note that this will reset the variable to the value set by ENVIRONMENT, if it was set, and otherwise to its state from the rest of the CTest execution.
  • set: Replaces the current value of MYVAR with VALUE.
  • unset: Unsets the current value of MYVAR.
  • string_append: Appends singular VALUE to the current value of MYVAR.
  • string_prepend: Prepends singular VALUE to the current value of MYVAR.
  • path_list_append: Appends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • path_list_prepend: Prepends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • cmake_list_append: Appends singular VALUE to the current value of MYVAR using ; as the separator.
  • cmake_list_prepend: Prepends singular VALUE to the current value of MYVAR using ; as the separator.

๐Ÿฆ‹ Test Step Options ๐Ÿฆ‹

The test step is only defined if you provide at least one of the following TEST_... options. iykyk ๐Ÿ’œ

  • TEST_COMMAND <cmd>... โ€” okay so this one overrides the default test command (generator expressions, like the ones in cmake-generator-expressions(7), are supported ๐Ÿ’…). If you donโ€™t give this option, the test step just builds the external projectโ€™s own test target, which is the default vibe. You can also pass <cmd> as an empty string, which keeps the test step defined but makes it do absolutely nothing. Do not specify any of the other TEST_... options when you pass an empty string as the test command โ€” and honestly, if the test step target isnโ€™t needed, just omit all the TEST_... options altogether.
  • TEST_BEFORE_INSTALL <bool> โ€” when this is enabled, the test step runs before the install step. The default behavior is for the test step to run after install.
  • TEST_AFTER_INSTALL <bool> โ€” this is mainly useful when you want to say โ€œyes, I want the test stepโ€ but all the default behavior is already enough. Setting it to a boolean true value ensures the test step is defined and that it comes after the install step. If both TEST_BEFORE_INSTALL and TEST_AFTER_INSTALL are enabled, the latter is silently ignored ๐Ÿ‘€.
  • TEST_EXCLUDE_FROM_MAIN <bool> โ€” Added in version 3.2. If enabled, the main buildโ€™s default ALL target will not depend on the test step. This is a handy way to make sure the test step is defined but only gets invoked when you manually ask for it. It may cause a step target to be created automatically for either the install or build step. See policy CMP0114 ๐Ÿซถ.
  • TEST_ENVIRONMENT_MODIFICATION <modification>... โ€” Added in version 4.2. Specify environment variables that should be modified for the test step. You set a semicolon-separated list of environment variables and values of the form MYVAR=OP:VALUE, where MYVAR is the case-sensitive name of an environment variable to be modified. Entries are considered in the order specified in the propertyโ€™s value. The OP may be one of:
    • reset: Reset to the unmodified value, ignoring all modifications to MYVAR prior to this entry. Note that this will reset the variable to the value set by ENVIRONMENT, if it was set, and otherwise to its state from the rest of the CTest execution.
    • set: Replaces the current value of MYVAR with VALUE.
    • unset: Unsets the current value of MYVAR.
    • string_append: Appends singular VALUE to the current value of MYVAR.
    • string_prepend: Prepends singular VALUE to the current value of MYVAR.
    • path_list_append: Appends singular VALUE to the current value of MYVAR using the host platformโ€™s path list separator (; on Windows and : elsewhere).
    • path_list_prepend: Prepends singular VALUE to the current value of MYVAR using the host platformโ€™s path list separator (; on Windows and : elsewhere).
    • cmake_list_append: Appends singular VALUE to the current value of MYVAR using ; as the separator.
    • cmake_list_prepend: Prepends singular VALUE to the current value of MYVAR using ; as the separator.

๐ŸŒธ Output Logging Options ๐ŸŒธ

Each of the following LOG_... options can be used to wrap the relevant step in a script to capture its output to files. The log files will be created in LOG_DIR if supplied, or otherwise in the STAMP_DIR directory with step-specific file names โœจ.

  • LOG_DOWNLOAD <bool> โ€” when enabled, the output of the download step is logged to files.
  • LOG_UPDATE <bool> โ€” when enabled, the output of the update step is logged to files.
  • LOG_PATCH <bool> โ€” Added in version 3.14. When enabled, the output of the patch step is logged to files.
  • LOG_CONFIGURE <bool> โ€” when enabled, the output of the configure step is logged to files.
  • LOG_BUILD <bool> โ€” when enabled, the output of the build step is logged to files.
  • LOG_INSTALL <bool> โ€” when enabled, the output of the install step is logged to files.
  • LOG_TEST <bool> โ€” when enabled, the output of the test step is logged to files.
  • LOG_MERGED_STDOUTERR <bool> โ€” Added in version 3.14. When enabled, stdout and stderr will be merged for any step whose output is being logged to files.
  • LOG_OUTPUT_ON_FAILURE <bool> โ€” Added in version 3.14. This option only has an effect if at least one of the other LOG_<step> options is enabled. If an error occurs for a step which has logging to file enabled, that stepโ€™s output will be printed to the console if LOG_OUTPUT_ON_FAILURE is set to true. For cases where a large amount of output is recorded, just the end of that output may be printed to the console.

๐Ÿ–ฅ๏ธ Terminal Access Options ๐Ÿ–ฅ๏ธ

Added in version 3.4. Steps can be given direct access to the terminal in some cases. Giving a step access to the terminal may allow it to receive terminal input if required, such as for authentication details not provided by other options. With the Ninja generator, these options place the steps in the console job pool (JOB_POOLS). Each step can be given access to the terminal individually via the following options:

  • USES_TERMINAL_DOWNLOAD <bool> โ€” give the download step access to the terminal.
  • USES_TERMINAL_UPDATE <bool> โ€” give the update step access to the terminal.
  • USES_TERMINAL_PATCH <bool> โ€” Added in version 3.23. Give the patch step access to the terminal.
  • USES_TERMINAL_CONFIGURE <bool> โ€” give the configure step access to the terminal.
  • USES_TERMINAL_BUILD <bool> โ€” give the build step access to the terminal.
  • USES_TERMINAL_INSTALL <bool> โ€” give the install step access to the terminal.
  • USES_TERMINAL_TEST <bool> โ€” give the test step access to the terminal.

๐ŸŽฏ Target Options ๐ŸŽฏ

  • DEPENDS <targets>... โ€” specify other targets on which the external project depends. Those other targets will be brought up to date before any of the external projectโ€™s steps are executed. Because the external project uses additional custom targets internally for each step, the DEPENDS option is the most convenient way to ensure all of those steps depend on the other targets. Simply doing add_dependencies(<name> <targets>) will not make any of the steps dependent on <targets> โ€” no cap, thatโ€™s just how it is ๐Ÿ˜ญ.
  • EXCLUDE_FROM_ALL <bool> โ€” when enabled, this option excludes the external project from the default ALL target of the main build.
  • STEP_TARGETS <step-target>... โ€” generate custom targets for the specified steps. This is required if the steps need to be triggered manually or if they need to be used as dependencies of other targets. If this option is not specified, the default value is taken from the EP_STEP_TARGETS directory property. See ExternalProject_Add_StepTargets() below for further discussion of the effects of this option.
  • INDEPENDENT_STEP_TARGETS <step-target>... โ€” Deprecated since version 3.19: This is allowed only if policy CMP0114 is not set to NEW. Generates custom targets for the specified steps and prevents these targets from having the usual dependencies applied to them. If this option is not specified, the default value is taken from the EP_INDEPENDENT_STEP_TARGETS directory property. This option is mostly useful for allowing individual steps to be driven independently, such as for a CDash setup where each step should be initiated and reported individually rather than as one whole build. See ExternalProject_Add_StepTargets() below for further discussion of the effects of this option.

๐Ÿงš Miscellaneous Options ๐Ÿงš

  • LIST_SEPARATOR <sep> โ€” for any of the various ..._COMMAND options, CMAKE_ARGS, and ..._ENVIRONMENT_MODIFICATION operations, ExternalProject will replace <sep> with ; in the specified command lines. This can be used to ensure a command has a literal ; in it where direct usage would otherwise be interpreted as argument separators to CMake APIs instead. Note that the separator should be chosen to avoid being confused for non-list-separator usages of the sequence. For example, using LIST_SEPARATOR allows for passing list values to CMake cache variables on the command line:
ExternalProject_Add(example
  ... # Download options, etc.
  LIST_SEPARATOR ","
  CMAKE_ARGS "-DCMAKE_PREFIX_PATH:STRING=${first_prefix},${second_prefix}"
)
  • COMMAND <cmd>... โ€” any of the other ..._COMMAND options can have additional commands appended to them by following them with as many COMMAND ... options as needed (generator expressions are supported). For example:
ExternalProject_Add(example
  ... # Download options, etc.
  BUILD_COMMAND ${CMAKE_COMMAND} -E echo "Starting $<CONFIG> build"
  COMMAND       ${CMAKE_COMMAND} --build <BINARY_DIR> --config $<CONFIG>
  COMMAND       ${CMAKE_COMMAND} -E echo "$<CONFIG> build complete"
)

It should also be noted that each build step is created via a call to ExternalProject_Add_Step(). See that commandโ€™s documentation for the automatic substitutions that are supported for some options.

๐Ÿ” Obtaining Project Properties ๐Ÿ”

  • ExternalProject_Get_Property โ€” the ExternalProject_Get_Property() function retrieves external project target properties:
ExternalProject_Get_Property(<name> <prop1> [<prop2>...])

The function stores property values in variables of the same name. Property names correspond to the keyword argument names of ExternalProject_Add(). For example, the source directory might be retrieved like so:

ExternalProject_Get_property(myExtProj SOURCE_DIR)
message("Source dir of myExtProj = ${SOURCE_DIR}")

๐Ÿ’… Explicit Step Management ๐Ÿ’…

So like, ExternalProject_Add() on its own is often literally all you need to fold an external project into your main build โ€” iconic, no notes. But bestie, sometimes the scenario is spicy and you need some extra work to get the exact behavior you want, like adding in a custom step or making steps available as manually triggerable targets. That's where ExternalProject_Add_Step(), ExternalProject_Add_StepTargets() and ExternalProject_Add_StepDependencies come in โ€” they're the lower level control squad you need to implement those step-level capabilities. ๐Ÿซถ

๐ŸŒธ ExternalProject_Add_Step ๐ŸŒธ

The ExternalProject_Add_Step() function specifies an additional custom step for an external project that was defined by an earlier call to ExternalProject_Add():

ExternalProject_Add_Step(<name> <step> [<option>...])

<name> is the same as the name you passed to that original ExternalProject_Add() call. Heads up though: the <step> you specify must not be one of the pre-defined steps (mkdir, download, update, patch, configure, build, install or test). Those ones are taken, okay? ๐Ÿšซ

The supported options are:

  • COMMAND <cmd>... โ€” the command line to be executed by this custom step (generator expressions are supported). You can repeat this option multiple times to specify multiple commands, and they'll be executed in order. โœจ
  • COMMENT "<text>..." โ€” text to be printed when the custom step executes. A little hype message for your build log, love that.
  • DEPENDEES <step>... โ€” other steps (custom or pre-defined) on which this step depends.
  • DEPENDERS <step>... โ€” other steps (custom or pre-defined) that depend on this new custom step. It's giving main character energy โ€” everyone's waiting on it.
  • DEPENDS <file>... โ€” files on which this custom step depends.
  • ENVIRONMENT_MODIFICATION <modification>... โ€” Added in version 4.2. ๐ŸŽ€

Specify environment variables that should be modified while running the commands in the external project step.

Set a semicolon-separated list of environment variables and values of the form MYVAR=OP:VALUE, where MYVAR is the case-sensitive name of an environment variable to be modified. Entries are considered in the order specified in the property's value. The OP may be one of:

  • reset: Reset to the unmodified value, ignoring all modifications to MYVAR prior to this entry. Note that this will reset the variable to the value set by ENVIRONMENT, if it was set, and otherwise to its state from the rest of the CTest execution.
  • set: Replaces the current value of MYVAR with VALUE.
  • unset: Unsets the current value of MYVAR.
  • string_append: Appends singular VALUE to the current value of MYVAR.
  • string_prepend: Prepends singular VALUE to the current value of MYVAR.
  • path_list_append: Appends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • path_list_prepend: Prepends singular VALUE to the current value of MYVAR using the host platform's path list separator (; on Windows and : elsewhere).
  • cmake_list_append: Appends singular VALUE to the current value of MYVAR using ; as the separator.
  • cmake_list_prepend: Prepends singular VALUE to the current value of MYVAR using ; as the separator.
  • INDEPENDENT <bool> โ€” Added in version 3.19.

Specifies whether this step is independent of the external dependencies specified by the ExternalProject_Add()'s DEPENDS option. The default is FALSE. Steps marked as independent may depend only on other steps marked independent. See policy CMP0114. ๐Ÿ‘‘

Note that this use of the term "independent" refers only to independence from external targets specified by the DEPENDS option and is orthogonal to a step's dependencies on other steps. Ik it's a vibe, but them's the rules.

If a step target is created for an independent step by the ExternalProject_Add() STEP_TARGETS option or by the ExternalProject_Add_StepTargets() function, it will not depend on the external targets, but may depend on targets for other steps.

  • BYPRODUCTS <file>... โ€” Added in version 3.2.

Files that will be generated by this custom step but which might or might not have their modification time updated by subsequent builds. This may also be required to explicitly declare dependencies when you're using the Ninja generator. This list of files will ultimately be passed through as the BYPRODUCTS option to the add_custom_command() used to implement the custom step internally, and that has additional documentation. ๐Ÿ“š

  • ALWAYS <bool> โ€” when enabled, this option specifies that the custom step should always be run (i.e. that it is always considered out of date). Never beating the "still needs to run" allegations, fr fr.
  • JOB_SERVER_AWARE <bool> โ€” Added in version 3.28.

Specifies that the custom step is aware of the GNU Make job server. See the add_custom_command() documentation of its JOB_SERVER_AWARE option for details.

  • EXCLUDE_FROM_MAIN <bool> โ€” when enabled, this option specifies that the external project's main target does not depend on the custom step. This may cause step targets to be created automatically for the steps on which this step depends. See policy CMP0114.
  • WORKING_DIRECTORY <dir> โ€” specifies the working directory to set before running the custom step's command. If this option is not specified, the directory will be the value of CMAKE_CURRENT_BINARY_DIR at the point where ExternalProject_Add_Step() was called. Home is where the binary dir is, bestie. ๐Ÿ’–
  • LOG <bool> โ€” if set, this causes the output from the custom step to be captured to files in the external project's LOG_DIR if supplied or STAMP_DIR.
  • USES_TERMINAL <bool> โ€” if enabled, this gives the custom step direct access to the terminal if possible.

The command line, comment, working directory and byproducts of every standard and custom step are processed to replace the tokens <SOURCE_DIR>, <SOURCE_SUBDIR>, <BINARY_DIR>, <INSTALL_DIR>, <TMP_DIR>, <DOWNLOAD_DIR> and <DOWNLOADED_FILE> with their corresponding property values defined in the original call to ExternalProject_Add().

Added in version 3.3: token replacement is extended to byproducts. ๐Ÿฆ‹

Added in version 3.11: the <DOWNLOAD_DIR> substitution token.

๐Ÿงš ExternalProject_Add_StepTargets ๐Ÿงš

The ExternalProject_Add_StepTargets() function generates targets for the steps listed. The name of each created target will be of the form <name>-<step>:

ExternalProject_Add_StepTargets(<name> <step1> [<step2>...])

Creating a target for a step allows it to be used as a dependency of another target, or to be triggered manually. Having targets for specific steps also allows them to be driven independently of each other by specifying targets on build command lines. For example, you may be submitting to a sub-project based dashboard where you want to drive the configure portion of the build, then submit to the dashboard, followed by the build portion, followed by tests. And bestie, if you invoke a custom target that depends on a step halfway through the step dependency chain, then all the previous steps will also run to ensure everything is up to date. Chain reaction, but make it productive. ๐Ÿ’ซ

Internally, ExternalProject_Add() calls ExternalProject_Add_Step() to create each step. If any STEP_TARGETS were specified, then ExternalProject_Add_StepTargets() will also be called after ExternalProject_Add_Step(). Even if a step is not mentioned in the STEP_TARGETS option, ExternalProject_Add_StepTargets() can still be called later to manually define a target for the step. So like, it's never too late. ๐Ÿ™ˆ

The STEP_TARGETS option for ExternalProject_Add() is generally the easiest way to ensure targets are created for specific steps of interest. For custom steps, ExternalProject_Add_StepTargets() must be called explicitly if a target should also be created for that custom step. An alternative to these two options is to populate the EP_STEP_TARGETS directory property. It acts as a default for the step target options and can save having to repeatedly specify the same set of step targets when multiple external projects are being defined. Efficiency slay. โญ

Added in version 3.19: if CMP0114 is set to NEW, step targets are fully responsible for holding the custom commands implementing their steps. The primary target created by ExternalProject_Add depends on the step targets, and the step targets depend on each other. The target-level dependencies match the file-level dependencies used by the custom commands for each step. The targets for steps created with ExternalProject_Add_Step()'s INDEPENDENT option do not depend on the external targets specified by ExternalProject_Add()'s DEPENDS option. The predefined steps mkdir, download, update, and patch are independent. ๐Ÿ’…

If CMP0114 is not NEW, the following deprecated behavior is available: ๐Ÿ™‚

  • A deprecated NO_DEPENDS option can go right after the <name> and before the first step. If you slap NO_DEPENDS on there, the step target will not depend on the dependencies of the external project (like, it won't depend on any dependencies of the <name> custom target that ExternalProject_Add() made). This is usually safe for the download, update and patch steps, since those don't typically need the deps to be updated and built. But using NO_DEPENDS for any of the other pre-defined steps? Yeah, that may break parallel builds ๐Ÿ˜ฌ. Only use NO_DEPENDS where you're certain the named steps genuinely don't have dependencies. And for custom steps, think about whether the custom commands actually need the dependencies configured, built and installed.
  • The INDEPENDENT_STEP_TARGETS option for ExternalProject_Add(), or the EP_INDEPENDENT_STEP_TARGETS directory property, tells the function to call ExternalProject_Add_StepTargets() internally using the NO_DEPENDS option for the steps you listed.

ExternalProject_Add_StepDependencies

Added in version 3.2.

The ExternalProject_Add_StepDependencies() function is your go-to for adding dependencies to a step. The deps you add have to be targets CMake already knows about (ordinary executable or library targets, custom targets, or even step targets of another external project โ€” all valid bestie ๐Ÿ’…):

ExternalProject_Add_StepDependencies(<name> <step> <target1> [<target2>...])

This function is careful and sets both target and file level dependencies, and it makes sure parallel builds won't break. Use it instead of add_dependencies() whenever you're adding a dependency for any of the step targets generated by the ExternalProject module. It's the icon behavior, fr fr ๐Ÿ‘‘

Examples

Okay so the following example shows how to download and build a hypothetical project called FooBar from github:

include(ExternalProject)
ExternalProject_Add(foobar
  GIT_REPOSITORY    git@github.com:FooCo/FooBar.git
  GIT_TAG           origin/release/1.2.3
)

For the sake of the example, we also define a second hypothetical external project called SecretSauce, downloaded from a web server. Two URLs are given so it can take advantage of a faster internal network if available, with a fallback to a slower external server. The project is a typical Makefile project with no configure step, so some of the default commands are overridden. The build only needs to build the sauce target:

find_program(MAKE_EXE NAMES gmake nmake make)
ExternalProject_Add(secretsauce
  URL               http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
                    https://www.somecompany.com/downloads/sauce-2.7.zip
  URL_HASH          MD5=d41d8cd98f00b204e9800998ecf8427e
  CONFIGURE_COMMAND ""
  BUILD_COMMAND     ${MAKE_EXE} sauce
)

Suppose the build step of secretsauce requires that foobar must already be built. You can enforce that like this:

ExternalProject_Add_StepDependencies(secretsauce build foobar)

Another alternative would be to create a custom target for foobar's build step and make secretsauce depend on that rather than the whole foobar project. That means foobar only needs to be built โ€” it doesn't need to run its install or test steps before secretsauce can be built. The dependency can also be defined along with the secretsauce project:

ExternalProject_Add_StepTargets(foobar build)
ExternalProject_Add(secretsauce
  URL               http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
                    https://www.somecompany.com/downloads/sauce-2.7.zip
  URL_HASH          MD5=d41d8cd98f00b204e9800998ecf8427e
  CONFIGURE_COMMAND ""
  BUILD_COMMAND     ${MAKE_EXE} sauce
  DEPENDS           foobar-build
)

Instead of calling ExternalProject_Add_StepTargets(), the target could be defined along with the foobar project itself:

ExternalProject_Add(foobar
  GIT_REPOSITORY git@github.com:FooCo/FooBar.git
  GIT_TAG        origin/release/1.2.3
  STEP_TARGETS   build
)

If lots of external projects should have the same set of step targets, setting a directory property may be more convenient. The build step target could be created automatically by setting the EP_STEP_TARGETS directory property before creating the external projects with ExternalProject_Add():

set_property(DIRECTORY PROPERTY EP_STEP_TARGETS build)

Lastly, suppose secretsauce provides a script called makedoc that can generate its own documentation. Further suppose the script expects the output directory to be provided as the only parameter, and that it should be run from the secretsauce source directory. A custom step and a custom target to trigger the script can be defined like so:

ExternalProject_Add_Step(secretsauce docs
  COMMAND           <SOURCE_DIR>/makedoc <BINARY_DIR>
  WORKING_DIRECTORY <SOURCE_DIR>
  COMMENT           "Building secretsauce docs"
  ALWAYS            TRUE
  EXCLUDE_FROM_MAIN TRUE
)
ExternalProject_Add_StepTargets(secretsauce docs)

The custom step could then be triggered from the main build like so:

cmake --build . --target secretsauce-docs

FeatureSummary

This module hands you commands for generating a summary of enabled/disabled features. So slay โœจ

Load this module in CMake with:

include(FeatureSummary)

Commands provided by this module can be used to generate a summary of enabled and disabled packages and/or features for a build tree, like this gorgeousness:

-- The following features have been enabled:

 * Example, usage example

-- The following OPTIONAL packages have been found:

 * LibXml2 (required version >= 2.4), XML library, <http://xmlsoft.org>
   Enables HTML-import in MyWordProcessor
   Enables odt-export in MyWordProcessor
 * PNG, image library, <http://www.libpng.org/pub/png/>
   Enables saving screenshots

-- The following OPTIONAL packages have not been found:

 * Lua, the Lua scripting language, <https://www.lua.org>
   Enables macros in MyWordProcessor
 * OpenGL, Open Graphics Library

Global Properties

The following global properties are used by this module:

FeatureSummary_PKG_TYPES

Added in version 3.8.

This global property defines a semicolon-separated list of package types used by the FeatureSummary module.

The order in this list is important โ€” the first package type in the list has the lowest importance, while the last has the highest importance. A package's type can only be changed to a type with higher importance.

The default package types are RUNTIME, OPTIONAL, RECOMMENDED and REQUIRED, with their importance ranked as RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED.

FeatureSummary_REQUIRED_PKG_TYPES

Added in version 3.8.

This global property defines a semicolon-separated list of package types that are considered required.

If one or more packages in these categories are not found, CMake will abort when the feature_summary() command is called with the FATAL_ON_MISSING_REQUIRED_PACKAGES option enabled. No pressure though ๐Ÿ’€

The default value for this global property is REQUIRED.

FeatureSummary_DEFAULT_PKG_TYPE

Added in version 3.8.

This global property defines the default package type.

When the feature_summary() command is called, and the user has not explicitly set a type for some package, its type will be set to the value of this property.

This value must be one of the types defined in the FeatureSummary_PKG_TYPES global property.

The default value for this global property is OPTIONAL.

FeatureSummary_<TYPE>_DESCRIPTION

Added in version 3.9.

This global property can be defined for each package <TYPE> to a string that will be used in the output titles of the feature_summary() command. For example:

The following <FeatureSummary_<TYPE>_DESCRIPTION> have been found:

If it's not set, the default string <TYPE> packages is used.

Commands

This module provides the following commands:

  • feature_summary()
  • set_package_properties()
  • add_feature_info()

Printing Feature Summary

feature_summary

Prints information about enabled or disabled packages and features of a project:

feature_summary(
  WHAT (ALL
    | PACKAGES_FOUND | PACKAGES_NOT_FOUND
    | <TYPE>_PACKAGES_FOUND | <TYPE>_PACKAGES_NOT_FOUND
    | ENABLED_FEATURES | DISABLED_FEATURES)
  [FILENAME <file>]
  [APPEND]
  [VAR <variable-name>]
  [INCLUDE_QUIET_PACKAGES]
  [FATAL_ON_MISSING_REQUIRED_PACKAGES]
  [DESCRIPTION <description> | DEFAULT_DESCRIPTION]
  [QUIET_ON_EMPTY]
)

This command is literally made for printing info about enabled or disabled packages and features of a project. By default, only the names of the features/packages get printed โ€” plus their required version when one was specified. Use set_package_properties() to add more useful info, like a homepage URL for the respective package or its purpose in the project. So much more chic ๐Ÿ’–

The arguments are:

WHAT โ€” This is the only mandatory option. It specifies what information will be printed:

  • ALL โ€” Print everything. The whole vibe check.
  • ENABLED_FEATURES โ€” The list of all features which are enabled.
  • DISABLED_FEATURES โ€” The list of all features which are disabled.
  • PACKAGES_FOUND โ€” The list of all packages which have been found.
  • PACKAGES_NOT_FOUND โ€” The list of all packages which have not been found. (sad girl hours ๐Ÿ˜ญ)

For each package type <TYPE> defined by the FeatureSummary_PKG_TYPES global property, the following information can also be used:

  • <TYPE>_PACKAGES_FOUND โ€” The list of only packages of type <TYPE> which have been found.
  • <TYPE>_PACKAGES_NOT_FOUND โ€” the list of only packages of type <TYPE> that did not get found. Just the missing ones, no cap ๐Ÿ’…
Changed in version 3.1: the WHAT option is now a multi-value keyword, so you can actually combine these values (everything except the ALL value) to customize the output however you want. Obsessed. For example:
feature_summary(WHAT ENABLED_FEATURES DISABLED_FEATURES)
  • FILENAME <file> โ€” if you pass this, the info gets printed into this file instead of the terminal ๐ŸŽ€ a relative <file> path is interpreted as being relative to the current source directory (i.e. CMAKE_CURRENT_SOURCE_DIR).
  • APPEND โ€” if you pass this, the output gets appended to the <file> you gave the FILENAME option. Otherwise the file just gets overwritten if it already exists ๐Ÿ˜ญ (rip your old logs).
  • VAR <variable-name> โ€” if you pass this, the info gets stored into the specified variable <variable-name> instead of the terminal ๐Ÿซถ
  • INCLUDE_QUIET_PACKAGES โ€” if you pass this, packages that were searched with find_package(... QUIET) will also show up in the list. By default they get skipped, lowkey ghosted ๐Ÿ‘ป
  • FATAL_ON_MISSING_REQUIRED_PACKAGES โ€” if you pass this, CMake straight-up aborts with a fatal error when a package marked as one of the package types listed in the FeatureSummary_REQUIRED_PKG_TYPES global property has not been found ๐Ÿ’€ like it's not playing around.
  • DESCRIPTION <description> โ€” a description or headline that gets printed above the actual content โœจ without this option, if you only requested one package type, no title is printed โ€” unless a custom string is explicitly set using this option, or the DEFAULT_DESCRIPTION option is used, which outputs a default title for the requested type.
  • DEFAULT_DESCRIPTION โ€” Added in version 3.9. The default description/headline printed above the content, as opposed to the customizable DESCRIPTION <description> ๐ŸŒธ
  • QUIET_ON_EMPTY โ€” Added in version 3.8. If you pass this, then when only one package type was requested and no packages belonging to that category were found, no output at all gets printed (including the DESCRIPTION), and nothing gets added to the FILENAME or the VAR variable ๐Ÿ™ˆ silent treatment, deserved.

๐ŸŽ€ Package Properties

set_package_properties

Sets package properties:

set_package_properties(
  <PackageName>
  PROPERTIES
    [URL <url>]
    [DESCRIPTION <description>]
    [TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED)]
    [PURPOSE <purpose>]
)

Use this command to configure and provide info about the package named <PackageName>, which can then be displayed using the feature_summary() command ๐Ÿฆ‹ you can call it either directly inside the corresponding Find module or in the project that uses the module, after invoking the find_package() call. The features you can set info for are determined automatically after the find_package() command. Main character energy, honestly.

The arguments are:

  • <PackageName> โ€” the name of the package. For example, as specified in the find_package(<PackageName>) argument.
  • PROPERTIES โ€” specifies the properties to set:
    • URL <url> โ€” this should be the homepage of the package, or something similar ๐ŸŒˆ ideally this is set already directly in the Find module.
    • DESCRIPTION <description> โ€” a short description of what that package is, at most one sentence ๐Ÿ“ ideally this is set already directly in the Find module.
    • TYPE <type> โ€” what type of dependency the using project has on that package.

Default <type> is OPTIONAL. In this case it's a package that can be used by the project when it's available at buildtime, but the project also works without it ๐Ÿ‘‘

The RECOMMENDED package type is similar to OPTIONAL, i.e. the project will build if the package isn't present, but the functionality of the resulting binaries will be severely limited ๐Ÿ˜ญ if a REQUIRED package isn't available at buildtime, the project may not even build. This can be combined with the feature_summary(FATAL_ON_MISSING_REQUIRED_PACKAGES) command option.

Last but not least, a RUNTIME package is a package that's actually not used at all during the build, but which is required for actually running the resulting binaries ๐Ÿƒโ€โ™€๏ธ so if such a package is missing, the project can still be built, but it may not work later on. Not me finding out at runtime ๐Ÿ’€

If set_package_properties() is called multiple times for the same package with different TYPEs, the TYPE is only changed to higher TYPEs (RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED), and lower TYPEs are ignored ๐Ÿซถ the TYPE property is project-specific, so it can't be set by the Find module โ€” it must be set in the project.

The accepted types can be changed by setting the FeatureSummary_PKG_TYPES global property โœจ

  • PURPOSE <purpose> โ€” this describes which features this package enables in the project, i.e. it tells the user what functionality they get in the resulting binaries ๐ŸŽ if set_package_properties() is called multiple times for a package, all PURPOSE properties get appended to a list of purposes of the package in the project. Same as the TYPE property, the PURPOSE property is also project-specific, so it can't be set by the Find module โ€” it must be set in the project.

๐Ÿ’– Adding Feature Info

add_feature_info

Adds feature information:

add_feature_info(<name> <condition> <description>)

Use this command to add info about a feature identified with a given <name> โญ

The arguments are:

  • <name> โ€” identification name for a feature being added.
  • <condition> โ€” specifies the conditions that determine whether this feature is enabled or disabled. The <condition> argument can be:
    • A single condition (such as a variable name).
    • Added in version 3.8: a semicolon-separated list of multiple conditions ๐Ÿ“
    • Added in version 4.0: a full Condition Syntax as used in an if(<condition>) clause. See policy CMP0183. This enables using the entire condition syntax (such as grouping conditions with parens and similar) ๐Ÿ”ฅ
  • <description> โ€” a text describing the feature. This info can be displayed using feature_summary() for ENABLED_FEATURES and DISABLED_FEATURES respectively.

๐Ÿ’€ Deprecated Commands

The following legacy and deprecated commands are provided for backward compatibility with previous CMake versions โ€” they're giving "still here for the plot", ngl:

set_package_info

Deprecated since version 3.8: use the set_package_properties() and add_feature_info() commands instead ๐Ÿ™ˆ

Sets up information about the specified package, which can then be displayed via feature_summary():

set_package_info(<PackageName> <description> [<url> [<purpose>]])
  • <PackageName> โ€” name of the package.
  • <description> โ€” a short description of the package.
  • <url> โ€” homepage of the package.
  • <purpose> โ€” the purpose of the package.

This command can be used either directly in the Find module or in the project which uses the FeatureSummary module, after the find_package() call. The features for which info can be set are added automatically by the find_package() command โœจ

set_feature_info

Deprecated since version 3.8.

Sets feature info for a package:

set_feature_info(<name> <description> [<url>])

Does the same as:

set_package_info(<name> <description> [<url>])
Deprecated since version 3.8.

Prints enabled features:

print_enabled_features()

Does the same as:

feature_summary(WHAT ENABLED_FEATURES DESCRIPTION "Enabled features:")
Deprecated since version 3.8.

Prints disabled features:

print_disabled_features()

Does the same as:

feature_summary(WHAT DISABLED_FEATURES DESCRIPTION "Disabled features:")

๐ŸŒธ Examples

๐ŸŽ€ Example: Appending Feature Summary to a File

In the following example, the feature summary output will be appended to a specified file instead of printing ๐Ÿ“

include(FeatureSummary)
feature_summary(WHAT ALL FILENAME ${CMAKE_BINARY_DIR}/all.log APPEND)

๐Ÿฆ‹ Example: Storing Feature Summary in a Variable

In the following example, the feature summary of enabled features is stored in a specified variable enabledFeaturesText, including the QUIET packages ๐Ÿ‘‘

include(FeatureSummary)

feature_summary(
  WHAT ENABLED_FEATURES
  INCLUDE_QUIET_PACKAGES
  DESCRIPTION "Enabled Features:"
  VAR enabledFeaturesText
)

okay bestie, last line of that loop, then we move on:

message(STATUS "${enabledFeaturesText}")

๐ŸŽ€ Example: Adding a Custom Package Type

So this next example adds a custom package type and prints only the categories that are not empty. Obsessed with a tidy summary, honestly:

include(FeatureSummary)

set_property(GLOBAL APPEND PROPERTY FeatureSummary_PKG_TYPES BUILD)

find_package(FOO)
set_package_properties(FOO PROPERTIES TYPE BUILD)

feature_summary(
  WHAT BUILD_PACKAGES_FOUND
  DESCRIPTION "Build tools found:"
  QUIET_ON_EMPTY
)

feature_summary(
  WHAT BUILD_PACKAGES_NOT_FOUND
  DESCRIPTION "Build tools not found:"
  QUIET_ON_EMPTY
)

๐ŸŒธ Example: Setting Package Info

Here's how you set the info for a package. It's giving โ€œgive the summary actual contextโ€:

include(FeatureSummary)

find_package(LibXml2)
set_package_properties(
  LibXml2
  PROPERTIES
    DESCRIPTION "XML library"
    URL "http://xmlsoft.org"
)
# or
set_package_properties(
  LibXml2
  PROPERTIES
    TYPE RECOMMENDED
    PURPOSE "Enables HTML-import in MyWordProcessor"
)
# or
set_package_properties(
  LibXml2
  PROPERTIES
    TYPE OPTIONAL
    PURPOSE "Enables odt-export in MyWordProcessor"
)

find_package(DBUS)
set_package_properties(
  DBUS
  PROPERTIES
    TYPE RUNTIME
    PURPOSE "Necessary to disable the screensaver during a presentation"
)

โœจ Example: Printing Feature Summary

In this one, the module outputs the feature summary at the end of the configuration. And if any required package is not found, processing stops with an error message at the end of the configuration phase. No quiet missing-required erasure, periodt.

cmake_minimum_required(VERSION 3.15)
project(Example)

add_library(example example.c)

include(FeatureSummary)

find_package(CURL)
set_package_properties(CURL PROPERTIES TYPE REQUIRED)
target_link_libraries(example PRIVATE CURL::libcurl)

find_package(LibXml2 QUIET)
set_package_properties(LibXml2 PROPERTIES TYPE RECOMMENDED)
if(LibXml2_FOUND)
  target_link_libraries(example PRIVATE LibXml2::LibXml2)
endif()

feature_summary(
  WHAT ALL
  INCLUDE_QUIET_PACKAGES
  DESCRIPTION "Feature summary:"
  FATAL_ON_MISSING_REQUIRED_PACKAGES
)

๐Ÿฆ‹ Examples: Setting Feature Info

Example for setting the info for a feature:

include(FeatureSummary)

option(WITH_FOO "Help for foo" ON)

add_feature_info(Foo WITH_FOO "this feature provides very cool stuff")

Example for setting feature info based on a list of conditions:

include(FeatureSummary)

option(WITH_FOO "Help for foo" ON)
option(WITH_BAR "Help for bar" OFF)

add_feature_info(
  FooBar
  "WITH_FOO;NOT WITH_BAR"
  "this feature is enabled when WITH_FOO is ON and WITH_BAR turned OFF"
)

In the next example, feature info is set depending on a full condition syntax. Unlike a semicolon-separated list of conditions, this lets you use the entire condition syntax as the if clause argument:

include(FeatureSummary)

option(WITH_FOO "Help for foo" ON)
option(WITH_BAR "Help for bar" ON)
option(WITH_BAZ "Help for baz" OFF)

add_feature_info(
  FooBarBaz
  "WITH_FOO AND (WITH_BAR OR WITH_BAZ)"
  "this feature is enabled when the entire condition is true"
)

๐Ÿงš FetchContent

Added in version 3.11.

This module gives you commands to populate content at configure time or as part of the calling script.

Load this module in CMake with:

include(FetchContent)
Note: The Using Dependencies Guide gives a high-level intro to this whole topic. It gives a broader overview of where the FetchContent module fits into the bigger picture, including its relationship to the find_package() command. The guide is recommended pre-reading before moving on to the details below.

Overview

This module enables populating content at configure time via any method supported by the ExternalProject module. Meanwhile ExternalProject_Add() downloads at build time, but FetchContent makes content available immediately, so the configure step can use the content in commands like add_subdirectory(), include(), or file() operations. It's giving configure-time bestie behavior, not build-time waiting.

Content population details should be defined separately from the command that performs the actual population. This separation ensures all the dependency details are defined before anything might try to use them to populate content. That's particularly important in more complex project hierarchies where dependencies may be shared between multiple projects.

A typical example declares content details for some dependencies and then ensures they're populated with a separate call:

FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)
FetchContent_Declare(
  myCompanyIcons
  URL      https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
)

FetchContent_MakeAvailable(googletest myCompanyIcons)

FetchContent_MakeAvailable() ensures the named dependencies have been populated, either by an earlier call or by populating them itself. When it performs the population, it will also add them to the main build, if possible, so the main build can use the populated projects' targets, etc. See the command's documentation for how these steps are performed.

With hierarchical project arrangement, projects at higher levels in the hierarchy are able to override the declared details of content specified anywhere lower in the project hierarchy. The first details declared for a given dependency take precedence, regardless of where in the project hierarchy that occurs. Similarly, the first call that tries to populate a dependency "wins", with subsequent populations reusing the result of the first instead of repeating the population again. See the Examples which demonstrate this scenario.

The FetchContent module also supports defining and populating content in a single call, with no check for whether the content has been populated elsewhere already. This should not be done in projects, but may be appropriate for populating content in CMake script mode. See FetchContent_Populate() for details.

Commands

FetchContent_Declare

FetchContent_Declare(
  <name>
  <contentOptions>...
  [EXCLUDE_FROM_ALL]
  [SYSTEM]
  [OVERRIDE_FIND_PACKAGE |
   FIND_PACKAGE_ARGS args...]
)

The FetchContent_Declare() function records the options that describe how to populate the specified content. If such details have already been recorded earlier in this project (regardless of where in the project hierarchy), this and all later calls for the same content <name> are ignored. This "first to record, wins" approach is what allows hierarchical projects to have parent projects override content details of child projects.

The content <name> can be any string without spaces, but good practice would be to use only letters, numbers, and underscores. The name will be treated case-insensitively, and it should be obvious for the content it represents. It is often the name of the child project, or the value given to its top level project() command (if it is a CMake project). For well-known public projects, the name should generally be the official name of the project. Choosing an unusual name makes it unlikely that other projects needing that same content will use the same name, leading to the content being populated multiple times.

The <contentOptions> can be any of the download, update, or patch options that the ExternalProject_Add() command understands. The configure, build, install, and test steps are explicitly disabled, so options related to those steps are prohibited and will be discarded if given. The SOURCE_SUBDIR option is an exception, see FetchContent_MakeAvailable() for details on how that affects behavior.

Changed in version 3.30: When policy CMP0168 is set to NEW, some output-related and directory-related options are ignored. See the policy documentation for details.

In most cases, <contentOptions> will just be a couple of options defining the download method and method-specific details like a commit tag or archive hash. For example:

FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)

FetchContent_Declare(
  myCompanyIcons
  URL      https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
)

FetchContent_Declare(
  myCompanyCertificates
  SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
  SVN_REVISION   -r12345
)

Where contents are being fetched from a remote location and you do not control that server, it is advisable to use a hash for GIT_TAG rather than a branch or tag name. A commit hash is more secure and helps to confirm that the downloaded contents are what you expected.

Changed in version 3.14: Commands for the download, update, or patch steps can access the terminal. This may be needed for things like password prompts or real-time display of command progress.

Added in version 3.22: the CMAKE_TLS_VERIFY, CMAKE_TLS_CAINFO, CMAKE_NETRC, and CMAKE_NETRC_FILE variables now hand out the defaults for their matching content options โ€” literally the exact same way they already do it for ExternalProject_Add(). ๐ŸŽ€ Before this glow-up, FetchContent straight up ignored those variables. Not seen, not invited. ๐Ÿ’€

Added in version 3.24:

๐Ÿ” FIND_PACKAGE_ARGS

Okay so this one is for those scenarios where FetchContent_MakeAvailable() might first try a call to find_package() to satisfy the dependency for <name>. Bestie, by default that call is just plain find_package(<name>) โ€” no extras, no frills. But FIND_PACKAGE_ARGS lets you slide in extra arguments that get appended after the <name>. โœจ

You can also write FIND_PACKAGE_ARGS with literally nothing after it, and that means find_package() can still be called if FETCHCONTENT_TRY_FIND_PACKAGE_MODE is set to OPT_IN, or isn't set at all. ๐Ÿซถ

โš ๏ธ It would not normally be appropriate to specify REQUIRED as one of the extra arguments after FIND_PACKAGE_ARGS. Why? Because that would mean the find_package() call must succeed โ€” so none of the other details you specified in the FetchContent_Declare() call would ever get a chance to be used as a fall-back. No plan B. No safety net. ๐Ÿ˜ญ

Everything after the FIND_PACKAGE_ARGS keyword gets appended to the find_package() call, so all the other <contentOptions> have to come before the FIND_PACKAGE_ARGS keyword. Order matters, queen. ๐Ÿ‘‘

If the CMAKE_FIND_PACKAGE_TARGETS_GLOBAL variable is set to true at the time FetchContent_Declare() is called, a GLOBAL keyword will be appended to the find_package() arguments โ€” unless it was already specified. It'll also get appended if FIND_PACKAGE_ARGS wasn't given, but FETCHCONTENT_TRY_FIND_PACKAGE_MODE was set to ALWAYS. ๐ŸŒˆ

OVERRIDE_FIND_PACKAGE cannot be used when FIND_PACKAGE_ARGS is given. Pick a lane, babe. ๐Ÿ’…

Dependency Providers discusses another way that FetchContent_MakeAvailable() calls can get redirected. But like โ€” FIND_PACKAGE_ARGS is for project control, whereas dependency providers let users override project behavior. Different vibes, different lanes. ๐Ÿฆ‹

๐Ÿ” OVERRIDE_FIND_PACKAGE

When a FetchContent_Declare(<name> ...) call includes this option, subsequent calls to find_package(<name> ...) will make sure that FetchContent_MakeAvailable(<name>) has been called first, and then use the config package files chilling in the CMAKE_FIND_PACKAGE_REDIRECTS_DIR directory (which are usually created by FetchContent_MakeAvailable()). โœจ

So basically this makes FetchContent_MakeAvailable() override find_package() for that named dependency, letting the former satisfy the package requirements of the latter. It's giving "I got you, bestie." ๐Ÿซถ

FIND_PACKAGE_ARGS cannot be used when OVERRIDE_FIND_PACKAGE is given. Mutual exclusivity, periodt. ๐Ÿ’…

If a dependency provider has been set and the project calls find_package() for the <name> dependency, OVERRIDE_FIND_PACKAGE will not stop the provider from seeing that call. Dependency providers always get the chance to intercept any direct call to find_package() โ€” except if that call contains the BYPASS_PROVIDER option. ๐Ÿ‘€

Added in version 3.25:

๐Ÿงš SYSTEM

If the SYSTEM argument is provided, the SYSTEM directory property of a subdirectory added by FetchContent_MakeAvailable() will be set to true. That affects the non-imported targets created as part of that command. See the SYSTEM target property documentation for a much more detailed discussion of the effects. ๐Ÿ’œ

Added in version 3.28:

๐Ÿšซ EXCLUDE_FROM_ALL

If the EXCLUDE_FROM_ALL argument is provided, then targets in the subdirectory added by FetchContent_MakeAvailable() will not be included in the ALL target by default โ€” and they may be excluded from IDE project files too. See the docs for the directory property EXCLUDE_FROM_ALL for a detailed discussion of the effects. ๐ŸŒธ


๐ŸŒŸ FetchContent_MakeAvailable

Added in version 3.14.

FetchContent_MakeAvailable(<name1> [<name2>...])

This command makes sure that each of the named dependencies are made available to the project by the time it returns. โญ

There must have been a call to FetchContent_Declare() for each dependency, and the first such call controls how that dependency gets made available, as described below. First one wins, no cap. ๐Ÿ‘‘

If FETCHCONTENT_SOURCE_DIR_<uppercaseName> is not set:

  • Added in version 3.24: If a dependency provider is set, call the provider's command with FETCHCONTENT_MAKEAVAILABLE_SERIAL as the first argument, followed by the arguments of the first call to FetchContent_Declare() for <name>. If SOURCE_DIR or BINARY_DIR weren't part of the original declared arguments, they'll be added with their default values. If FETCHCONTENT_TRY_FIND_PACKAGE_MODE was set to NEVER when the details were declared, any FIND_PACKAGE_ARGS will be omitted. The OVERRIDE_FIND_PACKAGE keyword is also always omitted. If the provider fulfilled the request, FetchContent_MakeAvailable() considers that dependency handled, skips the remaining steps below, and moves on to the next dependency in the list. ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ
  • Added in version 3.24: If permitted, find_package(<name> [<args>...]) will be called, where <args>... may be provided by the FIND_PACKAGE_ARGS option in FetchContent_Declare(). The value of the FETCHCONTENT_TRY_FIND_PACKAGE_MODE variable at the time FetchContent_Declare() was called is what determines whether FetchContent_MakeAvailable() can call find_package(). And if the CMAKE_FIND_PACKAGE_TARGETS_GLOBAL variable is set to true when FetchContent_MakeAvailable() is called, it still affects any imported targets created when that in turn calls find_package() โ€” even if that variable was false when the corresponding details were declared. Sneaky but factual. ๐Ÿ”ฅ

If the dependency wasn't satisfied by a provider or a find_package() call, FetchContent_MakeAvailable() then uses the following logic to make the dependency available:

  • If the dependency has already been populated earlier in this run, set the <lowercaseName>_POPULATED, <lowercaseName>_SOURCE_DIR, and <lowercaseName>_BINARY_DIR variables in the same way as a call to FetchContent_GetProperties(), then skip the remaining steps below and move on to the next dependency in the list. Already handled, bestie. ๐Ÿ’…
  • Populate the dependency using the details recorded by an earlier call to FetchContent_Declare(). Halt with a fatal error if no such details have been recorded. ๐Ÿ’€ FETCHCONTENT_SOURCE_DIR_<uppercaseName> can be used to override the declared details and use content provided at the specified location instead. ๐Ÿฆ‹
  • Added in version 3.24: make sure the CMAKE_FIND_PACKAGE_REDIRECTS_DIR directory actually contains a <lowercaseName>-config.cmake and a <lowercaseName>-config-version.cmake file (or, same energy, <name>Config.cmake and <name>ConfigVersion.cmake). Heads up: that directory gets cleared at the start of every CMake run, so it's a fresh slate every time. If there's still no config file after the dependency got populated in the previous step, CMake writes a minimal one for you that includes any <lowercaseName>-extra.cmake or <name>Extra.cmake file with the OPTIONAL flag โ€” so the files can literally be missing and you won't get a warning ๐Ÿ’…. Same deal for the version file: if none exists, a very simple one gets written that sets PACKAGE_VERSION_COMPATIBLE and PACKAGE_VERSION_EXACT to true. This is what makes all future find_package() calls for that dependency use the redirected config file, no matter what version requirements they ask for. Real talk though: CMake can't automatically figure out an arbitrary dependency's version, so it cannot set PACKAGE_VERSION. When the dependency gets pulled in via add_subdirectory() in the next step, it may choose to overwrite the generated config version file in CMAKE_FIND_PACKAGE_REDIRECTS_DIR with one that does set PACKAGE_VERSION. The dependency can also write a <lowercaseName>-extra.cmake or <name>Extra.cmake file to do custom processing, or to define any variables that their normal (installed) package config file would otherwise usually define โ€” and ngl, many projects don't do any custom processing or set any variables, so they simply have no need to do this. If it's required, the main project can write these files instead when the dependency project doesn't. That's the whole slay: it lets the main project fill in missing details from older dependencies that haven't โ€” or can't โ€” be updated to support this functionality. See Integrating With find_package() for examples ๐Ÿฆ‹.
  • If the top directory of the populated content contains a CMakeLists.txt file, CMake calls add_subdirectory() to add it to the main build. And it is not an error for there to be no CMakeLists.txt file โ€” that's lowkey the point, because it lets you use the command for dependencies that make downloaded content available at a known location, but which don't need or support being added directly to the build โœจ.
    • Added in version 3.18: the SOURCE_SUBDIR option can be given in the declared details to look somewhere below the top directory instead (i.e. the same way that SOURCE_SUBDIR is used by the ExternalProject_Add() command). The path you hand to SOURCE_SUBDIR must be relative, and it will be treated as relative to the top directory. It can also point to a directory that doesn't contain a CMakeLists.txt file, or even to a directory that doesn't exist at all ๐Ÿ™ˆ. Useful trick: this lets you avoid adding a project that contains a CMakeLists.txt file in its top directory.
    • Added in version 3.25: if the SYSTEM keyword was included in the call to FetchContent_Declare(), the SYSTEM keyword will be added to the add_subdirectory() command.
    • Added in version 3.28: if the EXCLUDE_FROM_ALL keyword was included in the call to FetchContent_Declare(), the EXCLUDE_FROM_ALL keyword will be added to the add_subdirectory() command.
    • Added in version 3.29: CMAKE_EXPORT_FIND_PACKAGE_NAME is set to the dependency name before calling add_subdirectory().

Okay so here's the vibe check projects should live by: aim to declare the details of all dependencies you might use before you call FetchContent_MakeAvailable() for any of them. Why? Because if any of the dependencies are also sub-dependencies of one or more of the others, the main project still controls the details that get used โ€” since it declares them first, before the dependencies even get a chance ๐Ÿซถ. In the following code samples, assume that the uses_other dependency also uses FetchContent to add the other dependency internally:

# WRONG: Should declare all details first
FetchContent_Declare(uses_other ...)
FetchContent_MakeAvailable(uses_other)

FetchContent_Declare(other ...)    # Will be ignored, uses_other beat us to it
FetchContent_MakeAvailable(other)  # Would use details declared by uses_other

# CORRECT: All details declared first, so they will take priority
FetchContent_Declare(uses_other ...)
FetchContent_Declare(other ...)
FetchContent_MakeAvailable(uses_other other)

Also note that CMAKE_VERIFY_INTERFACE_HEADER_SETS and CMAKE_VERIFY_PRIVATE_HEADER_SETS are explicitly set to false upon entry to FetchContent_MakeAvailable(), and are restored to their original values before the command returns ๐Ÿ’€. Why? Because developers typically only want to verify header sets from the main project, not those from any dependencies โ€” this local manipulation of the CMAKE_VERIFY_INTERFACE_HEADER_SETS and CMAKE_VERIFY_PRIVATE_HEADER_SETS variables is what gives you that intuitive behavior. Want verification back on for all or some dependencies? Use variables like CMAKE_PROJECT_INCLUDE or CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE. You can also just set the VERIFY_INTERFACE_HEADER_SETS and VERIFY_PRIVATE_HEADER_SETS properties of individual targets. Options galore, icon behavior ๐Ÿ‘‘.


๐Ÿงš FetchContent_Populate

So FetchContent_Populate() is a self-contained call that does content population as a totally isolated operation. Fr fr, it is rarely the right command to use โ€” projects should almost always reach for FetchContent_Declare() and FetchContent_MakeAvailable() instead ๐Ÿ˜ญ. The main use case for FetchContent_Populate() is in CMake script mode <#script-processing-mode> as part of implementing some other higher level custom feature.

FetchContent_Populate(
  <name>
  [QUIET]
  [SUBBUILD_DIR <subBuildDir>]
  [SOURCE_DIR <srcDir>]
  [BINARY_DIR <binDir>]
  ...
)

At least one option must be specified after <name>, otherwise the call gets interpreted differently (see below) ๐Ÿ‘€. The supported options for FetchContent_Populate() are the same as those for FetchContent_Declare(), with a few exceptions. These ones do not relate to populating content with FetchContent_Populate() and therefore are not supported:

  • EXCLUDE_FROM_ALL
  • SYSTEM
  • OVERRIDE_FIND_PACKAGE
  • FIND_PACKAGE_ARGS

The few options shown in the signature above are either specific to FetchContent_Populate(), or their behavior is slightly modified from how ExternalProject_Add() treats them:

QUIET โ€” you can give the QUIET option to hide the output associated with populating the specified content ๐Ÿคซ. But if the population fails, the output will be shown regardless of whether you gave this option or not, so the cause of the failure can actually be diagnosed. Also: the FETCHCONTENT_QUIET variable has no effect on FetchContent_Populate() calls of this form, the ones where the content details are provided directly.

Changed in version 3.30: the QUIET option and the FETCHCONTENT_QUIET variable have no effect when policy CMP0168 is set to NEW. The output is still quiet by default in that case, but verbosity is controlled by the message logging level (see CMAKE_MESSAGE_LOG_LEVEL and --log-level) ๐Ÿ’….

SUBBUILD_DIR โ€” you can provide the SUBBUILD_DIR argument to change the location of the sub-build created to perform the population. The default value is ${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild, and honestly it would be unusual to need to override this default. If you specify a relative path, it'll be interpreted as relative to CMAKE_CURRENT_BINARY_DIR. And don't confuse this option with the SOURCE_SUBDIR option โ€” that one only affects the FetchContent_MakeAvailable() command ๐ŸŽ€.

Changed in version 3.30: SUBBUILD_DIR is ignored when policy CMP0168 is set to NEW, since there is no sub-build in that case.

SOURCE_DIR, BINARY_DIR โ€” the SOURCE_DIR and BINARY_DIR arguments are supported by ExternalProject_Add(), but FetchContent_Populate() uses different default values. SOURCE_DIR defaults to ${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src, and BINARY_DIR defaults to ${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build. If you specify a relative path, it'll be interpreted as relative to CMAKE_CURRENT_BINARY_DIR. Defaults set, paths handled, no cap ๐Ÿ’œ.

Okay so real talk: anything you pass that isn't one of the explicit options above gets yeeted straight through to ExternalProject_Add() <#command:externalproject_add>, unmodified, so it can set up the download, patch, and update steps. But a few options are explicitly prohibited โ€” the FetchContent_Populate() command literally disables them:

  • CONFIGURE_COMMAND
  • BUILD_COMMAND
  • INSTALL_COMMAND
  • TEST_COMMAND

When you use this form, FETCHCONTENT_FULLY_DISCONNECTED and FETCHCONTENT_UPDATES_DISCONNECTED and policy CMP0170 <#policy:CMP0170> are all just... ignored. not them being ghosted, it's just not their moment ๐Ÿ’…

When this form of FetchContent_Populate() returns, it's gonna set these variables in the scope of whoever called it:

  • <lowercaseName>_SOURCE_DIR โ€” the location where the populated content can be found upon return. this is the one you actually want โœจ
  • <lowercaseName>_BINARY_DIR โ€” a directory that was originally intended for use as a corresponding build directory, but is unlikely to be relevant when you're using this form of the command. it's giving "invited but not needed" ๐Ÿซถ

If you're using FetchContent_Populate() inside CMake script mode <#script-processing-mode>, heads up bestie: the implementation sets up a sub-build, which therefore requires a CMake generator and build tool to be available. If those can't be found by default, then the CMAKE_GENERATOR <#variable:CMAKE_GENERATOR> and potentially the CMAKE_MAKE_PROGRAM <#variable:CMAKE_MAKE_PROGRAM> variables will need to be set appropriately on the command line invoking the script. like, you gotta hand it the tools, it can't just manifest them ๐Ÿ˜ญ

Changed in version 3.30: If policy CMP0168 <#policy:CMP0168> is set to NEW, no sub-build is used. Within CMake script mode <#script-processing-mode>, that allows FetchContent_Populate() to be called without any build tool or CMake generator. we love a glow-up ๐Ÿ‘‘
Added in version 3.18: Added support for the DOWNLOAD_NO_EXTRACT option. ๐ŸŽ€

The command supports another form, although it should no longer be used:

FetchContent_Populate(<name>)
Changed in version 3.30: This form is deprecated. Policy CMP0169 <#policy:CMP0169> provides backward compatibility for projects that still need to use this form, but projects should be updated to use FetchContent_MakeAvailable() instead. fr fr, migrate. it's for your own good ๐Ÿ’€

In this form, the only argument given to FetchContent_Populate() is the <name>. When used this way, the command assumes the content details have been recorded by an earlier call to FetchContent_Declare(). Those details are stored in a global property, so they are unaffected by things like variable or directory scope. iconic behavior, honestly โ€” therefore, it doesn't matter where in the project the details were previously declared, as long as they have been declared before the call to FetchContent_Populate(). Those saved details are then used to populate the content using a method based on ExternalProject_Add() <#command:externalproject_add> (see policy CMP0168 <#policy:CMP0168> for important behavioral aspects of how that's done).

When this form of FetchContent_Populate() returns, the following variables will be set in the scope of the caller:

  • <lowercaseName>_POPULATED โ€” this will always be set to TRUE by the call. always. no cap โœ…
  • <lowercaseName>_SOURCE_DIR โ€” the location where the populated content can be found upon return. ๐Ÿ“
  • <lowercaseName>_BINARY_DIR โ€” a directory intended for use as a corresponding build directory. ๐Ÿ—‚๏ธ

The values of those three variables can also be retrieved from anywhere in the project hierarchy using the FetchContent_GetProperties() command. convenient?? yes ma'am ๐Ÿฆ‹

The implementation ensures that if the content has already been populated in a previous CMake run, that content will be reused rather than repopulating again. For the common case where population involves downloading content, the cost of the download is only paid once. your bandwidth said thank you ๐Ÿ’– But note that it is an error to call FetchContent_Populate(<name>) with the same <name> more than once within a single CMake run. See FetchContent_GetProperties() for how to determine if population of a <name> has already been performed in the current run. do not test it. it will not go well ๐Ÿ™ˆ


๐Ÿ’ซ FetchContent_GetProperties

When you're using saved content details, a call to FetchContent_MakeAvailable() or FetchContent_Populate() records information in global properties which can be queried at any time. This information may include the source and binary directories associated with the content, and also whether or not the content population has been processed during the current configure run.

FetchContent_GetProperties(
  <name>
  [SOURCE_DIR <srcDirVar>]
  [BINARY_DIR <binDirVar>]
  [POPULATED <doneVar>]
)

The SOURCE_DIR, BINARY_DIR, and POPULATED options can be used to specify which properties should be retrieved. Each option accepts a value which is the name of the variable in which to store that property. so meta, we're naming the variable that holds the answer ๐Ÿ˜… Most of the time though, only <name> is given, in which case the call will then set the same variables as a call to FetchContent_MakeAvailable(name) or FetchContent_Populate(name). Note that the SOURCE_DIR and BINARY_DIR values can be empty if the call is fulfilled by a dependency provider <#dependency-providers>. empty string era, we've all been there ๐Ÿ“

This command is rarely needed when you're using FetchContent_MakeAvailable(). It's more commonly used as part of implementing the deprecated pattern with FetchContent_Populate(), which ensures that the relevant variables will always be defined regardless of whether or not the population has been performed elsewhere in the project already:

# WARNING: This pattern is deprecated, don't use it!
#
# Check if population has already been performed
FetchContent_GetProperties(depname)
if(NOT depname_POPULATED)
  # Fetch the content using previously declared details
  FetchContent_Populate(depname)

  # Set custom variables, policies, etc.
  # ...

  # Bring the populated content into the build
  add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
endif()
WARNING: that pattern is deprecated, don't use it! The comment says it, I'm saying it, the manpage is saying it. three sources, one truth ๐Ÿ’…

๐Ÿงš FetchContent_SetPopulated

Added in version 3.24. โญ

Note: This command should only be called by dependency providers <#dependency-providers>. Calling it in any other context is unsupported and future CMake versions may halt with a fatal error in such cases. like, do not. unsupported means unsupported ๐Ÿ˜ญ
FetchContent_SetPopulated(
  <name>
  [SOURCE_DIR <srcDir>]
  [BINARY_DIR <binDir>]
)

If a provider command fulfills a FETCHCONTENT_MAKEAVAILABLE_SERIAL request, it must call this function before returning. mandatory, bestie The SOURCE_DIR and BINARY_DIR arguments can be used to specify the values that FetchContent_GetProperties() should return for its corresponding arguments. Only provide SOURCE_DIR and BINARY_DIR if they have the same meaning as if they had been populated by the built-in FetchContent_MakeAvailable() implementation. same meaning or don't bother ๐Ÿซถ


๐ŸŒธ Variables

A number of cache variables can influence the behavior where details from a FetchContent_Declare() call are used to populate content.

Note: All of these variables are intended for the developer to customize behavior. They should not normally be set by the project. project's job is vibes, developer's job is settings โœจ

๐ŸŽ€ FETCHCONTENT_BASE_DIR

In most cases, the saved details don't specify any options relating to the directories to use for the internal sub-build, final source, and build areas. It's generally best to leave these decisions up to the FetchContent module to handle on the project's behalf. let it cook ๐Ÿ“ The FETCHCONTENT_BASE_DIR cache variable controls the point under which all content population directories are collected, but in most cases, developers would not need to change this. The default location is ${CMAKE_BINARY_DIR}/_deps, but if developers change this value, they should aim to keep the path short and just below the top level of the build tree to avoid running into path length problems on Windows. windows path length said "not today" ๐Ÿ’€

๐Ÿฆ‹ FETCHCONTENT_QUIET

The logging output during population can be quite verbose, making the configure stage quite noisy. so much yapping This cache option (ON by default) hides all population output unless an error is encountered. If you're experiencing problems with hung downloads, temporarily switching this option off may help diagnose which content population is causing the issue. ๐Ÿ”

Changed in version 3.30: FETCHCONTENT_QUIET is ignored if policy CMP0168 <#policy:CMP0168> is set to NEW. The output is still quiet by default in that case, but verbosity is controlled by the message logging level (see CMAKE_MESSAGE_LOG_LEVEL <#variable:CMAKE_MESSAGE_LOG_LEVEL> and --log-level <#cmdoption-cmake-log-level>). different knob, same quietness ๐Ÿคซ

๐Ÿ‘‘ FETCHCONTENT_FULLY_DISCONNECTED

When this option is enabled, no attempt is made to download or update any content. It's assumed that all content has already been populated in a previous run, or the source directories have been pointed at existing contents the developer has provided manually (using options described further below). When the developer knows that no changes have been made to any content details, turning this option ON can speed up the configure stage. It is OFF by default. โšก

Note: The FETCHCONTENT_FULLY_DISCONNECTED variable is not an appropriate way to prevent any network access on the first run in a build directory. Doing so can break projects, lead to misleading error messages, and hide subtle population failures. it will lie to you and you will believe it ๐Ÿ˜ญ This variable is specifically intended to only be turned on after the first time CMake has been run. If you want to prevent network access even on the first run, use a dependency provider <#dependency-providers> and populate the dependency from local content instead. that's the actual move ๐Ÿ’…
Changed in version 3.30: The constraint that the source directory has already been populated when FETCHCONTENT_FULLY_DISCONNECTED is true is now enforced. See policy CMP0170 <#policy:CMP0170>. they're checking now. behave. ๐Ÿ”ฅ
  • FETCHCONTENT_UPDATES_DISCONNECTED โ€” okay so this one is like the chill, less severe sibling of FETCHCONTENT_FULLY_DISCONNECTED. ๐Ÿ’… Instead of straight-up bypassing all the download and update logic, FETCHCONTENT_UPDATES_DISCONNECTED only stops the update step from making connections to remote servers when you're using the git or hg download methods. Updates still happen if details about the update step change โ€” but the update is attempted using only the info already available locally. So switching to a different tag or commit that's already fetched locally will succeed โœจ, but switching to an unknown commit hash will fail ๐Ÿ˜ญ. The download step is not affected at all, so if content hasn't been downloaded before, it will still be downloaded when this option is enabled. This can speed up the configure step, but not as much as FETCHCONTENT_FULLY_DISCONNECTED. And FETCHCONTENT_UPDATES_DISCONNECTED is OFF by default.
  • FETCHCONTENT_TRY_FIND_PACKAGE_MODE โ€” added in version 3.24. ๐Ÿ‘‘

This variable modifies the details that FetchContent_Declare() records for a given dependency. The tea here โ˜•: while it ultimately controls the behavior of FetchContent_MakeAvailable(), it's the variable's value when FetchContent_Declare() is called that gets used. It makes no difference what the variable is set to when FetchContent_MakeAvailable() is called. Since the variable should only be set by the user and not by projects directly, it'll typically have the same value throughout anyway, so this distinction is not usually noticeable. ๐Ÿ™ˆ

FETCHCONTENT_TRY_FIND_PACKAGE_MODE ultimately controls whether FetchContent_MakeAvailable() is allowed to call find_package() to satisfy a dependency. The variable can be set to one of these values:

  • OPT_IN โ€” FetchContent_MakeAvailable() will only call find_package() if the FetchContent_Declare() call included a FIND_PACKAGE_ARGS keyword. This is also the default behavior if FETCHCONTENT_TRY_FIND_PACKAGE_MODE is not set. ๐ŸŒธ
  • ALWAYS โ€” find_package() can be called by FetchContent_MakeAvailable() regardless of whether the FetchContent_Declare() call included a FIND_PACKAGE_ARGS keyword or not. If no FIND_PACKAGE_ARGS keyword was given, the behavior will be as though FIND_PACKAGE_ARGS had been provided, with no additional arguments after it. ๐Ÿ”ฅ
  • NEVER โ€” FetchContent_MakeAvailable() will not call find_package(). Any FIND_PACKAGE_ARGS given to the FetchContent_Declare() call will be ignored. ๐Ÿ’€

As a special case ๐ŸŽ€, if the FETCHCONTENT_SOURCE_DIR_<uppercaseName> variable has a non-empty value for a dependency, it's assumed that the user is overriding all other methods of making that dependency available. FETCHCONTENT_TRY_FIND_PACKAGE_MODE will have no effect on that dependency, and FetchContent_MakeAvailable() will not try to call find_package() for it.


In addition to the above, the following variables are also defined for each content name:

  • FETCHCONTENT_SOURCE_DIR_<uppercaseName> โ€” if this is set, no download or update steps are performed for the specified content, and the <lowercaseName>_SOURCE_DIR variable returned to the caller is pointed at this location. ๐Ÿซถ This gives developers a way to have a separate checkout of the content that they can modify freely without interference from the build. The build simply uses that existing source, but it still defines <lowercaseName>_BINARY_DIR to point inside its own build area. Developers are strongly encouraged to use this mechanism rather than editing the sources populated in the default location, because changes to sources in the default location can be lost when content population details are changed by the project. ๐Ÿ˜ญ No cap.
  • FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName> โ€” this is the per-content equivalent of FETCHCONTENT_UPDATES_DISCONNECTED. If the global option or this option is ON, then updates for the git and hg methods will not contact any remote for the named content. They'll only use information already available locally. Disabling updates for individual content can be useful for content whose details rarely change, while still leaving other frequently changing content with updates enabled. ๐Ÿ’–

๐ŸŒˆ Examples ๐ŸŒˆ

๐ŸŽ€ Typical Case ๐ŸŽ€

This first, fairly straightforward example ensures that some popular testing frameworks are available to the main build. It's giving "classic, iconic, does exactly what it says":

include(FetchContent)
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)
FetchContent_Declare(
  Catch2
  GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  GIT_TAG        605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
)

# After the following call, the CMake targets defined by googletest and
# Catch2 will be available to the rest of the build
FetchContent_MakeAvailable(googletest Catch2)

๐Ÿฆ‹ Integrating With find_package() ๐Ÿฆ‹

For the previous example, if the user wanted to try to find googletest and Catch2 via find_package() first before trying to download and build them from source, they could set the FETCHCONTENT_TRY_FIND_PACKAGE_MODE variable to ALWAYS. ๐Ÿ‘‘ But heads up โ€” this would also affect any other calls to FetchContent_Declare() throughout the project, which might not be acceptable. ๐Ÿ˜ฌ The behavior can be enabled for just these two dependencies instead by adding FIND_PACKAGE_ARGS to the declared details and leaving FETCHCONTENT_TRY_FIND_PACKAGE_MODE unset, or set to OPT_IN:

include(FetchContent)
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  FIND_PACKAGE_ARGS NAMES GTest
)
FetchContent_Declare(
  Catch2
  GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  GIT_TAG        605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
  FIND_PACKAGE_ARGS
)

# This will try calling find_package() first for both dependencies
FetchContent_MakeAvailable(googletest Catch2)

For Catch2, no additional arguments to find_package() are needed, so no additional arguments are provided after the FIND_PACKAGE_ARGS keyword. For googletest, its package is more commonly called GTest, so arguments are added to support it being found by that name. โœจ iykyk

If the user wanted to disable FetchContent_MakeAvailable() from calling find_package() for any dependency โ€” even if it provided FIND_PACKAGE_ARGS in its declared details โ€” they could set FETCHCONTENT_TRY_FIND_PACKAGE_MODE to NEVER. ๐Ÿšซ

If the project wanted to indicate that these two dependencies should be downloaded and built from source, and that find_package() calls should be redirected to use the built dependencies, the OVERRIDE_FIND_PACKAGE option should be used when declaring the content details:

include(FetchContent)
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  OVERRIDE_FIND_PACKAGE
)
FetchContent_Declare(
  Catch2
  GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  GIT_TAG        605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
  OVERRIDE_FIND_PACKAGE
)

# The following will automatically forward through to FetchContent_MakeAvailable()
find_package(googletest)
find_package(Catch2)

CMake provides a FindGTest module which defines some variables that older projects may use instead of linking to the imported targets. To support those cases, we can provide an extra file. ๐ŸŽ€ In keeping with the "first to define, wins" philosophy of FetchContent, we only write out that file if something else hasn't already done so:

FetchContent_MakeAvailable(googletest)

if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake AND
   NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestExtra.cmake)
  file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake
[=[
if("${GTEST_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest)
  set(GTEST_LIBRARIES GTest::gtest)
endif()
if("${GTEST_MAIN_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest_main)
  set(GTEST_MAIN_LIBRARIES GTest::gtest_main)
endif()
if("${GTEST_BOTH_LIBRARIES}" STREQUAL "")
  set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
endif()
]=])
endif()

Projects will also likely be using find_package(GTest) rather than find_package(googletest), but it's possible to make use of the CMAKE_FIND_PACKAGE_REDIRECTS_DIR area to pull in the latter as a dependency of the former. This is likely to be sufficient to satisfy a typical find_package(GTest) call. ๐Ÿซถ

FetchContent_MakeAvailable(googletest)

if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake AND
   NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfig.cmake)
  file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
[=[
include(CMakeFindDependencyMacro)
find_dependency(googletest)
]=])
endif()

if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake AND
   NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfigVersion.cmake)
  file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake
[=[
include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-config-version.cmake OPTIONAL)
if(NOT PACKAGE_VERSION_COMPATIBLE)
  include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestConfigVersion.cmake OPTIONAL)
endif()
]=])
endif()

๐ŸŽฏ Overriding Where To Find CMakeLists.txt

Okay so sometimes the sub-project's CMakeLists.txt file is not chilling at the top level of its source tree โ€” like, it's hiding in a subfolder somewhere, living its truth. That's where the SOURCE_SUBDIR option comes in: it tells FetchContent exactly where to go find it. ๐Ÿ’…

The example below shows how to use that option, and it also sets a variable that's meaningful to the subproject before pulling it into the main build. Heads up: it's set as an INTERNAL cache variable to avoid problems with policy CMP0077 <#policy:CMP0077>. iykyk.

include(FetchContent)
FetchContent_Declare(
  protobuf
  GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
  GIT_TAG        ae50d9b9902526efd6c7a1907d09739f959c6297 # v3.15.0
  SOURCE_SUBDIR  cmake
)
set(protobuf_BUILD_TESTS OFF CACHE INTERNAL "")
FetchContent_MakeAvailable(protobuf)

๐ŸŒณ Complex Dependency Hierarchies

In more complex project hierarchies, the dependency relationships can get more complicated. Buckle up bestie. ๐ŸŽข

Consider a hierarchy where projA is the top level project, and it depends directly on projects projB and projC. Both projB and projC can be built standalone, and they also both depend on another project projD. On top of that, projB additionally depends on projE. This example assumes that all five projects are available on a company git server. The CMakeLists.txt of each project might have sections like the following:

projA

include(FetchContent)
FetchContent_Declare(
  projB
  GIT_REPOSITORY git@mycompany.com:git/projB.git
  GIT_TAG        4a89dc7e24ff212a7b5167bef7ab079d
)
FetchContent_Declare(
  projC
  GIT_REPOSITORY git@mycompany.com:git/projC.git
  GIT_TAG        4ad4016bd1d8d5412d135cf8ceea1bb9
)
FetchContent_Declare(
  projD
  GIT_REPOSITORY git@mycompany.com:git/projD.git
  GIT_TAG        origin/integrationBranch
)
FetchContent_Declare(
  projE
  GIT_REPOSITORY git@mycompany.com:git/projE.git
  GIT_TAG        v2.3-rc1
)

# Order is important, see notes in the discussion further below
FetchContent_MakeAvailable(projD projB projC)

projB

include(FetchContent)
FetchContent_Declare(
  projD
  GIT_REPOSITORY git@mycompany.com:git/projD.git
  GIT_TAG        20b415f9034bbd2a2e8216e9a5c9e632
)
FetchContent_Declare(
  projE
  GIT_REPOSITORY git@mycompany.com:git/projE.git
  GIT_TAG        68e20f674a48be38d60e129f600faf7d
)

FetchContent_MakeAvailable(projD projE)

projC

include(FetchContent)
FetchContent_Declare(
  projD
  GIT_REPOSITORY git@mycompany.com:git/projD.git
  GIT_TAG        7d9a17ad2c962aa13e2fbb8043fb6b8a
)

FetchContent_MakeAvailable(projD)

A few key points should be noted in the above, bestie โ€” this is the important part:

  • projB and projC define different content details for projD, but projA also defines a set of content details for projD. Because projA will define them first, the details from projB and projC will not be used. The override details defined by projA are not required to match either of those from projB or projC, but it is up to the higher level project to ensure that the details it does define still make sense for the child projects. ๐Ÿ‘‘
  • In the projA call to FetchContent_MakeAvailable(), projD is listed ahead of projB and projC, so it will be populated before either projB or projC. It isn't required for projA to do this, but doing so ensures that projA fully controls the environment in which projD is brought into the build (directory properties are particularly relevant). โœจ
  • While projA defines content details for projE, it does not need to explicitly call FetchContent_MakeAvailable(projE) or FetchContent_Populate(projD) itself. Instead, it leaves that to the child projB. For higher level projects, it is often enough to just define the override content details and leave the actual population to the child projects. This saves repeating the same thing at each level of the project hierarchy unnecessarily, but it should only be done if directory properties set by dependencies are not expected to influence the population of the shared dependency (projE in this case).

๐Ÿ“ฆ Populating Content Without Adding It To The Build

Projects don't always need to add the populated content to the build. Sometimes the project just wants to make the downloaded content available at a predictable location. ๐Ÿ—บ๏ธ

The next example ensures that a set of standard company toolchain files (and potentially even the toolchain binaries themselves) is available early enough to be used for that same build:

cmake_minimum_required(VERSION 3.14)

include(FetchContent)
FetchContent_Declare(
  mycom_toolchains
  URL  https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
)
FetchContent_MakeAvailable(mycom_toolchains)

project(CrossCompileExample)

The project could be configured to use one of the downloaded toolchains like so:

cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src

When CMake processes the CMakeLists.txt file, it will download and unpack the tarball into _deps/mycompany_toolchains-src relative to the build directory. The CMAKE_TOOLCHAIN_FILE <#variable:CMAKE_TOOLCHAIN_FILE> variable is not used until the project() <#command:project> command is reached, at which point CMake looks for the named toolchain file relative to the build directory. Because the tarball has already been downloaded and unpacked by then, the toolchain file will be in place โ€” even the very first time that cmake is run in the build directory. ๐ŸŽ€


๐Ÿงš Populating Content In CMake Script Mode

This last example demonstrates how one might download and unpack a firmware tarball using CMake's script mode <#script-processing-mode>. The call to FetchContent_Populate() specifies all the content details, and the unpacked firmware will be placed in a firmware directory below the current working directory.

getFirmware.cmake

# NOTE: Intended to be run in script mode with cmake -P
include(FetchContent)
FetchContent_Populate(
  firmware
  URL        https://mycompany.com/assets/firmware-1.23-arm.tar.gz
  URL_HASH   MD5=68247684da89b608d466253762b0ff11
  SOURCE_DIR firmware
)

โœจ FindPackageHandleStandardArgs โœจ

This module provides commands intended for use in Find Modules <#find-modules> implementing find_package(<PackageName>) <#command:find_package> calls.

Load this module in a CMake find module with:

FindFoo.cmake

include(FindPackageHandleStandardArgs)

๐ŸŒธ Commands

This module provides the following commands:

  • find_package_handle_standard_args()
  • find_package_check_version()

๐Ÿ’… find_package_handle_standard_args

Handles the REQUIRED, QUIET and version-related arguments of find_package() <#command:find_package>.

There are two signatures:

find_package_handle_standard_args(
  <PackageName>
  (DEFAULT_MSG|<custom-failure-message>)
  <required-vars>...
)
find_package_handle_standard_args(
  <PackageName>
  [REQUIRED_VARS <required-vars>...]
  [VERSION_VAR <version-var>]
  [HANDLE_VERSION_RANGE]
  [HANDLE_COMPONENTS]
  [CONFIG_MODE]
  [NAME_MISMATCHED]
  [REASON_FAILURE_MESSAGE <reason-failure-message>]
  [FAIL_MESSAGE <custom-failure-message>]
  [FOUND_VAR <result-var>] # Deprecated
)

This command sets the <PackageName>_FOUND variable to TRUE if all the variables listed in <required-vars>... contain valid results (e.g., valid filepaths) and any optional constraints are satisfied, and FALSE otherwise. A success or failure message may be displayed based on the results and on whether the REQUIRED and/or QUIET option was given to the find_package() <#command:find_package> call. ๐Ÿซถ

The arguments are:

  • <PackageName> โ€” the name of the package. For example, as written in the Find<PackageName>.cmake find module filename.
  • (DEFAULT_MSG|<custom-failure-message>) โ€” in the simple signature, this specifies the failure message. Use DEFAULT_MSG to ask for a default message to be computed (recommended). Not valid in the full signature.
  • REQUIRED_VARS <required-vars>... โ€” specify the variables which are required for this package. These may be named in the generated failure message asking the user to set the missing variable values. Therefore these should typically be cache entries such as Foo_LIBRARY and not output variables like Foo_LIBRARIES.

Changed in version 3.18: if HANDLE_COMPONENTS is specified, this option can be omitted.

  • VERSION_VAR <version-var> โ€” specify the name of a variable that holds the version of the package that has been found. This version will be checked against the (potentially) specified required version given to the find_package() <#command:find_package> call, including its EXACT option. The default messages include information about the required version and the version which has been actually found, both if the version is ok or not. ๐Ÿ”ฅ
  • HANDLE_VERSION_RANGE โ€” added in version 3.19. Enable handling of a version range, if one is specified. Without this option, a developer warning will be displayed if a version range is specified.
  • HANDLE_COMPONENTS โ€” enable handling of package components. In this case, the command will report which components have been found and which are missing, and the <PackageName>_FOUND variable will be set to FALSE if any of the required components (i.e. not the ones listed after the OPTIONAL_COMPONENTS option of find_package() <#command:find_package>) are missing. ๐Ÿ˜ญ
  • CONFIG_MODE โ€” specify that the calling find module is a wrapper around a call to find_package(<PackageName> NO_MODULE). This implies a VERSION_VAR value of <PackageName>_VERSION. The command will automatically check whether the package configuration file was found.
  • NAME_MISMATCHED โ€” added in version 3.17.

Indicate that the <PackageName> does not match the value of the CMAKE_FIND_PACKAGE_NAME variable. Like, this is usually a mistake and CMake will side-eye you with a warning ๐Ÿ˜ฌ โ€” but sometimes it's lowkey intentional, like when you're using the command for components of a bigger package. So it's allowed, just be aware.

  • REASON_FAILURE_MESSAGE <reason-failure-message> โ€” Added in version 3.16. ๐Ÿ’ซ Here's where you drop your own custom message explaining why the failure happened, and it gets appended to the default generated message. Main character reason, default-message supporting role ๐ŸŽ€
  • FAIL_MESSAGE <custom-failure-message> โ€” Lets you specify a completely custom failure message instead of the default generated one. Not recommended ๐Ÿ™ˆ ngl, just let the default do its thing.
  • FOUND_VAR <result-var> โ€” Deprecated since version 3.3: this option should no longer be used, periodt ๐Ÿ’… It specifies either <PackageName>_FOUND or <PACKAGENAME>_FOUND as the result variable. It exists only for backward compatibility with older CMake versions and is now ignored. Both result variables are now always set anyway โ€” with or without this option โ€” for compatibility. So it's giving "we keep it around but we don't listen to it" energy ๐Ÿซ 
Note ๐Ÿ’– โ€” If <PackageName> doesn't match CMAKE_FIND_PACKAGE_NAME for the calling module, you get a warning that there's a mismatch. Two ways to dodge it: set the FPHSA_NAME_MISMATCHED variable (if you're using the old signature), or use the NAME_MISMATCHED argument (new signature). And so you don't force callers to require newer CMake versions just to use your module: for the new signature, if the NAME_MISMATCHED argument isn't passed, the variable's value gets used if it's defined. But using both at the same time? That's an error, bestie ๐Ÿ˜ญ pick a lane.

find_package_check_version โœจ

Added in version 3.19.

This one checks if a given version is valid against the version-related arguments of find_package() ๐Ÿฆ‹

find_package_check_version(
  <version>
  <result-var>
  [HANDLE_VERSION_RANGE]
  [RESULT_MESSAGE_VARIABLE <message-var>]
)

Okay so the arguments, one by one ๐Ÿ‘‘

  • <version> โ€” the version string you want checked. That's it, that's the whole vibe.
  • <result-var> โ€” the name of the result variable that'll hold a boolean value giving the result of the check. TRUE found, FALSE not, yk ๐Ÿ˜Œ
  • HANDLE_VERSION_RANGE โ€” turns on handling of a version range, if one is specified. Without this option, you get a developer warning if a version range is specified. So like, if ranges are in play and you didn't opt in, expect to be called out ๐Ÿ’€
  • RESULT_MESSAGE_VARIABLE <message-var> โ€” specify a variable to get back a message describing the result of the check. Cute little receipt of what happened ๐Ÿงพ

Examples ๐ŸŽ€

Examples: Full Signature

Example for using a full signature of find_package_handle_standard_args():

FindLibArchive.cmake

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
  LibArchive
  REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR
  VERSION_VAR LibArchive_VERSION
)

In this case, the LibArchive package counts as found if both LibArchive_LIBRARY and LibArchive_INCLUDE_DIR are valid. Also, the version of LibArchive gets checked using the version contained in LibArchive_VERSION. And since no FAIL_MESSAGE is given, the default messages get printed. Slay, defaults ๐Ÿ‘‘

Another example for the full signature of find_package_handle_standard_args():

FindAutomoc4.cmake

find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Automoc4 CONFIG_MODE)

So here, a FindAutomoc4.cmake module wraps a call to find_package(Automoc4 NO_MODULE) and adds an extra search directory for automoc4. Then the call to find_package_handle_standard_args() produces a proper success/failure message. Like, it handles the messaging so you don't have to ๐Ÿ’…

Example: Simple Signature

Example for using a simple signature of find_package_handle_standard_args():

FindLibXml2.cmake

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
  LibXml2
  DEFAULT_MSG
  LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR
)

In this example, the LibXml2 package is considered found if both LIBXML2_LIBRARY and LIBXML2_INCLUDE_DIR variables are valid. Then LibXml2_FOUND also gets set to TRUE. If it's not found and REQUIRED was used, it fails with a message(FATAL_ERROR), regardless of whether QUIET was used or not ๐Ÿ˜ค no quiet-option immunity here. If it is found, success gets reported, including the content of the first required variable specified in <required-vars>..... And on repeated CMake runs, the same message won't be printed again โ€” no spam, we love that for us โœจ

Example: Checking Version

Example for the find_package_check_version() usage:

FindFoo.cmake

include(FindPackageHandleStandardArgs)
find_package_check_version(
  1.2.3
  result
  HANDLE_VERSION_RANGE
  RESULT_MESSAGE_VARIABLE reason
)
if(result)
  message(STATUS "${reason}")
else()
  # Logic when version check is not successful.
  message(WARNING "${reason}")
endif()

See Also ๐ŸŒˆ

  • Find Modules for details how to write a find module. iykyk ๐Ÿ“–

FindPackageMessage ๐Ÿ’Œ

This module provides a command for printing find result messages, and it's intended for use in Find Modules implementing find_package(<PackageName>) calls. Basically: "hey bestie, we found this thing, here's where it is" ๐Ÿ“ฃ

Load this module in a CMake find module with:

FindFoo.cmake

include(FindPackageMessage)

Commands ๐Ÿ‘‘

This module provides the following command:

find_package_message

Prints a message once for each unique find result, to inform the user which package was found and where:

find_package_message(<PackageName> <message> <details>)
  • <PackageName> โ€” the name of the package (for example, as used in the Find<PackageName>.cmake module filename).
  • <message> โ€” the message string to display.
  • <details> โ€” a unique identifier for tracking message display. The <message> is printed only once per distinct <details> value. If the <details> string changes in a subsequent configuration phase, the message will be displayed again. So it's a little memory-holder for "did I already say this?" ๐Ÿง โœจ

If find_package() was called with the QUIET option, the <message> is not printed. Respect the quiet, periodt ๐Ÿคซ


Examples ๐Ÿ“

Printing a result message in a custom find module:

FindFoo.cmake

find_library(Foo_LIBRARY foo)
find_path(Foo_INCLUDE_DIR foo.h)

include(FindPackageMessage)

if(Foo_LIBRARY AND Foo_INCLUDE_DIR)
  find_package_message(
    Foo
    "Found Foo: ${Foo_LIBRARY}"
    "[${Foo_LIBRARY}][${Foo_INCLUDE_DIR}]"
  )
else()
  message(STATUS "Could NOT find Foo")
endif()

When writing standard find modules, use the FindPackageHandleStandardArgs module and its find_package_handle_standard_args() command, which automatically prints the find result message based on whether the package was found. Like, why hand-roll it when the icon already does it ๐Ÿ‘‘

FindFoo.cmake

# ...

include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(
  Foo
  REQUIRED_VARS Foo_LIBRARY Foo_INCLUDE_DIR
)

FortranCInterface ๐Ÿฆ‹

This module provides variables and commands to detect Fortran/C Interface. Yes, Fortran and C, together, in one project โ€” iconic crossover episode ๐Ÿ’œ

Load this module in a CMake project with:

include(FortranCInterface)

This module automatically detects the API by which C and Fortran languages interact. It just figures it out for you and honestly? obsessed ๐Ÿ”ฅ


Variables ๐ŸŒธ

Result Variables

Including this module defines the following variables that indicate if the mangling is found:

  • FortranCInterface_GLOBAL_FOUND โ€” boolean indicating whether global subroutines and functions are available. โœ…/โŒ
  • FortranCInterface_MODULE_FOUND โ€” boolean indicating whether module subroutines and functions (declared by MODULE PROCEDURE) are available. That's the fancy module-scoped ones ๐Ÿ’…

Input Variables

This module also provides the following variables to specify the detected mangling, though a typical use case doesn't need to reference them at all โ€” you can just use the Commands below and vibe โœจ

  • FortranCInterface_GLOBAL_PREFIX โ€” prefix for a global symbol without an underscore.
  • FortranCInterface_GLOBAL_SUFFIX โ€” suffix for a global symbol without an underscore.
  • FortranCInterface_GLOBAL_CASE โ€” the case for a global symbol without an underscore, either UPPER or LOWER.
  • FortranCInterface_GLOBAL__PREFIX โ€” prefix for a global symbol with an underscore. (Yes, that's two underscores in the name โ€” not a typo, bestie ๐Ÿ˜ญ)
  • FortranCInterface_GLOBAL__SUFFIX โ€” suffix for a global symbol with an underscore.
  • FortranCInterface_GLOBAL__CASE โ€” the case for a global symbol with an underscore, either UPPER or LOWER.
  • FortranCInterface_MODULE_PREFIX โ€” prefix for a module symbol without an underscore.
  • FortranCInterface_MODULE_MIDDLE โ€” middle of a module symbol without an underscore that appears between the name of the module and the name of the symbol. The literal middle child ๐Ÿฅบ
  • FortranCInterface_MODULE_SUFFIX โ€” suffix for a module symbol without an underscore.
  • FortranCInterface_MODULE_CASE โ€” the case for a module symbol without an underscore, either UPPER or LOWER.
  • FortranCInterface_MODULE_ORDER โ€” Added in version 4.1. Order of components for module symbols without an underscore:
    • MODULE_THEN_SYMBOL โ€” the module name appears before the symbol name, i.e., <PREFIX><module><MIDDLE><symbol><SUFFIX>.
    • SYMBOL_THEN_MODULE โ€” the module name appears after the symbol name, i.e., <PREFIX><symbol><MIDDLE><module><SUFFIX>.
  • FortranCInterface_MODULE__PREFIX โ€” prefix for a module symbol with an underscore.
  • FortranCInterface_MODULE__MIDDLE โ€” middle of a module symbol with an underscore that appears between the name of the module and the name of the symbol.
  • FortranCInterface_MODULE__SUFFIX โ€” suffix for a module symbol with an underscore.
  • FortranCInterface_MODULE__CASE โ€” the case for a module symbol with an underscore, either UPPER or LOWER.
  • FortranCInterface_MODULE__ORDER โ€” Added in version 4.1. Order of components for module symbols with an underscore:
  • MODULE_THEN_SYMBOL โ€” the module name shows up before the symbol name, like <PREFIX><module><MIDDLE><symbol><SUFFIX>. ๐Ÿ’…
  • SYMBOL_THEN_MODULE โ€” opposite behavior bestie: module name comes after the symbol, i.e. <PREFIX><symbol><MIDDLE><module><SUFFIX>. ๐Ÿฆ‹

โœจ Variables For Additional Manglings โœจ

This module already knows about a bunch of possible GLOBAL and MODULE manglings for lots of Fortran compilers, but it also hands you an interface so you can add your own. ๐Ÿซถ Set the following variables before including this module to add extra manglings:

FortranCInterface_GLOBAL_SYMBOLS

FortranCInterface_MODULE_SYMBOLS

...before including this module, to specify manglings of the symbols MySub, My_Sub, MyModule:MySub, and My_Module:My_Sub. ๐ŸŒธ

๐ŸŽ€ Commands ๐ŸŽ€

This module provides the following commands:

FortranCInterface_HEADER

Generates a C header file stuffed with macros that mangle symbol names ๐Ÿ’–:

FortranCInterface_HEADER(
  <file>
  [MACRO_NAMESPACE <macro-ns>]
  [SYMBOL_NAMESPACE <ns>]
  [SYMBOLS [<module>:]<function> ...]
)

This command generates a <file> with definitions of these macros:

#define FortranCInterface_GLOBAL (name,NAME) ...
#define FortranCInterface_GLOBAL_(name,NAME) ...
#define FortranCInterface_MODULE (mod,name, MOD,NAME) ...
#define FortranCInterface_MODULE_(mod,name, MOD,NAME) ...

These macros mangle four categories of Fortran symbols, respectively:

  • Global symbols without '_': call mysub()
  • Global symbols with '_': call my_sub()
  • Module symbols without '_': use mymod; call mysub()
  • Module symbols with '_': use mymod; call my_sub()

If the mangling for some category isn't known, its macro is just left undefined (she's ghosting you ๐Ÿ‘ป). And heads up: all macros require raw names in both lower case and upper case, no exceptions.

The options are:

  • MACRO_NAMESPACE โ€” replaces the default FortranCInterface_ prefix with whatever namespace <macro-ns> you hand it. ๐ŸŽ€
  • SYMBOL_NAMESPACE โ€” prefixes all the preprocessor definitions generated by the SYMBOLS option with a given namespace <ns>. โœจ
  • SYMBOLS โ€” lists the symbols to mangle automatically with C preprocessor definitions:
<function>          ==> #define <ns><function> ...
<module>:<function> ==> #define <ns><module>_<function> ...

If the mangling for some symbol isn't known, then no preprocessor definition gets created, and a warning is displayed. ๐Ÿ™ˆ

FortranCInterface_VERIFY

Verifies that the Fortran and C/C++ compilers actually work together, no cap ๐Ÿงš:

FortranCInterface_VERIFY([CXX] [QUIET])

This command tests whether a simple test executable using Fortran and C (and C++ when the CXX option is given) compiles and links successfully. The result lands in the cache entry FortranCInterface_VERIFIED_C (or FortranCInterface_VERIFIED_CXX if CXX is given) as a boolean. If the check fails and QUIET is not given, the command terminates with a fatal error message describing the problem. ๐Ÿ’€ The whole point of this check is to stop a build early for incompatible compiler combinations. The test is built in the Release configuration.


๐ŸŒˆ Examples ๐ŸŒˆ

Examples: Basic Usage

The following example creates a FC.h header that defines mangling macros FC_GLOBAL(), FC_GLOBAL_(), FC_MODULE(), and FC_MODULE_():

include(FortranCInterface)
FortranCInterface_HEADER(FC.h MACRO_NAMESPACE "FC_")

The next example creates a FCMangle.h header that defines those same FC_*() mangling macros as the previous example, plus the preprocessor symbols FC_mysub and FC_mymod_my_sub. Slay. ๐Ÿ‘‘

include(FortranCInterface)
FortranCInterface_HEADER(
  FCMangle.h
  MACRO_NAMESPACE "FC_"
  SYMBOL_NAMESPACE "FC_"
  SYMBOLS mysub mymod:my_sub
)

Example: Additional Manglings

The following example shows how to specify manglings of the symbols MySub, My_Sub, MyModule:MySub, and My_Module:My_Sub. The code below tells this module to try the given GLOBAL and MODULE manglings. (The carets point at raw symbol names for clarity in this example, but they are not needed. ๐Ÿซถ)

set(FortranCInterface_GLOBAL_SYMBOLS mysub_ my_sub__ MYSUB_)
  #                                  ^^^^^  ^^^^^^   ^^^^^
set(FortranCInterface_MODULE_SYMBOLS
    __mymodule_MOD_mysub __my_module_MOD_my_sub)
  #   ^^^^^^^^     ^^^^^   ^^^^^^^^^     ^^^^^^

include(FortranCInterface)

# ...

๐Ÿ’… GenerateExportHeader ๐Ÿ’…

This module provides commands for generating a header file containing preprocessor macro definitions to control C/C++ symbol visibility. ๐Ÿ‘€

Load this module in a CMake project with:

include(GenerateExportHeader)

Added in version 3.12: Support for C projects. Previous versions supported C++ projects only. โœจ

When developing C or C++ projects, especially for cross-platform use, symbol visibility determines which functions, classes, global variables, templates, and other symbols are made visible to users of the library. It's giving gatekeeper energy fr fr.

For example, on Windows, symbols must be explicitly marked with __declspec(dllexport) when building a shared library, and __declspec(dllimport) when using it. Other platforms may use attributes like __attribute__((visibility("default"))).

This module simplifies the creation and usage of preprocessor macros to manage these requirements, avoiding repetitive and error-prone #ifdef blocks in source code. ๐Ÿ˜ญ (not the #ifdef spaghetti)

Some symbol visibility can also be controlled with compiler options. In CMake, target properties such as <LANG>_VISIBILITY_PRESET and VISIBILITY_INLINES_HIDDEN enable compiler visibility flags, where appropriate. See also the related convenience variables CMAKE_<LANG>_VISIBILITY_PRESET and CMAKE_VISIBILITY_INLINES_HIDDEN to enable it for all targets in the current scope. These are commonly used in combination with this module to further simplify C/C++ code, removing the need for some of the preprocessor macros in the source code. ๐Ÿงš

โญ Commands โญ

This module provides the following commands:

๐ŸŒธ Generating Export Header ๐ŸŒธ

generate_export_header

Generates a header file suitable for inclusion in source code, containing preprocessor export macros for controlling the visibility of symbols ๐Ÿ’–:

generate_export_header(
  <target>
  [BASE_NAME <base-name>]
  [EXPORT_FILE_NAME <export-file-name>]
  [EXPORT_MACRO_NAME <export-macro-name>]
  [NO_EXPORT_MACRO_NAME <no-export-macro-name>]
  [DEPRECATED_MACRO_NAME <deprecated-macro-name>]
  [DEFINE_NO_DEPRECATED]
  [NO_DEPRECATED_MACRO_NAME <no-deprecated-macro-name>]
  [STATIC_DEFINE <static-define>]
  [PREFIX_NAME <prefix>]
  [CUSTOM_CONTENT_FROM_VARIABLE <variable>]
  [INCLUDE_GUARD_NAME <include-guard-name>]
)

By default, this command generates a header file named <target-name-lowercase>_export.h in the current binary directory (CMAKE_CURRENT_BINARY_DIR). This header defines a set of preprocessor macros used to mark API symbols as exported, hidden, or deprecated across different platforms and build types (e.g., static or shared builds), and is intended to be installed along with the library's public headers, because it affects public API declarations. ๐Ÿ‘‘

  • <MACRO>_EXPORT: Marks symbols for export or import, making them visible as part of the public API when building or consuming a shared library. ๐Ÿ”ฅ
  • <MACRO>_NO_EXPORT: Marks symbols that should not be exported. If the <LANG>_VISIBILITY_PRESET target property is set to hidden, using this macro in source code is typically redundant.
  • <MACRO>_DEPRECATED: Marks symbols as deprecated. When such symbols are used, the compiler emits a warning at compile-time. ๐Ÿ’€
  • <MACRO>_DEPRECATED_EXPORT: Combines export/import and deprecation markers for a symbol that is both part of the public API and deprecated. ๐Ÿ’…
  • <MACRO>_DEPRECATED_NO_EXPORT: Marks a deprecated symbol that should not be exported (internal and deprecated).
  • <MACRO>_NO_DEPRECATED: A macro that can be used in source code to conditionally exclude deprecated code parts from the build via preprocessor logic. ๐Ÿฆ‹

The <MACRO> part is derived by default from the uppercase name of the target or the explicitly provided <base-name>. All macro names can be customized using the optional arguments. ๐ŸŽ€

The arguments are:

  • <target> โ€” name of a target for which the export header will be generated. Supported target types:
    • STATIC library (in this case, export-related macros are defined without values) ๐ŸŒธ
    • SHARED library
    • MODULE library
    • Added in version 3.1: OBJECT library โญ
  • BASE_NAME <base-name> โ€” if specified, it overrides the default file name and macro names.
  • EXPORT_FILE_NAME <export-file-name> โ€” if specified, it overrides the full path and the name of the generated export header file (<base-name-lowercase>_export.h) to <export-file-name>. If given as a relative path, it will be interpreted relative to the current binary directory (CMAKE_CURRENT_BINARY_DIR). ๐Ÿซถ
  • EXPORT_MACRO_NAME <export-macro-name> โ€” if specified, it overrides the default macro name for the export directive.
  • NO_EXPORT_MACRO_NAME <no-export-macro-name> โ€” if specified, the <no-export-macro-name> will be used for the macro name that designates the attribute for items that shouldn't be exported. ๐Ÿ™ˆ
  • DEPRECATED_MACRO_NAME <deprecated-macro-name> โ€” if specified, the following names will be used:
    • <deprecated-macro-name> (macro for marking deprecated symbols)
  • <deprecated-macro-name>_EXPORT โ€” okay so this one's the macro for deprecated symbols that do get export markers ๐ŸŽ€
    • <deprecated-macro-name>_NO_EXPORT โ€” and this is the macro for deprecated symbols with the no-export markers ๐ŸŽ€

โ€ฆand you use those instead of the default names, which come in the format <MACRO>_DEPRECATED{,_EXPORT,_NO_EXPORT}. iykyk โœจ

DEFINE_NO_DEPRECATED

If you pass this, it defines a macro named <MACRO>_NO_DEPRECATED. That's literally it, bestie โ€” a whole little flag macro appears ๐Ÿ’…

NO_DEPRECATED_MACRO_NAME <no-deprecated-macro-name>

Only really does anything when you pair it with the DEFINE_NO_DEPRECATED option. If you specify it, then a macro named <no-deprecated-macro-name> gets used instead of the default <MACRO>_NO_DEPRECATED. So you get to name your own little guy ๐Ÿฆ‹

STATIC_DEFINE <static-define>

If specified, the <static-define> macro name is used instead of the default <MACRO>_STATIC_DEFINE. What does this macro even do? It controls the symbol export behavior in the generated header for static libraries โ€” main character of the static world ๐Ÿ‘‘

It's typically used when you're building both shared and static variants of a library from the same sources, using a single generated export header. And when this macro is defined for the static library, the export-related macros expand to nothing. Which matters a LOT on Windows, because symbol decoration is only required for shared libraries there, not static ones. no cap ๐Ÿ”ฅ

PREFIX_NAME <prefix>

If specified, that extra <prefix> gets prepended to all the generated macro names. Prepend arc, slay ๐Ÿ’œ

CUSTOM_CONTENT_FROM_VARIABLE <variable>

Added in version 3.7.

If specified, the content from the <variable> value is appended to the generated header file content after the preprocessor macro definitions. So yes, it goes at the bottom, after the macros โ€” respect the order ๐Ÿซถ

INCLUDE_GUARD_NAME <include-guard-name>

Added in version 3.11.

If specified, <include-guard-name> is used as the preprocessor macro name to guard against multiple inclusions of the generated header, instead of the default name <export-macro-name>_H. Protect that header from being included twice, periodt โœจ

<base-name-lowercase>_export.h

   #ifndef <include-guard-name>
   #define <include-guard-name>
   // ...
   #endif /* <include-guard-name> */

๐Ÿ’€ Deprecated Command ๐Ÿ’€

add_compiler_export_flags

Deprecated since version 3.0: Set the target properties CXX_VISIBILITY_PRESET (<LANG>_VISIBILITY_PRESET) and VISIBILITY_INLINES_HIDDEN instead.

Okay so here's the whole thing, bestie: this adds the C++ compiler options -fvisibility=hidden (and -fvisibility-inlines-hidden, if supported) to hide all symbols by default โ€” either to the CMAKE_CXX_FLAGS variable (CMAKE_<LANG>_FLAGS) or to a variable you specify. Like:

add_compiler_export_flags([<output_variable>])

And on Windows this command is a straight-up no-op, because Windows doesn't need extra compiler flags for exporting support. Not its problem ๐Ÿ™ˆ

<output-variable> : Optional variable name that gets populated with a string of space-separated C++ compile options required to enable visibility support for the compiler/architecture in use. And if you do specify this argument, the CMAKE_CXX_FLAGS variable (CMAKE_<LANG>_FLAGS) will not be modified. Nobody touches it, iconic ๐Ÿ’…


๐ŸŒˆ Examples ๐ŸŒˆ

Example: Generating Export Header

The following example demonstrates how to use this module to generate an export header in the current binary directory (example_export.h) and use it in a C++ library named example to control symbols visibility. The generated header defines the preprocessor macros EXAMPLE_EXPORT, EXAMPLE_NO_EXPORT, EXAMPLE_DEPRECATED, EXAMPLE_DEPRECATED_EXPORT, and EXAMPLE_DEPRECATED_NO_EXPORT, and it's installed along with the library's other public headers. Obsessed with the tidiness honestly ๐ŸŽ€

CMakeLists.txt

cmake_minimum_required(VERSION 3.24)
project(GenerateExportHeaderExample)

# Set default visibility of all symbols to hidden
set(CMAKE_CXX_VISIBILITY_PRESET "hidden")
set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE)

add_library(example)

include(GenerateExportHeader)
generate_export_header(example)

target_sources(
  example
  PRIVATE example.cxx
  PUBLIC
    FILE_SET HEADERS
      FILES example.h
    FILE_SET generated_headers
      TYPE HEADERS
      BASE_DIRS ${CMAKE_CURRENT_BINARY_DIR}
      FILES ${CMAKE_CURRENT_BINARY_DIR}/example_export.h
)

install(
  TARGETS example
  FILE_SET HEADERS
  FILE_SET generated_headers
)

And in the ABI header files:

example.h

#include "example_export.h"

// This class is part of the public API and is exported
class EXAMPLE_EXPORT SomeClass
{
public:
  SomeClass();
  void doSomething();

  // This method is deprecated
  EXAMPLE_DEPRECATED void legacyMethod();
};

// This function is exported and deprecated
EXAMPLE_DEPRECATED_EXPORT void legacyPublicFunction();

// This function is deprecated but not exported
EXAMPLE_DEPRECATED void legacyInternalFunction();

example.cxx

#include <iostream>
#include "example.h"

SomeClass::SomeClass() = default;

void SomeClass::doSomething()
{
  std::cout << "SomeClass::doSomething() called" << std::endl;
}

void SomeClass::legacyMethod()
{
  std::cout << "SomeClass::legacyMethod() is deprecated" << std::endl;
}

void legacyPublicFunction()
{
  std::cout << "legacyPublicFunction() is deprecated" << std::endl;
}

void internalLegacyFunction()
{
  std::cout << "legacyInternalFunction() is deprecated" << std::endl;
}

Examples: Customizing Generated Header

The BASE_NAME argument can be used to override the generated file name and the names used for the macros. The following will generate a file named other_name_export.h containing export-related macros such as OTHER_NAME_EXPORT, OTHER_NAME_NO_EXPORT, OTHER_NAME_DEPRECATED, etc. Glow-up for your header ๐ŸŒธ

add_library(example example.cxx)
include(GenerateExportHeader)
generate_export_header(example BASE_NAME "other_name")

And the BASE_NAME may be overridden by specifying other command options. For example, the following creates a macro OTHER_NAME_EXPORT instead of EXAMPLE_EXPORT, but the other macros and the generated header file name stay at their default values. Selective rebranding, we love to see it ๐Ÿ’…

add_library(example example.cxx)
include(GenerateExportHeader)
generate_export_header(example EXPORT_MACRO_NAME "OTHER_NAME_EXPORT")

The following example creates the KDE_DEPRECATED macro instead of the default EXAMPLE_DEPRECATED:

add_library(example example.cxx)
include(GenerateExportHeader)
generate_export_header(example DEPRECATED_MACRO_NAME "KDE_DEPRECATED")

The DEFINE_NO_DEPRECATED option can be used to define a macro which can be used to remove deprecated code from preprocessor output. Bye-bye legacy code, you will not be missed ๐Ÿฆ‹

option(EXCLUDE_DEPRECATED "Exclude deprecated parts of the library")
if(EXCLUDE_DEPRECATED)
  set(NO_BUILD_DEPRECATED DEFINE_NO_DEPRECATED)
endif()

include(GenerateExportHeader)
generate_export_header(example ${NO_BUILD_DEPRECATED})

example.h

class EXAMPLE_EXPORT SomeClass
{
public:
#ifndef EXAMPLE_NO_DEPRECATED
  EXAMPLE_DEPRECATED void legacyMethod();
#endif
};

example.cxx

#ifndef EXAMPLE_NO_DEPRECATED
void SomeClass::legacyMethod() {  }
#endif

The PREFIX_NAME argument can be used to prepend all generated macro names with some prefix. For example, the following will generate macros such as VTK_SOMELIB_EXPORT, etc. Prefix era ๐Ÿ”ฅ

include(GenerateExportHeader)
generate_export_header(somelib PREFIX_NAME "VTK_")

Appending additional content to the generated header can be done with the CUSTOM_CONTENT_FROM_VARIABLE argument:

include(GenerateExportHeader)
set(content [[#include "project_api.h"]])
generate_export_header(example CUSTOM_CONTENT_FROM_VARIABLE content)

Example: Building Shared and Static Library

In the following example, both a shared and a static library are built from the same sources, and the <MACRO>_STATIC_DEFINE macro compile definition is defined to make sure the same generated export header works for both. One header, two libraries, main character energy ๐Ÿ‘‘

add_library(example_shared SHARED example.cxx)
add_library(example_static STATIC example.cxx)

include(GenerateExportHeader)
generate_export_header(example_shared BASE_NAME "example")

# Define macro to disable export attributes for static build
target_compile_definitions(example_static PRIVATE EXAMPLE_STATIC_DEFINE)

Example: Upgrading Deprecated Command

In earlier versions of CMake, the add_compiler_export_flags() command was used to add symbol visibility compile options. Look at this historical artifact ๐Ÿ˜ญ

CMakeLists.txt

add_library(example example.cxx)

include(GenerateExportHeader)

add_compiler_export_flags(flags)
string(REPLACE " " ";" flags "${flags}")
set_property(TARGET example APPEND PROPERTY COMPILE_OPTIONS "${flags}")

generate_export_header(example)

In new code, the following target properties are used to achieve the same functionality. Glow-up complete โœจ

CMakeLists.txt

add_library(example example.cxx)

include(GenerateExportHeader)

set_target_properties(
  example
  PROPERTIES
    CXX_VISIBILITY_PRESET hidden
    VISIBILITY_INLINES_HIDDEN TRUE
)

generate_export_header(example)

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The DEFINE_SYMBOL target property, for customizing the preprocessor macro name used by the generated header. This macro determines whether the library header is being included during the library's own compilation or when it's used by another project (e.g., after installation). Context is everything, bestie ๐Ÿซถ
  • The ENABLE_EXPORTS target property.
  • The WINDOWS_EXPORT_ALL_SYMBOLS target property.

๐Ÿงš GNUInstallDirs ๐Ÿงš

This module defines the installation directory variables according to the GNU Coding Standards (https://www.gnu.org/prep/standards/html_node/Directory-Variables.html) and provides a command to compute installation-related absolute paths. Very "know where everything goes" of it ๐Ÿ’œ

Load this module in a CMake project with:

include(GNUInstallDirs)

Result Variables

Inclusion of this module defines the following variables:

  • CMAKE_INSTALL_<dir> โ€” bestie, this is the destination for files of a given type. You can pass this value to the DESTINATION options of install() commands for the corresponding file type. It should be a path relative to the installation prefix so it can be converted into an absolute path in a relocatable way. But โ€” there are some special cases, documented below. ๐Ÿ‘€

So like, absolute paths are allowed, but they're not recommended, because they do NOT work with the cmake --install command's --prefix option, or with the cpack installer generators. And there's genuinely no need to make paths absolute by prepending CMAKE_INSTALL_PREFIX โ€” that prefix is already used by default if the DESTINATION is a relative path. Save yourself the trouble, iykyk. ๐Ÿ’…

  • CMAKE_INSTALL_FULL_<dir> โ€” the absolute path generated from the corresponding CMAKE_INSTALL_<dir> value. If the value isn't already an absolute path, an absolute path gets constructed โ€” typically by prepending the value of the CMAKE_INSTALL_PREFIX variable, except in the special cases documented below. โœจ

These variables shouldn't be used in install() commands, because they don't work with the cmake --install command's --prefix option, or with the cpack installer generators. Periodt.


where <dir> is one of these icons ๐Ÿ‘‘:

  • BINDIR โ€” user executables (bin)
  • SBINDIR โ€” system admin executables (sbin)
  • LIBEXECDIR โ€” program executables (libexec)
  • SYSCONFDIR โ€” read-only single-machine data (etc)

Changed in version 4.1: if the CMAKE_INSTALL_PREFIX falls into the special cases, the default paths are the absolute path variants as described there. See policy CMP0192. ๐Ÿซถ

  • SHAREDSTATEDIR โ€” modifiable architecture-independent data (com)
  • LOCALSTATEDIR โ€” modifiable single-machine data (var)

Changed in version 4.1: if the CMAKE_INSTALL_PREFIX falls into the special cases, the default paths are the absolute path variants as described there. See policy CMP0192. ๐Ÿซถ

  • RUNSTATEDIR โ€” run-time variable data (LOCALSTATEDIR/run)

Added in version 3.9.

Changed in version 4.1: if the CMAKE_INSTALL_PREFIX falls into the special cases, the default paths are the absolute path variants as described there. See policy CMP0192. ๐Ÿซถ

  • LIBDIR โ€” object code libraries (lib or lib64)

On Linux, when you're not cross-compiling, the default is the distro's arch-specific library directory, like lib or lib64. On Debian, this may be lib/<multiarch-tuple> when CMAKE_INSTALL_PREFIX is /usr. When cross-compiling, the default is lib. ๐ŸŒธ

Note: when an alternative installation prefix is specified with the --prefix option at install time, the special case with the multi-architecture tuple is evaluated based on the configuration-time CMAKE_INSTALL_PREFIX, not on the alternative prefix value. Don't get it twisted! ๐Ÿ˜ญ
  • INCLUDEDIR โ€” C header files (include)
  • OLDINCLUDEDIR โ€” C header files for non-gcc (/usr/include)
  • DATAROOTDIR โ€” read-only architecture-independent data root (share)
  • DATADIR โ€” read-only architecture-independent data (DATAROOTDIR)

DATADIR and DATAROOTDIR are treated separately so that DATADIR can be customized for project-specific data files, while DATAROOTDIR stays unchanged for the standard architecture-independent locations INFODIR, LOCALEDIR, MANDIR, and DOCDIR. The way that's such a clean design tho. ๐Ÿงš

  • INFODIR โ€” info documentation (DATAROOTDIR/info)
  • LOCALEDIR โ€” locale-dependent data (DATAROOTDIR/locale)
  • MANDIR โ€” man documentation (DATAROOTDIR/man)
  • DOCDIR โ€” documentation root (DATAROOTDIR/doc/PROJECT_NAME)

If the includer doesn't define a value, the above-shown default gets used, and the value shows up in the cache for the user to edit. Highkey convenient. ๐Ÿ’–

If a default value for CMAKE_INSTALL_<dir> is used and CMAKE_INSTALL_PREFIX gets changed, the new default value gets calculated off the new CMAKE_INSTALL_PREFIX value. Using --prefix in cmake --install will not alter these values. ๐Ÿคทโ€โ™€๏ธ

๐Ÿ’€ Special Cases ๐Ÿ’€

Added in version 3.4.

These particular values of CMAKE_INSTALL_PREFIX are special, bestie โ€” pay attention:

  • /

For <dir> other than SYSCONFDIR, LOCALSTATEDIR and RUNSTATEDIR, the value of CMAKE_INSTALL_<dir> is prefixed with usr/ if it isn't user-specified as an absolute path. For example, the INCLUDEDIR value include becomes usr/include. This is required by the GNU Coding Standards (https://www.gnu.org/prep/standards/html_node/Directory-Variables.html), which state:

When building the complete GNU system, the prefix will be empty and /usr will be a symbolic link to /.

Changed in version 4.1: the CMAKE_INSTALL_<dir> variables are cached with the usr/ prefix. See policy CMP0193. โœจ

  • /usr

For <dir> equal to SYSCONFDIR, LOCALSTATEDIR or RUNSTATEDIR, the CMAKE_INSTALL_FULL_<dir> is computed by prepending just / to the value of CMAKE_INSTALL_<dir> if it isn't already an absolute path. For example, the SYSCONFDIR value etc becomes /etc. This is required by the GNU Coding Standards (https://www.gnu.org/prep/standards/html_node/Directory-Variables.html). ๐Ÿฆ‹

Changed in version 4.1: the default values of CMAKE_INSTALL_<dir> for <dir> equal to SYSCONFDIR, LOCALSTATEDIR and RUNSTATEDIR are the absolute paths /etc, /var and /var/run respectively. See policy CMP0192.

  • /opt/...

For <dir> equal to SYSCONFDIR, LOCALSTATEDIR or RUNSTATEDIR, the CMAKE_INSTALL_FULL_<dir> is computed by appending the prefix to the value of CMAKE_INSTALL_<dir> if it isn't already an absolute path. For example, the SYSCONFDIR value etc becomes /etc/opt/.... This is defined by the Filesystem Hierarchy Standard (https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html). ๐Ÿ“š

This behavior does not apply to paths under /opt/homebrew/.... (sorry, Homebrew girlies ๐Ÿ“)

Changed in version 4.1: the default values of CMAKE_INSTALL_<dir> for <dir> equal to SYSCONFDIR, LOCALSTATEDIR and RUNSTATEDIR are the absolute paths /etc/opt/..., /var/opt/... and /var/run/opt/... respectively. See policy CMP0192.

Note: when an alternative installation prefix is specified with the --prefix option at install time, these special cases are evaluated based on the configuration-time CMAKE_INSTALL_PREFIX, not on the alternative prefix value. Literally the same energy as before, just saying it again for the people in the back. ๐Ÿ™ˆ

๐ŸŽ€ Commands ๐ŸŽ€

This module provides the following command:

GNUInstallDirs_get_absolute_install_dir

Added in version 3.7.

Computes an absolute installation path from a given relative path:

GNUInstallDirs_get_absolute_install_dir(<result-var> <input-var> <dir>)

This command takes the value from the variable <input-var> and computes its absolute path according to the GNU standard installation directories. If the input path is relative, it gets prepended with CMAKE_INSTALL_PREFIX and may be adjusted for the special cases described above. โœจ

The arguments are:

  • <result-var> โ€” name of the variable in which to store the computed absolute path.
  • <input-var> โ€” name of the variable containing the path that will be used to compute its associated absolute installation path.

Changed in version 4.1: this variable is no longer altered. See policy CMP0193. In previous CMake versions, this command modified the <input-var> variable value based on the special cases. โš ๏ธ

  • <dir> โ€” Added in version 3.20.

The directory type name, e.g. SYSCONFDIR, LOCALSTATEDIR, RUNSTATEDIR, etc. This argument determines whether special cases apply when computing the absolute path.

Changed in version 3.20: before the <dir> argument was introduced, the directory type could be specified by setting the dir variable prior to calling this command. As of CMake 3.20, if the <dir> argument is provided explicitly, the dir variable is ignored. ๐Ÿ’…

While this command is used internally by this module to compute the CMAKE_INSTALL_FULL_<dir> variables, it's also exposed publicly so users can create additional custom installation path variables and compute absolute paths where necessary, using the same logic. Main character energy for a helper command, honestly. ๐Ÿ‘‘

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The install() command.

๐ŸŒˆ GoogleTest ๐ŸŒˆ

Added in version 3.9.

This module provides commands to help you use the Google Test infrastructure. ๐Ÿงช

Load this module in a CMake project with:

include(GoogleTest)

Two mechanisms for adding tests are provided. gtest_add_tests() has been around for some time, originally via find_package(GTest). gtest_discover_tests() was introduced in CMake 3.10. โญ

The (older) gtest_add_tests() scans source files to identify tests. This is usually effective, with some caveats, including in cross-compiling environments, and it makes setting additional properties on tests more convenient. However, its handling of parameterized tests is less comprehensive, and it requires re-running CMake to detect changes to the list of tests. ๐Ÿ˜ฎโ€๐Ÿ’จ

The (newer) gtest_discover_tests() discovers tests by asking the compiled test executable to enumerate its tests. This is more robust and provides better handling of parameterized tests, and it does not require CMake to be re-run when tests change. However, it may not work in a cross-compiling environment, and setting test properties is less convenient. Trade-offs, bestie, trade-offs. โš–๏ธ

More details can be found in the documentation of the respective functions. ๐Ÿ’–

Okay so both of these commands are literally designed to replace your old-school add_test() call โ€” they register tests, and they create a separate CTest test for each individual Google Test test case. Ngl, that's sometimes less efficient, because common set-up and tear-down logic can't be shared by multiple test cases executing in the same instance. But it hands you way more fine-grained pass/fail info to CTest, which is usually considered the more beneficial trade. By default the CTest test name is the same as the Google Test name (i.e. suite.testcase) โ€” see also TEST_PREFIX and TEST_SUFFIX. ๐Ÿซถ


โœจ gtest_add_tests โœจ

Automatically add tests with CTest by scanning source code for Google Test macros:

gtest_add_tests(TARGET target
                [SOURCES src1...]
                [EXTRA_ARGS args...]
                [WORKING_DIRECTORY dir]
                [TEST_PREFIX prefix]
                [TEST_SUFFIX suffix]
                [SKIP_DEPENDENCY]
                [TEST_LIST outVar]
)

gtest_add_tests tries to identify tests by scanning source files. It's generally effective, sure, but bestie be warned: it uses only a basic regular expression match, which can absolutely be defeated by atypical test declarations, and it's unable to fully "split" parameterized tests. ๐Ÿ˜ญ Additionally, it requires that CMake be re-run to discover any newly added, removed or renamed tests (by default that means CMake is re-run when any test source file is changed, but see SKIP_DEPENDENCY). The upside though? It declares tests at CMake time, which somewhat simplifies setting additional properties on tests, and it always works in a cross-compiling environment. ๐Ÿ’…

The options are:

  • TARGET target โ€” Specifies the Google Test executable, which must be a known CMake executable target. CMake will substitute the location of the built executable when running the test.
  • SOURCES src1... โ€” When provided, only the listed files will be scanned for test cases. If this option is not given, the SOURCES property of the specified target will be used to obtain the list of sources.
  • EXTRA_ARGS args... โ€” Any extra arguments to pass on the command line to each test case.
    • Changed in version 3.31: Empty values in args... are preserved, see CMP0178.
  • WORKING_DIRECTORY dir โ€” Specifies the directory in which to run the discovered test cases. If this option is not provided, the current binary directory is used.
  • TEST_PREFIX prefix โ€” Specifies a prefix to be prepended to the name of each discovered test case. This can be useful when the same source files are being used in multiple calls to gtest_add_test() but with different EXTRA_ARGS.
  • TEST_SUFFIX suffix โ€” Similar to TEST_PREFIX except the suffix is appended to the name of every discovered test case. Both TEST_PREFIX and TEST_SUFFIX may be specified.
  • SKIP_DEPENDENCY โ€” Normally, the function creates a dependency which will cause CMake to be re-run if any of the sources being scanned are changed. That's to ensure the list of discovered tests is updated. If this behavior is not desired (as may be the case while you're actually writing the test cases), this option can be used to prevent the dependency from being added.
  • TEST_LIST outVar โ€” The variable named by outVar will be populated in the calling scope with the list of discovered test cases. This lets the caller do things like manipulate test properties of the discovered tests. ๐ŸŽ€
Changed in version 3.31: Empty values in the TEST_LAUNCHER and CROSSCOMPILING_EMULATOR target properties are preserved, see policy CMP0178.

Usage example, bestie, straight from the source:

include(GoogleTest)
add_executable(FooTest FooUnitTest.cxx)
gtest_add_tests(TARGET      FooTest
                TEST_SUFFIX .noArgs
                TEST_LIST   noArgsTests
)
gtest_add_tests(TARGET      FooTest
                EXTRA_ARGS  --someArg someValue
                TEST_SUFFIX .withArgs
                TEST_LIST   withArgsTests
)
set_tests_properties(${noArgsTests}   PROPERTIES TIMEOUT 10)
set_tests_properties(${withArgsTests} PROPERTIES TIMEOUT 20)

For backward compatibility, the following form is also supported:

gtest_add_tests(exe args files...)
  • exe โ€” The path to the test executable or the name of a CMake target.
  • args โ€” A semicolon-separated list of extra arguments to be passed to executable. The entire list must be passed as a single argument. Enclose it in quotes, or pass "" for no arguments. (Yes, "". Not vibes. Actual empty quotes. ๐Ÿ™ˆ)
  • files... โ€” A list of source files to search for tests and test fixtures. Alternatively, use AUTO to specify that exe is the name of a CMake executable target whose sources should be scanned.
include(GoogleTest)
set(FooTestArgs --foo 1 --bar 2)
add_executable(FooTest FooUnitTest.cxx)
gtest_add_tests(FooTest "${FooTestArgs}" AUTO)

๐ŸŒˆ gtest_discover_tests ๐ŸŒˆ

Automatically add tests with CTest by querying the compiled test executable for available tests:

gtest_discover_tests(target
                     [EXTRA_ARGS args...]
                     [WORKING_DIRECTORY dir]
                     [TEST_PREFIX prefix]
                     [TEST_SUFFIX suffix]
                     [TEST_FILTER expr]
                     [NO_PRETTY_TYPES] [NO_PRETTY_VALUES]
                     [PROPERTIES name1 value1...]
                     [TEST_LIST var]
                     [DISCOVERY_TIMEOUT seconds]
                     [XML_OUTPUT_DIR dir]
                     [DISCOVERY_MODE <POST_BUILD|PRE_TEST>]
                     [DISCOVERY_EXTRA_ARGS args...]
)

Added in version 3.10.

gtest_discover_tests() sets up a post-build or pre-test command on the test executable that generates the list of tests by parsing the output from running the test executable with the --gtest_list_tests argument. Compared to the source-parsing approach of gtest_add_tests(), this guarantees you get the full list of tests, including instantiations of parameterized tests. ๐Ÿ‘‘

Since test discovery happens at build or test time, you don't have to re-run CMake when the list of tests changes โ€” iconic, honestly. However (and this is the catch, bestie), it requires that CROSSCOMPILING_EMULATOR is properly set in order to function in a cross-compiling environment.

Also, setting properties on tests is somewhat less convenient, since the tests are not available at CMake time. Additional test properties may be assigned to the set of tests as a whole using the PROPERTIES option. If you need more fine-grained test control, custom content may be provided through an external CTest script using the TEST_INCLUDE_FILES directory property. The set of discovered tests is made accessible to such a script via the <target>_TESTS variable (see the TEST_LIST option below for further discussion and limitations). ๐Ÿฆ‹

The options are:

  • target โ€” Specifies the Google Test executable, which must be a known CMake executable target. CMake will substitute the location of the built executable when running the test.
  • EXTRA_ARGS args... โ€” Any extra arguments to pass on the command line to each test case.
    • Changed in version 3.31: Empty values in args... are preserved, see CMP0178.
  • WORKING_DIRECTORY dir โ€” Specifies the directory in which to run the discovered test cases. If this option is not provided, the current binary directory is used.
  • TEST_PREFIX prefix โ€” Specifies a prefix to be prepended to the name of each discovered test case. This can be useful when the same test executable is being used in multiple calls to gtest_discover_tests() but with different EXTRA_ARGS.
  • TEST_SUFFIX suffix โ€” Similar to TEST_PREFIX except the suffix is appended to the name of every discovered test case. Both TEST_PREFIX and TEST_SUFFIX may be specified.
  • TEST_FILTER expr โ€” Added in version 3.22. Filter expression to pass as a --gtest_filter argument during test discovery. Note that the expression is a wildcard-based format that matches against the original test names as used by gtest. For type- or value-parameterized tests, these names may be different to the potentially pretty-printed test names that ctest uses. ๐Ÿงš
  • NO_PRETTY_TYPES โ€” By default, the type index of type-parameterized tests is replaced by the actual type name in the CTest test name. If this behavior is undesirable (e.g. because the type names are unwieldy), this option will suppress it.
  • NO_PRETTY_VALUES โ€” By default, the value index of value-parameterized tests is replaced by the actual value in the CTest test name. If this behavior is undesirable (e.g. because the value strings are unwieldy), this option will suppress it.
  • PROPERTIES name1 value1... โ€” Specifies additional properties to be set on all tests discovered by this invocation of gtest_discover_tests().
  • TEST_LIST var โ€” so instead of dumping the test list into the default <target>_TESTS, you get it in var. iconic when you're reusing the same test executable across multiple gtest_discover_tests() calls ngl. heads up tho: this variable is only available in CTest. and bestie, listen โ€” due to a limitation of CMake's parsing rules, any test with a square bracket in its name gets omitted from the list stored in this variable ๐Ÿ˜ญ those tests are still defined and executed by ctest as normal, so like, no crisis, just a lil gap.
  • DISCOVERY_TIMEOUT num โ€” โœจ added in version 3.10.3 โœจ this is how long (in seconds) CMake waits for the test to enumerate its available tests. if the test takes longer than that, discovery (and your whole build ๐Ÿซ ) fails. most test executables enumerate super fast, but under some exceptional circumstances a test may need a longer timeout. the default is 5. see also the TIMEOUT option of execute_process().
Note, bestie: in CMake versions 3.10.1 and 3.10.2, this option was called TIMEOUT. that clashed with the TIMEOUT test property, which is one of the common properties that would be set with the PROPERTIES keyword โ€” usually leading to legal but unintended behavior ๐Ÿ’€ so the keyword got changed to DISCOVERY_TIMEOUT in CMake 3.10.3 to fix it. the ambiguous behavior of the TIMEOUT keyword in 3.10.1 and 3.10.2 has not been preserved. periodt.
  • XML_OUTPUT_DIR dir โ€” added in version 3.18. if specified, the parameter gets passed along with --gtest_output=xml: to the test executable. the actual file name is the same as the test target, including prefix and suffix. use this instead of EXTRA_ARGS --gtest_output=xml to avoid race conditions writing the XML result output when you're doing parallel test execution ๐Ÿ”ฅ like, trust, it's giving safer.
  • DISCOVERY_MODE โ€” added in version 3.18. gives you greater control over when gtest_discover_tests() performs test discovery. by default, POST_BUILD sets up a post-build command to do discovery at build time. but in certain scenarios โ€” like cross-compiling โ€” this POST_BUILD behavior is not desirable. PRE_TEST, by contrast, delays test discovery until just prior to test execution. that way discovery happens in the target environment, where the test has a better chance at finding appropriate runtime dependencies ๐Ÿ’…

DISCOVERY_MODE defaults to the value of the CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE variable if it's not passed when calling gtest_discover_tests(). so you get a mechanism for globally selecting a preferred test discovery behavior without having to modify each call site. obsessed actually.

  • DISCOVERY_EXTRA_ARGS args... โ€” added in version 3.31. any extra arguments to pass on the command line for the discovery command. slay.

Added in version 3.29: the TEST_LAUNCHER target property is honored during test discovery and test execution ๐ŸŽ€

Changed in version 3.31: empty values in the TEST_LAUNCHER and CROSSCOMPILING_EMULATOR target properties are preserved, see policy CMP0178.


๐Ÿงš InstallRequiredSystemLibraries ๐Ÿงš

this module searches for compiler-provided system runtime libraries and adds installation rules for them. lowkey a lifesaver on Windows fr fr.

load it in a CMake project with:

include(InstallRequiredSystemLibraries)

some optional variables may be set prior to including this module to adjust behavior:

  • CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS โ€” specify additional runtime libraries that may not be detected. after inclusion, any detected libraries will be appended to this. ๐ŸŒธ
  • CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_SKIP โ€” set to TRUE to skip calling the install(PROGRAMS) command, which lets the includer specify its own install rule, using the value of CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS to get the list of libraries. you're the main character of your own install rules, i respect it.
  • CMAKE_INSTALL_DEBUG_LIBRARIES โ€” set to TRUE to install the debug runtime libraries when available with MSVC tools.
  • CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY โ€” set to TRUE to install only the debug runtime libraries with MSVC tools, even if the release runtime libraries are also available. debug girlies rise ๐Ÿ‘‘
  • CMAKE_INSTALL_UCRT_LIBRARIES โ€” added in version 3.6. set to TRUE to install the Windows Universal CRT libraries for app-local deployment (e.g. to Windows XP). this is meaningful only with MSVC from Visual Studio 2015 or higher.

Added in version 3.9: you may set a CMAKE_WINDOWS_KITS_10_DIR environment variable to an absolute path to tell CMake to look for Windows 10 SDKs in a custom location. the specified directory is expected to contain Redist/ucrt/DLLs/* directories ๐Ÿฆ‹

  • CMAKE_INSTALL_MFC_LIBRARIES โ€” set to TRUE to install the MSVC MFC runtime libraries.
  • CMAKE_INSTALL_OPENMP_LIBRARIES โ€” set to TRUE to install the MSVC OpenMP runtime libraries.
  • CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION โ€” specify the install(PROGRAMS) command DESTINATION option. if not specified, the default is bin on Windows and lib elsewhere.
  • CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS โ€” set to TRUE to disable warnings about required library files that don't exist. (for example, Visual Studio Express editions may not provide the redistributable files ๐Ÿ™ˆ)
  • CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT โ€” added in version 3.3. specify the install(PROGRAMS) command COMPONENT option. if not specified, no such option will be used.

Added in version 3.10: support for installing Intel compiler runtimes. we love to see it โœจ


๐Ÿ’œ ProcessorCount ๐Ÿ’œ

this module provides a command to determine the number of processors/cores. literally the "how many friends can come to the party" module.

load this module in CMake with:

include(ProcessorCount)

Commands

this module provides the following command:

ProcessorCount โ€” determines the number of logical CPU cores available on the machine:

ProcessorCount(<variable>)

this command sets a variable named <variable> to the number of logical CPU cores available on the machine, if the information can be determined. if successful, the variable is guaranteed to be set to a positive integer (>=1). if the processor count can't be determined, it's set to 0 ๐Ÿ’€

currently, this functionality is implemented for AIX, Cygwin, FreeBSD, Haiku, HPUX, Linux, macOS, QNX, Sun and Windows. around the world, bestie ๐ŸŒ

this command provides an approximation of the number of compute cores available on the current machine, making it useful for parallel building and testing. it's meant to help utilize as much of the machine as seems reasonable, though users should consider other workloads running on the machine before using its full capacity for parallel tasks. like, don't hog the whole group chat bandwidth, yk? ๐Ÿซถ

Changed in version 3.15: on Linux, returns the container CPU count instead of the host CPU count.

Note: this module relies on system-dependent commands to determine the number of processors, which may not always provide accurate information in certain environments. a more generally accurate logical CPU count can also be obtained with cmake_host_system_information():
cmake_host_system_information(RESULT n QUERY NUMBER_OF_LOGICAL_CORES)

Examples

in the following example this module is used in a ctest -S dashboard script to determine the number of cores to use for a parallel CTest Build Step:

include(ProcessorCount)
ProcessorCount(n)
if(NOT n EQUAL 0)
  set(CTEST_BUILD_FLAGS -j${n})
  set(ctest_test_args ${ctest_test_args} PARALLEL_LEVEL ${n})
endif()

ate, no notes ๐Ÿ’…


๐ŸŒˆ SelectLibraryConfigurations ๐ŸŒˆ

this module provides a command to automatically set library variables when a package is available with multiple Build Configurations. it's intended for use in Find Modules implementing find_package(<PackageName>) calls. highkey niche but so useful.

load this module in a CMake find module with:

FindFoo.cmake

include(SelectLibraryConfigurations)

supported build configurations are Release and Debug, since these are the most common ones in such packages ๐ŸŒธ

Note: this module has been available since early versions of CMake, back when the <PackageName>_LIBRARIES result variable was used for linking found packages. when writing standard find modules, Imported Targets should be preferred. in addition to or as an alternative to this module, imported targets provide finer control over linking through the IMPORTED_CONFIGURATIONS property. glow-up behavior, honestly โœจ

Commands

this module provides the following command:

select_library_configurations โ€” sets and adjusts library variables based on debug and release build configurations:

select_library_configurations(<basename>)

this command is a helper for setting the <basename>_LIBRARY and <basename>_LIBRARIES result variables when a library might be provided with multiple build configurations.

the argument is:

  • <basename> โ€” the base name of the library, used as a prefix for variable names. this is the name of the package as used in the Find<PackageName>.cmake module filename, or the component name, when the find module provides them. ๐ŸŽ€

prior to calling this command, the following cache variables should be set in the find module (for example, by the find_library() command):

  • <basename>_LIBRARY_RELEASE โ€” a cache variable holding the full path to the Release build of the library ๐Ÿ’– if it's not set already, or nothing turns up, this command sets it to <basename>_LIBRARY_RELEASE-NOTFOUND (sad girl hours).
  • <basename>_LIBRARY_DEBUG โ€” same vibe but for the Debug build ๐Ÿ› it stores the full path, and if it's unset or unfound it becomes <basename>_LIBRARY_DEBUG-NOTFOUND.

Then, bestie, the command sets these local result variables:

  • <basename>_LIBRARY โ€” a result variable that gets the value of your <basename>_LIBRARY_RELEASE if that was found; otherwise it takes <basename>_LIBRARY_DEBUG if that was found. Both found? Release wins, no debate, release takes precedence ๐Ÿ‘‘ neither found? it's set to <basename>_LIBRARY-NOTFOUND.

Okay so this next bit is important โ€” if the CMake Generator (cmake-generators(7)) your build is using supports build configurations, then this variable becomes a list of the found libraries, each one prepended with the optimized or debug keyword that says which library should get linked for that given configuration. Those keywords are the exact ones target_link_libraries() understands. But if no build configuration has been set, or your generator doesn't do build configurations at all, then the value won't contain those keywords. Simple as that โœจ

  • <basename>_LIBRARIES โ€” a result variable set to the same value as <basename>_LIBRARY. Literally twins ๐Ÿซถ
Note: you should call the select_library_configurations() command before handling the standard find module arguments with find_package_handle_standard_args(), so that the <PackageName>_FOUND result variable actually ends up correctly set based on <basename>_LIBRARY or the other related variables. Order matters, periodt ๐Ÿ’…

Examples

Setting library variables based on the build configuration inside a find module file:

FindFoo.cmake

# Find release and debug build of the library
find_library(Foo_LIBRARY_RELEASE ...)
find_library(Foo_LIBRARY_DEBUG ...)

# Set Foo_LIBRARY and Foo_LIBRARIES result variables
include(SelectLibraryConfigurations)
select_library_configurations(Foo)

# Set Foo_FOUND variable and print result message.
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
  Foo
  REQUIRED_VARS Foo_LIBRARY ...
)

And when your find module provides components with multiple build configurations:

FindFoo.cmake

include(SelectLibraryConfigurations)
foreach(component IN LISTS Foo_FIND_COMPONENTS)
  # ...
  select_library_configurations(Foo_${component})
  # ...
endforeach()

A project can then use this find module like this:

CMakeLists.txt

find_package(Foo)
target_link_libraries(project_target PRIVATE ${Foo_LIBRARIES})
# ...

๐Ÿงš TestForANSIForScope

This module checks whether the CXX compiler restricts the scope of variables declared in a for-init-statement to the loop body ๐Ÿ‘€

Load this module in a CMake project with:

include(TestForANSIForScope)

So back in early C++ (pre-C++98), variables declared in for(<init-statement> ...) could stay accessible outside the loop after its body finished (for() { <body> }). Messy, I know ๐Ÿ˜ญ

This module defines the following cache variable:

  • CMAKE_NO_ANSI_FOR_SCOPE โ€” a cache variable containing the result of the check. It'll be 0 if the for-init-statement has restricted scope (C++ 98 and newer), and 1 if it doesn't (ANSI C++).
Note: as of the C++ 98 standard, variables declared in a for-init-statement are restricted to the loop body, which makes this whole behavior obsolete. History lesson over ๐ŸŽ€

Examples

Including this module will check the for() loop scope behavior and define the CMAKE_NO_ANSI_FOR_SCOPE cache variable:

CMakeLists.txt

include(TestForANSIForScope)
file(
  CONFIGURE
  OUTPUT config.h
  CONTENT "#cmakedefine CMAKE_NO_ANSI_FOR_SCOPE"
)

which can be then used in a C++ program:

example.cxx

#include "config.h"

#ifdef CMAKE_NO_ANSI_FOR_SCOPE
#  define for if(false) {} else for
#endif

See Also

  • The CMakeBackwardCompatibilityCXX module.

๐ŸŒˆ TestForANSIStreamHeaders

This module checks whether the CXX compiler supports standard library headers without the .h extension (like <iostream>), which is honestly such a flex โœจ

Load this module in a CMake project with:

include(TestForANSIStreamHeaders)

Early versions of C++ (pre-C++98) didn't support including standard headers without extensions. Rough times ๐Ÿ’€

This module defines the following cache variable:

  • CMAKE_NO_ANSI_STREAM_HEADERS โ€” a cache variable containing the result of the check. Set to 0 if the standard headers can be included without the .h extension (C++ 98 and newer), and 1 if .h is required (ANSI C++).
Note: the C++ standard headers without extensions got formally introduced in the C++ 98 standard, making this issue obsolete. Girl, it's vintage ๐ŸŽ€

Examples

Including this module will check how the C++ standard headers can be included and define the CMAKE_NO_ANSI_STREAM_HEADERS cache variable:

CMakeLists.txt

include(TestForANSIStreamHeaders)
file(
  CONFIGURE
  OUTPUT config.h
  CONTENT "#cmakedefine CMAKE_NO_ANSI_STREAM_HEADERS"
)

A C++ program can then include the available header conditionally:

example.cxx

#include "config.h"

#ifdef CMAKE_NO_ANSI_STREAM_HEADERS
#  include <iostream.h>
#else
#  include <iostream>
#endif

int main() { ... }

See Also

  • The CMakeBackwardCompatibilityCXX module.

๐Ÿฆ‹ TestForSSTREAM

This module checks whether the C++ standard header <sstream> exists and actually functions correctly. Not just exists โ€” works. We verify, we don't assume ๐Ÿ’…

Load this module in a CMake project with:

include(TestForSSTREAM)

In early versions of C++ (pre-C++98), the <sstream> header was not formally standardized and may not have been available at all ๐Ÿ˜ญ

This module defines the following cache variables:

  • CMAKE_NO_ANSI_STRING_STREAM โ€” a cache variable indicating whether the <sstream> header is available. 0 if <sstream> is available (C++ 98 and newer), 1 if <sstream> is missing (ANSI C++).
  • CMAKE_HAS_ANSI_STRING_STREAM โ€” a cache variable that is the opposite of CMAKE_NO_ANSI_STRING_STREAM (true if <sstream> is available and false if <sstream> is missing). Mirror image, bestie ๐Ÿชž
Note: the <sstream> header was formally introduced in the C++ 98 standard, making this check obsolete for modern compilers. Iconic but retired ๐Ÿ‘‘

Examples

Including this module will check for <sstream> support and define the CMAKE_NO_ANSI_STRING_STREAM cache variable:

CMakeLists.txt

include(TestForSSTREAM)
file(
  CONFIGURE
  OUTPUT config.h
  CONTENT "#cmakedefine CMAKE_NO_ANSI_STRING_STREAM"
)

Then it can be used in a C++ program:

example.cxx

#include "config.h"

#ifndef CMAKE_NO_ANSI_STRING_STREAM
#  include <sstream>
#endif

int main() { ... }

See Also

  • The CMakeBackwardCompatibilityCXX module.

๐Ÿซถ TestForSTDNamespace

This module checks whether the CXX compiler supports the std namespace for the C++ Standard Library ๐ŸŒธ

Load this module in a CMake project with:

include(TestForSTDNamespace)

Early versions of C++ (pre-C++98) did not have a requirement for a dedicated namespace for C++ Standard Template Library (STL) components (e.g. list, etc.) and other parts of the C++ Standard Library (such as I/O streams cout, endl, etc), so they were just available globally. Everything everywhere all at once, no namespace ๐Ÿ˜ญ

This module defines the following cache variable:

  • CMAKE_NO_STD_NAMESPACE โ€” a cache variable containing the result of the check. Set to 0 if the std namespace is supported (C++ 98 and newer), and 1 if not (ANSI C++).
Note: the std namespace got formally introduced in the C++ 98 standard, making this issue obsolete. Ancient history, still slaps ๐ŸŽ€

Examples

Including this module will check for the std namespace support and define the CMAKE_NO_STD_NAMESPACE cache variable:

CMakeLists.txt

include(TestForSTDNamespace)
file(
  CONFIGURE
  OUTPUT config.h
  CONTENT "#cmakedefine CMAKE_NO_STD_NAMESPACE"
)

which can be then used in a C++ program to define the missing namespace:

example.cxx

#include "config.h"

#ifdef CMAKE_NO_STD_NAMESPACE
#  define std
#endif

See Also

  • The CMakeBackwardCompatibilityCXX module.

๐Ÿงš UseEcos

This module defines variables and provides commands required to build an eCos application ๐ŸŒฑ load it in a CMake project with:

include(UseEcos)

Commands

This module provides the following commands:

Building an eCos Application

ecos_add_include_directories

Adds the eCos include directories for the current CMakeLists.txt file:

ecos_add_include_directories()

ecos_adjust_directory

Adjusts the paths of given source files:

ecos_adjust_directory(<var> <sources>...)

This command modifies the paths of the source files <sources>... to make them suitable for use with ecos_add_executable(), and stores them in the variable <var> ๐Ÿ”ฅ

  • <var> โ€” result variable name holding a new list of source files with adjusted paths.
  • <sources>... โ€” a list of relative or absolute source files to adjust their paths.

Use this command when the actual sources are located one level upwards. A ../ has to be prepended in front of every source file that is given as a relative path. Yes, you literally have to add the ../ yourself, it's giving manual labour ๐Ÿ™ˆ

ecos_add_executable

Creates an eCos application executable:

ecos_add_executable(<name> <sources>...)
  • <name> โ€” the name of the executable.
  • <sources>... โ€” a list of all source files, where the path has been adjusted beforehand by calling the ecos_adjust_directory().

Oh and also โ€” this command sets the ECOS_DEFINITIONS local variable, which holds some common compile definitions. Free little bonus variable, we love that for us ๐Ÿ’…

๐Ÿงฐ Selecting the Toolchain ๐Ÿงฐ

These three besties each flip on a different toolchain for the directory where you call them. Pick your fighter:

ecos_use_arm_elf_tools โ€” enables the ARM ELF toolchain for the directory where it's called:

ecos_use_arm_elf_tools()

Use this one when you're compiling for the xscale processor. That's the whole vibe ๐Ÿซถ

ecos_use_i386_elf_tools โ€” enables the i386 ELF toolchain for the directory where it's called:

ecos_use_i386_elf_tools()

ecos_use_ppc_eabi_tools โ€” enables the PowerPC toolchain for the directory where it's called:

ecos_use_ppc_eabi_tools()

๐Ÿท๏ธ Variables ๐Ÿท๏ธ

This module also defines the following variables, and yes they're iconic:

  • ECOSCONFIG_EXECUTABLE โ€” a cache variable holding a path to the ecosconfig executable (that's the eCos configuration program, for the uninitiated ๐Ÿงš).
  • ECOS_CONFIG_FILE โ€” a local variable that defaults to ecos.ecc. If your eCos configuration file has a different name, adjust this variable before calling the ecos_add_executable().

๐ŸŒฐ Examples ๐ŸŒฐ

Okay so here's the glow-up demo: defining an eCos executable target in a project that follows the common eCos convention of listing source files in a ProjectSources.txt file, located one directory above the current CMakeLists.txt:

CMakeLists.txt

include(UseEcos)

# Add the eCos include directories.
ecos_add_include_directories()

# Include the file with the eCos sources list. This file, for example, defines
# a list of eCos sources:
#   set(sources file_1.cxx file_2.cxx file_3.cxx)
include(../ProjectSources.txt)

# When using such directory structure, relative source paths must be adjusted:
ecos_adjust_directory(adjusted_sources ${sources})

# Create eCos executable.
ecos_add_executable(ecos_app ${adjusted_sources})

โ˜• UseJava โ˜•

This file provides support for Java. It's assumed that FindJava has already been loaded โ€” like, that's a prerequisite, bestie, don't skip it ๐Ÿ™ˆ. See FindJava for info on how to load Java into your CMake project.

Load this module in a CMake project with:

include(UseJava)

๐Ÿ“‹ Synopsis ๐Ÿ“‹

Creating and Installing JARS

add_jar (<target_name> [SOURCES] <source1> [<source2>...] ...)
install_jar (<target_name> DESTINATION <destination> [COMPONENT <component>])
install_jni_symlink (<target_name> DESTINATION <destination> [COMPONENT <component>])

Header Generation

create_javah ((TARGET <target> | GENERATED_FILES <VAR>) CLASSES <class>... ...)

Exporting JAR Targets

install_jar_exports (TARGETS <jars>... FILE <filename> DESTINATION <destination> ...)
export_jars (TARGETS <jars>... [NAMESPACE <namespace>] FILE <filename>)

Finding JARs

find_jar (<VAR> NAMES <name1> [<name2>...] [PATHS <path1> [<path2>... ENV <var>]] ...)

Creating Java Documentation

create_javadoc (<VAR> (PACKAGES <pkg1> [<pkg2>...] | FILES <file1> [<file2>...]) ...)

๐Ÿซ™ Creating And Installing JARs ๐Ÿซ™

add_jar

Creates a jar file containing java objects and, optionally, resources. Here's the full signature, no cap:

add_jar(<target_name>
        [SOURCES] <source1> [<source2>...] [<resource1>...]
        [RESOURCES NAMESPACE <ns1> <resource1>... [NAMESPACE <nsX> <resourceX>...]... ]
        [INCLUDE_JARS <jar1> [<jar2>...]]
        [INCLUDE_MODULES <jar1> [<jar2>...]]
        [ENTRY_POINT <entry>]
        [VERSION <version>]
        [MANIFEST <manifest>]
        [OUTPUT_NAME <name>]
        [OUTPUT_DIR <dir>]
        [GENERATE_NATIVE_HEADERS <target>
                                 [DESTINATION (<dir>|INSTALL <dir> [BUILD <dir>])]]
        )

This command creates a <target_name>.jar. It compiles the <source> files you give it and adds the <resource> files you give it to the jar file. Source files can be java files or listing files (prefixed by @). If you only give it resource files, then it just makes a jar file and that's it, slay โœจ

  • SOURCES โ€” compiles the specified source files and adds the result in the jar file.

Added in version 3.4: support for response files, prefixed by @.

  • RESOURCES โ€” added in version 3.21.

Adds the named <resource> files to the jar by stripping the source file path and placing the file beneath <ns> within the jar. Like so:

RESOURCES NAMESPACE "/com/my/namespace" "a/path/to/resource.txt"

that results in a resource accessible via /com/my/namespace/resource.txt within the jar. Cute, right? ๐ŸŽ€

Resources may be added without adjusting the namespace by adding them to the list of SOURCES (the original behavior) โ€” in that case, resource paths must be relative to CMAKE_CURRENT_SOURCE_DIR. Adding resources without using the RESOURCES parameter in out of source builds will almost certainly result in confusion. Like, chaos, bestie ๐Ÿ˜ญ

Note: adding resources via the SOURCES parameter relies upon a hard-coded list of file extensions which are tested to determine whether they compile (e.g. File.java). SOURCES files which match the extensions are compiled. Files which do not match are treated as resources. To include uncompiled resources matching those file extensions, use the RESOURCES parameter.
  • INCLUDE_JARS โ€” the list of jars is added to the classpath when compiling the java sources, and also to the dependencies of the target. INCLUDE_JARS also accepts other target names created by add_jar(). For backwards compatibility, jar files listed as sources are ignored (as they have been since the very first version of this module, vintage icon behavior ๐Ÿ‘‘).
  • INCLUDE_MODULES โ€” added in version 4.3.

The list of jars is added to the module path when building the java sources, and also to the dependencies of the target. INCLUDE_MODULES also accepts other target names created by add_jar().

  • ENTRY_POINT โ€” defines an entry point in the jar file.
  • VERSION โ€” adds a version to the target output name.

The following example will create a jar file with the name shibboleet-1.2.0.jar and will create a symlink shibboleet.jar pointing to the jar with the version information:

add_jar(shibboleet shibbotleet.java VERSION 1.2.0)
  • MANIFEST โ€” defines a custom manifest for the jar.
  • OUTPUT_NAME โ€” specify a different output name for the target.
  • OUTPUT_DIR โ€” sets the directory where the jar file will be generated. If not specified, CMAKE_CURRENT_BINARY_DIR is used as the output directory.
  • GENERATE_NATIVE_HEADERS โ€” added in version 3.11.

Generates native header files for methods declared as native. These files provide the connective glue that allows your Java and C code to interact ๐Ÿงš. An INTERFACE target will be created for easy usage of the generated files. The sub-option DESTINATION can be used to specify the output directory for generated header files.

This option requires, at least, version 1.8 of the JDK.

For optimum usage of this option, it's recommended to include module JNI before any call to add_jar(). The produced target for native headers can then be used to compile C/C++ sources with the target_link_libraries() command:

find_package(JNI)
add_jar(foo foo.java GENERATE_NATIVE_HEADERS foo-native)
add_library(bar bar.cpp)
target_link_libraries(bar PRIVATE foo-native)

Added in version 3.20: the DESTINATION sub-option now supports the possibility to specify different output directories for BUILD and INSTALL steps. If the BUILD directory isn't specified, a default directory will be used.

To export the interface target generated by the GENERATE_NATIVE_HEADERS option, the sub-option INSTALL of DESTINATION is required:

add_jar(foo foo.java GENERATE_NATIVE_HEADERS foo-native
                     DESTINATION INSTALL include)
install(TARGETS foo-native EXPORT native)
install(DIRECTORY "$<TARGET_PROPERTY:foo-native,NATIVE_HEADERS_DIRECTORY>/"
        DESTINATION include)
install(EXPORT native DESTINATION /to/export NAMESPACE foo)

Some variables can be set to customize the behavior of add_jar() as well as the java compiler โ€” lowkey handy:

  • CMAKE_JAVA_COMPILE_FLAGS โ€” specify additional flags to the java compiler.
  • CMAKE_JAVA_INCLUDE_PATH โ€” specify additional paths to the class path.
  • CMAKE_JNI_TARGET โ€” if the target is a JNI library, set this boolean variable to TRUE to enable creation of a JNI symbolic link (see also install_jni_symlink()).
  • CMAKE_JAR_CLASSES_PREFIX โ€” if multiple jars should be produced from the same java source filetree, set/reset CMAKE_JAR_CLASSES_PREFIX prior to calling add_jar() to prevent the accumulation of duplicate class files in subsequent jars:
set(CMAKE_JAR_CLASSES_PREFIX com/redhat/foo)
add_jar(foo foo.java)

set(CMAKE_JAR_CLASSES_PREFIX com/redhat/bar)
add_jar(bar bar.java)

The add_jar() function sets the following target properties on <target_name> โ€” main character properties, honestly ๐Ÿ’…

  • INSTALL_FILES โ€” the files which should be installed. This is used by install_jar().
  • JNI_SYMLINK โ€” the JNI symlink which should be installed. This is used by install_jni_symlink().
  • JAR_FILE โ€” the location of the jar file so that you can include it.
  • CLASSDIR โ€” the directory where the class files hang out ๐Ÿ—‚๏ธ. Like, if you wanna use them with javah, this is the spot.
  • NATIVE_HEADERS_DIRECTORY โ€” added in version 3.20. The directory where the native headers get generated โœจ. It's defined when the GENERATE_NATIVE_HEADERS option is specified.

install_jar ๐Ÿ’…

This one installs the jar file to whatever destination you point at:

install_jar(<target_name> <destination>)
install_jar(<target_name> DESTINATION <destination> [COMPONENT <component>])

So install_jar drops the <target_name> file into the given <destination> ๐Ÿ“ฆ. Key thing, bestie: it has to be called in the same scope as add_jar() or it will fail โ€” no cap, it just won't work ๐Ÿ˜ญ.

Added in version 3.4: that second signature with the DESTINATION and COMPONENT options.

  • DESTINATION โ€” specify the directory on disk to which a file will be installed.
  • COMPONENT โ€” specify an installation component name with which the install rule is associated, like "runtime" or "development".

The install_jar() command sets the following target properties on <target_name>:

  • INSTALL_DESTINATION โ€” holds the <destination> as described above, and it's what install_jar_exports() reads. ๐Ÿซถ

Installs JNI symlinks for a target generated by add_jar():

install_jni_symlink(<target_name> <destination>)
install_jni_symlink(<target_name> DESTINATION <destination> [COMPONENT <component>])

This command installs the <target_name> JNI symlinks to the given <destination> ๐Ÿ”—. Same energy as before: call it in the same scope as add_jar() or it will fail ๐Ÿ™ˆ.

Added in version 3.4: the second signature with the DESTINATION and COMPONENT options.

  • DESTINATION โ€” specify the directory on disk to which a file will be installed.
  • COMPONENT โ€” specify an installation component name with which the install rule is associated, such as "runtime" or "development".

Utilize the following commands to create a JNI symbolic link:

set(CMAKE_JNI_TARGET TRUE)
add_jar(shibboleet shibbotleet.java VERSION 1.2.0)
install_jar(shibboleet ${LIB_INSTALL_DIR}/shibboleet)
install_jni_symlink(shibboleet ${JAVA_LIB_INSTALL_DIR})

๐Ÿฆ‹ Header Generation ๐Ÿฆ‹

create_javah

Added in version 3.4.

Generates C header files for java classes ๐ŸŽ€:

create_javah(TARGET <target> | GENERATED_FILES <VAR>
             CLASSES <class>...
             [CLASSPATH <classpath>...]
             [DEPENDS <depend>...]
             [OUTPUT_NAME <path>|OUTPUT_DIR <path>]
             )
โš ๏ธ Deprecated since version 3.11: this command will no longer be supported starting with version 10 of the JDK, because they suppressed the javah tool (JEP 313). The add_jar(GENERATE_NATIVE_HEADERS) command should be used instead. So like... it's giving "on its way out", bestie ๐Ÿ’€ โ€” use the replacement.

Create C header files from java classes. These files provide the connective glue that allow your Java and C code to interact โœจ.

There are two main signatures for create_javah(). The first one returns generated files through the variable specified by the GENERATED_FILES option. For example:

create_javah(GENERATED_FILES files_headers
  CLASSES org.cmake.HelloWorld
  CLASSPATH hello.jar
)

The second signature for create_javah() creates a target which encapsulates header files generation. E.g.

create_javah(TARGET target_headers
  CLASSES org.cmake.HelloWorld
  CLASSPATH hello.jar
)

Both signatures share the same options ๐Ÿ‘‘.

  • CLASSES โ€” specifies Java classes used to generate headers.
  • CLASSPATH โ€” specifies various paths to look up classes. Here .class files, jar files or targets created by command add_jar can be used.
  • DEPENDS โ€” targets on which the javah target depends.
  • OUTPUT_NAME โ€” concatenates the resulting header files for all the classes listed by option CLASSES into <path>. Same behavior as option -o of the javah tool.
  • OUTPUT_DIR โ€” sets the directory where the header files will be generated. Same behavior as option -d of the javah tool. If not specified, CMAKE_CURRENT_BINARY_DIR is used as the output directory ๐ŸŒธ.

๐ŸŒˆ Exporting JAR Targets ๐ŸŒˆ

install_jar_exports

Added in version 3.7.

Installs a target export file:

install_jar_exports(TARGETS <jars>...
                    [NAMESPACE <namespace>]
                    FILE <filename>
                    DESTINATION <destination> [COMPONENT <component>])

This command installs a target export file <filename> for the named jar targets to the given <destination> directory ๐Ÿ’–. Its function is similar to that of install(EXPORT).

  • TARGETS โ€” list of targets created by add_jar() command.
  • NAMESPACE โ€” added in version 3.9. The <namespace> value will be prepend to the target names as they are written to the import file โœจ.
  • FILE โ€” specify name of the export file.
  • DESTINATION โ€” specify the directory on disk to which a file will be installed.
  • COMPONENT โ€” specify an installation component name with which the install rule is associated, such as "runtime" or "development".

export_jars

Added in version 3.7.

Writes a target export file:

export_jars(TARGETS <jars>...
            [NAMESPACE <namespace>]
            FILE <filename>)

This command writes a target export file <filename> for the named <jars> targets ๐Ÿ“. Its function is similar to that of export().

  • TARGETS โ€” list of targets created by add_jar() command.
  • NAMESPACE โ€” added in version 3.9. The <namespace> value will be prepend to the target names as they are written to the import file ๐Ÿ‘‘
  • FILE โ€” specify name of the export file.

๐Ÿ”ฅ Finding JARs ๐Ÿ”ฅ

find_jar

Finds the specified jar file:

find_jar(<VAR>
         <name> | NAMES <name1> [<name2>...]
         [PATHS <path1> [<path2>... ENV <var>]]
         [VERSIONS <version1> [<version2>]]
         [DOC "cache documentation string"]
        )

This command is used to find a full path to the named jar ๐Ÿ”. A cache entry named by <VAR> is created to store the result of this command. If the full path to a jar is found, the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND, and the search will be attempted again next time find_jar() is invoked with the same variable. Fr fr, that's the whole loop ๐Ÿ˜Œ.

  • NAMES โ€” specify one or more possible names for the jar file.
  • PATHS โ€” specify directories to search in addition to the default locations. The ENV var sub-option reads paths from a system environment variable.
  • VERSIONS โ€” specify jar versions.
  • DOC โ€” specify the documentation string for the <VAR> cache entry.

๐ŸŽ€ Creating Java Documentation ๐ŸŽ€

create_javadoc

Creates java documentation based on files and packages ๐Ÿ“š:

create_javadoc(<VAR>
               (PACKAGES <pkg1> [<pkg2>...] | FILES <file1> [<file2>...])
               [SOURCEPATH <sourcepath>]
               [CLASSPATH <classpath>]
               [INSTALLPATH <install path>]
               [DOCTITLE <the documentation title>]
               [WINDOWTITLE <the title of the document>]
               [AUTHOR (TRUE|FALSE)]
               [USE (TRUE|FALSE)]
               [VERSION (TRUE|FALSE)]
               )

The create_javadoc() command can be used to create java documentation ๐Ÿ’…. There are two main signatures for create_javadoc().

The first signature works with package names on a path with source files:

create_javadoc(my_example_doc
               PACKAGES com.example.foo com.example.bar
               SOURCEPATH "${CMAKE_CURRENT_SOURCE_DIR}"
               CLASSPATH ${CMAKE_JAVA_INCLUDE_PATH}
               WINDOWTITLE "My example"
               DOCTITLE "<h1>My example</h1>"
               AUTHOR TRUE
               USE TRUE
               VERSION TRUE
              )

The second signature for create_javadoc() works on a given list of files:

create_javadoc(my_example_doc
               FILES java/A.java java/B.java
               CLASSPATH ${CMAKE_JAVA_INCLUDE_PATH}
               WINDOWTITLE "My example"
               DOCTITLE "<h1>My example</h1>"
               AUTHOR TRUE
               USE TRUE
               VERSION TRUE
              )

Both signatures share most of the options. For more details please read the javadoc manpage ๐Ÿซถ.

  • PACKAGES โ€” specify java packages.
  • FILES โ€” specify java source files. If relative paths are specified, they are relative to CMAKE_CURRENT_SOURCE_DIR.
  • SOURCEPATH โ€” specify the directory where to look for packages. By default, the CMAKE_CURRENT_SOURCE_DIR directory is used.
  • CLASSPATH โ€” specify where to find user class files. Same behavior as option -classpath of the javadoc tool.
  • INSTALLPATH โ€” tells CMake where to drop the java docs ๐Ÿ’–. If you set it, everything lands in ${CMAKE_INSTALL_PREFIX}/share/javadoc/<VAR>.
  • DOCTITLE โ€” the title that goes near the top of the overview summary file โœจ. Behaves exactly like the -doctitle option of the javadoc tool.
  • WINDOWTITLE โ€” the title that gets placed in the HTML <title> tag ๐ŸŽ€. Same behavior as the -windowtitle option of the javadoc tool.
  • AUTHOR โ€” when it's TRUE, the @author text gets included in the generated docs ๐Ÿซถ. Same behavior as the -author option of the javadoc tool.
  • USE โ€” when it's TRUE, it creates class and package usage pages ๐Ÿ‘‘ โ€” literally one Use page for each documented class and package. Same behavior as the -use option of the javadoc tool.
  • VERSION โ€” when it's TRUE, the version text is included in the generated docs โญ. Same behavior as the -version option of the javadoc tool.

๐ŸŒธ UseSWIG ๐ŸŒธ

Okay so this module is the SWIG support package ๐Ÿฆ‹. It assumes the FindSWIG module has already been loaded โ€” like, that's a prerequisite bestie, no cap.

Load it into your CMake project with:

include(UseSWIG)

โœจ CMake Commands โœจ

Here's the command this module hands you for SWIG work ๐Ÿ’…:

swig_add_library

Added in version 3.8.

This defines a swig module with the name and language you give it ๐ŸŒˆ:

swig_add_library(<name>
                 [TYPE <SHARED|MODULE|STATIC|USE_BUILD_SHARED_LIBS>]
                 LANGUAGE <language>
                 [NO_PROXY]
                 [DEBUG_POSTFIX <postfix>]
                 [OUTPUT_DIR <directory>]
                 [OUTFILE_DIR <directory>]
                 SOURCES <file>...
                )

Targets made with swig_add_library have the exact same capabilities as targets made with add_library() ๐Ÿ”ฅ โ€” so you can totally use them with any command that expects a target (e.g. target_link_libraries()). Iconic behavior, honestly.

Changed in version 3.13: this command creates a target with the specified <name> when policy CMP0078 is set to NEW ๐Ÿ’œ. Otherwise the legacy behavior picks a different target name and stashes it in the SWIG_MODULE_<name>_REAL_NAME variable.

Changed in version 3.15: an alternate library name (set with the OUTPUT_NAME property, for example) gets passed on to Python and CSharp wrapper libraries ๐Ÿ.

Changed in version 3.21: the generated library uses standard naming conventions for the CSharp language when policy CMP0122 is set to NEW โœจ. Otherwise it's the legacy behavior, periodt.

Heads up bestie โš ๏ธ: for multi-config generators, this module does not support configuration-specific files generated by SWIG. All build configurations have to result in the same generated source file. Like, all of them. No exceptions ๐Ÿ˜ญ.
Also for Makefile Generators: if, for some sources, the USE_SWIG_DEPENDENCIES property is FALSE, then swig_add_library does not track file dependencies โ€” so you're required to depend on the <name>_swig_compilation custom target for any targets that need the swig-generated files to exist ๐Ÿ’€. Other generators may depend on the source files that SWIG would generate.
  • TYPE โ€” SHARED, MODULE and STATIC mean exactly the same thing as they do for the add_library() command ๐Ÿซถ. If USE_BUILD_SHARED_LIBS is specified, the library type becomes STATIC or SHARED based on whether the current value of the BUILD_SHARED_LIBS variable is ON. And if you specify no type at all? MODULE gets used. Defaults, slay.
  • LANGUAGE โ€” specify the target language ๐ŸŒ.

Added in version 3.1: Go and Lua language support.

Added in version 3.2: R language support.

Added in version 3.18: Fortran language support.

  • NO_PROXY โ€” Added in version 3.12. Prevents the generation of the wrapper layer (that's the swig -noproxy option) ๐Ÿ™ˆ.
  • DEBUG_POSTFIX โ€” Added in version 4.2. Manages the DEBUG_POSTFIX target property ๐Ÿ’…. Currently it's only meaningful for the python language. If the DEBUG_CONFIGURATIONS global property is defined, it defines the <CONFIG>_POSTFIX target property for each debug configuration.
  • OUTPUT_DIR โ€” Added in version 3.12. Specifies where to write the language-specific files (the swig -outdir option) ๐ŸŽ€. If you don't give it, the CMAKE_SWIG_OUTDIR variable gets used. And if neither is specified, the default depends on the value of the UseSWIG_MODULE_VERSION variable, like this:
    • If UseSWIG_MODULE_VERSION is 1 or is undefined, output is written to the CMAKE_CURRENT_BINARY_DIR directory.
    • If UseSWIG_MODULE_VERSION is 2, a dedicated directory gets used ๐Ÿฆ‹. You can grab the path of this directory from the SWIG_SUPPORT_FILES_DIRECTORY target property.
  • OUTFILE_DIR โ€” Added in version 3.12. Specifies an output directory name where the generated source file will be placed (the swig -o option) ๐ŸŒŸ. If it's not specified, the SWIG_OUTFILE_DIR variable is used. If neither is specified, OUTPUT_DIR or CMAKE_SWIG_OUTDIR is used instead.
  • SOURCES โ€” the list of sources for the library ๐Ÿ“š. Files with the .i extension get identified as sources for the SWIG tool. Other files are handled in the standard way.

Added in version 3.14: this behavior can be overridden by specifying the SWIG_SOURCE_FILE_EXTENSIONS variable.

Big important note bestie ๐Ÿšจ: if UseSWIG_MODULE_VERSION is set to 2, it is strongly recommended to use a dedicated directory unique to the target whenever either the OUTPUT_DIR option or the CMAKE_SWIG_OUTDIR variable are specified. Why? Because the output directory contents get erased as part of the target build ๐Ÿ˜ญ โ€” so to prevent interference between targets or losing other important files, each target should have its own dedicated output directory. Protect your files, periodt.

๐Ÿฆ‹ Properties on Source Files ๐Ÿฆ‹

Source file properties on module files must be set before the invocation of the swig_add_library command โ€” that's how you specify special SWIG behavior and make sure the generated files receive the required settings ๐Ÿ’–.

  • CPLUSPLUS โ€” calls SWIG in c++ mode ๐Ÿ”ฅ. For example:
set_property(SOURCE mymod.i PROPERTY CPLUSPLUS ON)
swig_add_library(mymod LANGUAGE python SOURCES mymod.i)
  • SWIG_FLAGS โ€” Deprecated since version 3.12: replaced with the fine-grained properties that follow ๐Ÿ™ˆ. Passes custom flags to the SWIG executable.
  • INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_OPTIONS โ€” Added in version 3.12. Adds custom flags to the SWIG compiler and has the same semantics as the INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_OPTIONS properties โœจ.
  • USE_TARGET_INCLUDE_DIRECTORIES โ€” Added in version 3.13. If set to TRUE, the contents of the target property INCLUDE_DIRECTORIES get forwarded to the SWIG compiler ๐Ÿซถ. If set to FALSE, the target property INCLUDE_DIRECTORIES gets ignored. If it's not set, the target property SWIG_USE_TARGET_INCLUDE_DIRECTORIES gets considered.
  • GENERATED_INCLUDE_DIRECTORIES, GENERATED_COMPILE_DEFINITIONS and GENERATED_COMPILE_OPTIONS โ€” Added in version 3.12. Adds custom flags to the C/C++ generated source ๐ŸŒˆ. They fill, respectively, the INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_OPTIONS properties of the generated C/C++ file.
  • DEPENDS โ€” Added in version 3.12. Specifies additional dependencies for the source file ๐Ÿ’œ.
  • USE_SWIG_DEPENDENCIES โ€” Added in version 3.20. If set to TRUE, implicit dependencies get generated by the swig tool itself ๐ŸŽ€. This property is only meaningful for Makefile, Ninja, Xcode, and Visual Studio generators. Default value is FALSE.

Added in version 3.21: added the support of the Xcode generator.

Added in version 3.22: added the support of Visual Studio Generators.

  • SWIG_MODULE_NAME โ€” specifies the actual import name of the module in the target language ๐Ÿ‘‘. This is required if it can't be scanned automatically from source, or if it's different from the module file basename. For example:
set_property(SOURCE mymod.i PROPERTY SWIG_MODULE_NAME mymod_realname)

Changed in version 3.14: if policy CMP0086 is set to NEW, -module <module_name> gets passed to the SWIG compiler.

  • OUTPUT_DIR โ€” Added in version 3.19. Specifies where to write the language-specific files (the swig -outdir option) for the source file in question ๐ŸŒธ. If it's not specified, the other ways to define the output directory apply (see the OUTPUT_DIR option of the swig_add_library() command).
  • OUTFILE_DIR โ€” Added in version 3.19. Specifies an output directory where the generated source file will be placed (the swig -o option) for the source file in question โญ. If it's not specified, the OUTPUT_DIR source property gets used. If neither are specified, the other ways to define the output file directory apply (see the OUTFILE_DIR option of the swig_add_library() command).

โœจ Properties on Targets โœจ

okay so bestie, you can set properties on the target library and they'll apply the same config to literally all the SWIG input files at once. group-chat-wide announcement energy ๐Ÿ’…

SWIG_INCLUDE_DIRECTORIES, SWIG_COMPILE_DEFINITIONS and SWIG_COMPILE_OPTIONS

  • Added in version 3.12.
  • These get applied to every single SWIG input file, and they have the exact same semantics as the target properties INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_OPTIONS. no cap, same vibes ๐Ÿซถ
set (UseSWIG_TARGET_NAME_PREFERENCE STANDARD)
swig_add_library(mymod LANGUAGE python SOURCES mymod.i)
set_property(TARGET mymod PROPERTY SWIG_COMPILE_DEFINITIONS MY_DEF1 MY_DEF2)
set_property(TARGET mymod PROPERTY SWIG_COMPILE_OPTIONS -bla -blb)

SWIG_USE_TARGET_INCLUDE_DIRECTORIES

  • Added in version 3.13.
  • Set it to TRUE and the contents of the target property INCLUDE_DIRECTORIES get forwarded to the SWIG compiler, like passing along the aux. If it's FALSE or just not defined at all, that target property INCLUDE_DIRECTORIES is ignored entirely ๐Ÿ™ˆ
  • Wanna override it per-file? The source property USE_TARGET_INCLUDE_DIRECTORIES is your girl.

SWIG_GENERATED_INCLUDE_DIRECTORIES, SWIG_GENERATED_COMPILE_DEFINITIONS and SWIG_GENERATED_COMPILE_OPTIONS

  • Added in version 3.12.
  • These populate, respectively, the properties INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_FLAGS of all the generated C/C++ files. every single one. go off ๐Ÿ’–

SWIG_DEPENDS

  • Added in version 3.12.
  • Adds dependencies to all SWIG input files. so clingy, but make it build-system ๐Ÿ’€

๐ŸŒธ Read-only Target Properties ๐ŸŒธ

These ones are output properties โ€” you read them, you don't write them. They hand you the tea about support files generated by SWIG interface compilation. ip, not editable ๐Ÿ˜Œ

SWIG_SUPPORT_FILES

  • Added in version 3.12.
  • This output property is a list of the wrapper files generated during SWIG compilation.
set (UseSWIG_TARGET_NAME_PREFERENCE STANDARD)
swig_add_library(mymod LANGUAGE python SOURCES mymod.i)
get_property(support_files TARGET mymod PROPERTY SWIG_SUPPORT_FILES)
Note: only the most principal support files are listed. If you're using some advanced SWIG features (say, %template), the associated support files might not show up here. Prefer using the SWIG_SUPPORT_FILES_DIRECTORY property to handle support files, bestie โ€” it's the main character for that job ๐Ÿ‘‘

SWIG_SUPPORT_FILES_DIRECTORY

  • Added in version 3.12.
  • This output property tells you the directory where support files will be generated.
Note: when the source property OUTPUT_DIR is defined, multiple directories can be specified as part of SWIG_SUPPORT_FILES_DIRECTORY. not just one, she contains multitudes ๐ŸŒˆ

๐ŸŽ€ CMake Variables ๐ŸŽ€

Some variables customize how swig_add_library behaves, and also how SWIG itself behaves. set them, live your truth:

UseSWIG_MODULE_VERSION

  • Added in version 3.12.
  • Specifies different behaviors for the UseSWIG module:
    • Set to 1 or left undefined: legacy behavior is applied.
    • Set to 2: a new strategy is applied regarding support files โ€” the output directory of support files is erased before SWIG interface compilation. yes, wiped. fresh slate vibes โœจ

CMAKE_SWIG_FLAGS

  • Adds flags to all the swig calls. all of them. periodt.

CMAKE_SWIG_OUTDIR

  • Says where to write the language-specific files (that's the swig -outdir option).

SWIG_OUTFILE_DIR

  • Added in version 3.8.
  • Names an output directory where the generated source file gets placed. If you don't specify it, CMAKE_SWIG_OUTDIR is used instead. she's the fallback bestie ๐Ÿซถ

SWIG_MODULE_<name>_EXTRA_DEPS

  • Specifies extra dependencies for the generated module for <name>.

SWIG_SOURCE_FILE_EXTENSIONS

  • Added in version 3.14.
  • Gives a list of source file extensions to override the default behavior of only considering .i files as sources for the SWIG tool. for example:
set(SWIG_SOURCE_FILE_EXTENSIONS ".i" ".swg")

SWIG_USE_SWIG_DEPENDENCIES

  • Added in version 3.20.
  • If set to TRUE, implicit dependencies are generated by the swig tool itself. This variable is only meaningful for Makefile, Ninja, Xcode, and Visual Studio generators. Default value is FALSE.
  • The source file property USE_SWIG_DEPENDENCIES, if not defined, will be initialized with the value of this variable.
  • Added in version 3.21: added the support of the Xcode generator.
  • Added in version 3.22: added the support of Visual Studio Generators.

๐Ÿ’€ Deprecated Commands ๐Ÿ’€

swig_link_libraries

  • Deprecated since version 3.13: use target_link_libraries() with the standard target name, or with ${SWIG_MODULE_<name>_REAL_NAME} for legacy target naming.
  • Links libraries to a swig module:
swig_link_libraries(<name> <item>...)
  • This command has the same capabilities as the target_link_libraries() command. same powers, older packaging ๐Ÿ™ˆ
Note: when policy CMP0078 is set to NEW, swig_add_library() creates a standard target with the specified <name> and target_link_libraries() must be used instead of this command. With the legacy behavior (when CMP0078 is set to OLD and the UseSWIG_TARGET_NAME_PREFERENCE variable is set to "LEGACY", or in CMake versions prior to 3.12), it is preferable to use target_link_libraries(${SWIG_MODULE_<name>_REAL_NAME} ...) instead of this command. consider this your official heads-up, bestie โš ๏ธ

๐Ÿฆ‹ UsewxWidgets ๐Ÿฆ‹

This module is basically a convenience wrapper for using the wxWidgets library (formerly known as wxWindows โ€” glow-up โœจ), and it propagates its usage requirements โ€” library directories, include directories, compiler flags, the whole fit โ€” into the current directory scope so targets can use them.

Load this module in a CMake project with:

include(UsewxWidgets)

This module calls include_directories() and link_directories(), sets compile definitions for the current directory, and appends some compile flags to use the wxWidgets library after calling find_package(wxWidgets). that's the whole ritual ๐Ÿ’…

๐ŸŒŸ Examples ๐ŸŒŸ

Include this module in a project after finding wxWidgets, to configure its usage requirements:

CMakeLists.txt

# Note that for MinGW users the order of libraries is important.
find_package(wxWidgets COMPONENTS net gl core base)

add_library(example example.cxx)

if(wxWidgets_FOUND)
  include(UsewxWidgets)

  # Link wxWidgets libraries for each dependent executable/library target.
  target_link_libraries(example PRIVATE ${wxWidgets_LIBRARIES})
endif()

As of CMake 3.27, a better approach is to link only the wxWidgets::wxWidgets imported target to the specific targets that require it, rather than including this module. Imported targets give you better control of the package usage properties โ€” include directories and compile flags and all that โ€” by applying them only to the targets they're linked to, avoiding unnecessary propagation to every single target in the current directory. iconic behavior, honestly ๐Ÿ‘‘

CMakeLists.txt

find_package(wxWidgets COMPONENTS net gl core base)

add_library(example example.cxx)

# Link the imported target for each dependent executable/library target.
target_link_libraries(example PRIVATE wxWidgets::wxWidgets)

๐ŸŽ€ See Also ๐ŸŽ€

  • The FindwxWidgets module to find wxWidgets.

๐Ÿ” FIND MODULES ๐Ÿ”

These modules search for third-party software. They're normally called through the find_package() command โ€” like, that's their whole thing, that's their moment ๐Ÿ’–


๐ŸŒˆ FindALSA ๐ŸŒˆ

Finds the Advanced Linux Sound Architecture (ALSA) library (asound):

find_package(ALSA [<version>] [...])

โญ Imported Targets โญ

This module provides the following Imported Targets:

  • ALSA::ALSA โ€” Added in version 3.12. Target encapsulating the ALSA library usage requirements. This target is available only if ALSA is found. no ALSA, no target, them's the rules ๐Ÿซถ

โญ Result Variables โญ

This module defines the following variables:

  • ALSA_FOUND โ€” Boolean indicating whether the (requested version of) ALSA library was found.
  • ALSA_VERSION โ€” Added in version 4.2. The version of ALSA found.
  • ALSA_LIBRARIES โ€” List of libraries needed for linking to use the ALSA library.
  • ALSA_INCLUDE_DIRS โ€” Include directories containing headers needed to use the ALSA library.

โญ Cache Variables โญ

The following cache variables may also be set:

  • ALSA_INCLUDE_DIR โ€” The ALSA include directory.
  • ALSA_LIBRARY โ€” The absolute path of the asound library.

โญ Deprecated Variables โญ

The following variables are provided for backward compatibility:

  • ALSA_VERSION_STRING โ€” Deprecated since version 4.2: superseded by the ALSA_VERSION. The version of ALSA found. she's retired but still showing up to the group chat ๐Ÿ’€

โญ Examples โญ

Finding the ALSA library and linking it to a project target:

find_package(ALSA)
target_link_libraries(project_target PRIVATE ALSA::ALSA)

๐ŸŒธ FindArmadillo ๐ŸŒธ

Finds the Armadillo C++ library:

find_package(Armadillo [<version>] [...])

Armadillo is a library for linear algebra and scientific computing. math girlie behavior, we respect it ๐Ÿงฎโœจ

Added in version 3.18: support for linking wrapped libraries directly (see the ARMA_DONT_USE_WRAPPER preprocessor macro that needs to be defined before including the <armadillo> header).

โญ Result Variables โญ

This module defines the following variables:

  • Armadillo_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) Armadillo library was found.
  • Armadillo_VERSION โ€” Added in version 4.2. The version of Armadillo found (e.g., 14.90.0).
  • Armadillo_VERSION_NAME โ€” Added in version 4.2. The version name of Armadillo found (e.g., Antipodean Antileech).
  • ARMADILLO_INCLUDE_DIRS โ€” List of required include directories.
  • ARMADILLO_LIBRARIES โ€” List of libraries to be linked.

โญ Deprecated Variables โญ

The following variables are provided for backward compatibility:

  • ARMADILLO_FOUND โ€” Deprecated since version 4.2: use Armadillo_FOUND, which has the same value. literally the same value, bestie, just a different name ๐Ÿ™ˆ

...a Boolean saying whether the (requested version of) the Armadillo library was found. Lowkey the whole point of the search, bestie ๐Ÿซถ

  • ARMADILLO_VERSION_STRING โ€” ๐Ÿซ  Deprecated since version 4.2: superseded by the Armadillo_VERSION. Yeah it still exists, but it's giving legacy. This is the version of Armadillo found.
  • ARMADILLO_VERSION_MAJOR โ€” Deprecated since version 4.2: superseded by the Armadillo_VERSION. Major version number.
  • ARMADILLO_VERSION_MINOR โ€” Deprecated since version 4.2: superseded by the Armadillo_VERSION. Minor version number.
  • ARMADILLO_VERSION_PATCH โ€” Deprecated since version 4.2: superseded by the Armadillo_VERSION. Patch version number.
  • ARMADILLO_VERSION_NAME โ€” Deprecated since version 4.2: superseded by the Armadillo_VERSION_NAME. The version name of Armadillo found (e.g., Antipodean Antileech). Yes that's a real release name and it ate ๐Ÿ’…

๐ŸŒธ Examples ๐ŸŒธ

Finding Armadillo and creating an imported target โ€” this is the whole ritual, no cap:

find_package(Armadillo REQUIRED)

if(Armadillo_FOUND AND NOT TARGET Armadillo::Armadillo)
  add_library(Armadillo::Armadillo INTERFACE IMPORTED)
  set_target_properties(
    Armadillo::Armadillo
    PROPERTIES
      INTERFACE_LINK_LIBRARIES "${ARMADILLO_LIBRARIES}"
      INTERFACE_INCLUDE_DIRECTORIES "${ARMADILLO_INCLUDE_DIRS}"
  )
endif()

add_executable(foo foo.cc)
target_link_libraries(foo PRIVATE Armadillo::Armadillo)

๐Ÿ”ฎ FindASPELL ๐Ÿ”ฎ

Finds the GNU Aspell spell checker library. Yes, the thing that tells you you spelled "definately" wrong ๐Ÿ˜ญ

find_package(ASPELL [<version>] [COMPONENTS <components>] [...])

๐ŸŽ€ Components ๐ŸŽ€

This module supports optional components, and you pick them with the find_package() command:

find_package(ASPELL [COMPONENTS <components>...])

Supported components include:

  • ASPELL โ€” โœจ Added in version 4.1. Finds the Aspell library and its include paths.
  • Executable โ€” โœจ Added in version 4.1. Finds the Aspell command-line interactive spell checker executable.

If you don't specify any components, the module searches for both the ASPELL and Executable components by default. Generous of it honestly ๐Ÿซถ

๐Ÿ‘‘ Imported Targets ๐Ÿ‘‘

This module provides the following imported targets when CMAKE_ROLE is PROJECT:

  • ASPELL::ASPELL โ€” โœจ Added in version 4.1. Target encapsulating the Aspell library usage requirements. It is available only when the ASPELL component is found.
  • ASPELL::Executable โ€” โœจ Added in version 4.1. Target encapsulating the Aspell command-line spell checker executable. It is available only when the Executable component is found.

๐Ÿ“ Result Variables ๐Ÿ“

This module defines the following variables:

  • ASPELL_FOUND โ€” Boolean indicating whether (the requested version of) Aspell and all requested components were found. Note the "and" โ€” partial matches do not count, periodt.
  • ASPELL_VERSION โ€” โœจ Added in version 4.1. Version string of the found Aspell if any. It may be only determined if the Executable component is found. If version isn't determined, version value is not set. (Yes, that's a little tragic. It is what it is ๐Ÿ™ˆ)
  • ASPELL_INCLUDE_DIRS โ€” โœจ Added in version 4.1. Include directories needed to use Aspell. They are available when the ASPELL component is found.

The Aspell library may also provide a backward-compatible interface for Pspell via the pspell.h header file. If such an interface is found, it is also added to the list of include directories. Cute little bonus ๐ŸŽ

  • ASPELL_LIBRARIES โ€” Libraries needed to link to Aspell. They are available when the ASPELL component is found.

Changed in version 4.1: this variable is now set as a regular result variable instead of being a cache variable. So if you were poking at the cache expecting it thereโ€ฆ not anymore bestie ๐Ÿ’€

๐Ÿฆ‹ Cache Variables ๐Ÿฆ‹

The following cache variables may also be set:

  • ASPELL_INCLUDE_DIR โ€” The directory containing the aspell.h header file when using the Executable component.
  • ASPELL_LIBRARY โ€” โœจ Added in version 4.1. The path to the Aspell library when using the ASPELL component.
  • ASPELL_EXECUTABLE โ€” The path to the aspell command-line spell checker program when using the Executable component.

๐Ÿ’œ Examples ๐Ÿ’œ

Finding the Aspell library with CMake 4.1 or later and linking it to a project target:

find_package(ASPELL COMPONENTS ASPELL)
target_link_libraries(project_target PRIVATE ASPELL::ASPELL)

When writing backward-compatible code that supports CMake 4.0 and earlier, a local imported target can be defined directly in the project:

find_package(ASPELL COMPONENTS ASPELL)
if(ASPELL_FOUND AND NOT TARGET ASPELL::ASPELL)
  add_library(ASPELL::ASPELL INTERFACE IMPORTED)
  set_target_properties(
    ASPELL::ASPELL
    PROPERTIES
      INTERFACE_LINK_LIBRARIES "${ASPELL_LIBRARIES}"
      INTERFACE_INCLUDE_DIRECTORIES "${ASPELL_INCLUDE_DIR}"
  )
endif()
target_link_libraries(project_target PRIVATE ASPELL::ASPELL)

Example, how to execute the aspell command-line spell checker in a project:

find_package(ASPELL COMPONENTS Executable)
execute_process(COMMAND ${ASPELL_EXECUTABLE} --help)

๐ŸŒˆ FindAVIFile ๐ŸŒˆ

Finds the AVIFile library and include paths โ€” repo lives at https://avifile.sourceforge.net/ if you wanna go look ๐Ÿ‘€

find_package(AVIFile [...])

AVIFile is a set of libraries for i386 machines to use various AVI codecs. Support is limited beyond Linux. Windows provides native AVI support, and so doesn't need this library. So likeโ€ฆ it's a very specific vibe, iykyk ๐ŸŽ€

โญ Result Variables โญ

This module defines the following variables:

  • AVIFile_FOUND โ€” โœจ Added in version 3.3. Boolean indicating whether AVIFile was found.
  • AVIFILE_LIBRARIES โ€” The libraries to link against.
  • AVIFILE_DEFINITIONS โ€” Definitions to use when compiling.

๐Ÿงš Cache Variables ๐Ÿงš

The following cache variables may also be set:

  • AVIFILE_INCLUDE_DIR โ€” Directory containing avifile.h and other AVIFile headers.

๐Ÿฅ€ Deprecated Variables ๐Ÿฅ€

The following variables are provided for backward compatibility:

  • AVIFILE_FOUND โ€” Deprecated since version 4.2: use AVIFile_FOUND, which has the same value. Same value, just different spelling energy โ€” swap it out when you can ๐Ÿ’…

๐Ÿ”ฅ Examples ๐Ÿ”ฅ

Finding AVIFile and conditionally creating an interface imported target that encapsulates its usage requirements for linking to a project target:

find_package(AVIFile)

if(AVIFile_FOUND AND NOT TARGET AVIFile::AVIFile)
  add_library(AVIFile::AVIFile INTERFACE IMPORTED)
  set_target_properties(
    AVIFile::AVIFile
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${AVIFILE_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${AVIFILE_LIBRARIES}"
      INTERFACE_COMPILE_DEFINITIONS "${AVIFILE_DEFINITIONS}"
  )
endif()

target_link_libraries(example PRIVATE AVIFile::AVIFile)

๐Ÿฆ‹ FindBacktrace ๐Ÿฆ‹

Finds backtrace(3) (docs at https://man7.org/linux/man-pages/man3/backtrace.3.html), a library that provides functions for application self-debugging. Basically your app snitching on itself when it trips ๐Ÿ’€

find_package(Backtrace [...])

This module checks whether backtrace(3) is supported, either through the standard C library (libc), or a separate library. Either way, we eat ๐Ÿฝ๏ธ

๐ŸŒŸ Imported Targets ๐ŸŒŸ

This module provides the following imported targets:

  • Backtrace::Backtrace โ€” โœจ Added in version 3.30. An interface library encapsulating the usage requirements of Backtrace. This target is available only when Backtrace is found.

๐ŸŒธ Result Variables ๐ŸŒธ

This module defines the following variables:

  • Backtrace_FOUND โ€” Boolean indicating whether the backtrace(3) support is available.
  • Backtrace_INCLUDE_DIRS โ€” The include directories needed to use the backtrace(3) header.
  • Backtrace_LIBRARIES โ€” The libraries (linker flags) needed to use backtrace(3), if any. "If any" is doing heavy lifting there ngl.

๐Ÿ’– Cache Variables ๐Ÿ’–

The following cache variables are also available to set or use:

  • Backtrace_HEADER โ€” The header file needed for backtrace(3). This variable allows dynamic usage of the header in the project code. It can also be overridden by the user. Go off, override it ๐Ÿ‘‘
  • Backtrace_INCLUDE_DIR โ€” The directory holding the backtrace(3) header.
  • Backtrace_LIBRARY โ€” The external library providing backtrace, if any.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding Backtrace and linking it to a project target as of CMake 3.30:

CMakeLists.txt

find_package(Backtrace)
target_link_libraries(app PRIVATE Backtrace::Backtrace)

The Backtrace_HEADER variable can be used, for example, in a configuration header file created by configure_file():

CMakeLists.txt

add_library(app app.c)

find_package(Backtrace)
target_link_libraries(app PRIVATE Backtrace::Backtrace)

configure_file(config.h.in config.h)

config.h.in

#cmakedefine01 Backtrace_FOUND
#if Backtrace_FOUND
#  include <@Backtrace_HEADER@>
#endif

app.c

#include "config.h"

If the project needs to support CMake 3.29 or earlier, the imported target can be defined manually. Annoying but iconic ๐Ÿ™ˆ

CMakeLists.txt

find_package(Backtrace)
if(Backtrace_FOUND AND NOT TARGET Backtrace::Backtrace)
  add_library(Backtrace::Backtrace INTERFACE IMPORTED)
  set_target_properties(
    Backtrace::Backtrace
    PROPERTIES
      INTERFACE_LINK_LIBRARIES "${Backtrace_LIBRARIES}"
      INTERFACE_INCLUDE_DIRECTORIES "${Backtrace_INCLUDE_DIRS}"
  )
endif()
target_link_libraries(app PRIVATE Backtrace::Backtrace)

โญ FindBISON โญ

Finds the Bison command-line parser generator and provides a CMake command to generate custom build rules for using Bison. Parser generator era is so back ๐Ÿ”ฅ

find_package(BISON [<version>] [...])

Bison is a parser generator that replaced earlier Yacc (Yet Another Compiler-Compiler). On Unix-like systems, most common implementation is GNU Bison. On Windows, this module looks for Windows-compatible Bison, if installed. Cross-platform queen behavior ๐Ÿ’…

๐ŸŽ€ Result Variables ๐ŸŽ€

This module defines the following variables:

  • BISON_FOUND โ€” Boolean indicating whether (the requested version of) Bison was found.
  • BISON_VERSION โ€” The version of Bison found.

๐Ÿ“ Cache Variables ๐Ÿ“

The following cache variables may also be set:

  • BISON_EXECUTABLE โ€” The path to the bison command-line program.

๐Ÿ‘‘ Commands ๐Ÿ‘‘

This module provides the following command if bison is found:

  • bison_target โ€” Creates a custom build rule to generate a parser file from a Yacc file using Bison:
                 bison_target(
                   <name>
                   <input-yacc-file>
                   <output-parser-file>
                   [DEFINES_FILE <header>]
                   [VERBOSE [<file>]]       # The [<file>] argument is deprecated
                   [REPORT_FILE <file>]
                   [OPTIONS <options>...]
                   [COMPILE_FLAGS <string>] # Deprecated
                 )

Changed in version 3.14: when policy CMP0088 is set to NEW, bison runs in the CMAKE_CURRENT_BINARY_DIR directory. (iykyk โ€” it's a whole where do the files go thing.)

  • <name> โ€” a string that's basically this command invocation's little name tag. Everyone in the build refers to it by this.
  • <input-yacc-file> โ€” the path to your input Yacc source file (.y). Give it a relative path and it gets interpreted relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR). ๐ŸŽ€
  • <output-parser-file> โ€” the path where Bison drops the parser file it generates. Relative path? Then it's interpreted relative to the current Bison working directory. (Yes, that working directory is its own whole thing, keep up bestie ๐Ÿ’…)
  • DEFINES_FILE <header> โ€” Added in version 3.4. So by default Bison can generate a header file holding the list of tokens. This option lets you name a custom <header> file for Bison to generate. Relative path โ†’ interpreted relative to the current Bison working directory. โœจ
  • VERBOSE [<file>] โ€” turns on generation of a verbose grammar and parser report. Default vibe: the report file lands in the current Bison working directory, named <output-parser-filename>.output. ๐Ÿ“„

Then there's <file>, which is deprecated since version 3.7 โ€” use VERBOSE REPORT_FILE <file> instead. It specifies the path the report file gets copied to. It's only hanging around for backward compatibility, and it only works when <output-parser-file> is given as an absolute path. So likeโ€ฆ narrowly useful, lowkey a relic. ๐Ÿ’€

  • REPORT_FILE <file> โ€” Added in version 3.7. Team it up with VERBOSE to give the report output a custom path <file>, overriding the default location. Relative path โ†’ interpreted relative to the current Bison working directory. ๐Ÿฆ‹
  • OPTIONS <options>... โ€” Added in version 4.0. A semicolon-separated list of extra options tacked onto the bison command line. This is the new hotness. ๐Ÿ”ฅ
  • COMPILE_FLAGS <string> โ€” Deprecated since version 4.0: superseded by OPTIONS <options>.... It's a string of space-separated extra options added to the bison command line. Pretty please note: a semicolon-separated list will not work here. Spaces only. That's the whole trap. ๐Ÿ™ˆ

Command variables

This command also defines these variables for you, bestie:

  • BISON_<name>_DEFINED โ€” boolean, tells you whether this command was successfully invoked. ๐Ÿซถ
  • BISON_<name>_INPUT โ€” the input source file. Basically an alias for <input-yacc-file>.
  • BISON_<name>_OUTPUT_SOURCE โ€” the output parser file that bison generated.
  • BISON_<name>_OUTPUT_HEADER โ€” the header file that bison generated, if any.
  • BISON_<name>_OUTPUTS โ€” a list of every file bison generated: the output parser file, the header file, and the report file. Iconic little bundle. ๐Ÿ‘‘
  • BISON_<name>_OPTIONS โ€” Added in version 4.0. A list of the command-line options used for the bison command.
  • BISON_<name>_COMPILE_FLAGS โ€” Deprecated since version 4.0: superseded by the BISON_<name>_OPTIONS variable, which holds the same value. A list of command-line options used for the bison command.

Examples: Finding Bison

Finding Bison:

find_package(BISON)

Finding Bison with a minimum required version:

find_package(BISON 2.1.3)

Finding Bison and making it required โ€” so if Bison isn't found, processing stops with an error message:

find_package(BISON 2.1.3 REQUIRED)

Example: Generating Parser

Find Bison, then add your input Yacc source file parser.y so it gets processed by Bison into the parser.cpp source file with header parser.h โ€” all at build phase:

find_package(BISON)

if(BISON_FOUND)
  bison_target(MyParser parser.y parser.cpp DEFINES_FILE parser.h)
endif()

add_executable(Foo main.cpp ${BISON_MyParser_OUTPUTS})

See how ${BISON_MyParser_OUTPUTS} just carries everything along? Chef's kiss. ๐Ÿ˜Œ

Examples: Command-line Options

You can pass extra command-line options to the bison executable as a list. For example, adding the -Wall option to report all warnings, and --no-lines (-l) to not generate #line directives:

find_package(BISON)

if(BISON_FOUND)
  bison_target(MyParser parser.y parser.cpp OPTIONS -Wall --no-lines)
endif()

Generator expressions can be used inside the OPTIONS <options>... argument too, bestie โœจ. For example, to add the --debug (-t) option only for the Debug build type:

find_package(BISON)

if(BISON_FOUND)
  bison_target(MyParser parser.y parser.cpp OPTIONS $<$<CONFIG:Debug>:-t>)
endif()

See Also

  • The FindFLEX module, for finding the Flex scanner generator. ๐Ÿค

FindBLAS

Finds the installed Basic Linear Algebra Subprograms (BLAS) Fortran library โ€” the thing that implements the BLAS linear-algebra interface (https://netlib.org/blas/):

find_package(BLAS [...])

Heads up: at least one of the C, CXX, or Fortran languages must be enabled. No languages enabled, no BLAS. Periodt. ๐Ÿ’…

Imported Targets

This module provides these Imported Targets:

  • BLAS::BLAS โ€” Added in version 3.18. A target encapsulating the libraries and usage requirements needed to use BLAS. It's only available if BLAS is found. ๐ŸŽ€

Result Variables

This module defines these variables:

  • BLAS_FOUND โ€” boolean, says whether the library implementing the BLAS interface was found. ๐ŸŒŸ
  • BLAS_LINKER_FLAGS โ€” uncached list of required linker flags (excluding -l and -L).
  • BLAS_LIBRARIES โ€” uncached list of libraries (using full path name) to link against to use BLAS. Lowkey may be empty if the compiler implicitly links BLAS. It's giving "trust me bro" but it's documented, so.
  • BLAS95_LIBRARIES โ€” uncached list of libraries (using full path name) to link against to use the BLAS95 interface.
  • BLAS95_FOUND โ€” boolean, says whether the library implementing the BLAS95 interface was found. ๐Ÿฆ‹

Input Variables

These variables are settable to influence this module's behavior:

  • BLA_STATIC โ€” if ON, the static linkage will be used.
  • BLA_VENDOR โ€” set it to one of the BLAS/LAPACK Vendors to search for BLAS only from that specified vendor. Not set? Then all vendors are considered. โœจ
  • BLA_F95 โ€” if ON, the module tries to find the BLAS95 interfaces.
  • BLA_PREFER_PKGCONFIG โ€” Added in version 3.11. If set, pkg-config gets used to search for a BLAS library first, and if one is found, that one is preferred.
  • BLA_PKGCONFIG_BLAS โ€” Added in version 3.25. If set, the pkg-config method looks for this module name instead of just blas.
  • BLA_SIZEOF_INTEGER โ€” Added in version 3.22. Specifies the BLAS/LAPACK library integer size:
    • 4 โ€” search for a BLAS/LAPACK with 32-bit integer interfaces.
    • 8 โ€” search for a BLAS/LAPACK with 64-bit integer interfaces.
    • ANY โ€” search for any BLAS/LAPACK. Most likely a BLAS/LAPACK with 32-bit integer interfaces will be found.
  • BLA_THREAD โ€” Added in version 4.1. Specifies the BLAS/LAPACK threading model:
    • SEQ โ€” sequential model.
    • OMP โ€” OpenMP model.
    • ANY โ€” search for any BLAS/LAPACK; if both are available, most likely OMP will be found.

This is currently only supported by NVIDIA NVPL. Just so you know. ๐Ÿ‘€

BLAS/LAPACK Vendors

  • Generic โ€” generic reference implementation.
  • ACML, ACML_MP, ACML_GPU โ€” AMD Core Math Library.
  • AOCL, AOCL_mt โ€” Added in version 3.27. AMD Optimizing CPU Libraries.
  • Apple, NAS โ€” Apple BLAS (Accelerate), and Apple NAS (vecLib).
  • Arm, Arm_mp, Arm_ilp64, Arm_ilp64_mp โ€” Added in version 3.18. Arm Performance Libraries.
  • ATLAS โ€” Automatically Tuned Linear Algebra Software.
  • CXML, DXML โ€” Compaq/Digital Extended Math Library.
  • EML, EML_mt โ€” Added in version 3.20. Elbrus Math Library.
  • FLAME โ€” Added in version 3.11. BLIS Framework.
  • FlexiBLAS โ€” Added in version 3.19.
  • Fujitsu_SSL2, Fujitsu_SSL2BLAMP, Fujitsu_SSL2SVE, Fujitsu_SSL2BLAMPSVE โ€” Added in version 3.20. Fujitsu SSL2 serial and parallel blas/lapack with SVE instructions.
  • Goto โ€” GotoBLAS.
  • IBMESSL, IBMESSL_SMP โ€” IBM Engineering and Scientific Subroutine Library.
  • Intel โ€” Intel MKL 32 bit and 64 bit obsolete versions.
  • Intel10_32 โ€” Intel MKL v10 32 bit, threaded code.
  • Intel10_64lp โ€” Intel MKL v10+ 64 bit, threaded code, lp64 model.
  • Intel10_64lp_seq โ€” Intel MKL v10+ 64 bit, sequential code, lp64 model.
  • Intel10_64ilp โ€” Added in version 3.13. Intel MKL v10+ 64 bit, threaded code, ilp64 model.
  • Intel10_64ilp_seq โ€” Added in version 3.13. Intel MKL v10+ 64 bit, sequential code, ilp64 model.
  • Intel10_64_dyn โ€” Added in version 3.17. Intel MKL v10+ 64 bit, single dynamic library.
  • libblastrampoline โ€” Added in version 3.30. A BLAS/LAPACK demuxing library using PLT trampolines.
  • NVPL โ€” Added in version 4.1. NVIDIA Performance Libraries.
  • NVHPC โ€” Added in version 3.21. NVIDIA HPC SDK.
  • OpenBLAS โ€” Added in version 3.6.
  • PhiPACK โ€” Portable High Performance ANSI C (PHiPAC).
  • SCSL, SCSL_mp โ€” Scientific Computing Software Library.
  • SGIMATH โ€” SGI Scientific Mathematical Library.
  • SunPerf โ€” Sun Performance Library.

Intel MKL

To use the Intel MKL implementation of BLAS, a project must enable at least one of the C or CXX languages. Then set BLA_VENDOR to an Intel MKL variant โ€” either on the command line as -DBLA_VENDOR=Intel10_64lp, or right in your project code:

set(BLA_VENDOR Intel10_64lp)
find_package(BLAS)

So like, to actually build something with Intel MKL, the end user has to set up an Intel MKL environment first โ€” no skipping this step bestie:

Intel oneAPI

Source the full Intel environment script:

. /opt/intel/oneapi/setvars.sh

Or, if you're being all minimal about it, source just the MKL component environment script:

. /opt/intel/oneapi/mkl/latest/env/vars.sh

Intel Classic

Source the full Intel environment script:

. /opt/intel/bin/compilervars.sh intel64

Or the MKL component script, your call:

. /opt/intel/mkl/bin/mklvars.sh intel64

Those environment scripts set the MKLROOT environment variable to the top of the MKL installation โœจ and they also add the location of the runtime libraries to the dynamic library loader environment variable for your platform (think LD_LIBRARY_PATH). This is lowkey necessary for programs linked against MKL to actually run, so don't ghost it.

Note: as of Intel oneAPI 2021.2, loading only the MKL component does not make all of its dependencies available. Specifically the iomp5 library must be available separately, or you can provide it by also loading the compiler component environment: sh . /opt/intel/oneapi/compiler/latest/env/vars.sh

Examples

Finding BLAS and linking it to a project target, the whole vibe:

find_package(BLAS)
target_link_libraries(example PRIVATE BLAS::BLAS)

๐Ÿ’ฅ FindBullet

Finds the Bullet physics engine ๐ŸŽณ:

find_package(Bullet [...])

Result Variables

This module defines the following variables:

  • Bullet_FOUND โ€” Added in version 3.3. Boolean indicating whether Bullet was found.
  • BULLET_INCLUDE_DIRS โ€” the Bullet include directories.
  • BULLET_LIBRARIES โ€” libraries needed to link to Bullet. By default, all Bullet components (Dynamics, Collision, LinearMath, and SoftBody) are added.

Hints

This module accepts the following variables:

  • BULLET_ROOT โ€” can be set to the Bullet install path or the Windows build path to specify where to find Bullet.

Deprecated Variables

The following variables are provided for backward compatibility:

  • BULLET_FOUND โ€” Deprecated since version 4.2: use Bullet_FOUND, which has the same value. Boolean indicating whether Bullet was found.

Examples

Finding Bullet and then conditionally creating an interface imported target that encapsulates its usage requirements for linking to a project target โ€” very main character of you:

find_package(Bullet)

if(Bullet_FOUND AND NOT TARGET Bullet::Bullet)
  add_library(Bullet::Bullet INTERFACE IMPORTED)
  set_target_properties(
    Bullet::Bullet
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${BULLET_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${BULLET_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE Bullet::Bullet)

๐Ÿ—œ๏ธ FindBZip2

Finds the BZip2 data compression library (libbz2) โ€” yes the one that goes brrr on your tarballs:

find_package(BZip2 [<version>] [...])

Imported Targets

This module provides the following imported targets:

  • BZip2::BZip2 โ€” Added in version 3.12. Target encapsulating the usage requirements of the BZip2 library. This target is available only when BZip2 is found. ๐Ÿ‘‘

Result Variables

This module defines the following variables:

  • BZip2_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of the) BZip2 library was found.
  • BZip2_VERSION โ€” Added in version 4.2. The version of BZip2 found.
  • BZIP2_INCLUDE_DIRS โ€” Added in version 3.12. Include directories needed to use the BZip2 library.
  • BZIP2_LIBRARIES โ€” libraries needed for linking to use BZip2.

Cache Variables

The following cache variables may also be set:

  • BZIP2_INCLUDE_DIR โ€” the directory containing the BZip2 headers.
  • BZIP2_LIBRARY_RELEASE โ€” the path to the BZip2 library for release configurations.
  • BZIP2_LIBRARY_DEBUG โ€” the path to the BZip2 library for debug configurations.
  • BZIP2_NEED_PREFIX โ€” boolean indicating whether BZip2 functions are prefixed with BZ2_ (e.g., BZ2_bzCompressInit()). Versions of BZip2 prior to 1.0.0 used unprefixed function names (e.g., bzCompressInit()). history lesson fr fr ๐Ÿ“œ

Deprecated Variables

The following variables are provided for backward compatibility:

  • BZIP2_FOUND โ€” Deprecated since version 4.2: use BZip2_FOUND, which has the same value. Boolean indicating whether the (requested version of the) BZip2 library was found.
  • BZIP2_VERSION_STRING โ€” Deprecated since version 3.26: superseded by the BZIP2_VERSION (and BZip2_VERSION). The version of BZip2 found.
  • BZIP2_VERSION โ€” Added in version 3.26. Deprecated since version 4.2: superseded by the BZIP2_VERSION. The version of BZip2 found.

Examples

Finding the BZip2 library and linking it to a project target โ€” chef's kiss ๐ŸคŒ:

find_package(BZip2)
target_link_libraries(project_target PRIVATE BZip2::BZip2)

๐ŸงŠ FindCoin3D

Finds Coin3D (Open Inventor):

find_package(Coin3D [...])

Coin3D is an implementation of the Open Inventor API. It provides data structures and algorithms for 3D visualization ๐Ÿฆ‹ โ€” like, actual little 3D worlds, love that for it.

Result Variables

This module defines the following variables:

  • Coin3D_FOUND โ€” Added in version 3.3. Boolean indicating whether Coin3D, Open Inventor was found.

Cache Variables

The following cache variables may also be set:

  • COIN3D_INCLUDE_DIRS โ€” directory containing the Open Inventor header files (Inventor/So.h).
  • COIN3D_LIBRARIES โ€” Coin3D libraries required for linking.

Deprecated Variables

The following variables are provided for backward compatibility:

  • COIN3D_FOUND โ€” Deprecated since version 4.2: use Coin3D_FOUND, which has the same value. Boolean indicating whether Coin3D, Open Inventor was found.

Examples

Finding Coin3D and conditionally creating an interface imported target that encapsulates its usage requirements for linking to a project target:

find_package(Coin3D)

if(Coin3D_FOUND AND NOT TARGET Coin3D::Coin3D)
  add_library(Coin3D::Coin3D INTERFACE IMPORTED)
  set_target_properties(
    Coin3D::Coin3D
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${COIN3D_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${COIN3D_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE Coin3D::Coin3D)

๐ŸŸฉ FindCUDAToolkit

Added in version 3.17.

Finds the NVIDIA CUDA toolkit and the associated libraries โ€” but here's the slay: it does not require the CUDA language to be enabled for a given project โœจ:

find_package(CUDAToolkit [<version>] [QUIET] [REQUIRED] [EXACT] [...])

Heads up: this module does not search for the NVIDIA CUDA Samples. Not its job, not its problem.

Added in version 3.19: QNX support.

๐Ÿ” Search Behavior

The CUDA Toolkit search behavior uses the following order:

  1. If the CUDA language has been enabled, we use the directory containing the compiler as the first search location for nvcc.
  2. If the variable CMAKE_CUDA_COMPILER or the environment variable CUDACXX is defined, it will be used as the path to the nvcc executable.
  3. If the CUDAToolkit_ROOT CMake configuration variable (e.g., -DCUDAToolkit_ROOT=/some/path) or environment variable is defined, it will be searched. If both an environment variable and a configuration variable are specified, the configuration variable takes precedence. โš–๏ธ

The directory specified here must be such that the executable nvcc or the appropriate version.txt or version.json file can be found underneath the specified directory.

  1. If the CUDA_PATH environment variable is defined, it will be searched for nvcc.
  2. The user's path is searched for nvcc using find_program(). If this is found, no subsequent search attempts are performed. Users are responsible for ensuring that the first nvcc to show up in the path is the desired path in the event that multiple CUDA Toolkits are installed. ๐Ÿ‘€
  3. On Unix systems, if the symbolic link /usr/local/cuda exists, this is used. No subsequent search attempts are performed. No default symbolic link location exists for the Windows platform.
  4. The platform specific default install locations are searched. If exactly one candidate is found, this is used. The default CUDA Toolkit install locations searched are:
    • macOS โ€” /Developer/NVIDIA/CUDA-X.Y
    • Other Unix โ€” /usr/local/cuda-X.Y
    • Windows โ€” C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vX.Y

Where X.Y would be a specific version of the CUDA Toolkit, such as /usr/local/cuda-9.0 or C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0.

Note: when multiple CUDA Toolkits are installed in the default location of a system (e.g., both /usr/local/cuda-9.0 and /usr/local/cuda-10.0 exist but the /usr/local/cuda symbolic link does not exist), this package is marked as not found. ๐Ÿ˜ญ There are too many factors involved in making an automatic decision in the presence of multiple CUDA Toolkits being installed. In this situation, users are encouraged to either (1) set CUDAToolkit_ROOT or (2) ensure that the correct nvcc executable shows up in $PATH for find_program() to find. You got this ๐Ÿ’ช

Arguments

  • [<version>] โ€” the [<version>] argument requests a version with which the package found should be compatible. See the find_package version format for more details.

โœจ Options โœจ

  • REQUIRED โ€” if you specify this, configuration will error if a suitable CUDA Toolkit is not found. no silent sadness, bestie ๐Ÿ’…
  • QUIET โ€” if you specify this, the search for a suitable CUDA Toolkit will not produce any messages. stealth mode activated ๐Ÿซถ
  • EXACT โ€” if you specify this, the CUDA Toolkit is considered found only if the exact VERSION specified is recovered. no substitutions, periodt ๐Ÿ’€

๐ŸŽ€ Imported Targets ๐ŸŽ€

An imported target named CUDA::toolkit is provided.

This module also gives you imported targets for each one of these libraries that are part of the CUDAToolkit:

  • CUDA Runtime Library
  • CUDA Driver Library
  • cuBLAS
  • cuDLA
  • cuFile
  • cuFFT
  • cuRAND
  • cuSOLVER
  • cuSPARSE
  • cuPTI
  • NPP
  • nvBLAS
  • nvGRAPH
  • nvJPEG
  • nvidia-ML
  • nvPTX Compiler
  • nvRTC
  • nvJitLink
  • nvFatBin
  • nvToolsExt
  • nvtx3
  • OpenCL
  • cuLIBOS
  • cufilt

๐Ÿ’– CUDA Runtime Library ๐Ÿ’–

The CUDA Runtime library (cudart) is what most applications will typically need to link against to make any calls such as cudaMalloc, and cudaFree.

Targets Created:

  • CUDA::cudart
  • CUDA::cudart_static

๐Ÿš— CUDA Driver Library ๐Ÿš—

The CUDA Driver library (cuda) is used by applications that use calls such as cuMemAlloc, and cuMemFree.

Targets Created:

  • CUDA::cuda_driver

๐Ÿ”ฅ cuBLAS ๐Ÿ”ฅ

The CUDA Basic Linear Algebra Subroutine library โ€” yes that's the baddie at https://docs.nvidia.com/cuda/cublas.

Targets Created:

  • CUDA::cublas
  • CUDA::cublas_static
  • CUDA::cublasLt starting in CUDA 10.1
  • CUDA::cublasLt_static starting in CUDA 10.1

๐Ÿง  cuDLA ๐Ÿง 

Added in version 3.27.

The NVIDIA Tegra Deep Learning Accelerator library, docs at https://docs.nvidia.com/cuda/cuda-for-tegra-appnote#cudla.

Targets Created:

  • CUDA::cudla starting in CUDA 11.6

๐Ÿ“ cuFile ๐Ÿ“

Added in version 3.25.

The NVIDIA GPUDirect Storage cuFile library โ€” the API reference guide lives at https://docs.nvidia.com/gpudirect-storage/api-reference-guide.

Targets Created:

  • CUDA::cuFile starting in CUDA 11.4
  • CUDA::cuFile_static starting in CUDA 11.4
  • CUDA::cuFile_rdma starting in CUDA 11.4
  • CUDA::cuFile_rdma_static starting in CUDA 11.4

๐Ÿฆ‹ cuFFT ๐Ÿฆ‹

The CUDA Fast Fourier Transform library, aka https://docs.nvidia.com/cuda/cufft.

Targets Created:

  • CUDA::cufft
  • CUDA::cufftw
  • CUDA::cufft_static
  • CUDA::cufft_static_nocallback starting in CUDA 9.2, requires CMake 3.23+
  • CUDA::cufftw_static

๐ŸŽฒ cuRAND ๐ŸŽฒ

The CUDA random number generation library โ€” https://docs.nvidia.com/cuda/curand, RNG icon behavior.

Targets Created:

  • CUDA::curand
  • CUDA::curand_static

๐Ÿ‘‘ cuSOLVER ๐Ÿ‘‘

A GPU accelerated linear system solver library, https://docs.nvidia.com/cuda/cusolver.

Targets Created:

  • CUDA::cusolver
  • CUDA::cusolver_static

๐ŸŒธ cuSPARSE ๐ŸŒธ

The CUDA sparse matrix library, https://docs.nvidia.com/cuda/cusparse.

Targets Created:

  • CUDA::cusparse
  • CUDA::cusparse_static

๐Ÿ” cupti ๐Ÿ”

The NVIDIA CUDA Profiling Tools Interface, https://developer.nvidia.com/cupti.

Targets Created:

  • CUDA::cupti
  • CUDA::cupti_static

Added in version 3.27:

  • CUDA::nvperf_host starting in CUDA 10.2
  • CUDA::nvperf_host_static starting in CUDA 10.2
  • CUDA::nvperf_target starting in CUDA 10.2
  • CUDA::pcsamplingutil starting in CUDA 11.3

๐ŸŽจ NPP ๐ŸŽจ

The NVIDIA 2D Image and Signal Processing Performance Primitives libraries, https://docs.nvidia.com/cuda/npp.

Targets Created:

  • nppc:
    • CUDA::nppc
    • CUDA::nppc_static
  • nppial: Arithmetic and logical operation functions in nppi_arithmetic_and_logical_operations.h
    • CUDA::nppial
    • CUDA::nppial_static
  • nppicc: Color conversion and sampling functions in nppi_color_conversion.h
    • CUDA::nppicc
    • CUDA::nppicc_static
  • nppicom: JPEG compression and decompression functions in nppi_compression_functions.h โ€” Removed starting in CUDA 11.0, use nvJPEG instead. ๐Ÿ’€
    • CUDA::nppicom
    • CUDA::nppicom_static
  • nppidei: Data exchange and initialization functions in nppi_data_exchange_and_initialization.h
    • CUDA::nppidei
    • CUDA::nppidei_static
  • nppif: Filtering and computer vision functions in nppi_filter_functions.h
    • CUDA::nppif
    • CUDA::nppif_static
  • nppig: Geometry transformation functions found in nppi_geometry_transforms.h
    • CUDA::nppig
    • CUDA::nppig_static
  • nppim: Morphological operation functions found in nppi_morphological_operations.h
    • CUDA::nppim
    • CUDA::nppim_static
  • nppist: Statistics and linear transform in nppi_statistics_functions.h and nppi_linear_transforms.h
    • CUDA::nppist
    • CUDA::nppist_static
  • nppisu: Memory support functions in nppi_support_functions.h
    • CUDA::nppisu
    • CUDA::nppisu_static
  • nppitc: Threshold and compare operation functions in nppi_threshold_and_compare_operations.h
    • CUDA::nppitc
    • CUDA::nppitc_static
  • npps:
    • CUDA::npps
    • CUDA::npps_static

โšก nvBLAS โšก

The GPU-accelerated drop-in BLAS library, https://docs.nvidia.com/cuda/nvblas. Heads up: this is a shared library only.

Targets Created:

  • CUDA::nvblas

๐Ÿ•ธ๏ธ nvGRAPH ๐Ÿ•ธ๏ธ

A GPU-accelerated graph analytics library, https://docs.nvidia.com/cuda/archive/10.0/nvgraph. Removed starting in CUDA 11.0 โ€” she's gone, bestie ๐Ÿ˜ญ

Targets Created:

  • CUDA::nvgraph
  • CUDA::nvgraph_static

๐Ÿ–ผ๏ธ nvJPEG ๐Ÿ–ผ๏ธ

A GPU-accelerated JPEG codec library, https://docs.nvidia.com/cuda/nvjpeg. Introduced in CUDA 10.

Targets Created:

  • CUDA::nvjpeg
  • CUDA::nvjpeg_static

๐Ÿงš nvPTX Compiler ๐Ÿงš

Added in version 3.25.

The PTX Compiler APIs, https://docs.nvidia.com/cuda/ptx-compiler-api. These are a set of APIs which can be used to compile a PTX program into GPU assembly code. Introduced in CUDA 11.1. Oh and btw, this is a static library only.

Targets Created:

  • CUDA::nvptxcompiler_static starting in CUDA 11.1

๐Ÿ”ฎ nvRTC ๐Ÿ”ฎ

A runtime compilation library for CUDA, https://docs.nvidia.com/cuda/nvrtc.

Targets Created:

  • CUDA::nvrtc

Added in version 3.26:

  • CUDA::nvrtc_builtins
  • CUDA::nvrtc_static starting in CUDA 11.5
  • CUDA::nvrtc_builtins_static starting in CUDA 11.5

The JIT Link APIs, https://docs.nvidia.com/cuda/nvjitlink.

Targets Created:

  • CUDA::nvJitLink starting in CUDA 12.0
  • CUDA::nvJitLink_static starting in CUDA 12.0

๐ŸŒˆ nvFatBin ๐ŸŒˆ

Added in version 3.30.

The Fatbin Creator APIs, https://docs.nvidia.com/cuda/nvfatbin.

Targets Created:

  • CUDA::nvfatbin starting in CUDA 12.4
  • CUDA::nvfatbin_static starting in CUDA 12.4

๐Ÿ“Š nvidia-ML ๐Ÿ“Š

The NVIDIA Management Library, https://developer.nvidia.com/management-library-nvml.

Targets Created:

  • CUDA::nvml
  • CUDA::nvml_static starting in CUDA 12.4

Added in version 3.31: Added CUDA::nvml_static.

๐Ÿงฐ nvToolsExt ๐Ÿงฐ

Deprecated since version 3.25: With CUDA 10.0+, use nvtx3. Starting in CUDA 12.9 the nvToolsExt library no longer exists. she's literally retired ๐Ÿ’€

The legacy NVIDIA Tools Extension, https://docs.nvidia.com/cuda/archive/9.0/profiler-users-guide#nvtx. FYI this is a shared library only.

Targets Created:

  • CUDA::nvToolsExt

๐ŸŒŸ nvtx3 ๐ŸŒŸ

Added in version 3.25.

The header-only NVIDIA Tools Extension library, https://nvidia.github.io/NVTX/doxygen. Introduced in CUDA 10.0.

Targets created:

  • CUDA::nvtx3
  • CUDA::nvtx3_interop

Added in version 4.1.

This is provided by CUDA 12.9 and above for use by languages that cannot consume C++ header-only libraries, such as Fortran. shoutout Fortran besties fr fr ๐Ÿซถ

โš™๏ธ OpenCL โš™๏ธ

The NVIDIA Open Computing Language library, https://developer.nvidia.com/opencl. Once again: this is a shared library only.

Targets Created:

  • CUDA::OpenCL

๐Ÿงต cuLIBOS ๐Ÿงต

The cuLIBOS library is a backend thread abstraction layer library which is static only. The CUDA::cublas_static, CUDA::cusparse_static, CUDA::cufft_static, CUDA::curand_static, and (when implemented) NPP libraries all automatically have this dependency linked.

Target Created:

  • CUDA::culibos
Note: direct usage of this target by consumers should not be necessary. like, she's backstage crew, not the main character ๐Ÿ’…

๐Ÿ› ๏ธ bin2c ๐Ÿ› ๏ธ

Added in version 4.3.

A utility that converts binary files to C files containing byte arrays.

Target Created:

  • CUDA::bin2c

๐Ÿงผ compute-sanitizer ๐Ÿงผ

Added in version 4.4.

The NVIDIA Compute Sanitizer library, https://docs.nvidia.com/compute-sanitizer, which allows the tracing of CUDA runtime and driver calls.

Target Created:

  • CUDA::sanitizer

๐Ÿฉน cufilt ๐Ÿฉน

Added in version 4.4.

The cu++filt binary utility โ€” docs at https://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#cu-filt โ€” also provides a static library for demangling CUDA C++ symbols.

Targets Created:

  • CUDA::cufilt starting in CUDA 11.4

๐Ÿ“‹ Result Variables ๐Ÿ“‹

This module defines the following variables:

  • CUDAToolkit_FOUND โ€” a boolean specifying whether or not the CUDA Toolkit was found.
  • CUDAToolkit_VERSION โ€” the exact version of the CUDA Toolkit found (as reported by nvcc --version, version.txt, or version.json).
  • CUDAToolkit_VERSION_MAJOR โ€” the major version of the CUDA Toolkit.
  • CUDAToolkit_VERSION_MINOR โ€” the minor version of the CUDA Toolkit.
  • CUDAToolkit_VERSION_PATCH โ€” the patch version of the CUDA Toolkit.
  • CUDAToolkit_BIN_DIR โ€” the path to the CUDA Toolkit library directory that contains the CUDA executable nvcc.
  • CUDAToolkit_INCLUDE_DIRS โ€” list of paths to all the CUDA Toolkit folders containing header files required to compile a project linking against CUDA.
  • CUDAToolkit_LIBRARY_DIR โ€” the path to the CUDA Toolkit library directory that contains the CUDA Runtime library cudart.
  • CUDAToolkit_LIBRARY_ROOT โ€” Added in version 3.18. The path to the CUDA Toolkit directory containing the nvvm directory and either version.txt or version.json.
  • CUDAToolkit_TARGET_DIR โ€” the path to the CUDA Toolkit directory including the target architecture when cross-compiling. When not cross-compiling this will be equivalent to the parent directory of CUDAToolkit_BIN_DIR.
  • CUDAToolkit_NVCC_EXECUTABLE โ€” the path to the NVIDIA CUDA compiler, nvcc. Heads up bestie: this path might not be the same as CMAKE_<LANG>_COMPILER. Also, nvcc genuinely has to be found, because that's how we figure out the CUDA Toolkit version and suss out the Toolkit's other features. This variable is set purely as a convenience for modules that depend on this one. ๐Ÿซถ

๐Ÿ’– FindCups

Finds the Common UNIX Printing System (CUPS):

find_package(Cups [<version>] [...]).

โœจ Imported Targets

This module hands you the following Imported Targets:

  • Cups::Cups โ€” added in version 3.15. The target encapsulating CUPS's usage requirements. It's only available if CUPS is actually found, so no phantom targets, no cap. ๐Ÿ‘‘

๐ŸŒธ Result Variables

This module defines these variables:

  • Cups_FOUND โ€” added in version 3.3. A boolean saying whether (the requested version of) CUPS was found. True or false, that's the whole vibe check.
  • Cups_VERSION โ€” added in version 4.2. The version of CUPS that got found.
  • CUPS_INCLUDE_DIRS โ€” the include directories you need to actually use CUPS.

๐ŸŽ€ Cache Variables

These cache variables may also get set:

  • CUPS_INCLUDE_DIR โ€” the directory holding the CUPS headers.
  • CUPS_LIBRARIES โ€” the libraries you need to link against to use CUPS.

๐Ÿฆ‹ Hints

This module accepts one variable, and it's a whole mouthful:

  • CUPS_REQUIRE_IPP_DELETE_ATTRIBUTE โ€” set this variable to TRUE to require the CUPS version that actually features the ippDeleteAttribute() function (i.e. at least CUPS 1.1.19). Like, don't skimp on the version, bestie.

๐Ÿ’… Deprecated Variables

These are provided for backward compatibility only:

  • CUPS_FOUND โ€” deprecated since version 4.2: use Cups_FOUND, which has the exact same value. Boolean indicating whether (the requested version of) CUPS was found.
  • CUPS_VERSION_STRING โ€” deprecated since version 4.2: superseded by Cups_VERSION. The version of CUPS found.

โญ Examples

Finding CUPS and linking it up to a project target:

find_package(Cups)
target_link_libraries(project_target PRIVATE Cups::Cups)

๐Ÿ”ฅ FindCURL

Finds the native curl installation โ€” include directories and libraries โ€” for transferring data with URLS:

find_package(CURL [<version>] [COMPONENTS <components>...] [...])

Added in version 3.17: if curl is built with its own CMake-based build system, it'll ship its own CMake Package Configuration file (CURLConfig.cmake) for use with the find_package() command in config mode. By default this module looks for that file first, and if it finds it, it just returns the results without doing anything extra. If the upstream configuration file isn't there, this module falls back to module mode and searches the standard locations. Bestie behaviour fr fr. ๐Ÿ˜Œ

Added in version 3.13: the Debug and Release library variants are found separately. No mixing, no matching, we keep them apart. ๐Ÿ’…

๐Ÿ’œ Components

Added in version 3.14.

This module supports optional components so you can detect which protocols and features are available in the installed curl (and yes, these can vary depending on the curl version):

Protocols: DICT FILE FTP FTPS GOPHER GOPHERS HTTP HTTPS IMAP IMAPS IPFS IPNS
           LDAP LDAPS MQTT POP3 POP3S RTMP RTMPS RTSP SCP SFTP SMB SMBS SMTP
           SMTPS TELNET TFTP WS WSS
Features:  alt-svc asyn-rr AsynchDNS brotli CAcert Debug ECH gsasl GSS-API
           HSTS HTTP2 HTTP3 HTTPS-proxy HTTPSRR IDN IPv6 Kerberos Largefile
           libz MultiSSL NTLM NTLM_WB PSL SPNEGO SSL SSLS-EXPORT SSPI
           threadsafe TLS-SRP TrackMemory Unicode UnixSockets zstd

You can list components in the find_package() command as required, meaning curl only counts as found if they're all there:

find_package(CURL [COMPONENTS <protocols>... <features>...])

Or you can check them optionally, which lets you handle things conditionally in your code:

find_package(CURL [OPTIONAL_COMPONENTS <protocols>... <features>...])

Go read the curl documentation for more info on which protocols and features are supported. Component names are case-sensitive and follow the upstream curl naming conventions, so don't go lowercase-girling them. ๐Ÿ™ˆ

๐Ÿงš Imported Targets

This module provides the following Imported Targets:

  • CURL::libcurl โ€” added in version 3.12. The target encapsulating curl's usage requirements, available if curl is found. Slay.

๐ŸŒˆ Result Variables

This module defines these variables:

  • CURL_FOUND โ€” boolean indicating whether (the requested version of) curl and all the required components were found.
  • CURL_VERSION โ€” added in version 4.0. The version of curl found. This supersedes CURL_VERSION_STRING.
  • CURL_<component>_FOUND โ€” added in version 3.14. Boolean indicating whether the specified component (a curl protocol or feature) was found.
  • CURL_INCLUDE_DIRS โ€” include directories containing curl/curl.h and the other headers you need to use curl.
Note: when curl is found via config mode, this variable is only available with curl version 8.9 or newer. ๐Ÿซ 
  • CURL_LIBRARIES โ€” the list of libraries you need to link against to use curl.
Note: when curl is found via module mode, this is a list of library file paths. In config mode, this variable is only available with curl version 8.9 or newer and contains a list of imported targets. Two different vibes, iykyk.

๐Ÿ“ Hints

This module accepts these variables:

  • CURL_NO_CURL_CMAKE โ€” added in version 3.17. Set this variable to TRUE to disable searching for curl via config mode. Sometimes you just wanna do it the old way.
  • CURL_USE_STATIC_LIBS โ€” added in version 3.28. Set this variable to TRUE to use static libraries. This only means anything when curl is not found via config mode. Context matters, bestie.

๐Ÿ’€ Deprecated Variables

This one's here for backward compatibility:

  • CURL_VERSION_STRING โ€” deprecated since version 4.0: superseded by CURL_VERSION. The version of curl found. Let it go, it's had its era. ๐Ÿ˜ญ

๐Ÿ‘‘ Examples

Finding the curl library and specifying the required minimum version:

find_package(CURL 7.61.0)

Finding the curl library and linking it to a project target:

find_package(CURL)
target_link_libraries(project_target PRIVATE CURL::libcurl)

Using components to check whether the found curl supports specific protocols or features:

find_package(CURL OPTIONAL_COMPONENTS HTTPS SSL)

if(CURL_HTTPS_FOUND)
  # curl supports the HTTPS protocol
endif()

if(CURL_SSL_FOUND)
  # curl has SSL feature enabled
endif()

๐ŸŽ€ FindCurses

Finds the curses or ncurses library:

find_package(Curses [...])

Curses is a terminal control library for Unix-like systems, used to build text user interface (TUI) applications. It was originally developed in 1978 โ€” yes, she's a vintage icon โ€” and has since evolved into multiple implementations, most notably ncurses (new curses), BSD curses, and PDCurses (a public domain curses library for non-Unix platforms). History lesson over, go make a TUI. โœจ

๐Ÿ’– Result Variables

This module defines these variables:

  • Curses_FOUND โ€” added in version 3.3. Boolean indicating whether Curses was found.
  • CURSES_INCLUDE_DIRS โ€” added in version 3.1. The include directories needed to use Curses.
  • CURSES_LIBRARIES โ€” the libraries needed to use Curses.
  • CURSES_CFLAGS โ€” added in version 3.16. Compiler flags which ought be given to C/C++ compilers when using Curses.
  • CURSES_HAVE_CURSES_H โ€” boolean indicating whether curses.h is available.
  • CURSES_HAVE_NCURSES_H โ€” boolean indicating whether ncurses.h is available.
  • CURSES_HAVE_NCURSES_NCURSES_H โ€” boolean indicating whether ncurses/ncurses.h is available.
  • CURSES_HAVE_NCURSES_CURSES_H โ€” boolean indicating whether ncurses/curses.h is available.

๐Ÿฆ‹ Hints

This module accepts these variables:

  • CURSES_NEED_NCURSES โ€” set this variable to TRUE before calling find_package(Curses) if you specifically require the ncurses implementation's functionality.
  • CURSES_NEED_WIDE โ€” added in version 3.10. Set this variable to TRUE before calling find_package(Curses) if Unicode (wide character) support is required. Wide chars or nothing. ๐ŸŒธ

๐Ÿ™ˆ Deprecated Variables

These are here for backward compatibility:

  • CURSES_FOUND โ€” deprecated since version 4.2: use Curses_FOUND, which has the same value. Boolean indicating whether Curses was found.
  • CURSES_INCLUDE_DIR โ€” deprecated since version 3.1: use the CURSES_INCLUDE_DIRS variable instead. Path to a Curses include directory.
  • CURSES_LIBRARY โ€” deprecated since version 2.4: use the CURSES_LIBRARIES variable instead. Path to Curses library.

๐ŸŒŸ Examples

Finding Curses and creating an imported interface target for linking it to a project target:

find_package(Curses)
if(Curses_FOUND AND NOT TARGET Curses::Curses)
  add_library(Curses::Curses INTERFACE IMPORTED)
  set_target_properties(
    Curses::Curses
    PROPERTIES
      INTERFACE_LINK_LIBRARIES "${CURSES_LIBRARIES}"
      INTERFACE_INCLUDE_DIRECTORIES "${CURSES_INCLUDE_DIRS}"
  )
endif()

add_executable(app app.c)
target_link_libraries(app PRIVATE Curses::Curses)

When ncurses is specifically required:

set(CURSES_NEED_NCURSES TRUE)
find_package(Curses)

๐ŸŽฏ FindCVS

Finds the Concurrent Versions System (CVS):

find_package(CVS [...])

โญ Result Variables

This module defines this variable:

  • CVS_FOUND โ€” boolean indicating whether the cvs command-line client was found.

๐Ÿ“ Cache Variables

This cache variable may also be set:

  • CVS_EXECUTABLE โ€” path to the cvs command-line client.

๐Ÿ’œ Examples

Finding CVS and executing it in a process:

find_package(CVS)
if(CVS_FOUND)
  execute_process(COMMAND ${CVS_EXECUTABLE} --help)
endif()

๐Ÿงš FindCxxTest

Finds CxxTest (https://github.com/CxxTest/cxxtest), a C++ unit testing framework suite, and hooks you up with a helper command to create test runners and integrate them with CTest:

find_package(CxxTest [...])

๐Ÿ”ฅ Result Variables

This module defines these variables:

  • CxxTest_FOUND โ€” added in version 4.2. Boolean indicating whether the CxxTest framework was found.
  • CXXTEST_INCLUDE_DIRS โ€” include directories containing the headers needed to use CxxTest.
  • CXXTEST_TESTGEN_EXECUTABLE โ€” the path to the found CxxTest test generator script (Perl- or Python-based), selected based on the found interpreter or the user-specified preference. She picks the one that fits, periodt. ๐Ÿ’…
  • CXXTEST_TESTGEN_INTERPRETER โ€” the path to whichever interpreter (Perl or Python) got found, the one used to run the test generator script when it's actually needed โ€” like, say, on platforms where script shebang lines are simply not supported ๐Ÿ˜ญ

๐Ÿ—„๏ธ Cache Variables

Bestie, these live in the cache, and yes you can set them too:

  • CXXTEST_PYTHON_TESTGEN_EXECUTABLE โ€” the path to the Python-based CxxTest test generator script.
  • CXXTEST_PERL_TESTGEN_EXECUTABLE โ€” the path to the Perl-based CxxTest test generator script.
โš ๏ธ Real talk: the Perl-based test generator script was removed in CxxTest version 4.0, in favor of the Python-based script. So don't be shocked when it ghosts you.

๐Ÿ’ก Hints

This module accepts the following variables before you call find_package(CxxTest):

  • CXXTEST_TESTGEN_ARGS โ€” set this to a semicolon-separated list of command-line options you wanna pass to the CxxTest code generator. If you don't set it, the default value is --error-printer. slay โœจ

๐Ÿ› ๏ธ Commands

This module hands you the following command if CxxTest is found:

  • cxxtest_add_test โ€” creates a CxxTest runner and adds it to the CTest testing suite:
cxxtest_add_test(<test-name> <gen-source-file> <input-files-to-testgen>...)

Parameters, one by one, no skipping:

  • <test-name> โ€” the name of the test executable target that gets created and registered as a test in the CTest suite.
  • <gen-source-file> โ€” the name of the source file that the CxxTest code generator will generate. This must be a relative path, and it's interpreted relative to the current binary directory (CMAKE_CURRENT_BINARY_DIR).
  • <input-files-to-testgen>... โ€” a list of header files containing test suite classes derived from the C++ class CxxTest::TestSuite, which get included in the test runner. These must be given as absolute paths โ€” like, actual full paths, no shortcuts ๐Ÿซถ

๐Ÿ‘ป Deprecated Variables

These are here purely for backward compatibility, iykyk:

  • CXXTEST_FOUND โ€” deprecated since version 4.2: use CxxTest_FOUND, which has the same value. Boolean indicating whether the CxxTest framework was found.
  • CXXTEST_USE_PYTHON โ€” deprecated since version 2.8.3: in earlier versions of CMake, this hint variable was used to force the Python-based test generator over the Perl one, no matter which scripting language was installed. Now it's only considered when both Perl and Python interpreters are found. A boolean hint variable that, when set to true, prefers the Python code generator over the Perl one if both interpreters are found. Only relevant when you're using CxxTest version 3.

๐ŸŒธ Examples

This example shows how CxxTest can be used in CMake with this module. If CxxTest is found:

  • An additional interface imported target is created manually in the project to encapsulate the CxxTest usage requirements, and it's linked to the specified tests. Such a target is useful, for example, when you're dealing with multiple tests.
  • The test generator gets invoked to create foo_test.cc in the current binary directory from the input header foo_test.h located in the current source directory.
  • An executable named unit_test_foo is built and registered as a test in CTest. periodt ๐Ÿ’…

CMakeLists.txt

find_package(CxxTest)

# Create interface imported target:
if(CxxTest_FOUND AND NOT TARGET CxxTest::CxxTest)
  add_library(CxxTest::CxxTest INTERFACE IMPORTED)
  set_target_properties(
    CxxTest::CxxTest
    PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${CXXTEST_INCLUDE_DIRS}"
  )
endif()

# Add test:
if(CxxTest_FOUND)
  enable_testing()

  cxxtest_add_test(
    unit_test_foo
    foo_test.cc
    ${CMAKE_CURRENT_SOURCE_DIR}/foo_test.h
  )

  target_link_libraries(
    unit_test_foo
    PRIVATE
      CxxTest::CxxTest
      # Link any project targets as needed, if test depends on them:
      foo
  )
endif()

foo_test.h

#include <cxxtest/TestSuite.h>

class MyTestSuite : public CxxTest::TestSuite
{
public:
  void testAddition(void)
  {
    TS_ASSERT(1 + 1 > 1);
    TS_ASSERT_EQUALS(1 + 1, 2);
  }
};

๐Ÿง FindCygwin

Finds Cygwin โ€” that POSIX-compatible environment that runs natively on Microsoft Windows:

find_package(Cygwin [...])
๐Ÿ“Œ Note: this module is primarily intended for use in other Find Modules to help locate programs when using the find_*() commands, like find_program(). In most cases, just using those commands directly is enough. Only reach for this module if a specific program is known to be installed via Cygwin and is usable from Windows.

๐Ÿ“Š Result Variables

This module defines the following variables:

  • Cygwin_FOUND โ€” added in version 4.2. Boolean indicating whether Cygwin was found. ๐Ÿ’–
  • CYGWIN_INSTALL_PATH โ€” the path to the Cygwin root installation directory.

โœจ Examples

Finding the Cygwin installation and using its path inside a custom find module:

FindFoo.cmake

find_package(Cygwin)
find_program(Foo_EXECUTABLE NAMES foo PATHS ${CYGWIN_INSTALL_PATH}/bin)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo REQUIRED_VARS Foo_EXECUTABLE)

๐Ÿ‘€ See Also

  • The FindMsys module, to find the MSYS path in a similar way.

๐Ÿฉป FindDCMTK

Finds the DICOM ToolKit (DCMTK) libraries and applications:

find_package(DCMTK [...])

DCMTK is a set of libraries and applications implementing large parts of the DICOM Standard โ€” that's Digital Imaging and Communications in Medicine, for the uninitiated ๐Ÿฉบ

Added in version 3.5: this module is now able to find a version of DCMTK that does or does not export a DCMTKConfig.cmake file.

DCMTK, since its version 3.6.1_20140617, supports and installs a package configuration file (DCMTKConfig.cmake) so it can be used with the find_package() command in config mode.

This module now runs a two-step process:

  1. Step 1: attempts to find a DCMTK version that provides a DCMTKConfig.cmake file, and if found, returns the results without any further action.
  2. Step 2: if step 1 failed, the module falls back to module mode (it searches standard locations) and sets the DCMTK_* result variables.

Until every client updates to the more recent DCMTK, build systems are gonna need to support different versions of DCMTK. That's just the vibe rn ๐Ÿ˜ญ

On any given system, the following combinations of DCMTK versions could be considered for the DCMTK installed on the system (for example, via a system package manager), or locally (for example, a custom installation, or through the FetchContent module):

  • Case A โ€” System DCMTK: N/A; Local DCMTK: [ ] DCMTKConfig; Supported? YES
  • Case B โ€” System DCMTK: N/A; Local DCMTK: [X] DCMTKConfig; Supported? YES
  • Case C โ€” System DCMTK: [ ] DCMTKConfig; Local DCMTK: N/A; Supported? YES
  • Case D โ€” System DCMTK: [X] DCMTKConfig; Local DCMTK: N/A; Supported? YES
  • Case E โ€” System DCMTK: [ ] DCMTKConfig; Local DCMTK: [ ] DCMTKConfig; Supported? YES (*)
  • Case F โ€” System DCMTK: [X] DCMTKConfig; Local DCMTK: [ ] DCMTKConfig; Supported? NO
  • Case G โ€” System DCMTK: [ ] DCMTKConfig; Local DCMTK: [X] DCMTKConfig; Supported? YES
  • Case H โ€” System DCMTK: [X] DCMTKConfig; Local DCMTK: [X] DCMTKConfig; Supported? YES

Legend, so you can read the above:

  • (*) โ€” see the Troubleshooting section.
  • N/A โ€” DCMTK is not available.
  • [ ] DCMTKConfig โ€” DCMTK does NOT export a DCMTKConfig.cmake file.
  • [X] DCMTKConfig โ€” DCMTK does export a DCMTKConfig.cmake file.

๐Ÿ“Š Result Variables

This module defines the following variables:

  • DCMTK_FOUND โ€” Boolean indicating whether DCMTK was found.
  • DCMTK_INCLUDE_DIRS โ€” include directories containing the headers you need to use DCMTK.
  • DCMTK_LIBRARIES โ€” the libraries you need to link against to use DCMTK.

๐Ÿ’ก Hints

This module accepts the following variables:

  • DCMTK_DIR โ€” (optional) source directory for DCMTK.

๐Ÿš‘ Troubleshooting

What do you do if the project finds a different version of DCMTK? ๐Ÿ˜ณ

Remove the DCMTK entry from the CMake cache, per the find_package() documentation, and re-run configuration. To find DCMTK on a custom location, use variables like CMAKE_PREFIX_PATH, or DCMTK_DIR.

๐ŸŒˆ Examples

Example: Finding DCMTK

Finding DCMTK with this module โ€” that's it, that's the whole thing:

find_package(DCMTK)

๐Ÿ’… Example: Finding DCMTK Without This Module

okay so picture this: you wanna be all independent and explicitly use the DCMTKConfig.cmake package configuration file โ€” which, ngl, is recommended when possible โ€” and find DCMTK in config mode without using this module. the move is literally just handing find_package() the NO_MODULE option:

find_package(DCMTK NO_MODULE)

๐ŸŽ€ Example: Creating Imported Target

in the next lil scenario, DCMTK gets searched with this module, and then an imported target is conditionally created to give you DCMTK usage requirements that you can painlessly link to your project targets. the vibe: if DCMTK is found in config mode, the DCMTK::DCMTK imported target will already be available through the found config files instead, so you don't gotta do anything:

find_package(DCMTK)

# Upstream DCMTKConfig.cmake already provides DCMTK::DCMTK imported target
if(DCMTK_FOUND AND NOT TARGET DCMTK::DCMTK)
  add_library(DCMTK::DCMTK INTERFACE IMPORTED)
  set_target_properties(
    DCMTK:DCMTK
    PROPERTIES
      INTERFACE_LINK_LIBRARIES "${DCMTK_LIBRARIES}"
      INTERFACE_INCLUDE_DIRECTORIES "${DCMTK_INCLUDE_DIRS}"
  )
endif()

target_link_libraries(example PRIVATE DCMTK::DCMTK)

๐Ÿฆ‹ FindDevIL ๐Ÿฆ‹

finds the Developer's Image Library, DevIL (over at https://openil.sourceforge.net/), bestie:

find_package(DevIL [<version>] [...])
โœจ Added in version 4.2: support for the <version> argument in the find_package() call. and yes, the version can also be specified as a range. iconic.

so the DevIL package is internally a whole squad of libraries, all distributed as part of the same release:

  • The core Image Library (IL) โ€” this one is always required when you're working with DevIL, because it provides the main image loading and manipulation functionality. it's the main character, fr.
  • The Image Library Utilities (ILU) โ€” depends on IL and provides image filters and effects. only required if your application actually uses this extended functionality.
  • The Image Library Utility Toolkit (ILUT) โ€” depends on both IL and ILU, and on top of that provides an interface to OpenGL. only needed if the application uses DevIL together with OpenGL.

๐Ÿ’– Imported Targets

this module provides the following Imported Targets:

  • DevIL::IL โ€” Added in version 3.21. target encapsulating the core Image Library (IL) usage requirements, available if the DevIL package is found.
  • DevIL::ILU โ€” Added in version 3.21. target encapsulating the Image Library Utilities (ILU) usage requirements, available if the DevIL package is found. this target also links to DevIL::IL for convenience, since ILU depends on the core IL library.
  • DevIL::ILUT โ€” Added in version 3.21. target encapsulating the Image Library Utility Toolkit (ILUT) usage requirements, available if the DevIL package and its ILUT library are found. this target also links to DevIL::ILU, and transitively to DevIL::IL, since ILUT depends on both. the way that dependency chain just works ๐Ÿ’…

๐ŸŒธ Result Variables

this module defines the following variables:

  • DevIL_FOUND โ€” Added in version 3.8. boolean indicating whether the (requested version of the) DevIL package was found, including the IL and ILU libraries.
  • DevIL_VERSION โ€” Added in version 4.2. the version of the DevIL found.
  • DevIL_ILUT_FOUND โ€” Added in version 3.21. boolean indicating whether the ILUT library was found. on most systems, ILUT is found when both IL and ILU are available.

๐Ÿงš Cache Variables

the following cache variables may also be set:

  • IL_INCLUDE_DIR โ€” the directory containing the il.h, ilu.h and ilut.h header files.
  • IL_LIBRARIES โ€” the full path to the core Image Library (IL).
  • ILU_LIBRARIES โ€” the full path to the ILU library.
  • ILUT_LIBRARIES โ€” the full path to the ILUT library.

โญ Examples

finding the DevIL package and linking against the core Image Library (IL) โ€” chef's kiss simple:

find_package(DevIL)
target_link_libraries(app PRIVATE DevIL::IL)

linking against the Image Library Utilities (ILU):

find_package(DevIL)
target_link_libraries(app PRIVATE DevIL::ILU)

linking against the Image Library Utility Toolkit (ILUT):

find_package(DevIL)
target_link_libraries(app PRIVATE DevIL::ILUT)

๐Ÿ”ฅ FindDoxygen ๐Ÿ”ฅ

finds Doxygen (over at https://www.doxygen.nl) โ€” that's the source code documentation generator, if you didn't know โ€” along with some optional supporting tools, and it hands you a command for integrating Doxygen-based documentation into your CMake projects. obsessed:

find_package(Doxygen [<version>] [COMPONENTS <components>...] [...])

๐ŸŽ€ Components

additional Doxygen supporting tools can be specified as components with the find_package() command:

find_package(Doxygen [COMPONENTS <components>...])

supported components include:

  • doxygen โ€” Added in version 3.9. finds the doxygen executable. this component is always automatically implied, even if you don't request it. it's the default bestie.
  • dot โ€” Added in version 3.9. finds the Graphviz (https://graphviz.org) dot utility, used for rendering graphs and diagrams as part of the documentation.
  • mscgen โ€” Added in version 3.9. finds the Message Chart Generator (https://www.mcternan.me.uk/mscgen/) utility used by Doxygen's \msc and \mscfile commands.
  • dia โ€” Added in version 3.9. finds the Dia (https://wiki.gnome.org/Apps/Dia) diagram editor used by Doxygen's \diafile command.

๐Ÿ’œ Imported Targets

this module provides the following Imported Targets, each of which is defined if the corresponding component was requested and its associated executable was found:

  • Doxygen::doxygen โ€” Added in version 3.9. imported executable target encapsulating the doxygen executable usage requirements, available if Doxygen is found.
  • Doxygen::dot โ€” Added in version 3.9. imported executable target encapsulating the dot executable usage requirements, available if the above dot component is found.
  • Doxygen::mscgen โ€” Added in version 3.9. imported executable target encapsulating the mscgen executable usage requirements, available if the above mscgen component is found.
  • Doxygen::dia โ€” Added in version 3.9. imported executable target encapsulating the dia executable usage requirements, available if the above dia component is found.

these targets can be used in commands such as add_custom_command() and are preferred over the older, now-deprecated variables like DOXYGEN_EXECUTABLE. like, please don't be using the deprecated ones, i'm begging ๐Ÿ™ˆ

๐ŸŒˆ Result Variables

this module defines the following variables:

  • Doxygen_FOUND โ€” Added in version 3.3. boolean indicating whether the (requested version of the) doxygen executable and all requested required components were found.
  • Doxygen_VERSION โ€” Added in version 4.2. the version of Doxygen found (as reported by doxygen --version).

๐Ÿ‘‘ Commands

this module provides the following command:

โœจ doxygen_add_docs โœจ

Added in version 3.9. adds a custom target for generating documentation with Doxygen during the build phase:

doxygen_add_docs(
  <target-name>
  [<files-or-dirs>...]
  [ALL]
  [USE_STAMP_FILE]
  [WORKING_DIRECTORY <dir>]
  [COMMENT <comment>]
  [CONFIG_FILE <file>]
)

by default, this convenience command also generates a configuration file named Doxyfile.<target-name> in the current binary directory at CMake configuration phase. it provides sensible defaults, so most projects literally only need to specify input files or directories. additional behavior and configuration can be customized using the variables described in the following sections.

the arguments are:

  • <target-name> โ€” the name of the target to be created for generating documentation with Doxygen.
  • <files-or-dirs>... โ€” one or more paths (files or directories) that serve as input sources for documentation. these are passed to the INPUT Doxygen configuration tag in the generated Doxyfile.<target-name>. files listed here are also added as SOURCES argument of the underlying add_custom_target() command, so they appear in the IDE project's source list. when using the USE_STAMP_FILE option, only files (not directories, symlinks, or wildcards) are allowed, and each must exist when this command is called. no cap.
  • ALL โ€” Added in version 3.12. adds the created documentation target to the default build target so that it runs automatically as part of the build phase.
  • USE_STAMP_FILE โ€” Added in version 3.16. enables use of a stamp file to avoid regenerating documentation unless source files have changed. stamp file named <target-name>.stamp is created in the current binary directory by an underlying custom command. with this option present, all entries in <files-or-dirs> must be existing files (i.e. no directories, symlinks or wildcards) when this command is called โ€” an error is raised if any listed path is invalid. without this option, CMake will re-run Doxygen every time the <target-name> target is built, regardless of whether any input source file listed in <files-or-dirs> has changed. so yeah, it's giving "rebuild the whole thing bestie" energy ๐Ÿ’€
  • WORKING_DIRECTORY <dir> โ€” by default, the Doxygen working directory is the current source directory (CMAKE_CURRENT_SOURCE_DIR). this aligns with using relative input paths. use this option to change and override the directory where Doxygen is being run โ€” the absolute path <dir> will then be used as the base point for relative paths. also note that Doxygen's default behavior is to strip the working directory from relative paths in the generated documentation. see the STRIP_FROM_PATH config tag in the Doxygen manual (https://www.doxygen.nl/manual/config.html) for more details.
  • COMMENT <comment> โ€” bestie if you pass this, the <comment> string gets handed straight to the add_custom_target() <#command:add_custom_target> command that builds the custom target under the hood. Translation: it shows up in the build system output whenever that target builds. cute little label for your build logs ๐Ÿ’…
  • CONFIG_FILE <file> โ€” Added in version 3.27. โœจ

If you set this, the file you give (with a full path, no shortcuts) is used as the Doxygen configuration file instead of the default Doxyfile.<target-name>. slay, custom config era ๐ŸŽ€


โœจ Variables for customizing Doxygen configuration โœจ

So doxygen_add_docs() generates a Doxygen configuration file full of config tags. Like, for example:

Doxygen.<target-name>

DOXYFILE_ENCODING      = UTF-8
PROJECT_NAME           = DoxygenExample
PROJECT_NUMBER         = 1.2.3
PROJECT_BRIEF          = "Example project using Doxygen"
PROJECT_LOGO           =
OUTPUT_DIRECTORY       = /home/user/doxygen-example/build
GENERATE_HTML          = YES
GENERATE_MAN           = NO
# ...

In CMake you can tweak these tags by setting input variables shaped like DOXYGEN_<tag>, where <tag> is one of the configuration tags listed in the Doxygen manual <https://www.doxygen.nl/manual/config.html>. iykyk ๐Ÿงš

For example, to change the GENERATE_HTML and GENERATE_MAN configuration tags, you set these variables before calling doxygen_add_docs():

CMakeLists.txt

find_package(Doxygen)

if(Doxygen_FOUND)
  set(DOXYGEN_GENERATE_HTML NO)
  set(DOXYGEN_GENERATE_MAN YES)

  doxygen_add_docs(project_docs ${PROJECT_SOURCE_DIR})
endif()

๐ŸŒธ Default configuration ๐ŸŒธ

By default, doxygen_add_docs() overrides a bunch of Doxygen's settings so they fit typical CMake projects better. Each of the following variables is explicitly set unless it was already defined before you called doxygen_add_docs() โ€” with a few exceptions noted below, because of course there are exceptions ๐Ÿ˜ญ

  • DOXYGEN_HAVE_DOT โ€” set to YES if the dot component was requested and found, NO otherwise. Any existing value of DOXYGEN_HAVE_DOT is ignored (the module said "not you" ๐Ÿ’€).
  • DOXYGEN_DOT_MULTI_TARGETS โ€” set to YES by this module (heads up: this needs a dot version newer than 1.8.10). This option only matters if DOXYGEN_HAVE_DOT is also set to YES.
  • DOXYGEN_GENERATE_LATEX โ€” set to NO by this module. no latex for u ๐Ÿ™ˆ
  • DOXYGEN_WARN_FORMAT โ€” for Visual Studio based generators, this gets set to the form the Visual Studio IDE recognizes: $file($line) : $text. For all other generators, Doxygen's default value is left alone, untouched, not overridden.
  • DOXYGEN_PROJECT_NAME โ€” filled in with the name of the current project (i.e. PROJECT_NAME <#variable:PROJECT_NAME>). ๐Ÿ‘‘
  • DOXYGEN_PROJECT_NUMBER โ€” filled in with the version of the current project (i.e. PROJECT_VERSION <#variable:PROJECT_VERSION>).
  • DOXYGEN_PROJECT_BRIEF โ€” filled in with the description of the current project (i.e. PROJECT_DESCRIPTION <#variable:PROJECT_DESCRIPTION>).
  • DOXYGEN_INPUT โ€” this one gets automatically filled with the list of files and directories you passed to doxygen_add_docs(). For consistent behavior with other built-in commands like add_executable() <#command:add_executable>, add_library() <#command:add_library>, and add_custom_target() <#command:add_custom_target>, projects should not set this variable manually. If a project does set a variable named DOXYGEN_INPUT, it gets ignored and a warning gets issued. don't do it, you'll get called out fr fr
  • DOXYGEN_RECURSIVE โ€” set to YES by this module.
  • DOXYGEN_EXCLUDE_PATTERNS โ€” if the <files-or-dirs> argument of doxygen_add_docs() contains directories, this variable specifies the patterns used to exclude files from them. These patterns are added by default so CMake-specific files and directories stay out of the input. If your project sets this variable, those contents get merged with these additional patterns rather than replacing them โ€” so no, you can't yeet them:
*/.git/*
*/.svn/*
*/.hg/*
*/CMakeFiles/*
*/_CPack_Packages/*
DartConfiguration.tcl
CMakeLists.txt
CMakeCache.txt
  • DOXYGEN_OUTPUT_DIRECTORY โ€” set to CMAKE_CURRENT_BINARY_DIR <#variable:CMAKE_CURRENT_BINARY_DIR> by this module. If the project supplies its own value for this and it's a relative path, it gets interpreted relative to the current binary directory (CMAKE_CURRENT_BINARY_DIR <#variable:CMAKE_CURRENT_BINARY_DIR>). This is necessary because Doxygen will normally be run from a directory within the source tree, so relative source paths work as expected. If that directory doesn't exist, it gets recursively created before Doxygen runs. โœจ it builds itself โœจ

๐Ÿฆ‹ Lists ๐Ÿฆ‹

So a number of Doxygen config tags accept lists of values, and Doxygen wants them separated by whitespace โ€” meanwhile in CMake a list is a string with items separated by semicolons <#cmake-language-lists>. different love languages, basically ๐Ÿ˜ญ

doxygen_add_docs() specifically checks for the following Doxygen config tags and, if set, converts their associated CMake DOXYGEN_<tag> variable values into Doxygen-formatted lists:

  • ABBREVIATE_BRIEF
  • ALIASES
  • CITE_BIB_FILES
  • DIAFILE_DIRS
  • DOTFILE_DIRS
  • DOT_FONTPATH
  • ENABLED_SECTIONS
  • EXAMPLE_PATH
  • EXAMPLE_PATTERNS
  • EXCLUDE
  • EXCLUDE_PATTERNS
  • EXCLUDE_SYMBOLS
  • EXPAND_AS_DEFINED
  • EXTENSION_MAPPING
  • EXTRA_PACKAGES
  • EXTRA_SEARCH_MAPPINGS
  • FILE_PATTERNS
  • FILTER_PATTERNS
  • FILTER_SOURCE_PATTERNS
  • HTML_EXTRA_FILES
  • HTML_EXTRA_STYLESHEET
  • IGNORE_PREFIX
  • IMAGE_PATH
  • INCLUDE_FILE_PATTERNS
  • INCLUDE_PATH
  • INPUT
  • LATEX_EXTRA_FILES
  • LATEX_EXTRA_STYLESHEET
  • MATHJAX_EXTENSIONS
  • MSCFILE_DIRS
  • PLANTUML_INCLUDE_PATH
  • PREDEFINED
  • QHP_CUST_FILTER_ATTRS
  • QHP_SECT_FILTER_ATTRS
  • STRIP_FROM_INC_PATH
  • STRIP_FROM_PATH
  • TAGFILES
  • TCL_SUBST

For example, to customize the Doxygen file patterns, you just set a normal semicolon-separated list <#cmake-language-lists> in CMake:

CMakeLists.txt

find_package(Doxygen)

if(Doxygen_FOUND)
  set(DOXYGEN_FILE_PATTERNS *.c *.cxx *.h *.hxx)
  doxygen_add_docs(example_docs ${CMAKE_CURRENT_SOURCE_DIR} ALL)
endif()

Which produces a Doxygen list of patterns separated by spaces in the generated configuration file:

Doxyfile.<target-name>

# ...
FILE_PATTERNS          = *.c *.cxx *.h *.hxx

look at that conversion happen. chef's kiss ๐Ÿ”ฅ

๐Ÿ’œ Automatic quoting ๐Ÿ’œ

If a Doxygen single-value tag contains spaces, its value has to be surrounded by double quotes ("..."). doxygen_add_docs() automatically quotes the values of the following Doxygen tags when it generates the Doxyfile, if they contain at least one space:

  • CHM_FILE
  • DIA_PATH
  • DOCBOOK_OUTPUT
  • DOCSET_FEEDNAME
  • DOCSET_PUBLISHER_NAME
  • DOT_FONTNAME
  • DOT_PATH
  • EXTERNAL_SEARCH_ID
  • FILE_VERSION_FILTER
  • GENERATE_TAGFILE
  • HHC_LOCATION
  • HTML_FOOTER
  • HTML_HEADER
  • HTML_OUTPUT
  • HTML_STYLESHEET
  • INPUT_FILTER
  • LATEX_FOOTER
  • LATEX_HEADER
  • LATEX_OUTPUT
  • LAYOUT_FILE
  • MAN_OUTPUT
  • MAN_SUBDIR
  • MATHJAX_CODEFILE
  • MSCGEN_PATH
  • OUTPUT_DIRECTORY
  • PERL_PATH
  • PLANTUML_JAR_PATH
  • PROJECT_BRIEF
  • PROJECT_LOGO
  • PROJECT_NAME
  • QCH_FILE
  • QHG_LOCATION
  • QHP_CUST_FILTER_NAME
  • QHP_VIRTUAL_FOLDER
  • RTF_EXTENSIONS_FILE
  • RTF_OUTPUT
  • RTF_STYLESHEET_FILE
  • SEARCHDATA_FILE
  • USE_MDFILE_AS_MAINPAGE
  • WARN_FORMAT
  • WARN_LOGFILE
  • XML_OUTPUT
  • DOXYGEN_VERBATIM_VARS โ€” Added in version 3.11. โญ

This is a CMake input variable used by doxygen_add_docs() to specify a list of Doxygen input variables (including their leading DOXYGEN_ prefix) whose values should be passed to the generated Doxyfile configuration without automatic quoting.

When you use this variable, your project is then responsible for making sure those variables' values actually make sense when dropped directly into the generated Doxyfile configuration. For list variables, items are still separated by spaces in the output, but no quoting is applied to the individual items. that's on you now bestie ๐Ÿซถ

For certain Doxygen tags, such as ALIASES, the automatic quoting done by doxygen_add_docs() may interfere with correct syntax (e.g., embedded quotes). so yeah, that's literally why this variable exists ๐Ÿ’…

So like, <#bracket-argument> bracket syntax is literally your bestie here โ€” it makes dealing with embedded quotes so much less of a nightmare. For example, this next bit will quote DOXYGEN_PROJECT_BRIEF but skip each item in the DOXYGEN_ALIASES list:

CMakeLists.txt

find_package(Doxygen)

if(Doxygen_FOUND)
  set(DOXYGEN_PROJECT_BRIEF "String with spaces")
  set(
    DOXYGEN_ALIASES
    [[somealias="@some_command param"]]
    "anotherAlias=@foobar"
  )
  set(DOXYGEN_VERBATIM_VARS DOXYGEN_ALIASES)

  add_doxygen_docs(project_docs ${PROJECT_SOURCE_DIR})
endif()

And the resultant Doxyfile config comes out looking like this:

Doxyfile.project_docs

PROJECT_BRIEF = "String with spaces"
ALIASES       = somealias="@some_command param" anotherAlias=@foobar

Deprecated Variables ๐Ÿ’€

Okay so for compatibility with previous versions of CMake, these variables are also defined โ€” but bestie, they're deprecated and you should genuinely not be using them anymore:

  • DOXYGEN_FOUND โ€” Deprecated since version 4.2: use Doxygen_FOUND instead.

Boolean indicating whether the (requested version of) doxygen executable and all requested required components were found. It has a boolean value of YES or NO.

  • DOXYGEN_EXECUTABLE โ€” Deprecated since version 3.9: use the Doxygen::doxygen imported target instead of referring to the doxygen executable directly.

Cache variable containing the path to the doxygen command.

  • DOXYGEN_DOT_FOUND โ€” Deprecated since version 3.9: use Doxygen_dot_FOUND.

Boolean result variable indicating whether dot executable was found.

  • DOXYGEN_DOT_EXECUTABLE โ€” Deprecated since version 3.9: use the Doxygen::dot imported target instead of referring to the dot executable directly.

Cache variable containing the path to the dot command-line executable.

  • DOXYGEN_DOT_PATH โ€” Deprecated since version 3.9.

Result variable containing the path to the directory where the dot executable is located as reported in DOXYGEN_DOT_EXECUTABLE. The path may have forward slashes even on Windows and is not suitable for direct substitution into a Doxyfile.in template. If you actually need this value, get the IMPORTED_LOCATION <#prop_tgt:IMPORTED_LOCATION> property of the Doxygen::dot target and use get_filename_component() <#command:get_filename_component> to extract the directory part of that path. Also consider using file(TO_NATIVE_PATH) <#to-native-path> to prepare the path for a Doxygen configuration file. ๐Ÿ’…

  • DOXYGEN_SKIP_DOT โ€” Deprecated since version 3.9.

This hint variable has no effect when specifying components in find_package(Doxygen COMPONENTS ...). In backward-compatibility mode (i.e. without specifying components) it prevents this find module from searching for Graphviz's dot utility.

  • DOXYGEN_VERSION โ€” Deprecated since version 4.2: superseded by Doxygen_VERSION.

The version of Doxygen found.


Examples โœจ

Examples: Finding Doxygen ๐Ÿ”

Finding Doxygen, that's it, that's the vibe:

find_package(Doxygen)

Or โ€” finding Doxygen and specifying a minimum required version:

find_package(Doxygen 1.9)

Or โ€” finding Doxygen and making it required (if it's not found, processing stops with an error message, no chill):

find_package(Doxygen REQUIRED)

Or โ€” finding Doxygen as required, with dot tool as a required component and mscgen and dia tools as optional components:

find_package(Doxygen REQUIRED COMPONENTS dot OPTIONAL_COMPONENTS mscgen dia)

Example: Using Doxygen in CMake ๐Ÿ‘‘

This one's a whole demo of how to find Doxygen and create documentation from source files at build phase. Once the project is built, the generated documentation files will be located in the html directory inside the project binary directory. Iconic.

CMakeLists.txt

cmake_minimum_required(VERSION 3.24)
project(
  DoxygenExample
  DESCRIPTION "Example project using Doxygen"
  VERSION 1.2.3
)

add_executable(example example.c)

find_package(Doxygen)

if(Doxygen_FOUND)
  doxygen_add_docs(project_docs example.c ALL USE_STAMP_FILE)
endif()

example.c

/**
 * @file example.c
 * @brief A simple example to demonstrate Doxygen.
 */

#include <stdio.h>

/**
 * @brief Calculates the sum of two integers.
 *
 * @param a First integer.
 * @param b Second integer.
 * @return Sum of a and b.
 *
 * @par Example
 * @code
 * int result = sum(3, 4);
 * printf("%d\n", result); // Outputs: 7
 * @endcode
 */
int sum(int a, int b) { return a + b; }

/**
 * @brief Main function.
 *
 * @return 0 on success.
 */
int main(void)
{
  int result = sum(5, 7);
  printf("Result: %d\n", result);
  return 0;
}

Example: Configuring Doxygen With Variables ๐ŸŽ€

In the following example, Doxygen configuration is customized using CMake variables. The configuration sets file patterns when using a directory as the source input (CMAKE_CURRENT_SOURCE_DIR <#variable:CMAKE_CURRENT_SOURCE_DIR>), enables a theme toggle for switching between light and dark modes, suppresses Doxygen's standard output during the build phase, specifies a Markdown file as the main page, and disables warnings about undocumented code:

find_package(Doxygen)

if(Doxygen_FOUND)
  set(DOXYGEN_FILE_PATTERNS *.c *.cxx *.md)
  set(DOXYGEN_HTML_COLORSTYLE "TOGGLE")
  set(DOXYGEN_QUIET YES)
  set(DOXYGEN_USE_MDFILE_AS_MAINPAGE "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
  set(DOXYGEN_WARN_IF_UNDOCUMENTED NO)

  doxygen_add_docs(example_docs ${CMAKE_CURRENT_SOURCE_DIR} ALL)
endif()

Example: Custom Configuration File ๐ŸŒธ

Here a custom Doxyfile configuration file is created in the current binary directory (CMAKE_CURRENT_BINARY_DIR <#variable:CMAKE_CURRENT_BINARY_DIR>) before calling doxygen_add_docs(). That way you can customize project-specific config tags however you need:

CMakeLists.txt

find_package(Doxygen)

if(Doxygen_FOUND)
  configure_file(Doxyfile.in Doxyfile)

  doxygen_add_docs(
    example_docs
    foo.c bar.c
    ALL
    USE_STAMP_FILE
    COMMENT "Generating project documentation with custom Doxyfile"
    CONFIG_FILE ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile
  )
endif()

Doxyfile.in

PROJECT_NAME           = "Customized project name"
OUTPUT_DIRECTORY       = "@CMAKE_CURRENT_BINARY_DIR@"
# ...

FindEnvModules ๐Ÿงš

Added in version 3.15.

Finds an Environment Modules implementation and provides commands for use in CMake scripts:

find_package(EnvModules [...])

The Environment Modules system is a command-line tool that manages Unix-like shell environments by dynamically modifying environment variables. It's commonly used in High-Performance Computing (HPC) environments to support multiple software versions or configurations. Very much the main character of HPC setups, honestly.

This module is compatible with the two most common implementations:

  • Lua-based Lmod
  • TCL-based Environment Modules

This module is primarily intended for setting up compiler and library environments within a CTest Script <#ctest-script> (ctest -S). It may also be used in a CMake Script <#script-processing-mode> (cmake -P).

Note: the loaded environment will not persist beyond the end of the calling process. Do not use this module in CMake project code (such as CMakeLists.txt) to load compiler environments โ€” the environment changes won't be available during the build phase, and then you'll be sad ๐Ÿ˜ญ. In such a case, load the desired environment before invoking CMake or the generated build system. Periodt.

Result Variables ๐Ÿ“‹

This module defines the following variables:

  • EnvModules_FOUND โ€” Boolean indicating whether a compatible Environment Modules framework was found.

Cache Variables ๐Ÿ—‚๏ธ

The following cache variables may also be set:

  • EnvModules_COMMAND โ€” the path to a low level module command to use.

Hints ๐Ÿ’ก

This module accepts the following variables before calling the find_package(EnvModules):

  • ENV{MODULESHOME} โ€” this environment variable is usually set by the Environment Modules implementation, and can be used as a hint to locate the module command to execute.

Commands ๐Ÿซถ

This module provides the following commands for interacting with the Environment Modules system, if found:

env_module

Executes an arbitrary module command:

env_module(<command> <args>...)
env_module(
  COMMAND <command> <args>...
  [OUTPUT_VARIABLE <out-var>]
  [RESULT_VARIABLE <ret-var>]
)

The options are:

  • COMMAND <command> <args>... โ€” the module sub-command and arguments to execute, as if passed directly to the module command in the shell environment.
  • OUTPUT_VARIABLE <out-var> โ€” stores the standard output of the executed module command in the specified variable.
  • RESULT_VARIABLE <ret-var> โ€” stores the return code of the executed module command in the specified variable.

env_module_swap

Swaps one module for another:

env_module_swap(
  <out-mod>
  <in-mod>
  [OUTPUT_VARIABLE <out-var>]
  [RESULT_VARIABLE <ret-var>]
)

This is functionally equivalent to the module swap <out-mod> <in-mod> shell command.

The options are:

  • OUTPUT_VARIABLE <out-var> โ€” stores the standard output of the executed module command in the specified variable.
  • RESULT_VARIABLE <ret-var> โ€” stores the return code of the executed module command in the specified variable.

env_module_list

Retrieves the list of currently loaded modules:

env_module_list(<out-var>)

This is functionally equivalent to the module list shell command. The result is stored in <out-var> as a properly formatted CMake semicolon-separated list <#cmake-language-lists> variable. Slay. ๐Ÿ”ฅ

env_module_avail โ€” bestie, this one just asks what's out there. It retrieves the list of available modules:

env_module_avail([<mod-prefix>] <out-var>)

It's functionally equivalent to running the module avail <mod-prefix> shell command, just โœจcivilizedโœจ. The result lands in <out-var> as a properly formatted CMake semicolon-separated list variable (you know the one, #cmake-language-lists ๐Ÿซถ).

๐ŸŒธ Examples ๐ŸŒธ

Okay so picture this: a CTest script setting up a whole Cray Programming Environment, and our module is the main character. Once the Environment Modules system is found, env_module() is used to load the necessary compiler, MPI and scientific libraries to set up the build environment. The CRAYPE_LINK_TYPE environment variable gets set to dynamic to specify dynamic linking โ€” this tells the Cray Linux Environment compiler driver to link against dynamic libraries at runtime instead of linking static libraries at compile time, so the compiler produces dynamically linked executable files. ๐Ÿ’…

example-script.cmake

set(CTEST_BUILD_NAME "CrayLinux-CrayPE-Cray-dynamic")
set(CTEST_BUILD_CONFIGURATION Release)
set(CTEST_BUILD_FLAGS "-k -j8")
set(CTEST_CMAKE_GENERATOR "Unix Makefiles")

# ...

find_package(EnvModules REQUIRED)

# Clear all currently loaded Environment Modules to start with a clean state
env_module(purge)

# Load the base module-handling system to use other modules
env_module(load modules)

# Load Cray Programming Environment (Cray PE) support, which manages
# platform-specific optimizations and architecture selection
env_module(load craype)

# Load the Cray programming environment
env_module(load PrgEnv-cray)

# Load settings targeting the Intel Knights Landing (KNL) CPU architecture
env_module(load craype-knl)

# Load the Cray MPI (Message Passing Interface) library, needed for
# distributed computing
env_module(load cray-mpich)

# Load Cray's scientific library package, which includes optimized math
# libraries (like BLAS, LAPACK)
env_module(load cray-libsci)

set(ENV{CRAYPE_LINK_TYPE} dynamic)

# ...

๐Ÿฆ‹ FindEXPAT ๐Ÿฆ‹

Finds the native Expat headers and library, no cap:

find_package(EXPAT [<version>] [...])

Expat is a stream-oriented XML parser library written in C. That's it, that's the whole vibe. ๐Ÿ˜Œ

๐Ÿ’œ Imported Targets ๐Ÿ’œ

This module provides the following Imported Targets (#imported-targets):

  • EXPAT::EXPAT โ€” Added in version 3.10. Target encapsulating the Expat library (expat) usage requirements. It's only available if Expat is actually found, so don't come for it if it's not there.

โœจ Result Variables โœจ

This module defines the following variables:

  • EXPAT_FOUND โ€” Boolean indicating whether (the requested version of) Expat was found.
  • EXPAT_VERSION โ€” Added in version 4.2. The version of Expat found. Obsessed with her.
  • EXPAT_INCLUDE_DIRS โ€” Include directories containing expat.h and related headers needed to use Expat.
  • EXPAT_LIBRARIES โ€” Libraries you need to link against to use Expat.

๐ŸŽ€ Hints ๐ŸŽ€

This module accepts the following variables:

  • EXPAT_USE_STATIC_LIBS โ€” Added in version 3.28. Set it to TRUE to use static libraries. Also: Added in version 3.31: Implemented on non-Windows platforms. ๐Ÿซถ

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

The following variables are provided for backward compatibility only, iykyk:

  • EXPAT_VERSION_STRING โ€” Deprecated since version 4.2: Superseded by the EXPAT_VERSION. The version of Expat found.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding the Expat library and linking it to a project target โ€” literal perfection:

find_package(EXPAT)
target_link_libraries(project_target PRIVATE EXPAT::EXPAT)

๐Ÿงš FindFLEX ๐Ÿงš

Finds the Fast Lexical Analyzer (Flex) command-line generator and its library, and hands you CMake commands to create custom build rules for using Flex:

find_package(FLEX [<version>] [...])

Flex generates lexical analyzers, also known as scanners or lexers. It also includes a runtime library (fl) that supplies support functions for the generated scanners โ€” input handling, buffer management, and error reporting. She does it all ๐Ÿ’….

โญ Result Variables โญ

This module defines the following variables:

  • FLEX_FOUND โ€” Boolean indicating whether (the requested version of) Flex was found.
  • FLEX_VERSION โ€” The version of Flex found.
  • FLEX_INCLUDE_DIRS โ€” The include directories containing headers for using the Flex library.
  • FLEX_LIBRARIES โ€” The libraries needed to link against to use the Flex library.

๐Ÿ“ Cache Variables ๐Ÿ“

The following cache variables may also be set:

  • FLEX_EXECUTABLE โ€” The path to the flex executable.

๐Ÿ‘‘ Commands ๐Ÿ‘‘

This module provides the following commands if flex is found:

๐Ÿ”ฅ Generating Scanners ๐Ÿ”ฅ

flex_target

Creates a custom build rule to generate a scanner file from a lex file using Flex:

flex_target(
  <name>
  <input-lex-file>
  <output-scanner-file>
  [DEFINES_FILE <header>]
  [OPTIONS <options>...]
  [COMPILE_FLAGS <string>] # Deprecated
)

Changed in version 3.17: When policy CMP0098 (#policy:CMP0098) is set to NEW, flex runs in the CMAKE_CURRENT_BINARY_DIR (#variable:CMAKE_CURRENT_BINARY_DIR) directory. Periodt.

  • <name> โ€” String used as an identifier for this command invocation.
  • <input-lex-file> โ€” The path to an input Flex source file (.l). If given as a relative path, it will be interpreted relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR, #variable:CMAKE_CURRENT_SOURCE_DIR).
  • <output-scanner-file> โ€” The path of the output file to be generated by Flex. If given as a relative path, it will be interpreted relative to the current Flex working directory.
  • DEFINES_FILE <header> โ€” Added in version 3.5. If Flex is configured to output a header file, this option may be used to specify its name. If given as a relative path, it will be interpreted relative to the current Flex working directory.
  • OPTIONS <options>... โ€” Added in version 4.0. A semicolon-separated list (#cmake-language-lists) of extra options added to the flex command line.
  • COMPILE_FLAGS <string> โ€” Deprecated since version 4.0: Superseded by OPTIONS <options>.... A string of space-separated extra options added to the flex command line. A semicolon-separated list (#cmake-language-lists) will not work โ€” not me warning you twice ๐Ÿ™ˆ.

Command variables

This command also defines the following variables:

  • FLEX_<name>_DEFINED โ€” Boolean indicating whether this command was successfully invoked.
  • FLEX_<name>_INPUT โ€” The Flex source file, an alias for <input-lex-file>.
  • FLEX_<name>_OUTPUT_HEADER โ€” Added in version 3.5. The header file generated by flex, if any.
  • FLEX_<name>_OUTPUTS โ€” A list of files generated by flex, including the output scanner file, and the header file.
  • FLEX_<name>_OPTIONS โ€” Added in version 4.0. A list of command-line options used for the flex command.

๐ŸŽ€ Adding Dependency Between Scanner and Parser ๐ŸŽ€

add_flex_bison_dependency

Adds the required dependency between a scanner and a parser:

add_flex_bison_dependency(<flex-name> <bison-name>)

Flex scanners often rely on token definitions generated by Bison, meaning the code produced by Flex depends on the header file created by Bison. So this command wires up the required dependency between a scanner and a parser, where <flex-name> and <bison-name> are the first parameters of respectively flex_target(<name> ...) and bison_target(<name> ...) (#command:bison_target) commands. Matching besties fr fr ๐Ÿซถ.

๐ŸŒธ Examples ๐ŸŒธ

Examples: Finding Flex

Finding Flex, the classic:

find_package(FLEX)

Finding Flex and specifying its minimum required version:

find_package(FLEX 2.5.13)

Finding Flex and making it required (if Flex is not found, processing stops with an error message โ€” no soft launches here):

find_package(FLEX 2.5.13 REQUIRED)

Example: Generating Scanner

Finding Flex and generating a scanner source file in the current binary directory from the lex source file in the current source directory:

find_package(FLEX)

if(FLEX_FOUND)
  flex_target(MyScanner lexer.l lexer.cpp)
endif()

add_executable(foo foo.cc ${FLEX_MyScanner_OUTPUTS})

Example: Command-line Options

Adding additional command-line options to the flex executable can be passed as a list. For example, adding the --warn option to report warnings, and the --noline (-L) to not generate #line directives:

find_package(FLEX)

if(FLEX_FOUND)
  flex_target(MyScanner lexer.l lexer.cpp OPTIONS --warn --noline)
endif()

Generator expressions (#manual:cmake-generator-expressions(7)) can be used in the OPTIONS <options>... argument. For example, to add the --debug (-d) option only for the Debug build type:

find_package(FLEX)

if(FLEX_FOUND)
  flex_target(MyScanner lexer.l lexer.cpp OPTIONS $<$<CONFIG:Debug>:--debug>)
endif()

Example: Using Flex Library

Finding Flex and creating an interface imported target (#imported-targets) that encapsulates its library usage requirements for linking to a project target:

find_package(FLEX)

if(FLEX_FOUND AND NOT TARGET FLEX::fl)
  add_library(FLEX::fl INTERFACE IMPORTED)
  set_target_properties(
    FLEX::fl
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${FLEX_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${FLEX_LIBRARIES}"
  )
endif()

if(FLEX_FOUND)
  flex_target(MyScanner lexer.l lexer.cpp)
endif()

add_executable(Foo foo.cc ${FLEX_MyScanner_OUTPUTS})
target_link_libraries(Foo PRIVATE FLEX::fl)

Example: Using Flex and Bison

The following example demonstrates how to use Flex and Bison (#module:FindBISON) in CMake โ€” the iconic duo, honestly:

find_package(BISON)
find_package(FLEX)

if(BISON_FOUND AND FLEX_FOUND)
  bison_target(MyParser parser.y parser.cpp)
  flex_target(MyScanner lexer.l lexer.cpp)
  add_flex_bison_dependency(MyScanner MyParser)
endif()

add_executable(Foo foo.cc ${BISON_MyParser_OUTPUTS} ${FLEX_MyScanner_OUTPUTS})

# ...

See Also

  • The FindBISON module to find that Bison parser generator bestie ๐Ÿ‚โœจ

๐ŸŽจ FindFLTK ๐ŸŽจ

Finds the Fast Light Toolkit (FLTK), a cross-platform toolkit for GUI development, iykyk:

find_package(FLTK [...])

Okay so FLTK uses a CMake-based build system and ships a package configuration file so projects can find it โ€” slay ๐Ÿ’…. As of its 1.4.0 version it also provides Imported Targets <#imported-targets> that encapsulate usage requirements. For example, fltk::fltk, which can be linked to project targets where FLTK is needed. This module takes that into account and first attempts to find FLTK in config mode. If the configuration file is not available, it falls back to module mode and searches standard locations. Also see the official FLTK documentation for more info on how to use FLTK with CMake ๐Ÿซถ

Added in version 3.11: Debug and release (optimized) library variants are found separately and use per-configuration <#build-configurations> variables. So organized of them โœจ

๐Ÿ“‹ Result Variables

This module defines the following variables:

  • FLTK_FOUND โ€” Boolean indicating whether FLTK was found ๐Ÿ’–
  • FLTK_LIBRARIES โ€” Libraries needed to link against to use FLTK.
  • FLTK_WRAP_UI โ€” Boolean indicating whether the fluid executable is found. This variable is available only if FLTK is found in module mode, and can be used, for example, to conditionally invoke the fltk_wrap_ui() <#command:fltk_wrap_ui> command if it is needed and available ๐ŸŒธ

๐Ÿ—‚๏ธ Cache Variables

The following cache variables are also available to set or use:

  • FLTK_FLUID_EXECUTABLE โ€” The path to the fluid binary tool.
  • FLTK_INCLUDE_DIR โ€” The include directory containing header files needed to use FLTK.
  • FLTK_BASE_LIBRARY_RELEASE โ€” Added in version 3.11. The path to the release (optimized) FLTK base library.
  • FLTK_BASE_LIBRARY_DEBUG โ€” Added in version 3.11. The path to the debug FLTK base library.
  • FLTK_GL_LIBRARY_RELEASE โ€” Added in version 3.11. The path to the release (optimized) FLTK GL library.
  • FLTK_GL_LIBRARY_DEBUG โ€” Added in version 3.11. The path to the debug FLTK GL library.
  • FLTK_FORMS_LIBRARY_RELEASE โ€” Added in version 3.11. The path to the release (optimized) FLTK Forms library.
  • FLTK_FORMS_LIBRARY_DEBUG โ€” Added in version 3.11. The path to the debug FLTK Forms library.
  • FLTK_IMAGES_LIBRARY_RELEASE โ€” Added in version 3.11. The path to the release (optimized) FLTK Images protobuf library.
  • FLTK_IMAGES_LIBRARY_DEBUG โ€” Added in version 3.11. The path to the debug FLTK Images library.

๐ŸŽ›๏ธ Input Variables

By default, this module searches for all FLTK libraries and its fluid executable. The following variables can be set before calling find_package(FLTK) to indicate which elements are optional for a successful configuration:

  • FLTK_SKIP_FLUID โ€” Set to boolean true to mark the fluid executable as optional.
  • FLTK_SKIP_FORMS โ€” Set to boolean true to mark the FLTK Forms library as optional; it will therefore not be included in the FLTK_LIBRARIES result variable.
  • FLTK_SKIP_IMAGES โ€” Set to boolean true to mark the FLTK Image library as optional; it will therefore not be included in the FLTK_LIBRARIES result variable.
  • FLTK_SKIP_OPENGL โ€” Set to boolean true to mark the FLTK OpenGL library as optional; it will therefore not be included in the FLTK_LIBRARIES result variable.

โœจ Examples โœจ

Finding FLTK and conditionally creating a fltk::fltk imported interface target, if it is not provided by the upstream FLTK package. The imported target can then be linked to a project target:

find_package(FLTK)

if(FLTK_FOUND AND NOT TARGET fltk::fltk)
  add_library(fltk::fltk INTERFACE IMPORTED)
  set_target_properties(
    fltk::fltk
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${FLTK_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${FLTK_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE fltk::fltk)

๐Ÿฆ‹ FindFLTK2 ๐Ÿฆ‹

Note: This module is specifically for FLTK version 2.x. The 2.0 series was originally a development branch intended as the next major version of FLTK. However, it never reached stable release status, and active development has shifted back to the FLTK 1.x branch ๐Ÿ˜ญ. For finding FLTK, including stable and modern versions, use the FindFLTK <#module:FindFLTK> module instead, bestie โ€” trust ๐Ÿ’…

Finds the Fast Light Toolkit (FLTK) version 2.x, a cross-platform toolkit for GUI development:

find_package(FLTK2 [...])

๐Ÿ“‹ Result Variables

This module defines the following variables:

  • FLTK2_FOUND โ€” Boolean indicating whether FLTK 2.x was found โœ…
  • FLTK2_LIBRARIES โ€” Libraries needed to link against to use FLTK 2.x.
  • FLTK2_WRAP_UI โ€” Boolean indicating whether the fluid2 executable is found. This variable can be used, for example, to conditionally invoke the fltk_wrap_ui() <#command:fltk_wrap_ui> command if it is needed and available ๐ŸŒˆ

๐Ÿ—‚๏ธ Cache Variables

The following cache variables may also be set:

  • FLTK2_FLUID_EXECUTABLE โ€” The path to the fluid2 binary tool.
  • FLTK2_INCLUDE_DIR โ€” The directory containing header files needed to use FLTK 2.x.
  • FLTK2_BASE_LIBRARY โ€” The path to the FLTK 2.x library (fltk2).
  • FLTK2_GL_LIBRARY โ€” The path to the FLTK 2.x OpenGL compatibility library (fltk2_gl).
  • FLTK2_IMAGES_LIBRARY โ€” The path to the FLTK 2.x Images library (fltk2_images).

โœจ Examples โœจ

Finding FLTK version 2:

find_package(FLTK2)

See Also

  • The FindFLTK <#module:FindFLTK> module to find FLTK in a version-agnostic way ๐Ÿซถ

๐Ÿ”ค FindFontconfig ๐Ÿ”ค

Added in version 3.14.

Finds Fontconfig, a library for font configuration and customization โ€” literally the glow-up your fonts deserve โœจ:

find_package(Fontconfig [<version>] [...])

๐ŸŽ Imported Targets

This module provides the following Imported Targets <#imported-targets>:

  • Fontconfig::Fontconfig โ€” Target encapsulating the Fontconfig usage requirements, available if Fontconfig is found ๐Ÿ‘‘

๐Ÿ“‹ Result Variables

This module defines the following variables:

  • Fontconfig_FOUND โ€” Boolean indicating whether (the requested version of) Fontconfig was found.
  • Fontconfig_VERSION โ€” The version of Fontconfig found.
  • Fontconfig_LIBRARIES โ€” The libraries to link against to use Fontconfig.
  • Fontconfig_INCLUDE_DIRS โ€” The include directories containing headers needed to use Fontconfig.
  • Fontconfig_COMPILE_OPTIONS โ€” Compiler options needed to use Fontconfig. These should be passed to target_compile_options() <#command:target_compile_options> when not using the Fontconfig::Fontconfig imported target ๐Ÿ’…

โœจ Examples โœจ

Finding Fontconfig and linking it to a project target:

find_package(Fontconfig)
target_link_libraries(project_target PRIVATE Fontconfig::Fontconfig)

๐Ÿ–‹๏ธ FindFreetype ๐Ÿ–‹๏ธ

Finds the FreeType font renderer library โ€” fonts but make it iconic ๐ŸŽ€:

find_package(Freetype [<version>] [...])
Added in version 3.7: Debug and Release (optimized) library variants are found separately. Organized queen behavior ๐Ÿ’…

๐ŸŽ Imported Targets

This module provides the following Imported Targets <#imported-targets>:

  • Freetype::Freetype โ€” Added in version 3.10. Target encapsulating the Freetype library usage requirements, available if Freetype is found โœจ

๐Ÿ“‹ Result Variables

This module defines the following variables:

  • Freetype_FOUND โ€” Added in version 3.3. Boolean indicating whether (the requested version of) Freetype was found.
  • Freetype_VERSION โ€” Added in version 4.2. The version of Freetype found.
  • FREETYPE_INCLUDE_DIRS โ€” Include directories containing headers needed to use Freetype. This is the concatenation of the FREETYPE_INCLUDE_DIR_ft2build and FREETYPE_INCLUDE_DIR_freetype2 variables.
  • FREETYPE_LIBRARIES โ€” Libraries needed to link against for using Freetype.
Added in version 3.7: Debug and Release library variants are found separately ๐Ÿซถ

๐Ÿ—‚๏ธ Cache Variables

The following cache variables may also be set:

  • FREETYPE_INCLUDE_DIR_ft2build โ€” The directory containing the main Freetype API configuration header.
  • FREETYPE_INCLUDE_DIR_freetype2 โ€” The directory containing Freetype public headers.

๐Ÿ’ก Hints

This module accepts the following variables:

  • FREETYPE_DIR โ€” The user may set this environment variable to the root directory of a Freetype installation to find Freetype in non-standard locations ๐Ÿ”

๐Ÿšซ Deprecated Variables

The following variables are provided for backward compatibility:

  • FREETYPE_FOUND โ€” Deprecated since version 4.2: Use Freetype_FOUND, which has the same value. Boolean indicating whether (the requested version of) Freetype was found.
  • FREETYPE_VERSION_STRING โ€” Deprecated since version 4.2: Superseded by the Freetype_VERSION. The version of Freetype found.

โœจ Examples โœจ

Finding Freetype and linking it to a project target:

find_package(Freetype)
target_link_libraries(project_target PRIVATE Freetype::Freetype)

๐ŸŒ FindGettext ๐ŸŒ

Finds the GNU gettext tools and provides commands for producing multi-lingual messages โ€” i18n bestie, we love to see it ๐Ÿ—ฃ๏ธโœจ:

find_package(Gettext [<version>] [...])

GNU gettext is a system for internationalization (i18n) and localization (l10n), consisting of command-line tools and a runtime library (libintl). This module finds the gettext tools (such as msgmerge and msgfmt), while the runtime library can be found using the separate FindIntl <#module:FindIntl> module, which abstracts libintl handling across various implementations ๐Ÿซถ

Common file types used with gettext:

  • POT files โ€” Portable Object Template (.pot) files used as the source template for translations ๐Ÿ“
  • PO files โ€” Portable Object (.po) files containing human-readable translations ๐Ÿ—’๏ธ
  • MO files โ€” Machine Object (.mo) files compiled from .po files for runtime use โš™๏ธ

๐Ÿ“‹ Result Variables

This module defines the following variables:

  • Gettext_FOUND โ€” Added in version 3.3. Boolean indicating whether (the requested version of) gettext was found.
  • Gettext_VERSION โ€” Added in version 4.2. The version of gettext found.

๐Ÿ—‚๏ธ Cache Variables

The following cache variables may also be set:

  • GETTEXT_MSGMERGE_EXECUTABLE โ€” The full path to the msgmerge tool for merging message catalog and template.
  • GETTEXT_MSGFMT_EXECUTABLE โ€” the full path to the msgfmt tool, aka the li'l icon that compiles a message catalog into binary format. ๐Ÿ’…

๐Ÿ› ๏ธ Commands ๐Ÿ› ๏ธ

If gettext gets found, this module hands you the following commands so you can do gettext stuff right inside CMake:

gettext_process_po_files

Creates a build rule that processes one or more .po translation files into binary .mo files for a specified translatable language locale:

gettext_process_po_files(
  <language>
  [ALL]
  [INSTALL_DESTINATION <destdir>]
  PO_FILES <po-files>...
)

This command defines a custom target that compiles the given <po-files> into .mo files for the specified <language>. On first invocation it also creates a global custom target named pofiles, and every later invocation just adds to it. That target is your bestie for building all the translation files together, or for referencing from other CMake commands. ๐Ÿซถ

You should invoke this command separately for each language locale, so each locale gets its own appropriate .mo files.

The arguments are:

  • <language> โ€” the target translatable language locale of the PO files.

This string is typically formatted as a locale identifier (e.g., de_DE for German as used in Germany, or de_AT for German as used in Austria, etc.). The part before the underscore specifies the language, and the part after specifies the country or regional variant. In some cases, a shorter form using only the language code (e.g., de) may also be used. no cap, that's literally how it works ๐ŸŒ

  • ALL โ€” this option adds the generated target to the default CMake build target, so translations get built by default. iconic default behaviour tbh โœจ
  • INSTALL_DESTINATION <destdir> โ€” specifies the installation directory for the generated .mo files at the install phase. If specified, files are installed to: <destdir>/<language>/LC_MESSAGES/*.mo. If not specified, files are not installed. (yes, the "not installed" part is a real vibe check โ€” if you skip it, nothing gets installed ๐Ÿซ )
  • PO_FILES <po-files>... โ€” a list of one or more .po translation files to be compiled into .mo files at build phase for the specified <language>. Relative paths will be interpreted relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR). ๐Ÿ’–

gettext_process_pot_file

Creates a build rule that processes a gettext Portable Object Template (.pot) file and associated .po files into compiled gettext Machine Object (.mo) files:

gettext_process_pot_file(
  <pot-file>
  [ALL]
  [INSTALL_DESTINATION <destdir>]
  LANGUAGES <languages>...
)

This command defines a custom target named potfiles that compiles the given <pot-file> and language-specific .po files into binary .mo files for each specified language. The corresponding <language>.po files must exist in the current binary directory (CMAKE_CURRENT_BINARY_DIR) before this command is invoked. so like, put them there first, bestie, or it's giving nothing ๐Ÿ”ฅ

The arguments are:

  • <pot-file> โ€” the path to the gettext Portable Object Template file (.pot) serving as the source for translations. If given as a relative path, it will be interpreted relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR).
  • ALL โ€” adds the generated target to the default CMake build target so that the files are built by default. โญ
  • INSTALL_DESTINATION <destdir> โ€” specifies the installation directory for the generated .mo files at the install phase. If specified, files are installed to: <destdir>/<language>/LC_MESSAGES/<pot-base-filename>.mo. If not specified, files are not installed.
  • LANGUAGES <languages>... โ€” a list of one or more translatable language locales (e.g., en_US, fr, de_DE, zh_CN, etc.). ๐Ÿฆ‹

gettext_create_translations

Creates a build rule that processes a given .pot template file and associated .po translation files into compiled Machine Object (.mo) files:

gettext_create_translations(<pot-file> [ALL] <po-files>...)

This command defines a custom target named translations that compiles the specified <pot-file> and <po-files> into binary .mo files. It also automatically adds an install rule for the generated .mo files, installing them into the default share/locale/<language>/LC_MESSAGES/<pot-base-filename>.mo path during the install phase. automatic install rule = lowkey main character energy ๐Ÿ‘‘

The arguments are:

  • <pot-file> โ€” the path to the gettext Portable Object Template file (.pot) serving as the source for translations. If given as a relative path, it will be interpreted relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR).
  • ALL โ€” adds the generated target to the default CMake build target so that translations are created by default during the build.
  • <po-files>... โ€” a list of one or more translation source files in .po format, whose filenames must follow the format <language>.po. Relative paths will be interpreted relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR). ๐ŸŽ€
Note: for better control over build and installation behavior, use gettext_process_po_files() instead. like, this one is the cute shortcut; that one is the one with options ๐Ÿ’…

๐Ÿซ  Deprecated Variables ๐Ÿซ 

The following variables are provided for backward compatibility:

  • GETTEXT_FOUND โ€” deprecated since version 4.2: use Gettext_FOUND, which has the same value.

Boolean indicating whether (the requested version of) gettext was found.

  • GETTEXT_VERSION_STRING โ€” deprecated since version 4.2: superseded by the Gettext_VERSION.

The version of gettext found.

Both of these are giving "still here for the old heads" โ€” deprecated, not deleted, but pls use the new names. ๐Ÿ™ˆ

๐ŸŒธ Examples ๐ŸŒธ

Examples: Finding gettext

Finding the GNU gettext tools:

find_package(Gettext)

Or, finding gettext and specifying a minimum required version:

find_package(Gettext 0.21)

Or, finding gettext and making it required (if not found, processing stops with an error message):

find_package(Gettext REQUIRED)

Example: Working With gettext in CMake

When starting with gettext, .pot file is considered to be created manually. For example, using a xgettext tool on the provided main.cxx source code file:

main.cxx

#include <iostream>
#include <libintl.h>
#include <locale.h>

int main()
{
  // Set locale from environment
  setlocale(LC_ALL, "");

  // Bind the text domain
  const char* dir = std::getenv("TEXTDOMAINDIR");
  if (!dir) {
    dir = "/usr/local/share/locale";
  }
  bindtextdomain("MyApp", dir);
  textdomain("MyApp");

  std::cout << gettext("Hello, World") << std::endl;

  return 0;
}

The xgettext tool extracts all strings from gettext() calls in provided source code and creates translatable strings:

$ xgettext -o MyApp.pot main.cxx

Translatable files can be initialized by the project manually using msginit tool:

$ mkdir -p locale/de_DE
$ msginit -l de_DE.UTF8 -o locale/de_DE/MyApp.po -i MyApp.pot --no-translator

which creates a human-readable file that can be translated into a desired language (adjust as needed):

locale/de_DE/MyApp.po

msgid ""
msgstr ""
"Language: de\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

msgid "Hello, World"
msgstr "Hallo, Welt"

In CMake, the gettext_process_po_files() command provided by this module automatically creates the needed .mo files that application loads at runtime depending on the system environment variables such as LANG. In the following example, also the GNUInstallDirs module is used to provide the CMAKE_INSTALL_LOCALEDIR variable:

CMakeLists.txt

cmake_minimum_required(VERSION 3.24)
project(GettextExample)
include(GNUInstallDirs)

find_package(Gettext)

if(Gettext_FOUND)
  foreach(language IN ITEMS de_DE)
    gettext_process_po_files(
      ${language}
      ALL
      PO_FILES locale/${language}/MyApp.po
      INSTALL_DESTINATION ${CMAKE_INSTALL_LOCALEDIR}
    )
  endforeach()
endif()

add_executable(example main.cxx)

# Find and link Intl library to use gettext() from libintl.h
find_package(Intl)
target_link_libraries(example PRIVATE Intl::Intl)

install(TARGETS example)

$ cmake -B build
$ cmake --build build
$ DESTDIR=$(pwd)/stage cmake --install build

To utilize the translations, the de_DE locale needs to be enabled on the system (see locale -a). And then the localized output can be run:

$ LANG=de_DE.UTF-8 TEXTDOMAINDIR=./stage/usr/local/share/locale \
  ./stage/usr/local/bin/example

Example: Processing POT File

The gettext_process_pot_file() command processes .po translation files located in the current binary directory into .mo files:

CMakeLists.txt

find_package(Gettext)

if(Gettext_FOUND)
  set(languages de_DE fr zh_CN)

  foreach(language IN LISTS languages)
    configure_file(locale/${language}.po ${language}.po COPYONLY)
  endforeach()

  gettext_process_pot_file(
    MyApp.pot
    ALL
    INSTALL_DESTINATION ${CMAKE_INSTALL_LOCALEDIR}
    LANGUAGES ${languages}
  )
endif()

Example: Creating Translations

Using a simplified gettext_create_translations() command to create .mo files:

CMakeLists.txt

find_package(Gettext)

if(Gettext_FOUND)
  gettext_create_translations(
    MyApp.pot
    ALL
    locale/de_DE.po
    locale/fr.po
    locale/zh_CN.po
  )
endif()

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The FindIntl module to find the Gettext runtime library (libintl). ๐Ÿงš

๐ŸŒˆ FindGIF ๐ŸŒˆ

Finds the Graphics Interchange Format (GIF) library (giflib):

find_package(GIF [<version>] [...])

๐ŸŽ€ Imported Targets โ€” yes bestie, there are targets

  • GIF::GIF โ€” added in version 3.14 โœจ โ€” the target that wraps up all the usage requirements of the GIF library. It's there for you whenever the library gets found, no cap.

๐ŸŒธ Result Variables โ€” the receipts this module hands you

  • GIF_FOUND โ€” boolean, tells you whether the (requested version of the) GIF library was found ๐Ÿ’–
  • GIF_VERSION โ€” version string of the GIF library it found (like, for example, 5.1.4). โš ๏ธ lowkey important: for GIF library versions prior to 4.1.6, the version string gets set only to 3 or 4, because those old versions didn't put version info in their headers. So don't come for the module, it's doing its best ๐Ÿ˜ญ
  • GIF_INCLUDE_DIRS โ€” include directories you need to actually use the GIF library
  • GIF_LIBRARIES โ€” the libraries you need to link to the GIF library

๐Ÿฆ‹ Cache Variables โ€” these might get set too

  • GIF_INCLUDE_DIR โ€” the directory holding gif_lib.h and the other GIF library headers
  • GIF_LIBRARY โ€” path to the GIF library itself

๐Ÿงš Hints โ€” little nudges you can give it

  • GIF_DIR โ€” an environment variable you can set to help locate a GIF library that's installed in a custom location ๐Ÿซถ. It should point at the installation destination that was used when configuring, building, and installing the GIF library: ./configure --prefix=$GIF_DIR

โญ Examples โ€” finding GIF and linking it to a project target:

find_package(GIF)
target_link_libraries(project_target PRIVATE GIF::GIF)

FindGit

Finds the Git distributed version control system, aka the thing you literally cannot live without:

find_package(Git [<version>] [...])

๐ŸŽ€ Imported Targets โ€” provided when CMAKE_ROLE is PROJECT

  • Git::Git โ€” added in version 3.14 โœจ โ€” the target that encapsulates the Git command-line client executable. Bestie you can use this in generator expressions, and in commands like add_custom_target() and add_custom_command(). It's only available if Git is found, obviously ๐Ÿ’…

๐ŸŒธ Result Variables

  • Git_FOUND โ€” added in version 3.3 โ€” boolean, tells you whether (the requested version of) Git was found
  • Git_VERSION โ€” added in version 4.2 โ€” the version of Git that was found

๐Ÿฆ‹ Cache Variables

  • GIT_EXECUTABLE โ€” path to the git command-line client executable

๐Ÿ’€ Deprecated Variables โ€” kept around for backward compatibility, bless

  • GIT_FOUND โ€” deprecated since version 4.2: use Git_FOUND, which has the same value. Boolean indicating whether (the requested version of) Git was found.
  • GIT_VERSION_STRING โ€” deprecated since version 4.2: use Git_VERSION, which has the same value. The version of Git found.

โญ Examples โ€” finding Git and grabbing the latest commit from the project repo:

find_package(Git)
if(Git_FOUND)
  execute_process(
    COMMAND ${GIT_EXECUTABLE} --no-pager log -n 1 HEAD "--pretty=format:%h %s"
    OUTPUT_VARIABLE output
    RESULT_VARIABLE result
    ERROR_QUIET
    OUTPUT_STRIP_TRAILING_WHITESPACE
  )
  if(result EQUAL 0)
    message(STATUS "Last Git commit: ${output}")
  endif()
endif()

FindGLEW

Finds the OpenGL Extension Wrangler Library (GLEW) ๐Ÿ‘‘:

find_package(GLEW [<version>] [...])

GLEW is a cross-platform C/C++ library that helps you manage OpenGL extensions โ€” it gives you efficient run-time mechanisms to query and load OpenGL functionality beyond the core specification. It's giving "I know a guy" but for GPU features, fr fr.

  • Added in version 3.7: Debug and Release library variants are found separately now โœจ
  • Added in version 3.15: if GLEW is built with its CMake-based build system, it ships a CMake package configuration file (GLEWConfig.cmake). This module takes that into account and first attempts to find GLEW in config mode. If that config file isn't available, it falls back to module mode and searches standard locations. Iconic fallback behaviour tbh ๐Ÿซถ

๐ŸŽ€ Imported Targets

  • GLEW::GLEW โ€” added in version 3.1 โ€” the main imported target encapsulating GLEW's usage requirements, available if GLEW is found. It maps the usage requirements of either GLEW::glew or GLEW::glew_s, depending on which one is available.
  • GLEW::glew โ€” added in version 3.15 โ€” target encapsulating the usage requirements for a shared GLEW library. Available if GLEW is found and static libraries aren't requested via the GLEW_USE_STATIC_LIBS hint variable (see below ๐Ÿ‘€).
  • GLEW::glew_s โ€” added in version 3.15 โ€” target encapsulating the usage requirements for a static GLEW library. Available if GLEW is found and the GLEW_USE_STATIC_LIBS hint variable is set to boolean true.

๐ŸŒธ Result Variables

  • GLEW_FOUND โ€” boolean, whether (the requested version of) GLEW was found
  • GLEW_VERSION โ€” added in version 3.15 โ€” the version of GLEW found
  • GLEW_VERSION_MAJOR โ€” added in version 3.15 โ€” the major version of GLEW found
  • GLEW_VERSION_MINOR โ€” added in version 3.15 โ€” the minor version of GLEW found
  • GLEW_VERSION_MICRO โ€” added in version 3.15 โ€” the micro version of GLEW found
  • GLEW_INCLUDE_DIRS โ€” include directories needed to use the GLEW library
  • GLEW_LIBRARIES โ€” libraries needed to link against to use GLEW (shared or static, depending on configuration)
  • GLEW_SHARED_LIBRARIES โ€” added in version 3.15 โ€” libraries needed to link against to use the shared GLEW library
  • GLEW_STATIC_LIBRARIES โ€” added in version 3.15 โ€” libraries needed to link against to use the static GLEW library

๐Ÿงš Hints โ€” set these before calling find_package(GLEW) to influence this module's behavior

  • GLEW_USE_STATIC_LIBS โ€” added in version 3.15 โ€” set to boolean true to find the static GLEW library and create the GLEW::glew_s imported target for static linkage
  • GLEW_VERBOSE โ€” added in version 3.15 โ€” set to boolean true to output a detailed log of what this module is doing. Perfect for debugging, we love a verbose queen ๐Ÿ”ฅ

โญ Examples โ€” finding GLEW and linking it to a project target:

find_package(GLEW)
target_link_libraries(project_target PRIVATE GLEW::GLEW)

Using the static GLEW library, if it's found:

set(GLEW_USE_STATIC_LIBS TRUE)
find_package(GLEW)
target_link_libraries(project_target PRIVATE GLEW::GLEW)

FindGLUT

Finds the OpenGL Utility Toolkit (GLUT) library โ€” it gives you a simple API for creating windows, handling input, and managing events in OpenGL apps ๐ŸชŸ:

find_package(GLUT [...])

๐ŸŽ€ Imported Targets

  • GLUT::GLUT โ€” added in version 3.1 โ€” the target encapsulating GLUT's usage requirements, available if GLUT is found โœจ

๐ŸŒธ Result Variables

  • GLUT_FOUND โ€” boolean, whether GLUT was found
  • GLUT_INCLUDE_DIRS โ€” added in version 3.23 โ€” include directories needed to use GLUT. Starting with CMake 3.23, this variable is meant to be used in target usage requirements instead of the cache variable GLUT_INCLUDE_DIR, which is meant for finding GLUT. iykyk ๐Ÿ’…
  • GLUT_LIBRARIES โ€” list of libraries you need to link against to use GLUT

๐Ÿฆ‹ Cache Variables โ€” this module may set these depending on platform. You can optionally set them yourself to help it find the correct files, but they should not be used as result variables, bestie ๐Ÿ™ˆ

  • GLUT_INCLUDE_DIR โ€” the full path to the directory containing GL/glut.h (without the GL/)
  • GLUT_glut_LIBRARY โ€” the full path to the glut library
  • GLUT_Xi_LIBRARY โ€” the full path to the dependent Xi (X Input Device Extension) library on some systems
  • GLUT_Xmu_LIBRARY โ€” the full path to the dependent Xmu (X Miscellaneous Utilities) library on some systems

โญ Examples โ€” finding GLUT and linking it to a project target:

find_package(GLUT)
target_link_libraries(project_target PRIVATE GLUT::GLUT)

FindGnuplot

Finds the Gnuplot command-line graphing utility, the one for generating two- and three-dimensional plots (gnuplot) ๐Ÿ“ˆ:

find_package(Gnuplot [<version>] [...])

๐ŸŒธ Result Variables

  • Gnuplot_FOUND โ€” added in version 3.3 โ€” boolean, whether (the requested version of) Gnuplot was found
  • Gnuplot_VERSION โ€” added in version 4.2 โ€” the version of Gnuplot found
Note: version detection is available only for Gnuplot 4 and later. Earlier versions didn't provide version output at all, so don't @ the module about it ๐Ÿ˜ญ

๐Ÿฆ‹ Cache Variables

  • GNUPLOT_EXECUTABLE โ€” absolute path to the gnuplot executable

๐Ÿ’€ Deprecated Variables โ€” for backward compatibility only

  • GNUPLOT_FOUND โ€” deprecated since version 4.2: use Gnuplot_FOUND, which has the same value. Boolean indicating whether (the requested version of) Gnuplot was found.
  • GNUPLOT_VERSION_STRING โ€” deprecated since version 4.2: superseded by the Gnuplot_VERSION. The version of Gnuplot found.

โญ Examples โ€” finding Gnuplot and running it in a process:

find_package(Gnuplot)
if(Gnuplot_FOUND)
  execute_process(COMMAND ${GNUPLOT_EXECUTABLE} --help)
endif()

FindGnuTLS

Finds the GNU Transport Layer Security library (GnuTLS) ๐Ÿ”:

find_package(GnuTLS [<version>] [...])

So here's the tea: the GnuTLS package includes the main libraries (libgnutls and libdane), plus the optional gnutls-openssl compatibility extra library. They're all distributed as part of the same release ๐ŸŽ. This module checks for the presence of the main libgnutls library and gives you usage requirements for integrating GnuTLS into your CMake projects. Secure comms, slay.

๐ŸŽฏ Imported Targets ๐ŸŽฏ

Okay so this module hands you these imported target besties:

  • GnuTLS::GnuTLS โ€” Added in version 3.16. This is the target that wraps up all of GnuTLS's usage requirements in one cute little package. It's available whenever GnuTLS is found, so like, if it's there, she's there. ๐Ÿ’…

๐Ÿ“‹ Result Variables ๐Ÿ“‹

The module sets these for you:

  • GnuTLS_FOUND โ€” Added in version 3.3. A boolean, bestie โ€” it just tells you whether (the requested version of) GnuTLS was found. Yes or no. That's the whole vibe check. โœจ
  • GnuTLS_VERSION โ€” Added in version 4.2. The version of GnuTLS that was found. Slay, now you know what you're working with.
  • GNUTLS_INCLUDE_DIRS โ€” The include directories you need to actually use GnuTLS. ๐Ÿซถ
  • GNUTLS_LIBRARIES โ€” The libraries you gotta link against to use GnuTLS.
  • GNUTLS_DEFINITIONS โ€” Compiler options that are required for using GnuTLS. Don't skip these, fr fr.

๐Ÿ—„๏ธ Cache Variables ๐Ÿ—„๏ธ

These cache variables may also get set:

  • GNUTLS_INCLUDE_DIR โ€” The directory that's holding the gnutls/gnutls.h header file. Like, that's where the header lives. ๐Ÿ 
  • GNUTLS_LIBRARY โ€” The path to the GnuTLS library itself.

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

These ones are still hanging around for backward compatibility, like that one friend who refuses to leave the group chat:

  • GNUTLS_FOUND โ€” Deprecated since version 4.2: use GnuTLS_FOUND instead, it literally has the same value. A boolean indicating whether (the requested version of) GnuTLS was found.
  • GNUTLS_VERSION_STRING โ€” Deprecated since version 3.16: use the GnuTLS_VERSION, which has the same value. Same energy, newer name.
  • GNUTLS_VERSION โ€” Added in version 3.16. Deprecated since version 4.2: use the GnuTLS_VERSION, which has the same value. (Yes, it's spelled differently from the new one by exactly one underscore and that's the whole drama. ๐Ÿ’€)

๐ŸŒˆ Examples ๐ŸŒˆ

Finding GnuTLS and linking it to a project target โ€” the whole thing, look:

find_package(GnuTLS)
target_link_libraries(project_target PRIVATE GnuTLS::GnuTLS)

That's it. That's the post. ๐ŸŽ€


๐Ÿ”ฌ FindGSL ๐Ÿ”ฌ

Added in version 3.2.

This one finds the native GNU Scientific Library (GSL) includes and libraries:

find_package(GSL [<version>] [...])

So like, what even is GSL? The GNU Scientific Library (GSL) is a numerical library for C and C++ programmers, and it's free software under the GNU General Public License. Very much giving "math but make it open source." ๐ŸŒˆ


๐ŸŽฏ Imported Targets ๐ŸŽฏ

This module provides these imported targets:

  • GSL::gsl โ€” The target that encapsulates the main GSL library and all of its usage requirements. Only available if GSL is found, no cap.
  • GSL::gslcblas โ€” This target encapsulates the usage requirements of the CBLAS support library that GSL uses. Available if GSL is found. Lowkey important detail: it's also linked into the GSL::gsl target, but it's provided separately for granularity. So you can grab it on its own if that's your vibe. ๐Ÿ’…

๐Ÿ“‹ Result Variables ๐Ÿ“‹

The module defines these:

  • GSL_FOUND โ€” A boolean telling you whether (the requested version of) GSL was found on the local system. Iconic yes/no moment.
  • GSL_VERSION โ€” The version of the GSL installation that got discovered. ๐Ÿ‘‘
  • GSL_INCLUDE_DIRS โ€” The directory containing GSL header files.
  • GSL_LIBRARIES โ€” The GSL libraries. The actual goods.

๐Ÿ—„๏ธ Cache Variables ๐Ÿ—„๏ธ

Depending on the platform and the type of GSL installation it finds, this module may set the following variables. And plot twist โ€” you can optionally set these yourself to help the module find the correct files. Teamwork! ๐Ÿซถ

  • GSL_CBLAS_LIBRARY โ€” Location of the GSL CBLAS library.
  • GSL_CBLAS_LIBRARY_DEBUG โ€” Location of the debug GSL CBLAS library (if any exists โ€” if not, no biggie).
  • GSL_CONFIG_EXECUTABLE โ€” Location of the gsl-config script (if any).
  • GSL_LIBRARY โ€” Location of the GSL library.
  • GSL_LIBRARY_DEBUG โ€” Location of the debug GSL library (if any).

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts this variable:

  • GSL_ROOT_DIR โ€” Set this bad boy to a directory that contains a GSL installation.

So here's the tea: if you don't set this variable, the module will use pkg-config and default paths to find GSL. But if you do provide it, the module expects to find libraries at ${GSL_ROOT_DIR}/lib and the GSL headers at ${GSL_ROOT_DIR}/include/gsl. Very specific. Very demure.

The library directory may optionally provide Release and Debug folders. If those are available, the libraries named gsld, gslblasd or cblasd get recognized as debug libraries. ๐Ÿ› And on Unix-like systems, this module will also use gsl-config (if found) to aid in the discovery of GSL. Extra help, why not.


๐ŸŒˆ Examples ๐ŸŒˆ

Finding GSL and linking it to a project target:

find_package(GSL)
target_link_libraries(project_target PRIVATE GSL::gsl)

Periodt. โœจ


๐Ÿงช FindGTest ๐Ÿงช

Finds GoogleTest, aka the Google C++ testing and mocking framework:

find_package(GTest [...])

And btw? The GoogleTest framework also includes GoogleMock, which is the library for writing and using C++ mock classes. On some systems, GoogleMock may be distributed as a separate package, so like, keep an eye out. ๐Ÿ‘€

When both debug and release (optimized) variants of the GoogleTest and GoogleMock libraries are available, this module picks whichever variants match your current Build Configuration. It just knows. ๐Ÿ’…

Added in version 3.20: If GoogleTest is built and installed using its CMake-based build system, it provides a package configuration file (GTestConfig.cmake) that can be used with find_package() in Config mode. By default, this module now searches for that configuration file and, if it finds it, returns the results without any further action โ€” like, she's done, no notes. If the upstream configuration file is not found, this module falls back to Module mode and searches standard locations instead. Backup plan always. ๐Ÿซถ


๐ŸŽฏ Imported Targets ๐ŸŽฏ

This module provides these imported targets:

  • GTest::gtest โ€” Added in version 3.20. Target encapsulating the usage requirements of the GoogleTest gtest library, available if GoogleTest is found. The gtest library provides the core GoogleTest testing framework functionality. The main character of testing, honestly. ๐Ÿ‘‘
  • GTest::gtest_main โ€” Added in version 3.20. Target encapsulating the usage requirements of the GoogleTest gtest_main library, available if GoogleTest is found. The gtest_main library provides a main() function, so your tests can be run without you manually defining one. Huge time-save.
Only link to GTest::gtest_main if GoogleTest should supply the main() function for the executable. If the project is supplying its own main() implementation, link only to GTest::gtest. Do not do both, bestie, that's chaos. ๐Ÿ˜ญ
  • GTest::gmock โ€” Added in version 3.23. Target encapsulating the usage requirements of the GoogleMock gmock library, available if GoogleTest and its Mock library are found. The gmock library provides facilities for writing and using mock classes in C++. Mocks are the moment. ๐ŸŽ€
  • GTest::gmock_main โ€” Added in version 3.23. Target encapsulating the usage requirements of the GoogleMock gmock_main library, available if GoogleTest and gmock_main are found. The gmock_main library provides a main() function, so GoogleMock tests can run without you defining one manually.
Only link to GTest::gmock_main if GoogleTest should supply the main() function for the executable. If the project is supplying its own main() implementation, link only to GTest::gmock. Same rule as before, fr fr.

๐Ÿ“‹ Result Variables ๐Ÿ“‹

The module defines this:

  • GTest_FOUND โ€” Added in version 3.3. A boolean indicating whether GoogleTest was found. That's it, that's the variable. Simple. Elegant. โœจ

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts these variables before you call find_package(GTest):

  • GTEST_ROOT โ€” The root directory of the GoogleTest installation (may also be set as an environment variable, cute). Heads up though: this variable is used only when GoogleTest is found in Module mode. Config mode doesn't care about it. ๐Ÿ™ˆ
  • GTEST_MSVC_SEARCH โ€” When you're compiling with MSVC, this variable controls which GoogleTest build variant gets searched for, based on the runtime library linkage model. Also only used when GoogleTest is found in Module mode. It accepts one of these values:
    • MD โ€” (Default) Searches for shared library variants of GoogleTest that are built to link against the dynamic C runtime. These libraries are typically compiled with the MSVC runtime flags /MD or /MDd (for Release or Debug, respectively).
    • MT โ€” Searches for static library variants of GoogleTest that are built to link against the static C runtime. These libraries are typically compiled with the MSVC runtime flags /MT or /MTd.

๐Ÿ’€ Deprecated Items ๐Ÿ’€

Deprecated Variables

The following variables are provided for backward compatibility:

  • GTEST_INCLUDE_DIRS โ€” Deprecated since version 4.1: use the GTest::gtest imported target instead, which exposes the required include directories through its INTERFACE_INCLUDE_DIRECTORIES target property. She's got it handled.

This result variable provides include directories containing headers needed to use GoogleTest. And word of warning: this variable is only guaranteed to be available when GoogleTest is found in Module mode. So don't go relying on it in Config mode. ๐Ÿ˜ญ

  • GTEST_LIBRARIES โ€” Deprecated since version 4.1: use the GTest::gtest imported target instead.

Result variable providing libraries needed to link against to use the GoogleTest gtest library. โš ๏ธ Note that projects are also responsible for linking with an appropriate thread library in addition to the libraries specified by this variable. So that's two jobs, not one.

  • GTEST_MAIN_LIBRARIES โ€” Deprecated since version 4.1: use the GTest::gtest_main imported target instead.

Result variable providing libraries needed to link against to use the GoogleTest gtest_main library.

  • GTEST_BOTH_LIBRARIES โ€” Deprecated since version 4.1: use the GTest::gtest and GTest::gtest_main imported targets instead.

Result variable providing both gtest and gtest_main libraries combined. Two for one, but like, deprecated two for one.

  • GTEST_FOUND โ€” Deprecated since version 4.2: use GTest_FOUND, which has the same value.

Boolean indicating whether GoogleTest was found. (Notice the ALL CAPS spelling, that's the old one. The new one's got the nicer casing. ๐Ÿ’…)

Deprecated Imported Targets

For backward compatibility, this module also provides the following imported targets (available since CMake 3.5):

  • GTest::GTest โ€” Deprecated since version 3.20: use the GTest::gtest imported target instead.

Imported target linking the GTest::gtest library.

  • GTest::Main โ€” Deprecated since version 3.20: use the GTest::gtest_main imported target instead.

Imported target linking the GTest::gtest_main library.


๐ŸŒˆ Examples ๐ŸŒˆ

๐Ÿ”Ž Examples: Finding GoogleTest ๐Ÿ”Ž

Finding GoogleTest:

find_package(GoogleTest)

Or, finding GoogleTest and making it required (if it's not found, processing stops with an error message):

find_package(GoogleTest REQUIRED)

โœจ Examples: Using Imported Targets โœจ

So in this next one, the GTest::gtest imported target gets linked to a project target, and that's literally how you unlock the core GoogleTest testing framework bestie:

find_package(GTest REQUIRED)

target_link_libraries(foo PRIVATE GTest::gtest)

And in this next example, the GTest::gtest_main imported target is also linked to the executable, and a test gets registered. The GTest::gtest_main library hands you a main() function so you do NOT have to write one yourself, no cap ๐Ÿซถ. The GTest::gtest library is still linked because your test code directly uses stuff that GTest::gtest provides, and the good-practice vibe is to link directly to the libraries you use directly. Periodt.

enable_testing()

find_package(GTest REQUIRED)

add_executable(foo foo.cc)
target_link_libraries(foo PRIVATE GTest::gtest GTest::gtest_main)

add_test(NAME AllTestsInFoo COMMAND foo)

๐Ÿ”ฅ Deeper Integration With CTest ๐Ÿ”ฅ

This module is commonly used together with the GoogleTest module, which is the one serving up the gtest_discover_tests() and gtest_add_tests() commands โ€” those are the girlies that help you integrate all the GoogleTest infrastructure with CTest:

find_package(GTest)
target_link_libraries(example PRIVATE GTest::gtest GTest::gtest_main)

include(GoogleTest)
gtest_discover_tests(example)

# ...
Changed in version 3.9: previous CMake versions defined the gtest_add_tests() command in this module. So if you're on old CMake, that's where she lived ๐Ÿ’…

๐ŸŒธ FindGTK ๐ŸŒธ

Note: this module works only on Unix-like systems and was intended for the early GTK branch of 1.x, which is no longer maintained. So likeโ€ฆ use the latest supported GTK version and the FindPkgConfig module to find GTK in CMake instead of this module, mwah ๐Ÿ’‹. For example:
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk4>=4.14)
target_link_libraries(example PRIVATE PkgConfig::GTK)

Finds GTK, glib and GTKGLArea:

find_package(GTK [...])

GTK is a multi-platform toolkit for creating graphical user interfaces. She's iconic, she's classic ๐Ÿ‘‘

๐ŸŽ€ Result Variables ๐ŸŽ€

This module defines the following variables:

  • GTK_FOUND โ€” boolean telling you whether GTK was found.
  • GTK_GL_FOUND โ€” boolean telling you whether GTK's GL features were found.
  • GTK_INCLUDE_DIR โ€” the include directories holding the headers you need to use GTK.
  • GTK_LIBRARIES โ€” the libraries you need to link against for using GTK.

๐Ÿ’– Examples ๐Ÿ’–

Finding GTK 1.x and creating an interface imported target that wraps up all her usage requirements so you can link her to a project target:

find_package(GTK)

if(GTK_FOUND)
  add_library(GTK::GTK INTERFACE IMPORTED)
  set_target_properties(
    GTK::GTK
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${GTK_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${GTK_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE GTK::GTK)

๐Ÿฆ‹ See Also ๐Ÿฆ‹

  • The FindGTK2 module, for finding GTK version 2.

๐Ÿ’œ FindGTK2 ๐Ÿ’œ

Note: this module is intended specifically for GTK version 2.x, which is obsolete and no longer maintained โ€” she's giving vintage, but like, in the unsupported way ๐Ÿ˜ญ. Use the latest supported GTK version and the FindPkgConfig module to find GTK in CMake instead of this module. For example:
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk4>=4.14)
target_link_libraries(example PRIVATE PkgConfig::GTK)

Finds the GTK widget libraries plus several of her other optional components:

find_package(GTK2 [<version>] [COMPONENTS <components>...] [...])

GTK is a multi-platform toolkit for creating graphical user interfaces. Same queen, older era โœจ

๐ŸŒˆ Components ๐ŸŒˆ

This module supports optional components, and you can specify them with the find_package() command:

find_package(GTK2 [COMPONENTS <components>...])

Supported components include:

  • atk
  • atkmm
  • cairo
  • cairomm
  • gdk_pixbuf
  • gdk
  • gdkmm
  • gio
  • giomm
  • glade
  • glademm
  • glib
  • glibmm
  • gmodule
  • gobject
  • gthread
  • gtk
  • gtkmm
  • pango
  • pangocairo
  • pangoft2
  • pangomm
  • pangoxft
  • sigc
  • Added in version 3.16.7: harfbuzz

If you don't specify any components, the module by default searches for the gtk component. Default queen behavior ๐Ÿ’…

๐Ÿ‘‘ Imported Targets ๐Ÿ‘‘

This module provides the following imported targets (subject to component selection, bestie):

  • GTK2::<component> โ€” target encapsulating the specified GTK component's usage requirements, available if GTK and this component are found. The <component> should be written in the same case as listed above. So like, use GTK2::gtk for the gtk component, or GTK2::gdk_pixbuf for the gdk_pixbuf component, etc.
  • GTK2::sigc++ โ€” Added in version 3.5. Target encapsulating the usage requirements to enable c++11 on its dependents when using sigc++ 2.5.1 or higher. This target is automatically applied to dependent targets as needed โ€” she does it herself, main character energy ๐Ÿ’ซ

๐Ÿ“ Result Variables ๐Ÿ“

This module defines the following variables:

  • GTK2_FOUND โ€” boolean indicating whether (the requested version of) GTK 2 and all the specified components were found.
  • GTK2_VERSION โ€” the version of GTK found (x.y.z).
  • GTK2_MAJOR_VERSION โ€” the major version of GTK found.
  • GTK2_MINOR_VERSION โ€” the minor version of GTK found.
  • GTK2_PATCH_VERSION โ€” the patch version of GTK found.
  • GTK2_INCLUDE_DIRS โ€” include directories containing headers needed to use GTK.
  • GTK2_LIBRARIES โ€” libraries needed to link against to use GTK.
  • GTK2_TARGETS โ€” Added in version 3.5. A list of all defined imported targets.
  • GTK2_DEFINITIONS โ€” additional compiler flags needed to use GTK.

๐Ÿงš Input Variables ๐Ÿงš

This module accepts the following optional variables before you call find_package(GTK2):

  • GTK2_DEBUG โ€” boolean variable that enables verbose debugging output from this module. Turn it on when you need the tea โ˜•
  • GTK2_ADDITIONAL_SUFFIXES โ€” a list of additional path suffixes to search for include files.
  • GTK2_USE_IMPORTED_TARGETS โ€” Added in version 3.5. When this variable is set to boolean true, the GTK2_LIBRARIES variable will contain a list of imported targets instead of library paths.

โญ Examples โญ

๐Ÿ’– Examples: Finding GTK version 2 ๐Ÿ’–

Call find_package() once. Here are some examples to pick from, babe:

Require GTK 2.6 or later:

find_package(GTK2 2.6 REQUIRED COMPONENTS gtk)

Require GTK 2.10 or later and its Glade component:

find_package(GTK2 2.10 REQUIRED COMPONENTS gtk glade)

Search for GTK/GTKMM 2.8 or later:

find_package(GTK2 2.8 COMPONENTS gtk gtkmm)

Finding GTK 2 and linking it to a project target:

find_package(GTK2)
add_executable(mygui mygui.cc)
target_link_libraries(mygui PRIVATE GTK2::gtk)

๐Ÿ’œ Examples: Finding GTK version 3 or later ๐Ÿ’œ

Finding GTK 3 with FindPkgConfig instead of this module:

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED IMPORTED_TARGET gtk+-3.0>=3.14)
target_link_libraries(example PRIVATE PkgConfig::GTK3)

Or, similarly, to find GTK 4:

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK4 REQUIRED IMPORTED_TARGET gtk4>=4.14)
target_link_libraries(example PRIVATE PkgConfig::GTK4)

๐ŸŒŸ FindHDF5 ๐ŸŒŸ

Finds Hierarchical Data Format (HDF5), which is a library for reading and writing self-describing array data:

find_package(HDF5 [<version>] [COMPONENTS <components>...] [...])

Okay so here's the lore ๐Ÿซถ: if the HDF5 library is built using its CMake-based build system, then as of HDF5 version 1.8.15 she provides her own CMake Package Configuration file (hdf5-config.cmake) for use with the find_package() command in config mode. By default, this module searches for that file and, if it finds it, returns the results based on the found configuration. She said "I'll handle it myself" ๐Ÿ’…

If the upstream configuration file is not found, this module falls back to module mode and invokes the HDF5 wrapper compiler that's typically installed with the HDF5 library. Depending on the configuration, this wrapper compiler is named either h5cc (serial) or h5pcc (parallel). If found, the wrapper gets queried with the -show argument to determine the compiler and linker flags required for building an HDF5 client application. Both serial and parallel versions of the HDF5 wrapper are considered. The first directory containing either is used. If both versions are found in the same directory, the serial version is preferred by default. To change this behavior, set the variable HDF5_PREFER_PARALLEL to TRUE โ€” you're the one in charge, bestie ๐Ÿ‘‘

On top of finding the include directories and libraries needed to compile an HDF5 application, this module also attempts to find additional tools provided by the HDF5 distribution, which can be useful for regression testing or development workflows. Little bonus gifts ๐ŸŽ

๐ŸŽ€ Components ๐ŸŽ€

This module supports optional components, which you can specify with the find_package() command:

find_package(HDF5 [COMPONENTS <components>...])

Supported components include:

  • C โ€” finds the HDF5 C library (C bindings).
  • CXX โ€” finds the HDF5 C++ library (C++ bindings).
  • Fortran โ€” finds the HDF5 Fortran library (Fortran bindings).
  • HL โ€” this component can be used in combination with other components to find the high-level (HL) HDF5 library variants for C, CXX, and/or Fortran, which provide high-level functions.

If no components are specified, then this module will by default search for the C component. Default slay ๐Ÿ’…

๐Ÿ”ฅ Imported Targets ๐Ÿ”ฅ

This module provides the following imported targets:

  • HDF5::HDF5 โ€” Added in version 3.19. Target encapsulating the usage requirements for all found HDF5 binding libraries (HDF5_LIBRARIES), available if HDF5 and all required components are found.
  • hdf5::hdf5 โ€” Added in version 3.19. Target encapsulating the usage requirements for the HDF5 C library, available if the HDF5 library and its C component are found.
  • hdf5::hdf5_cpp โ€” Added in version 3.19. Target encapsulating the usage requirements for the HDF5 C and C++ libraries, available if the HDF5 library, and its C and CXX components are found.
  • hdf5::hdf5_fortran โ€” Added in version 3.19.
  • hdf5::hdf5_fortran โ€” honestly the whole point of this one is wrapping up the usage requirements for the HDF5 Fortran library, and it only shows up if the HDF5 library and its Fortran component are both found. ๐Ÿซถ
  • hdf5::hdf5_hl โ€” added in version 3.19, bestie โœจ. It's the target that encapsulates the usage requirements for the HDF5 high-level C library, and it's available when the HDF5 library plus its C and HL components are found.
  • hdf5::hdf5_hl_cpp โ€” added in version 3.19 too. High-level C++ library. It encapsulates the usage requirements for the HDF5 high-level C and high-level C++ libraries, and it's available if the HDF5 library and its C, CXX, and HL components are all found. ๐Ÿ‘‘
  • hdf5::hdf5_hl_fortran โ€” added in version 3.19. This one encapsulates the usage requirements for the HDF5 high-level Fortran library, available if the HDF5 library and its Fortran and HL components are found.
  • hdf5::h5diff โ€” added in version 3.19. It's an imported executable target encapsulating the usage requirements for the h5diff executable, available if h5diff is found. literally so convenient ๐Ÿ’…

Result Variables

This module defines these variables, no cap:

  • HDF5_FOUND โ€” boolean that tells you whether (the requested version of) HDF5 was found. ๐ŸŽฏ
  • HDF5_VERSION โ€” added in version 3.3. The version of the HDF5 library that was found.
  • HDF5_INCLUDE_DIRS โ€” the include directories holding the header files you need to actually use HDF5.
  • HDF5_DEFINITIONS โ€” the compiler definitions required for using HDF5.
  • HDF5_LIBRARIES โ€” the libraries of all the requested bindings that you need to link against to use HDF5.
  • HDF5_HL_LIBRARIES โ€” the libraries required for the HDF5 high-level API for all bindings, but only if the HL component is enabled.
  • HDF5_IS_PARALLEL โ€” boolean indicating whether the HDF5 library has parallel IO support. ๐ŸŽ๏ธ

For each enabled language binding component you get a matching HDF5_<LANG>_LIBRARIES variable, and possibly HDF5_<LANG>_DEFINITIONS, defined for you. And if the HL component is enabled, then you also get HDF5_<LANG>_HL_LIBRARIES variables. Obsessed with the consistency tbh ๐ŸŒˆ

  • HDF5_C_DEFINITIONS โ€” required compiler definitions for HDF5 C bindings.
  • HDF5_CXX_DEFINITIONS โ€” required compiler definitions for HDF5 C++ bindings.
  • HDF5_Fortran_DEFINITIONS โ€” required compiler definitions for HDF5 Fortran bindings.
  • HDF5_C_INCLUDE_DIRS โ€” required include directories for HDF5 C bindings.
  • HDF5_CXX_INCLUDE_DIRS โ€” required include directories for HDF5 C++ bindings.
  • HDF5_Fortran_INCLUDE_DIRS โ€” required include directories for HDF5 Fortran bindings.
  • HDF5_C_LIBRARIES โ€” required libraries for the HDF5 C bindings.
  • HDF5_CXX_LIBRARIES โ€” required libraries for the HDF5 C++ bindings.
  • HDF5_Fortran_LIBRARIES โ€” required libraries for the HDF5 Fortran bindings.
  • HDF5_C_HL_LIBRARIES โ€” required libraries for the high-level C bindings, if the HL component is enabled.
  • HDF5_CXX_HL_LIBRARIES โ€” required libraries for the high-level C++ bindings, if the HL component is enabled.
  • HDF5_Fortran_HL_LIBRARIES โ€” required libraries for the high-level Fortran bindings, if the HL component is enabled. ๐Ÿ’–

Cache Variables

These cache variables may also get set, keep an eye out ๐Ÿ‘€:

  • HDF5_C_COMPILER_EXECUTABLE โ€” the path to the HDF5 C wrapper compiler.
  • HDF5_CXX_COMPILER_EXECUTABLE โ€” the path to the HDF5 C++ wrapper compiler.
  • HDF5_Fortran_COMPILER_EXECUTABLE โ€” the path to the HDF5 Fortran wrapper compiler.
  • HDF5_C_COMPILER_EXECUTABLE_NO_INTERROGATE โ€” added in version 3.6. The path to the primary C compiler which is also the HDF5 wrapper. Heads up: this variable is used only in module mode. ๐Ÿงš
  • HDF5_CXX_COMPILER_EXECUTABLE_NO_INTERROGATE โ€” added in version 3.6. The path to the primary C++ compiler which is also the HDF5 wrapper. Again, used only in module mode.
  • HDF5_Fortran_COMPILER_EXECUTABLE_NO_INTERROGATE โ€” added in version 3.6. The path to the primary Fortran compiler which is also the HDF5 wrapper. Module mode only, iykyk.
  • HDF5_DIFF_EXECUTABLE โ€” the path to the HDF5 dataset comparison tool (h5diff).

Hints

Okay so these variables can be set before you call find_package(HDF5), and they guide the search for the HDF5 library. Little cheat codes โœจ

  • HDF5_PREFER_PARALLEL โ€” added in version 3.4. Set this to boolean true to prefer parallel HDF5 (by default, serial is preferred, jsyk). This variable is used only in module mode.
  • HDF5_FIND_DEBUG โ€” added in version 3.9. Set it to boolean true and this module gives you extra debugging output. Lifesaver when things get messy ๐Ÿ˜ญ
  • HDF5_NO_FIND_PACKAGE_CONFIG_FILE โ€” added in version 3.8. Set this to boolean true to skip finding and using the CMake package configuration file (hdf5-config.cmake).
  • HDF5_USE_STATIC_LIBRARIES โ€” set this to a boolean value to decide whether or not to prefer a static link over a dynamic link for HDF5 and all of its dependencies.

Added in version 3.10: support for HDF5_USE_STATIC_LIBRARIES on Windows. ๐ŸชŸ

Examples

Examples: Finding HDF5

Finding HDF5, the classic:

find_package(HDF5)

Specifying a minimum required version of HDF5 to find:

find_package(HDF5 1.8.15)

Finding HDF5 and making it required โ€” and if HDF5 isn't found, processing stops with an error message. dramatic but fair ๐Ÿ’€

find_package(HDF5 1.8.15 REQUIRED)

Searching for static HDF5 libraries:

set(HDF5_USE_STATIC_LIBRARIES TRUE)
find_package(HDF5)

Specifying components to find high-level C and C++ functions:

find_package(HDF5 COMPONENTS C CXX HL)

Examples: Using HDF5

Finding HDF5 and linking it to a project target. slay ๐ŸŽ€

find_package(HDF5)
target_link_libraries(project_target PRIVATE HDF5::HDF5)

Using Fortran HDF5 and HDF5-HL functions:

find_package(HDF5 COMPONENTS Fortran HL)
target_link_libraries(project_target PRIVATE HDF5::HDF5)

FindHg

Finds the Mercurial command-line client executable (hg) and โ€” this is the cute part โ€” provides a command for extracting information from a Mercurial working copy:

find_package(Hg [<version>] [...])

Result Variables

This module defines these variables:

  • Hg_FOUND โ€” added in version 3.3. Boolean indicating whether the (requested version of) Mercurial client was found. ๐Ÿฆ‹
  • Hg_VERSION โ€” added in version 4.2. The version of Mercurial that was found.

Cache Variables

The following cache variables may also be set:

  • HG_EXECUTABLE โ€” absolute path to the Mercurial command-line client (hg).

Commands

This module provides the following command when the Mercurial client (hg) is found:

  • Hg_WC_INFO โ€” added in version 3.1. Extracts information of a Mercurial working copy:
Hg_WC_INFO(<dir> <var-prefix>)

This command defines the following variables if running the Mercurial client on the working copy located at the given location <dir> succeeds; otherwise a SEND_ERROR message is generated. so like, no silent failures here ๐Ÿ˜ค

  • <var-prefix>_WC_CHANGESET โ€” current changeset.
  • <var-prefix>_WC_REVISION โ€” current revision.

Deprecated Variables

These variables are provided for backward compatibility only:

  • HG_FOUND โ€” deprecated since version 4.2: use Hg_FOUND, which has the same value. Boolean indicating whether the (requested version of) Mercurial client was found.
  • HG_VERSION_STRING โ€” deprecated since version 4.2: use Hg_VERSION, which has the same value. The version of Mercurial found. ๐Ÿ™ˆ

Examples

Finding the Mercurial client and retrieving information about the current project's working copy:

find_package(Hg)
if(Hg_FOUND)
  Hg_WC_INFO(${PROJECT_SOURCE_DIR} Project)
  message("Current revision is ${Project_WC_REVISION}")
  message("Current changeset is ${Project_WC_CHANGESET}")
endif()

FindHSPELL

Finds the Hebrew spell-checker and morphology engine (Hspell):

find_package(HSPELL [<version>] [...])

Result Variables

This module defines these variables:

  • HSPELL_FOUND โ€” boolean indicating whether (the requested version of) Hspell was found. ๐Ÿ“
  • HSPELL_VERSION โ€” added in version 4.2. The version of Hspell found (x.y).
  • HSPELL_VERSION_MAJOR โ€” the major version of Hspell found.
  • HSPELL_VERSION_MINOR โ€” the minor version of Hspell found.

Cache Variables

The following cache variables may also be set:

  • HSPELL_INCLUDE_DIR โ€” the Hspell include directory.
  • HSPELL_LIBRARIES โ€” the libraries needed to use Hspell.

Deprecated Variables

Provided for backward compatibility:

  • HSPELL_VERSION_STRING โ€” deprecated since version 4.2: use HSPELL_VERSION, which has the same value. The version of Hspell found (x.y).

Examples

Finding Hspell:

find_package(HSPELL)

FindHTMLHelp

Finds the Microsoft HTML Help Compiler and its API, which is part of the HTML Help Workshop:

find_package(HTMLHelp [...])
Note, bestie: HTML Help Workshop is in maintenance mode only and is considered deprecated. For modern documentation, consider alternatives such as Microsoft Help Viewer for producing .mshc files or web-based documentation tools. ๐Ÿ’€

Result Variables

This module defines the following variable:

  • HTMLHelp_FOUND โ€” added in version 4.2. Boolean indicating whether HTML Help was found.

Cache Variables

The following cache variables may also be set:

  • HTML_HELP_COMPILER โ€” full path to the HTML Help Compiler (hhc.exe), used to compile .chm files.
  • HTML_HELP_INCLUDE_PATH โ€” directory containing htmlhelp.h, required for applications integrating the HTML Help API.
  • HTML_HELP_LIBRARY โ€” full path to the htmlhelp.lib library, required for linking applications that use the HTML Help API.

Examples

Finding the HTML Help Compiler:

find_package(HTMLHelp)
message(STATUS "HTML Help Compiler found at: ${HTML_HELP_COMPILER}")

FindIce

Added in version 3.1. ๐Ÿ’œ

Finds the Internet Communication Engine (Ice) programs, libraries and datafiles:

find_package(Ice [<version>] COMPONENTS <components>... [...])

Ice is an open-source remote procedure call (RPC) framework developed by ZeroC, and it provides SDKs for various languages so you can develop network applications. main character framework energy ngl ๐Ÿ‘‘

Added in version 3.4: imported targets for components plus many new *_EXECUTABLE variables. ๐ŸŽ‰

Added in version 3.7: Debug and Release library variants get found separately bestie, two different vibes, two different results, no mixing ๐Ÿ’…

Added in version 3.10: Ice 3.7 support is in the building ๐ŸŽ‰ โ€” and that includes the new components, the new programs, and the Nuget package. Slay.


๐ŸŽ€ Components ๐ŸŽ€

Ice isn't just one thing, it's a whole little ecosystem of libraries and programs (executables). This find module supports components, which you can specify using the find_package() command, so you can pick exactly which Ice libraries your CMake project gets to use. And heads up: executables that come with the Ice installation are always searched automatically, no matter which components you asked for. They just show up. Main character energy fr fr ๐Ÿ‘‘

Which components even exist? Depends on the Ice version you've got, bestie. But to successfully find Ice, you gotta specify at least one component:

find_package(Ice COMPONENTS <components>...)

Supported components include:

  • Freeze
  • Glacier2
  • Ice
  • IceBox
  • IceDB
  • IceDiscovery
  • IceGrid
  • IceLocatorDiscovery
  • IcePatch
  • IceSSL
  • IceStorm
  • IceUtil
  • IceXML
  • Slice

Ice 3.7 and later also include these C++11-specific components โœจ

  • Glacier2++11
  • Ice++11
  • IceBox++11
  • IceDiscovery++11
  • IceGrid++11
  • IceLocatorDiscovery++11
  • IceSSL++11
  • IceStorm++11

๐ŸŒˆ Imported Targets ๐ŸŒˆ

This module provides the following Imported Targets:

  • Ice::<component> โ€” Added in version 3.4. This is the target that encapsulates all the usage requirements for the specified Ice component (library), and it's available if that component was found. Write <component> in the same case as it's listed above, okay? Like, use Ice::Glacier2 for the Ice Glacier2 library, or Ice::Ice++11 for the Ice++11 library, etc. Case matters, don't play with me ๐Ÿ™ˆ

๐Ÿ’– Result Variables ๐Ÿ’–

This module defines these variables, and yes, there are a lot of them:

  • Ice_FOUND โ€” Boolean that tells you whether the (requested version of the) main programs, libraries and all requested components for using Ice were found. Basically the vibe check โœ…
  • Ice_VERSION โ€” the version of the Ice release that got found.
  • Ice_INCLUDE_DIRS โ€” the include directories holding the headers you need to use Ice.
  • Ice_LIBRARIES โ€” the component libraries you need to link against to use Ice.
  • Ice_SLICE_DIRS โ€” the data directories containing interface definitions (*.ice files) for Slice (Specification Language for Ice).

Ice component libraries are stored in these bad boys:

  • Ice_<COMPONENT>_FOUND โ€” Boolean, was the specified Ice component found or not. Write <COMPONENT> in uppercase.
  • Ice_<COMPONENT>_LIBRARIES โ€” the libraries provided by the specified Ice component. Again, <COMPONENT> goes in uppercase.

Slice programs are stored in:

  • Ice_SLICE2CONFLUENCE_EXECUTABLE โ€” Added in version 3.14. The path to the slice2confluence executable.
  • Ice_SLICE2CPP_EXECUTABLE โ€” the path to the slice2cpp executable.
  • Ice_SLICE2CS_EXECUTABLE โ€” the path to the slice2cs executable.
  • Ice_SLICE2FREEZEJ_EXECUTABLE โ€” the path to the slice2freezej executable.
  • Ice_SLICE2FREEZE_EXECUTABLE โ€” the path to the slice2freeze executable.
  • Ice_SLICE2HTML_EXECUTABLE โ€” the path to the slice2html executable.
  • Ice_SLICE2JAVA_EXECUTABLE โ€” the path to the slice2java executable.
  • Ice_SLICE2JS_EXECUTABLE โ€” Added in version 3.4. The path to the slice2js executable.
  • Ice_SLICE2MATLAB_EXECUTABLE โ€” Added in version 3.14. The path to the slice2matlab executable.
  • Ice_SLICE2OBJC_EXECUTABLE โ€” Added in version 3.10. The path to the slice2objc executable.
  • Ice_SLICE2PHP_EXECUTABLE โ€” the path to the slice2php executable.
  • Ice_SLICE2PY_EXECUTABLE โ€” the path to the slice2py executable.
  • Ice_SLICE2RB_EXECUTABLE โ€” the path to the slice2rb executable.

Ice programs are stored in:

  • Ice_GLACIER2ROUTER_EXECUTABLE โ€” Added in version 3.4. The path to the glacier2router executable.
  • Ice_ICEBOX_EXECUTABLE โ€” Added in version 3.4. The path to the icebox executable.
  • Ice_ICEBOX++11_EXECUTABLE โ€” Added in version 3.10. The path to the icebox++11 executable.
  • Ice_ICEBOXADMIN_EXECUTABLE โ€” Added in version 3.4. The path to the iceboxadmin executable.
  • Ice_ICEBOXD_EXECUTABLE โ€” Added in version 3.4. The path to the iceboxd executable.
  • Ice_ICEBOXNET_EXECUTABLE โ€” Added in version 3.4. The path to the iceboxnet executable.
  • Ice_ICEBRIDGE_EXECUTABLE โ€” Added in version 3.10. The path to the icebridge executable.
  • Ice_ICEGRIDADMIN_EXECUTABLE โ€” Added in version 3.4. The path to the icegridadmin executable.
  • Ice_ICEGRIDDB_EXECUTABLE โ€” Added in version 3.10. The path to the icegriddb executable.
  • Ice_ICEGRIDNODE_EXECUTABLE โ€” Added in version 3.4. The path to the icegridnode executable.
  • Ice_ICEGRIDNODED_EXECUTABLE โ€” Added in version 3.4. The path to the icegridnoded executable.
  • Ice_ICEGRIDREGISTRY_EXECUTABLE โ€” Added in version 3.4. The path to the icegridregistry executable.
  • Ice_ICEGRIDREGISTRYD_EXECUTABLE โ€” Added in version 3.4. The path to the icegridregistryd executable.
  • Ice_ICEPATCH2CALC_EXECUTABLE โ€” the path to the icepatch2calc executable.
  • Ice_ICEPATCH2CLIENT_EXECUTABLE โ€” Added in version 3.4. The path to the icepatch2client executable.
  • Ice_ICEPATCH2SERVER_EXECUTABLE โ€” Added in version 3.4. The path to the icepatch2server executable.
  • Ice_ICESERVICEINSTALL_EXECUTABLE โ€” Added in version 3.4. The path to the iceserviceinstall executable.
  • Ice_ICESTORMADMIN_EXECUTABLE โ€” Added in version 3.4. The path to the icestormadmin executable.
  • Ice_ICESTORMDB_EXECUTABLE โ€” Added in version 3.10. The path to the icestormdb executable.
  • Ice_ICESTORMMIGRATE_EXECUTABLE โ€” Added in version 3.4. The path to the icestormmigrate executable.

Ice database programs are stored in the following variables โ€” and quick context bestie: on Windows these come with the Ice installation; on other platforms you usually get them through the standard Berkeley DB packages ๐Ÿซถ

  • Ice_DB_ARCHIVE_EXECUTABLE โ€” Added in version 3.4. The path to the db_archive executable.
  • Ice_DB_CHECKPOINT_EXECUTABLE โ€” Added in version 3.4. The path to the db_checkpoint executable.
  • Ice_DB_DEADLOCK_EXECUTABLE โ€” Added in version 3.4. The path to the db_deadlock executable.
  • Ice_DB_DUMP_EXECUTABLE โ€” Added in version 3.4. The path to the db_dump executable.
  • Ice_DB_HOTBACKUP_EXECUTABLE โ€” Added in version 3.4. The path to the db_hotbackup executable.
  • Ice_DB_LOAD_EXECUTABLE โ€” Added in version 3.4. The path to the db_load executable.
  • Ice_DB_LOG_VERIFY_EXECUTABLE โ€” Added in version 3.4. The path to the db_log_verify executable.
  • Ice_DB_PRINTLOG_EXECUTABLE โ€” Added in version 3.4. The path to the db_printlog executable.
  • Ice_DB_RECOVER_EXECUTABLE โ€” Added in version 3.4. The path to the db_recover executable.
  • Ice_DB_STAT_EXECUTABLE โ€” Added in version 3.4. The path to the db_stat executable.
  • Ice_DB_TUNER_EXECUTABLE โ€” Added in version 3.4. The path to the db_tuner executable.
  • Ice_DB_UPGRADE_EXECUTABLE โ€” Added in version 3.4. The path to the db_upgrade executable.
  • Ice_DB_VERIFY_EXECUTABLE โ€” Added in version 3.4. The path to the db_verify executable.
  • Ice_DUMPDB_EXECUTABLE โ€” Added in version 3.4. The path to the dumpdb executable.
  • Ice_TRANSFORMDB_EXECUTABLE โ€” Added in version 3.4. The path to the transformdb executable.

๐Ÿฆ‹ Cache Variables ๐Ÿฆ‹

These cache variables can also be set manually, iykyk:

  • Ice_<PROGRAM>_EXECUTABLE โ€” the path to the specified <PROGRAM> executable. Here <PROGRAM> is the uppercase name of the Ice program as listed in the result variables of executables up above ๐Ÿ‘†
  • Ice_INCLUDE_DIR โ€” the directory containing the Ice headers.
  • Ice_SLICE_DIR โ€” the data directory containing interface definitions for Slice.
  • Ice_<COMPONENT>_LIBRARY โ€” the path to the library for the specified component. <COMPONENT> goes in uppercase, periodt.

๐ŸŒธ Hints ๐ŸŒธ

This module accepts the following variables:

  • Ice_HOME โ€” set this CMake variable to the root of the Ice installation and it'll go search for Ice in your custom little location ๐Ÿ 
Note: On Windows, Ice 3.7.0 and later hand out libraries via the NuGet package manager. The appropriate NuGet packages get searched for using CMAKE_PREFIX_PATH, or alternatively you can set Ice_HOME to the location of a specific NuGet package to restrict the search. Choose your fighter ๐Ÿ’…
  • ICE_HOME โ€” an environment variable (uppercased, notice the case difference bestie) that can also be set to the root of the Ice installation. But the Ice_HOME CMake variable takes precedence, so it wins the crown ๐Ÿ‘‘
  • Ice_DEBUG โ€” set this to boolean true and you get debug output from this module. Very demure, very helpful ๐Ÿ›
Note: In most cases, none of the above variables need to be set โ€” unless you've got multiple Ice versions installed and you need one specific one. On Windows, the most recent version is typically found using the registry. On Unix-like systems, programs, headers and libraries are usually found in standard locations, although Ice_SLICE_DIRS might not be detected automatically (commonly known locations are searched, so don't panic). All the other variables default based on the value of Ice_HOME, if it's set. You can also set Ice_HOME while selectively overriding specific locations for individual components. This might be required, for example, in newer versions of Visual Studio if the heuristics aren't sufficient to identify the correct programs and libraries for that specific Visual Studio version. So like, the defaults do their best but sometimes you gotta step in ๐Ÿซก

โญ Examples โญ

Finding the Ice core library and linking it to a project target:

find_package(Ice COMPONENTS Ice)
target_link_libraries(project_target PRIVATE Ice::Ice)

Finding the Ice core library and the IceSSL library, and linking both of them to a project target:

find_package(Ice COMPONENTS Ice IceSSL)
target_link_libraries(project_target PRIVATE Ice::Ice Ice::IceSSL)

Finding the Ice core library as a required component and the Ice Freeze library as an optional one:

find_package(Ice COMPONENTS Ice OPTIONAL_COMPONENTS Freeze)

FindIconv

Added in version 3.11.

Okay so this one goes hunting for the iconv() POSIX.1 functions on your system:

find_package(Iconv [<version>] [...] )

Bestie, plot twist: those iconv functions might already live in the standard C library, or they might show up externally as a whole extra library. Either way, we find them ๐Ÿ’…

Imported Targets

  • Iconv::Iconv โ€” the target that bundles up all the iconv usage requirements. Heads up: it only exists if iconv was actually found, no cap.

Result Variables

  • Iconv_FOUND โ€” a boolean saying whether (the requested version of) iconv support was found. Slay or sad, nothing in between.
  • Iconv_VERSION โ€” Added in version 3.21. The version of iconv we found, in x.y form.
Note: some libiconv implementations justโ€ฆ don't embed the version in their header files ๐Ÿ˜ญ In that case the Iconv_VERSION* variables come back empty. Not a bug, just how it is.
  • Iconv_VERSION_MAJOR โ€” Added in version 3.21. The major version of iconv.
  • Iconv_VERSION_MINOR โ€” Added in version 3.21. The minor version of iconv.
  • Iconv_INCLUDE_DIRS โ€” the include directories that hold the iconv headers.
  • Iconv_LIBRARIES โ€” the iconv libraries you'll be linking against.

Cache Variables

These cuties may also get set:

  • Iconv_IS_BUILT_IN โ€” a boolean telling you whether iconv support is coming from the C standard library or not. And like, even if the C library does provide iconv(), an external libiconv implementation hanging around might make this come out false. Vibe check accordingly ๐Ÿซถ
  • Iconv_INCLUDE_DIR โ€” the directory holding the iconv headers.
  • Iconv_LIBRARY โ€” the iconv library (in the case that it's not implicitly given in the C library).
Note: on POSIX platforms iconv might be part of the C library, and then the cache variables Iconv_INCLUDE_DIR and Iconv_LIBRARY might just be empty. No drama.

Examples

Finding iconv and linking it to a project target โ€” literally the whole plot:

find_package(Iconv)
target_link_libraries(project_target PRIVATE Iconv::Iconv)

FindIcotool

Finds icotool, the command-line program for converting and creating Win32 icon and cursor files:

find_package(Icotool [<version>] [...] )

Result Variables

  • Icotool_FOUND โ€” Added in version 3.3. Boolean telling you whether (the requested version of) icotool was found.
  • Icotool_VERSION โ€” Added in version 4.2. The version of icotool we found.

Cache Variables

  • ICOTOOL_EXECUTABLE โ€” the full path to the icotool tool.

Deprecated Variables

These ones are still here purely for backward compatibility, bestie โ€” they're giving legacy energy:

  • ICOTOOL_FOUND โ€” Deprecated since version 4.2: use Icotool_FOUND, which has the same value.
  • ICOTOOL_VERSION_STRING โ€” Deprecated since version 4.2: use Icotool_VERSION, which has the same value. It's the version of icotool found.

Examples

Finding icotool and running it in a process to make a .ico icon out of the source img.png image sitting in the current source directory โ€” chef's kiss ๐ŸŽ€

find_package(Icotool)
if(Icotool_FOUND)
  execute_process(
    COMMAND
      ${ICOTOOL_EXECUTABLE} -c -o ${CMAKE_CURRENT_BINARY_DIR}/img.ico img.png
  )
endif()

FindICU

Added in version 3.7.

Finds the International Components for Unicode (ICU) libraries and programs:

find_package(ICU [<version>] COMPONENTS <components>... [...] )
Added in version 3.11: support for static libraries on Windows. We love to see it.

Components

This module supports components, and you specify them like this:

find_package(ICU COMPONENTS <components>...)

Here's the full roster of supported components, no gatekeeping:

  • data โ€” finds the ICU Data library. On Windows this library component is named dt; otherwise any of these component names may be used, and the appropriate platform-specific library name gets selected automatically. Iconic.
  • i18n โ€” finds the ICU Internationalization library. On Windows this library component is named in; otherwise any of these component names may be used, and the appropriate platform-specific library name gets selected automatically.
  • io โ€” finds the ICU Stream and I/O (Unicode stdio) library.
  • le โ€” finds the deprecated ICU Layout Engine library, which got removed as of ICU version 58. Rip, she's gone ๐Ÿ’€
  • lx โ€” finds the ICU Layout Extensions Engine library, used for paragraph layout.
  • test โ€” finds the ICU test suits.
  • tu โ€” finds the ICU Tool Utility library.
  • uc โ€” finds the base ICU Common and Data libraries. Every other ICU library requires this one, so honestly you should include it when you're working with ICU components. Main character library fr.
At least one component should be specified for this module to successfully find ICU. Zero components = zero success, iykyk.

Imported Targets

  • ICU::<component> โ€” the target encapsulating the usage requirements for the specified ICU component, available only if that component is found. Write <component> in lowercase, exactly like the list above. So like, use ICU::i18n for the Internationalization library. ๐Ÿ’–

Result Variables

  • ICU_FOUND โ€” boolean saying whether the (requested version of) main ICU programs and libraries were found.
  • ICU_VERSION โ€” the version of the ICU release found.
  • ICU_INCLUDE_DIRS โ€” the include directories holding the ICU headers.
  • ICU_LIBRARIES โ€” component libraries to be linked.

The ICU programs get defined in these variables, bestie, brace yourself, there's a lot of them:

  • ICU_GENCNVAL_EXECUTABLE โ€” the path to the gencnval executable.
  • ICU_ICUINFO_EXECUTABLE โ€” the path to the icuinfo executable.
  • ICU_GENBRK_EXECUTABLE โ€” the path to the genbrk executable.
  • ICU_ICU-CONFIG_EXECUTABLE โ€” the path to the icu-config executable.
  • ICU_GENRB_EXECUTABLE โ€” the path to the genrb executable.
  • ICU_GENDICT_EXECUTABLE โ€” the path to the gendict executable.
  • ICU_DERB_EXECUTABLE โ€” the path to the derb executable.
  • ICU_PKGDATA_EXECUTABLE โ€” the path to the pkgdata executable.
  • ICU_UCONV_EXECUTABLE โ€” the path to the uconv executable.
  • ICU_GENCFU_EXECUTABLE โ€” the path to the gencfu executable.
  • ICU_MAKECONV_EXECUTABLE โ€” the path to the makeconv executable.
  • ICU_GENNORM2_EXECUTABLE โ€” the path to the gennorm2 executable.
  • ICU_GENCCODE_EXECUTABLE โ€” the path to the genccode executable.
  • ICU_GENSPREP_EXECUTABLE โ€” the path to the gensprep executable.
  • ICU_ICUPKG_EXECUTABLE โ€” the path to the icupkg executable.
  • ICU_GENCMN_EXECUTABLE โ€” the path to the gencmn executable.

ICU component libraries live in these variables:

  • ICU_<COMPONENT>_FOUND โ€” boolean telling you whether the ICU component was found. Write <COMPONENT> in uppercase. โœจ
  • ICU_<COMPONENT>_LIBRARIES โ€” libraries for the component. Again, <COMPONENT> in uppercase.

And the ICU datafiles:

  • ICU_MAKEFILE_INC โ€” the path to the Makefile.inc file.
  • ICU_PKGDATA_INC โ€” the path to the pkgdata.inc file.

Cache Variables

These may also get set:

  • ICU_<PROGRAM>_EXECUTABLE โ€” the path to the executable <PROGRAM>; write <PROGRAM> in uppercase. These correspond to the ICU program result variables listed above, so it's the same cast of characters, different variable.
  • ICU_INCLUDE_DIR โ€” the directory containing the ICU headers.
  • ICU_<COMPONENT>_LIBRARY โ€” the library for the ICU component. <COMPONENT> uppercase, as always ๐Ÿ’…

Hints

This module reads hints about search results from:

  • ICU_ROOT โ€” the root of the ICU installation. The environment variable ICU_ROOT may also be used; the ICU_ROOT variable takes precedence. Queen behaviour.
Note: in most cases, you won't need to set any of the above variables at all โ€” unless you've got multiple versions of ICU floating around and you specifically need one of them. Then it's hint time.

Examples

Finding ICU components and linking them to a project target:

find_package(ICU COMPONENTS i18n io uc)
target_link_libraries(project_target PRIVATE ICU::i18n ICU::io ICU::uc)

FindImageMagick

Finds ImageMagick, the software suite for displaying, converting, and manipulating raster images:

find_package(ImageMagick [<version>] [COMPONENTS <components>...] [...] )
Added in version 3.9: support for ImageMagick 7. Obsessed.

Components

This module supports components and searches for a set of ImageMagick tools. Typical components are the names of ImageMagick executables, but it's not limited to these โ€” future versions of ImageMagick may provide extra components that aren't listed here:

  • animate
  • compare
  • composite
  • conjure
  • convert
  • display
  • identify
  • import
  • mogrify
  • montage
  • stream

There are also components for these ImageMagick APIs:

  • Magick++ โ€” finds the ImageMagick C++ API.
  • MagickWand โ€” finds the ImageMagick MagickWand C API.
  • MagickCore โ€” finds the ImageMagick MagickCore low-level C API.

Components can be specified using the find_package() command:

find_package(ImageMagick [COMPONENTS <components>...])
If you specify no components at all, the module only searches for the ImageMagick executable directory. That's it, that's the whole search. ๐Ÿฆ‹

Imported Targets

  • ImageMagick::Magick++ โ€” Added in version 3.26. Target encapsulating the ImageMagick C++ API usage requirements, available if ImageMagick C++ is found.
  • ImageMagick::MagickWand โ€” Added in version 3.26. Target encapsulating the ImageMagick MagickWand C API usage requirements, available if MagickWand is found.
  • ImageMagick::MagickCore โ€” Added in version 3.26. Target encapsulating the ImageMagick MagickCore low-level C API usage requirements, available if MagickCore is found.

Result Variables

This module defines the following variables:

  • ImageMagick_FOUND โ€” boolean, bestie: was (the requested version of) ImageMagick found, along with all its requested components? yes or no ๐Ÿ’–
  • ImageMagick_VERSION โ€” added in version 4.2. the version of ImageMagick that got found, in the form <major>.<minor>.<patch>-<addendum> (so like 6.9.12-98, where 98 is the addendum release number โœจ)
ngl, version detection is only available for ImageMagick 6 and later ๐Ÿซถ
  • ImageMagick_INCLUDE_DIRS โ€” all the include directories you need to actually use ImageMagick ๐Ÿ“
  • ImageMagick_LIBRARIES โ€” the libraries you need to link against to use ImageMagick ๐Ÿ”—
  • ImageMagick_COMPILE_OPTIONS โ€” added in version 3.26. compile options of all the libraries โœจ
  • ImageMagick_<component>_FOUND โ€” boolean, was the ImageMagick <component> found ๐Ÿ‘‘
  • ImageMagick_<component>_EXECUTABLE โ€” the full path to the <component> executable ๐Ÿƒ
  • ImageMagick_<component>_INCLUDE_DIRS โ€” include directories holding the headers you need to use that ImageMagick <component> ๐ŸŽ€
  • ImageMagick_<component>_COMPILE_OPTIONS โ€” added in version 3.26. compile options of the ImageMagick <component> โœจ
  • ImageMagick_<component>_LIBRARIES โ€” added in version 3.31. the libraries you need to link against to use the ImageMagick <component> ๐Ÿ”—

Cache Variables

these cache variables may also be set:

  • ImageMagick_EXECUTABLE_DIR โ€” the full path to the directory that contains the ImageMagick executables ๐Ÿ“‚

Deprecated Variables

so these are here purely for backward compatibility vibes (they still work, they're just old):

  • ImageMagick_VERSION_STRING โ€” deprecated since version 4.2: use ImageMagick_VERSION, which has the same value. the version of ImageMagick found ๐Ÿ’€

Examples

finding ImageMagick with its Magick++ component and linking it to a project target โ€” slay:

find_package(ImageMagick COMPONENTS Magick++)
target_link_libraries(example PRIVATE ImageMagick::Magick++)

FindIntl

Added in version 3.2.

finds internationalization support โ€” like, the message translation functions such as gettext() ๐ŸŒโœจ

find_package(Intl [<version>] [...])

these functions originally come from the GNU libintl library, which is part of the GNU gettext utilities, but lowkey they may also be provided by the standard C library ๐Ÿซถ

Imported Targets

this module gives you the following Imported Targets:

  • Intl::Intl โ€” added in version 3.20. the target encapsulating the Intl usage requirements, available if Intl is found ๐Ÿ‘‘

Result Variables

this module defines these variables, bestie:

  • Intl_FOUND โ€” boolean, was (the requested version of) Intl found ๐Ÿ’–
  • Intl_VERSION โ€” added in version 3.21. the version of the found Intl implementation or library, in the format x.y.z โœจ
heads up: some Intl implementations don't embed the version in their header files. in that case the variables Intl_VERSION* will be empty ๐Ÿ˜ญ
  • Intl_VERSION_MAJOR โ€” added in version 3.21. the major version of Intl found
  • Intl_VERSION_MINOR โ€” added in version 3.21. the minor version of Intl found
  • Intl_VERSION_PATCH โ€” added in version 3.21. the patch version of Intl found
  • Intl_INCLUDE_DIRS โ€” include directories containing the headers you need to use Intl ๐Ÿ“
  • Intl_LIBRARIES โ€” the libraries you need to link against to use Intl ๐Ÿ”—

Cache Variables

these cache variables may also be set:

  • Intl_IS_BUILT_IN โ€” added in version 3.20. boolean saying whether the found Intl functionality is provided by the standard C library instead of a separate libintl library ๐Ÿงš
  • Intl_INCLUDE_DIR โ€” the directory containing the libintl.h header file ๐Ÿ“‚
  • Intl_LIBRARY โ€” the path to the Intl library (if any)
ok so on some platforms โ€” like Linux with GNU libc โ€” the gettext functions are just there in the C standard library and libintl isn't required at all. in that case Intl_LIBRARY and Intl_INCLUDE_DIR will be empty. no cap ๐Ÿ’…

Examples

finding the Intl support and linking the imported target for use in a project:

find_package(Intl)
target_link_libraries(app PRIVATE Intl::Intl)

See Also

  • The FindGettext module to find and use the GNU gettext tools (msgmerge, msgfmt, etc.) ๐Ÿ› ๏ธ

FindJasper

finds the JasPer Image Coding Toolkit โ€” yes, the one for handling image data in a whole variety of formats, such as the JPEG-2000 ๐Ÿ–ผ๏ธโœจ

find_package(Jasper [<version>] [...])

Imported Targets

this module provides the following Imported Targets:

  • Jasper::Jasper โ€” added in version 3.22. the target encapsulating the JasPer library usage requirements, available only if the library is found ๐Ÿ‘‘

Result Variables

this module defines these variables:

  • Jasper_FOUND โ€” added in version 3.3. boolean, was (the requested version of) JasPer found ๐Ÿ’–
  • Jasper_VERSION โ€” added in version 4.2. the version of JasPer found โœจ
  • JASPER_INCLUDE_DIRS โ€” added in version 3.22. the include directories you need to use the JasPer library ๐Ÿ“
  • JASPER_LIBRARIES โ€” the libraries you need to use JasPer ๐Ÿ”—

Cache Variables

these cache variables may also be set:

  • JASPER_INCLUDE_DIR โ€” the directory containing jasper/jasper.h and the other headers you need to use the JasPer library ๐Ÿ“‚
  • JASPER_LIBRARY_RELEASE โ€” the path to the release (optimized) variant of the JasPer library ๐Ÿš€
  • JASPER_LIBRARY_DEBUG โ€” the path to the debug variant of the JasPer library ๐Ÿ›

Deprecated Variables

backward-compatibility besties, still kicking around:

  • JASPER_FOUND โ€” deprecated since version 4.2: use Jasper_FOUND, which has the same value. boolean, was (the requested version of) JasPer found ๐Ÿ’€
  • JASPER_VERSION_STRING โ€” deprecated since version 4.2: superseded by the Jasper_VERSION. the version of JasPer found

Examples

finding the JasPer library and linking it to a project target:

find_package(Jasper)
target_link_libraries(project_target PRIVATE Jasper::Jasper)

FindJava

finds your Java installation and figures out its runtime tools and development components โ˜•๐Ÿ”ฅ

find_package(Java [<version>] [COMPONENTS <components>...] [...])

Added in version 3.10: support for Java 9+ version parsing ๐Ÿ‘‘

Components

this module supports optional components, which you can specify with the find_package() command:

find_package(Java [COMPONENTS <components>...])

the supported components include:

  • Runtime โ€” finds the Java Runtime Environment used to execute Java byte-compiled applications ๐Ÿƒ
  • Development โ€” finds the development tools (java, javac, javah, jar, and javadoc). specifying this component also implies the Runtime component ๐Ÿ› ๏ธ
  • IdlJ โ€” added in version 3.4. finds the Interface Description Language (IDL) to Java compiler ๐ŸŒธ
  • JarSigner โ€” added in version 3.4. finds the signer and verifier tool for Java Archive (JAR) files โœ๏ธ

if you specify no components at all, the module searches for the Runtime component by default. periodt ๐Ÿ’…

Result Variables

this module defines these variables:

  • Java_FOUND โ€” added in version 3.3. boolean, was (the requested version of) Java found with all the specified components ๐Ÿ’–
  • Java_<component>_FOUND โ€” boolean, was the <component> found ๐Ÿ‘‘
  • Java_VERSION โ€” the version of Java found. this gets set to: <major>[.<minor>[.<patch>[.<tweak>]]] โœจ
  • Java_VERSION_MAJOR โ€” the major version of Java found
  • Java_VERSION_MINOR โ€” the minor version of Java found
  • Java_VERSION_PATCH โ€” the patch version of Java found
  • Java_VERSION_TWEAK โ€” the tweak version of Java found (that's the part after the underscore character _)
  • Java_VERSION_STRING โ€” the version of Java found, e.g., 1.6.0_12
ok important: Java_VERSION and Java_VERSION_STRING are not guaranteed to be identical. for example, some Java versions may return Java_VERSION_STRING = 1.8.0_17 and Java_VERSION = 1.8.0.17. another example is the Java OEM, with Java_VERSION_STRING = 1.8.0-oem and Java_VERSION = 1.8.0. it's giving chaos but it's fine ๐Ÿ˜ญ

Cache Variables

these cache variables may also be set:

  • Java_JAVA_EXECUTABLE โ€” the full path to the Java runtime ๐Ÿƒ
  • Java_JAVAC_EXECUTABLE โ€” the full path to the Java compiler ๐Ÿ› ๏ธ
  • Java_JAVAH_EXECUTABLE โ€” the full path to the Java header generator
  • Java_JAVADOC_EXECUTABLE โ€” the full path to the Java documentation generator ๐Ÿ“–
  • Java_IDLJ_EXECUTABLE โ€” added in version 3.4. the full path to the Java idl compiler
  • Java_JAR_EXECUTABLE โ€” the full path to the Java archiver ๐Ÿ—„๏ธ
  • Java_JARSIGNER_EXECUTABLE โ€” added in version 3.4. the full path to the Java jar signer โœ๏ธ

Hints

this module accepts the following variables:

  • JAVA_HOME โ€” you can set this variable yourself to explicitly specify the installation directory of Java ๐Ÿ 

Examples

finding Java:

find_package(Java)

finding Java with at least the specified minimum version:

find_package(Java 1.8)

finding Java and making it required (so if Java isn't found, processing stops with an error message โ€” dramatic but fair ๐Ÿ’€):

find_package(Java 1.8 REQUIRED)

specifying exactly which Java components you need to find:

find_package(Java COMPONENTS Development JarSigner)

See Also

  • The FindJNI module to find Java Native Interface (JNI) ๐Ÿ‘‘
  • The UseJava module to use Java in CMake โ˜•

FindJNI

finds the Java Native Interface (JNI) include directories and libraries โ˜•๐Ÿ”—

find_package(JNI [<version>] [COMPONENTS <components>...] [...])

JNI is what lets Java code running in a Java Virtual Machine (JVM) or Dalvik Virtual Machine (DVM) on Android call โ€” and be called by โ€” native applications and libraries written in other languages such as C and C++ ๐Ÿงšโœจ

this module finds whether Java is installed and determines where the include files and libraries are. it also determines what the name of the library is ๐Ÿ‘‘

Added in version 3.24: imported targets, components, and Android NDK support ๐ŸŽ€

When you're using Android NDK, the corresponding package version gets reported and you can request a specific release. At Android API level 31 and above, the extra NativeHelper component can be requested too โœจ NativeHelper is also exposed as an implicit dependency of the JVM component (only if that doesn't cause a conflict, bestie, we're not about that drama) which gives you uniform access to JVM functions.

Components

This module supports optional components, and you specify them with the find_package() command:

find_package(JNI [COMPONENTS <components>...])

Supported components include:

  • AWT โ€” Added in version 3.24. Finds the Java Abstract Window Toolkit (AWT). ๐Ÿ’…
  • JVM โ€” Added in version 3.24. Finds the Java Virtual Machine (JVM).
  • NativeHelper โ€” Added in version 3.24. Finds the NativeHelper library on Android (libnativehelper.so), which exposes JVM functions such as JNI_CreateJavaVM().

If you don't specify any components, the module defaults are:

  • When targeting Android with API level 31 and above: the module looks for the NativeHelper component. For other Android API levels, components are by default not set.
  • When targeting other systems: the module looks for AWT and JVM components. ๐Ÿซถ

Imported Targets

This module provides the following Imported Targets:

  • JNI::JNI โ€” Added in version 3.24. The main target encapsulating all JNI usage requirements, available if jni.h is found.
  • JNI::AWT โ€” Added in version 3.24. Target encapsulating the Java AWT Native Interface (JAWT) library usage requirements, available if the AWT component is found.
  • JNI::JVM โ€” Added in version 3.24. Target encapsulating the Java Virtual Machine (JVM) library usage requirements, available if component JVM is found.
  • JNI::NativeHelper โ€” Added in version 3.24. Target encapsulating the NativeHelper library usage requirements, available when targeting Android API level 31 and above, and the library is found. ๐Ÿ‘‘

Result Variables

This module defines the following variables:

  • JNI_FOUND โ€” Boolean indicating whether (the requested version of) JNI was found.
  • JNI_<component>_FOUND โ€” Added in version 3.24. Boolean indicating whether the <component> was found.
  • JNI_VERSION โ€” Full Android NDK package version (including suffixes such as -beta3 and -rc1) or undefined otherwise.
  • JNI_VERSION_MAJOR โ€” Added in version 3.24. Android NDK major version or undefined otherwise.
  • JNI_VERSION_MINOR โ€” Added in version 3.24. Android NDK minor version or undefined otherwise.
  • JNI_VERSION_PATCH โ€” Added in version 3.24. Android NDK patch version or undefined otherwise.
  • JNI_INCLUDE_DIRS โ€” The include directories needed to use the JNI.
  • JNI_LIBRARIES โ€” The libraries (JAWT and JVM) needed to link against to use JNI.

Cache Variables

The following cache variables are also available to set or use:

  • JAVA_INCLUDE_PATH โ€” The directory containing the jni.h header.
  • JAVA_INCLUDE_PATH2 โ€” The directory containing machine-dependent headers jni_md.h and jniport.h. This variable is defined only if jni.h depends on one of these headers. In contrast, Android NDK jni.h can be typically used standalone. ๐Ÿ˜Œ
  • JAVA_AWT_INCLUDE_PATH โ€” The directory containing the jawt.h header.
  • JAVA_AWT_LIBRARY โ€” The path to the Java AWT Native Interface (JAWT) library.
  • JAVA_JVM_LIBRARY โ€” The path to the Java Virtual Machine (JVM) library.

Hints

This module accepts the following variables:

  • JAVA_HOME โ€” The caller can set this variable to specify the installation directory of Java explicitly.

Examples

Finding JNI and linking it to a project target, iconic behaviour honestly:

find_package(JNI)
target_link_libraries(project_target PRIVATE JNI::JNI)

Finding JNI with the AWT component specified and linking them to a project target:

find_package(JNI COMPONENTS AWT)
target_link_libraries(project_target PRIVATE JNI::JNI JNI::AWT)

A more common way to use Java and JNI in CMake is to use a dedicated UseJava module, and yes bestie that's the move:

find_package(Java)
find_package(JNI)
include(UseJava)

See Also

  • The FindJava module to find Java runtime tools and development components. ๐Ÿฆ‹
  • The UseJava module to use Java in CMake.

FindJPEG

Finds the Joint Photographic Experts Group (JPEG) library (libjpeg), photogenic queen that she is ๐Ÿ“ธ:

find_package(JPEG [<version>] [...])

Changed in version 3.12: Debug and Release JPEG library variants are now found separately. Slay.

Imported Targets

This module provides the following Imported Targets:

  • JPEG::JPEG โ€” Added in version 3.12. Target encapsulating the JPEG library usage requirements. It is available only when JPEG is found.

Result Variables

This module defines the following variables:

  • JPEG_FOUND โ€” Boolean indicating whether the (requested version of) JPEG library was found.
  • JPEG_VERSION โ€” Added in version 3.12. The version of JPEG library found.
  • JPEG_INCLUDE_DIRS โ€” Include directories containing headers needed to use JPEG.
  • JPEG_LIBRARIES โ€” Libraries needed to link to JPEG.

Cache Variables

The following cache variables may also be set:

  • JPEG_INCLUDE_DIR โ€” Directory containing the <jpeglib.h> and related header files.
  • JPEG_LIBRARY_RELEASE โ€” Added in version 3.12. Path to the release (optimized) variant of the JPEG library. โœจ
  • JPEG_LIBRARY_DEBUG โ€” Added in version 3.12. Path to the debug variant of the JPEG library. ๐Ÿ™ˆ

Deprecated Variables

The following variables are provided for backward compatibility:

  • JPEG_LIBRARY โ€” Deprecated since version 3.12: This variable has been superseded by the JPEG_LIBRARY_RELEASE and JPEG_LIBRARY_DEBUG variables. Path to the JPEG library.
She's giving legacy energy โ€” still here, but lowkey past her prime ๐Ÿ’€

Examples

Finding the JPEG library and linking it to a project target:

find_package(JPEG)
target_link_libraries(project_target PRIVATE JPEG::JPEG)

FindKDE3

Note: This module is specifically intended for KDE version 3, which is obsolete and no longer maintained. For modern application development using KDE technologies with CMake, use a newer version of KDE, and refer to the KDE documentation (https://develop.kde.org/docs/getting-started/building/cmake-build/). Like bestie this is straight-up ancient history, do not build new stuff with it, okay? ๐Ÿ˜ญ

Finds KDE 3 include directories, libraries, and KDE-specific preprocessor tools:

find_package(KDE3 [...])

This module provides usage requirements for building KDE 3 software and defines several helper commands to simplify working with KDE 3 in CMake.

Result Variables

This module defines the following variables:

  • KDE3_FOUND โ€” Boolean indicating whether KDE 3 was found.
  • KDE3_DEFINITIONS โ€” Compiler definitions required for compiling KDE 3 software.
  • KDE3_INCLUDE_DIRS โ€” The KDE and the Qt include directories, for use with the target_include_directories() command.
  • KDE3_LIB_DIR โ€” The directory containing the installed KDE 3 libraries, for use with the target_link_directories() command.
  • QT_AND_KDECORE_LIBS โ€” A list containing both the Qt and the kdecore library, typically used together when linking KDE 3. ๐Ÿซถ

Cache Variables

The following cache variables may also be set:

  • KDE3_INCLUDE_DIR โ€” The directory containing KDE 3 header files.
  • KDE3_DCOPIDL_EXECUTABLE โ€” The path to the dcopidl executable.
  • KDE3_DCOPIDL2CPP_EXECUTABLE โ€” The path to the dcopidl2cpp executable.
  • KDE3_KCFGC_EXECUTABLE โ€” The path to the kconfig_compiler executable.

Hints

This module accepts the following variables:

  • KDE3_BUILD_TESTS โ€” Provided as a user adjustable option. Set this variable to boolean true to build KDE 3 testcases.

Commands

This module provides the following commands to work with KDE 3 in CMake:

  • kde3_automoc โ€” Enables automatic processing with moc for the given source files:
kde3_automoc(<sources>...)

Call this command to enable automatic moc file handling. For example, if a source file (e.g., foo.cpp) contains include "foo.moc", a moc file for the corresponding header (foo.h) will be generated automatically. To skip processing for a specific source file, set the SKIP_AUTOMOC source file property. ๐Ÿงš

  • kde3_add_moc_files โ€” Processes header files with moc:
kde3_add_moc_files(<variable> <headers>...)

If not using kde3_automoc(), this command can be used to generate moc files for one or more <headers> files. The generated files are named <filename>.moc.cpp and the resulting list of these generated source files is stored in the variable named <variable> for use in project targets.

  • kde3_add_dcop_skels โ€” Generates KIDL and DCOP skeletons:
kde3_add_dcop_skels(<variable> <dcop-headers>...)

This command generates .kidl and DCOP skeleton source files from the given DCOP header files. The resulting list of generated source files is stored in the variable named <variable> for use in project targets. ๐Ÿ”ฅ

  • kde3_add_dcop_stubs โ€” Generates DCOP stubs:
kde3_add_dcop_stubs(<variable> <headers>...)

Use this command to generate DCOP stubs from one or more given header files. The resulting list of generated source files is stored in the variable named <variable> for use in project targets.

  • kde3_add_ui_files โ€” Adds Qt designer UI files:
kde3_add_ui_files(<variable> <ui-files>...)

This command creates the implementation files from the given Qt designer .ui files. The resulting list of generated files is stored in the variable named <variable> for use in project targets. ๐ŸŽ€

  • kde3_add_kcfg_files โ€” Adds KDE kconfig compiler files:
kde3_add_kcfg_files(<variable> <kcfgc-files>...)

Use this command to add KDE kconfig compiler files (.kcfgc) to the application/library. The resulting list of generated source files is stored in the variable named <variable> for use in project targets.

  • kde3_install_libtool_file โ€” Creates and installs a libtool file:
kde3_install_libtool_file(<target>)

This one creates and installs a basic libtool file for the target <target>. That's it, that's the whole vibe โœจ

  • kde3_add_executable โ€” adds a KDE executable:
kde3_add_executable(<name> <sources>...)

bestie this is functionally identical to the built-in add_executable() command. It was originally intended to support extra features in future versions of this module โ€” so like, it's the same thing in a cuter outfit ๐ŸŽ€

  • kde3_add_kpart โ€” creates a KDE plugin:
kde3_add_kpart(<name> [WITH_PREFIX] <sources>...)

This command creates a KDE plugin (KPart, kioslave, etc.) from one or more source files <sources>. It also creates and installs an appropriate libtool .la file, because it's an overachiever ๐Ÿ’…

If the WITH_PREFIX option is given, the resulting plugin name will be prefixed with lib. Otherwise, no prefix is added. Pick your fighter ๐Ÿซถ

  • kde3_add_kdeinit_executable โ€” creates a KDE application as a module loadable via kdeinit:
kde3_add_kdeinit_executable(<name> <sources>...)

This command creates a library named kdeinit_<name> from one or more source files <sources>. It also builds a small executable linked against this library. Two for the price of one, we love a bundle deal ๐Ÿ˜ญ๐Ÿ’–

Examples โœจ

Finding KDE 3, king of the one-liners:

find_package(KDE3)

FindKDE4

Note: This module is specifically intended for KDE version 4, which is obsolete and no longer maintained. Ngl, this is vintage. For modern application development using KDE technologies with CMake, use a newer version of KDE, and refer to the KDE documentation at https://develop.kde.org/docs/getting-started/building/cmake-build/ ๐Ÿฆ‹

Finds the KDE 4 installation:

find_package(KDE4 [...])

This module is a wrapper around the following upstream KDE 4 modules, so it's giving "middle manager of modules" energy ๐Ÿ‘‘

  • FindKDE4Internal.cmake โ€” upstream internal module, which finds the KDE 4 include directories, libraries, and KDE-specific preprocessor tools. It provides usage requirements for building KDE 4 software and defines several helper commands to simplify working with KDE 4 in CMake.
  • KDE4Macros.cmake โ€” upstream utility module that defines all additional KDE4-specific commands to use KDE 4 in CMake. For example: kde4_automoc(), kde4_add_executable(), kde4_add_library(), kde4_add_ui_files(), kde4_add_ui3_files(), kde4_add_kcfg_files(), kde4_add_kdeinit_executable(), etc.

Upstream KDE 4 modules are installed by the KDE 4 distribution package in $KDEDIRS/share/apps/cmake/modules/. This path is automatically appended to the CMAKE_MODULE_PATH variable when calling find_package(KDE4), so any additional KDE 4 modules can be included in the project with include(). For example ๐Ÿ“:

  • KDE4Defaults.cmake โ€” upstream internal module that sets some CMake options which are useful, but not required for building KDE 4 software. If these settings should be used, include this module after finding KDE 4:
find_package(KDE4)
include(KDE4Defaults)

For usage details, refer to the upstream KDE 4 documentation. For example, at the top of the FindKDE4Internal module a complete documentation is available for all variables and commands these modules provide. Iconic, honestly ๐Ÿ“š

Result Variables ๐ŸŒธ

This module defines the following variables:

  • KDE4_FOUND โ€” Boolean indicating whether KDE 4 was found. This variable is set by the upstream FindKDE4Internal module. (So like, not this module's fault if it's weird, iykyk ๐Ÿ’€)

Hints ๐Ÿ’ก

This module accepts the following variables before calling the find_package(KDE4):

  • ENV{KDEDIRS} โ€” environment variable containing the path to the KDE 4 installation.

KDE 4 is searched in the following directories in the given order โ€” respect the queue bestie ๐Ÿงš:

  1. CMAKE_INSTALL_PREFIX variable
  2. KDEDIRS environment variable
  3. /opt/kde4 path

Examples โœจ

Example: Basic Usage

Finding KDE 4 as required and using it in CMake:

find_package(KDE4 REQUIRED)

set(sources main.cpp mywidget.cpp mypart.cpp)

# The kde4_*() commands are provided by the KDE4Macros module, which is
# included automatically by FindKDE4, if KDE4 is found:
kde4_automoc(${sources})
kde4_add_executable(example ${sources})

target_include_directories(example PRIVATE ${KDE4_INCLUDES})
target_link_libraries(example PRIVATE ${KDE4_KDEUI_LIBS} ${KDE4_KPARTS_LIBS})

install(TARGETS example DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES kfoo.desktop DESTINATION ${XDG_APPS_DIR})

In the following example this module is used to find KDE 4 installation. Buckle up, this one's a whole journey ๐ŸŽข

project(kfoo)

find_package(KDE4 REQUIRED)

# Append path from where to include local project modules if any:
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)

include_directories(${KDE4_INCLUDE_DIRS})
add_definitions(${KDE4_DEFINITIONS})

set(sources main.cpp myappl.cpp view.cpp)

# If Qt designer UI files version 3 or 4 are available add them to the
# sources variable:
kde4_add_ui_files(sources maindialog.ui logindialog.ui)
kde4_add_ui3_files(sources printerdlg.ui previewdlg.ui)

# If there are files for the kconfig_compiler add them this way:
kde4_add_kcfg_files(sources settings.kcfg)

# When everything is listed, probably automoc is wanted:
kde4_automoc(${sources})

# Finally, specify what to build:
kde4_add_executable(kfoo ${sources})

The kde4_add_executable() command is a slightly extended version of the CMake command add_executable(). Additionally, it does some more RPATH handling and supports the KDE4_ENABLE_FINAL variable. The first argument is the name of the executable followed by a list of source files. If a library needs to be created instead of an executable, the kde4_add_library() can be used. It is an extended version of the add_library() command. It adds support for the KDE4_ENABLE_FINAL variable and under Windows it adds the -DMAKE_KFOO_LIB to the compile flags ๐ŸชŸ

find_package(KDE4 REQUIRED)

# ...

kde4_add_library(kfoo ${sources})

# Optionally, set the library version number if needed:
set_target_properties(kfoo PROPERTIES VERSION 5.0.0 SOVERSION 5)

KDE is very modular, so if a KPart, a control center module, or an ioslave needs to be created, here's how to do it:

find_package(KDE4 REQUIRED)
# ...
kde4_add_plugin(kfoo ${sources})

Now, the application/library/plugin probably needs to link to some libraries. For this use the standard target_link_libraries() command. For every KDE library there are variables available in the form of KDE4_FOO_LIBS. Use them to get also all depending libraries โ€” no cap, this is the good stuff ๐Ÿ”ฅ

target_link_libraries(kfoo ${KDE4_KDEUI_LIBS} ${KDE4_KIO_LIBS})

Example: The kdeinit Executable

In the following example, the so called kdeinit executable is created. The kde4_add_kdeinit_executable() command creates both an executable with the given name and a library with the given name prefixed with kdeinit_. The target_link_libraries() command adds all required libraries to the kdeinit_kbar library, and then links the kbar against the kdeinit_kbar:

find_package(KDE4 REQUIRED)

# ...

kde4_add_kdeinit_executable(kbar ${kbarSources})
target_link_libraries(kdeinit_kbar ${KDE4_KIO_LIBS})
target_link_libraries(kbar kdeinit_kbar)

install(TARGETS kbar DESTINATION ${CMAKE_INSTALL_BINDIR})
install(TARGETS kdeinit_kbar DESTINATION ${CMAKE_INSTALL_LIBDIR})

Example: Removing Compile Definitions

Sometimes, a default compile definition passed to the compiler needs to be removed. The remove_definitions() command can be used. For example, by default, the KDE4 build system sets the -DQT_NO_STL flag. If the project code uses some of the Qt STL compatibility layer, this flag should be removed ๐Ÿ™ˆ

find_package(KDE4 REQUIRED)

add_definitions(${KDE4_DEFINITIONS})

# ...

remove_definitions(-DQT_NO_STL)

FindLAPACK

Finds the installed Linear Algebra PACKage (LAPACK) Fortran library that implements the LAPACK linear-algebra interface at https://netlib.org/lapack/ โ€” math girlies rise ๐Ÿงฎ๐Ÿ’œ

find_package(LAPACK [...])

At least one of the C, CXX, or Fortran languages must be enabled. Like, pick one, bestie, it's not optional ๐Ÿ˜ญ

Imported Targets ๐Ÿ‘‘

This module provides the following Imported Targets:

  • LAPACK::LAPACK โ€” added in version 3.18. Target encapsulating the LAPACK usage requirements, available only if LAPACK is found. (So if it's not found, it just โœจdoesn't existโœจ โ€” check LAPACK_FOUND first, fr fr.)

Result Variables ๐ŸŒˆ

This module defines the following variables:

  • LAPACK_FOUND โ€” Boolean indicating whether the library implementing the LAPACK interface was found.
  • LAPACK_LINKER_FLAGS โ€” uncached list of required linker flags (excluding -l and -L).
  • LAPACK_LIBRARIES โ€” uncached list of libraries (using full path name) to link against to use LAPACK.
  • LAPACK95_LIBRARIES โ€” uncached list of libraries (using full path name) to link against to use LAPACK95.
  • LAPACK95_FOUND โ€” Boolean indicating whether the library implementing the LAPACK95 interface was found.

Input Variables ๐ŸŽ€

The following variables may be set to influence this module's behavior:

  • BLA_STATIC โ€” if ON, the static linkage will be used.
  • BLA_VENDOR โ€” set to one of the BLAS/LAPACK Vendors to search for BLAS only from the specified vendor. If not set, all vendors are considered. (Free-for-all mode ๐Ÿ’€)
  • BLA_F95 โ€” if ON, the module tries to find the BLAS95/LAPACK95 interfaces.
  • BLA_PREFER_PKGCONFIG โ€” added in version 3.20. If set, pkg-config will be used to search for a LAPACK library first and if one is found that is preferred. pkg-config girlies stay winning ๐Ÿซถ
  • BLA_PKGCONFIG_LAPACK โ€” added in version 3.25. If set, the pkg-config method will look for this module name instead of just lapack.
  • BLA_SIZEOF_INTEGER โ€” added in version 3.22. Specify the BLAS/LAPACK library integer size:
    • 4 โ€” search for a BLAS/LAPACK with 32-bit integer interfaces.
    • 8 โ€” search for a BLAS/LAPACK with 64-bit integer interfaces.
    • ANY โ€” search for any BLAS/LAPACK. Most likely, a BLAS/LAPACK with 32-bit integer interfaces will be found.
  • BLA_THREAD โ€” added in version 4.1. Specify the BLAS/LAPACK threading model:
    • SEQ โ€” sequential model.
    • OMP โ€” OpenMP model.
    • ANY โ€” search for any BLAS/LAPACK, if both are available most likely OMP will be found.

Ok so tiny footnote first: this one's only supported by NVIDIA NVPL right now. That's it, that's the whole note. ๐Ÿ’…

๐ŸŒธ Intel MKL

So if you wanna use the Intel MKL flavor of LAPACK, your project has to turn on at least one of the C or CXX languages first โ€” no languages, no MKL, that's the rule.

Then you set BLA_VENDOR to one of the Intel MKL variants, either straight from the command line like -DBLA_VENDOR=Intel10_64lp, or right in your project code:

set(BLA_VENDOR Intel10_64lp)
find_package(LAPACK)

And bestie, listen โ€” to actually build something with Intel MKL, the end user has to set up an Intel MKL environment first. That's on them, not on you. ๐Ÿซถ If you want the whole rundown, go peek at the FindBLAS module section, specifically the bit about Intel MKL.

โœจ Examples

Finding LAPACK and hooking it up to a project target, iconic:

find_package(LAPACK)
target_link_libraries(project_target PRIVATE LAPACK::LAPACK)

๐ŸŽ€ FindLATEX

Finds the LaTeX compiler plus all the LaTeX-adjacent software like BibTeX:

find_package(LATEX [...])

If you don't know what LaTeX is (the way I'd have to explain it: it's not "latex" like the glove material, ok ๐Ÿ˜ญ) โ€” it's a typesetting system for making technical and scientific documentation. Very academia, very "my thesis is 200 pages," we love her.

๐Ÿ’œ Components

Added in version 3.2.

You can optionally list components with the standard CMake syntax:

find_package(LATEX [COMPONENTS <component>...])

Here's the full roster of supported components:

  • PDFLATEX โ€” finds the PdfLaTeX compiler.
  • XELATEX โ€” finds the XeLaTeX compiler.
  • LUALATEX โ€” finds the LuaLaTeX compiler.
  • BIBTEX โ€” finds the BibTeX compiler.
  • BIBER โ€” finds the Biber compiler.
  • MAKEINDEX โ€” finds the MakeIndex compiler.
  • XINDY โ€” finds the xindy compiler.
  • DVIPS โ€” finds the DVI-to-PostScript (DVIPS) converter.
  • DVIPDF โ€” finds the DVIPDF converter.
  • PS2PDF โ€” finds the PS2PDF converter.
  • PDFTOPS โ€” finds the PDF-to-PostScript converter.
  • LATEX2HTML โ€” finds the converter for converting LaTeX documents to HTML.
  • HTLATEX โ€” finds the htlatex compiler.

๐Ÿฆ‹ Result Variables

This module sets these variables for you, no cap:

  • LATEX_FOUND โ€” boolean, tells you whether the LaTeX compiler and all of its required components were found.
  • LATEX_<component>_FOUND โ€” boolean, tells you whether that specific LaTeX <component> was found.

๐ŸŒธ Cache Variables

These cache variables might also get set:

  • LATEX_COMPILER โ€” the path to the LaTeX compiler.
  • PDFLATEX_COMPILER โ€” the path to the PdfLaTeX compiler.
  • XELATEX_COMPILER โ€” Added in version 3.2. The path to the XeLaTeX compiler.
  • LUALATEX_COMPILER โ€” Added in version 3.2. The path to the LuaLaTeX compiler.
  • BIBTEX_COMPILER โ€” the path to the BibTeX compiler.
  • BIBER_COMPILER โ€” Added in version 3.2. The path to the Biber compiler.
  • MAKEINDEX_COMPILER โ€” the path to the MakeIndex compiler.
  • XINDY_COMPILER โ€” Added in version 3.2. The path to the xindy compiler.
  • DVIPS_CONVERTER โ€” the path to the DVIPS converter.
  • DVIPDF_CONVERTER โ€” the path to the DVIPDF converter.
  • PS2PDF_CONVERTER โ€” the path to the PS2PDF converter.
  • PDFTOPS_CONVERTER โ€” Added in version 3.2. The path to the pdftops converter.
  • LATEX2HTML_CONVERTER โ€” the path to the LaTeX2Html converter.
  • HTLATEX_COMPILER โ€” Added in version 3.2. The path to the htlatex compiler.

๐Ÿ’– Examples

Finding LaTeX in a project, easy:

find_package(LATEX)

Finding the LaTeX compiler and telling CMake which extra LaTeX components have to be there before LaTeX counts as found:

find_package(LATEX COMPONENTS PDFLATEX)

if(LATEX_FOUND)
  execute_process(COMMAND ${LATEX_COMPILER} ...)
  execute_process(COMMAND ${PDFLATEX_COMPILER} ...)
endif()

Or go off and name multiple components at once:

find_package(LATEX COMPONENTS BIBTEX PS2PDF)

if(LATEXT_FOUND)
  # ...
endif()
Heads up bestie: that last check is spelled LATEXT_FOUND in the original โ€” yes, with the extra T. Not me, not a typo I introduced, it's literally what the docs say. Copy it exactly and don't come for me. ๐Ÿ’€

โญ FindLibArchive

Finds the libarchive library and its include directories:

find_package(LibArchive [<version>] [...])

Libarchive is a multi-format archive and compression library โ€” little legend handles All The Formats for you. ๐Ÿ”ฅ

๐Ÿ‘‘ Imported Targets

This module gives you these Imported Targets:

  • LibArchive::LibArchive โ€” Added in version 3.17. A target that bundles up libarchive's usage requirements. Only available if libarchive is found, obviously.

๐ŸŒˆ Result Variables

This module defines these:

  • LibArchive_FOUND โ€” boolean, says whether (the version you asked for of) libarchive was found.
  • LibArchive_VERSION โ€” a 3-component version string (major.minor.patch) of the libarchive that was found.
    • Added in version 3.6: support for a new libarchive version string format. Starting from libarchive version 3.2, a different preprocessor macro is used in the header to define the version. In CMake 3.5 and earlier, this variable only gets set for libarchive versions 3.1 and earlier. In CMake 3.6 and newer, it gets set for all libarchive versions. Glow-up behavior, honestly. โœจ
  • LibArchive_INCLUDE_DIRS โ€” the include search path for using libarchive.
  • LibArchive_LIBRARIES โ€” the libraries to link against for libarchive.

๐Ÿซถ Examples

Finding libarchive and linking it to a project target:

find_package(LibArchive)
target_link_libraries(project_target PRIVATE LibArchive::LibArchive)

๐Ÿงš FindLibinput

Added in version 3.14.

Finds the libinput library โ€” the one that handles input devices in Wayland compositors and also provides a generic X.Org input driver:

find_package(Libinput [<version>] [...])

๐Ÿ“ Imported Targets

This module provides these Imported Targets:

  • Libinput::Libinput โ€” the target encapsulating the libinput library usage requirements, available only if the library is found.

๐Ÿ’œ Result Variables

This module defines these variables:

  • Libinput_FOUND โ€” boolean, says whether the (requested version of the) libinput library was found.
  • Libinput_VERSION โ€” the version of libinput that was found.
  • Libinput_LIBRARIES โ€” the libraries to link against to use libinput.
  • Libinput_INCLUDE_DIRS โ€” the include directories holding the headers you need to use libinput.
  • Libinput_COMPILE_OPTIONS โ€” the compile options you need to use libinput. You can pass these to the target_compile_options() command when you're not using the Libinput::Libinput imported target.

๐ŸŽ€ Examples

Finding libinput and linking it to a project target:

find_package(Libinput)
target_link_libraries(project_target PRIVATE Libinput::Libinput)

๐Ÿฆ‹ FindLibLZMA

Finds liblzma โ€” the data compression library that implements LZMA (the Lempel-Ziv-Markov chain algorithm, yes that's a mouthful, no I will not be pronouncing it ๐Ÿ˜ญ):

find_package(LibLZMA [<version>] [...])

โญ Imported Targets

This module provides this Imported Target:

  • LibLZMA::LibLZMA โ€” Added in version 3.14. The target encapsulating liblzma's usage requirements, available only if liblzma is found.

๐ŸŒธ Result Variables

This module defines these:

  • LibLZMA_FOUND โ€” Added in version 3.3. Boolean, says whether (the requested version of) liblzma was found.
  • LibLZMA_VERSION โ€” Added in version 4.2. The version of liblzma that was found (given as a string, like for example 5.0.3).
  • LIBLZMA_INCLUDE_DIRS โ€” the include directories holding the headers you need to use liblzma.
  • LIBLZMA_LIBRARIES โ€” the libraries you need to link against to use liblzma.

๐Ÿ’… Cache Variables

These cache variables might also get set:

  • LIBLZMA_HAS_AUTO_DECODER โ€” boolean sanity check result, says whether the lzma_auto_decoder() function (that's the automatic decoder functionality) is found in liblzma. Required.
  • LIBLZMA_HAS_EASY_ENCODER โ€” boolean sanity check result, says whether the lzma_easy_encoder() function (the basic encoder API) is found in liblzma. Required.
  • LIBLZMA_HAS_LZMA_PRESET โ€” boolean sanity check result, says whether the lzma_lzma_preset() function (preset compression configuration) is found in liblzma. Required.

๐Ÿ™ˆ Deprecated Variables

These are kept around purely for backward compatibility:

  • LIBLZMA_FOUND โ€” Deprecated since version 4.2: use LibLZMA_FOUND, which holds the same value. Boolean, says whether (the requested version of) liblzma was found.
  • LIBLZMA_VERSION โ€” Added in version 3.26. Deprecated since version 4.2: superseded by LibLZMA_VERSION. The version of liblzma that was found.
  • LIBLZMA_VERSION_STRING โ€” Deprecated since version 3.26: superseded by LIBLZMA_VERSION (and LibLZMA_VERSION). The version of liblzma that was found.
  • LIBLZMA_VERSION_MAJOR โ€” Deprecated since version 3.26. The major version of liblzma that was found.
  • LIBLZMA_VERSION_MINOR โ€” Deprecated since version 3.26. The minor version of liblzma that was found.
  • LIBLZMA_VERSION_PATCH โ€” Deprecated since version 3.26. The patch version of liblzma that was found.

๐Ÿ”ฅ Examples

Finding liblzma and linking it to a project target:

find_package(LibLZMA)
target_link_libraries(project_target PRIVATE LibLZMA::LibLZMA)

๐ŸŽ€ FindLibXml2

Finds the XML processing library, aka libxml2:

find_package(LibXml2 [<version>] [...])

๐Ÿ’– Imported Targets

This module provides these Imported Targets:

  • LibXml2::LibXml2 โ€” Added in version 3.12. The target encapsulating libxml2's usage requirements, available only if the library is found.
  • LibXml2::xmllint โ€” Added in version 3.17. The target encapsulating the xmllint command-line executable, available only if the xmllint executable is found.

โœจ Result Variables

This module defines these variables:

  • LibXml2_FOUND โ€” Added in version 3.3. Boolean, says whether the (requested version of the) libxml2 library was found.
  • LibXml2_VERSION โ€” Added in version 4.2. The version of libxml2 that was found.
  • LIBXML2_INCLUDE_DIRS โ€” the include directories you need to use libxml2.
  • LIBXML2_LIBRARIES โ€” the libraries you need to link against to use libxml2.
  • LIBXML2_DEFINITIONS โ€” the compiler switches required for using libxml2.

๐ŸŒˆ Other Variables

  • LibXml2_USE_STATIC_LIBS โ€” Added in version 4.3. Set it to TRUE to use static libraries. The default is FALSE.

๐Ÿ“ Cache Variables

These cache variables might also get set:

  • LIBXML2_INCLUDE_DIR โ€” the include directory containing the libxml2 headers.
  • LIBXML2_LIBRARY โ€” the path to the libxml2 library itself, bestie.
  • LIBXML2_XMLLINT_EXECUTABLE โ€” the path to the XML checking tool xmllint that ships with libxml2. yes it's a whole vibe, it comes free with the library ๐Ÿ’…

๐Ÿฅ€ Deprecated Variables

okay so these are the OG variables, kept around purely for backward compatibility. still here, still slaying, justโ€ฆ retired:

  • LIBXML2_FOUND โ€” Deprecated since version 4.2: use LibXml2_FOUND instead, they literally have the same value fr fr. Boolean telling you whether the (requested version of the) libxml2 library was found.
  • LIBXML2_VERSION_STRING โ€” Deprecated since version 4.2: superseded by LibXml2_VERSION. It's the version of libxml2 that was found.

๐ŸŽ€ Examples

finding the libxml2 library and linking it to a project target, iconic behaviour:

find_package(LibXml2)
target_link_libraries(project_target PRIVATE LibXml2::LibXml2)

๐Ÿ’– FindLibXslt

she finds the XSL Transformations, Extensible Stylesheet Language Transformations (XSLT) library โ€” libxslt, duh:

find_package(LibXslt [<version>] [...])

๐Ÿ‘‘ Imported Targets

Added in version 3.18.

this module gives you these imported targets, and honestly? they ate:

  • LibXslt::LibXslt โ€” target that encapsulates the usage requirements of the libxslt library. only available if libxslt is actually found, obviously.
  • LibXslt::LibExslt โ€” target that encapsulates the usage requirements for the libexslt library. she's part of the libxslt package, and libexslt provides optional extensions to XSLT on top of libxslt. available only if the main libxslt library is found.
  • LibXslt::xsltproc โ€” target that encapsulates the command-line XSLT processor (xsltproc). this tool is part of the libxslt package and applies XSLT stylesheets to XML documents as a command-line alternative to the libxslt library. available only if the xsltproc executable is found. main character energy ๐Ÿงš

โœจ Result Variables

this module defines the following variables:

  • LibXslt_FOUND โ€” Added in version 3.3. Boolean indicating whether (the requested version of) libxslt was found.
  • LibXslt_VERSION โ€” Added in version 4.2. The version of libxslt found.
  • LIBXSLT_LIBRARIES โ€” the libraries you need to link to libxslt.
  • LIBXSLT_DEFINITIONS โ€” compiler switches required for using libxslt.
  • LIBXSLT_EXSLT_LIBRARIES โ€” libraries needed when linking against the exslt library. heads up: these are available and needed only when you're using the exslt library.

๐Ÿฆ‹ Cache Variables

these cache variables may also get set:

  • LIBXSLT_INCLUDE_DIR โ€” the directory containing libxslt/xslt.h and the other libxslt header files.
  • LIBXSLT_EXSLT_INCLUDE_DIR โ€” Added in version 3.18. the directory containing libexslt/exslt.h and the other exslt-related headers. these are needed only when you're using exslt (the extensions to XSLT).
  • LIBXSLT_XSLTPROC_EXECUTABLE โ€” full path to the XSLT processor executable xsltproc, if it was found. this path is optional, no pressure ๐Ÿซถ

๐Ÿฅ€ Deprecated Variables

again, backward compatibility only:

  • LIBXSLT_FOUND โ€” Deprecated since version 4.2: use LibXslt_FOUND, which has the same value. Boolean indicating whether (the requested version of) libxslt was found.
  • LIBXSLT_VERSION_STRING โ€” Deprecated since version 4.2: superseded by LibXslt_VERSION. The version of libxslt found.

๐ŸŽ€ Examples

finding the libxslt library and linking it to a project target:

find_package(LibXslt)
target_link_libraries(foo PRIVATE LibXslt::LibXslt)

when your project also needs the extensions to XSLT (exslt) library, you link both targets. both. not one. both ๐Ÿ’…

find_package(LibXslt)
target_link_libraries(foo PRIVATE LibXslt::LibXslt LibXslt::LibExslt)

and here's how you'd use the XSLT processor in a custom command build rule, lowkey a serve:

find_package(LibXslt)

if(TARGET LibXslt::xsltproc)
  # Executed when some build rule depends on example.html.
  add_custom_command(
    OUTPUT example.html
    COMMAND LibXslt::xsltproc -o example.html transform.xslt example.xml
  )
endif()

๐ŸŒธ FindLTTngUST

Added in version 3.6.

finds the LTTng (https://lttng.org/) โ€” that's Linux Trace Toolkit: next generation โ€” user space tracing library, aka LTTng-UST:

find_package(LTTngUST [<version>] [...])

๐Ÿ‘‘ Imported Targets

this module provides this imported target:

  • LTTng::UST โ€” the target providing the LTTng-UST library usage requirements. available only when LTTng-UST is found, periodt.

โœจ Result Variables

this module defines the following variables:

  • LTTngUST_FOUND โ€” Boolean indicating whether the (requested version of) LTTng-UST library was found.
  • LTTngUST_VERSION โ€” Added in version 4.2. The LTTng-UST version.
  • LTTNGUST_HAS_TRACEF โ€” TRUE if the tracef() API is available in the system's LTTng-UST.
  • LTTNGUST_HAS_TRACELOG โ€” TRUE if the tracelog() API is available in the system's LTTng-UST.

๐Ÿฆ‹ Cache Variables

these cache variables may also get set:

  • LTTNGUST_INCLUDE_DIRS โ€” the LTTng-UST include directories.
  • LTTNGUST_LIBRARIES โ€” the libraries needed to use LTTng-UST.

๐Ÿฅ€ Deprecated Variables

backward compatibility club, membership: these two:

  • LTTNGUST_FOUND โ€” Deprecated since version 4.2: use LTTngUST_FOUND, which has the same value. Boolean indicating whether the (requested version of) the LTTng-UST library was found.
  • LTTNGUST_VERSION_STRING โ€” Deprecated since version 4.2: superseded by LTTngUST_VERSION. The LTTng-UST version.

๐ŸŽ€ Examples

finding the LTTng-UST library and linking it to a project target:

find_package(LTTugNST)
target_link_libraries(project_target PRIVATE LTTng::UST)

๐ŸŒˆ FindLua

finds the Lua library:

find_package(Lua [<version>] [...])

Lua is a embeddable scripting language. (the original said "a embeddable", we don't fix, we report ๐Ÿซก)

Added in version 3.18: support for Lua 5.4.

Added in version 4.3: support for Lua 5.5.

okay so when you're working with Lua, its library headers are intended to be included in project source code like this:

#include <lua.h>

and not like this:

#include <lua/lua.h>

why? because the location of Lua headers may differ across platforms and may exist in locations other than lua/. so write it the first way, bestie, trust ๐Ÿ’–

โœจ Result Variables

this module defines the following variables:

  • Lua_FOUND โ€” Added in version 3.3. Boolean indicating whether (the requested version of) Lua was found.
  • Lua_VERSION โ€” Added in version 4.2. The version of Lua found.
  • Lua_VERSION_MAJOR โ€” Added in version 4.2. The major version of Lua found.
  • Lua_VERSION_MINOR โ€” Added in version 4.2. The minor version of Lua found.
  • Lua_VERSION_PATCH โ€” Added in version 4.2. The patch version of Lua found.
  • LUA_LIBRARIES โ€” the libraries you need to link against to use Lua. this list includes both the lua and lualib libraries, no crumbs left behind.

๐Ÿฆ‹ Cache Variables

this cache variable may also get set:

  • LUA_INCLUDE_DIR โ€” the directory containing the Lua header files, such as lua.h, lualib.h, and lauxlib.h, needed to use Lua.

๐Ÿฅ€ Deprecated Variables

the backward-compat crew:

  • LUA_FOUND โ€” Deprecated since version 4.2: use Lua_FOUND, which has the same value. Boolean indicating whether (the requested version of) Lua was found.
  • LUA_VERSION_STRING โ€” Deprecated since version 4.2: superseded by Lua_VERSION. The version of Lua found.
  • LUA_VERSION_MAJOR โ€” Deprecated since version 4.2: superseded by Lua_VERSION_MAJOR. The major version of Lua found.
  • LUA_VERSION_MINOR โ€” Deprecated since version 4.2: superseded by Lua_VERSION_MINOR. The minor version of Lua found.
  • LUA_VERSION_PATCH โ€” Deprecated since version 4.2: superseded by Lua_VERSION_PATCH. The patch version of Lua found.

๐ŸŽ€ Examples

finding the Lua library and creating an interface imported target that encapsulates its usage requirements for linking to a project target. look at her go:

find_package(Lua)

if(Lua_FOUND AND NOT TARGET Lua::Lua)
  add_library(Lua::Lua INTERFACE IMPORTED)
  set_target_properties(
    Lua::Lua
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE Lua::Lua)

๐Ÿฆ‹ FindLua50

Note: this module is intended specifically for Lua version branch 5.0, which is obsolete and not maintained anymore. obsolete. not maintained. gone but not forgotten ๐Ÿ˜ญ in new code, use the latest supported Lua version and the version-agnostic module FindLua instead. please. for me.

finds the Lua library:

find_package(Lua50 [...])

Lua is a embeddable scripting language.

when working with Lua, its library headers are intended to be included in project source code as:

#include <lua.h>

and not:

#include <lua/lua.h>

because the location of Lua headers may differ across platforms and may exist in locations other than lua/. same deal as before, it's not a phase ๐Ÿ’€

โœจ Result Variables

this module defines this variable:

  • Lua50_FOUND โ€” Added in version 3.3. Boolean indicating whether Lua was found.

๐Ÿฆ‹ Cache Variables

these cache variables may also get set:

  • LUA_INCLUDE_DIR โ€” the directory containing the Lua header files, such as lua.h, lualib.h, and lauxlib.h, needed to use Lua.
  • LUA_LIBRARIES โ€” the libraries needed to link against to use Lua. this list includes both the lua and lualib libraries.

๐Ÿฅ€ Deprecated Variables

one singular legend, kept for backward compatibility:

  • LUA50_FOUND โ€” Deprecated since version 4.2: use Lua50_FOUND, which has the same value. Boolean indicating whether Lua was found.

๐ŸŽ€ Examples

finding the Lua 5.0 library and creating an interface imported target that encapsulates its usage requirements for linking to a project target. retro but make it cute:

find_package(Lua50)

if(Lua50_FOUND AND NOT TARGET Lua50::Lua50)
  add_library(Lua50::Lua50 INTERFACE IMPORTED)
  set_target_properties(
    Lua50::Lua50
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE Lua50::Lua50)

โœจ See Also

  • The FindLua module ๐Ÿ’œ โ€” for finding Lua in a version-agnostic way (iykyk, this is the one you actually want most of the time).

๐Ÿš FindLua51

โš ๏ธ Note, bestie: this module is intended specifically for Lua version branch 5.1, which is obsolete and not maintained anymore. In new code, use the latest supported Lua version and the version-agnostic FindLua module instead. Likeโ€ฆ fr fr, 5.1 is giving vintage. Cute, but no.

Finds the Lua library:

find_package(Lua51 [<version>] [...])

Lua is an embeddable scripting language ๐ŸŒธ.

When working with Lua, its library headers are intended to be included in project source code as:

#include <lua.h>

and not as:

#include <lua/lua.h>

Why? Because the location of Lua headers may differ across platforms and may exist in locations other than lua/. The way that path is not universal ๐Ÿ˜ญ.

๐Ÿ’– Result Variables

This module defines the following variables:

  • Lua51_FOUND โ€” Added in version 3.3. Boolean indicating whether (the requested version of) Lua was found.
  • Lua51_VERSION โ€” Added in version 4.2. The version of Lua 5.1 found.

๐ŸŽ€ Cache Variables

The following cache variables may also be set:

  • LUA_INCLUDE_DIR โ€” the directory containing the Lua header files, such as lua.h, lualib.h, and lauxlib.h, needed to use Lua.
  • LUA_LIBRARIES โ€” libraries needed to link against to use Lua.

๐Ÿฆ‹ Deprecated Variables

The following variables are provided for backward compatibility (aka legacy era ๐Ÿ’€):

  • LUA51_FOUND โ€” Deprecated since version 4.2: use Lua51_FOUND, which has the same value. Boolean indicating whether (the requested version of) Lua was found.
  • LUA_VERSION_STRING โ€” Deprecated since version 4.2: use Lua51_VERSION, which has the same value. The version of Lua 5.1 found.

๐ŸŒˆ Examples

Finding the Lua 5.1 library and creating an imported target that encapsulates its usage requirements for linking to a project target โ€” this is the glow-up, bestie:

find_package(Lua51)

if(Lua51_FOUND AND NOT TARGET Lua51::Lua51)
  add_library(Lua51::Lua51 INTERFACE IMPORTED)
  set_target_properties(
    Lua51::Lua51
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE Lua51::Lua51)

โœจ See Also

  • The FindLua module ๐Ÿ’œ โ€” for finding Lua in a version-agnostic way.

๐Ÿงฎ FindMatlab

Finds MATLAB or MATLAB Compiler Runtime (MCR) and provides its tools, libraries and compilers to CMake:

find_package(Matlab [<version>] [COMPONENTS <components>...] [REGISTRY_VIEW <view>] [...])

The primary purpose of this module is to find the libraries associated with MATLAB or the MCR in order to be able to build MATLAB extensions (MEX files) ๐Ÿ”ฅ. But it can also be used:

  • to run specific commands in MATLAB in case MATLAB is available
  • for declaring MATLAB unit tests
  • to retrieve various information from MATLAB (MEX extensions, versions and release queries, ...)

Added in version 3.12: MATLAB Compiler Runtime (MCR) support ๐Ÿซถ.

Added in version 3.30: support for specifying a version range to find_package(), support for specifying the REGISTRY_VIEW argument to find_package(), plus the matlab_extract_all_installed_versions_from_registry() and matlab_get_all_valid_matlab_roots_from_registry() commands. The default behavior remained unchanged, by using the registry view TARGET. No cap, it just kept the old vibe โœจ.

๐Ÿ“Œ Note: the version given to the find_package() argument is the MATLAB version, which should not be confused with the MATLAB release name (e.g. R2023b). The matlab_get_version_from_release_name() and matlab_get_release_name_from_version() commands provide a mapping between the release name and the version. Two different name systems, iconic of them honestly ๐Ÿ™ˆ.

๐Ÿงฉ Components

This module supports optional components which can be specified using the find_package() command:

find_package(Matlab [COMPONENTS <components>...])

Supported components include:

  • ENG_LIBRARY โ€” Added in version 3.3. Finds the ENG library of MATLAB.
  • MAT_LIBRARY โ€” Added in version 3.7. Finds the MAT library of MATLAB.
  • MAIN_PROGRAM โ€” Added in version 3.3. Finds the MATLAB binary program. Note that this component is not available on the MCR version, and will yield an error if the MCR is found instead of the regular MATLAB installation ๐Ÿ˜ญ.
  • MEX_COMPILER โ€” Added in version 3.3. Finds the MEX compiler.
  • MCC_COMPILER โ€” Added in version 3.13. Finds the MCC compiler, included with the MATLAB Compiler add-on.
  • SIMULINK โ€” Added in version 3.3. Finds the Simulink environment.

๐Ÿ‘‘ Implicitly Found Components

The following components are always found unconditionally, without needing to be specified explicitly โ€” they just show up, main character energy:

  • MX_LIBRARY โ€” Changed in version 3.14: this component has been removed and is now always found unconditionally. Added in version 3.3. Finds the MATLAB mx library.
  • ENGINE_LIBRARY โ€” Changed in version 3.14: this component has been removed and is now always found unconditionally. Added in version 3.13. Finds the MATLAB engine library.
  • DATAARRAY_LIBRARY โ€” Changed in version 3.14: this component has been removed and is now always found unconditionally. Added in version 3.13. Finds the C++ MATLAB data array library.

If no components are specified, the module looks for the MX_LIBRARY, ENGINE_LIBRARY, and DATAARRAY_LIBRARY by default. So you're covered either way ๐Ÿ’….

๐ŸŽฏ Imported Targets

This module provides the following imported targets:

  • Matlab::mex โ€” Added in version 3.22. Target encapsulating the mex library usage requirements, always available for MATLAB installations. Available for MCR installations if provided by MCR.
  • Matlab::mx โ€” Added in version 3.22. Target encapsulating the usage requirements of the mx library of MATLAB (arrays), always available for MATLAB installations. Available for MCR installations if provided by MCR.
  • Matlab::eng โ€” Added in version 3.22. Target encapsulating the MATLAB engine library usage requirements. Available only if the ENG_LIBRARY component is requested.
  • Matlab::mat โ€” Added in version 3.22. Target encapsulating the MATLAB matrix library usage requirements. Available only if the MAT_LIBRARY component is requested.
  • Matlab::MatlabEngine โ€” Added in version 3.22. Target encapsulating the MATLAB C++ engine library usage requirements, always available for MATLAB R2018a and newer. Available for MCR installations if provided by MCR.
  • Matlab::MatlabDataArray โ€” Added in version 3.22. Target encapsulating the MATLAB C++ data array library usage requirements, always available for MATLAB R2018a and newer. Available for MCR installations if provided by MCR.

๐Ÿ’– Result Variables

This module defines the following variables:

  • Matlab_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) MATLAB installation was found. All variables below are defined if MATLAB is found.
  • Matlab_VERSION โ€” Added in version 3.27. The numerical version (e.g. 23.2.0) of MATLAB found. Not to be confused with the MATLAB release name (e.g. R2023b) that can be obtained with matlab_get_release_name_from_version(). When a MATLAB/MCR installation is found automatically and the Matlab_VERSION is not given, the version is queried from MATLAB directly (on Windows this may pop up a MATLAB window ๐Ÿ™ˆ) or from the MCR installation.
  • Matlab_ROOT_DIR โ€” Added in version 3.3. The final root of the MATLAB installation determined by this module.
  • Matlab_MAIN_PROGRAM โ€” Added in version 3.3. The MATLAB binary program. Available only if the component MAIN_PROGRAM is given in the find_package() argument.
  • Matlab_INCLUDE_DIRS โ€” Added in version 3.3. The path of the MATLAB libraries headers.
  • Matlab_MEX_LIBRARY โ€” library for MEX, always available for MATLAB installations. Available for MCR installations if provided by MCR.
  • Matlab_MX_LIBRARY โ€” the mx library of MATLAB (arrays), always available for MATLAB installations. Available for MCR installations if provided by MCR.
  • Matlab_ENG_LIBRARY โ€” MATLAB engine library. Available only if the component ENG_LIBRARY is requested.
  • Matlab_MAT_LIBRARY โ€” Added in version 3.7. MATLAB matrix library. Available only if the component MAT_LIBRARY is requested.
  • Matlab_ENGINE_LIBRARY โ€” Added in version 3.13. MATLAB C++ engine library, always available for MATLAB R2018a and newer. Available for MCR installations if provided by MCR.
  • Matlab_DATAARRAY_LIBRARY โ€” Added in version 3.13. MATLAB C++ data array library, always available for MATLAB R2018a and newer. Available for MCR installations if provided by MCR.
  • Matlab_LIBRARIES โ€” the whole set of libraries of MATLAB. The full collection, the entire friend group ๐Ÿซถ.
  • Matlab_MEX_COMPILER โ€” Added in version 3.3. The MEX compiler of MATLAB. Currently not used. Available only if the component MEX_COMPILER is requested.
  • Matlab_MCC_COMPILER โ€” Added in version 3.13. The mcc compiler of MATLAB. Included with the MATLAB Compiler add-on. Available only if the component MCC_COMPILER is requested.

๐ŸŽ€ Cache Variables

The following cache variables may also be set:

  • Matlab_MEX_EXTENSION โ€” Added in version 3.3. The extension of the MEX files for the current platform (given by MATLAB).
  • Matlab_ROOT_DIR โ€” Added in version 3.3. The location of the root of the MATLAB installation found. If this value is changed by the user, the result variables are recomputed. Live update behavior, slay โœจ.

๐Ÿงš Input Variables

Users or projects may set the following variables to configure the module behavior before calling find_package(Matlab):

  • Matlab_ROOT โ€” Added in version 3.25. Default value for the Matlab_ROOT_DIR variable, the root of the MATLAB installation.
  • Matlab_ROOT_DIR โ€” Added in version 3.3.

The root folder of the MATLAB installation. If you set this before the call to find_package(), the module will go look for the components in that path. If you don't set it, an automatic search for MATLAB happens instead. If you do set it, it should point to a valid version of MATLAB. โœจ

You can specify this variable to hand over the path of the exact MATLAB version you want. Otherwise, the behavior is platform specific, bestie:

  • Windows: the installed versions of MATLAB/MCR are retrieved from the Windows registry. The REGISTRY_VIEW argument may optionally be specified to manually control whether 32bit or 64bit versions shall be searched for.
  • macOS: the installed versions of MATLAB/MCR are given by the MATLAB default installation paths under $HOME/Applications and /Applications. If no such application is found, it falls back to the one that might be accessible from the PATH.
  • Unix: the desired MATLAB should be accessible from the PATH. This does not work for MCR installation, and Matlab_ROOT_DIR should be specified on this platform. ๐Ÿ˜ญ

  • MATLAB_FIND_DEBUG โ€” Added in version 3.3. If set to a boolean true, extra debug information gets outputted to the console, like the lookup of MATLAB and the intermediate configuration steps. Your lil' peek behind the curtain ๐Ÿ•ต๏ธโ€โ™€๏ธ
  • MATLAB_ADDITIONAL_VERSIONS โ€” Added in version 3.3. If set, it specifies additional versions of MATLAB for the automatic retrieval of the installed versions that may be handled and looked for.

The mapping of the release names and the version of MATLAB is performed by defining pairs (name, version). This variable should be a list of strings, organized by pairs of release name and versions, like this:

set(
  MATLAB_ADDITIONAL_VERSIONS
    "release_name1=corresponding_version1"
    "release_name2=corresponding_version2"
    # ...
)

find_package(Matlab)

Example, because we love a concrete example ๐Ÿ’–:

set(
  MATLAB_ADDITIONAL_VERSIONS
    "R2013b=8.2"
    "R2013a=8.1"
    "R2012b=8.0"
    # ...
)

find_package(Matlab)

The order of entries in this list matters when several versions of MATLAB are installed โ€” priority is set according to the ordering in this list. So put your fave first, no cap. ๐Ÿ‘‘


๐Ÿ’ป Commands ๐Ÿ’ป

This module provides the following commands, and yes, we're going through every single one:

  • matlab_get_version_from_release_name()
  • matlab_get_release_name_from_version()
  • matlab_get_version_from_matlab_run()
  • matlab_extract_all_installed_versions_from_registry()
  • matlab_get_all_valid_matlab_roots_from_registry()
  • matlab_add_mex()
  • matlab_get_mex_suffix()
  • matlab_add_unit_test()

matlab_get_version_from_release_name

Added in version 3.3.

Returns the version of MATLAB from a release name:

matlab_get_version_from_release_name(<release-name> <version-var>)

The arguments are:

  • <release-name> โ€” input release name string (e.g. R2023b).
  • <version-var> โ€” the name of the variable in which to store the version of MATLAB. The output result is e.g. 23.2.0.
Note: this command provides correct versions mappings for MATLAB but not MCR. ๐Ÿ™ˆ

matlab_get_release_name_from_version

Added in version 3.3.

Returns the release name from the version of MATLAB:

matlab_get_release_name_from_version(<version> <release-name-var>)

The arguments are:

  • <version> โ€” input MATLAB version string (e.g. 23.2.0).
  • <release-name-var> โ€” the name of the variable in which to store the MATLAB release name. The output result is e.g. R2023b.
Note: this command provides correct version mappings for MATLAB but not MCR. Same energy as above, the MCR girlies are on their own. ๐Ÿ’€

matlab_get_version_from_matlab_run

Added in version 3.3.

Runs the specified MATLAB program and extracts the version of MATLAB/MCR, given the full directory of the MATLAB/MCR installation path:

matlab_get_version_from_matlab_run(<matlab-binary> <matlab-versions-var>)

The arguments are:

  • <matlab-binary> โ€” the path to the matlab binary executable.
  • <matlab-versions-var> โ€” the name of the variable in which a list of extracted MATLAB versions are stored.

If the path provided for the MATLAB installation points to an MCR installation, the version is extracted from the installed files. Sneaky but valid. ๐Ÿงš


matlab_extract_all_installed_versions_from_registry

Added in version 3.3.

Parses the Windows registry and finds all installed MATLAB versions:

matlab_extract_all_installed_versions_from_registry(<versions-var>
  [REGISTRY_VIEW <view>])

The arguments are:

  • <versions-var> โ€” the name of the variable in which to store the list of all MATLAB versions found.
  • REGISTRY_VIEW <view> โ€” Added in version 3.30. Optional registry view argument that provides a more precise interface on how to interact with the Windows Registry. The argument is passed (or omitted) to cmake_host_system_information() without further checks or modification. For example, <view> value can be one of 64, 32, 64_32, 32_64, HOST, TARGET, BOTH.

The old signature is:

matlab_extract_all_installed_versions_from_registry(<win64>
  <versions-var>)

The arguments are:

  • <win64> โ€” boolean whether to search for the 64-bit version of MATLAB. If set to boolean true, the 64-bit registry view will be searched. If set to boolean false, the 32-bit registry view will be searched. For finer control, use the above signature. โœจ
  • <versions-var> โ€” the name of the variable in which to store the list of all MATLAB versions found.

This command is available on Windows only. The part of the registry parsed is dependent on the host processor.

The returned list contains all versions under HKLM\SOFTWARE\Mathworks\MATLAB, HKLM\SOFTWARE\Mathworks\MATLAB Runtime and HKLM\SOFTWARE\Mathworks\MATLAB Compiler Runtime, or an empty list in case an error occurred (or nothing found). Bestie, if it's empty, it's empty. ๐Ÿซถ

Note: only the versions are provided. No check is made over the existence of the installation referenced in the registry. So likeโ€ฆ it might be lying to you and that's by design. ๐Ÿ˜ญ

matlab_get_all_valid_matlab_roots_from_registry

Added in version 3.3.

Returns all the possible MATLAB or MCR paths, according to a previously given list:

matlab_get_all_valid_matlab_roots_from_registry(
  <matlab-versions>
  <matlab-roots-var>
  [REGISTRY_VIEW <view>]
)

This command populates the MATLAB root with valid versions of MATLAB or MATLAB Runtime (MCR) and is mainly useful for the searching of all possible MATLAB installations. Only the existing/accessible paths are kept โ€” ghost paths get ghosted. ๐Ÿ‘ป

The arguments are:

  • <matlab-versions> โ€” a semicolon-separated list of each of the MATLAB or MCR installations. Specify it as a single string value.
  • <matlab-roots-var> โ€” the name of the variable in which to store a list of locations of each of the MATLAB or MCR installations.

The value of this variable is organized in triplets (type,version_number,matlab_root_path), where type indicates either MATLAB or MCR. Triplets! It's giving coordinated outfit. ๐ŸŽ€

  • REGISTRY_VIEW <view> โ€” Added in version 3.30. Optional registry view argument that provides a more precise interface on how to interact with the Windows Registry. The argument is passed (or omitted) to cmake_host_system_information() without further checks or modification. For example, <view> value can be one of 64, 32, 64_32, 32_64, HOST, TARGET, BOTH.

matlab_add_mex

Added in version 3.3.

Adds a target that compiles MATLAB MEX target file:

matlab_add_mex(
  NAME <name>
  [EXECUTABLE | MODULE | SHARED]
  SRC <sources>...
  [OUTPUT_NAME <output-name>]
  [DOCUMENTATION <file>]
  [LINK_TO <targets>...]
  [R2017b | R2018a]
  [EXCLUDE_FROM_ALL]
  [NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES]
  [...]
)

This command compiles the given sources with the current tool-chain in order to produce a MEX file. The final name of the produced output may be specified, as well as additional link libraries, and a documentation entry for the MEX file. Remaining arguments of the call are passed to the add_library() or add_executable() command. It's giving "we handle the MEX stuff, you handle the rest". ๐Ÿ’…

The arguments are:

  • NAME <name> โ€” the name of the target.
  • SRC <sources>... โ€” one or more source files to be compiled.
  • LINK_TO <targets>... โ€” a list of additional link dependencies. The target links to libmex and libmx by default, unless the NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES option is passed.
  • OUTPUT_NAME <output-name> โ€” if given, overrides the default name. The default name is the name of the target without any prefix and with Matlab_MEX_EXTENSION suffix.
  • DOCUMENTATION <file> โ€” if given, the <file> will be considered as being the documentation file for the MEX file. This file is copied into the same folder without any processing, with the same name as the final MEX file, and with extension .m. In that case, typing help <name> in MATLAB prints the documentation contained in this file. Iconic behavior honestly. ๐Ÿ‘‘

โ€ฆand just so we're clear, that documentation file does not get processed at all โ€” it literally just has to look like this, no notes:

% This is the documentation
function ret = mex_target_output_name(input1)
  • R2017b or R2018a โ€” added in version 3.14. You can pass this to pick which version of the C API gets used: R2017b = the traditional (separate complex) C API, and it lines up with the -R2017b flag for the mex command. R2018a = the new interleaved complex C API, and it lines up with the -R2018a flag for the mex command. It's ignored for MATLAB versions prior to R2018a. Defaults to R2017b, bestie.
  • MODULE or SHARED โ€” added in version 3.7. Pass this to say what type of library you want created.
  • EXECUTABLE โ€” added in version 3.7. Pass this and you get an executable instead of a library. If you don't explicitly give a type, the default type is SHARED.
  • EXCLUDE_FROM_ALL โ€” this one means exactly the same thing as the EXCLUDE_FROM_ALL target property, and it gets forwarded straight to the add_library(), or add_executable() command.
  • NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES โ€” added in version 3.24. This option permits to disable the automatic linking of MATLAB libraries, so that only the libraries that are actually required can be linked via the LINK_TO option. Chef's kiss for keeping your link line clean ๐Ÿ’…

matlab_get_mex_suffix

Added in version 3.3.

Returns the extension to be used for the MEX files (aka the suffix):

matlab_get_mex_suffix(<matlab-root> <mex-suffix-var>)

The arguments are:

  • <matlab-root> โ€” the root of MATLAB/MCR installation. For example, the value of the Matlab_ROOT_DIR variable.
  • <mex-suffix-var> โ€” the name of the variable in which the suffix will be returned.
Heads up, babe: this command is platform and architecture dependent. Do not call it before the appropriate MATLAB root has been found. Like, don't. It will not slay.

matlab_add_unit_test

Added in version 3.3.

Adds a MATLAB unit test file to the project's test set of CMake/CTest:

matlab_add_unit_test(
  NAME <name>
  UNITTEST_FILE <matlab-file-containing-unittest.m>
  [CUSTOM_TEST_COMMAND <matlab-command-to-run-as-test>]
  [UNITTEST_PRECOMMAND <matlab-command-to-run>]
  [TIMEOUT <timeout>]
  [ADDITIONAL_PATH <paths>...]
  [MATLAB_ADDITIONAL_STARTUP_OPTIONS <options>...]
  [TEST_ARGS <args>...]
  [NO_UNITTEST_FRAMEWORK]
  [WORKING_DIRECTORY <dir>]
)

By default, the MATLAB unit test framework will be used (>= 2013a) to run the added MATLAB script, but regular .m files returning an exit code can be used as well (0 indicating a success). Testing era โœจ

This command requires the component MAIN_PROGRAM and hence is not available for an MCR installation. ๐Ÿ’€

The unit test uses the MATLAB unittest framework (default, available starting MATLAB 2013b+) except if the option NO_UNITTEST_FRAMEWORK is given.

The command expects one MATLAB test script file to be given. In the case NO_UNITTEST_FRAMEWORK is given, the unittest script file should contain the script to be run, plus an exit command with the exit value. This exit value will be passed to the ctest framework (0 success, non 0 failure). Additional arguments accepted by add_test() can be passed through TEST_ARGS (e.g. CONFIGURATIONS <config> ...).

The arguments are:

  • NAME <name> โ€” the name of the unittest in ctest.
  • UNITTEST_FILE <matlab-file-containing-unittest.m> โ€” the MATLAB unittest file. Its path will be automatically added to the MATLAB path.
  • CUSTOM_TEST_COMMAND <matlab-command-to-run-as-test> โ€” MATLAB script command to run as the test. If this is not set, then the following is run: runtests('matlab_file_name'), exit(max([ans(1,:).Failed])) where matlab_file_name is the UNITTEST_FILE without the extension.
  • UNITTEST_PRECOMMAND <matlab-command-to-run> โ€” MATLAB script command to be ran before the file containing the test (e.g. GPU device initialization based on CMake variables).
  • TIMEOUT <timeout> โ€” the test timeout in seconds. Defaults to 180 seconds as the MATLAB unit test may hang. ๐Ÿ˜ญ
  • ADDITIONAL_PATH <paths>... โ€” a list of paths to add to the MATLAB path prior to running the unit test.
  • MATLAB_ADDITIONAL_STARTUP_OPTIONS <options> โ€” a list of additional option in order to run MATLAB from the command line. The -nosplash, -nodesktop, and -nodisplay options are always added automatically. Built-in slay.
  • TEST_ARGS <args>... โ€” additional options provided to the add_test command. These options are added to the default options (e.g. CONFIGURATIONS Release).
  • NO_UNITTEST_FRAMEWORK โ€” when set, indicates that the test should not use the unittest framework of MATLAB (available for versions >= R2013a).
  • WORKING_DIRECTORY <dir> โ€” this will be the working directory for the test. If specified it will also be the output directory used for the log file of the test run. If not specified the temporary directory ${CMAKE_BINARY_DIR}/Matlab will be used as the working directory and the log location.

Known Issues

Symbol clash in a MEX target

By default, every symbol inside a MEX file defined with the command matlab_add_mex() have hidden visibility, except for the entry point. This is the default behavior of the MEX compiler, which lowers the risk of symbol collision between the libraries shipped with MATLAB, and the libraries to which the MEX file is linking to. This is also the default on Windows platforms.

However, this is not sufficient in certain case, where for instance the MEX file is linking against libraries that are already loaded by MATLAB, even if those libraries have different SONAMES. A possible solution is to hide the symbols of the libraries to which the MEX target is linking to. This can be achieved in GNU GCC compilers with the linker option -Wl,--exclude-libs,ALL.

Tests using GPU resources

In case the MEX file is using the GPU and in order to be able to run unit tests on this MEX file, the GPU resources should be properly released by MATLAB. A possible solution is to make MATLAB aware of the use of the GPU resources in the session, which can be performed by a command, such as D = gpuDevice(), at the beginning of the test script (or via a fixture).

Examples

Finding MATLAB and linking imported target to a project target:

find_package(Matlab)
target_link_libraries(example PRIVATE Matlab::mx)

FindMFC

Finds the native Microsoft Foundation Class Library (MFC) for developing MFC applications on Windows:

find_package(MFC [...])
Note: MFC is an optional component in Visual Studio and must be installed separately for this module to succeed. No MFC component, no luck, bestie. ๐Ÿ’…

Once the MFC libraries and headers are found, no additional manual linking is needed, as they are part of the development environment. Iconic, honestly.

Result Variables

This module defines the following variables:

  • MFC_FOUND โ€” Boolean indicating whether MFC support was found.

Examples

Using this module to check if the application can link to the MFC libraries:

find_package(MFC)

if(MFC_FOUND)
  # Example logic when MFC is available...
  set(CMAKE_MFC_FLAG 2)
  add_executable(app WIN32 main.cpp)
  target_compile_definitions(app PRIVATE _AFXDLL)
endif()

See Also

  • The CMAKE_MFC_FLAG variable.

FindMotif

Finds Motif (or LessTif) graphical user interface toolkit:

find_package(Motif [...])

Result Variables

This module defines the following variables:

  • Motif_FOUND โ€” added in version 3.3. Boolean indicating whether Motif was found.

Cache Variables

The following cache variables may also be set:

  • MOTIF_INCLUDE_DIR โ€” include directories needed to use Motif.
  • MOTIF_LIBRARIES โ€” libraries needed to link to Motif.

Deprecated Variables

The following variables are provided for backward compatibility:

  • MOTIF_FOUND โ€” deprecated since version 4.2: use Motif_FOUND, which has the same value. Boolean indicating whether Motif was found.
She's giving legacy support, not main character energy โ€” reach for Motif_FOUND instead, okay? ๐Ÿซถ

Examples

Finding Motif and creating an imported interface target for linking it to a project target:

find_package(Motif)

if(Motif_FOUND AND NOT TARGET Motif::Motif)
  add_library(Motif::Motif INTERFACE IMPORTED)
  set_target_properties(
    Motif::Motif
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${MOTIF_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${MOTIF_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE Motif::Motif)

FindMPEG

Finds the native MPEG library (libmpeg2):

find_package(MPEG [...])
Note: this module is functionally identical to the FindMPEG2 module, which also finds the libmpeg2 library. Both modules were introduced in the past to provide flexibility in handling potential differences in future versions of the MPEG library and to maintain backward compatibility across CMake releases.
The FindMPEG2 module additionally checks for the SDL dependency and includes it in its usage requirements. For working with libmpeg2, it is recommended to use the FindMPEG2 module instead of this one. Like, genuinely โ€” use the other one. ๐Ÿ˜Œ

Result Variables

This module defines the following variables:

  • MPEG_FOUND โ€” Boolean indicating whether the libmpeg2 library was found.
  • MPEG_LIBRARIES โ€” libraries needed to link against to use libmpeg2.

๐Ÿ’พ Cache Variables

okay so these are the cache variables the module may set for you, bestie โ€” look them up, don't guess:

  • MPEG_INCLUDE_DIR โ€” the directory that has mpeg2.h and all the related headers you need to actually use the libmpeg2 library. ๐ŸŽ€
  • MPEG_mpeg2_LIBRARY โ€” the path to the libmpeg2 library itself.
  • MPEG_vo_LIBRARY โ€” the path to the vo (Video Out) library.

โœจ Examples

so here's how you find the libmpeg2 library AND build an imported interface target to link it into one of your project targets. it's giving "two birds, one stone" energy ๐Ÿฆ‹:

find_package(MPEG)

if(MPEG_FOUND AND NOT TARGET MPEG::MPEG)
  add_library(MPEG::MPEG INTERFACE IMPORTED)
  set_target_properties(
    MPEG::MPEG
    PROPERTIES
      INTERFACE_LINK_LIBRARIES "${MPEG_LIBRARIES}"
      INTERFACE_INCLUDE_DIRECTORIES "${MPEG_INCLUDE_DIR}"
  )
endif()

target_link_libraries(project_target PRIVATE MPEG::MPEG)

๐Ÿ“ FindMPEG2

same vibe, different module โ€” FindMPEG2 finds the native MPEG2 library (libmpeg2):

find_package(MPEG2 [...])
๐Ÿ“Œ Note: depending on how the native libmpeg2 library got built and installed, it may depend on the SDL (Simple DirectMedia Layer) library. If SDL is found, this module includes it in its usage requirements when used. so like, it handles that for you, no cap.

๐Ÿซถ Result Variables

this module defines these variables, periodt:

  • MPEG2_FOUND โ€” boolean that tells you whether the libmpeg2 library was found. true/false, iconic.
  • MPEG2_LIBRARIES โ€” the libraries you need to link against to use libmpeg2.

๐ŸŽ€ Cache Variables

and these cache variables may also be set:

  • MPEG2_INCLUDE_DIR โ€” the directory containing mpeg2.h and the related headers needed to use the libmpeg2 library.
  • MPEG2_mpeg2_LIBRARY โ€” the path to the libmpeg2 library.
  • MPEG2_vo_LIBRARY โ€” the path to the vo (Video Out) library.

๐Ÿ’… Examples

finding libmpeg2 and making an imported interface target so you can link it to a project target โ€” literally the same slay as before:

find_package(MPEG2)

if(MPEG2_FOUND AND NOT TARGET MPEG2::MPEG2)
  add_library(MPEG2::MPEG2 INTERFACE IMPORTED)
  set_target_properties(
    MPEG2::MPEG2
    PROPERTIES
      INTERFACE_LINK_LIBRARIES "${MPEG2_LIBRARIES}"
      INTERFACE_INCLUDE_DIRECTORIES "${MPEG2_INCLUDE_DIR}"
  )
endif()

target_link_libraries(project_target PRIVATE MPEG2::MPEG2)

๐ŸŒˆ FindMPI

okay THIS one is the main character ๐Ÿ‘‘ โ€” FindMPI finds a Message Passing Interface (MPI) implementation:

find_package(MPI [<version>] [COMPONENTS <langs>...] [...])

so what even IS MPI? it's a library used to write high-performance distributed-memory parallel applications, and it's typically deployed on a cluster. MPI is a standard interface (defined by the MPI forum) and there are like, a LOT of implementations of it out there. ๐Ÿ–ฅ๏ธโœจ

Added in version 3.10: major overhaul of the module โ€” many new variables, per-language components, and support for a wider variety of runtimes. glow-up fr fr.

๐ŸŒธ Components

this module supports optional components that you can specify with the find_package() command to control which MPI languages it searches for:

find_package(MPI [COMPONENTS <langs>...])

supported components include:

  • C โ€” Added in version 3.10. finds the MPI C API.
  • CXX โ€” Added in version 3.10. finds the MPI C API that is usable from C++. (yes, the C API, from C++ โ€” that's the whole bit ๐Ÿ’€)
  • MPICXX โ€” Added in version 3.10. finds the MPI-2 C++ API that was removed in MPI-3. rip to a real one ๐Ÿ˜ญ
  • Fortran โ€” Added in version 3.10. finds the MPI Fortran API.

if you specify no components at all, the module searches for the C, CXX, and Fortran components automatically, depending on which languages are enabled in the project. automatic. effortless. ๐Ÿงš

โญ Imported Targets

this module provides these Imported Targets:

  • MPI::MPI_<lang> โ€” Added in version 3.9. a target encapsulating the usage requirements for using MPI from language <lang>, available if MPI is found. the <lang> is a specified component name as listed above. so clean, so modern. ๐Ÿซถ

๐Ÿฆ‹ Result Variables

this module defines the following variables:

  • MPI_FOUND โ€” boolean indicating that MPI settings for all requested components (languages) were found. if no components are specified, this variable is set to boolean true if MPI settings for all enabled languages were detected. and heads up: note that the MPICXX component does not affect this variable. ๐Ÿ‘€
  • MPI_VERSION โ€” the minimal version of MPI detected among the requested languages, or all enabled languages if no components were specified.

then the module sets the following variables per language in your CMake project, where <lang> is one of C, CXX, or Fortran:

  • MPI_<lang>_FOUND โ€” boolean indicating the MPI settings for <lang> were found and that simple MPI test programs compile with the provided settings.
  • MPI_<lang>_COMPILER โ€” the MPI compiler for <lang>, if such a program exists.
  • MPI_<lang>_COMPILE_OPTIONS โ€” compilation options for MPI programs in <lang>, given as a semicolon-separated list.
  • MPI_<lang>_COMPILE_DEFINITIONS โ€” compilation definitions for MPI programs in <lang>, given as a semicolon-separated list.
  • MPI_<lang>_INCLUDE_DIRS โ€” include path(s) for the MPI header.
  • MPI_<lang>_LINK_FLAGS โ€” linker flags for MPI programs.
  • MPI_<lang>_LIBRARIES โ€” all libraries to link MPI programs against.

the following variables, which tell you which bindings are present, will be defined too:

  • MPI_MPICXX_FOUND โ€” boolean indicating whether the MPI-2 C++ bindings are present (introduced in MPI-2, removed with MPI-3).
  • MPI_Fortran_HAVE_F77_HEADER โ€” true if the Fortran 77 header <mpif.h> is available.
  • MPI_Fortran_HAVE_F90_MODULE โ€” true if the Fortran 90 module mpi can be used for accessing MPI (MPI-2 and higher only).
  • MPI_Fortran_HAVE_F08_MODULE โ€” true if the Fortran 2008 mpi_f08 is available to MPI programs (MPI-3 and higher only).

if possible, the MPI version will be determined by this module. the facilities to detect the MPI version were introduced with MPI-1.2, and therefore cannot be found for older MPI versions โ€” so if you're on something ancient, sorry bestie, no version for you ๐Ÿ™ˆ.

  • MPI_<lang>_VERSION โ€” the MPI version implemented for <lang> by the MPI distribution.
  • MPI_<lang>_VERSION_MAJOR โ€” major version of MPI implemented for <lang> by the MPI distribution.
  • MPI_<lang>_VERSION_MINOR โ€” minor version of MPI implemented for <lang> by the MPI distribution.
๐Ÿ’ก note that there's no variable for the C bindings being accessible through <mpi.h>, since the MPI standards always have required this binding to work in both C and C++ code. it's just... a given. iykyk.

for running MPI programs, the module sets these variables:

  • MPIEXEC_EXECUTABLE โ€” executable for running MPI programs, if such exists.
  • MPIEXEC_NUMPROC_FLAG โ€” flag to pass to mpiexec before giving it the number of processors to run on.
  • MPIEXEC_MAX_NUMPROCS โ€” number of MPI processors to utilize. defaults to the number of processors detected on the host system.
  • MPIEXEC_PREFLAGS โ€” flags to pass to mpiexec directly before the executable to run.
  • MPIEXEC_POSTFLAGS โ€” flags to pass to mpiexec after other flags.

๐Ÿ”ฅ Variables for Locating MPI

this module performs a four-step search for an MPI implementation:

  1. Searches for MPIEXEC_EXECUTABLE and, if found, uses its base directory.
  2. Checks if the compiler has MPI support built-in. this is the case if the user passed a compiler wrapper as CMAKE_<LANG>_COMPILER or if they use Cray system compiler wrappers.
  3. Attempts to find an MPI compiler wrapper and determines the compiler information from it.
  4. Tries to find an MPI implementation that does not ship such a wrapper by guessing settings. currently, only Microsoft MPI and MPICH2 on Windows are supported.

for controlling the MPIEXEC_EXECUTABLE step, you may set these variables:

  • MPIEXEC_EXECUTABLE โ€” manually specify the location of mpiexec.
  • MPI_HOME โ€” specify the base directory of the MPI installation.
  • ENV{MPI_HOME} โ€” environment variable to specify the base directory of the MPI installation.
  • ENV{I_MPI_ROOT} โ€” environment variable to specify the base directory of the MPI installation.

for controlling the compiler wrapper step, you may set these variables:

  • MPI_<lang>_COMPILER โ€” search for the specified compiler wrapper and use it.
  • MPI_<lang>_COMPILER_FLAGS โ€” flags to pass to the MPI compiler wrapper during interrogation. some compiler wrappers support linking debug or tracing libraries if a specific flag is passed, and this variable may be used to obtain them. ๐ŸŽฏ
  • MPI_COMPILER_FLAGS โ€” used to initialize MPI_<lang>_COMPILER_FLAGS if no language specific flag has been given. empty by default.
  • MPI_EXECUTABLE_SUFFIX โ€” a suffix which is appended to all names that are being looked for. for instance, it may be set to .mpich or .openmpi to prefer the one or the other on Debian and its derivatives. sneaky but useful ๐Ÿ’…

in order to control the guessing step, you may set this variable:

  • MPI_GUESS_LIBRARY_NAME โ€” valid values are MSMPI and MPICH2. if set, only the given library will be searched for. by default, MSMPI will be preferred over MPICH2 if both are available. this also sets the MPI_SKIP_COMPILER_WRAPPER variable to true, which may be overridden. โš ๏ธ

each of the search steps may be skipped with these control variables:

  • MPI_ASSUME_NO_BUILTIN_MPI โ€” if true, the module assumes that the compiler itself does not provide an MPI implementation and skips to step 2.
  • MPI_SKIP_COMPILER_WRAPPER โ€” if true, no compiler wrapper will be searched for.
  • MPI_SKIP_GUESSING โ€” if true, the guessing step will be skipped.

additionally, this control variable is available to change search behavior:

  • MPI_CXX_SKIP_MPICXX โ€” add some definitions that will disable the MPI-2 C++ bindings. currently supported are MPICH, Open MPI, Platform MPI and derivatives thereof, for example, MVAPICH or Intel MPI.

and finally โ€” if the find procedure fails for the module's internal variable MPI_<lang>_WORKS, then the settings detected by or passed to the module did not work, and even a simple MPI test program failed to compile. ๐Ÿ˜ญ that's your sign that something's cooked, bestie.

MPI_<lang>_LIBRARIES and a whole list of include dirs in MPI_<lang>_ADDITIONAL_INCLUDE_DIRS? bestie, that's the โœจmanual overrideโœจ โ€” it straight-up disables the entire autodetection process. and yeah, you can set any other variable in addition to those two, no biggie. the module will then validate your MPI settings and store them in the cache. respect. ๐Ÿซถ

๐ŸงŠ Cache Variables

the variable MPI_<lang>_INCLUDE_DIRS gets assembled from the following variables, iykyk:

for C and CXX:

  • MPI_<lang>_HEADER_DIR โ€” where the <mpi.h> header lives on disk ๐Ÿ—‚๏ธ

for Fortran:

  • MPI_Fortran_F77_HEADER_DIR โ€” where the Fortran 77 header <mpif.h> lives, if it exists
  • MPI_Fortran_MODULE_DIR โ€” where the mpi or mpi_f08 modules live, if they're available

and for all the languages, these get considered too:

  • MPI_<lang>_ADDITIONAL_INCLUDE_DIRS โ€” a semicolon-separated list of paths you need on top of the normal include directories
  • MPI_<include-name>_INCLUDE_DIR โ€” path variables for include folders referred to by <include-name>
  • MPI_<lang>_ADDITIONAL_INCLUDE_VARS โ€” a semicolon-separated list of <include-name> that will be added to the include locations of <lang>

and the variable MPI_<lang>_LIBRARIES gets assembled from these:

  • MPI_<lib-name>_LIBRARY โ€” the location of a library called <lib-name> for use with MPI ๐Ÿ“š
  • MPI_<lang>_LIB_NAMES โ€” a semicolon-separated list of <lib-name> that will be added to the include locations of <lang>

๐Ÿ”ฌ Advanced Variables for Using MPI

okay so this module can do some advanced feature detections โ€” but only upon explicit request, no surprise poking around โœจ

Note: these checks literally cannot be performed without executing an MPI test program. so pls consider the special considerations for the behavior of try_run() during cross compilation ๐Ÿ˜ญ and also, running an MPI program can cause extra issues, like a firewall notification on some systems. only enable these detections if the info is absolutely needed. fr fr.

if the following variables are set to true, the respective search will be performed:

  • MPI_DETERMINE_Fortran_CAPABILITIES โ€” determines, for all available Fortran bindings, what the values of MPI_SUBARRAYS_SUPPORTED and MPI_ASYNC_PROTECTS_NONBLOCKING are, and makes those values available as MPI_Fortran_<binding>_SUBARRAYS and MPI_Fortran_<binding>_ASYNCPROT, where <binding> is one of F77_HEADER, F90_MODULE and F08_MODULE ๐Ÿ‘‘
  • MPI_DETERMINE_LIBRARY_VERSION โ€” for each language, finds the output of MPI_Get_library_version and makes it available as MPI_<lang>_LIBRARY_VERSION_STRING. this info is usually tied to the runtime component of an MPI implementation and might differ depending on <lang>. note that the return value is entirely implementation defined ๐Ÿ™ˆ this information might be used to identify the MPI vendor and, for example, pick the correct one of multiple third party binaries that matches the MPI vendor.

๐Ÿ’€ Deprecated Variables

these are kept around purely for backward compatibility (we love a legacy queen but she's retired):

  • MPI_COMPILER โ€” Deprecated since version 2.8.5: use the MPI_<lang>_COMPILER instead.
  • MPI_LIBRARY โ€” Deprecated since version 2.8.5: use the MPI_<lang>_LIBRARIES instead.
  • MPI_EXTRA_LIBRARY โ€” Deprecated since version 2.8.5: use the MPI_<lang>_LIBRARIES instead.
  • MPI_COMPILE_FLAGS โ€” Deprecated since version 2.8.5: use MPI_<lang>_COMPILE_OPTIONS and MPI_<lang>_COMPILE_DEFINITIONS instead.
  • MPI_INCLUDE_PATH โ€” Deprecated since version 2.8.5: use the MPI_<lang>_INCLUDE_DIRS instead.
  • MPI_LINK_FLAGS โ€” Deprecated since version 2.8.5: use the MPI_<lang>_LINK_FLAGS instead.
  • MPI_LIBRARIES โ€” Deprecated since version 2.8.5: use the MPI_<lang>_LIBRARIES instead.
  • MPI_<lang>_COMPILE_FLAGS โ€” Deprecated since version 3.10: use the MPI_<lang>_COMPILE_OPTIONS and MPI_<lang>_COMPILE_DEFINITIONS instead.
  • MPI_<lang>_INCLUDE_PATH โ€” Deprecated since version 3.10: for consumption use MPI_<lang>_INCLUDE_DIRS and for specifying folders use MPI_<lang>_ADDITIONAL_INCLUDE_DIRS instead.
  • MPIEXEC โ€” Deprecated since version 3.10: use MPIEXEC_EXECUTABLE instead.

๐ŸŒธ Examples

๐Ÿ’– Example: Basic Usage

finding MPI and linking the imported target to your project target โ€” the classic slay:

find_package(MPI)
target_link_libraries(example PRIVATE MPI::MPI_C)

๐ŸŽ€ Example: Usage of mpiexec

when you're using MPIEXEC_EXECUTABLE to execute MPI applications, typically all of the MPIEXEC_EXECUTABLE flags should be used, like this:

in the following example, the command is executed in a process. <executable> should be replaced with the MPI program, and <args> with the arguments to pass to the MPI program. ๐Ÿซก

find_package(MPI)

if(MPI_FOUND)
  execute_process(
    COMMAND
      ${MPIEXEC_EXECUTABLE}
      ${MPIEXEC_NUMPROC_FLAG}
      ${MPIEXEC_MAX_NUMPROCS}
      ${MPIEXEC_PREFLAGS}
      <executable>
      ${MPIEXEC_POSTFLAGS}
      <args>
  )
endif()

๐Ÿฆ‹ FindMsys

Added in version 3.21.

finds MSYS โ€” the POSIX-compatible environment that runs natively on Microsoft Windows ๐Ÿ’ปโœจ

find_package(Msys [...])
Note: this module is primarily intended for use in other Find Modules to help locate programs when using the find_*() commands, such as find_program(). in most cases, direct use of those commands is sufficient. use this module only if a specific program is known to be installed via MSYS and is usable from Windows.

โญ Result Variables

this module defines the following variables:

  • Msys_FOUND โ€” Added in version 4.2. Boolean indicating whether MSYS was found.
  • MSYS_INSTALL_PATH โ€” the path to the MSYS root installation directory ๐Ÿ“

๐ŸŒˆ Examples

finding the MSYS installation and using its path in a custom find module โ€” here's FindFoo.cmake:

find_package(Msys)
find_program(Foo_EXECUTABLE NAMES foo PATHS ${MSYS_INSTALL_PATH}/usr/bin)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo REQUIRED_VARS Foo_EXECUTABLE)

๐Ÿ‘€ See Also

  • the FindCygwin module, to find Cygwin path in a similar way ๐Ÿง

๐Ÿ“ FindODBC

Added in version 3.12.

finds the Open Database Connectivity (ODBC) library, which implements a standard API for accessing database systems ๐Ÿ—„๏ธโœจ

find_package(ODBC [...])

so like โ€” ODBC enables applications to communicate with different database management systems (DBMS) using a common set of functions. communication with a specific database is handled through ODBC drivers, which the library loads at runtime. iconique.

on Windows, when building with Visual Studio, this module assumes the ODBC library is provided by the available Windows SDK ๐ŸชŸ

on Unix-like systems, this module searches for the ODBC library provided by unixODBC or iODBC implementations of the ODBC API. by default, this module looks for the ODBC config program to determine the ODBC library and include directory โ€” first from unixODBC, then from iODBC. if no config program is found, it searches for the ODBC header and library in standard locations. no cap.

๐ŸŽฏ Imported Targets

this module provides the following Imported Targets:

  • ODBC::ODBC โ€” target encapsulating the ODBC usage requirements, available if ODBC is found ๐Ÿ’…

๐ŸŒŸ Result Variables

this module defines the following variables:

  • ODBC_FOUND โ€” Boolean indicating whether ODBC was found.
  • ODBC_INCLUDE_DIRS โ€” include directories containing headers needed to use ODBC.
  • ODBC_LIBRARIES โ€” libraries needed to link against to use ODBC.

๐ŸงŠ Cache Variables

the following cache variables may also be set:

  • ODBC_INCLUDE_DIR โ€” the path to the directory containing sql.h and other ODBC headers. may be empty on Windows, where the include directory corresponding to the expected Windows SDK is already available in the compilation environment.
  • ODBC_LIBRARY โ€” the path to the ODBC library or a library name. on Windows, this may be only a library name, because the library directory corresponding to the expected Windows SDK is already available in the compilation environment.
  • ODBC_CONFIG โ€” the path to the ODBC config program if found or specified. for example, odbc_config for unixODBC, or iodbc-config for iODBC ๐Ÿ”ง

โš ๏ธ Limitations

  • on Windows, this module does not search for iODBC.
  • on Unix-like systems, there is no built-in mechanism to prefer unixODBC over iODBC, or vice versa. to bypass this limitation, explicitly set the ODBC_CONFIG variable to the path of the desired ODBC config program.
  • this module does not support searching for or selecting a specific ODBC driver. sorry bestie ๐Ÿ˜ญ

๐Ÿ’œ Examples

๐Ÿงš Example: Finding and Using ODBC

finding ODBC and linking it to a project target โ€” in CMakeLists.txt:

find_package(ODBC)
target_link_libraries(project_target PRIVATE ODBC::ODBC)

๐Ÿ”ฅ Example: Finding a Custom ODBC Installation

the following examples are for Unix-like systems and demonstrate how to set hint and cache variables during the CMake configuration phase to help this module find a custom ODBC implementation (e.g. one not supported by default). we love a DIY moment.

to specify the installation prefix using CMAKE_PREFIX_PATH:

$ cmake -D CMAKE_PREFIX_PATH=/path/to/odbc-installation -B build

or using the dedicated ODBC_ROOT variable:

$ cmake -D ODBC_ROOT=/path/to/odbc-installation -B build

to manually specify the ODBC config program, if available, so that the ODBC installation can be automatically determined based on the config tool:

$ cmake -D ODBC_CONFIG=/path/to/odbc/bin/odbc-config -B build

to manually specify the ODBC library and include directory:

$ cmake \
    -D ODBC_LIBRARY=/path/to/odbc/lib/libodbc.so \
    -D ODBC_INCLUDE_DIR=/path/to/odbc/include \
    -B build

๐Ÿงš FindOpenACC

Added in version 3.10.

finds and detects the OpenACC support in a compiler ๐Ÿ”โšก

find_package(OpenACC [<version>] [...])

if the compiler supports OpenACC, the flags required to compile with OpenACC support are returned in variables for the different languages. currently, only NVHPC, PGI, GNU and Cray compilers are supported. periodt. ๐Ÿ‘‘

โœจ Imported Targets โœจ

Ok so this module hands you some imported targets <#imported-targets> and they're honestly so useful:

  • OpenACC::OpenACC_<lang> โ€” added in version 3.16. This target bundles up all the usage requirements for using OpenACC from <lang>. Heads up though: it only exists if OpenACC support was actually found. And <lang> is one of C, CXX, or Fortran. That's it, those three, no extras.

๐Ÿ’– Result Variables ๐Ÿ’–

Here's what the module sets for you:

  • OpenACC_FOUND โ€” added in version 3.25. A boolean that says hey, we found OpenACC flags for at least ONE language. Just one is enough, bestie.

Then, per language in your project (where <lang> is one of C, CXX, or Fortran), it sets:

  • OpenACC_<lang>_FOUND โ€” boolean, was OpenACC support for <lang> detected or not.
  • OpenACC_<lang>_FLAGS โ€” the OpenACC compiler flags for <lang>, separated by spaces.
  • OpenACC_<lang>_OPTIONS โ€” added in version 3.16. Same flags for <lang> but as a proper LIST. Perfect for target_compile_options or target_link_options. Chefs kiss.

And it'll also try to give you the OpenACC version variables:

  • OpenACC_<lang>_SPEC_DATE โ€” the date of the OpenACC spec your <lang> compiler implements.
  • OpenACC_<lang>_VERSION_MAJOR โ€” major version of OpenACC implemented by the <lang> compiler.
  • OpenACC_<lang>_VERSION_MINOR โ€” minor version, same deal.
  • OpenACC_<lang>_VERSION โ€” the whole OpenACC version implemented by the <lang> compiler.
Quick note on the spec date: it's formatted the way the OpenACC standard does it โ€” yyyymm โ€” where yyyy and mm are the year and month of the OpenACC specification that <lang> compiler implements. ๐ŸŒธ

๐ŸŽ€ Input Variables ๐ŸŽ€

This module takes this one:

  • OpenACC_ACCEL_TARGET=<target> โ€” if you set it, the correct target accelerator flag set for that <target> gets returned in the OpenACC_<lang>_FLAGS variable. Slay.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding OpenACC support and linking the imported target to a project target โ€” literally just this:

find_package(OpenACC)
target_link_libraries(example PRIVATE OpenACC::OpenACC_C)

๐Ÿฆ‹ FindOpenAL ๐Ÿฆ‹

Finds the Open Audio Library (OpenAL):

find_package(OpenAL [...])

So OpenAL is this cross-platform 3D audio API, right? It's built for efficient rendering of multichannel, three-dimensional positional audio. It's the go-to in games and multimedia apps when you want immersive, spatialized sound. Gamer vibes fr fr. ๐ŸŽฎ

Important, bestie: if your project uses this module, include the OpenAL header like #include <al.h>, and NOT like #include <AL/al.h>. The second one is not portable, and here's why: Windows/Creative Labs doesn't put OpenAL headers in AL/ by default, and macOS does its own thing with <OpenAL/al.h>. So yeah โ€” #include <al.h>. Periodt.

Imported Targets

  • OpenAL::OpenAL โ€” added in version 3.25. This target wraps up the OpenAL library usage requirements, and it's only available if the OpenAL library is found. Simple as that.

Result Variables

  • OpenAL_FOUND โ€” added in version 3.3. A boolean saying whether OpenAL was found.

Cache Variables

These cache variables may also get set:

  • OPENAL_INCLUDE_DIR โ€” the include directory holding the headers you need to actually use the OpenAL library.
  • OPENAL_LIBRARY โ€” the path to the OpenAL library itself.

Hints

This module accepts:

  • OPENALDIR โ€” an environment variable you can use to set the installation prefix of OpenAL when it lives somewhere non-standard.

Here's the tea on the search order โ€” OpenAL gets searched like this:

  1. By default on macOS, the system framework is searched first: /System/Library/Frameworks, and you can change its priority by setting the CMAKE_FIND_FRAMEWORK <#variable:CMAKE_FIND_FRAMEWORK> variable.
  2. The environment variable ENV{OPENALDIR}.
  3. System paths.
  4. User-compiled framework: ~/Library/Frameworks.
  5. Manually compiled framework: /Library/Frameworks.
  6. Add-on package: /opt.

Deprecated Variables

These are hanging around for backward compatibility:

  • OPENAL_FOUND โ€” deprecated since version 4.2: use OpenAL_FOUND, which has the same value. Boolean indicating whether OpenAL was found.

Examples

Find the OpenAL library and link it to a project target:

find_package(OpenAL)
target_link_libraries(project_target PRIVATE OpenAL::OpenAL)

๐Ÿ”ฅ FindOpenCL ๐Ÿ”ฅ

Added in version 3.1.

Finds Open Computing Language (OpenCL):

find_package(OpenCL [<version>] [...])

OpenCL is the framework for writing programs that execute across heterogeneous platforms โ€” think CPUs, GPUs, and other accelerators. Multi-platform main character energy. ๐Ÿ‘‘

Added in version 3.24: detection of OpenCL 3.0. Added in version 3.10: detection of OpenCL 2.1 and 2.2. We stay updated.

Imported Targets

  • OpenCL::OpenCL โ€” added in version 3.7. Target encapsulating the OpenCL usage requirements, available if OpenCL has been found. ๐Ÿ’…

Result Variables

  • OpenCL_FOUND โ€” boolean, did we find (the requested version of) OpenCL?
  • OpenCL_VERSION โ€” added in version 4.2. Highest supported OpenCL version found, in the form <major>.<minor> (e.g., 1.2).
  • OpenCL_VERSION_MAJOR โ€” the major version of the OpenCL implementation.
  • OpenCL_VERSION_MINOR โ€” the minor version of the OpenCL implementation.
  • OpenCL_INCLUDE_DIRS โ€” include directories needed to use OpenCL.
  • OpenCL_LIBRARIES โ€” libraries needed to link to OpenCL.

Cache Variables

May also be set:

  • OpenCL_INCLUDE_DIR โ€” the OpenCL include directory.
  • OpenCL_LIBRARY โ€” the path to the OpenCL library.

Deprecated Variables

Backward compatibility corner:

  • OpenCL_VERSION_STRING โ€” deprecated since version 4.2: use OpenCL_VERSION, which has the same value. Highest supported OpenCL version found, in the form <major>.<minor>.

Examples

Finding OpenCL and linking it to a project target:

find_package(OpenCL)
target_link_libraries(project_target PRIVATE OpenCL::OpenCL)

โญ FindOpenGL โญ

Finds OpenGL and the OpenGL Utility Library (GLU), so you can use OpenGL in a CMake project:

find_package(OpenGL [COMPONENTS <components>...] [...])

OpenGL (Open Graphics Library) is a cross-platform API for rendering 2D and 3D graphics. It's everywhere in CAD, games, and visualization software. Literally iconic.

  • GL is the core OpenGL library โ€” the fundamental graphics rendering API.
  • GLU (OpenGL Utility Library) is a companion library that gives you utility functions built on top of OpenGL, like tessellation and drawing more complex shapes.
Changed in version 3.2: X11 is no longer added as a dependency on Unix/Linux systems. Added in version 3.10: GLVND (GL Vendor-Neutral Dispatch library) support on Linux โ€” see the Linux-specific section below for that.

Components

This module supports optional components, which you specify with the find_package() <#command:find_package> command:

find_package(OpenGL [COMPONENTS <components>...])

Supported components are:

  • EGL โ€” added in version 3.10. The EGL interface between OpenGL, OpenGL ES and the underlying windowing system.
  • GLX โ€” added in version 3.10. An extension to X that interfaces OpenGL and OpenGL ES with the X window system.
  • OpenGL โ€” added in version 3.10. The cross-platform API for 3D graphics.
  • GLES2 โ€” added in version 3.27. A subset of the OpenGL API for embedded systems with limited capabilities.
  • GLES3 โ€” added in version 3.27. A subset of the OpenGL API for embedded systems with more capabilities.

Imported Targets

  • OpenGL::GL โ€” added in version 3.8. Target encapsulating the usage requirements of platform-specific OpenGL libraries, available if OpenGL is found.
  • OpenGL::GLU โ€” added in version 3.8. Target encapsulating the OpenGL Utility Library (GLU) usage requirements, available if GLU is found.

And also, the GLVND-specific library imported targets:

  • OpenGL::OpenGL โ€” added in version 3.10. Target encapsulating the libOpenGL usage requirements, available if the system is GLVND-based and OpenGL is found.
  • OpenGL::GLX โ€” added in version 3.10. Target encapsulating the usage requirements of the OpenGL Extension to the X Window System (GLX), available if OpenGL and GLX are found.
  • OpenGL::EGL โ€” added in version 3.10. Target encapsulating the EGL usage requirements, available if OpenGL and EGL are found.
  • OpenGL::GLES2 โ€” added in version 3.27. Target encapsulating the GLES2 usage requirements, available if OpenGL and GLES2 are found.
  • OpenGL::GLES3 โ€” added in version 3.27. Target encapsulating the GLES3 usage requirements, available if OpenGL and GLES3 are found.

Result Variables

  • OpenGL_FOUND โ€” added in version 3.3. Boolean indicating whether OpenGL AND all requested components were found. All of them, no partial credit.
  • OPENGL_XMESA_FOUND โ€” boolean indicating whether OpenGL XMESA was found.
  • OPENGL_GLU_FOUND โ€” boolean indicating whether GLU was found.
  • OpenGL_OpenGL_FOUND โ€” added in version 3.10. Boolean indicating whether the GLVND OpenGL library was found.
  • OpenGL_GLX_FOUND โ€” added in version 3.10. Boolean indicating whether GLVND GLX was found.
  • OpenGL_EGL_FOUND โ€” added in version 3.10. Boolean indicating whether GLVND EGL was found.
  • OpenGL_GLES2_FOUND โ€” added in version 3.27. Boolean indicating whether GLES2 was found.
  • OpenGL_GLES3_FOUND โ€” added in version 3.27. Boolean indicating whether GLES3 was found.
  • OPENGL_INCLUDE_DIRS โ€” added in version 3.29. Paths to the OpenGL include directories.
  • OPENGL_EGL_INCLUDE_DIRS โ€” added in version 3.10. Path to the EGL include directory.
  • OPENGL_LIBRARIES โ€” the paths to the OpenGL library, the windowing system libraries, and the GLU libraries, all bundled together ๐Ÿซถ. Heads up tho: on Linux this assumes GLX and is never correct for EGL-based targets. Clients are encouraged to use the OpenGL::* imported targets instead โ€” like, do that, bestie, it's giving best practice ๐Ÿ’….

๐ŸŽ€ Cache Variables ๐ŸŽ€

The following cache variables may also be set:

  • OPENGL_INCLUDE_DIR โ€” the path to the OpenGL include directory. But the OPENGL_INCLUDE_DIRS variable is preferred (it's the cooler older sibling, lowkey).
  • OPENGL_GLU_INCLUDE_DIR โ€” added in version 3.29. Path to the OpenGL GLU include directory โœจ.
  • OPENGL_egl_LIBRARY โ€” added in version 3.10. Path to the GLVND EGL library.
  • OPENGL_glu_LIBRARY โ€” path to the GLU library.
  • OPENGL_glx_LIBRARY โ€” added in version 3.10. Path to the GLVND GLX library.
  • OPENGL_opengl_LIBRARY โ€” added in version 3.10. Path to the GLVND OpenGL library.
  • OPENGL_gl_LIBRARY โ€” path to the OpenGL library.
  • OPENGL_gles2_LIBRARY โ€” added in version 3.27. Path to the OpenGL GLES2 library.
  • OPENGL_gles3_LIBRARY โ€” added in version 3.27. Path to the OpenGL GLES3 library.

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts the following variables:

  • OpenGL_GL_PREFERENCE โ€” added in version 3.10. This one's supported on Linux systems to specify the preferred way to provide legacy GL interfaces in case multiple choices are available. The value may be one of:
    • GLVND โ€” if the GLVND OpenGL and GLX libraries are available, prefer them. This forces OPENGL_gl_LIBRARY to be empty. Changed in version 3.11: this is the default, unless policy CMP0072 is set to OLD and no components are requested (since components correspond to GLVND libraries). โœจ
    • LEGACY โ€” prefer to use the legacy libGL library, if available. This makes OPENGL_opengl_LIBRARY and OPENGL_glx_LIBRARY point to OPENGL_gl_LIBRARY. ๐Ÿซก

๐Ÿง Linux-specific ๐Ÿง

Some Linux systems utilize GLVND as a new ABI for OpenGL. GLVND separates context libraries from OpenGL itself; OpenGL lives in "libOpenGL", and contexts are defined in "libGLX" or "libEGL". GLVND is currently the only way to get OpenGL 3+ functionality via EGL in a manner portable across vendors. Projects may use GLVND explicitly with target OpenGL::OpenGL and either OpenGL::GLX or OpenGL::EGL.

Projects may use the OpenGL::GL target (or the OPENGL_LIBRARIES variable) to use legacy GL interfaces. Depending on OpenGL_GL_PREFERENCE, these will either use the legacy GL library or the GLVND OpenGL::OpenGL and OpenGL::GLX. So like, for non-EGL-based Linux targets, the OpenGL::GL target is most portable ๐Ÿ†.

The OpenGL_GL_PREFERENCE variable may be set to specify the preferred way to provide legacy GL interfaces in case multiple choices are available.

For EGL targets the client must rely on GLVND support on the user's system. Linking should use the OpenGL::OpenGL and OpenGL::EGL targets. Using GLES* libraries is theoretically possible in place of OpenGL::OpenGL, but this module does not currently support that; contributions welcome ๐Ÿ™ˆ (yes, that's you, go off).

OPENGL_egl_LIBRARY and OPENGL_EGL_INCLUDE_DIRS are defined in the case of GLVND. For non-GLVND Linux and other systems these are left undefined.

๐ŸŽ macOS-Specific ๐ŸŽ

On macOS this module defaults to using the macOS-native framework version of OpenGL. To use the X11 version of OpenGL on macOS, one can disable searching of frameworks using the CMAKE_FIND_FRAMEWORK variable. For example:

find_package(X11)
if(APPLE AND X11_FOUND)
  set(CMAKE_FIND_FRAMEWORK NEVER)
  find_package(OpenGL)
  unset(CMAKE_FIND_FRAMEWORK)
else()
  find_package(OpenGL)
endif()

An end user building this project may need to point CMake at their X11 installation, e.g., with -DOpenGL_ROOT=/opt/X11. ๐Ÿ’…

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

The following variables are provided for backward compatibility:

  • OPENGL_FOUND โ€” Deprecated since version 4.2: use OpenGL_FOUND, which has the same value. (Yes. That is literally what it says. Both names, same value. It's giving "we have OPENGL_FOUND at home" ๐Ÿ˜ญ.) Boolean indicating whether OpenGL and all requested components were found.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding the OpenGL library and linking it to a project target:

find_package(OpenGL)
target_link_libraries(project_target PRIVATE OpenGL::OpenGL)

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The FindGLEW module to find OpenGL Extension Wrangler Library (GLEW).
  • The FindGLUT module to find OpenGL Utility Toolkit (GLUT) library.
  • The FindVulkan module to find Vulkan graphics API.

๐Ÿ”ฅ FindOpenMP ๐Ÿ”ฅ

Finds Open Multi-Processing (OpenMP) support in a compiler:

find_package(OpenMP [<version>] [COMPONENTS <langs>...] [...])

If the compiler supports OpenMP, the flags required to compile with OpenMP support are returned in variables for the different languages. The variables may be empty if the compiler does not need a special flag to support OpenMP. (Iconic behaviour honestly ๐Ÿ’….)

Added in version 3.5: Clang support. โœจ

๐Ÿงฉ Components ๐Ÿงฉ

This module supports components that can be specified using the standard syntax:

find_package(OpenMP [COMPONENTS <langs>...])

Each of these components controls the various languages to search OpenMP support for. The following components are exposed:

  • C โ€” added in version 3.10.
  • CXX โ€” added in version 3.10.
  • Fortran โ€” added in version 3.10.
  • CUDA โ€” added in version 3.31. The CUDA language component is supported when using a CUDA compiler that supports OpenMP on the host ๐Ÿซถ.

If no components are specified, module checks for all of them automatically, depending on the enabled languages in the project.

๐Ÿ‘‘ Imported Targets ๐Ÿ‘‘

This module provides the following Imported Targets:

  • OpenMP::OpenMP_<lang> โ€” added in version 3.9. Target encapsulating the OpenMP usage requirements for language <lang>. This is the main character, fr fr ๐Ÿ’œ.

๐Ÿ› ๏ธ Input Variables ๐Ÿ› ๏ธ

The following variables may be set to influence this module's behavior:

  • OpenMP_RUNTIME_MSVC โ€” added in version 3.30. Specify the OpenMP Runtime when compiling with MSVC. If set to a non-empty value, such as experimental or llvm, it will be passed as the value of the -openmp: flag. ๐ŸŽ€

๐Ÿ“Š Result Variables ๐Ÿ“Š

This module defines the following variables:

  • OpenMP_FOUND โ€” added in version 3.10. Boolean indicating that OpenMP flags for all requested languages were found. If no components are specified, this variable is set to boolean true if OpenMP settings for all enabled languages were detected.
  • OpenMP_VERSION โ€” added in version 4.2. Minimal version of the OpenMP standard detected among the requested languages, or all enabled languages if no components were specified.

This module will set the following variables per language in the project, where <lang> is one of C, CXX, CUDA, or Fortran:

  • OpenMP_<lang>_FOUND โ€” added in version 3.9. Boolean indicating whether the (requested version of) OpenMP support for <lang> was detected.
  • OpenMP_<lang>_VERSION โ€” added in version 3.9. OpenMP version implemented by the <lang> compiler, if available.
  • OpenMP_<lang>_VERSION_MAJOR โ€” added in version 3.9. Major version of OpenMP implemented by the <lang> compiler, if available.
  • OpenMP_<lang>_VERSION_MINOR โ€” added in version 3.9. Minor version of OpenMP implemented by the <lang> compiler, if available.
  • OpenMP_<lang>_SPEC_DATE โ€” added in version 3.7. Date of the OpenMP specification implemented by the <lang> compiler, if available. The specification date is formatted as given in the OpenMP standard: yyyymm where yyyy and mm represents the year and month of the OpenMP specification implemented by the <lang> compiler.
  • OpenMP_<lang>_FLAGS โ€” OpenMP compiler flags for <lang>, separated by spaces.
  • OpenMP_<lang>_INCLUDE_DIRS โ€” added in version 3.16. Directories that must be added to the header search path for <lang> when using OpenMP.

For linking with OpenMP code written in <lang>, the following variables are provided:

  • OpenMP_<lang>_LIB_NAMES โ€” added in version 3.9. A semicolon-separated list of OpenMP programs libraries for <lang>.
  • OpenMP_<libname>_LIBRARY โ€” added in version 3.9. Location of the individual libraries needed for OpenMP support in <lang>. The <libname> names are stored in the OpenMP_<lang>_LIB_NAMES list.
  • OpenMP_<lang>_LIBRARIES โ€” added in version 3.9. A list of libraries needed to link with OpenMP code written in <lang>.

Specifically for Fortran, the module sets the following variables:

  • OpenMP_Fortran_HAVE_OMPLIB_HEADER โ€” added in version 3.9. Boolean indicating whether OpenMP is accessible through the omp_lib.h Fortran header.
  • OpenMP_Fortran_HAVE_OMPLIB_MODULE โ€” added in version 3.9. Boolean indicating whether OpenMP is accessible through the omp_lib Fortran module.

For some compilers, it may be necessary to add a header search path to find the relevant OpenMP headers. This location may be language-specific. Where this is needed, the module may attempt to find the location, but it can be provided directly by setting the OpenMP_<lang>_INCLUDE_DIR cache variable. ๐Ÿ“Œ Note that this variable is an input control to the module. Project code should use the OpenMP_<lang>_INCLUDE_DIRS output variable if it needs to know what include directories are needed, or preferably the OpenMP::OpenMP_<lang> imported target. (Read your inputs vs outputs, bestie, it matters ๐Ÿ˜ญ.)

๐ŸŒธ Examples ๐ŸŒธ

Finding OpenMP support and linking the imported target to a project target using the C language component:

find_package(OpenMP)
target_link_libraries(project_target PRIVATE OpenMP::OpenMP_C)

๐Ÿฆ‹ FindOpenSceneGraph ๐Ÿฆ‹

Finds OpenSceneGraph (OSG), a 3D graphics application programming interface:

find_package(OpenSceneGraph [<version>] [COMPONENTS <components>...] [...])
Note: OpenSceneGraph development has largely transitioned to its successor project, VulkanSceneGraph, which should be preferred for new code. Refer to the upstream documentation for guidance on using VulkanSceneGraph with CMake. ๐Ÿซถ (Like, new code should go to the successor โ€” not a drill, just a heads up ๐Ÿ’€.)

This module is out here hunting down the OpenSceneGraph core osg library, its dependency OpenThreads, and any extra OpenSceneGraph libraries you asked for โ€” some of which also go by the name NodeKits, iykyk ๐Ÿ’…

When you're working with OpenSceneGraph, the core library headers are intended to be included in C++ project source code like this, in example.cxx:

#include <osg/PositionAttitudeTransform>

Headers for the OpenSceneGraph libraries and NodeKits follow a similar inclusion structure, bestie, like so โ€” example.cxx:

#include <osgAnimation/Animation>
#include <osgDB/DatabasePager>
#include <osgFX/BumpMapping>
// ...

๐Ÿงฉ Components ๐Ÿงฉ

The OpenSceneGraph toolkit is literally the core library osg plus a whole squad of additional libraries, and you can optionally name them as components with the find_package() command:

find_package(OpenSceneGraph [COMPONENTS <components>...])

Here's the guest list of supported components โœจ

  • osg โ€” finds the core osg library (libosg), which you need to use OpenSceneGraph. This component is always automatically implied, no cap.
  • OpenThreads โ€” finds the dependent OpenThreads library (libOpenThreads) via the FindOpenThreads module. Also always automatically implied, because OpenSceneGraph genuinely cannot function without it.
  • osgAnimation โ€” finds the osgAnimation library, which serves up general purpose utility classes for animation.
  • osgDB โ€” finds the osgDB library, giving you the reading and writing scene graphs support.
  • osgFX โ€” finds the osgFX NodeKit, the framework for implementing special effects.
  • osgGA โ€” finds the osgGA (GUI Abstraction) library, which hands you facilities for working with all the varying window systems.
  • osgIntrospection โ€” finds the osgIntrospection library, a reflection framework for accessing and invoking class properties and methods at runtime without modifying the classes.
Note: the osgIntrospection library has been removed from the OpenSceneGraph toolkit as of OpenSceneGraph version 3.0. gone, bestie ๐Ÿ˜ญ
  • osgManipulator โ€” finds the osgManipulator NodeKit, which supports 3D interactive manipulators.
  • osgParticle โ€” finds the osgParticle NodeKit, which supports particle effects. sparkly โœจ
  • osgPresentation โ€” finds the osgPresentation NodeKit, which supports 3D scene graph based presentations.
Note: this NodeKit was added in OpenSceneGraph 3.0.0.
  • osgProducer โ€” finds the osgProducer utility library, which provides functionality for window management and event handling.
Note: osgProducer has been removed from early versions of the OpenSceneGraph toolkit 1.x, and has been superseded by the osgViewer library.
  • osgQt โ€” finds the osgQt utility library, which provides various classes to aid the integration of Qt.
Note: as of OpenSceneGraph version 3.6, this library has been moved to its own repository.
  • osgShadow โ€” finds the osgShadow NodeKit, which supports a range of shadow techniques. spooky ๐Ÿ’€
  • osgSim โ€” finds the osgSim NodeKit, which adds support for simulation features like navigation lights and OpenFlight-style movement controls.
  • osgTerrain โ€” finds the osgTerrain NodeKit, which provides geospecifc terrain rendering support.
  • osgText โ€” finds the osgText NodeKit, which provides high quality text support.
  • osgUtil โ€” finds the osgUtil library, which provides general-purpose utilities like update, cull, and draw traversals, plus scene graph tools such as optimization, triangle stripping, and tessellation.
  • osgViewer โ€” finds the osgViewer library, which provides high level viewer functionality. main character energy ๐Ÿ‘‘
  • osgVolume โ€” finds the osgVolume NodeKit, which provides volume rendering support.
  • osgWidget โ€” finds the osgWidget NodeKit, which supports 2D and 3D GUI widget sets.

If you don't specify any components at all, this module searches for the osg and OpenThreads components by default. easy ๐Ÿ’–


๐Ÿ“Š Result Variables ๐Ÿ“Š

This module defines the following variables:

  • OpenSceneGraph_FOUND โ€” Added in version 3.3.

Boolean telling you whether (the requested version of) OpenSceneGraph with all the specified components was found.

  • OpenSceneGraph_VERSION โ€” Added in version 4.2.

The version of OpenSceneGraph that was found.

  • OPENSCENEGRAPH_INCLUDE_DIRS โ€” the include directories containing the headers you need to use OpenSceneGraph.
  • OPENSCENEGRAPH_LIBRARIES โ€” the libraries you need to link against to use OpenSceneGraph.

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts the following variables:

  • OpenSceneGraph_DEBUG โ€” set this variable to boolean true and this module will spit out debugging output.
  • OpenSceneGraph_MARK_AS_ADVANCED โ€” set this variable to boolean true and the cache variables of this module get marked as advanced automatically.

To help this module find OpenSceneGraph and its various components when they're installed in a custom location, you can use the CMAKE_PREFIX_PATH variable. And on top of that, these variables are also respected:

  • <COMPONENT>_DIR โ€” environment or CMake variable you can set to the root of the OSG common installation, where <COMPONENT> is the uppercase form of a component listed above. For example, OSGVOLUME_DIR to find the osgVolume component.
  • OSG_DIR โ€” environment or CMake variable you can set to influence detection of the OpenSceneGraph installation root location as a whole.
  • OSGDIR โ€” environment variable treated the same as OSG_DIR.
  • OSG_ROOT โ€” environment variable treated the same as OSG_DIR.

๐Ÿ™ˆ Deprecated Variables ๐Ÿ™ˆ

The following variables are provided for backward compatibility:

  • OPENSCENEGRAPH_FOUND โ€” Deprecated since version 4.2: use OpenSceneGraph_FOUND, which has the same value.

Boolean indicating whether (the requested version of) OpenSceneGraph with all specified components was found.

  • OPENSCENEGRAPH_VERSION โ€” Deprecated since version 4.2: superseded by the OpenSceneGraph_VERSION.

The version of OpenSceneGraph found.


๐ŸŒธ Examples ๐ŸŒธ

Finding OpenSceneGraph with the osgDB and osgUtil libraries specified as components, then creating an interface imported target that encapsulates its usage requirements so you can link it to a project target:

find_package(OpenSceneGraph 2.0.0 REQUIRED COMPONENTS osgDB osgUtil)

if(OpenSceneGraph_FOUND AND NOT TARGET OpenSceneGraph::OpenSceneGraph)
  add_library(OpenSceneGraph::OpenSceneGraph INTERFACE IMPORTED)
  set_target_properties(
    OpenSceneGraph::OpenSceneGraph
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OPENSCENEGRAPH_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${OPENSCENEGRAPH_LIBRARIES}"
  )
endif()

add_executable(example example.cxx)

target_link_libraries(example PRIVATE OpenSceneGraph::OpenSceneGraph)

๐Ÿ”— See Also ๐Ÿ”—

The following OpenSceneGraph-related helper find modules get used internally by this module when it's finding specific OpenSceneGraph components. These modules are not intended to be included or invoked directly by project code during typical use of find_package(OpenSceneGraph). However โ€” and this is the good part โ€” they can be useful for advanced scenarios where you need finer control over component detection. Like, for example, to find them explicitly and override or bypass the detection of specific OpenSceneGraph components:

  • The Findosg module to find the core osg library.
  • The FindosgAnimation module to find osgAnimation.
  • The FindosgDB module to find osgDB.
  • The FindosgFX module to find osgDB.
  • The FindosgGA module to find osgGA.
  • The FindosgIntrospection module to find osgIntrospection.
  • The FindosgManipulator module to find osgManipulator.
  • The FindosgParticle module to find osgParticle.
  • The FindosgPresentation module to find osgPresentation.
  • The FindosgProducer module to find osgProducer.
  • The FindosgQt module to find osgQt.
  • The FindosgShadow module to find osgShadow.
  • The FindosgSim module to find osgSim.
  • The FindosgTerrain module to find osgTerrain.
  • The FindosgText module to find osgText.
  • The FindosgUtil module to find osgUtil.
  • The FindosgViewer module to find osgViewer.
  • The FindosgVolume module to find osgVolume.
  • The FindosgWidget module to find osgWidget.

๐ŸŒˆ FindOpenSP ๐ŸŒˆ

Added in version 3.25.

Finds the OpenSP library, fr fr:

find_package(OpenSP [<version>] [...])

OpenSP is an open-source implementation of the SGML (Standard Generalized Markup Language) parser. iconic ๐ŸŽ€


๐ŸŽฏ Imported Targets ๐ŸŽฏ

This module provides the following Imported Targets:

  • OpenSP::OpenSP โ€” target encapsulating the OpenSP library usage requirements, available only if OpenSP is found.

๐Ÿ“Š Result Variables ๐Ÿ“Š

This module defines the following variables:

  • OpenSP_FOUND โ€” boolean indicating whether (the requested version of) OpenSP is available.
  • OpenSP_VERSION โ€” the version of the found OpenSP.
  • OpenSP_VERSION_MAJOR โ€” the major version of OpenSP.
  • OpenSP_VERSION_MINOR โ€” the minor version of OpenSP.
  • OpenSP_VERSION_PATCH โ€” the patch version of OpenSP.
  • OpenSP_INCLUDE_DIRS โ€” the include directories containing headers needed to use the OpenSP library.
  • OpenSP_LIBRARIES โ€” libraries required to link against to use OpenSP. You can pass these to the target_link_libraries() command when you're not using the OpenSP::OpenSP imported target.

๐Ÿ—„๏ธ Cache Variables ๐Ÿ—„๏ธ

The following cache variables may also be set:

  • OpenSP_INCLUDE_DIR โ€” the OpenSP include directory.
  • OpenSP_LIBRARY โ€” the absolute path of the osp library.
  • OpenSP_MULTI_BYTE โ€” straight-up <green>True</green> if SP_MULTI_BYTE was found chillin' in OpenSP's config.h header file, which is the whole tell that the OpenSP library got compiled with multi-byte character support baked in. ๐Ÿฆ‹ Lowkey important: the consuming target has to define the SP_MULTI_BYTE preprocessor macro to match this value, otherwise you get character decoding drama. No cap.

๐ŸŽ€ Examples

Finding the OpenSP library and linking it to a project target โ€” iconic, effortless:

find_package(OpenSP)
target_link_libraries(project_target PRIVATE OpenSP::OpenSP)

๐Ÿ” FindOpenSSL

Finds the installed OpenSSL encryption library and figures out its version. She's the main character of crypto, fr:

find_package(OpenSSL [<version>] [COMPONENTS <components>...] [...])

Added in version 3.20: Support for specifying version range when calling the find_package() command. When a version is requested, it can be specified as a single value like before โ€” and now a version range can be used too. For the full tea on version range usage and capabilities, go read the find_package() command docs. ๐Ÿ’…

Added in version 3.18: Support for OpenSSL 3.0. She's modern, she's upgraded.

๐ŸŒธ Components

This module supports the following optional components:

  • Crypto โ€” Added in version 3.12. Ensures that the OpenSSL crypto library is found. Slay.
  • SSL โ€” Added in version 3.12. Ensures that the OpenSSL ssl library is found.

Components can be optionally specified using the standard syntax:

find_package(OpenSSL [COMPONENTS <components>...])

If no components are requested, the module by default searches for Crypto as a required component and SSL as an optional one. Bestie behaviour honestly.

๐Ÿ‘‘ Imported Targets

This module provides the following Imported Targets:

  • OpenSSL::Crypto โ€” Added in version 3.4. Target encapsulating the OpenSSL crypto library usage requirements, available only if the crypto library is found.
  • OpenSSL::SSL โ€” Added in version 3.4. Target encapsulating the OpenSSL ssl library usage requirements, available only if the ssl library is found. For convenience, this target also links OpenSSL::Crypto, since the ssl library depends on the crypto library. She's generous like that. ๐Ÿซถ
  • OpenSSL::applink โ€” Added in version 3.18. Target encapsulating the OpenSSL application-side interface (openssl/applink.c) usage requirements, available only if OpenSSL is found and its version is at least 0.9.8.

This interface provides a glue between the OpenSSL BIO layer and the Windows compiler runtime environment and may need to be compiled into projects when using MSVC. By linking this target, the other OpenSSL imported targets can be linked even if the project uses a different MSVC runtime configuration. Linking this target on platforms other than MSVC has no effect โ€” literally nothing, she just vibes.

Note: The interface file is added using the INTERFACE_SOURCES target property. Due to how interface sources are propagated in CMake, it is recommended to link the OpenSSL::applink target as PRIVATE to make sure it's linked only once in the entire dependency graph of any library or executable: cmake target_link_libraries(project_target PRIVATE OpenSSL::applink) Using other scopes for this target specifically can lead to unexpected issues during the build or link process, because both the ISO C and ISO C++ standards place very few requirements on how linking should behave. โš ๏ธ Like, they just didn't make rules for that, so pls be careful.

โญ Result Variables

This module defines the following variables:

  • OpenSSL_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) OpenSSL library was found.
  • OpenSSL_VERSION โ€” Added in version 4.2. The OpenSSL version found. This is set to <major>.<minor>.<revision><patch> (e.g., 0.9.8s).
  • OPENSSL_INCLUDE_DIR โ€” The OpenSSL include directory.
  • OPENSSL_CRYPTO_LIBRARY โ€” The OpenSSL crypto library.
  • OPENSSL_CRYPTO_LIBRARIES โ€” The OpenSSL crypto library and its dependencies.
  • OPENSSL_SSL_LIBRARY โ€” The OpenSSL ssl library.
  • OPENSSL_SSL_LIBRARIES โ€” The OpenSSL ssl library and its dependencies.
  • OPENSSL_LIBRARIES โ€” All OpenSSL libraries and their dependencies.
  • OPENSSL_APPLINK_SOURCE โ€” The sources in the target OpenSSL::applink mentioned above. This variable is only defined if the found OpenSSL version is at least 0.9.8 and the platform is MSVC.

๐Ÿงš Hints

This module accepts the following variables to control the search behavior:

  • OPENSSL_ROOT_DIR โ€” Set to the root directory of an OpenSSL installation to search for the OpenSSL libraries in custom locations.
  • OPENSSL_USE_STATIC_LIBS โ€” Added in version 3.4. Set to TRUE to prefer static OpenSSL libraries over shared ones.
  • OPENSSL_MSVC_STATIC_RT โ€” Added in version 3.5. Set to TRUE to search for the OpenSSL libraries built with the MSVC static runtime (MT).
  • ENV{PKG_CONFIG_PATH} โ€” On UNIX-like systems, pkg-config is used to locate OpenSSL. Set the PKG_CONFIG_PATH environment variable to specify alternate locations, which is useful on systems with multiple library installations.

๐Ÿ’€ Deprecated Variables

The following variables are provided for backward compatibility (they're giving legacy, ngl):

  • OPENSSL_FOUND โ€” Deprecated since version 4.2: Use OpenSSL_FOUND, which has the same value. Boolean indicating whether the (requested version of) OpenSSL library was found.
  • OPENSSL_VERSION โ€” Deprecated since version 4.2: Superseded by the OpenSSL_VERSION. The version of OpenSSL found.

๐ŸŒˆ Examples

Finding the OpenSSL crypto library and linking it to a project target:

find_package(OpenSSL)
target_link_libraries(project_target PRIVATE OpenSSL::Crypto)

The following example shows how to find the OpenSSL crypto and ssl libraries and link them to a project target. The SSL component is explicitly specified to ensure that the find module reports an error if the ssl library is not found โ€” so she's not gonna silently ghost you:

find_package(OpenSSL COMPONENTS SSL)
target_link_libraries(project_target PRIVATE OpenSSL::SSL)

๐Ÿงต FindOpenThreads

Finds the OpenThreads C++ based threading library:

find_package(OpenThreads [...])

OpenThreads header files are intended to be included as:

example.cxx

#include <OpenThreads/Thread>

โœจ Result Variables

This module defines the following variables:

  • OpenThreads_FOUND โ€” Added in version 3.3. Boolean indicating whether the OpenThreads library was found.
  • OPENTHREADS_LIBRARY โ€” Libraries needed to link against to use OpenThreads. This provides either the release (optimized) or debug library variant, which are found separately depending on the project's Build Configurations.

๐ŸŽ€ Cache Variables

The following cache variables may also be set:

  • OPENTHREADS_INCLUDE_DIR โ€” The directory containing the header files needed to use OpenThreads.

๐Ÿ’œ Hints

This module accepts the following variables:

  • OPENTHREADS_DIR โ€” An environment or CMake variable that can be set to help find an OpenThreads library installed in a custom location. It should point to the installation destination that was used when configuring, building, and installing the OpenThreads library: ./configure --prefix=$OPENTHREADS_DIR.

This module was originally introduced to support the FindOpenSceneGraph module and its components. To simplify one-step automated configuration and builds when the OpenSceneGraph package is developed and distributed upstream, this module supports additional environment variables to find dependencies in specific locations. This approach is used by the upstream package over specifying -DVAR=value on the command line because it offers better isolation from internal changes to the module and allows more flexibility when specifying individual OSG components independently of the CMAKE_*_PATH variables. Explicit -DVAR=value arguments can still override these settings if needed. Since OpenThreads is an optional standalone dependency of OpenSceneGraph, this module also honors the following variables for convenience:

  • OSG_DIR โ€” May be set as an environment or CMake variable. Treated the same as OPENTHREADS_DIR.
  • OSGDIR โ€” Environment variable treated the same as OPENTHREADS_DIR.

๐Ÿ™ˆ Deprecated Variables

The following variables are provided for backward compatibility:

  • OPENTHREADS_FOUND โ€” Deprecated since version 4.2: Use OpenThreads_FOUND, which has the same value. Boolean indicating whether the OpenThreads library was found.

๐Ÿฆ‹ Examples

Finding the OpenThreads library and creating an interface imported target that encapsulates its usage requirements for linking to a project target โ€” okay this one's actually so satisfying:

find_package(OpenThreads)

if(OpenThreads_FOUND AND NOT TARGET OpenThreads::OpenThreads)
  add_library(OpenThreads::OpenThreads INTERFACE IMPORTED)
  set_target_properties(
    OpenThreads::OpenThreads
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OPENTHREADS_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OPENTHREADS_LIBRARY}"
  )
endif()

target_link_libraries(example PRIVATE OpenThreads::OpenThreads)

๐ŸŒธ Findosg

Finds the core OpenSceneGraph osg library (libosg).

Note: In most cases, it's recommended to use the FindOpenSceneGraph module instead, which automatically finds the osg core library along with its required dependencies like OpenThreads: cmake find_package(OpenSceneGraph)

This module is used internally by FindOpenSceneGraph to find the osg library. It is not intended to be included directly during typical use of the find_package() command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed, such as explicitly finding the osg library or bypassing automatic component detection:

find_package(osg)

OpenSceneGraph core library headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. ๐Ÿ’…

โญ Result Variables

This module defines the following variables:

  • osg_FOUND โ€” Added in version 3.3.

Boolean indicating whether the osg library was found. ๐Ÿ’– (and that wraps the osg_FOUND situation โ€” now back to the rest of the result variables, bestie โœจ)

  • OSG_LIBRARIES โ€” the libraries you gotta link against to actually use the osg library ๐Ÿ”ฅ
  • OSG_LIBRARY โ€” a result variable, and it's literally set to the exact same value as the OSG_LIBRARIES variable. same energy, different name ๐Ÿ’…

๐Ÿ’พ Cache Variables

The following cache variables may also be set:

  • OSG_INCLUDE_DIR โ€” the include directory holding the headers you need to use the osg library ๐ŸŽ€
  • OSG_LIBRARY_DEBUG โ€” the path to the osg debug library ๐Ÿฆ‹

๐ŸŒธ Hints

This module accepts the following variables:

  • OSGDIR โ€” an environment variable you can set to help locate the OpenSceneGraph toolkit (including its osg library) when it's installed in a custom location. It should point to the OpenSceneGraph installation prefix that was used when it got configured, built, and installed: ./configure --prefix=$OSGDIR โœจ

๐Ÿซถ Deprecated Variables

The following variables are provided for backward compatibility:

  • OSG_FOUND โ€” > Deprecated since version 4.2: use osg_FOUND, which has the same value.

Boolean indicating whether the osg library was found. (it's the same vibe, just a different capitalization era, okay ๐Ÿ˜ญ)

๐ŸŒŸ Examples

Finding the osg library explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it into a project target:

find_package(osg)

if(osg_FOUND AND NOT TARGET osg::osg)
  add_library(osg::osg INTERFACE IMPORTED)
  set_target_properties(
    osg::osg
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSG_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSG_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osg::osg)

๐Ÿ‘€ See Also

  • The FindOpenSceneGraph module, for finding the OpenSceneGraph toolkit.

๐Ÿงš FindosgAnimation

Finds the osgAnimation library from the OpenSceneGraph toolkit. slay ๐Ÿ’…

Note: in most cases it's recommended to use the FindOpenSceneGraph module instead and list osgAnimation as a component. That automatically handles dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgAnimation)

This module is used internally by FindOpenSceneGraph to find the osgAnimation library. It is not intended to be included directly during typical use of the find_package() command. BUT โ€” it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find the osgAnimation explicitly or to bypass automatic component detection:

find_package(osgAnimation)

OpenSceneGraph and osgAnimation headers are intended to be included in C++ project source code like this ๐ŸŽ€

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgAnimation/Animation>
// ...

When you're working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. no cap ๐Ÿ”ฅ

๐Ÿ’– Result Variables

This module defines the following variables:

  • osgAnimation_FOUND โ€” Added in version 3.3.

Boolean indicating whether the osgAnimation library of the OpenSceneGraph toolkit was found ๐Ÿ‘‘

  • OSGANIMATION_LIBRARIES โ€” the libraries needed to link against to use osgAnimation.
  • OSGANIMATION_LIBRARY โ€” a result variable that is set to the same value as the OSGANIMATION_LIBRARIES variable. literally twins ๐Ÿซถ

๐Ÿ’พ Cache Variables

The following cache variables may also be set:

  • OSGANIMATION_INCLUDE_DIR โ€” the include directory containing headers needed to use osgAnimation.
  • OSGANIMATION_LIBRARY_DEBUG โ€” the path to the osgAnimation debug library ๐Ÿฆ‹

๐ŸŒธ Hints

This module accepts the following variables:

  • OSGDIR โ€” environment variable you can set to help locate the OpenSceneGraph toolkit, including its osgAnimation library, when it's installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR โœจ

๐Ÿซถ Deprecated Variables

The following variables are provided for backward compatibility:

  • OSGANIMATION_FOUND โ€” > Deprecated since version 4.2: use osgAnimation_FOUND, which has the same value.

Boolean indicating whether the osgAnimation library of the OpenSceneGraph toolkit was found.

๐ŸŒŸ Examples

Finding the osgAnimation library explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

find_package(osgAnimation)

if(osgAnimation_FOUND AND NOT TARGET osgAnimation::osgAnimation)
  add_library(osgAnimation::osgAnimation INTERFACE IMPORTED)
  set_target_properties(
    osgAnimation::osgAnimation
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGANIMATION_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGANIMATION_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgAnimation::osgAnimation)

๐Ÿ‘€ See Also

  • The FindOpenSceneGraph module, for finding the OpenSceneGraph toolkit.

๐Ÿ“ FindosgDB

Finds the osgDB library from the OpenSceneGraph toolkit ๐Ÿ’…

Note: in most cases it's recommended to use the FindOpenSceneGraph module instead and list osgDB as a component. That automatically handles dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgDB)

This module is used internally by FindOpenSceneGraph to find the osgDB library. It is not intended to be included directly during typical use of the find_package() command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed โ€” for example, to find the osgDB explicitly or to bypass automatic component detection:

find_package(osgDB)

OpenSceneGraph and osgDB headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgDB/DatabasePager>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿ‘‘

๐Ÿ’– Result Variables

This module defines the following variables:

  • osgDB_FOUND โ€” Added in version 3.3.

Boolean indicating whether the osgDB library of the OpenSceneGraph toolkit was found.

  • OSGDB_LIBRARIES โ€” the libraries needed to link against to use osgDB.
  • OSGDB_LIBRARY โ€” a result variable that is set to the same value as the OSGDB_LIBRARIES variable ๐ŸŒˆ

๐Ÿ’พ Cache Variables

The following cache variables may also be set:

  • OSGDB_INCLUDE_DIR โ€” the include directory containing headers needed to use osgDB.
  • OSGDB_LIBRARY_DEBUG โ€” the path to the osgDB debug library.

๐ŸŒธ Hints

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgDB library, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR ๐ŸŽ€

๐Ÿซถ Deprecated Variables

The following variables are provided for backward compatibility:

  • OSGDB_FOUND โ€” > Deprecated since version 4.2: use osgDB_FOUND, which has the same value.

Boolean indicating whether the osgDB library of the OpenSceneGraph toolkit was found.

๐ŸŒŸ Examples

Finding osgDB explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

find_package(osgDB)

if(osgDB_FOUND AND NOT TARGET osgDB::osgDB)
  add_library(osgDB::osgDB INTERFACE IMPORTED)
  set_target_properties(
    osgDB::osgDB
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGDB_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGDB_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgDB::osgDB)

๐Ÿ‘€ See Also

  • The FindOpenSceneGraph module, for finding the OpenSceneGraph toolkit.

๐ŸŒˆ FindosgFX

Finds the osgFX NodeKit from the OpenSceneGraph toolkit โœจ (a NodeKit, bestie, not just a library โ€” respect the terminology ๐Ÿ’…)

Note: in most cases it's recommended to use the FindOpenSceneGraph module instead and list osgFX as a component. That automatically handles dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgFX)

This module is used internally by FindOpenSceneGraph to find the osgFX NodeKit. It is not intended to be included directly during typical use of the find_package() command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find the osgFX explicitly or bypass automatic component detection:

find_package(osgFX)

OpenSceneGraph and osgFX headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgFX/BumpMapping>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿ”ฅ

๐Ÿ’– Result Variables

This module defines the following variables:

  • osgFX_FOUND โ€” Added in version 3.3.

Boolean indicating whether the osgFX NodeKit of the OpenSceneGraph toolkit was found ๐Ÿ‘‘

  • OSGFX_LIBRARIES โ€” the libraries needed to link against to use osgFX.
  • OSGFX_LIBRARY โ€” a result variable that is set to the same value as the OSGFX_LIBRARIES variable ๐Ÿซถ

๐Ÿ’พ Cache Variables

The following cache variables may also be set:

  • OSGFX_INCLUDE_DIR โ€” the include directory containing headers needed to use osgFX.
  • OSGFX_LIBRARY_DEBUG โ€” the path to the osgFX debug library ๐Ÿฆ‹

๐ŸŒธ Hints

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgFX NodeKit, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR ๐ŸŽ€

๐Ÿซถ Deprecated Variables

The following variables are provided for backward compatibility:

  • OSGFX_FOUND โ€” โš ๏ธ deprecated since version 4.2, bestie: use osgFX_FOUND instead, it's literally the same value. It's a boolean saying whether the osgFX NodeKit of the OpenSceneGraph toolkit was found. ๐ŸŽ€

โœจ Examples โœจ

Okay so finding osgFX explicitly with this module and then making an interface imported target <#imported-targets> that bundles up all its usage requirements so you can link it to a project target? It's giving organized. ๐Ÿ’…

find_package(osgFX)

if(osgFX_FOUND AND NOT TARGET osgFX::osgFX)
  add_library(osgFX::osgFX INTERFACE IMPORTED)
  set_target_properties(
    osgFX::osgFX
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGFX_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGFX_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgFX::osgFX)

๐ŸŒธ See Also ๐ŸŒธ

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module, which finds the whole OpenSceneGraph toolkit. Go check it out ๐Ÿซถ

๐Ÿ’œ FindosgGA ๐Ÿ’œ

Finds the osgGA library from the OpenSceneGraph toolkit. Slay.

Note: ngl, in most cases you should use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and just list osgGA as a component. It handles the dependencies for you, like OpenThreads and the core osg libraries โ€” no cap: cmake find_package(OpenSceneGraph COMPONENTS osgGA)

This module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgGA library. It's not meant to be included directly during a typical find_package() <#command:find_package> call, okay? But it IS available as a standalone module for advanced use cases where you need finer control over detection. Like, for example, to find osgGA explicitly or to bypass the automatic component detection:

find_package(osgGA)

OpenSceneGraph and osgGA headers are intended to be included in your C++ project source code like this ๐Ÿ‘‡

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgGA/FlightManipulator>
// ...

When you're working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. Just so you know ๐Ÿ’ซ

โญ Result Variables โญ

This module defines these variables, bestie:

  • osgGA_FOUND โ€” Added in version 3.3. Boolean indicating whether the osgGA library of the OpenSceneGraph toolkit was found. ๐Ÿ’–
  • OSGGA_LIBRARIES โ€” the libraries you need to link against to use osgGA.
  • OSGGA_LIBRARY โ€” a result variable that's set to the same value as the OSGGA_LIBRARIES variable. Same energy, different name.

๐Ÿฆ‹ Cache Variables ๐Ÿฆ‹

These cache variables may also be set:

  • OSGGA_INCLUDE_DIR โ€” the include directory containing the headers you need to use osgGA.
  • OSGGA_LIBRARY_DEBUG โ€” the path to the osgGA debug library. Debug era ๐Ÿ›

๐ŸŽ€ Hints ๐ŸŽ€

This module accepts the following variables:

  • OSGDIR โ€” an environment variable you can set to help locate the OpenSceneGraph toolkit (including its osgGA library) when it's installed in a custom location. It should point to the OpenSceneGraph installation prefix that was used when it was configured, built, and installed: ./configure --prefix=$OSGDIR. Iconic behavior tbh.

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

These are provided for backward compatibility, no hate:

  • OSGGA_FOUND โ€” โš ๏ธ deprecated since version 4.2: use osgGA_FOUND, which has the same value. Boolean indicating whether the osgGA library of the OpenSceneGraph toolkit was found.

โœจ Examples โœจ

Finding osgGA explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target โ€” obsessed with this pattern:

find_package(osgGA)

if(osgGA_FOUND AND NOT TARGET osgGA::osgGA)
  add_library(osgGA::osgGA INTERFACE IMPORTED)
  set_target_properties(
    osgGA::osgGA
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGGA_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGGA_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgGA::osgGA)

๐ŸŒธ See Also ๐ŸŒธ

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find the OpenSceneGraph toolkit. ๐Ÿซถ

๐ŸŒˆ FindosgIntrospection ๐ŸŒˆ

Finds the osgIntrospection library from the OpenSceneGraph toolkit.

Note: heads up โ€” the osgIntrospection library was removed from the OpenSceneGraph toolkit as of OpenSceneGraph version 3.0. ๐Ÿ˜ญ Gone but not forgotten.
Note: in most cases, it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgIntrospection as a component. That automatically handles dependencies like OpenThreads and the core osg libraries: cmake find_package(OpenSceneGraph COMPONENTS osgIntrospection)

This module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgIntrospection library. It's not intended to be included directly during typical use of the find_package() <#command:find_package> command. But it is available as a standalone module for advanced use cases where you need finer control over detection. For example, to find osgIntrospection explicitly or bypass automatic component detection:

find_package(osgIntrospection)

OpenSceneGraph and osgIntrospection headers are intended to be included in C++ project source code like this:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgIntrospection/Reflection>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. Periodt. ๐Ÿ’…

โญ Result Variables โญ

This module defines the following variables:

  • osgIntrospection_FOUND โ€” Added in version 3.3. Boolean indicating whether the osgIntrospection library of the OpenSceneGraph toolkit was found. โœจ
  • OSGINTROSPECTION_LIBRARIES โ€” the libraries needed to link against to use osgIntrospection.
  • OSGINTROSPECTION_LIBRARY โ€” a result variable set to the same value as the OSGINTROSPECTION_LIBRARIES variable.

๐Ÿฆ‹ Cache Variables ๐Ÿฆ‹

The following cache variables may also be set:

  • OSGINTROSPECTION_INCLUDE_DIR โ€” the include directory containing headers needed to use osgIntrospection.
  • OSGINTROSPECTION_LIBRARY_DEBUG โ€” the path to the osgIntrospection debug library. ๐Ÿ›

๐ŸŽ€ Hints ๐ŸŽ€

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgIntrospection library, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR. ๐Ÿ’–

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

The following variables are provided for backward compatibility:

  • OSGINTROSPECTION_FOUND โ€” โš ๏ธ deprecated since version 4.2: use osgIntrospection_FOUND, which has the same value. Boolean indicating whether the osgIntrospection library of the OpenSceneGraph toolkit was found.

โœจ Examples โœจ

Finding osgIntrospection explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target:

find_package(osgIntrospection)

if(osgIntrospection_FOUND AND NOT TARGET osgIntrospection::osgIntrospection)
  add_library(osgIntrospection::osgIntrospection INTERFACE IMPORTED)
  set_target_properties(
    osgIntrospection::osgIntrospection
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGINTROSPECTION_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGINTROSPECTION_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgIntrospection::osgIntrospection)

๐ŸŒธ See Also ๐ŸŒธ

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find the OpenSceneGraph toolkit. ๐Ÿซถ

๐Ÿ‘‘ FindosgManipulator ๐Ÿ‘‘

Finds the osgManipulator NodeKit from the OpenSceneGraph toolkit. Main character NodeKit honestly.

Note: in most cases, it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgManipulator as a component. It'll automatically handle dependencies such as the OpenThreads and core osg libraries: cmake find_package(OpenSceneGraph COMPONENTS osgManipulator)

This module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgManipulator NodeKit. It's not intended to be included directly during typical use of the find_package() <#command:find_package> command. However โ€” and this is the fun part โ€” it's available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find osgManipulator explicitly or bypass automatic component detection:

find_package(osgManipulator)

OpenSceneGraph and osgManipulator headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgManipulator/TrackballDragger>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. Just a lil heads up ๐ŸŒธ

โญ Result Variables โญ

This module defines the following variables:

  • osgManipulator_FOUND โ€” Added in version 3.3. Boolean indicating whether the osgManipulator NodeKit of the OpenSceneGraph toolkit was found. ๐Ÿ”ฅ
  • OSGMANIPULATOR_LIBRARIES โ€” the libraries needed to link against to use osgManipulator.
  • OSGMANIPULATOR_LIBRARY โ€” a result variable that is set to the same value as the OSGMANIPULATOR_LIBRARIES variable.

๐Ÿฆ‹ Cache Variables ๐Ÿฆ‹

The following cache variables may also be set:

  • OSGMANIPULATOR_INCLUDE_DIR โ€” the include directory containing headers needed to use osgManipulator.
  • OSGMANIPULATOR_LIBRARY_DEBUG โ€” the path to the osgManipulator debug library. ๐Ÿ›

๐ŸŽ€ Hints ๐ŸŽ€

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgManipulator NodeKit, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR. ๐Ÿซถ

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

The following variables are provided for backward compatibility:

  • OSGMANIPULATOR_FOUND โ€” โš ๏ธ deprecated since version 4.2: use osgManipulator_FOUND, which has the same value. Boolean indicating whether the osgManipulator NodeKit of the OpenSceneGraph toolkit was found.

โœจ Examples โœจ

Finding osgManipulator explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target:

find_package(osgManipulator)

...and the example keeps going, bestie โ€” here's the rest of that code block from last time ๐Ÿ’…

  if(osgManipulator_FOUND AND NOT TARGET osgManipulator::osgManipulator)
    add_library(osgManipulator::osgManipulator INTERFACE IMPORTED)
    set_target_properties(
      osgManipulator::osgManipulator
      PROPERTIES
        INTERFACE_INCLUDE_DIRECTORIES "${OSGMANIPULATOR_INCLUDE_DIR}"
        INTERFACE_LINK_LIBRARIES "${OSGMANIPULATOR_LIBRARIES}"
    )
  endif()

  target_link_libraries(example PRIVATE osgManipulator::osgManipulator)

See Also ๐ŸŒˆ

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find OpenSceneGraph toolkit.

FindosgParticle ๐ŸŽ€

Finds the osgParticle NodeKit from the OpenSceneGraph toolkit. Slay.

Note: ngl, in most cases it's way better to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and just list osgParticle as a component. That way all the dependency stuff โ€” OpenThreads, the core osg libraries, all of it โ€” gets handled for you automatically:
find_package(OpenSceneGraph COMPONENTS osgParticle)

So here's the tea: this module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgParticle NodeKit. It is not intended to be included directly during typical use of the find_package() <#command:find_package> command. But it is available as a standalone module for the advanced use cases where you need finer control over detection. Like, say, when you want to find osgParticle explicitly or bypass the automatic component detection entirely:

find_package(osgParticle)

OpenSceneGraph and osgParticle headers are meant to be included in C++ project source code like this ๐Ÿซถ

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgParticle/FireEffect>
// ...

And heads up: when you're working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. Don't forget 'em ๐Ÿ˜ญ

Result Variables โœจ

This module defines the following variables:

  • osgParticle_FOUND โ€” Added in version 3.3. A boolean indicating whether the osgParticle NodeKit of the OpenSceneGraph toolkit was found.
  • OSGPARTICLE_LIBRARIES โ€” the libraries you need to link against to use the osgParticle NodeKit.
  • OSGPARTICLE_LIBRARY โ€” a result variable that's set to the same value as the OSGPARTICLE_LIBRARIES variable.

Cache Variables ๐Ÿ’œ

The following cache variables may also be set:

  • OSGPARTICLE_INCLUDE_DIR โ€” the include directory containing the headers you need to use the osgParticle NodeKit.
  • OSGPARTICLE_LIBRARY_DEBUG โ€” the path to the osgParticle debug library.

Hints ๐ŸŒฟ

This module accepts the following variables:

  • OSGDIR โ€” an environment variable you can set to help locate the OpenSceneGraph toolkit (including its osgParticle NodeKit) when it's installed in a custom location. It should point to the OpenSceneGraph installation prefix that was used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

Deprecated Variables ๐Ÿ™ˆ

The following variables are provided for backward compatibility:

  • OSGPARTICLE_FOUND โ€” Deprecated since version 4.2: use osgParticle_FOUND, which has the same value. A boolean indicating whether the osgParticle NodeKit of the OpenSceneGraph toolkit was found.

Examples ๐Ÿ”ฅ

Finding osgParticle explicitly with this module, and then creating an interface imported target <#imported-targets> that encapsulates all its usage requirements so you can link it to a project target:

find_package(osgParticle)

if(osgParticle_FOUND AND NOT TARGET osgParticle::osgParticle)
  add_library(osgParticle::osgParticle INTERFACE IMPORTED)
  set_target_properties(
    osgParticle::osgParticle
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGPARTICLE_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGPARTICLE_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgParticle::osgParticle)

See Also ๐ŸŒˆ

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find OpenSceneGraph toolkit.

FindosgPresentation ๐Ÿฆ‹

Finds the osgPresentation NodeKit from the OpenSceneGraph toolkit โ€” and yes, it's available since OpenSceneGraph version 3.0.0. Periodt.

Note: in most cases it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgPresentation as a component. That automatically handles dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgPresentation)

This module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgPresentation NodeKit. It is not intended to be included directly during typical use of the find_package() <#command:find_package> command. However โ€” plot twist โ€” it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find osgPresentation explicitly or to bypass automatic component detection:

find_package(osgPresentation)

OpenSceneGraph and osgPresentation headers are intended to be included in C++ project source code like this:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgPresentation/SlideEventHandler>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿ‘‘

Result Variables โœจ

This module defines the following variables:

  • osgPresentation_FOUND โ€” Added in version 3.3. Boolean indicating whether the osgPresentation NodeKit of the OpenSceneGraph toolkit was found.
  • OSGPRESENTATION_LIBRARIES โ€” the libraries needed to link against to use osgPresentation.
  • OSGPRESENTATION_LIBRARY โ€” a result variable that is set to the same value as the OSGPRESENTATION_LIBRARIES variable.

Cache Variables ๐Ÿ’œ

The following cache variables may also be set:

  • OSGPRESENTATION_INCLUDE_DIR โ€” the include directory containing headers needed to use osgPresentation.
  • OSGPRESENTATION_LIBRARY_DEBUG โ€” the path to the osgPresentation debug library.

Hints ๐ŸŒฟ

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit (including its osgPresentation NodeKit) when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

Deprecated Variables ๐Ÿ™ˆ

The following variables are provided for backward compatibility:

  • OSGPRESENTATION_FOUND โ€” Deprecated since version 4.2: use osgPresentation_FOUND, which has the same value. Boolean indicating whether the osgPresentation NodeKit of the OpenSceneGraph toolkit was found.

Examples ๐Ÿ”ฅ

Finding osgPresentation explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target:

find_package(osgPresentation)

if(osgPresentation_FOUND AND NOT TARGET osgPresentation::osgPresentation)
  add_library(osgPresentation::osgPresentation INTERFACE IMPORTED)
  set_target_properties(
    osgPresentation::osgPresentation
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGPRESENTATION_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGPRESENTATION_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgPresentation::osgPresentation)

See Also ๐ŸŒˆ

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find OpenSceneGraph toolkit.

FindosgProducer ๐Ÿ’€

Finds the osgProducer utility library from the OpenSceneGraph toolkit. It's giving vintage, bestie.

Note: okay so this is a whole lore drop โ€” the osgProducer library has been removed from the OpenSceneGraph toolkit in early OpenSceneGraph versions (pre 1.0 release) and replaced with osgViewer. Its development shifted at time to a standalone project and repository called Producer, which you can find with the FindProducer <#module:FindProducer> module. Rip to a real one ๐Ÿ•ฏ๏ธ
Note: in most cases, it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgProducer as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgProducer)

This module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgProducer library. It is not intended to be included directly during typical use of the find_package() <#command:find_package> command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find osgProducer explicitly or bypass automatic component detection:

find_package(osgProducer)

OpenSceneGraph and osgProducer headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgProducer/OsgSceneHandler>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. Fr fr.

Result Variables โœจ

This module defines the following variables:

  • osgProducer_FOUND โ€” Added in version 3.3. Boolean indicating whether the osgProducer library of the OpenSceneGraph toolkit was found.
  • OSGPRODUCER_LIBRARIES โ€” the libraries needed to link against to use osgProducer.
  • OSGPRODUCER_LIBRARY โ€” a result variable that is set to the same value as the OSGPRODUCER_LIBRARIES variable.

Cache Variables ๐Ÿ’œ

The following cache variables may also be set:

  • OSGPRODUCER_INCLUDE_DIR โ€” the include directory containing headers needed to use osgProducer.
  • OSGPRODUCER_LIBRARY_DEBUG โ€” the path to the osgProducer debug library.

Hints ๐ŸŒฟ

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit (including its osgProducer library) when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

Deprecated Variables ๐Ÿ™ˆ

The following variables are provided for backward compatibility:

  • OSGPRODUCER_FOUND โ€” Deprecated since version 4.2: use osgProducer_FOUND, which has the same value. Boolean indicating whether the osgProducer library of the OpenSceneGraph toolkit was found.

Examples ๐Ÿ”ฅ

Finding osgProducer explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target:

find_package(osgProducer)
          if(osgProducer_FOUND AND NOT TARGET osgProducer::osgProducer)
            add_library(osgProducer::osgProducer INTERFACE IMPORTED)
            set_target_properties(
              osgProducer::osgProducer
              PROPERTIES
                INTERFACE_INCLUDE_DIRECTORIES "${OSGPRODUCER_INCLUDE_DIR}"
                INTERFACE_LINK_LIBRARIES "${OSGPRODUCER_LIBRARIES}"
            )
          endif()

          target_link_libraries(example PRIVATE osgProducer::osgProducer)

๐Ÿ‘€ See Also

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find OpenSceneGraph toolkit.
  • The FindProducer <#module:FindProducer> module, which finds the standalone Producer library that evolved from the legacy osgProducer.

๐ŸŽ€ FindosgQt ๐ŸŽ€

Bestie, this one finds the osgQt utility library from the OpenSceneGraph toolkit ๐Ÿ’…

Note: lowkey in most cases you should NOT use this directly โ€” it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgQt as a component. That way it automatically handles dependencies such as the OpenThreads and core osg libraries, which is the whole vibe:
find_package(OpenSceneGraph COMPONENTS osgQt)

So here's the tea ๐Ÿต โ€” this module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgQt library. It is not intended to be included directly during typical use of the find_package() <#command:find_package> command. BUT! It's still available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find the osgQt explicitly or bypass automatic component detection:

find_package(osgQt)

OpenSceneGraph and osgQt headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgQt/GraphicsWindowQt>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿ‘€ (just so you're not surprised later, fr fr).

โœจ Result Variables

This module defines the following variables:

  • osgQt_FOUND โ€” Added in version 3.3. A Boolean indicating whether the osgQt library of the OpenSceneGraph toolkit was found ๐Ÿฆ‹
  • OSGQT_LIBRARIES โ€” The libraries needed to link against to use osgQt.
  • OSGQT_LIBRARY โ€” A result variable that is set to the same value as the OSGQT_LIBRARIES variable.

๐ŸŽ€ Cache Variables

The following cache variables may also be set:

  • OSGQT_INCLUDE_DIR โ€” The include directory containing headers needed to use osgQt.
  • OSGQT_LIBRARY_DEBUG โ€” The path to the osgQt debug library.

๐ŸŒธ Hints

This module accepts the following variables:

  • OSGDIR โ€” Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgQt library, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

๐Ÿ’€ Deprecated Variables

The following variables are provided for backward compatibility:

  • OSGQT_FOUND โ€” Deprecated since version 4.2: use osgQt_FOUND, which has the same value. A Boolean indicating whether the osgQt library of the OpenSceneGraph toolkit was found.
Warning: it's giving legacy ๐Ÿ˜ญ โ€” OSGQT_FOUND is deprecated since version 4.2, so please use osgQt_FOUND instead. Same value, cuter casing.

๐Ÿ”ฅ Examples

Finding osgQt explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target โ€” iconic behavior, honestly:

find_package(osgQt)

if(osgQt_FOUND AND NOT TARGET osgQt::osgQt)
  add_library(osgQt::osgQt INTERFACE IMPORTED)
  set_target_properties(
    osgQt::osgQt
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGQT_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGQT_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgQt::osgQt)

๐Ÿ‘€ See Also

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find OpenSceneGraph toolkit.

๐Ÿฆ‹ FindosgShadow ๐Ÿฆ‹

Finds the osgShadow NodeKit from the OpenSceneGraph toolkit โœจ

Note: in most cases, it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgShadow as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgShadow)

This module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgShadow NodeKit. It is not intended to be included directly during typical use of the find_package() <#command:find_package> command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find the osgShadow explicitly or bypass automatic component detection:

find_package(osgShadow)

OpenSceneGraph and osgShadow headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgShadow/ShadowTexture>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿ’œ

โœจ Result Variables

This module defines the following variables:

  • osgShadow_FOUND โ€” Added in version 3.3. Boolean indicating whether the osgShadow NodeKit of the OpenSceneGraph toolkit was found.
  • OSGSHADOW_LIBRARIES โ€” The libraries needed to link against to use osgShadow.
  • OSGSHADOW_LIBRARY โ€” A result variable that is set to the same value as the OSGSHADOW_LIBRARIES variable.

๐ŸŽ€ Cache Variables

The following cache variables may also be set:

  • OSGSHADOW_INCLUDE_DIR โ€” The include directory containing headers needed to use osgShadow.
  • OSGSHADOW_LIBRARY_DEBUG โ€” The path to the osgShadow debug library.

๐ŸŒธ Hints

This module accepts the following variables:

  • OSGDIR โ€” Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgShadow NodeKit, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

๐Ÿ’€ Deprecated Variables

The following variables are provided for backward compatibility:

  • OSGSHADOW_FOUND โ€” Deprecated since version 4.2: use osgShadow_FOUND, which has the same value. Boolean indicating whether the osgShadow NodeKit of the OpenSceneGraph toolkit was found.
This one is also a legacy era relic ๐Ÿ˜ญ โ€” OSGSHADOW_FOUND is deprecated since version 4.2, so swap in osgShadow_FOUND. Same value, no drama.

๐Ÿ”ฅ Examples

Finding osgShadow explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target:

find_package(osgShadow)

if(osgShadow_FOUND AND NOT TARGET osgShadow::osgShadow)
  add_library(osgShadow::osgShadow INTERFACE IMPORTED)
  set_target_properties(
    osgShadow::osgShadow
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGSHADOW_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGSHADOW_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgShadow::osgShadow)

๐Ÿ‘€ See Also

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find OpenSceneGraph toolkit.

๐ŸŒˆ FindosgSim ๐ŸŒˆ

Finds the osgSim NodeKit from the OpenSceneGraph toolkit ๐Ÿ’–

Note: in most cases, it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgSim as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgSim)

This module is used internally by FindOpenSceneGraph <#module:FindOpenSceneGraph> to find the osgSim NodeKit. It is not intended to be included directly during typical use of the find_package() <#command:find_package> command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find the osgSim explicitly or bypass automatic component detection:

find_package(osgSim)

OpenSceneGraph and osgSim headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgSim/ImpostorSprite>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿซถ

โœจ Result Variables

This module defines the following variables:

  • osgSim_FOUND โ€” Added in version 3.3. Boolean indicating whether the osgSim NodeKit of the OpenSceneGraph toolkit was found.
  • OSGSIM_LIBRARIES โ€” The libraries needed to link against to use osgSim.
  • OSGSIM_LIBRARY โ€” A result variable that is set to the same value as the OSGSIM_LIBRARIES variable.

๐ŸŽ€ Cache Variables

The following cache variables may also be set:

  • OSGSIM_INCLUDE_DIR โ€” The include directory containing headers needed to use osgSim.
  • OSGSIM_LIBRARY_DEBUG โ€” The path to the osgSim debug library.

๐ŸŒธ Hints

This module accepts the following variables:

  • OSGDIR โ€” Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgSim NodeKit, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

๐Ÿ’€ Deprecated Variables

The following variables are provided for backward compatibility:

  • OSGSIM_FOUND โ€” Deprecated since version 4.2: use osgSim_FOUND, which has the same value. Boolean indicating whether the osgSim NodeKit of the OpenSceneGraph toolkit was found.
Not me having to say it again ๐Ÿ˜ญ โ€” OSGSIM_FOUND is deprecated since version 4.2, bestie. Use osgSim_FOUND, which has the same value.

๐Ÿ”ฅ Examples

Finding osgSim explicitly with this module and creating an interface imported target <#imported-targets> that encapsulates its usage requirements for linking it to a project target:

find_package(osgSim)

if(osgSim_FOUND AND NOT TARGET osgSim::osgSim)
  add_library(osgSim::osgSim INTERFACE IMPORTED)
  set_target_properties(
    osgSim::osgSim
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGSIM_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGSIM_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgSim::osgSim)

๐Ÿ‘€ See Also

  • The FindOpenSceneGraph <#module:FindOpenSceneGraph> module to find OpenSceneGraph toolkit.

๐Ÿงš FindosgTerrain ๐Ÿงš

Finds the osgTerrain NodeKit from the OpenSceneGraph toolkit โญ

Note: in most cases, it's recommended to use the FindOpenSceneGraph <#module:FindOpenSceneGraph> module instead and list osgTerrain as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgTerrain)

...so yeah, that's the whole "this is a standalone module for advanced use cases" thing. Continuing:

find_package(osgTerrain)

The OpenSceneGraph and osgTerrain headers are literally meant to be #included in your C++ source like this, bestie โ€” file example.cxx:

#include <osg/PositionAttitudeTransform>
#include <osgTerrain/Terrain>
// ...

And heads up ๐ŸŒธ โ€” when you're working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required. Not optional, not a vibe, just facts.

๐ŸŽ€ Result Variables ๐ŸŽ€

This module defines the following variables:

  • osgTerrain_FOUND โ€” added in version 3.3 โœจ Boolean indicating whether the osgTerrain NodeKit of the OpenSceneGraph toolkit was found.
  • OSGTERRAIN_LIBRARIES โ€” the libraries needed to link against to use osgTerrain.
  • OSGTERRAIN_LIBRARY โ€” a result variable that is set to the same value as the OSGTERRAIN_LIBRARIES variable.

๐Ÿงš Cache Variables ๐Ÿงš

The following cache variables may also be set:

  • OSGTERRAIN_INCLUDE_DIR โ€” the include directory containing headers needed to use osgTerrain.
  • OSGTERRAIN_LIBRARY_DEBUG โ€” the path to the osgTerrain debug library.

๐Ÿฆ‹ Hints ๐Ÿฆ‹

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgTerrain NodeKit, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

๐Ÿ’œ Deprecated Variables ๐Ÿ’œ

The following variables are provided for backward compatibility:

  • OSGTERRAIN_FOUND โ€” deprecated since version 4.2: use osgTerrain_FOUND, which has the same value. Boolean indicating whether the osgTerrain NodeKit of the OpenSceneGraph toolkit was found.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding osgTerrain explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target โ€” iconic, honestly:

find_package(osgTerrain)

if(osgTerrain_FOUND AND NOT TARGET osgTerrain::osgTerrain)
  add_library(osgTerrain::osgTerrain INTERFACE IMPORTED)
  set_target_properties(
    osgTerrain::osgTerrain
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGTERRAIN_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGTERRAIN_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgTerrain::osgTerrain)

๐Ÿ‘‘ See Also ๐Ÿ‘‘

  • The FindOpenSceneGraph module to find OpenSceneGraph toolkit.

๐Ÿฆ‹ FindosgText ๐Ÿฆ‹

Finds the osgText NodeKit from the OpenSceneGraph toolkit.

๐Ÿ’… Note: in most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgText as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgText)

This module is used internally by FindOpenSceneGraph to find the osgText NodeKit. It is not intended to be included directly during typical use of the find_package() command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed. Like, for example, to find the osgText explicitly or bypass automatic component detection:

find_package(osgText)

The OpenSceneGraph and osgText headers are intended to be included in C++ project source code as โ€” file example.cxx:

#include <osg/PositionAttitudeTransform>
#include <osgText/Text>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

๐ŸŽ€ Result Variables ๐ŸŽ€

This module defines the following variables:

  • osgText_FOUND โ€” added in version 3.3 โœจ Boolean indicating whether the osgText NodeKit of the OpenSceneGraph toolkit was found.
  • OSGTEXT_LIBRARIES โ€” the libraries needed to link against to use osgText.
  • OSGTEXT_LIBRARY โ€” a result variable that is set to the same value as the OSGTEXT_LIBRARIES variable.

๐Ÿงš Cache Variables ๐Ÿงš

The following cache variables may also be set:

  • OSGTEXT_INCLUDE_DIR โ€” the include directory containing headers needed to use osgText.
  • OSGTEXT_LIBRARY_DEBUG โ€” the path to the osgText debug library.

๐Ÿฆ‹ Hints ๐Ÿฆ‹

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgText NodeKit, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

๐Ÿ’œ Deprecated Variables ๐Ÿ’œ

The following variables are provided for backward compatibility:

  • OSGTEXT_FOUND โ€” deprecated since version 4.2: use osgText_FOUND, which has the same value. Boolean indicating whether the osgText NodeKit of the OpenSceneGraph toolkit was found.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding osgText explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target โ€” slay:

find_package(osgText)

if(osgText_FOUND AND NOT TARGET osgText::osgText)
  add_library(osgText::osgText INTERFACE IMPORTED)
  set_target_properties(
    osgText::osgText
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGTEXT_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGTEXT_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgText::osgText)

๐Ÿ‘‘ See Also ๐Ÿ‘‘

  • The FindOpenSceneGraph module to find OpenSceneGraph toolkit.

๐Ÿซถ FindosgUtil ๐Ÿซถ

Finds the osgUtil library from the OpenSceneGraph toolkit.

๐Ÿ’… Note: in most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgUtil as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgUtil)

This module is used internally by FindOpenSceneGraph to find the osgUtil library. It is not intended to be included directly during typical use of the find_package() command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find the osgUtil explicitly or bypass automatic component detection:

find_package(osgUtil)

The OpenSceneGraph and osgUtil headers are intended to be included in C++ project source code as โ€” file example.cxx:

#include <osg/PositionAttitudeTransform>
#include <osgUtil/SceneView>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

๐ŸŽ€ Result Variables ๐ŸŽ€

This module defines the following variables:

  • osgUtil_FOUND โ€” added in version 3.3 โœจ Boolean indicating whether the osgUtil library of the OpenSceneGraph toolkit was found.
  • OSGUTIL_LIBRARIES โ€” the libraries needed to link against to use osgUtil.
  • OSGUTIL_LIBRARY โ€” a result variable that is set to the same value as the OSGUTIL_LIBRARIES variable.

๐Ÿงš Cache Variables ๐Ÿงš

The following cache variables may also be set:

  • OSGUTIL_INCLUDE_DIR โ€” the include directory containing headers needed to use osgUtil.
  • OSGUTIL_LIBRARY_DEBUG โ€” the path to the osgUtil debug library.

๐Ÿฆ‹ Hints ๐Ÿฆ‹

This module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgUtil library, when installed in a custom location. It should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: ./configure --prefix=$OSGDIR.

๐Ÿ’œ Deprecated Variables ๐Ÿ’œ

The following variables are provided for backward compatibility:

  • OSGUTIL_FOUND โ€” deprecated since version 4.2: use osgUtil_FOUND, which has the same value. Boolean indicating whether the osgUtil library of the OpenSceneGraph toolkit was found.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding osgUtil explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target โ€” no cap, this is the move:

find_package(osgUtil)

if(osgUtil_FOUND AND NOT TARGET osgUtil::osgUtil)
  add_library(osgUtil::osgUtil INTERFACE IMPORTED)
  set_target_properties(
    osgUtil::osgUtil
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGUTIL_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGUTIL_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgUtil::osgUtil)

๐Ÿ‘‘ See Also ๐Ÿ‘‘

  • The FindOpenSceneGraph module to find OpenSceneGraph toolkit.

โญ FindosgViewer โญ

Finds the osgViewer library from the OpenSceneGraph toolkit.

๐Ÿ’… Note: in most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgViewer as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgViewer)

This module is used internally by FindOpenSceneGraph to find the osgViewer library. It is not intended to be included directly during typical use of the find_package() command. However, it is available as a standalone module for advanced use cases where finer control over detection is needed. For example, to find the osgViewer explicitly or bypass automatic component detection:

find_package(osgViewer)

The OpenSceneGraph and osgViewer headers are intended to be included in C++ project source code as โ€” file example.cxx:

#include <osg/PositionAttitudeTransform>
#include <osgViewer/Viewer>
// ...

When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

๐ŸŽ€ Result Variables ๐ŸŽ€

This module defines the following variables:

  • osgViewer_FOUND โ€” added in version 3.3 โœจ boolean bestie, tells you if the osgViewer library from the OpenSceneGraph toolkit was actually found. yep or nope, that's it ๐Ÿ’…
  • OSGVIEWER_LIBRARIES โ€” the libraries you gotta link against to use osgViewer. no cap ๐Ÿซถ
  • OSGVIEWER_LIBRARY โ€” a result variable that's set to the exact same value as the OSGVIEWER_LIBRARIES variable. literally twins ๐Ÿ‘ฏ

๐ŸŽ€ Cache Variables ๐ŸŽ€

the following cache variables may also be set, bestie:

  • OSGVIEWER_INCLUDE_DIR โ€” the include directory holding the headers you need to use osgViewer ๐Ÿ“
  • OSGVIEWER_LIBRARY_DEBUG โ€” the path to the osgViewer debug library ๐Ÿ›

๐ŸŒธ Hints ๐ŸŒธ

this module accepts the following variables:

  • OSGDIR โ€” an environment variable you can set to help locate the OpenSceneGraph toolkit (including its osgViewer library) when it's installed in a custom location ๐Ÿ’ซ it should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed: . /configure --prefix=$OSGDIR. ok the exact thing is:
./configure --prefix=$OSGDIR

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

the following variables are provided for backward compatibility, iykyk:

  • OSGVIEWER_FOUND โ€” deprecated since version 4.2: use osgViewer_FOUND, which has the same value.

boolean indicating whether the osgViewer library of the OpenSceneGraph toolkit was found. (yes it's literally the same thing, that's the whole point of the rename ๐Ÿ™ˆ)

๐Ÿ”ฅ Examples ๐Ÿ”ฅ

finding osgViewer explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target โ€” main character energy fr:

find_package(osgViewer)

if(osgViewer_FOUND AND NOT TARGET osgViewer::osgViewer)
  add_library(osgViewer::osgViewer INTERFACE IMPORTED)
  set_target_properties(
    osgViewer::osgViewer
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGVIEWER_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGVIEWER_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgViewer::osgViewer)

โญ See Also โญ

  • the FindOpenSceneGraph module to find the OpenSceneGraph toolkit ๐Ÿ‘‘

๐Ÿฆ‹ FindosgVolume ๐Ÿฆ‹

finds the osgVolume NodeKit from the OpenSceneGraph toolkit. slay ๐Ÿ’œ

Note: in most cases it's recommended to use the FindOpenSceneGraph module instead and list osgVolume as a component. this will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgVolume)

this module is used internally by FindOpenSceneGraph to find the osgVolume NodeKit. it is not intended to be included directly during typical use of the find_package() command ๐Ÿซฃ however, it is available as a standalone module for advanced use cases where finer control over detection is needed. for example, to find the osgVolume explicitly or bypass automatic component detection:

find_package(osgVolume)

OpenSceneGraph and osgVolume headers are intended to be included in C++ project source code as โ€” in example.cxx:

#include <osg/PositionAttitudeTransform>
#include <osgVolume/Volume>
// ...

when working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿ‘€

๐Ÿ“ฆ Result Variables ๐Ÿ“ฆ

this module defines the following variables:

  • osgVolume_FOUND โ€” added in version 3.3. โœจ boolean indicating whether the osgVolume NodeKit of the OpenSceneGraph toolkit was found.
  • OSGVOLUME_LIBRARIES โ€” the libraries needed to link against to use osgVolume.
  • OSGVOLUME_LIBRARY โ€” a result variable that is set to the same value as the OSGVOLUME_LIBRARIES variable. matching, as always ๐Ÿ’…

๐ŸŽ€ Cache Variables ๐ŸŽ€

the following cache variables may also be set:

  • OSGVOLUME_INCLUDE_DIR โ€” the include directory containing headers needed to use osgVolume.
  • OSGVOLUME_LIBRARY_DEBUG โ€” the path to the osgVolume debug library ๐Ÿ›

๐ŸŒธ Hints ๐ŸŒธ

this module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgVolume NodeKit, when installed in a custom location. it should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed:
./configure --prefix=$OSGDIR

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

the following variables are provided for backward compatibility:

  • OSGVOLUME_FOUND โ€” deprecated since version 4.2: use osgVolume_FOUND, which has the same value.

boolean indicating whether the osgVolume NodeKit of the OpenSceneGraph toolkit was found. same value, new name, iconic โœจ

๐Ÿ”ฅ Examples ๐Ÿ”ฅ

finding osgVolume explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

find_package(osgVolume)

if(osgVolume_FOUND AND NOT TARGET osgVolume::osgVolume)
  add_library(osgVolume::osgVolume INTERFACE IMPORTED)
  set_target_properties(
    osgVolume::osgVolume
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGVOLUME_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGVOLUME_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgVolume::osgVolume)

โญ See Also โญ

  • the FindOpenSceneGraph module to find the OpenSceneGraph toolkit ๐Ÿซถ

๐ŸŒˆ FindosgWidget ๐ŸŒˆ

finds the osgWidget NodeKit from the OpenSceneGraph toolkit ๐Ÿ’–

Note: in most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgWidget as a component. this will automatically handle dependencies such as the OpenThreads and core osg libraries:
find_package(OpenSceneGraph COMPONENTS osgWidget)

this module is used internally by FindOpenSceneGraph to find the osgWidget NodeKit. it is not intended to be included directly during typical use of the find_package() command ๐Ÿ™ˆ however, it is available as a standalone module for advanced use cases where finer control over detection is needed. for example, to find the osgWidget explicitly or bypass automatic component detection:

find_package(osgWidget)

OpenSceneGraph and osgWidget headers are intended to be included in C++ project source code as โ€” in example.cxx:

#include <osg/PositionAttitudeTransform>
#include <osgWidget/Widget>
// ...

when working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required ๐Ÿ‘‘

๐Ÿ“ฆ Result Variables ๐Ÿ“ฆ

this module defines the following variables:

  • osgWidget_FOUND โ€” added in version 3.3. โœจ boolean indicating whether the osgWidget NodeKit of the OpenSceneGraph toolkit was found.
  • OSGWIDGET_LIBRARIES โ€” the libraries needed to link against to use osgWidget.
  • OSGWIDGET_LIBRARY โ€” a result variable that is set to the same value as the OSGWIDGET_LIBRARIES variable. slay ๐Ÿซถ

๐ŸŽ€ Cache Variables ๐ŸŽ€

the following cache variables may also be set:

  • OSGWIDGET_INCLUDE_DIR โ€” the include directory containing headers needed to use osgWidget.
  • OSGWIDGET_LIBRARY_DEBUG โ€” the path to the osgWidget debug library ๐Ÿ›

๐ŸŒธ Hints ๐ŸŒธ

this module accepts the following variables:

  • OSGDIR โ€” environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgWidget NodeKit, when installed in a custom location. it should point to the OpenSceneGraph installation prefix used when it was configured, built, and installed:
./configure --prefix=$OSGDIR

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

the following variables are provided for backward compatibility:

  • OSGWIDGET_FOUND โ€” deprecated since version 4.2: use osgWidget_FOUND, which has the same value.

boolean indicating whether the osgWidget NodeKit of the OpenSceneGraph toolkit was found. same energy, different casing ๐Ÿ’…

๐Ÿ”ฅ Examples ๐Ÿ”ฅ

finding osgWidget explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

find_package(osgWidget)

if(osgWidget_FOUND AND NOT TARGET osgWidget::osgWidget)
  add_library(osgWidget::osgWidget INTERFACE IMPORTED)
  set_target_properties(
    osgWidget::osgWidget
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${OSGWIDGET_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${OSGWIDGET_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE osgWidget::osgWidget)

โญ See Also โญ

  • the FindOpenSceneGraph module to find the OpenSceneGraph toolkit ๐ŸŒŸ

๐Ÿงš FindPatch ๐Ÿงš

added in version 3.10.

finds the patch command-line executable for applying diff patches to original files, bestie:

find_package(Patch [...])

๐Ÿ‘‘ Imported Targets ๐Ÿ‘‘

this module provides the following Imported Targets:

  • Patch::patch โ€” target encapsulating the patch command-line executable, available only if patch is found.

changed in version 4.0: this imported target is defined only when CMAKE_ROLE is PROJECT ๐Ÿซก

๐Ÿ“ฆ Result Variables ๐Ÿ“ฆ

this module defines the following variables:

  • Patch_FOUND โ€” boolean indicating whether the patch command-line executable was found. found it or didn't, simple as that โœจ

๐ŸŽ€ Cache Variables ๐ŸŽ€

the following cache variables may also be set:

  • Patch_EXECUTABLE โ€” the path to the patch command-line executable ๐Ÿ› ๏ธ

๐Ÿ”ฅ Examples ๐Ÿ”ฅ

finding the patch command and executing it in a process:

find_package(Patch)
if(Patch_FOUND)
  execute_process(
    COMMAND ${Patch_EXECUTABLE} -p1 -i ${CMAKE_CURRENT_SOURCE_DIR}/src.patch
  )
endif()

the imported target can be used, for example, inside the add_custom_command() command, which patches the given file when some build rule depends on its output:

find_package(Patch)
if(TARGET Patch::patch)
  # Executed when some build rule depends on the src.c file.
  add_custom_command(
    OUTPUT src.c
    COMMAND Patch::patch -p1 -i ${CMAKE_CURRENT_SOURCE_DIR}/src.patch
    # ...
  )
endif()

๐Ÿ“ FindPerl ๐Ÿ“

finds a Perl interpreter, no cap:

find_package(Perl [<version>] [...])

Perl is a general-purpose, interpreted, dynamic programming language ๐Ÿ’œ (yes the camel one, iconic)

๐Ÿ“ฆ Result Variables ๐Ÿ“ฆ

this module defines the following variables:

  • Perl_FOUND โ€” added in version 3.3. boolean indicating whether the (requested version of the) Perl executable was found. like, the version you asked for specifically ๐Ÿ‘€
  • Perl_VERSION โ€” added in version 4.2. the version of Perl found ๐ŸŒธ

๐ŸŽ€ Cache Variables ๐ŸŽ€

the following cache variables may also be set:

  • PERL_EXECUTABLE โ€” full path to the perl executable. the whole path. no crumbs. ๐Ÿ’…

๐Ÿซถ Deprecated Variables

these ones are still here for the back-compat girlies, but likeโ€ฆ they're on their way out:

  • PERL_FOUND โ€” Deprecated since version 4.2: use Perl_FOUND instead, it has the same value, no cap. it's a Boolean that says whether the (requested version of) Perl executable was found.
  • PERL_VERSION_STRING โ€” Deprecated since version 4.2: superseded by Perl_VERSION. it's the version of Perl that got found.

๐ŸŒธ Examples

finding the Perl interpreter and executing it in a process, iconic:

find_package(Perl)

if(Perl_FOUND)
  execute_process(COMMAND ${PERL_EXECUTABLE} --help)
endif()

๐Ÿฆ‹ See Also

  • the FindPerlLibs <#module:FindPerlLibs> module, for when you need the Perl libraries too ๐Ÿซถ

๐ŸŽ€ FindPerlLibs

finds Perl libraries, bestie:

find_package(PerlLibs [<version>] [...])

Perl is a general-purpose, interpreted, dynamic programming language.

this module detects whether the Perl interpreter is installed via the FindPerl <#module:FindPerl> module, and then it figures out the locations of the Perl include paths, the libraries, and the library name. literally does the whole scavenger hunt for you โœจ

๐Ÿ’– Result Variables

this module defines the following variables:

  • PerlLibs_FOUND โ€” Added in version 3.3. Boolean telling you whether (the requested version of) <perl.h> and libperl were found.
  • PerlLibs_VERSION โ€” Added in version 4.2. the version of the Perl library that was found.
  • PERL_SITESEARCH โ€” path to the sitesearch install directory (-V:installsitesearch).
  • PERL_SITEARCH โ€” path to the sitelib install directory (-V:installsitearch).
  • PERL_SITELIB โ€” path to the sitelib install directory (-V:installsitelib).
  • PERL_VENDORARCH โ€” path to the vendor arch install directory (-V:installvendorarch).
  • PERL_VENDORLIB โ€” path to the vendor lib install directory (-V:installvendorlib).
  • PERL_ARCHLIB โ€” path to the core arch lib install directory (-V:archlib).
  • PERL_PRIVLIB โ€” path to the core priv lib install directory (-V:privlib).
  • PERL_UPDATE_ARCHLIB โ€” path to the update arch lib install directory (-V:installarchlib).
  • PERL_UPDATE_PRIVLIB โ€” path to the update priv lib install directory (-V:installprivlib).
  • PERL_EXTRA_C_FLAGS โ€” the compilation flags used to build Perl. ๐Ÿ› ๏ธ

๐ŸŒˆ Cache Variables

these cache variables may also get set:

  • PERL_INCLUDE_PATH โ€” the directory containing perl.h and the other Perl header files.
  • PERL_LIBRARY โ€” path to the libperl.
  • PERL_EXECUTABLE โ€” full path to the perl executable.

๐Ÿ™ˆ Deprecated Variables

provided for backward compatibility, we keep them around like that one ex you're still mutuals with:

  • PERLLIBS_FOUND โ€” Deprecated since version 4.2: use PerlLibs_FOUND instead, which has the same value. Boolean indicating whether (the requested version of) <perl.h> and libperl were found.

๐Ÿ“ Examples

finding Perl libraries and specifying the minimum required version, slay:

find_package(PerlLibs 6.0)

๐Ÿ‘‘ See Also

  • the FindPerl <#module:FindPerl> module, for finding the Perl interpreter itself ๐Ÿซถ

๐Ÿ’œ FindPHP4

finds PHP version 4, the general-purpose scripting language:

find_package(PHP4 [...])
โš ๏ธ Note: this module is specifically for PHP version 4, which is obsolete and no longer supported. for modern development, use a newer PHP version please bestie, i'm begging ๐Ÿ˜ญ

this module checks if PHP 4 is installed and determines the locations of the include directories and the PHP command-line interpreter.

โœจ Result Variables

this module defines the following variables:

  • PHP4_FOUND โ€” Boolean indicating whether PHP 4 was found.

๐ŸŒธ Cache Variables

these cache variables may also get set:

  • PHP4_INCLUDE_PATH โ€” the directory containing php.h and the other headers you need to use PHP.
  • PHP4_EXECUTABLE โ€” the full path to the php command-line interpreter executable.

๐ŸŽ€ Examples

finding PHP:

find_package(PHP4)

๐Ÿฆ‹ FindPhysFS

finds the PhysicsFS library (PhysFS) โ€” it's the file I/O abstraction one ๐Ÿ—‚๏ธ

find_package(PhysFS [...])

๐Ÿ’– Result Variables

this module defines the following variables:

  • PhysFS_FOUND โ€” Added in version 3.3. Boolean indicating whether the PhysicsFS library was found.

๐Ÿ”ฅ Cache Variables

these cache variables may also get set:

  • PHYSFS_INCLUDE_DIR โ€” directory containing the <physfs.h> and related headers you need for using the library.
  • PHYSFS_LIBRARY โ€” path to the PhysicsFS library you need to link against.

๐Ÿงš Hints

this module accepts the following variables:

  • PHYSFSDIR โ€” an environment variable you can set to help locate a PhysicsFS library installed in a custom location. it should point to the installation destination that was used when configuring, building, and installing the PhysicsFS library: ./configure --prefix=$PHYSFSDIR.

๐Ÿ’€ Deprecated Variables

provided for backward compatibility:

  • PHYSFS_FOUND โ€” Deprecated since version 4.2: use the PhysFS_FOUND, which has the same value. Boolean indicating whether the PhysicsFS library was found.

โญ Examples

finding the PhysicsFS library:

find_package(PhysFS)

๐ŸŒˆ FindPike

finds the Pike compiler and interpreter:

find_package(Pike [...])

Pike is an interpreted, general purpose, high-level, dynamic programming language.

๐Ÿซถ Result Variables

this module defines the following variables:

  • Pike_FOUND โ€” Added in version 4.2. Boolean indicating whether Pike was found.

๐ŸŽ€ Cache Variables

these cache variables may also get set:

  • PIKE_INCLUDE_PATH โ€” the directory containing program.h.
  • PIKE_EXECUTABLE โ€” full path to the pike binary.

๐Ÿ“ Examples

finding Pike:

find_package(Pike)

๐Ÿ‘‘ FindPkgConfig

a pkg-config module for CMake. okay this one's kind of the main character ngl ๐Ÿ’…

it finds the pkg-config executable and hands you commands to actually use it in CMake:

find_package(PkgConfig [<version>] [QUIET] [REQUIRED] [...])

pkg-config is a command-line program for configuring build dependency information. initially developed by FreeDesktop, it's also available in several implementations, like pkgconf, u-config, and similar ones. it reads package data from the so-called PC metadata files (<module-name>.pc) that may come installed with packages. this module is a wrapper around the pkg-config command-line executable. ๐Ÿซถ

โœจ Result Variables

this module defines the following variables:

  • PkgConfig_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) pkg-config executable was found.
  • PkgConfig_VERSION โ€” Added in version 4.2. the version of pkg-config that was found.
  • PKG_CONFIG_EXECUTABLE โ€” the pathname of the pkg-config program.
  • PKG_CONFIG_ARGN โ€” Added in version 3.22. a list of arguments to pass to pkg-config.

both PKG_CONFIG_EXECUTABLE and PKG_CONFIG_ARGN are initialized by the module, but they may be overridden by the user. see Hints for how these variables get initialized ๐Ÿ‘€

๐ŸŒธ Commands

this module provides the following commands, if pkg-config is found:

  • pkg_check_modules()
  • pkg_search_module()
  • pkg_get_variable()

๐Ÿ’– pkg_check_modules

checks for all the given modules, and sets a whole variety of result variables in the calling scope:

pkg_check_modules(
  <prefix>
  [QUIET]
  [REQUIRED]
  [NO_CMAKE_PATH]
  [NO_CMAKE_ENVIRONMENT_PATH]
  [IMPORTED_TARGET [GLOBAL]]
  <module-spec> [<module-spec>...]
)

the arguments are:

  • <prefix> โ€” a prefix string that gets prepended to the result variables for the specified modules.
  • QUIET โ€” when this argument is given, no status messages will be printed. shhh ๐Ÿคซ
  • REQUIRED โ€” when this argument is given, the command fails with an error if any of the specified module(s) could not be found. no silent failures here bestie.
  • NO_CMAKE_PATH, NO_CMAKE_ENVIRONMENT_PATH โ€” Added in version 3.3. so normally the CMAKE_PREFIX_PATH <#variable:CMAKE_PREFIX_PATH>, CMAKE_FRAMEWORK_PATH <#variable:CMAKE_FRAMEWORK_PATH>, and CMAKE_APPBUNDLE_PATH <#variable:CMAKE_APPBUNDLE_PATH> cache and environment variables get added to the pkg-config search path. the NO_CMAKE_PATH and NO_CMAKE_ENVIRONMENT_PATH arguments disable this behavior for the cache variables and the environment variables respectively. and setting the PKG_CONFIG_USE_CMAKE_PREFIX_PATH variable to FALSE disables this behavior globally. ๐Ÿšซ
  • IMPORTED_TARGET [GLOBAL] โ€” Added in version 3.7. this argument creates an imported target <#imported-targets> named PkgConfig::<prefix> that you can pass directly as an argument to target_link_libraries() <#command:target_link_libraries>. it encapsulates the usage requirements for all the specified modules <module-spec>... at once. โœจ
    • GLOBAL โ€” Added in version 3.13. this argument is used together with IMPORTED_TARGET and makes the imported target available in global scope.
    • Added in version 3.15: non-library linker options reported by pkg-config are stored in the INTERFACE_LINK_OPTIONS <#prop_tgt:INTERFACE_LINK_OPTIONS> target property.
    • Changed in version 3.18: include directories specified with -isystem are stored in the INTERFACE_INCLUDE_DIRECTORIES <#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES> target property. previous versions of CMake left them in the INTERFACE_COMPILE_OPTIONS <#prop_tgt:INTERFACE_COMPILE_OPTIONS> property.
  • <module-spec> โ€” each <module-spec> can be either a bare module name (as defined in its PC metadata file name <module-name>.pc), or a module name with a version constraint (the operators =, <, >, <= and >= are supported). here are the examples for a module named foo with various constraints:
    • foo matches any version.
    • foo<2 only matches versions before 2.
    • foo>=3.1 matches any version from 3.1 or later.
    • foo=1.2.3 requires that foo must be exactly version 1.2.3.

โœจ Result Variables โœจ

Okay so when the call comes back, these variables might get set ๐Ÿ’–. There are two whole sets of them, bestie: one for the normal everyday case where <XXX> = <prefix>, and another one for the info pkg-config hands over when you call it with the --static option, where <XXX> = <prefix>_STATIC. Two flavors, same energy ๐Ÿ“.

  • <XXX>_FOUND โ€” a Boolean variable, set to 1 if the module(s) actually exist. Literally the vibe check of the whole operation ๐Ÿ’…
  • <XXX>_LIBRARIES โ€” a list of only the libraries, with the -l stripped off, no cap.
  • <XXX>_LINK_LIBRARIES โ€” the libraries and their absolute paths. Glow-up version of the above โœจ
  • <XXX>_LIBRARY_DIRS โ€” the paths of the libraries, -L removed, we don't need it.
  • <XXX>_LDFLAGS โ€” all the required linker flags, the whole set.
  • <XXX>_LDFLAGS_OTHER โ€” all the other linker flags. The leftovers, but make it fashion ๐ŸŽ€
  • <XXX>_INCLUDE_DIRS โ€” the -I preprocessor flags, with the -I taken out.
  • <XXX>_CFLAGS โ€” all required cflags, every last one.
  • <XXX>_CFLAGS_OTHER โ€” the other compiler flags. Yes queen, the extras ๐Ÿ’œ

Everyone except <XXX>_FOUND may turn into a semicolon-separated list (cmake-language-lists) if the associated variable that came back from pkg-config has multiple values. So don't be shocked when it's a list, it's giving "many values" energy ๐ŸŒˆ.

Changed in version 3.18: include directories that are specified with -isystem now get stored in the <XXX>_INCLUDE_DIRS variable. Previous versions of CMake just left them chillin' in <XXX>_CFLAGS_OTHER. Glow-up for real ๐Ÿฆ‹

Also there are some special variables whose prefix depends on how many <module-spec> you fed in ๐Ÿ‘€. When there's only one <module-spec>, <YYY> is simply <prefix>, but if you give two or more <module-spec> items, <YYY> becomes <prefix>_<module-name>. Math! But cute math ๐Ÿงš

  • <YYY>_VERSION โ€” the version of the module, iconic.
  • <YYY>_PREFIX โ€” the prefix directory of the module.
  • <YYY>_INCLUDEDIR โ€” the include directory of the module.
  • <YYY>_LIBDIR โ€” the lib directory of the module.
Changed in version 3.8: for any given <prefix>, pkg_check_modules() can be called multiple times with different parameters ๐Ÿ’€. Previous versions of CMake cached the first successful result and just kept returning that one โ€” not anymore, bestie.
Changed in version 3.16: if a full path to the found library can't be determined but it's still visible to the linker, it gets passed through as -l<name>. Previous versions of CMake just failed in that case ๐Ÿ˜ญ. We don't do that anymore.

๐ŸŒธ pkg_search_module ๐ŸŒธ

This one searches for the first successful match out of one or more module specifications you hand it. First one to hit, wins ๐Ÿ†:

pkg_search_module(
  <prefix>
  [QUIET]
  [REQUIRED]
  [NO_CMAKE_PATH]
  [NO_CMAKE_ENVIRONMENT_PATH]
  [IMPORTED_TARGET [GLOBAL]]
  <module-spec> [<module-spec>...]
)

The behavior and arguments are literally the same as pkg_check_modules(), except instead of checking for all the specified modules, it searches for just the first successful match. That's the whole twist ๐Ÿ”ฅ.

Use this when some package is known to possibly have multiple <module-spec> across different platforms or versions for the same package. iykyk ๐Ÿ’ซ

Result Variables

This command defines all the same variables as described above, plus:

  • <prefix>_MODULE_NAME
Added in version 3.16: if a module is found, the <prefix>_MODULE_NAME variable will contain the name of the matching module ๐Ÿ‘‘. Super useful if the pkg_get_variable() command needs to be called with the <module-name> argument that was found by pkg_search_module(). Chain them together, bestie ๐Ÿซถ

๐Ÿฆ‹ pkg_get_variable ๐Ÿฆ‹

Added in version 3.4: retrieves the value of a pkg-config variable and stores it in the result variable in the calling scope:
pkg_get_variable(
  <result-var>
  <module-name>
  <var-name>
  [DEFINE_VARIABLES <key>=<value>...]
)

The arguments, one by one ๐Ÿ’…:

  • <result-var> โ€” name of the result variable that will contain the value of the pkg-config variable. If pkg-config returns multiple values for the specified variable <var-name>, then <result-var> will contain a semicolon-separated list (cmake-language-lists). Surprise! It's a list ๐ŸŒˆ
  • <module-name> โ€” name of the module as defined in its PC metadata file name, i.e. <module-name>.pc.
  • <var-name> โ€” the pkg-config variable name from the PC metadata file <module-name>.pc.
  • DEFINE_VARIABLES <key>=<value>...
Added in version 3.28: specify key-value pairs to redefine variables affecting the variable retrieved with pkg-config ๐ŸŽ€

โญ Hints โญ

This module accepts the following variables before calling find_package(PkgConfig) to influence how it behaves. Set them first, then call, that's the order bestie ๐Ÿซถ:

  • ENV{PKG_CONFIG_PATH} โ€” environment variable that specifies additional paths where pkg-config will search for its .pc files. The pkg-config tool by default uses this variable, while CMake also provides the more common CMAKE_PREFIX_PATH variable to specify additional paths where to look for packages and their .pc files โœจ.
  • ENV{PKG_CONFIG}
Added in version 3.1: environment variable that can be set to the path of the pkg-config executable, and can be used to initialize the PKG_CONFIG_EXECUTABLE variable, if it has not yet been set ๐Ÿ’–.

PKG_CONFIG_EXECUTABLE

This cache variable can be set to the path of the pkg-config executable. find_program() is called internally by the module with this variable.

Changed in version 3.22: if the PKG_CONFIG environment variable is set, only the first argument is taken from it when using it as a hint. Just the first one, bestie ๐Ÿ‘€

PKG_CONFIG_ARGN

Added in version 3.22: this cache variable can be set to a list of arguments to additionally pass to pkg-config if needed. If it's not provided, it gets initialized from the PKG_CONFIG environment variable, if that's set. The first argument in that environment variable is assumed to be the pkg-config program, while all remaining arguments after that are used to initialize PKG_CONFIG_ARGN. If no such environment variable is defined, PKG_CONFIG_ARGN is initialized to an empty string. The module does not update the variable once it has been set in the cache โ€” so once it's in there, it's staying, periodt ๐Ÿ’…

PKG_CONFIG_USE_CMAKE_PREFIX_PATH

Added in version 3.1: specifies whether pkg_check_modules() and pkg_search_module() should add the paths in the CMAKE_PREFIX_PATH, CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH cache and environment variables to the pkg-config search path ๐Ÿ‘‘

If this variable is not set, this behavior is enabled by default if CMAKE_MINIMUM_REQUIRED_VERSION is 3.1 or later, and disabled otherwise. So it depends on your minimum version, no cap ๐ŸŒธ


๐Ÿ’€ Deprecated Variables ๐Ÿ’€

The following variables are provided for backward compatibility. They still work, but like, they're vintage now ๐Ÿ™ˆ:

  • PKG_CONFIG_FOUND
Deprecated since version 4.2: use PkgConfig_FOUND, which has the same value.

Boolean indicating whether the (requested version of) pkg-config executable was found.

  • PKG_CONFIG_VERSION_STRING
Deprecated since version 4.2: use PkgConfig_VERSION, which has the same value.

The version of pkg-config that was found.


๐ŸŽ€ Examples ๐ŸŽ€

Examples: Finding pkg-config

Finding pkg-config, the basic slay:

find_package(PkgConfig)

Finding pkg-config and making it required โ€” if it's not found, processing stops with an error message ๐Ÿ˜ญ:

find_package(PkgConfig REQUIRED)

Finding pkg-config quietly without printing a status message, as commonly used in find modules ๐Ÿคซ:

find_package(PkgConfig QUIET)

Examples: Using pkg_check_modules()

Checking for any version of glib2. If found, the output variable GLIB2_VERSION will hold the actual version found โœจ:

find_package(PkgConfig QUIET)

if(PkgConfig_FOUND)
  pkg_check_modules(GLIB2 glib-2.0)
endif()

The following example looks for at least version 2.10 of glib2. If found, the output variable GLIB2_VERSION will hold the actual version found ๐Ÿ’–:

find_package(PkgConfig QUIET)

if(PkgConfig_FOUND)
  pkg_check_modules(GLIB2 glib-2.0>=2.10)
endif()

The following example looks for both glib2-2.0 (at least version 2.10) and any version of gtk2+-2.0. Only if both are found will FOO be considered found โ€” it's an all-or-nothing situation bestie ๐Ÿซถ. The FOO_glib-2.0_VERSION and FOO_gtk+-2.0_VERSION variables will be set to their respective found module versions ๐Ÿ‘‘

find_package(PkgConfig QUIET)

if(PkgConfig_FOUND)
  pkg_check_modules(FOO glib-2.0>=2.10 gtk+-2.0)
endif()

The following example requires any version of xrender, no negotiations ๐Ÿ”ฅ:

find_package(PkgConfig QUIET REQUIRED)
pkg_check_modules(XRENDER REQUIRED xrender)

Example output variables set by a successful call:

XRENDER_LIBRARIES=Xrender;X11
XRENDER_STATIC_LIBRARIES=Xrender;X11;pthread;Xau;Xdmcp

Example: Using pkg_search_module()

Searching for the LibXml2 package, which might be provided with different module specifications (libxml-2.0 or libxml2) ๐Ÿ’ซ:

find_package(PkgConfig QUIET)

if(PkgConfig_FOUND)
  pkg_search_module(BAR libxml-2.0 libxml2 libxml>=2)
endif()

Example: Creating Imported Target

In the following example an imported target is created from the module specifications so you can use it in the project directly without using a find module ๐ŸŽ€. These imported targets can be used, for example, in cases where the package is known to support pkg-config on all supported platforms:

find_package(PkgConfig QUIET REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk4>=4.14)
target_link_libraries(example PRIVATE PkgConfig::GTK)

Example: Using pkg_get_variable()

Retrieving the value of the pkg-config variable girdir from the package Gobject ๐ŸŒธ:

find_package(PkgConfig QUIET)

if(PkgConfig_FOUND)
  pkg_get_variable(GI_GIRDIR gobject-introspection-1.0 girdir)
endif()

message(STATUS "${GI_GIRDIR}")

๐Ÿ” See Also ๐Ÿ”

  • The cmake_pkg_config() command for a modern and more advanced way to work with pkg-config in CMake without requiring the pkg-config executable to be installed ๐Ÿ‘‘. Literally the upgrade arc.
  • Find Modules for details on how to write a find module ๐Ÿงš. Go write your own, bestie, you got this ๐Ÿ’œ

๐Ÿ–ผ๏ธ FindPNG

okay so this one finds libpng โ€” the official reference library for the PNG image format ๐Ÿ’–:

find_package(PNG [<version>] [...])
Note: the PNG library depends on the ZLib compression library, and ZLib must be found for this module to succeed. no ZLib, no PNG, no exceptions bestie ๐Ÿ˜ญ

Imported Targets

here's the imported target <#imported-targets> it gives you:

  • PNG::PNG โ€” Added in version 3.5. the icon โœจ this target encapsulates the libpng library usage requirements, and it's available if libpng is found.

Result Variables

these lil cuties get defined:

  • PNG_FOUND โ€” boolean saying whether the (requested version of the) PNG library was found ๐Ÿ‘‘
  • PNG_VERSION โ€” Added in version 4.2. the version of the PNG library that was found.
  • PNG_INCLUDE_DIRS โ€” the directory containing the PNG headers (e.g., png.h).
  • PNG_LIBRARIES โ€” PNG libraries required for linking.
  • PNG_DEFINITIONS โ€” compile definitions for using PNG, if any. you can add them with the target_compile_definitions() <#command:target_compile_definitions> command when you're not using the PNG::PNG imported target ๐Ÿซถ

Deprecated Variables

these may also get set for backward compatibility (read: old vibes, still functional):

  • PNG_LIBRARY โ€” Deprecated since version 3.0: Use the PNG::PNG imported target. path to the PNG library.
  • PNG_INCLUDE_DIR โ€” Deprecated since version 3.0: Use the PNG::PNG imported target. directory containing the PNG headers (same as PNG_INCLUDE_DIRS).
  • PNG_VERSION_STRING โ€” Deprecated since version 4.2: Superseded by the PNG_VERSION. the version of the PNG library found.

Examples

finding PNG and actually using it in a project, slay:

find_package(PNG)
target_link_libraries(project_target PRIVATE PNG::PNG)

๐Ÿ˜ FindPostgreSQL

this one finds your PostgreSQL installation โ€” the client library (libpq) and optionally the server ๐Ÿฆ‹:

find_package(PostgreSQL [<version>] [...])

Imported Targets

  • PostgreSQL::PostgreSQL โ€” Added in version 3.14. the whole package ๐Ÿ’… this target encapsulates all usage requirements of the required libpq client library and the optionally requested PostgreSQL server component. it's only available if PostgreSQL is found.

Result Variables

  • PostgreSQL_FOUND โ€” boolean saying whether the minimum required version and components of PostgreSQL were found.
  • PostgreSQL_VERSION โ€” Added in version 4.2. the version of PostgreSQL found.
  • PostgreSQL_LIBRARIES โ€” the PostgreSQL libraries needed for linking.
  • PostgreSQL_INCLUDE_DIRS โ€” the include directories containing PostgreSQL headers.
  • PostgreSQL_LIBRARY_DIRS โ€” the directories containing PostgreSQL libraries.
  • PostgreSQL_TYPE_INCLUDE_DIR โ€” the include directory containing PostgreSQL server headers.

Components

this module supports this extra component:

  • Server โ€” Added in version 3.20. makes sure the server headers are also found. โš ๏ธ note that PostgreSQL_TYPE_INCLUDE_DIR gets set regardless of whether you specified this component in the find_package() call. it's giving "always invited to the party" energy.

Deprecated Variables

backward-compat zone:

  • PostgreSQL_VERSION_STRING โ€” Deprecated since version 4.2: Superseded by the PostgreSQL_VERSION. the version of PostgreSQL found.

Examples

finding the client library and linking it to a project target:

find_package(PostgreSQL)
target_link_libraries(project_target PRIVATE PostgreSQL::PostgreSQL)

specifying a minimum required PostgreSQL version:

find_package(PostgreSQL 11)

finding the client library and requiring server headers using the Server component โ€” this gives you an imported target with all the usage requirements, which you then link to a project target:

find_package(PostgreSQL COMPONENTS Server)
target_link_libraries(project_target PRIVATE PostgreSQL::PostgreSQL)

and when you're checking for PostgreSQL client library features ๐Ÿ‘€ some capabilities are indicated by preprocessor macros in the libpq-fe.h header (e.g. LIBPQ_HAS_PIPELINING). others may require using the check_symbol_exists() <#command:check_symbol_exists> command:

find_package(PostgreSQL)
target_link_libraries(project_target PRIVATE PostgreSQL::PostgreSQL)

# The PQservice() function is available as of PostgreSQL 18.
if(TARGET PostgreSQL::PostgreSQL)
  include(CheckSymbolExists)
  include(CMakePushCheckState)

  cmake_push_check_state(RESET)
  set(CMAKE_REQUIRED_LIBRARIES PostgreSQL::PostgreSQL)
  check_symbol_exists(PQservice "libpq-fe.h" PROJECT_HAS_PQSERVICE)
  cmake_pop_check_state()
endif()

๐ŸŽฌ FindProducer

Note: Producer (also known as Open Producer) originated from the osgProducer utility library in early versions of the OpenSceneGraph toolkit, and was later developed into a standalone library. the osgProducer was eventually replaced by the osgViewer library, and the standalone Producer library became obsolete and is no longer maintained ๐Ÿ’€ for details about OpenSceneGraph usage, refer to the FindOpenSceneGraph <#module:FindOpenSceneGraph> module.

this module finds the Producer library โ€” a windowing and event handling library designed primarily for real-time graphics applications ๐ŸŒˆ:

find_package(Producer [...])

Producer library headers are meant to be included in C++ project source code like this:

example.cxx

#include <Producer/CameraGroup>

Result Variables

  • Producer_FOUND โ€” Added in version 3.3. boolean saying whether Producer was found โœจ

Cache Variables

these cache variables may also be set:

  • PRODUCER_INCLUDE_DIR โ€” the include directory containing headers needed to use Producer.
  • PRODUCER_LIBRARY โ€” the path to the Producer library needed to link against for usage.

Hints

this module accepts these variables:

  • PRODUCER_DIR โ€” an environment variable you can set to help locate a custom installation of the Producer library ๐Ÿงš it should point to the root directory where the Producer library was installed. this should match the installation prefix used when configuring and building Producer, such as with ./configure --prefix=$PRODUCER_DIR.

because Producer was historically tightly integrated with OpenSceneGraph, this module also accepts these environment variables as equivalents to PRODUCER_DIR, as a convenience so you can specify a common installation root for multiple OpenSceneGraph-related libraries all at once:

  • OSGDIR โ€” environment variable treated the same as PRODUCER_DIR.
  • OSG_DIR โ€” environment variable treated the same as PRODUCER_DIR.

Deprecated Variables

backward compatibility, bestie:

  • PRODUCER_FOUND โ€” Deprecated since version 4.2: Use Producer_FOUND, which has the same value. boolean saying whether Producer was found.

Examples

finding the Producer library and creating an imported target <#imported-targets> that encapsulates its usage requirements, so you can link it to a project target ๐Ÿ”ฅ:

find_package(Producer)

if(Producer_FOUND AND NOT TARGET Producer::Producer)
  add_library(Producer::Producer INTERFACE IMPORTED)
  set_target_properties(
    Producer::Producer
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${PRODUCER_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${PRODUCER_LIBRARY}"
  )
endif()

target_link_libraries(example PRIVATE Producer::Producer)

๐Ÿ“ฆ FindProtobuf

Note: if the Protobuf library is built and installed using its CMake-based build system, it provides a package configuration file <#config-file-packages> for use with the find_package() <#command:find_package> command in config mode: find_package(Protobuf CONFIG) in that case, imported targets and CMake commands such as protobuf_generate() are provided by the upstream package rather than this module ๐Ÿ’… plus, some variables documented here are not available in config mode, since imported targets are preferred. for usage details, refer to the upstream documentation โ€” that's the recommended way to use Protobuf with CMake. โš ๏ธ this module works only in module mode.

this module finds the Protocol Buffers library (Protobuf) in module mode:

find_package(Protobuf [<version>] [...])

Protobuf is an open-source, language-neutral, and platform-neutral mechanism for serializing structured data, developed by Google ๐Ÿฆ‹ it's commonly used for data exchange between programs or across networks.

Added in version 3.6: support for the <version> argument in find_package(Protobuf <version>) <#command:find_package>.

Changed in version 3.6: all input and output variables use the Protobuf_ prefix. variables with the PROTOBUF_ prefix are supported for backward compatibility.

Imported Targets

  • protobuf::libprotobuf โ€” Added in version 3.9. target encapsulating the Protobuf library usage requirements, available if the Protobuf library is found ๐Ÿ‘‘
  • protobuf::libprotobuf-lite โ€” Added in version 3.9. target encapsulating the protobuf-lite library usage requirements, available if Protobuf and its lite library are found.
  • protobuf::libprotoc โ€” Added in version 3.9. target encapsulating the protoc library usage requirements, available if Protobuf and its protoc library are found.
  • protobuf::protoc โ€” Added in version 3.10. imported executable target encapsulating the protoc compiler usage requirements, available if Protobuf and protoc are found โœจ

Result Variables

  • Protobuf_FOUND โ€” Added in version 3.3. boolean saying whether the (requested version of the) Protobuf library was found.
  • Protobuf_VERSION โ€” Added in version 3.6. the version of Protobuf found.
  • Protobuf_INCLUDE_DIRS โ€” include directories needed to use Protobuf.
  • Protobuf_LIBRARIES โ€” libraries needed to link against to use Protobuf.
  • Protobuf_PROTOC_LIBRARIES โ€” libraries needed to link against to use the protoc library.
  • Protobuf_LITE_LIBRARIES โ€” libraries needed to link against to use the protobuf-lite library.

๐Ÿ’พ Cache Variables

Okay so you can also just hand-set these cache variables yourself if you're feeling brave (or if the finder isn't cooperating) โ€” here's the full menu, bestie:

  • Protobuf_INCLUDE_DIR โ€” the include directory that has all your Protobuf headers in it ๐ŸŽ€
  • Protobuf_LIBRARY โ€” the path to the actual protobuf library, yes queen ๐Ÿ‘‘
  • Protobuf_PROTOC_LIBRARY โ€” the path to the protoc library
  • Protobuf_PROTOC_EXECUTABLE โ€” the path to the protoc compiler itself (the little guy who does the actual work) ๐Ÿ› ๏ธ
  • Protobuf_LIBRARY_DEBUG โ€” path to the protobuf debug library ๐Ÿ›
  • Protobuf_PROTOC_LIBRARY_DEBUG โ€” path to the protoc debug library
  • Protobuf_LITE_LIBRARY โ€” path to the protobuf-lite library (the diet version, lowkey slaps)
  • Protobuf_LITE_LIBRARY_DEBUG โ€” path to the protobuf-lite debug library
  • Protobuf_SRC_ROOT_FOLDER โ€” okay so when you're compiling with MSVC and you set this cache variable, the module goes looking for libraries and binaries in the protobuf-default Visual Studio project build locations, which are exactly these two:
    • <Protobuf_SRC_ROOT_FOLDER>/vsprojects/{Debug,Release}, or
    • <Protobuf_SRC_ROOT_FOLDER>/vsprojects/x64/{Debug,Release}

literally just those, no improvising ๐Ÿ’…


๐Ÿซถ Hints

So before you call find_package(Protobuf), this module will happily accept these optional variables. Set them up front, bestie:

  • Protobuf_DEBUG โ€” Added in version 3.6. โœจ A boolean variable that turns on this module's debug messages so you can print them out for debugging purposes. It's giving "turn on the lights so I can see what's happening" ๐Ÿ”
  • Protobuf_USE_STATIC_LIBS โ€” Added in version 3.9. Set it to ON and you force the use of the static libraries. Default is OFF. No in-between, no situationship โ€” static or nothing ๐Ÿ˜ค

๐Ÿ› ๏ธ Commands

So if Protobuf gets found, this module hands you the following commands. Lucky you ๐Ÿ€


๐ŸŒฑ Generating Source Files

protobuf_generate

Added in version 3.13.

Okay this is the main character right here ๐Ÿ‘‘ โ€” it automatically generates source files from .proto schema files at build time:

protobuf_generate(
  [TARGET <target>]
  [LANGUAGE <lang>]
  [OUT_VAR <variable>]
  [EXPORT_MACRO <macro>]
  [PROTOC_OUT_DIR <out-dir>]
  [PLUGIN <plugin>]
  [PLUGIN_OPTIONS <plugin-options>]
  [DEPENDENCIES <dependencies>...]
  [PROTOS <proto-files>...]
  [IMPORT_DIRS <dirs>...]
  [APPEND_PATH]
  [GENERATE_EXTENSIONS <extensions>...]
  [PROTOC_OPTIONS <options>...]
  [PROTOC_EXE <executable>]
  [DESCRIPTORS]
)

And now the options, one by one, no skipping, we don't do that here ๐Ÿ’–

  • TARGET <target> โ€” the CMake target that the generated files get added to as sources. This one is required when OUT_VAR <variable> isn't used โ€” like, pick one, bestie, you can't have neither ๐Ÿ™ˆ
  • LANGUAGE <lang> โ€” a single value, and it's either cpp or python. That's it. It decides what kind of source files you get. Defaults to cpp. Wanna use some other language? Then use the GENERATE_EXTENSIONS option instead, iykyk ๐ŸŒˆ
  • OUT_VAR <variable> โ€” the name of a CMake variable that gets filled up with the paths to all your generated source files. Real "here's your receipt" energy ๐Ÿงพ
  • EXPORT_MACRO <macro> โ€” the name of a preprocessor macro that gets applied to all generated Protobuf message classes and extern variables. Use it for stuff like declaring DLL exports โ€” the macro should expand to __declspec(dllexport) or __declspec(dllimport), depending on what's being compiled. Fun fact: this option is only used when LANGUAGE is cpp โœจ
  • PROTOC_OUT_DIR <out-dir> โ€” the output directory for the generated source files. Defaults to: CMAKE_CURRENT_BINARY_DIR ๐Ÿ“
  • PLUGIN <plugin> โ€” Added in version 3.21. An optional plugin executable. Think like, the path to grpc_cpp_plugin, for example ๐Ÿงฉ
  • PLUGIN_OPTIONS <plugin-options> โ€” Added in version 3.28. Extra options that get passed to the plugin, like generate_mock_code=true for the gRPC C++ plugin. Slay ๐Ÿ’…
  • DEPENDENCIES <dependencies>... โ€” Added in version 3.28. Dependencies that the file generation depends on. These get forwarded to the underlying add_custom_command(DEPENDS) invocation.
Changed in version 4.1: this argument now accepts multiple values (DEPENDENCIES a b c...). Before that it was single-value only (DEPENDENCIES "a;b;c;..."). Glow-up fr fr ๐Ÿ”ฅ
  • PROTOS <proto-files>... โ€” a list of .proto schema files to process. And if <target> is also specified, these get combined with all the .proto source files from that target. Teamwork ๐Ÿซถ
  • IMPORT_DIRS <dirs>... โ€” a list of one or more common parent directories for the schema files. Example time: if your schema file is proto/helloworld/helloworld.proto and the import directory is proto/, then the generated files land at <out-dir>/helloworld/helloworld.pb.h and <out-dir>/helloworld/helloworld.pb.cc. Obsessed with how clean that is ๐ŸŒธ
  • APPEND_PATH โ€” if specified, the base paths of all proto schema files get appended to IMPORT_DIRS. Which means protoc gets invoked with an -I argument for each directory containing a .proto file ๐Ÿ›ค๏ธ
  • GENERATE_EXTENSIONS <extensions>... โ€” if you omit LANGUAGE, you must set this to specify the extensions generated by protoc. No vibes-based guessing allowed ๐Ÿšซ
  • PROTOC_OPTIONS <options>... โ€” Added in version 3.28. A list of additional command-line options passed directly to the protoc compiler. Straight to the source, no middleman ๐Ÿ’ซ
  • PROTOC_EXE <executable> โ€” Added in version 4.0. The command-line program, path, or CMake executable used to generate your Protobuf bindings. If you omit it, the protobuf::protoc imported target is used by default ๐ŸŽฏ
  • DESCRIPTORS โ€” if specified, a command-line option --descriptor_set_out=<proto-file> gets appended to the protoc compiler for each .proto source file, which enables the creation of self-describing messages โœจ
Warning bestie: this option can only be used when <lang> is cpp and Protobuf is found in module mode. Note: this option is not available when Protobuf is found in config mode ๐Ÿ˜ญ

๐Ÿ’€ Deprecated Commands

The following commands are still here for backward compatibility. They're giving "still invited to the party but sitting at the kids' table" ๐Ÿฅฒ

Note: protobuf_generate_cpp() and protobuf_generate_python() work correctly only within the same directory scope where find_package(Protobuf ...) is called. Don't go wandering ๐Ÿšถโ€โ™€๏ธ Note: if Protobuf is found in config mode, then protobuf_generate_cpp() and protobuf_generate_python() are not available as of Protobuf version 3.0.0 โ€” unless the upstream package configuration hint variable protobuf_MODULE_COMPATIBLE is set to boolean true before you call find_package(Protobuf ...). Read that twice, it matters ๐Ÿ™ˆ

protobuf_generate_cpp

Deprecated since version 4.1: Use protobuf_generate().

Automatically generates C++ source files from .proto schema files at build time:

protobuf_generate_cpp(
  <sources-variable>
  <headers-variable>
  [DESCRIPTORS <variable>]
  [EXPORT_MACRO <macro>]
  <proto-files>...
)
  • <sources-variable> โ€” name of the variable to define, which will contain a list of generated C++ source files ๐Ÿ’…
  • <headers-variable> โ€” name of the variable to define, which will contain a list of generated header files ๐ŸŽ€
  • DESCRIPTORS <variable> โ€” Added in version 3.10. Name of the variable to define, which will contain a list of generated descriptor files, if you requested them.
Note: this option is not available when Protobuf is found in config mode ๐Ÿ˜ญ
  • EXPORT_MACRO <macro> โ€” name of a macro that should expand to __declspec(dllexport) or __declspec(dllimport), depending on what's being compiled โœจ
  • <proto-files>... โ€” one of more .proto files to be processed. (Yes, "one of more" โ€” that's the original wording, I'm not touching it, it's iconic in its own way ๐Ÿ’€)

protobuf_generate_python

Deprecated since version 4.1: Use protobuf_generate().

Added in version 3.4.

Automatically generates Python source files from .proto schema files at build time:

protobuf_generate_python(<python-sources-variable> <proto-files>...)
  • <python-sources-variable> โ€” name of the variable to define, which will contain a list of generated Python source files ๐Ÿ
  • <proto-files>... โ€” one or more .proto files to be processed ๐Ÿฆ‹

So protobuf_generate_cpp() and protobuf_generate_python() will also accept the following optional variables before they get invoked, because they're vintage like that:

  • Protobuf_IMPORT_DIRS โ€” Deprecated since version 4.1. A list of additional directories to search for imported .proto files ๐Ÿ”
  • PROTOBUF_GENERATE_CPP_APPEND_PATH โ€” Deprecated since version 4.1: Use the protobuf_generate(APPEND_PATH) command option. A boolean variable that, if set to boolean true, causes protoc to be invoked with an -I argument for each directory containing a .proto file. And by default? It's already set to boolean true ๐ŸŽ‰ (so it's on unless you say otherwise, no cap)

๐ŸŒŸ Examples

๐ŸŒˆ Examples: Finding Protobuf

Finding the Protobuf library, simplest possible slay:

find_package(Protobuf)

Or, finding Protobuf and specifying a minimum required version:

find_package(Protobuf 30)

Or, finding Protobuf and making it required โ€” which means if it's not found, processing stops with an error message. No soft launches here ๐Ÿšจ:

find_package(Protobuf REQUIRED)

๐Ÿงš Example: Finding Protobuf in Config Mode

So when the Protobuf library is built and installed using its own CMake-based build system, you can find it in config mode like this:

find_package(Protobuf CONFIG)

But lowkey, some Protobuf installations might still not provide a package configuration file ๐Ÿ˜ญ. The following example shows how to use the CMAKE_FIND_PACKAGE_PREFER_CONFIG variable to find Protobuf in config mode and then fall back to module mode if the config file isn't found. Best of both worlds, we love a backup plan ๐Ÿซถ:

set(CMAKE_FIND_PACKAGE_PREFER_CONFIG TRUE)
find_package(Protobuf)
unset(CMAKE_FIND_PACKAGE_PREFER_CONFIG)

๐Ÿ’œ Example: Using Protobuf

Finding Protobuf and linking its imported library target to a project target:

...and then the link step is literally just this:

find_package(Protobuf)
target_link_libraries(example PRIVATE protobuf::libprotobuf)

โœจ Example: Processing Proto Schema Files โœจ

Bestie, this one shows how to take every *.proto schema source file you added to a target and glow it up into C++ source files:

CMakeLists.txt

cmake_minimum_required(VERSION 3.24)
project(ProtobufExample)

add_executable(example main.cxx person.proto)

find_package(Protobuf)

if(Protobuf_FOUND)
  protobuf_generate(TARGET example)
endif()

target_link_libraries(example PRIVATE protobuf::libprotobuf)
target_include_directories(example PRIVATE ${CMAKE_CURRENT_BINARY_DIR})

person.proto

syntax = "proto3";

message Person {
  string name = 1;
  int32 id = 2;
}

main.cxx

#include <iostream>
#include "person.pb.h"

int main()
{
  Person person;
  person.set_name("Alice");
  person.set_id(123);

  std::cout << "Name: " << person.name() << "\n";
  std::cout << "ID: " << person.id() << "\n";

  return 0;
}

๐Ÿ’… Example: Using Protobuf and gRPC ๐Ÿ’…

This is the moment for Protobuf plus gRPC together, okay:

CMakeLists.txt

find_package(Protobuf REQUIRED)
find_package(gRPC CONFIG REQUIRED)

add_library(ProtoExample Example.proto)
target_link_libraries(ProtoExample PUBLIC gRPC::grpc++)

protobuf_generate(TARGET ProtoExample)
protobuf_generate(
  TARGET ProtoExample
  LANGUAGE grpc
  PLUGIN protoc-gen-grpc=$<TARGET_FILE:gRPC::grpc_cpp_plugin>
  PLUGIN_OPTIONS generate_mock_code=true
  GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc
)

๐ŸŒธ Examples: Upgrading Deprecated Commands ๐ŸŒธ

Here's how to process .proto files into C++ code using a deprecated command and then its modern replacement. The glow-up is real.

CMakeLists.txt with deprecated command

find_package(Protobuf)

if(Protobuf_FOUND)
  protobuf_generate_cpp(
    proto_sources
    proto_headers
    EXPORT_MACRO DLL_EXPORT
    DESCRIPTORS proto_descriptors
    src/protocol/Proto1.proto
    src/protocol/Proto2.proto
  )
endif()

target_sources(
  example
  PRIVATE ${proto_sources} ${proto_headers} ${proto_descriptors}
)
target_link_libraries(example PRIVATE protobuf::libprotobuf)

CMakeLists.txt with upgraded code

find_package(Protobuf)

if(Protobuf_FOUND)
  protobuf_generate(
    TARGET example
    EXPORT_MACRO DLL_EXPORT
    IMPORT_DIRS src/protocol
    DESCRIPTORS
    PROTOS
      src/protocol/Proto1.proto
      src/protocol/Proto2.proto
  )
endif()

target_link_libraries(example PRIVATE protobuf::libprotobuf)

And the Python flavor, deprecated command first:

CMakeLists.txt with deprecated command

find_package(Protobuf)

if(Protobuf_FOUND)
  protobuf_generate_python(python_sources foo.proto)
endif()

add_custom_target(proto_files DEPENDS ${python_sources})

CMakeLists.txt with upgraded code

find_package(Protobuf)

if(Protobuf_FOUND)
  protobuf_generate(
    LANGUAGE python
    PROTOS foo.proto
    OUT_VAR python_sources
  )
endif()

add_custom_target(proto_files DEPENDS ${python_sources})

๐Ÿ FindPython ๐Ÿ

Added in version 3.12.

Finds the Python interpreter, compiler and development environment (include directories and libraries):

find_package(Python [<version>] [COMPONENTS <components>...] [...])

Added in version 3.19: When a version is requested, it can be specified as a simple value or as a range. For a detailed description of version range usage and capabilities, refer to the find_package() command.

The following components are supported:

  • Interpreter โ€” search for Python interpreter.
  • Compiler โ€” search for Python compiler. Only offered by IronPython.
  • Development โ€” search for development artifacts (include directories and libraries).

Added in version 3.18: This component includes two sub-components which can be specified independently:

  • Development.Module โ€” search for artifacts for Python module developments.
  • Development.Embed โ€” search for artifacts for Python embedding developments.

Added in version 3.26:

  • Development.SABIModule โ€” search for artifacts for Python module developments using the Stable Application Binary Interface (https://docs.python.org/3/c-api/stable.html). This component is available only for version 3.2 and upper.

Added in version 3.14:

  • NumPy โ€” search for NumPy include directories. Specifying this component also implies the components Interpreter and Development.Module.

Changed in version 4.2: The component Development.Module is no longer implied when the policy CMP0201 is set to NEW.

If no COMPONENTS are specified, Interpreter is assumed.

If component Development is specified, it implies sub-components Development.Module and Development.Embed.

Changed in version 4.1: In a cross-compiling mode (i.e. the CMAKE_CROSSCOMPILING variable is defined to true), the following constraints, when the policy CMP0190 is set to NEW, now apply to the requested components:

  • Interpreter or Compiler alone: the host artifacts will be searched.
  • Interpreter or Compiler with Development or any sub-component: The target artifacts will be searched. In this case, the CMAKE_CROSSCOMPILING_EMULATOR variable must be defined and will be used to execute the interpreter or the compiler.

When both host and target artifacts are needed, two different calls to the find_package() command should be done. The Python_ARTIFACTS_PREFIX variable can be helpful in this situation.

To ensure consistent versions between components Interpreter, Compiler, Development (or one of its sub-components) and NumPy, specify all components at the same time:

find_package (Python COMPONENTS Interpreter Development)

This module looks preferably for version 3 of Python. If not found, version 2 is searched. To manage concurrent versions 3 and 2 of Python, use FindPython3 and FindPython2 modules rather than this one.

Note: If components Interpreter and Development (or one of its sub-components) are both specified, this module search only for interpreter with same platform architecture as the one defined by CMake configuration. This constraint does not apply if only Interpreter component is specified.

โœจ Imported Targets โœจ

This module provides the following Imported Targets:

Changed in version 3.14: Imported Targets are only created when CMAKE_ROLE is PROJECT.

  • Python::Interpreter โ€” Python interpreter. This target is defined only if the Interpreter component is found.
  • Python::InterpreterDebug โ€” Added in version 3.30. Python debug interpreter. This target is defined only if the Interpreter component is found and the Python_EXECUTABLE_DEBUG variable is defined. The target is only defined on the Windows platform.
  • Python::InterpreterMultiConfig โ€” Added in version 3.30. Python interpreter. The release or debug version of the interpreter will be used, based on the context (platform, configuration). This target is defined only if the Interpreter component is found.
  • Python::Compiler โ€” Python compiler. This target is defined only if the Compiler component is found.
  • Python::Module โ€” Added in version 3.15. Python library for Python module. Target defined if component Development.Module is found.
  • Python::SABIModule โ€” Added in version 3.26. Python library for Python module using the Stable Application Binary Interface. Target defined if component Development.SABIModule is found.
  • Python::Python โ€” Python library for Python embedding. Target defined if component Development.Embed is found.
  • Python::NumPy โ€” Added in version 3.14. NumPy Python library. Target defined if component NumPy is found. Moreover, this target has the Python::Module target as dependency.

Changed in version 4.2: This target does not have anymore the Python::Module target as dependency when the policy CMP0201 is set to NEW.

๐ŸŒˆ Result Variables ๐ŸŒˆ

This module defines the following variables (see Standard Variable Names):

  • Python_FOUND โ€” Boolean indicating whether system has the Python requested components.
  • Python_Interpreter_FOUND โ€” Boolean indicating whether system has the Python interpreter.
  • Python_EXECUTABLE โ€” Path to the Python interpreter.
  • Python_EXECUTABLE_DEBUG โ€” Added in version 3.30. Path to the debug Python interpreter. It is only defined on the Windows platform.
  • Python_INTERPRETER โ€” Added in version 3.30. Path to the Python interpreter, defined as a generator expression (see cmake-generator-expressions(7)) selecting the Python_EXECUTABLE or Python_EXECUTABLE_DEBUG variable based on the context (platform, configuration).
  • Python_INTERPRETER_ID โ€” A short string unique to the interpreter. Possible values include:
    • Python
    • ActivePython
    • Anaconda
    • Canopy
    • IronPython
    • PyPy
  • Python_FREE_THREADED โ€” Added in version 4.4. Boolean value, which is true if the python is free threaded (i.e. config var Py_GIL_DISABLED has value 1), false otherwise.
  • Python_STDLIB โ€” Standard platform independent installation directory. Information returned by sysconfig.get_path('stdlib').
  • Python_STDARCH โ€” Standard platform dependent installation directory. Information returned by sysconfig.get_path('platstdlib').
  • Python_SITELIB โ€” Third-party platform independent installation directory. Information returned by sysconfig.get_path('purelib').
  • Python_SITEARCH โ€” Third-party platform dependent installation directory.

That last bit? Straight from sysconfig.get_path('platlib') โ€” that's where it gets its info. ๐Ÿ’…

Now, onto the rest of the variables, bestie:

  • Python_SOABI โ€” Added in version 3.17. The extension suffix for modules โœจ โ€” computed from sysconfig.get_config_var('EXT_SUFFIX') or sysconfig.get_config_var('SOABI') or python3-config --extension-suffix.
  • Python_SOSABI โ€” Added in version 3.26. The extension suffix for modules using the Stable Application Binary Interface. Here's the vibe: it's computed from importlib.machinery.EXTENSION_SUFFIXES if the COMPONENT Interpreter was specified. Otherwise the extension is abi3 or abi3t โ€” except for Windows, MSYS and CYGWIN, where this is literally an empty string. ๐Ÿซ 
  • Python_Compiler_FOUND โ€” a Boolean saying whether the system has the Python compiler. Yes/no, iconic.
  • Python_COMPILER โ€” the path to the Python compiler. Only offered by IronPython, so don't go looking for it elsewhere, bestie.
  • Python_COMPILER_ID โ€” a short string unique to the compiler. Possible values include:
    • IronPython
  • Python_DOTNET_LAUNCHER โ€” Added in version 3.18. The .Net interpreter. Only used by the IronPython implementation. ๐ŸŽ€
  • Python_Development_FOUND โ€” a Boolean saying whether the system has the Python development artifacts.
  • Python_Development.Module_FOUND โ€” Added in version 3.18. Boolean: does the system have the Python development artifacts for a Python module? ๐Ÿฆ‹
  • Python_Development.SABIModule_FOUND โ€” Added in version 3.26. Boolean: does the system have the Python development artifacts for a Python module using the Stable Application Binary Interface?
  • Python_Development.Embed_FOUND โ€” Added in version 3.18. Boolean: does the system have the Python development artifacts for Python embedding?
  • Python_INCLUDE_DIRS โ€” the Python include directories. ๐Ÿ“‚
  • Python_DEFINITIONS โ€” Added in version 3.30.3. The Python preprocessor definitions.
  • Python_DEBUG_POSTFIX โ€” Added in version 3.30. The postfix of the debug python module. You can use this variable to define the DEBUG_POSTFIX target property, no cap. ๐Ÿ”ฅ
  • Python_LINK_OPTIONS โ€” Added in version 3.19. The Python link options. Some configurations literally require specific link options for a correct build and execution โ€” so don't sleep on these.
  • Python_LIBRARIES โ€” the Python libraries.
  • Python_LIBRARY_DIRS โ€” the Python library directories.
  • Python_RUNTIME_LIBRARY_DIRS โ€” the Python runtime library directories.
  • Python_SABI_LIBRARIES โ€” Added in version 3.26. The Python libraries for the Stable Application Binary Interface. โœจ
  • Python_SABI_LIBRARY_DIRS โ€” Added in version 3.26. The Python SABI library directories.
  • Python_RUNTIME_SABI_LIBRARY_DIRS โ€” Added in version 3.26. The Python runtime SABI library directories.
  • Python_VERSION โ€” Python version.
  • Python_VERSION_MAJOR โ€” Python major version.
  • Python_VERSION_MINOR โ€” Python minor version.
  • Python_VERSION_PATCH โ€” Python patch version.
  • Python_PyPy_VERSION โ€” Added in version 3.18. Python PyPy version.
  • Python_NumPy_FOUND โ€” Added in version 3.14. Boolean: does the system have the NumPy? ๐Ÿ“
  • Python_NumPy_INCLUDE_DIRS โ€” Added in version 3.14. The NumPy include directories.
  • Python_NumPy_VERSION โ€” Added in version 3.14. The NumPy version.

๐ŸŽ€ Hints ๐ŸŽ€

  • Python_ROOT_DIR โ€” define the root directory of a Python installation. Easy. ๐Ÿ’–
  • Python_USE_STATIC_LIBS โ€” the whole "which flavor of lib" situation:
    • If not defined, search for shared libraries and static libraries in that order.
    • If set to TRUE, search only for static libraries.
    • If set to FALSE, search only for shared libraries.
โš ๏ธ Heads up: this hint is ignored on Windows because static libraries are literally not available on that platform. ๐Ÿ™ˆ
โš ๏ธ Note: this hint is honored only when searching for Python version 3.

So the Python_FIND_ABI variable is a 4-tuple specifying, in this exact order: pydebug (d), pymalloc (m), unicode (u) and gil_disabled (t) flags.

Added in version 3.30: a fourth element specifying the gil_disabled flag (i.e. free threaded python) is added and is optional. If not specified, the value is OFF.

Added in version 4.4.1: the pydebug flag is now supported on Windows systems for Python 3.14+.

Each element can be set to one of these:

  • ON: corresponding flag is selected. โœ…
  • OFF: corresponding flag is not selected. โŒ
  • ANY: both possibilities (ON and OFF) will be searched. ๐ŸŽฒ
โš ๏ธ Note: if Python_FIND_ABI is not defined, the following defaults apply: - On POSIX systems: ANY, ANY, ANY, OFF. - On Windows systems: OFF, OFF, OFF, OFF.

From this 4-tuple, various ABIs get searched starting from the most specialized to the most general. And when ANY is specified for pydebug and gil_disabled, the debug and free threaded versions are searched after the non-debug and non-gil-disabled ones. Order matters, bestie. ๐Ÿ’…

For example, if we have:

set (Python_FIND_ABI "ON" "ANY" "ANY" "ON")

The following flag combinations will be appended, in that order, to the artifact names:

  • On POSIX systems: tdmu, tdm, tdu, and td.
  • On Windows systems: tmu_d, tm_d, tu_d, and t_d.

And to search any possible ABIs:

set (Python_FIND_ABI "ANY" "ANY" "ANY" "ANY")

The following combinations, in that order, will be used:

  • On POSIX systems: mu, m, u, <empty>, dmu, dm, du, d, tmu, tm, tu, t, tdmu, tdm, tdu, and td.
  • On Windows systems: mu, m, u, <empty>, mu_d, m_d, u_d, _d, tmu, tm, tu, t, tmu_d, tm_d, tu_d, and t_d.
โš ๏ธ Note: this hint is fully usable on POSIX systems. On Windows systems, only the gil_disabled and pydebug flags are supported. And the pydebug flag is only supported for Python 3.14+. So on Windows, when Python_FIND_ABI is defined, Python distributions from python.org (https://www.python.org/) will be found only if the value for the flags pymalloc and unicode is OFF or ANY. That's the fine print, iykyk. ๐Ÿ˜ญ
  • Python_FIND_STRATEGY โ€” Added in version 3.15. This variable defines how the lookup will be done. You can set Python_FIND_STRATEGY to one of these:
    • VERSION: try to find the most recent version in all specified locations. This is the default if policy CMP0094 is undefined or set to OLD. ๐Ÿ”ฅ
    • LOCATION: stops lookup as soon as a version satisfying version constraints is founded. This is the default if policy CMP0094 is set to NEW.

See also Python_FIND_UNVERSIONED_NAMES.

  • Python_FIND_REGISTRY โ€” Added in version 3.13. On Windows, the Python_FIND_REGISTRY variable determines the order of preference between registry and environment variables. Set it to one of these:
    • FIRST: try to use registry before environment variables. This is the default. ๐Ÿ‘‘
    • LAST: try to use registry after environment variables.
    • NEVER: never try to use registry.
  • Python_FIND_FRAMEWORK โ€” Added in version 3.15. On macOS, the Python_FIND_FRAMEWORK variable determines the order of preference between Apple-style and unix-style package components. It can take the same values as the CMAKE_FIND_FRAMEWORK variable.
โš ๏ธ Note: the value ONLY is not supported, so FIRST will be used instead.

If Python_FIND_FRAMEWORK is not defined, the CMAKE_FIND_FRAMEWORK variable will be used, if any.

  • Python_FIND_VIRTUALENV โ€” Added in version 3.15. This variable defines the handling of virtual environments managed by virtualenv or conda. It's meaningful only when a virtual environment is active (i.e. the activate script has been evaluated). In that case, it takes precedence over the Python_FIND_REGISTRY and CMAKE_FIND_FRAMEWORK variables. Set Python_FIND_VIRTUALENV to one of these:
    • FIRST: the virtual environment is used before any other standard paths to look-up for the interpreter. This is the default. ๐Ÿฆ‹
    • ONLY: only the virtual environment is used to look-up for the interpreter.
    • STANDARD: the virtual environment is not used to look-up for the interpreter, but environment variable PATH is always considered. In this case, variable Python_FIND_REGISTRY (Windows) or CMAKE_FIND_FRAMEWORK (macOS) can be set with value LAST or NEVER to select preferably the interpreter from the virtual environment. ๐Ÿงš

Added in version 3.17: added support for conda environments.

โš ๏ธ Note: if the component Development is requested (or one of its sub-components) and is not found or the wrong artifacts are returned, including also the component Interpreter may be helpful. ๐Ÿ’ก
  • Python_FIND_IMPLEMENTATIONS โ€” Added in version 3.18. This variable defines, in an ordered list, the different implementations which will be searched. It can hold the following values:
    • CPython: this is the standard implementation. Various products, like Anaconda or ActivePython, rely on this implementation. โญ
    • IronPython: this implementation uses the CSharp language for .NET Framework on top of the Dynamic Language Runtime (DLR). See IronPython at https://ironpython.net.
    • PyPy: this implementation uses the RPython language and the RPython translation toolchain to produce the python interpreter. See PyPy at https://pypy.org.

The default value is:

  • Windows platform: CPython, IronPython
  • Other platforms: CPython โ€” literally the default one, no surprise ๐Ÿ’…
Note: this hint has the lowest priority of all hints, bestie. So even if you, like, put IronPython first and CPython second, a Python product based on CPython can still get picked โ€” because, for example with Python_FIND_STRATEGY=LOCATION, each location gets searched for IronPython first and CPython second. The order of the hints does not fully save you ๐Ÿ˜ญ
Note: when IronPython is specified, on platforms other than Windows the .Net interpreter (i.e. the mono command) is expected to be available through the PATH variable. No mono, no party ๐Ÿ™ˆ

Python_FIND_UNVERSIONED_NAMES

Added in version 3.20. โœจ

This variable defines how the generic names will be searched. Currently, it only applies to the generic names of the interpreter โ€” namely python3 or python2 and python. You can set Python_FIND_UNVERSIONED_NAMES to one of these values:

  • FIRST โ€” the generic names are searched before the more specialized ones (such as python2.5, for example).
  • LAST โ€” the generic names are searched after the more specialized ones. This is the default. ๐Ÿ‘‘
  • NEVER โ€” the generic names are not searched at all. ๐Ÿšซ

See also Python_FIND_STRATEGY.


Artifacts Specification

Added in version 3.16.

To solve special cases, it's possible to specify the artifacts directly by setting the following variables โ€” no searching, you just tell it where stuff lives ๐Ÿ’–

Python_EXECUTABLE

The path to the interpreter.

Python_COMPILER

The path to the compiler.

Python_DOTNET_LAUNCHER

Added in version 3.18.

The .Net interpreter. Only used by the IronPython implementation.

Python_LIBRARY

The path to the library. It will be used to compute the variables Python_LIBRARIES, Python_LIBRARY_DIRS and Python_RUNTIME_LIBRARY_DIRS.

Python_SABI_LIBRARY

Added in version 3.26.

The path to the library for Stable Application Binary Interface. It will be used to compute the variables Python_SABI_LIBRARIES, Python_SABI_LIBRARY_DIRS and Python_RUNTIME_SABI_LIBRARY_DIRS.

Python_INCLUDE_DIR

The path to the directory of the Python headers. It will be used to compute the variable Python_INCLUDE_DIRS.

Python_NumPy_INCLUDE_DIR

The path to the directory of the NumPy headers. It will be used to compute the variable Python_NumPy_INCLUDE_DIRS.

Note: all paths must be absolute. Any artifact specified with a relative path will just be ignored, sorry babe ๐Ÿ’€
Note: when an artifact is specified, all HINTS will be ignored and no search will be performed for this artifact. If more than one artifact is specified, it is the user's responsibility to ensure the consistency of the various artifacts. That's on you, bestie ๐Ÿซถ

By default, this module supports multiple calls in different directories of a project with different version/component requirements while providing correct and consistent results for each call. To support this behavior, the CMake cache is not used in the traditional way, which can be problematic for interactive specification. So, to enable also interactive specification, the module behavior can be controlled with the following variable:

Python_ARTIFACTS_INTERACTIVE

Added in version 3.18.

Selects the behavior of the module. It's a boolean variable:

  • If set to TRUE: create CMake cache entries for the above artifact specification variables so that users can edit them interactively. This disables support for multiple version/component requirements. โš ๏ธ
  • If set to FALSE or undefined: enable multiple version/component requirements.

Python_ARTIFACTS_PREFIX

Added in version 4.0.

Define a custom prefix which will be used for the definition of all the result variables, targets, and commands. By using this variable, this module supports multiple calls in the same directory with different version/component requirements. For example, in case of cross-compilation, development components are needed but the native python interpreter can also be required:

find_package(Python COMPONENTS Development)

set(Python_ARTIFACTS_PREFIX "_HOST")
find_package(Python COMPONENTS Interpreter)

# Here Python_HOST_EXECUTABLE and Python_HOST::Interpreter artifacts are defined
Note: for consistency with standard behavior of modules, the various standard _FOUND variables (i.e. the ones without the custom prefix) are also defined by each call to the find_package() command.

Commands

This module defines the command Python_add_library (when CMAKE_ROLE is PROJECT), which has the same semantics as add_library() and adds a dependency to target Python::Python or, when the library type is MODULE, to target Python::Module or Python::SABIModule (when the USE_SABI option is specified) โ€” and takes care of Python module naming rules ๐ŸŽ€

Python_add_library (<name> [STATIC | SHARED | MODULE [USE_SABI <version>] [WITH_SOABI]]
                    <source1> [<source2> ...])

If the library type is not specified, MODULE is assumed.

Added in version 3.17: for MODULE library type, if the option WITH_SOABI is specified, the module suffix will include the Python_SOABI value, if any. โœจ

Added in version 3.26: for MODULE type, if the option USE_SABI is specified, the preprocessor definition Py_LIMITED_API will be specified, as PRIVATE, for the target <name> with the value computed from the <version> argument. The expected format for <version> is major[.minor], where each component is a numeric value. If the minor component is specified, the version should be, at least, 3.2, which is the version where the Stable Application Binary Interface was introduced. Specifying only major version 3 is equivalent to 3.2.

Changed in version 4.4: when USE_SABI is specified, if Python_FREE_THREADED is true and the Python version is 3.15 or upper, the Py_TARGET_ABI3T preprocessor definition will be defined rather than Py_LIMITED_API (see PEP 803 for more details). ๐ŸŒ€

When the option WITH_SOABI is also specified, the module suffix will include the Python_SOSABI value, if any.

Added in version 3.30: for MODULE type, the DEBUG_POSTFIX target property is initialized with the value of the Python_DEBUG_POSTFIX variable if defined.


FindPython2

Added in version 3.12.

Finds the Python 2 interpreter, compiler and development environment (include directories and libraries):

find_package(Python2 [<version>] [COMPONENTS <components>...] [...])

Added in version 3.19: when a version is requested, it can be specified as a simple value or as a range. For a detailed description of version range usage and capabilities, refer to the find_package() command.

The following components are supported:

  • Interpreter โ€” search for Python 2 interpreter ๐Ÿ
  • Compiler โ€” search for Python 2 compiler. Only offered by IronPython.
  • Development โ€” search for development artifacts (include directories and libraries). Added in version 3.18: this component includes two sub-components which can be specified independently:
    • Development.Module โ€” search for artifacts for Python 2 module developments.
    • Development.Embed โ€” search for artifacts for Python 2 embedding developments.
  • Added in version 3.14:
    • NumPy โ€” search for NumPy include directories. Specifying this component implies also the components Interpreter and Development.Module.

Changed in version 4.2: the component Development.Module is no longer implied when the policy CMP0201 is set to NEW.

If no COMPONENTS are specified, Interpreter is assumed.

If component Development is specified, it implies the sub-components Development.Module and Development.Embed.

Changed in version 4.1: in a cross-compiling mode (i.e. the CMAKE_CROSSCOMPILING variable is defined to true), the following constraints, when the policy CMP0190 is set to NEW, now apply to the requested components:

  • Interpreter or Compiler alone: the host artifacts will be searched. ๐Ÿ–ฅ๏ธ
  • Interpreter or Compiler with Development or any sub-component: the target artifacts will be searched. In this case, the CMAKE_CROSSCOMPILING_EMULATOR variable must be defined and will be used to execute the interpreter or the compiler. โš ๏ธ

When both host and target artifacts are needed, two different calls to the find_package() command should be done. The Python_ARTIFACTS_PREFIX variable can be helpful in this situation. ๐Ÿ’ก

To ensure consistent versions between components Interpreter, Compiler, Development (or one of its sub-components) and NumPy, specify all components at the same time:

find_package (Python2 COMPONENTS Interpreter Development)

This module looks only for version 2 of Python. This module can be used concurrently with the FindPython3 module to use both Python versions. Slay ๐Ÿ’…

The FindPython module can be used if the Python version does not matter for you.

Note: if components Interpreter and Development (or one of its sub-components) are both specified, this module searches only for an interpreter with the same platform architecture as the one defined by the CMake configuration. This constraint does not apply if only the Interpreter component is specified.

Imported Targets

This module provides the following Imported Targets:

Changed in version 3.14: Imported Targets are only created when CMAKE_ROLE is PROJECT. ๐Ÿ‘‘

Python2::Interpreter

Python 2 interpreter. This target is defined only if the Interpreter component is found.

Python2::InterpreterDebug

Added in version 3.30.

Python 2 debug interpreter. This target is defined only if the Interpreter component is found and the Python2_EXECUTABLE_DEBUG variable is defined. The target is only defined on the Windows platform. ๐ŸชŸ

Python2::InterpreterMultiConfig

Added in version 3.30.

Python 2 interpreter. The release or debug version of the interpreter will be used, based on the context (platform, configuration). This target is defined only if the Interpreter component is found ๐ŸŒˆ

  • Python2::Compiler โ€” the Python 2 compiler, bestie. This target only shows up if the Compiler component is found. no compiler, no target, that's the vibe ๐Ÿ’…
  • Python2::Module โ€” Added in version 3.15. It's the Python 2 library for a Python module. Target gets defined if the component Development.Module is found โœจ
  • Python2::Python โ€” the Python 2 library for Python embedding. Target is defined if component Development.Embed is found ๐Ÿซถ
  • Python2::NumPy โ€” Added in version 3.14. The NumPy library for Python 2. Target is defined if component NumPy is found. And also โ€” this target has the Python2::Module target as a dependency, iykyk.

Changed in version 4.2: this target does not have the Python2::Module target as a dependency anymore when the policy CMP0201 is set to NEW. periodt.


๐ŸŒธ Result Variables ๐ŸŒธ

This module defines the following variables (peep the Standard Variable Names page for the lore):

  • Python2_FOUND โ€” boolean, tells you whether the system has the Python 2 components you asked for ๐Ÿ‘‘
  • Python2_Interpreter_FOUND โ€” boolean, tells you whether the system has the Python 2 interpreter.
  • Python2_EXECUTABLE โ€” path to the Python 2 interpreter.
  • Python2_EXECUTABLE_DEBUG โ€” Added in version 3.30. Path to the debug Python 2 interpreter. It's only defined on the Windows platform, ngl.
  • Python2_INTERPRETER โ€” Added in version 3.30. Path to the Python 2 interpreter, defined as a generator expression that picks the Python2_EXECUTABLE or Python2_EXECUTABLE_DEBUG variable based on the context (platform, configuration). lowkey genius โœจ
  • Python2_INTERPRETER_ID โ€” a short string unique to the interpreter. Possible values include:
    • Python
    • ActivePython
    • Anaconda
    • Canopy
    • IronPython
    • PyPy
  • Python2_STDLIB โ€” standard platform independent installation directory. Info comes back from sysconfig.get_path('stdlib') or else distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True).
  • Python2_STDARCH โ€” standard platform dependent installation directory. Info returned by sysconfig.get_path('platstdlib') or else distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True).
  • Python2_SITELIB โ€” third-party platform independent installation directory. Info returned by sysconfig.get_path('purelib') or else distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False).
  • Python2_SITEARCH โ€” third-party platform dependent installation directory. Info returned by sysconfig.get_path('platlib') or else distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False).
  • Python2_Compiler_FOUND โ€” boolean, tells you whether the system has the Python 2 compiler.
  • Python2_COMPILER โ€” path to the Python 2 compiler. Only offered by IronPython, fun fact ๐Ÿฆ‹
  • Python2_COMPILER_ID โ€” a short string unique to the compiler. Possible values include:
    • IronPython
  • Python2_DOTNET_LAUNCHER โ€” Added in version 3.18. The .Net interpreter. Only used by the IronPython implementation.
  • Python2_Development_FOUND โ€” boolean, tells you whether the system has the Python 2 development artifacts.
  • Python2_Development.Module_FOUND โ€” Added in version 3.18. Boolean, tells you whether the system has the Python 2 development artifacts for a Python module.
  • Python2_Development.Embed_FOUND โ€” Added in version 3.18. Boolean, tells you whether the system has the Python 2 development artifacts for Python embedding.
  • Python2_INCLUDE_DIRS โ€” the Python 2 include directories ๐Ÿ’–
  • Python2_DEBUG_POSTFIX โ€” Added in version 3.30. Postfix of the debug python module. You can use this variable to define the DEBUG_POSTFIX target property.
  • Python2_LINK_OPTIONS โ€” Added in version 3.19. The Python 2 link options. Some configurations need specific link options for a correct build and execution, so likeโ€ฆ don't skip these ๐Ÿ™ˆ
  • Python2_LIBRARIES โ€” the Python 2 libraries.
  • Python2_LIBRARY_DIRS โ€” the Python 2 library directories.
  • Python2_RUNTIME_LIBRARY_DIRS โ€” the Python 2 runtime library directories.
  • Python2_VERSION โ€” Python 2 version.
  • Python2_VERSION_MAJOR โ€” Python 2 major version.
  • Python2_VERSION_MINOR โ€” Python 2 minor version.
  • Python2_VERSION_PATCH โ€” Python 2 patch version.
  • Python2_PyPy_VERSION โ€” Added in version 3.18. Python 2 PyPy version.
  • Python2_NumPy_FOUND โ€” Added in version 3.14. Boolean, tells you whether the system has NumPy.
  • Python2_NumPy_INCLUDE_DIRS โ€” Added in version 3.14. The NumPy include directories.
  • Python2_NumPy_VERSION โ€” Added in version 3.14. The NumPy version.

๐Ÿ” Hints ๐Ÿ”

  • Python2_ROOT_DIR โ€” define the root directory of a Python 2 installation. like, "hey, it's over here" energy ๐ŸŽ€
  • Python2_USE_STATIC_LIBS โ€” the whole static-vs-shared situation:
    • If not defined, search for shared libraries and static libraries in that order.
    • If set to TRUE, search only for static libraries.
    • If set to FALSE, search only for shared libraries.
Note: this hint gets ignored on Windows because static libraries are not available on this platform. not me finding out the hard way ๐Ÿ’€
  • Python2_FIND_STRATEGY โ€” Added in version 3.15. This variable defines how the lookup will be done. You can set Python2_FIND_STRATEGY to one of these:
    • VERSION: try to find the most recent version in all specified locations. This is the default if policy CMP0094 is undefined or set to OLD.
    • LOCATION: stops the lookup as soon as a version satisfying the version constraints is found. This is the default if policy CMP0094 is set to NEW.

See also Python2_FIND_UNVERSIONED_NAMES. ๐Ÿซถ

  • Python2_FIND_REGISTRY โ€” Added in version 3.13. On Windows, the Python2_FIND_REGISTRY variable determines the order of preference between registry and environment variables. It can be set to one of the following:
    • FIRST: try to use the registry before environment variables. This is the default.
    • LAST: try to use the registry after environment variables.
    • NEVER: never try to use the registry.
  • Python2_FIND_FRAMEWORK โ€” Added in version 3.15. On macOS, the Python2_FIND_FRAMEWORK variable determines the order of preference between Apple-style and unix-style package components. This variable can take the same values as the CMAKE_FIND_FRAMEWORK variable.
Note: the value ONLY is not supported, so FIRST will be used instead. ok werk ๐Ÿ’…

If Python2_FIND_FRAMEWORK is not defined, the CMAKE_FIND_FRAMEWORK variable will be used, if any.

  • Python2_FIND_VIRTUALENV โ€” Added in version 3.15. This variable defines the handling of virtual environments managed by virtualenv or conda. It's only meaningful when a virtual environment is active (i.e. the activate script has been evaluated). In that case, it takes precedence over the Python2_FIND_REGISTRY and CMAKE_FIND_FRAMEWORK variables. You can set Python2_FIND_VIRTUALENV to one of the following:
    • FIRST: the virtual environment is used before any other standard paths to look up the interpreter. This is the default.
    • ONLY: only the virtual environment is used to look up the interpreter.
    • STANDARD: the virtual environment is not used to look up the interpreter, but the environment variable PATH is always considered. In this case, the variable Python2_FIND_REGISTRY (Windows) or CMAKE_FIND_FRAMEWORK (macOS) can be set with the value LAST or NEVER to preferably select the interpreter from the virtual environment.

Added in version 3.17: added support for conda environments. ๐Ÿ

Note: if the component Development is requested (or one of its sub-components) and it's not found, or the wrong artifacts come back, including the component Interpreter too may be helpful. little pro move, you're welcome โœจ
  • Python2_FIND_IMPLEMENTATIONS โ€” Added in version 3.18. This variable defines, as an ordered list, the different implementations that will be searched. Python2_FIND_IMPLEMENTATIONS can hold the following values:
    • CPython: this is the standard implementation. Various products, like Anaconda or ActivePython, rely on this implementation.
    • IronPython: this implementation uses the CSharp language for .NET Framework on top of the Dynamic Language Runtime (DLR). See IronPython at https://ironpython.net.
    • PyPy: this implementation uses the RPython language and the RPython translation toolchain to produce the python interpreter. See PyPy at https://pypy.org.

The default value is:

  • Windows platform: CPython, IronPython
  • Other platforms: CPython
Note: this hint has the lowest priority of all the hints, so even if, for example, you specify IronPython first and CPython second, a python product based on CPython can still be selected โ€” because, for example with Python2_FIND_STRATEGY=LOCATION, each location will be searched first for IronPython and second for CPython. the way that ordering is not what you think ๐Ÿ˜ญ
Note: when IronPython is specified on platforms other than Windows, the .Net interpreter (i.e. the mono command) is expected to be available through the PATH variable.
  • Python2_FIND_UNVERSIONED_NAMES โ€” Added in version 3.20. This variable defines how the generic names will be searched. Currently it only applies to the generic names of the interpreter, namely python2 and python. You can set Python2_FIND_UNVERSIONED_NAMES to one of the following values:
    • FIRST: the generic names are searched before the more specialized ones (such as python2.5, for example).
  • LAST โ€” the generic names get searched after the more specialized ones. This is the default, bestie, so if you don't touch anything, this is what you're getting. ๐Ÿ’…
  • NEVER โ€” the generic names are not searched at all. Like, zero, none, don't even look. ๐Ÿ™ˆ

Also peep Python2_FIND_STRATEGY for the full picture on this one, iykyk.


โœจ Artifacts Specification โœจ

Added in version 3.16.

Okay so sometimes stuff is extra and you just gotta skip the whole search and say "bestie, here's the artifact, take it." That's literally what this is โ€” you set these variables directly:

  • Python2_EXECUTABLE โ€” the path to the interpreter. ๐Ÿ
  • Python2_COMPILER โ€” the path to the compiler.
  • Python2_DOTNET_LAUNCHER โ€” Added in version 3.18. The .Net interpreter. Only used by the IronPython implementation.
  • Python2_LIBRARY โ€” the path to the library. It will be used to compute the variables Python2_LIBRARIES, Python2_LIBRARY_DIRS and Python2_RUNTIME_LIBRARY_DIRS.
  • Python2_INCLUDE_DIR โ€” the path to the directory of the Python headers. It will be used to compute the variable Python2_INCLUDE_DIRS.
  • Python2_NumPy_INCLUDE_DIR โ€” the path to the directory of the NumPy headers. It will be used to compute the variable Python2_NumPy_INCLUDE_DIRS.
Note: all paths must be absolute. Any artifact specified with a relative path will be, like, completely ignored. No cap. ๐Ÿšซ
Note: when an artifact is specified, all HINTS will be ignored and no search will be performed for this artifact. And if more than one artifact is specified, it is the user's responsibility to ensure the consistency of the various artifacts. That's on you, queen. ๐Ÿ‘‘

By default, this module supports multiple calls in different directories of a project with different version/component requirements while providing correct and consistent results for each call. To support this behavior, the CMake cache is not used in the traditional way โ€” which can be problematic for interactive specification. So, to enable also interactive specification, module behavior can be controlled with the following variable:

  • Python2_ARTIFACTS_INTERACTIVE โ€” Added in version 3.18. Selects the behavior of the module. This is a boolean variable:
    • If set to TRUE: create CMake cache entries for the above artifact specification variables so that users can edit them interactively. This disables support for multiple version/component requirements.
    • If set to FALSE or undefined: enable multiple version/component requirements.
  • Python2_ARTIFACTS_PREFIX โ€” Added in version 4.0. Defines a custom prefix which will be used for the definition of all the result variables, targets, and commands. By using this variable, this module supports multiple calls in the same directory with different version/component requirements. Like, for example, in case of cross-compilation, development components are needed but the native python interpreter can also be required:
find_package(Python2 COMPONENTS Development)

set(Python2_ARTIFACTS_PREFIX "_HOST")
find_package(Python2 COMPONENTS Interpreter)

# Here Python2_HOST_EXECUTABLE and Python2_HOST::Interpreter artifacts are defined
Note: for consistency with standard behavior of modules, the various standard _FOUND variables (i.e. without the custom prefix) are also defined by each call to the find_package() command. ๐Ÿซถ

๐Ÿ› ๏ธ Commands ๐Ÿ› ๏ธ

This module defines the command Python2_add_library (when CMAKE_ROLE is PROJECT), which has the same semantics as add_library() and adds a dependency to target Python2::Python or, when the library type is MODULE, to target Python2::Module โ€” and it takes care of Python module naming rules:

Python2_add_library (<name> [STATIC | SHARED | MODULE]
                     <source1> [<source2> ...])

If the library type is not specified, MODULE is assumed.

Added in version 3.30: for MODULE type, the DEBUG_POSTFIX target property is initialized with the value of the Python2_DEBUG_POSTFIX variable if defined. ๐Ÿ’–


๐Ÿ FindPython3 ๐Ÿ

Added in version 3.12.

Finds the Python 3 interpreter, compiler and development environment (include directories and libraries):

find_package(Python3 [<version>] [COMPONENTS <components>...] [...])

Added in version 3.19: when a version is requested, it can be specified as a simple value or as a range. For a detailed description of version range usage and capabilities, refer to the find_package() command.

The following components are supported:

  • Interpreter: search for Python 3 interpreter.
  • Compiler: search for Python 3 compiler. Only offered by IronPython.
  • Development: search for development artifacts (include directories and libraries).
    • Added in version 3.18: this component includes two sub-components which can be specified independently:
      • Development.Module: search for artifacts for Python 3 module developments.
      • Development.Embed: search for artifacts for Python 3 embedding developments.
    • Added in version 3.26:
      • Development.SABIModule: search for artifacts for Python 3 module developments using the Stable Application Binary Interface. This component is available only for version 3.2 and upper. ๐ŸŒˆ
  • Added in version 3.14:
    • NumPy: search for NumPy include directories. Specifying this component implies also the components Interpreter and Development.Module.

Changed in version 4.2: the component Development.Module is no longer implied when the policy CMP0201 is set to NEW.

If no COMPONENTS are specified, Interpreter is assumed.

If component Development is specified, it implies sub-components Development.Module and Development.Embed.

Changed in version 4.1: in a cross-compiling mode (i.e. the CMAKE_CROSSCOMPILING variable is defined to true), the following constraints, when the policy CMP0190 is set to NEW, now apply to the requested components:

  • Interpreter or Compiler alone: the host artifacts will be searched.
  • Interpreter or Compiler with Development or any sub-component: the target artifacts will be searched. In this case, the CMAKE_CROSSCOMPILING_EMULATOR variable must be defined and will be used to execute the interpreter or the compiler.

When both host and target artifacts are needed, two different calls to the find_package() command should be done. The Python_ARTIFACTS_PREFIX variable can be helpful in this situation. โœจ

To ensure consistent versions between components Interpreter, Compiler, Development (or one of its sub-components) and NumPy, specify all components at the same time:

find_package (Python3 COMPONENTS Interpreter Development)

This module looks only for version 3 of Python. This module can be used concurrently with the FindPython2 module to use both Python versions. ๐Ÿ‘ฏ

The FindPython module can be used if the Python version does not matter for you.

Note: if components Interpreter and Development (or one of its sub-components) are both specified, this module searches only for an interpreter with the same platform architecture as the one defined by the CMake configuration. This constraint does not apply if only the Interpreter component is specified. ๐Ÿงš

๐Ÿ‘‘ Imported Targets ๐Ÿ‘‘

This module provides the following Imported Targets:

Changed in version 3.14: Imported Targets are only created when CMAKE_ROLE is PROJECT.

  • Python3::Interpreter โ€” Python 3 interpreter. This target is defined only if the Interpreter component is found.
  • Python3::InterpreterDebug โ€” Added in version 3.30. Python 3 debug interpreter. This target is defined only if the Interpreter component is found and the Python3_EXECUTABLE_DEBUG variable is defined. The target is only defined on the Windows platform. ๐ŸชŸ
  • Python3::InterpreterMultiConfig โ€” Added in version 3.30. Python 3 interpreter. The release or debug version of the interpreter will be used, based on the context (platform, configuration). This target is defined only if the Interpreter component is found.
  • Python3::Compiler โ€” Python 3 compiler. This target is defined only if the Compiler component is found.
  • Python3::Module โ€” Added in version 3.15. Python 3 library for Python module. Target defined if component Development.Module is found.
  • Python3::SABIModule โ€” Added in version 3.26. Python 3 library for Python module using the Stable Application Binary Interface. Target defined if component Development.SABIModule is found. ๐Ÿ’…
  • Python3::Python โ€” Python 3 library for Python embedding. Target defined if component Development.Embed is found.
  • Python3::NumPy โ€” Added in version 3.14. NumPy library for Python 3. Target defined if component NumPy is found. Moreover, this target has the Python3::Module target as dependency.
    • Changed in version 4.2: this target does not have anymore the Python3::Module target as dependency when the policy CMP0201 is set to NEW.

๐Ÿ“Š Result Variables ๐Ÿ“Š

This module defines the following variables (see Standard Variable Names):

  • Python3_FOUND โ€” Boolean indicating whether the system has the Python 3 requested components.
  • Python3_Interpreter_FOUND โ€” Boolean indicating whether the system has the Python 3 interpreter.
  • Python3_EXECUTABLE โ€” path to the Python 3 interpreter. ๐Ÿ
  • Python3_EXECUTABLE_DEBUG โ€” Added in version 3.30. Path to the debug Python 3 interpreter. It is only defined on the Windows platform.
  • Python3_INTERPRETER โ€” Added in version 3.30. Path to the Python 3 interpreter, defined as a generator expression selecting the Python3_EXECUTABLE or Python3_EXECUTABLE_DEBUG variable based on the context (platform, configuration). โœจ
  • Python3_INTERPRETER_ID โ€” a short string unique to the interpreter. Possible values include:
    • Python
    • ActivePython
    • Anaconda
    • Canopy
    • IronPython
    • PyPy
  • Python3_FREE_THREADED โ€” Added in version 4.4.

Boolean value, which is true if the python is free threaded (i.e. config var Py_GIL_DISABLED has value 1), false otherwise. ๐Ÿงต

  • Python3_STDLIB โ€” the standard platform independent installation directory. This is literally just what sysconfig.get_path('stdlib') hands back, no cap. โœจ
  • Python3_STDARCH โ€” the standard platform dependent installation directory. Comes straight from sysconfig.get_path('platstdlib'). ๐ŸŽ€
  • Python3_SITELIB โ€” the third-party platform independent installation directory, aka sysconfig.get_path('purelib'). ๐Ÿ’–
  • Python3_SITEARCH โ€” the third-party platform dependent installation directory, aka sysconfig.get_path('platlib'). ๐Ÿฆ‹
  • Python3_SOABI โ€” Added in version 3.17. The extension suffix for modules. It's computed from sysconfig.get_config_var('EXT_SUFFIX') or sysconfig.get_config_var('SOABI') or python3-config --extension-suffix. ๐ŸŒธ
  • Python3_SOSABI โ€” Added in version 3.26. The extension suffix for modules using the Stable Application Binary Interface. Computed from importlib.machinery.EXTENSION_SUFFIXES if the COMPONENT Interpreter was specified. Otherwise the extension is abi3 or abi3t โ€” except on Windows, MSYS and CYGWIN, where it's just an empty string. ๐Ÿ’…
  • Python3_Compiler_FOUND โ€” boolean, tells you whether the system has the Python 3 compiler. ๐Ÿ™ˆ
  • Python3_COMPILER โ€” path to the Python 3 compiler. Only IronPython offers this one. ๐Ÿ”ฅ
  • Python3_COMPILER_ID โ€” a short string that's unique to the compiler. Possible values include:
    • IronPython
  • Python3_DOTNET_LAUNCHER โ€” Added in version 3.18. The .Net interpreter. Only used by the IronPython implementation. โญ
  • Python3_Development_FOUND โ€” boolean, tells you whether the system has the Python 3 development artifacts.
    • Python3_Development.Module_FOUND โ€” Added in version 3.18. Boolean, tells you whether the system has the Python 3 development artifacts for a Python module. ๐Ÿ’œ
    • Python3_Development.SABIModule_FOUND โ€” Added in version 3.26. Boolean, tells you whether the system has the Python 3 development artifacts for a Python module using the Stable Application Binary Interface. ๐ŸŒˆ
    • Python3_Development.Embed_FOUND โ€” Added in version 3.18. Boolean, tells you whether the system has the Python 3 development artifacts for Python embedding. ๐Ÿ‘‘
  • Python3_INCLUDE_DIRS โ€” the Python 3 include directories.
  • Python3_DEFINITIONS โ€” Added in version 3.30.3. The Python 3 preprocessor definitions. ๐ŸŽ€
  • Python3_DEBUG_POSTFIX โ€” Added in version 3.30. The postfix of the debug python module. You can use this variable to define the DEBUG_POSTFIX target property. โœจ
  • Python3_LINK_OPTIONS โ€” Added in version 3.19. The Python 3 link options. Heads up: some configurations genuinely need specific link options to build and execute correctly. ๐Ÿ”—
  • Python3_LIBRARIES โ€” the Python 3 libraries.
  • Python3_LIBRARY_DIRS โ€” the Python 3 library directories.
  • Python3_RUNTIME_LIBRARY_DIRS โ€” the Python 3 runtime library directories.
  • Python3_SABI_LIBRARIES โ€” Added in version 3.26. The Python 3 libraries for the Stable Application Binary Interface. ๐Ÿฆ‹
  • Python3_SABI_LIBRARY_DIRS โ€” Added in version 3.26. The Python 3 SABI library directories.
  • Python3_RUNTIME_SABI_LIBRARY_DIRS โ€” Added in version 3.26. The Python 3 runtime SABI library directories.
  • Python3_VERSION โ€” the Python 3 version.
  • Python3_VERSION_MAJOR โ€” the Python 3 major version.
  • Python3_VERSION_MINOR โ€” the Python 3 minor version.
  • Python3_VERSION_PATCH โ€” the Python 3 patch version.
  • Python3_PyPy_VERSION โ€” Added in version 3.18. The Python 3 PyPy version. ๐Ÿ’…
  • Python3_NumPy_FOUND โ€” Added in version 3.14. Boolean, tells you whether the system has NumPy. ๐Ÿ“
  • Python3_NumPy_INCLUDE_DIRS โ€” Added in version 3.14. The NumPy include directories.
  • Python3_NumPy_VERSION โ€” Added in version 3.14. The NumPy version.

โœจ Hints โœจ

  • Python3_ROOT_DIR โ€” define the root directory of a Python 3 installation. ๐Ÿ“
  • Python3_USE_STATIC_LIBS โ€” this one's a vibe check on which libraries you want:
    • If it's not defined, it searches for shared libraries and static libraries, in that order.
    • If it's set to TRUE, it searches only for static libraries.
    • If it's set to FALSE, it searches only for shared libraries.
Note: this hint gets ignored on Windows, because static libraries literally aren't available on that platform. ๐Ÿ˜ญ
  • Python3_FIND_ABI โ€” Added in version 3.16. This variable defines which ABIs โ€” as defined in PEP 3149 (https://peps.python.org/pep-3149/) โ€” should be searched. ๐Ÿ”

The Python3_FIND_ABI variable is a 4-tuple specifying, in that order, the pydebug (d), pymalloc (m), unicode (u) and gil_disabled (t) flags.

Added in version 3.30: a fourth element, specifying the gil_disabled flag (i.e. free threaded python), is added and is optional. If it's not specified, the value is OFF.

Added in version 4.4.1: the pydebug flag is now supported on Windows systems for Python 3.14+.

Each element can be set to one of these:

  • ON: the corresponding flag is selected.
  • OFF: the corresponding flag is not selected.
  • ANY: both possibilities (ON and OFF) will be searched. ๐ŸŽ€
Note: if Python3_FIND_ABI is not defined, these are the defaults that apply: - On POSIX systems: ANY, ANY, ANY, OFF. - On Windows systems: OFF, OFF, OFF, OFF.

From this 4-tuple, various ABIs get searched starting from the most specialized and going to the most general. Also, when ANY is specified for pydebug and gil_disabled, debug and free threaded versions get searched after the non-debug and non-gil-disabled ones. ๐Ÿ’ซ

For example, if we have:

set (Python3_FIND_ABI "ON" "ANY" "ANY" "ON")

The following flag combinations will be appended, in that order, to the artifact names:

  • On POSIX systems: tdmu, tdm, tdu, and td.
  • On Windows systems: tmu_d, tm_d, tu_d, and t_d.

And to search any possible ABIs:

set (Python3_FIND_ABI "ANY" "ANY" "ANY" "ANY")

The following combinations, in that order, will be used:

  • On POSIX systems: mu, m, u, <empty>, dmu, dm, du, d, tmu, tm, tu, t, tdmu, tdm, tdu, and td.
  • On Windows systems: mu, m, u, <empty>, mu_d, m_d, u_d, _d, tmu, tm, tu, t, tmu_d, tm_d, tu_d, and t_d. ๐ŸŒˆ
Note: this hint is fully usable on POSIX systems. On Windows systems, only the gil_disabled and pydebug flags are supported. And on top of that, the pydebug flag is only supported for Python 3.14+. So on Windows systems, when Python3_FIND_ABI is defined, Python distributions from python.org (https://www.python.org/) will be found only if the value for the flags pymalloc and unicode is OFF or ANY. ๐Ÿ’€
  • Python3_FIND_STRATEGY โ€” Added in version 3.15. Defines how lookup gets done. You can set Python3_FIND_STRATEGY to one of these:
    • VERSION: try to find the most recent version in all the specified locations. This is the default if policy CMP0094 is undefined or set to OLD.
    • LOCATION: stops lookup as soon as a version satisfying the version constraints is found. This is the default if policy CMP0094 is set to NEW. ๐ŸŽฏ

See also Python3_FIND_UNVERSIONED_NAMES.

  • Python3_FIND_REGISTRY โ€” Added in version 3.13. On Windows, this variable determines the order of preference between registry and environment variables. You can set it to one of these:
    • FIRST: try to use the registry before environment variables. This is the default.
    • LAST: try to use the registry after environment variables.
    • NEVER: never try to use the registry. ๐Ÿ™…โ€โ™€๏ธ
  • Python3_FIND_FRAMEWORK โ€” Added in version 3.15. On macOS, this variable determines the order of preference between Apple-style and unix-style package components. It can take the same values as the CMAKE_FIND_FRAMEWORK variable.
Note: the value ONLY is not supported, so FIRST gets used instead. ๐Ÿ™ˆ

If Python3_FIND_FRAMEWORK isn't defined, the CMAKE_FIND_FRAMEWORK variable gets used, if there is one. ๐ŸŽ

  • Python3_FIND_VIRTUALENV โ€” Added in version 3.15. This one defines the handling of virtual environments managed by virtualenv or conda. It's only meaningful when a virtual environment is active (i.e. the activate script has been evaluated). When that's the case, it takes precedence over the Python3_FIND_REGISTRY and CMAKE_FIND_FRAMEWORK variables. You can set Python3_FIND_VIRTUALENV to one of these:
    • FIRST: the virtual environment gets used before any other standard paths when looking up the interpreter. This is the default. ๐Ÿ’–
    • ONLY: only the virtual environment is used to look up the interpreter.
    • STANDARD: the virtual environment isn't used to look up the interpreter, but the environment variable PATH is always considered. In this case, the variable Python3_FIND_REGISTRY (Windows) or CMAKE_FIND_FRAMEWORK (macOS) can be set with the value LAST or NEVER to select preferably the interpreter from the virtual environment. ๐ŸŒธ

Added in version 3.17: added support for conda environments.

Note: if the component Development is requested (or one of its sub-components) and it isn't found, or the wrong artifacts get returned, including the component Interpreter as well may be helpful. ๐Ÿซถ
  • Python3_FIND_IMPLEMENTATIONS โ€” Added in version 3.18.

This variable defines, in an ordered list, the different implementations which will be searched. The Python3_FIND_IMPLEMENTATIONS variable can hold the following values:

  • CPython โ€” this is the standard implementation. Various products, like Anaconda or ActivePython, rely on this implementation. ๐Ÿ’–
  • IronPython โ€” This implementation use the CSharp language for .NET Framework on top of the Dynamic Language Runtime (DLR). See IronPython <https://ironpython.net>. ๐Ÿฆ‹
  • PyPy โ€” This implementation use RPython language and RPython translation toolchain to produce the python interpreter. See PyPy <https://pypy.org>. ๐ŸŒธ

The default value is:

  • Windows platform: CPython, IronPython ๐ŸŽ€
  • Other platforms: CPython โœจ
Note: This hint has the lowest priority of all hints, so even if, for example, you specify IronPython first and CPython in second, a python product based on CPython can be selected because, for example with Python3_FIND_STRATEGY=LOCATION, each location will be search first for IronPython and second for CPython. ๐Ÿ’€ like, it's a hint, bestie, not a command, okay??
Note: When IronPython is specified, on platforms other than Windows, the .Net interpreter (i.e. mono command) is expected to be available through the PATH variable. ๐Ÿซถ

Python3_FIND_UNVERSIONED_NAMES โ€” Added in version 3.20.

This variable defines how the generic names will be searched. Currently, it only applies to the generic names of the interpreter, namely, python3 and python. The Python3_FIND_UNVERSIONED_NAMES variable can be set to one of the following values:

  • FIRST โ€” The generic names are searched before the more specialized ones (such as python3.5 for example). ๐Ÿ”ฅ
  • LAST โ€” The generic names are searched after the more specialized ones. This is the default. ๐Ÿ‘‘
  • NEVER โ€” The generic name are not searched at all. ๐Ÿ™ˆ

See also Python3_FIND_STRATEGY. ๐ŸŒˆ


โœจ Artifacts Specification โœจ

Added in version 3.16.

To solve special cases, it is possible to specify directly the artifacts by setting the following variables:

  • Python3_EXECUTABLE โ€” The path to the interpreter. ๐Ÿงš
  • Python3_COMPILER โ€” The path to the compiler. ๐Ÿ’…
  • Python3_DOTNET_LAUNCHER โ€” Added in version 3.18. The .Net interpreter. Only used by IronPython implementation. ๐Ÿฆ‹
  • Python3_LIBRARY โ€” The path to the library. It will be used to compute the variables Python3_LIBRARIES, Python3_LIBRARY_DIRS and Python3_RUNTIME_LIBRARY_DIRS. ๐Ÿ’–
  • Python3_SABI_LIBRARY โ€” Added in version 3.26. The path to the library for Stable Application Binary Interface. It will be used to compute the variables Python3_SABI_LIBRARIES, Python3_SABI_LIBRARY_DIRS and Python3_RUNTIME_SABI_LIBRARY_DIRS. โญ
  • Python3_INCLUDE_DIR โ€” The path to the directory of the Python headers. It will be used to compute the variable Python3_INCLUDE_DIRS. ๐ŸŒธ
  • Python3_NumPy_INCLUDE_DIR โ€” The path to the directory of the NumPy headers. It will be used to compute the variable Python3_NumPy_INCLUDE_DIRS. ๐Ÿ“
Note: All paths must be absolute. Any artifact specified with a relative path will be ignored. no cap, it will simply not see it ๐Ÿ˜ญ
Note: When an artifact is specified, all HINTS will be ignored and no search will be performed for this artifact. If more than one artifact is specified, it is the user's responsibility to ensure the consistency of the various artifacts. ๐Ÿ‘‘ that's on you, bestie

By default, this module supports multiple calls in different directories of a project with different version/component requirements while providing correct and consistent results for each call. To support this behavior, CMake cache is not used in the traditional way which can be problematic for interactive specification. So, to enable also interactive specification, module behavior can be controlled with the following variable:

Python3_ARTIFACTS_INTERACTIVE โ€” Added in version 3.18.

Selects the behavior of the module. This is a boolean variable:

  • If set to TRUE: Create CMake cache entries for the above artifact specification variables so that users can edit them interactively. This disables support for multiple version/component requirements. ๐ŸŽ€
  • If set to FALSE or undefined: Enable multiple version/component requirements. โœจ

Python3_ARTIFACTS_PREFIX โ€” Added in version 4.0.

Define a custom prefix which will be used for the definition of all the result variables, targets, and commands. By using this variable, this module supports multiple calls in the same directory with different version/component requirements. For example, in case of cross-compilation, development components are needed but the native python interpreter can also be required:

find_package(Python3 COMPONENTS Development)

set(Python3_ARTIFACTS_PREFIX "_HOST")
find_package(Python3 COMPONENTS Interpreter)

# Here Python3_HOST_EXECUTABLE and Python3_HOST::Interpreter artifacts are defined
Note: For consistency with standard behavior of modules, the various standard _FOUND variables (i.e. without the custom prefix) are also defined by each call to the find_package() command. ๐Ÿ’œ

๐ŸŽ€ Commands ๐ŸŽ€

This module defines the command Python3_add_library (when CMAKE_ROLE is PROJECT), which has the same semantics as add_library() and adds a dependency to target Python3::Python or, when library type is MODULE, to target Python3::Module or Python3::SABIModule (when USE_SABI option is specified) and takes care of Python module naming rules:

Python3_add_library (<name> [STATIC | SHARED | MODULE [USE_SABI <version>] [WITH_SOABI]]
                     <source1> [<source2> ...])

If the library type is not specified, MODULE is assumed. ๐Ÿซถ

Added in version 3.17: For MODULE library type, if option WITH_SOABI is specified, the module suffix will include the Python3_SOABI value, if any.

Added in version 3.26: For MODULE type, if the option USE_SABI is specified, the preprocessor definition Py_LIMITED_API will be specified, as PRIVATE, for the target <name> with the value computed from <version> argument. The expected format for <version> is major[.minor], where each component is a numeric value. If minor component is specified, the version should be, at least, 3.2 which is the version where the Stable Application Binary Interface <https://docs.python.org/3/c-api/stable.html> was introduced. Specifying only major version 3 is equivalent to 3.2. ๐Ÿค“

Changed in version 4.4: When USE_SABI is specified, if Python3_FREE_THREADED is true and Python version is 3.15 or upper, Py_TARGET_ABI3T preprocessor definition will be defined rather than Py_LIMITED_API (see PEP 803 <https://peps.python.org/pep-0803/> for more details). ๐Ÿ’€

When option WITH_SOABI is also specified, the module suffix will include the Python3_SOSABI value, if any.

Added in version 3.30: For MODULE type, the DEBUG_POSTFIX target property is initialized with the value of Python3_DEBUG_POSTFIX variable if defined. ๐ŸŒŸ


๐ŸŒˆ FindQt3 ๐ŸŒˆ

Finds Qt3, a cross-platform application development framework for creating graphical user interfaces and applications:

find_package(Qt3 [<version>] [...])
Note: This module is for Qt version 3. As of Qt version 5, the Qt upstream also provides an exported configuration to find Qt. New code should follow the cmake-qt(7) instead of using this module. ๐Ÿ‘‘ like, she's iconic but she's retired, bestie

๐Ÿ’… Result Variables ๐Ÿ’…

This module defines the following variables:

  • Qt3_FOUND โ€” Added in version 3.3. Boolean indicating whether (the requested version of) Qt3 was found. โœจ
  • QT_FOUND โ€” Same as Qt3_FOUND. Boolean indicating whether (the requested version of) Qt3 was found. This variable is provided for compatibility with other Qt find modules. ๐Ÿฆ‹
  • Qt3_VERSION โ€” Added in version 4.2. The version of Qt3 that was found. ๐Ÿ’–
  • QT_LIBRARIES โ€” Libraries needed to link against for using Qt3. ๐Ÿ”ฅ
  • QT_DEFINITIONS โ€” A list of compile definitions to use when compiling code that uses Qt3. ๐ŸŒธ

๐ŸŽ€ Cache Variables ๐ŸŽ€

The following cache variables may also be set:

  • QT_INCLUDE_DIR โ€” The directory containing qt.h and other Qt3 header files. ๐Ÿ“

The following cache variables may also be set but are not meant for general use:

  • QT_MOC_EXECUTABLE โ€” Path to the moc tool. ๐Ÿงš
  • QT_UIC_EXECUTABLE โ€” Path to the uic tool. ๐Ÿงš
  • QT_QT_LIBRARY โ€” Path to the Qt3 library. โญ
  • QT_QTMAIN_LIBRARY โ€” Path to the qtmain library. This is only required by Qt3 on Windows. ๐Ÿ™ˆ

๐Ÿ’œ Hints ๐Ÿ’œ

  • QT_MT_REQUIRED โ€” To search for the multithreaded version of Qt3, set this variable to TRUE before looking for Qt3. ๐Ÿซถ

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

The following variables are provided for backward compatibility:

  • QT_VERSION_STRING โ€” Deprecated since version 4.2: Use Qt3_VERSION, which has the same value. The version of Qt3 that was found. ๐Ÿ˜ญ

โญ Examples โญ

Finding Qt3 on the system:

find_package(Qt3)
if(Qt3_FOUND)
  target_link_libraries(foo PRIVATE ${QT_LIBRARIES})
  target_include_directories(foo PRIVATE ${QT_INCLUDE_DIR})
  target_compile_definitions(foo PRIVATE ${QT_DEFINITIONS})
endif()

Looking for the multithreaded version of Qt3:

set(QT_MT_REQUIRED TRUE)
find_package(Qt3)

๐ŸŒธ FindQt4 ๐ŸŒธ

Finds Qt4, a cross-platform application development framework for creating graphical user interfaces and applications:

find_package(Qt4 [<version>] [...])

This module defines a number of imported targets, macros, and variables to use Qt4 in the project. โœจ

Note: This module is for Qt version 4. As of Qt version 5, the Qt upstream also provides an exported configuration to find Qt. New code should follow the cmake-qt(7) instead of using this module. ๐ŸŽ€

To detect the Qt4 package, the Qt4 qmake tool is required and must be available in the system path. ๐Ÿ’…

Note: When you're using Imported Targets, the qtmain.lib static library gets linked automatically on Windows for WIN32 executables (that's the WIN32_EXECUTABLE target property btw). Wanna kill it for the whole project? Set the QT4_NO_LINK_QTMAIN variable before you find Qt4. Wanna kill it for just one executable? Set the QT4_NO_LINK_QTMAIN target property to TRUE on that executable. Easy ๐Ÿ’…

๐Ÿ› ๏ธ Qt Build Tools ๐Ÿ› ๏ธ

Qt lowkey relies on some bundled tools for code generation, and they are so iconic:

  • moc โ€” meta-object code generation, the moment โœจ
  • uic โ€” widget layout and population ๐ŸŽ€
  • rcc โ€” virtual filesystem content generation ๐Ÿฆ‹

These tools may get automatically invoked by cmake(1) if the right conditions are met. Peep cmake-qt(7) for more, bestie.

๐Ÿ”— Imported Targets ๐Ÿ”—

You can link Qt libraries using their corresponding Imported Target with the target_link_libraries() command:

target_link_libraries(myexe Qt4::QtGui Qt4::QtXml)

The way that linking to an imported target automatically applies the correct include directories and compile definitions when building myexe?? Obsessed. ๐Ÿซถ

Imported targets also manage their own dependencies, so listing Qt4::QtCore is literally unnecessary if another Qt library already depends on it. Likewise, Qt4::QtGui is automatically included when you link Qt4::QtDeclarative. And you can vibe-check whether a target exists with the if(TARGET) command ๐Ÿ‘‘

If both the debug and release versions of a Qt toolkit library are available, CMake selects the appropriate one based on the build configuration. Bestie behavior fr fr.

This module provides the following imported targets, if found:

  • Qt4::QtCore โ€” The QtCore target
  • Qt4::QtGui โ€” The QtGui target
  • Qt4::Qt3Support โ€” The Qt3Support target
  • Qt4::QtAssistant โ€” The QtAssistant target
  • Qt4::QtAssistantClient โ€” The QtAssistantClient target
  • Qt4::QAxContainer โ€” The QAxContainer target (Windows only)
  • Qt4::QAxServer โ€” The QAxServer target (Windows only)
  • Qt4::QtDBus โ€” The QtDBus target
  • Qt4::QtDeclarative โ€” The QtDeclarative target
  • Qt4::QtDesigner โ€” The QtDesigner target
  • Qt4::QtDesignerComponents โ€” The QtDesignerComponents target
  • Qt4::QtHelp โ€” The QtHelp target
  • Qt4::QtMotif โ€” The QtMotif target
  • Qt4::QtMultimedia โ€” The QtMultimedia target
  • Qt4::QtNetwork โ€” The QtNetwork target
  • Qt4::QtNsPlugin โ€” The QtNsPlugin target
  • Qt4::QtOpenGL โ€” The QtOpenGL target
  • Qt4::QtScript โ€” The QtScript target
  • Qt4::QtScriptTools โ€” The QtScriptTools target
  • Qt4::QtSql โ€” The QtSql target
  • Qt4::QtSvg โ€” The QtSvg target
  • Qt4::QtTest โ€” The QtTest target
  • Qt4::QtUiTools โ€” The QtUiTools target
  • Qt4::QtWebKit โ€” The QtWebKit target
  • Qt4::QtXml โ€” The QtXml target
  • Qt4::QtXmlPatterns โ€” The QtXmlPatterns target
  • Qt4::phonon โ€” The phonon target

๐Ÿ“Š Result Variables ๐Ÿ“Š

This module defines the following variables, and yes you should absolutely check them:

  • Qt4_FOUND โ€” Boolean indicating whether (the requested version of) Qt4 was found. ๐Ÿ‘‘
  • QT_FOUND โ€” Same as Qt4_FOUND. Boolean indicating whether (the requested version of) Qt4 was found. This variable is available for compatibility with other Qt find modules.
  • QT_VERSION_MAJOR โ€” The major version of Qt found.
  • QT_VERSION_MINOR โ€” The minor version of Qt found.
  • QT_VERSION_PATCH โ€” The patch version of Qt found.

๐Ÿ’ก Hints ๐Ÿ’ก

  • QT4_NO_LINK_QTMAIN โ€” If set to boolean true before finding Qt4, it globally disables linking the qtmain.lib static library on Windows. Periodt.

๐Ÿงš Macros ๐Ÿงš

Sometimes it's necessary or useful to invoke the Qt build tools in a more-manual way โ€” like, hand-crafted, artisanal build rules ๐Ÿ˜Œ. This module provides the following macros to add targets for such uses:

qt4_wrap_cpp

Creates build rules for running moc on a given list of input files:

qt4_wrap_cpp(<variable> <files>... [TARGET <target>] [OPTIONS <options>...])

This macro creates build rules for processing a list of input files <files> that contain Qt classes with the Q_OBJECT declaration. Per-directory preprocessor definitions are also added.

  • <variable> โ€” Name of a variable where a list of generated output files is stored.
  • <files> โ€” One or more input source files.
  • TARGET โ€” If specified, the INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS target properties from the <target> are passed to moc.
  • OPTIONS โ€” Optional list of options given to moc, such as those found when executing moc -help.
Note: Instead of using qt4_wrap_cpp(), the CMAKE_AUTOMOC variable can be set to process source files with moc automatically. Let the machine do the work, bestie ๐Ÿ’…

qt4_wrap_ui

Creates build rules for running uic on a given list of Qt designer ui input files:

qt4_wrap_ui(<variable> <files>... [OPTIONS <options>...])
  • <variable> โ€” Name of a variable where a list of generated output filenames is stored.
  • <files> โ€” One or more Qt designer ui input source files.
  • OPTIONS โ€” Optional list of options given to uic, such as those found when executing uic -help.
Note: Instead of using qt4_wrap_ui(), the CMAKE_AUTOUIC variable can be set to process ui files with uic automatically. So slay ๐ŸŽ€

qt4_add_resources

Creates build rules for running rcc on a given list of input Qt resource files:

qt4_add_resources(<variable> <files>... [OPTIONS <options>...])
  • <variable> โ€” Name of a variable where a list of generated output filenames is stored.
  • <files> โ€” One or more Qt resource input source files.
  • OPTIONS โ€” Optional list of options given to rcc, such as those found when executing rcc -help.
Note: Instead of using qt4_add_resources(), the CMAKE_AUTORCC variable can be set to process resource files with rcc automatically. Iykyk ๐ŸŒˆ

qt4_generate_moc

Creates a build rule that generates an output file by running moc on a given input file:

qt4_generate_moc(<input-file> <output-file> [TARGET <target>])

This macro creates a build rule for <input-file> to generate <output-file>. Use this if for some reason qt4_wrap_cpp() isn't feasible โ€” like, e.g. because a custom filename is needed for the moc file or similar. No judgment ๐Ÿซถ

  • TARGET โ€” If specified, the INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS target properties from the <target> are passed to moc.

qt4_add_dbus_interface

Creates the interface header and implementation files from an interface XML file:

qt4_add_dbus_interface(<variable> <interface-file> <basename>)

This macro creates the interface header (<basename>.h) and implementation files (<basename>.{cpp,moc}) from the given interface XML file <interface-file> and adds it to the variable which contains a list of sources (specified as variable name <variable>).

You can pass additional parameters to the qdbusxml2cpp call by setting the following source file properties on the input file <interface-file>:

  • INCLUDE โ€” The given file will be included in the generated interface header.
  • CLASSNAME โ€” The name of the generated class.
  • NO_NAMESPACE โ€” The generated class will not be wrapped in a namespace.

qt4_add_dbus_interfaces

Creates the interface header and implementation files from multiple interface XML files:

qt4_add_dbus_interfaces(<variable> <interface-files>...)

This macro creates the interface header and implementation files for all listed interface XML files <interface-files>. The basename will be automatically determined from the name of the XML file. The resulting output files list is stored in a variable <variable>.

The source file properties described for qt4_add_dbus_interface() also apply here. Same energy, batch mode โœจ


qt4_add_dbus_adaptor

Generates an adaptor class for a D-Bus interface:

qt4_add_dbus_adaptor(<variable> <xmlfile> <parent-header> <parent-classname>
                     [<basename>] [<classname>])

Creates a D-Bus adaptor (header and implementation file) from the XML file describing the interface, and adds it to the list of sources. The adaptor forwards the calls to a parent class, defined in <parent-header> and named <parent-classname>. The generated filenames will be <basename>adaptor.{cpp,h} where <basename> defaults to the basename of the XML file if not given. If <classname> is provided, then it will be used as the classname of the adaptor itself. Generated filenames are stored in a variable <variable>.


qt4_generate_dbus_interface

Generates a D-Bus XML interface file from a given header file:

qt4_generate_dbus_interface(<header> [<interface>] [OPTIONS <options>...])

This macro creates a build rule to extract declaration from the given <header> file to generate a corresponding XML interface file.

  • <header> โ€” Path to header file from which the XML interface file is generated.
  • <interface> โ€” Path to the generated XML interface file. If this optional argument is omitted, the name of the interface file is constructed from the basename of the header with the suffix .xml appended. A relative path is interpreted as relative to CMAKE_CURRENT_BINARY_DIR.
  • OPTIONS โ€” A list of options that may be given to qdbuscpp2xml, such as those found when executing qdbuscpp2xml --help.

qt4_create_translation

Creates build rules for generating TS and QM files:

qt4_create_translation(<qm-files-var> <directories>... <sources>...
                       <ts-files>... [OPTIONS <options>...])

Okay so that one's got a lot going on and we're gonna get into it right after this ๐Ÿ’œ

This macro is basically the โœจtranslation factoryโœจ โ€” it creates build rules that generate TS (Translation Source, .ts) files via lupdate and QM (Qt Message, .qm) files via lrelease, all from the <directories> and/or <sources> you hand it. The TS files get created and/or updated in the source tree (unless you gave full paths). The QM files are generated in the build tree. ๐ŸŽ€

  • <qm-files-var> โ€” the list of generated QM files gets stashed in this variable. Want your translations updated? Either add <qm-files-var> to the source list of the project library/executable so they're always updated, or add a custom target to control when they get updated/generated. You've got options, bestie. ๐Ÿ’…
  • <directories> โ€” a list of directories containing source files.
  • <sources> โ€” a list of source files.
  • <ts-files> โ€” a list of TS (Translation Source) files.

OPTIONS

Optional list of flags passed straight through to lupdate, such as -extensions, to specify file extensions for directory scanning. ๐Ÿฆ‹

qt4_add_translation

Creates build rules for generating QM files from the given TS files:

qt4_add_translation(<qm-files-var> <ts-files>...)

This macro creates build rules for generating QM files from the given TS files, and it stores a list of the generated filenames of QM files in the <qm-files-var> variable. Heads up though: the <ts-files> must exist and are not updated in any way. No cap, it will not touch them. ๐Ÿ™ˆ

qt4_automoc

Deprecated since version 2.8.11: Use feature provided by the CMAKE_AUTOMOC variable instead. ๐Ÿ˜ญ

Runs moc on input files:

qt4_automoc(<source-files>... [TARGET <target>])

This macro can be used to have moc automatically handled. For example, if there are foo.h and foo.cpp files, and in foo.h a class uses the Q_OBJECT preprocessor macro, moc has to run on it. If using qt4_wrap_cpp() isn't wanted (however, it is reliable and mature, just saying ๐Ÿ‘‘), the #include "foo.moc" can be inserted in foo.cpp and then foo.cpp given as an argument to qt4_automoc(). This will scan all listed files <source-files> at configuration phase for such included moc files, and if it finds them, a rule is generated to run moc at build time on the accompanying header file foo.h. If a source file has the SKIP_AUTOMOC property set, that file will be ignored by this macro.

TARGET โ€” If specified, the INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS target properties from the <target> are passed to moc.

qt4_use_modules

Deprecated since version 2.8.11: Use target_link_libraries() with Imported Targets instead. ๐Ÿ’€

Provides Qt modules to a project so you can link them to a target:

qt4_use_modules(<target> [<LINK_PUBLIC|LINK_PRIVATE>] <modules>...)

This function makes <target> use the <modules> from Qt. Using a Qt module means linking to the library, adding the relevant include directories for the module, and adding the relevant compiler defines for using the module. Modules are roughly equivalent to Qt4 components. Slay. โญ

LINK_PUBLIC or LINK_PRIVATE โ€” Optional linking mode, used as the corresponding argument in the target_link_libraries() call.

For example, calling qt4_use_modules(myexe Core Gui Declarative) will use the QtCore, QtGui and QtDeclarative components on the project target myexe.

Deprecated Variables

The following variables are provided for backward compatibility:

QT4_FOUND

Deprecated since version 2.8.11: Use Qt4_FOUND, which has the same value. ๐Ÿซถ

Examples

Typical usage to find Qt4 could be something like:

set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
find_package(Qt4 4.4.3 REQUIRED QtGui QtXml)
add_executable(myexe main.cpp)
target_link_libraries(myexe PRIVATE Qt4::QtGui Qt4::QtXml)

FindQuickTime

Finds the QuickTime multimedia framework, which provides support for video, audio, and interactive media:

find_package(QuickTime [...])
Note: This module is for the QuickTime framework, which has been deprecated by Apple and is no longer supported. On Apple systems, use AVFoundation and AVKit instead. ๐Ÿ’€ Not me finding out the framework itself is retired...

Result Variables

This module defines the following variables:

QuickTime_FOUND

Added in version 3.3.

Boolean indicating whether QuickTime was found. โœจ

Cache Variables

The following cache variables may also be set:

QUICKTIME_LIBRARY โ€” The path to the QuickTime library.

QUICKTIME_INCLUDE_DIR โ€” Directory containing QuickTime headers. ๐Ÿ’–

Hints

This module accepts the following variables:

QUICKTIME_DIR โ€” Environment variable that can be set to help locate a QuickTime library installed in a custom location. It should point to the installation destination that was used when configuring, building, and installing the QuickTime library:

./configure --prefix=$QUICKTIME_DIR

Deprecated Variables

The following variables are provided for backward compatibility:

QUICKTIME_FOUND

Deprecated since version 4.2: Use QuickTime_FOUND, which has the same value. ๐Ÿ˜ญ

Boolean indicating whether QuickTime was found.

Examples

Finding the QuickTime library and creating an imported interface target for linking it to a project target:

find_package(QuickTime)

if(QuickTime_FOUND AND NOT TARGET QuickTime::QuickTime)
  add_library(QuickTime::QuickTime INTERFACE IMPORTED)
  set_target_properties(
    QuickTime::QuickTime
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${QUICKTIME_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${QUICKTIME_LIBRARY}"
  )
endif()

target_link_libraries(example PRIVATE QuickTime::QuickTime)

FindRTI

Finds HLA RTI standard libraries and their include directories:

find_package(RTI [...])

RTI (Run-Time Infrastructure) is a simulation infrastructure standardized by IEEE and SISO, and it's required when implementing HLA (High Level Architecture). The wiki vibes live at https://en.wikipedia.org/wiki/Run-time_infrastructure_(simulation) iykyk. It provides a well-defined C++ API, which ensures that M&S (Modeling and Simulation) applications remain independent of any particular RTI implementation. It's giving "plug and play but for simulations". ๐Ÿงš

Result Variables

This module defines the following variables:

RTI_FOUND โ€” Boolean indicating whether HLA RTI was found.

RTI_LIBRARIES โ€” The libraries to link against to use RTI.

RTI_DEFINITIONS โ€” Compile definitions for using RTI. Default value is set to -DRTI_USES_STD_FSTREAM. ๐Ÿ”ฅ

Cache Variables

The following cache variables may also be set:

RTI_INCLUDE_DIR โ€” Directory where RTI include files are found.

Examples

Finding RTI and creating an imported interface target for linking it to a project target:

find_package(RTI)

if(RTI_FOUND AND NOT TARGET RTI::RTI)
  add_library(RTI::RTI INTERFACE IMPORTED)
  set_target_properties(
    RTI::RTI
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${RTI_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${RTI_LIBRARIES}"
      INTERFACE_COMPILE_DEFINITIONS "${RTI_DEFINITIONS}"
  )
endif()

target_link_libraries(example PRIVATE RTI::RTI)

FindRuby

Finds the Ruby installation and the locations of its include files and libraries:

find_package(Ruby [<version>] [COMPONENTS <components>...] [...])

Ruby is a general-purpose programming language (and a whole personality, honestly ๐Ÿ’Ž). This module supports Ruby 2.0 through 4.0. Virtual environments, such as RVM or RBENV, are also supported. ๐ŸŽ€

Components

Added in version 4.3.

This module supports the following components:

Interpreter โ€” The Ruby interpreter executable.

Development โ€” Headers and libraries needed to build Ruby extensions or embed Ruby.

If no components are specified, both Interpreter and Development are searched for. FOMO avoided. ๐Ÿ’…

Imported Targets

Added in version 4.3.

This module defines the following IMPORTED targets:

Ruby::Interpreter โ€” Ruby interpreter. Target defined if component Interpreter is found.

Ruby::Ruby โ€” Ruby library for embedding Ruby in C/C++ applications. Target defined if component Development is found.

Ruby::Module โ€” Ruby library for building Ruby extension modules. Target defined if component Development is found. Use this target when creating native extensions that will be loaded into Ruby via require. On most platforms, extension modules do not link directly to libruby. Includes appropriate symbol visibility settings. ๐Ÿฆ‹

Result Variables

This module defines the following variables:

Ruby_FOUND

Added in version 3.3.

Boolean indicating whether (the requested version of) ruby was found.

Ruby_VERSION โ€” The version of ruby which was found, e.g. 3.2.6.

Ruby_VERSION_MAJOR โ€” Ruby major version.

Ruby_VERSION_MINOR โ€” Ruby minor version.

Ruby_VERSION_PATCH โ€” Ruby patch version. ๐Ÿ“

Ruby_EXECUTABLE โ€” The full path to the ruby binary.

Ruby_INCLUDE_DIRS โ€” Include dirs to be used when using the ruby library.

Ruby_LIBRARIES

Added in version 3.18.

Libraries needed to use ruby from C.

Changed in version 3.18: Previous versions of CMake used the RUBY_ prefix for all variables. ๐Ÿ˜ญ So if you're on an old version, that's why nothing matches, bestie.

Hints

This module accepts the following variables:

Ruby_FIND_VIRTUALENV

Added in version 3.18.

This variable defines the handling of virtual environments. It can be left empty or be set to one of the following values:

  • FIRST: Virtual Ruby environments are searched for first, then the system Ruby installation. This is the default.
  • ONLY: Only virtual environments are searched.
  • STANDARD: Only the system Ruby installation is searched.

Virtual environments may be provided by:

  • rvm โ€” Requires that the MY_RUBY_HOME environment is defined.
  • rbenv โ€” Requires that rbenv is installed in ~/.rbenv/bin or that the RBENV_ROOT environment variable is defined. ๐ŸŒˆ

Deprecated Variables

The following variables are provided for backward compatibility:

Deprecated since version 4.0: bestie, these variables are deprecated. See policy CMP0185.

  • RUBY_FOUND โ€” literally the same thing as Ruby_FOUND.
  • RUBY_VERSION โ€” same as Ruby_VERSION.
  • RUBY_EXECUTABLE โ€” same as Ruby_EXECUTABLE.
  • RUBY_INCLUDE_DIRS โ€” same as Ruby_INCLUDE_DIRS.
  • RUBY_INCLUDE_PATH โ€” same as Ruby_INCLUDE_DIRS.
  • RUBY_LIBRARY โ€” same as Ruby_LIBRARY.

โœจ Examples โœจ

Finding Ruby and specifying the minimum required version, no cap:

find_package(Ruby 3.2.6 EXACT REQUIRED)
# or
find_package(Ruby 3.2)

๐ŸŒˆ FindSDL ๐ŸŒˆ

Finds the SDL (Simple DirectMedia Layer) library:

find_package(SDL [<version>] [...])

SDL is that iconic cross-platform library for building multimedia software โ€” games, emulators, the whole vibe. ๐ŸŽฎ

Note: this module is specifically intended for SDL version 1. Starting with version 2, SDL ships a CMake package configuration file when it's built with CMake, so you should find it with find_package(SDL2) instead. Similarly, SDL version 3 can be found with find_package(SDL3). Those newer versions give you separate Imported Targets that bundle up all the usage requirements. Check the official SDL documentation for more info. ๐Ÿ’…

Also lowkey important: the include path for the SDL header changed in recent SDL 1 versions โ€” it went from SDL/SDL.h to just plain SDL.h. That change matches SDL's whole convention of using #include "SDL.h" for portability, because not every system installs the headers in an SDL/ subdirectory (FreeBSD, looking at you ๐Ÿ‘€).

When you're targeting macOS and using the SDL framework, make sure you include both SDLmain.h and SDLmain.m in the project. On other platforms, the SDLmain library is usually linked with -lSDLmain, and this module will try to locate it automatically for you. And on macOS specifically, this module adds the -framework Cocoa flag as needed.

๐Ÿ‘‘ Imported Targets

This module serves up the following Imported Targets:

  • SDL::SDL โ€” Added in version 3.19. The target that encapsulates the SDL library usage requirements, available if SDL is found. ๐Ÿซถ

๐Ÿฆ‹ Result Variables

This module defines these variables:

  • SDL_FOUND โ€” boolean, tells you whether (the requested version of) SDL was found.
  • SDL_VERSION โ€” Added in version 3.19. The human-readable string containing the version of SDL that was found.
  • SDL_VERSION_MAJOR โ€” Added in version 3.19. The major version of SDL that was found.
  • SDL_VERSION_MINOR โ€” Added in version 3.19. The minor version of SDL that was found.
  • SDL_VERSION_PATCH โ€” Added in version 3.19. The patch version of SDL that was found.
  • SDL_INCLUDE_DIRS โ€” Added in version 3.19. The include directories you need to actually use SDL.
  • SDL_LIBRARIES โ€” Added in version 3.19. The libraries you need to link against to use SDL.

๐ŸŒธ Cache Variables

You can optionally set these to help the module find the right files:

  • SDL_INCLUDE_DIR โ€” the directory that contains the SDL.h header file.
  • SDL_LIBRARY โ€” a list of libraries containing the path to the SDL library plus the libraries needed to link against to use SDL.

๐Ÿ’œ Hints

This module accepts these variables:

  • SDL_BUILDING_LIBRARY โ€” when you set this to boolean true, the SDL_main library gets excluded from linking, because you don't need it when you're building the SDL library itself (only applications need a main() function, bestie). If it's not set, the module assumes you're building an application and tries to locate and include the appropriate SDL_main link flags in the returned SDL_LIBRARY variable.
  • SDLDIR โ€” an environment variable you can set to help locate an SDL library installed in a custom location. It should point to the installation destination that was used when configuring, building and installing the SDL library: ./configure --prefix=$SDLDIR.

On macOS, setting this variable will prefer the Framework version (if one's found) over the others. In that case you'd have to manually change the cache value of SDL_LIBRARY to override that selection, or set the CMAKE_INCLUDE_PATH variable to modify the search paths. ๐Ÿ™ˆ

๐Ÿ”ฅ Troubleshooting

If the SDL library doesn't get found automatically, the SDL_LIBRARY_TEMP variable may be empty, and SDL_LIBRARY won't be set. That typically means CMake couldn't locate the SDL library at all (think SDL.dll, libSDL.so, SDL.framework, etc.). To fix it, manually set SDL_LIBRARY_TEMP to the correct path and reconfigure the project. Same energy with SDLMAIN_LIBRARY โ€” if it's unset, you may need to specify it manually too. These variables are what get used to construct the final SDL_LIBRARY value, so if they're not set, SDL_LIBRARY just stays undefined. ๐Ÿ˜ญ

๐Ÿ“ Deprecated Variables

These are here purely for backward compatibility:

  • SDL_VERSION_STRING โ€” Deprecated since version 3.19: superseded by SDL_VERSION, which has the same value. The human-readable string containing the version of SDL if it was found.

โญ Examples โญ

Finding the SDL library and linking it to a project target:

find_package(SDL)
target_link_libraries(project_target PRIVATE SDL::SDL)

When you're working with SDL version 2, the upstream package provides the SDL2::SDL2 imported target directly, so you can use it in a project without touching this module at all:

find_package(SDL2)
target_link_libraries(project_target PRIVATE SDL2::SDL2)

And same for SDL version 3, obviously:

find_package(SDL3)
target_link_libraries(project_target PRIVATE SDL3::SDL3)

๐Ÿ’ซ See Also

  • The FindSDL_gfx module, for finding the SDL_gfx library. ๐ŸŽจ
  • The FindSDL_image module, for finding the SDL_image library. ๐Ÿ–ผ๏ธ
  • The FindSDL_mixer module, for finding the SDL_mixer library. ๐ŸŽต
  • The FindSDL_net module, for finding the SDL_net library. ๐ŸŒ
  • The FindSDL_sound module, for finding the SDL_sound library. ๐Ÿ”Š
  • The FindSDL_ttf module, for finding the SDL_ttf library. ๐Ÿ”ค

๐Ÿงš FindSDL_gfx ๐Ÿงš

Added in version 3.25.

Finds the SDL_gfx library, the one that provides graphics support in SDL (Simple DirectMedia Layer) applications:

find_package(SDL_gfx [<version>] [...])
Note: this module is for SDL_gfx version 1. If you're on version 2 or newer, refer to the upstream documentation instead. ๐Ÿ’…

๐Ÿ‘‘ Imported Targets

  • SDL::SDL_gfx โ€” the target that encapsulates the SDL_gfx library usage requirements, available if SDL_gfx is found.

๐Ÿฆ‹ Result Variables

  • SDL_gfx_FOUND โ€” boolean, tells you whether the (requested version of the) SDL_gfx library was found.
  • SDL_gfx_VERSION โ€” Added in version 4.2. The human-readable string containing the version of SDL_gfx that was found.

๐ŸŒธ Cache Variables

These cache variables may also be set:

  • SDL_GFX_INCLUDE_DIRS โ€” the directory containing the headers you need to use SDL_gfx.
  • SDL_GFX_LIBRARIES โ€” the path to the SDL_gfx library you need to link against to use SDL_gfx.

๐Ÿ’œ Hints

  • SDLDIR โ€” an environment variable you can set to help locate an SDL library installed in a custom location. It should point to the installation destination that was used when configuring, building and installing the SDL library: ./configure --prefix=$SDLDIR.

๐Ÿ“ Deprecated Variables

For backward compatibility only, bestie:

  • SDL_GFX_FOUND โ€” Deprecated since version 4.2: use SDL_gfx_FOUND, which has the same value. Boolean indicating whether the (requested version of the) SDL_gfx library was found.
  • SDL_GFX_VERSION_STRING โ€” Deprecated since version 4.2: use SDL_gfx_VERSION. The human-readable string containing the version of SDL_gfx that was found.

โญ Examples โญ

Finding the SDL_gfx library and linking it to a project target:

find_package(SDL_gfx)
target_link_libraries(project_target PRIVATE SDL::SDL_gfx)

๐Ÿ’ซ See Also

  • The FindSDL module, for finding the main SDL library. ๐Ÿซถ

๐ŸŽ€ FindSDL_image ๐ŸŽ€

Finds the SDL_image library โ€” the one that loads images of all kinds of formats as SDL (Simple DirectMedia Layer) surfaces:

find_package(SDL_image [<version>] [...])
Note: this module is specifically intended for SDL_image version 1. Starting with version 2.6, SDL_image ships a CMake package configuration file when built with CMake, so it should be found with find_package(SDL2_image). Similarly, SDL_image version 3 can be found with find_package(SDL3_image). Those newer versions provide Imported Targets that bundle up the usage requirements โ€” check the official SDL documentation for the details. ๐Ÿ˜Œ

๐Ÿฆ‹ Result Variables

  • SDL_image_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of the) SDL_image library was found.
  • SDL_image_VERSION โ€” Added in version 4.2. The human-readable string containing the version of SDL_image that was found.
  • SDL_IMAGE_INCLUDE_DIRS โ€” include directories containing the headers you need to use the SDL_image library.
  • SDL_IMAGE_LIBRARIES โ€” libraries you need to link against to use the SDL_image library.

๐Ÿ’œ Hints

  • SDLDIR โ€” an environment variable you can set to help locate an SDL library installed in a custom location. It should point to the installation destination that was used when configuring, building and installing the SDL library: ./configure --prefix=$SDLDIR.

๐Ÿ“ Deprecated Variables

Backward-compat crew, reporting for duty:

  • SDL_IMAGE_VERSION_STRING โ€” Deprecated since version 4.2: use SDL_image_VERSION, which has the same value. The human-readable string containing the version of SDL_image that was found.
  • SDL_IMAGE_FOUND โ€” Deprecated since version 4.2: use SDL_image_FOUND, which has the same value.
  • SDLIMAGE_FOUND โ€” Deprecated since version 2.8.10: use SDL_image_FOUND, which has the same value.
  • SDLIMAGE_INCLUDE_DIR โ€” Deprecated since version 2.8.10: use SDL_IMAGE_INCLUDE_DIRS, which has the same value.
  • SDLIMAGE_LIBRARY โ€” deprecated since version 2.8.10 ๐Ÿ™ˆ like, use SDL_IMAGE_LIBRARIES instead โ€” it's literally the same value, no cap ๐Ÿ’…

๐ŸŽ€ Examples ๐ŸŽ€

Okay so here's how you find the SDL_image library and build yourself an imported interface target to link it to your project target โ€” iconic behavior honestly:

find_package(SDL_image)

if(SDL_image_FOUND AND NOT TARGET SDL::SDL_image)
  add_library(SDL::SDL_image INTERFACE IMPORTED)
  set_target_properties(
    SDL::SDL_image
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${SDL_IMAGE_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${SDL_IMAGE_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE SDL::SDL_image)

When you're working with SDL_image version 2, the upstream package provides the SDL2_image::SDL2_image imported target directly โ€” so like, you don't even need this module at all, you can just use it in a project straight up:

find_package(SDL2_image)
target_link_libraries(project_target PRIVATE SDL2_image::SDL2_image)

Similarly, for SDL_image version 3:

find_package(SDL3_image)
target_link_libraries(project_target PRIVATE SDL3_image::SDL3_image)

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The [FindSDL](#module:FindSDL) module to find the main SDL library ๐ŸŒˆ

๐ŸŽง FindSDL_mixer ๐ŸŽง

Finds the SDL_mixer library โ€” the one that provides an audio mixer with support for various file formats in SDL (Simple DirectMedia Layer) applications ๐ŸŽตโœจ:

find_package(SDL_mixer [<version>] [...])
Note: this module is specifically intended for SDL_mixer version 1 bestie, don't get it twisted ๐Ÿซถ Starting with version 2.5, SDL_mixer provides a CMake package configuration file when built with CMake and should be found using find_package(SDL2_mixer). These newer versions provide [Imported Targets](#imported-targets) that encapsulate usage requirements โ€” so much cleaner. Refer to the official SDL documentation for more information ๐Ÿ’œ

โœจ Result Variables โœจ

This module defines the following variables:

  • SDL_mixer_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) SDL_mixer library was found โœ…
  • SDL_mixer_VERSION โ€” Added in version 4.2. The human-readable string containing the version of SDL_mixer found ๐Ÿท๏ธ
  • SDL_MIXER_INCLUDE_DIRS โ€” Include directories containing headers needed to use the SDL_mixer library ๐Ÿ“
  • SDL_MIXER_LIBRARIES โ€” Libraries needed to link against to use SDL_mixer ๐Ÿ”—

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts the following variables:

  • SDLDIR โ€” Environment variable that can be set to help locate an SDL library installed in a custom location. It should point to the installation destination that was used when configuring, building, and installing SDL library: ./configure --prefix=$SDLDIR ๐Ÿ› ๏ธ

๐ŸŒซ๏ธ Deprecated Variables ๐ŸŒซ๏ธ

The following variables are provided for backward compatibility (aka, they're giving retired icon energy ๐Ÿ‘‘):

  • SDL_MIXER_VERSION_STRING โ€” Deprecated since version 4.2: Use SDL_mixer_VERSION, which has the same value. The human-readable string containing the version of SDL_mixer found ๐Ÿ’€
  • SDL_MIXER_FOUND โ€” Deprecated since version 4.2: Use SDL_mixer_FOUND, which has the same value ๐Ÿ™ˆ
  • SDLMIXER_FOUND โ€” Deprecated since version 2.8.10: Use SDL_mixer_FOUND, which has the same value ๐Ÿ™ˆ
  • SDLMIXER_INCLUDE_DIR โ€” Deprecated since version 2.8.10: Use SDL_MIXER_INCLUDE_DIRS, which has the same value ๐Ÿ™ˆ
  • SDLMIXER_LIBRARY โ€” Deprecated since version 2.8.10: Use SDL_MIXER_LIBRARIES, which has the same value ๐Ÿ™ˆ

๐Ÿ“– Examples ๐Ÿ“–

Finding the SDL_mixer library and creating an imported interface target for linking it to a project target โ€” slay:

find_package(SDL_mixer)

if(SDL_mixer_FOUND AND NOT TARGET SDL::SDL_mixer)
  add_library(SDL::SDL_mixer INTERFACE IMPORTED)
  set_target_properties(
    SDL::SDL_mixer
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${SDL_MIXER_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${SDL_MIXER_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE SDL::SDL_mixer)

When working with SDL_mixer version 2, the upstream package provides the SDL2_mixer::SDL2_mixer imported target directly. It can be used in a project without using this module:

find_package(SDL2_mixer)
target_link_libraries(project_target PRIVATE SDL2_mixer::SDL2_mixer)

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The [FindSDL](#module:FindSDL) module to find the main SDL library ๐ŸŒˆ

๐ŸŒ FindSDL_net ๐ŸŒ

Finds the SDL_net library โ€” a cross-platform network library for use with SDL (Simple DirectMedia Layer) applications, networking era fr fr ๐Ÿฆ‹:

find_package(SDL_net [<version>] [...])
Note: this module is specifically intended for SDL_net version 1 ๐Ÿซถ Starting with version 2.1, SDL_net provides a CMake package configuration file when built with CMake and should be found using find_package(SDL2_net). These newer versions provide [Imported Targets](#imported-targets) that encapsulate usage requirements. Refer to the official SDL documentation for more information ๐Ÿ’œ

โœจ Result Variables โœจ

This module defines the following variables:

  • SDL_net_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) SDL_net library was found โœ…
  • SDL_net_VERSION โ€” Added in version 4.2. The human-readable string containing the version of SDL_net found ๐Ÿท๏ธ
  • SDL_NET_INCLUDE_DIRS โ€” Include directories containing headers needed to use the SDL_net library ๐Ÿ“
  • SDL_NET_LIBRARIES โ€” Libraries needed to link against to use the SDL_net library ๐Ÿ”—

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts the following variables:

  • SDLDIR โ€” Environment variable that can be set to help locate an SDL library installed in a custom location. It should point to the installation destination that was used when configuring, building, and installing SDL library: ./configure --prefix=$SDLDIR ๐Ÿ› ๏ธ

๐ŸŒซ๏ธ Deprecated Variables ๐ŸŒซ๏ธ

The following variables are provided for backward compatibility:

  • SDL_NET_VERSION_STRING โ€” Deprecated since version 4.2: Use SDL_net_VERSION, which has the same value. The human-readable string containing the version of SDL_net found ๐Ÿ’€
  • SDL_NET_FOUND โ€” Deprecated since version 4.2: Use SDL_net_FOUND, which has the same value ๐Ÿ™ˆ
  • SDLNET_FOUND โ€” Deprecated since version 2.8.10: Use SDL_net_FOUND, which has the same value ๐Ÿ™ˆ
  • SDLNET_INCLUDE_DIR โ€” Deprecated since version 2.8.10: Use SDL_NET_INCLUDE_DIRS, which has the same value ๐Ÿ™ˆ
  • SDLNET_LIBRARY โ€” Deprecated since version 2.8.10: Use SDL_NET_LIBRARIES, which has the same value ๐Ÿ™ˆ

๐Ÿ“– Examples ๐Ÿ“–

Finding the SDL_net library and creating an imported interface target for linking it to a project target:

find_package(SDL_net)

if(SDL_net_FOUND AND NOT TARGET SDL::SDL_net)
  add_library(SDL::SDL_net INTERFACE IMPORTED)
  set_target_properties(
    SDL::SDL_net
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${SDL_NET_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${SDL_NET_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE SDL::SDL_net)

When working with SDL_net version 2, the upstream package provides the SDL2_net::SDL2_net imported target directly. It can be used in a project without using this module:

find_package(SDL2_net)
target_link_libraries(project_target PRIVATE SDL2_net::SDL2_net)

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The [FindSDL](#module:FindSDL) module to find the main SDL library ๐ŸŒˆ

๐Ÿ”Š FindSDL_sound ๐Ÿ”Š

Finds the SDL_sound library โ€” an abstract soundfile decoder for use in SDL (Simple DirectMedia Layer) applications, we love a decoder moment ๐Ÿ“:

find_package(SDL_sound [<version>] [...])
Note: this module is specifically intended for SDL_sound version 1 bestie ๐Ÿซถ Starting with version 2.0.2, SDL_sound provides a CMake package configuration file when built with CMake and should be found using find_package(SDL2_sound). These newer versions provide [Imported Targets](#imported-targets) that encapsulate usage requirements. Refer to the upstream SDL_sound documentation for more information ๐Ÿ’œ
Note: this module depends on SDL being found and must be called after the [find_package(SDL)](#module:FindSDL) ๐Ÿ˜ญ Depending on how the SDL_sound library is built, it may require additional dependent libraries to be found for this module to succeed. These dependencies may include MikMod, ModPlug, Ogg, Vorbis, SMPEG, FLAC, and Speex ๐ŸŽถ

โœจ Result Variables โœจ

This module defines the following variables:

  • SDL_sound_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) SDL_sound library was found โœ…
  • SDL_sound_VERSION โ€” Added in version 4.2. The human-readable string containing the version of SDL_sound found ๐Ÿท๏ธ
  • SDL_SOUND_LIBRARIES โ€” Libraries needed to link against to use the SDL_sound library ๐Ÿ”—

๐Ÿ—„๏ธ Cache Variables ๐Ÿ—„๏ธ

The following cache variables may also be set:

  • SDL_SOUND_INCLUDE_DIR โ€” The directory containing the SDL_sound.h and other headers needed to use the SDL_sound library ๐Ÿ“
  • SDL_SOUND_LIBRARY โ€” The name of just the SDL_sound library you would link against. Use SDL_SOUND_LIBRARIES for the link instructions and not this one ๐Ÿ‘€
  • MIKMOD_LIBRARY โ€” The path to the dependent MikMod library ๐ŸŽน
  • MODPLUG_LIBRARY โ€” The path to the dependent ModPlug library (libmodplug) ๐ŸŽ›๏ธ
  • OGG_LIBRARY โ€” The path to the dependent Ogg library ๐ŸŽง
  • VORBIS_LIBRARY โ€” The path to the dependent Vorbis library ๐ŸŽผ
  • SMPEG_LIBRARY โ€” The path to the dependent SMPEG library ๐Ÿ“ผ
  • FLAC_LIBRARY โ€” The path to the dependent FLAC library ๐Ÿ’ฟ
  • SPEEX_LIBRARY โ€” The path to the dependent Speex library ๐Ÿ—ฃ๏ธ

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts the following variables:

  • SDLDIR โ€” Environment variable that can be set to help locate an SDL library installed in a custom location. It should point to the installation destination that was used when configuring, building, and installing SDL library: ./configure --prefix=$SDLDIR ๐Ÿ› ๏ธ
On macOS, setting this variable will prefer the Framework version (if found) over others. In this case, the cache value of SDL_LIBRARY would need to be manually changed to override this selection or set the [CMAKE_INCLUDE_PATH](#variable:CMAKE_INCLUDE_PATH) variable to modify the search paths ๐ŸŽ
  • SDLSOUNDDIR โ€” Environment variable that works the same as SDLDIR ๐ŸŒ€
  • SDL_SOUND_EXTRAS โ€” okay so this one's an optional cache variable, and it's your little "bestie i need extra stuff" escape hatch ๐Ÿซถ anything you drop in here gets prepended to the SDL_SOUND_LIBRARIES result variable. It exists mostly for the cases this module lowkey failed to anticipate and you gotta bolt on some additional flags yourself. No cap, that's the whole vibe.

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

These ones are here purely for backward compatibility โ€” legacy vibes only, they still work but they're giving "still using my old username" energy ๐Ÿ˜ญ

  • SDL_SOUND_FOUND โ€” Deprecated since version 4.2: use SDL_sound_FOUND, which has the same value. Boolean indicating whether the (requested version of) SDL_sound library was found.
  • SDL_SOUND_VERSION_STRING โ€” Deprecated since version 4.2: use SDL_sound_VERSION, which has the same value. The human-readable string containing the version of SDL_sound found.

๐ŸŽ€ Examples ๐ŸŽ€

Finding the SDL_sound library and creating an imported interface target for linking it to a project target โ€” literally the whole glow-up in one snippet:

find_package(SDL)
find_package(SDL_sound)

if(SDL_sound_FOUND AND NOT TARGET SDL::SDL_sound)
  add_library(SDL::SDL_sound INTERFACE IMPORTED)
  set_target_properties(
    SDL::SDL_sound
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${SDL_SOUND_INCLUDE_DIR}"
      INTERFACE_LINK_LIBRARIES "${SDL_SOUND_LIBRARIES}"
  )

  # Append the SDL dependency as imported target to be transitively linked:
  set_property(
    TARGET SDL::SDL_sound
    APPEND
    PROPERTY INTERFACE_LINK_LIBRARIES SDL::SDL
  )
endif()

target_link_libraries(project_target PRIVATE SDL::SDL_sound)

When you're working with SDL_sound version 2, the upstream package provides the SDL2_sound::SDL2_sound imported target directly โ€” so you can skip this module entirely, no thoughts needed:

find_package(SDL2_sound)
target_link_libraries(project_target PRIVATE SDL2_sound::SDL2_sound)

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The FindSDL module to find the main SDL library. It's right there, go grab it ๐Ÿ’…

๐Ÿฆ‹ FindSDL_ttf ๐Ÿฆ‹

Finds the SDL_ttf library, aka the thing that lets you render text with TrueType fonts in SDL (Simple DirectMedia Layer) applications. Pretty text? Iconic. โœจ

find_package(SDL_ttf [<version>] [...] )
Note: this module is specifically intended for SDL_ttf version 1. Starting with version 2.0.15, SDL_ttf provides a CMake package configuration file when built with CMake and should be found using find_package(SDL2_ttf). Similarly, SDL_ttf version 3 can be found using find_package(SDL3_ttf). These newer versions provide Imported Targets that encapsulate usage requirements. Refer to the official SDL documentation for more information. So like โ€” check your version first, bestie ๐Ÿ™ˆ

๐Ÿ“‹ Result Variables ๐Ÿ“‹

This module defines the following variables:

  • SDL_ttf_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) SDL_ttf library was found. ๐Ÿ’–
  • SDL_ttf_VERSION โ€” Added in version 4.2. The human-readable string containing the version of SDL_ttf found.
  • SDL_TTF_INCLUDE_DIRS โ€” Include directories containing headers needed to use the SDL_ttf library.
  • SDL_TTF_LIBRARIES โ€” Libraries needed to link against to use SDL_ttf.

๐Ÿ’ก Hints ๐Ÿ’ก

This module accepts the following variables:

  • SDLDIR โ€” environment variable that can be set to help locate an SDL library installed in a custom location. It should point to the installation destination that was used when configuring, building, and installing the SDL library: ./configure --prefix=$SDLDIR. Yes, exactly like that ๐ŸŽฏ

๐Ÿ’€ Deprecated Variables ๐Ÿ’€

Backward-compat crew, reporting for duty:

  • SDL_TTF_VERSION_STRING โ€” Deprecated since version 4.2: use SDL_ttf_VERSION, which has the same value. The human-readable string containing the version of SDL_ttf found.
  • SDL_TTF_FOUND โ€” Deprecated since version 4.2: use SDL_ttf_FOUND, which has the same value.
  • SDLTTF_FOUND โ€” Deprecated since version 2.8.10: replaced with SDL_ttf_FOUND, which has the same value.
  • SDLTTF_INCLUDE_DIR โ€” Deprecated since version 2.8.10: replaced with SDL_TTF_INCLUDE_DIRS, which has the same value.
  • SDLTTF_LIBRARY โ€” Deprecated since version 2.8.10: replaced with SDL_TTF_LIBRARIES, which has the same value.

๐ŸŽ€ Examples ๐ŸŽ€

Finding the SDL_ttf library and creating an imported interface target for linking it to a project target:

find_package(SDL_ttf)

if(SDL_ttf_FOUND AND NOT TARGET SDL::SDL_ttf)
  add_library(SDL::SDL_ttf INTERFACE IMPORTED)
  set_target_properties(
    SDL::SDL_ttf
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${SDL_TTF_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${SDL_TTF_LIBRARIES}"
  )
endif()

target_link_libraries(project_target PRIVATE SDL::SDL_ttf)

When working with SDL_ttf version 2, the upstream package provides the SDL2_ttf::SDL2_ttf imported target directly. It can be used in a project without using this module:

find_package(SDL2_ttf)
target_link_libraries(project_target PRIVATE SDL2_ttf::SDL2_ttf)

Similarly, for SDL_ttf version 3:

find_package(SDL3_ttf)
target_link_libraries(project_target PRIVATE SDL3_ttf::SDL3_ttf)

๐Ÿ‘€ See Also ๐Ÿ‘€

  • The FindSDL module to find the main SDL library. Same energy as before, still slaps ๐Ÿ’…

๐ŸŒˆ FindSelfPackers ๐ŸŒˆ

Finds UPX, the Ultimate Packer for eXecutables โ€” yes that capitalization is real, and honestly? iconic ๐Ÿ‘‘

find_package(SelfPackers [...] )

This module searches for executable packer-tools that compress executables or shared libraries into on-the-fly, self-extracting versions. It currently supports UPX. That's it, that's the list ๐Ÿ“

๐Ÿ“‹ Result Variables ๐Ÿ“‹

This module defines the following variables:

  • SelfPackers_FOUND โ€” Added in version 4.2. Boolean indicating whether packer tools were found.

๐Ÿ—‚๏ธ Cache Variables ๐Ÿ—‚๏ธ

The following cache variables may also be set:

  • SELF_PACKER_FOR_EXECUTABLE โ€” Path to the executable packer for compressing executables.
  • SELF_PACKER_FOR_SHARED_LIB โ€” Path to the executable packer for compressing shared libraries.
  • SELF_PACKER_FOR_EXECUTABLE_FLAGS โ€” Command-line options to use when compressing executables.
  • SELF_PACKER_FOR_SHARED_LIB_FLAGS โ€” Command-line options to use when compressing shared libraries.

๐ŸŽ€ Examples ๐ŸŽ€

Finding UPX. That's the whole example. It's one line. It ate. โœจ

find_package(SelfPackers)

๐Ÿงš FindSQLite3 ๐Ÿงš

Added in version 3.14.

Finds the SQLite 3 library:

find_package(SQLite3 [<version>] [...] )

SQLite is a small, fast, self-contained, high-reliability, and full-featured SQL database engine written in C, intended for embedding in applications. Like, it's a whole database in a tiny little file and it literally never lets you down. Main character energy fr fr ๐Ÿ’–

๐ŸŽฏ Imported Targets ๐ŸŽฏ

This module provides the following Imported Targets:

  • SQLite3::SQLite3 โ€” target encapsulating SQLite library usage requirements. It is available only when SQLite is found. Added in version 4.3. ๐Ÿ”ฅ
  • SQLite::SQLite3 โ€” Deprecated. Identical to SQLite3::SQLite3.

If your project needs to support CMake < 4.3, consider adding the following to your project after calling find_package(SQLite3 ...):

if(NOT TARGET SQLite3::SQLite3) # CMake < 4.3
  add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif()

This will allow your project to use the new name while still permitting it to compile with older versions of CMake. Bestie, it's giving "have your cake and eat it too" and honestly we love that for you ๐Ÿซถ

๐Ÿ“‹ Result Variables ๐Ÿ“‹

This module defines the following variables:

  • SQLite3_FOUND โ€” Boolean indicating whether the (requested version of) the SQLite library was found.
  • SQLite3_VERSION โ€” the version of the SQLite library found.
  • SQLite3_INCLUDE_DIRS โ€” include directories containing the <sqlite3.h> and related headers needed to use SQLite.
  • SQLite3_LIBRARIES โ€” libraries needed to link against to use SQLite.

๐ŸŽ€ Examples ๐ŸŽ€

Finding the SQLite library and linking it to a project target. Two lines. Flawless. ๐Ÿ’…

find_package(SQLite3)
target_link_libraries(project_target PRIVATE SQLite3::SQLite3)

โญ FindSquish โญ

Finds Squish, a cross-platform automated GUI testing framework for applications built on various GUI technologies:

find_package(Squish [<version>] [...] )

Squish supports testing of both native and cross-platform toolkits, such as Qt, Java, and Tk. GUI testing but make it fancy โœจ

๐Ÿ“‹ Result Variables ๐Ÿ“‹

This module defines the following variables:

  • Squish_FOUND โ€” Added in version 3.3. Boolean indicating whether (the requested version of) Squish was found.
  • Squish_VERSION โ€” Added in version 4.2. The full version of the Squish found.
  • SQUISH_INSTALL_DIR_FOUND โ€” Boolean indicating whether the Squish installation directory was found.
  • SQUISH_SERVER_EXECUTABLE_FOUND โ€” Boolean indicating whether the Squish server executable was found.
  • SQUISH_CLIENT_EXECUTABLE_FOUND โ€” Boolean indicating whether the Squish client executable was found.

๐Ÿ—‚๏ธ Cache Variables ๐Ÿ—‚๏ธ

The following cache variables may also be set:

  • SQUISH_INSTALL_DIR โ€” the Squish installation directory containing bin, lib, etc.
  • SQUISH_SERVER_EXECUTABLE โ€” the path to the squishserver executable.
  • SQUISH_CLIENT_EXECUTABLE โ€” the path to the squishrunner executable.

๐Ÿ› ๏ธ Commands ๐Ÿ› ๏ธ

This module provides the following commands, if Squish is found:

squish_add_test

Adds a Squish test to the project:

squish_add_test(
  <name>
  AUT <target>
  SUITE <suite-name>
  TEST <squish-test-case-name>
  [PRE_COMMAND <command>]
  [POST_COMMAND <command>]
  [SETTINGSGROUP <group>]
)

This command is built on top of the add_test() command and adds a Squish test called <name> to the CMake project. It supports Squish versions 4 and newer. ๐ŸŽ€

During the CMake testing phase, the Squish server is started, the test is executed on the client, and the server is stopped once the test completes. If any of these steps fail (including if the test itself fails), a fatal error is raised indicating the test did not pass. So yeah โ€” if it breaks, it breaks loudly. No quiet failures here ๐Ÿ’€

The arguments are:

  • <name> โ€” the name of the test. This is passed as the first argument to the add_test() command.
  • AUT <target> โ€” the name of the CMake target to be used as the AUT (Application Under Test), i.e., the executable that will be tested. Yes, AUT = the one on stage getting examined ๐Ÿ‘‘
  • SUITE <suite-name> โ€” either the full path to the Squish test suite or just the suite name (like, literally just the last directory name of the suite, no path). And if you go the short way? Then the CMakeLists.txt that calls squish_add_test() has to live in the parent directory of the suite. Like, non-negotiable. ๐Ÿซถ
  • TEST <squish-test-case-name> โ€” the name of the Squish test, which lines up with the subdirectory of the test inside the suite directory.
  • PRE_COMMAND <command> โ€” an optional command to run before the Squish test kicks off. Pass it as a string. Could be a single command, or a semicolon-separated list of command and arguments. โœจ
  • POST_COMMAND <command> โ€” an optional command to run after the Squish test has finished. Same deal: pass it as a string, single command or semicolon-separated list of command and arguments. ๐ŸŽ€
  • SETTINGSGROUP <group> โ€” Deprecated since version 3.18: this argument is now just... ignored. Bestie it does nothing. It used to specify a settings group name for running the test instead of the default value CTest_<username>. RIP to a real one ๐Ÿ’€
Changed in version 3.18: in previous CMake versions, this command was named squish_v4_add_test(). So if you see that old name floating around, that's why. iykyk

๐Ÿงš squish_v3_add_test

Adds a Squish test to the project, but for when you're on Squish version 3.x:

squish_v3_add_test(
  <test-name>
  <application-under-test>
  <squish-test-case-name>
  <environment-variables>
  <test-wrapper>
)
Note: this command is for Squish version 3, which is not maintained anymore. Like, genuinely please use a newer Squish version and the squish_add_test() command instead. This is giving legacy energy ๐Ÿ•ฐ๏ธ

The arguments are:

  • <name> โ€” the name of the test.
  • <application-under-test> โ€” the path to the executable used as the AUT (Application Under Test), aka the executable that's gonna get tested.
  • <squish-test-case-name> โ€” the name of the Squish test, matching the subdirectory of the test within the suite directory.
  • <environment-variables> โ€” a semicolon-separated list of environment variables and their values (VAR=VALUE).
  • <test-wrapper> โ€” a string of one or more (semicolon-separated list) test wrappers that the test case needs.

๐Ÿ’œ Deprecated Variables

These following variables are hanging around purely for backward compatibility:

  • SQUISH_FOUND โ€” Deprecated since version 4.2: use Squish_FOUND, which has the exact same value. Boolean indicating whether (the requested version of) Squish was found.
  • SQUISH_VERSION โ€” Deprecated since version 4.2: superseded by Squish_VERSION. The full version of the Squish that was found.
  • SQUISH_VERSION_MAJOR โ€” Deprecated since version 4.2: superseded by Squish_VERSION. The major version of the Squish found.
  • SQUISH_VERSION_MINOR โ€” Deprecated since version 4.2: superseded by Squish_VERSION. The minor version of the Squish found.
  • SQUISH_VERSION_PATCH โ€” Deprecated since version 4.2: superseded by Squish_VERSION. The patch version of the Squish found.

๐ŸŒธ Examples

Finding Squish and specifying a minimum required version:

find_package(Squish 6.5)

Adding a Squish test:

enable_testing()

find_package(Squish 6.5)
if(Squish_FOUND)
  squish_add_test(
    projectTestName
    AUT projectApp
    SUITE ${CMAKE_CURRENT_SOURCE_DIR}/tests/projectSuite
    TEST someSquishTest
  )
endif()

Example, how to use the squish_v3_add_test() command:

enable_testing()

find_package(Squish 3.0)
if(Squish_FOUND)
  squish_v3_add_test(
    projectTestName
    $<TARGET_FILE:projectApp>
    someSquishTest
    "FOO=1;BAR=2"
    testWrapper
  )
endif()

๐Ÿฆ‹ FindSubversion

Finds a Subversion command-line client executable (svn) and hands you commands for pulling info out of a Subversion working copy:

find_package(Subversion [<version>] [...])

โญ Result Variables

This module defines the following variables:

  • Subversion_FOUND โ€” boolean indicating whether the (requested version of the) Subversion command-line client was found.
  • Subversion_VERSION โ€” Added in version 4.2. Version of the svn command-line client that was found.

๐ŸŽ€ Cache Variables

These cache variables may also get set:

  • Subversion_SVN_EXECUTABLE โ€” path to the svn command-line client.

๐Ÿ‘‘ Commands

This module provides the following commands if the Subversion command-line client is found:

๐Ÿ’… Subversion_WC_INFO

Extracts information from a Subversion working copy sitting at a specified directory:

Subversion_WC_INFO(<dir> <var-prefix> [IGNORE_SVN_FAILURE])

This command defines the following variables if running Subversion's info subcommand on <dir> succeeds; otherwise a SEND_ERROR message gets generated (not cute ๐Ÿ˜ญ):

  • <var-prefix>_WC_URL โ€” URL of the repository (at <dir>).
  • <var-prefix>_WC_ROOT โ€” root URL of the repository.
  • <var-prefix>_WC_REVISION โ€” current revision.
  • <var-prefix>_WC_LAST_CHANGED_AUTHOR โ€” author of last commit.
  • <var-prefix>_WC_LAST_CHANGED_DATE โ€” date of last commit.
  • <var-prefix>_WC_LAST_CHANGED_REV โ€” revision of last commit.
  • <var-prefix>_WC_INFO โ€” output of the command svn info <dir>

The options are:

  • IGNORE_SVN_FAILURE โ€” Added in version 3.13. When specified, errors from the Subversion operation will not trigger a SEND_ERROR message. And in case of an error, those <var-prefix>_* variables just stay undefined. No drama ๐Ÿซถ

๐Ÿงš Subversion_WC_LOG

Retrieves the log message of the base revision of a Subversion working copy at a given location:

Subversion_WC_LOG(<dir> <var-prefix>)

This command defines the following variable if running Subversion's log subcommand on <dir> succeeds; otherwise a SEND_ERROR message is generated:

  • <var-prefix>_LAST_CHANGED_LOG โ€” last log of the base revision of a Subversion working copy located at <dir>.

๐Ÿ’œ Deprecated Variables

The following variables are provided for backward compatibility:

  • SUBVERSION_FOUND โ€” Deprecated since version 4.2: use Subversion_FOUND, which has the same value. Boolean indicating whether the (requested version of the) Subversion command-line client was found.
  • Subversion_VERSION_SVN โ€” Deprecated since version 4.2: use the Subversion_VERSION. Version of the svn command-line client that was found.

๐ŸŒˆ Examples

๐ŸŒธ Examples: Finding Subversion

Finding Subversion:

find_package(Subversion)

Or, finding Subversion and specifying a minimum required version:

find_package(Subversion 1.4)

Or, finding Subversion and making it required (and if it's not found, processing just stops with an error message โ€” brutal but fair):

find_package(Subversion REQUIRED)

๐Ÿ“ Example: Using Subversion

Finding Subversion and retrieving info about the current project's working copy:

find_package(Subversion)
if(Subversion_FOUND)
  Subversion_WC_INFO(${PROJECT_SOURCE_DIR} Project)
  message("Current revision is ${Project_WC_REVISION}")
  Subversion_WC_LOG(${PROJECT_SOURCE_DIR} Project)
  message("Last changed log is ${Project_LAST_CHANGED_LOG}")
endif()

๐Ÿ”ฅ FindSWIG

Finds the installed Simplified Wrapper and Interface Generator (SWIG, https://swig.org) executable and figures out its version:

find_package(SWIG [<version>] [COMPONENTS <langs>...] [...])

Added in version 3.19: support for specifying a version range when calling the find_package() command. When a version is requested, you can still spec it as a single value like before, and now you can also use a version range. For the whole detailed breakdown of version range usage and capabilities, go look at the find_package() command. It's giving thorough ๐Ÿ’…

โœจ Components

Added in version 3.18.

This module supports optional components to specify target languages.

If a COMPONENTS or OPTIONAL_COMPONENTS argument is given to the find_package() command, it'll also figure out supported target languages. Obsessed with the flexibility honestly:

find_package(SWIG [COMPONENTS <langs>...] [OPTIONAL_COMPONENTS <langs>...])

Any COMPONENTS you give to find_package() should be the names of supported target languages as provided to the LANGUAGE argument of swig_add_library(), like python or perl5. And heads up: language names must be lowercase. no cap ๐Ÿ” 

โญ Result Variables

This module defines the following variables:

  • SWIG_FOUND โ€” boolean indicating whether the (requested version of) SWIG and any required components were found on the system.
  • SWIG_VERSION โ€” SWIG executable version (result of swig -version).
  • SWIG_<lang>_FOUND โ€” if COMPONENTS or OPTIONAL_COMPONENTS are requested, each available target language <lang> (lowercase) gets set to TRUE.
  • SWIG_DIR โ€” path to the installed SWIG Lib directory (result of swig -swiglib).

๐ŸŽ€ Cache Variables

The following cache variables may also be set:

  • SWIG_EXECUTABLE โ€” the path to the SWIG executable. This executable is what's used to retrieve all the information for this module. And you can also manually set it to change the version to be found, straight from the command line. main character variable energy ๐Ÿ‘‘

๐Ÿฆ‹ Examples

Example usage requiring SWIG 4.0 or higher plus Python language support, with optional Fortran support:

find_package(SWIG 4.0 COMPONENTS python OPTIONAL_COMPONENTS fortran)
if(SWIG_FOUND)
  message("SWIG found: ${SWIG_EXECUTABLE}")
  if(NOT SWIG_fortran_FOUND)
    message(WARNING "SWIG Fortran bindings cannot be generated")
  endif()
endif()

This module is commonly used in conjunction with the UseSWIG module:

find_package(SWIG COMPONENTS python)
if(SWIG_FOUND)
  include(UseSWIG)

  swig_add_library(mymod LANGUAGE python SOURCES mymod.i)
endif()

๐ŸŒŸ See Also

  • The UseSWIG module to use SWIG in CMake. literally the go-to bestie for this ๐Ÿซถ

FindTCL ๐Ÿ’…

Okay so FindTCL finds Tcl (Tool Command Language), the dynamic programming language, bestie:

find_package(TCL [...])

This module locates a Tcl installation โ€” include dirs, libraries, the whole thing โ€” and determines the appropriate Tcl library name for linking. And because the Tcl ecosystem is a package, it also finds Tk, the GUI toolkit that gives you a library of basic widgets for building graphical user interfaces. ๐ŸŽ€

Result Variables โœจ

This module defines the following variables, fr fr:

  • TCL_FOUND โ€” Boolean indicating whether Tcl was found.
  • TK_FOUND โ€” Boolean indicating whether Tk was found.
  • TCLTK_FOUND โ€” Boolean indicating whether both Tcl and Tk were found.

Cache Variables ๐Ÿซถ

The following cache variables may also be set:

  • TCL_LIBRARY โ€” The path to the Tcl library (e.g., tcl, etc.).
  • TCL_INCLUDE_PATH โ€” The directory containing tcl.h and other Tcl-related headers needed to use Tcl.
  • TCL_TCLSH โ€” The path to the tclsh command-line executable.
  • TK_LIBRARY โ€” The path to the Tk library (e.g., tk, etc.).
  • TK_INCLUDE_PATH โ€” The directory containing tk.h and other Tk-related headers needed to use Tk.
  • TK_WISH โ€” The path to the wish windowing shell command-line executable.

Other Libraries ๐Ÿ’œ

The Tcl Stub Library can be found using the separate FindTclStub <# module:FindTclStub> module.

Examples ๐ŸŒธ

Finding Tcl:

find_package(TCL)

See Also ๐Ÿ‘‘

  • The FindTclsh <#module:FindTclsh> module to find the Tcl shell command-line executable.
  • The FindTclStub <#module:FindTclStub> module to find the Tcl Stubs Library.
  • The FindWish <#module:FindWish> module to find the wish windowing shell command-line executable .

FindTclsh ๐Ÿš

Finds the Tcl shell command-line executable (tclsh), which includes the Tcl (Tool Command Language) interpreter:

find_package(Tclsh [<version>] [...])

Result Variables โœจ

This module defines the following variables:

  • Tclsh_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) tclsh executable was found.
  • Tclsh_VERSION โ€” Added in version 4.2. The version of tclsh found.

Cache Variables ๐Ÿซถ

The following cache variables may also be set:

  • TCL_TCLSH โ€” The path to the tclsh executable.

Deprecated Variables ๐Ÿ’€

The following variables are provided for backward compatibility:

  • TCLSH_FOUND โ€” Deprecated since version 4.2: Use Tclsh_FOUND, which has the same value. Boolean indicating whether the (requested version of) tclsh executable was found.
  • TCLSH_VERSION_STRING โ€” Deprecated since version 4.2: Use Tclsh_VERSION, which has the same value. The version of tclsh found.

Examples ๐ŸŒธ

In the following example, this module is used to find the tclsh command-line executable, which is then executed in a process to evaluate TCL code from the script file located in the project source directory:

find_package(Tclsh)
if(Tclsh_FOUND)
  execute_process(COMMAND ${TCL_TCLSH} example-script.tcl)
endif()

See Also ๐Ÿ‘‘

  • The FindTCL <#module:FindTCL> module to find the Tcl installation.
  • The FindTclStub <#module:FindTclStub> module to find the Tcl Stubs Library.

FindTclStub ๐Ÿงฉ

Finds the Tcl Stub Library, which is used for building version-independent Tcl extensions:

find_package(TclStub [...])

Tcl (Tool Command Language) is a dynamic programming language, and the Tcl Stub Library provides a mechanism to allow Tcl extensions to be compiled in a way that they can work across multiple Tcl versions, without requiring recompilation. Slay. ๐Ÿ’…

This module is typically used in conjunction with Tcl development projects that aim to be portable across different Tcl releases. It first calls the FindTCL <#module:FindTCL> module to locate Tcl installation and then attempts to find the stub libraries corresponding to the located Tcl version.

Result Variables โœจ

This module defines the following variables:

  • TclStub_FOUND โ€” Added in version 4.2. Boolean indicating whether the Tcl Stub Library was found.

Cache Variables ๐Ÿซถ

The following cache variables may also be set:

  • TCL_STUB_LIBRARY โ€” The path to the Tcl stub library.
  • TK_STUB_LIBRARY โ€” The path to the Tk stub library.
  • TTK_STUB_LIBRARY โ€” The path to the ttk stub library.

Examples ๐ŸŒธ

Finding Tcl Stubs Library:

find_package(TclStub)

See Also ๐Ÿ‘‘

  • The FindTCL <#module:FindTCL> module to find the Tcl installation.
  • The FindTclsh <#module:FindTclsh> module to find the Tcl shell command-line executable.

Online references:


FindThreads ๐Ÿงต

Finds and determines the thread library of the system for multithreading support:

find_package(Threads [...])

Multithreading enables concurrent execution within a single program, typically by creating multiple threads of execution. Most commonly, this is done using libraries such as POSIX Threads (pthreads) on Unix-like systems or Windows threads on Windows.

This module abstracts the platform-specific differences and detects how to enable thread support โ€” whether it requires linking to a specific library, adding compiler flags (like -pthread), or both. On some platforms, threading is also implicitly available in default libraries without the need to use additional flags or libraries.

This module is suitable for use in both C and C++ projects (and occasionally other compiled languages) that rely on system-level threading APIs.

Using this module ensures that project builds correctly across different platforms by handling the detection and setup of thread support in a portable way. iconic behavior, honestly. ๐Ÿฆ‹

C and C++ Language Standards ๐Ÿงต

The C11 standard introduced a minimal cross-platform thread API via <threads.h> header file, and C++11 added <thread> header to the standard library, offering high-level multithreading support. These standard headers allow writing portable threaded code at the language level, without directly using platform-specific APIs like pthreads or Windows threads.

However, even with standard C11 or C++11 threads support available, there may still be a need for platform-specific compiler or linker flags (e.g., -pthread on Unix-like systems) for some applications. This is where FindThreads remains relevant โ€” it ensures these flags and any required libraries are correctly set up, even if not explicitly using system APIs.

In short:

  • Use <thread> (C++11 and later) or <threads.h> (C11) in source code for portability and simpler syntax.
  • Use find_package(Threads) in CMake project when application needs the traditional threading support and to ensure code compiles and links correctly across different platforms.

Imported Targets ๐Ÿ‘‘

This module provides the following Imported Targets <#imported-targets>:

  • Threads::Threads โ€” Added in version 3.1. Target encapsulating the usage requirements to enable threading through flags or a threading library, if found. This target is available if threads are detected as supported.

Result Variables โœจ

This module defines the following variables:

  • Threads_FOUND โ€” Boolean indicating whether Threads is supported, either through a separate library or a standard library.
  • CMAKE_THREAD_LIBS_INIT โ€” The thread library to use. This may be empty if the thread functions are provided by the system libraries and no special flags are needed to use them.
  • CMAKE_USE_WIN32_THREADS_INIT โ€” If the found thread library is the win32 one.
  • CMAKE_USE_PTHREADS_INIT โ€” If the found thread library is pthread compatible.
  • CMAKE_HP_PTHREADS_INIT โ€” If the found thread library is the HP thread library.

Variables Affecting Behavior ๐ŸŽ€

This module accepts the following variables before calling find_package(Threads):

  • THREADS_PREFER_PTHREAD_FLAG โ€” Added in version 3.1. If the use of the -pthread compiler and linker flag is preferred then the caller can set this variable to boolean true. The compiler flag can only be used with the imported target. Use of both the imported target as well as this switch is highly recommended for new code.

This variable has no effect if the system libraries provide the thread functions, i.e. when CMAKE_THREAD_LIBS_INIT will be empty.

Examples ๐ŸŒธ

Finding Threads and linking the imported target to a project target:

set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads)
target_link_libraries(example PRIVATE Threads::Threads)

FindTIFF ๐Ÿ–ผ๏ธ

Finds the TIFF library https://libtiff.gitlab.io/libtiff/ (libtiff):

find_package(TIFF [<version>] [COMPONENTS <components>...] [...])

This module also takes into account the upstream TIFF library's exported CMake package configuration, if available.

Components ๐Ÿงฉ

This module supports optional components which can be specified with:

find_package(TIFF [COMPONENTS <components>...])

Supported components include:

  • CXX โ€” Added in version 3.19. Optional component that ensures that the C++ wrapper library (libtiffxx) is found.

Imported Targets ๐Ÿ‘‘

This module provides the following Imported Targets <#imported-targets>:

  • TIFF::TIFF โ€” Added in version 3.5. Target encapsulating the TIFF library usage requirements, available only if the TIFF is found.
  • TIFF::CXX โ€” Added in version 3.19. Target encapsulating the usage requirements for the C++ wrapper library libtiffxx, available only if TIFF is found. This target provides CXX usage requirements only if the compiler is not MSVC. It also has the TIFF::TIFF target linked in to simplify its usage.

Result Variables โœจ

This module defines the following variables:

  • TIFF_FOUND โ€” Boolean indicating whether (the requested version of) TIFF is found.
  • TIFF_VERSION โ€” Added in version 4.2. The version of TIFF library found.
  • TIFF_INCLUDE_DIRS โ€” The directory containing the TIFF headers.
  • TIFF_LIBRARIES โ€” TIFF libraries to be linked.

Cache Variables ๐Ÿซถ

The following cache variables may also be set:

  • TIFF_INCLUDE_DIR โ€” The directory containing the TIFF headers.
  • TIFF_LIBRARY_RELEASE โ€” Added in version 3.4. The path to the TIFF library for release configurations.
  • TIFF_LIBRARY_DEBUG โ€” added in version 3.4. the path to the TIFF library for debug configs ๐Ÿฉต
  • TIFFXX_LIBRARY_RELEASE โ€” added in version 3.19. the path to the TIFFXX library for release configs.
  • TIFFXX_LIBRARY_DEBUG โ€” added in version 3.19. the path to the TIFFXX library for debug configs. bestie the debug/release split is literally the whole personality of this module ๐Ÿ’…

Deprecated Variables

okay so these are still here, but like... for backward compatibility only. they're giving "we keep it around for the old heads" โœจ

  • TIFF_VERSION_STRING โ€” deprecated since version 4.2: superseded by the TIFF_VERSION. just the version of the TIFF library that was found. she's retired, don't @ her ๐Ÿ™ˆ

Examples

finding TIFF and linking it to your project target, iconic behavior:

find_package(TIFF)
target_link_libraries(project_target PRIVATE TIFF::TIFF)

finding TIFF and TIFFXX by specifying the CXX component (yes you have to ask for it, it's not just gonna show up):

find_package(TIFF COMPONENTS CXX)
target_link_libraries(project_target PRIVATE TIFF::CXX)

๐Ÿฆ‹ FindVulkan

added in version 3.7. finds Vulkan โ€” the low-overhead, cross-platform 3D graphics and computing API โ€” plus all the related dev tools that the Vulkan SDK hands you, like:

find_package(Vulkan [<version>] [COMPONENTS <components>...] [...])

Vulkan ships with the commonly used utilities like shader compilers and SPIR-V tools (think DXC, glslc, glslang, etc. โ€” you know the ones) that support Vulkan-based dev workflows. no cap, the toolkit goes hard ๐Ÿ”ฅ

Components

added in version 3.24. this module supports several optional components that you can pass through find_package():

find_package(Vulkan [COMPONENTS <components>...])

each component gives you a matching imported target. the supported ones are:

  • glslc โ€” added in version 3.24. finds the SPIR-V compiler. note: this optional component is always implied automatically for backward compatibility, even if you don't request it. she invites herself, that's just how it is ๐Ÿ’…
  • glslangValidator โ€” added in version 3.24. finds the glslangValidator tool used to compile GLSL and HLSL shaders into SPIR-V. also always implied automatically for backward compatibility, even if you don't ask. same energy.
  • glslang โ€” added in version 3.24. finds the Khronos-reference front-end shader parser and SPIR-V code generation library (glslang).
  • shaderc_combined โ€” added in version 3.24. finds the Google static library used for Vulkan shader compilation.
  • SPIRV-Tools โ€” added in version 3.24. finds the Khronos library for analyzing and transforming SPIR-V modules.
  • MoltenVK โ€” added in version 3.24. finds the Khronos MoltenVK library, which is available on macOS, and implements a subset of the Vulkan API over the Apple Metal graphics framework ๐ŸŽ
  • dxc โ€” added in version 3.25. finds the DirectX Shader Compiler (DXC), library and command-line tool. heads up: Visual Studio also ships a DXC tool, but the version bundled with the Vulkan SDK is usually the one you need for Vulkan dev, since it has Vulkan capability enabled. not the same thing, don't get it twisted ๐Ÿ‘€
  • volk โ€” added in version 3.25. finds the Vulkan meta-loader volk library.

Imported Targets

this module hands you these imported targets:

  • Vulkan::Vulkan โ€” the target that encapsulates the main Vulkan library usage requirements. available if Vulkan is found. the main character fr ๐Ÿ‘‘
  • Vulkan::glslc โ€” added in version 3.19. imported executable target encapsulating the GLSLC SPIR-V compiler usage requirements. available if glslc is found.
  • Vulkan::Headers โ€” added in version 3.21. target encapsulating the usage requirements needed to include Vulkan headers. it provides only the include directories and does not link to any library โ€” which is exactly what you want if your app loads the Vulkan library dynamically at runtime ๐Ÿซถ available if Vulkan is found.
  • Vulkan::glslangValidator โ€” added in version 3.21. imported executable target encapsulating the glslangValidator usage requirements. available if this tool is found.
  • Vulkan::glslang โ€” added in version 3.24. target encapsulating the glslang library usage requirements. available if glslang is found in the SDK.
  • Vulkan::shaderc_combined โ€” added in version 3.24. target encapsulating the shaderc_combined library usage requirements. available if this library is found in the SDK.
  • Vulkan::SPIRV-Tools โ€” added in version 3.24. target encapsulating the SPIRV-Tools library usage requirements. available if this library is found in the SDK.
  • Vulkan::MoltenVK โ€” added in version 3.24. target encapsulating the MoltenVK library usage requirements. available if this library is found in the SDK.
  • Vulkan::volk โ€” added in version 3.25. target encapsulating the volk library usage requirements. available if volk is found in the SDK.
  • Vulkan::dxc_lib โ€” added in version 3.25. target encapsulating the usage requirements for the DirectX shader compiler library. available if the DXC library is found in the SDK.
  • Vulkan::dxc_exe โ€” added in version 3.25. imported executable target providing usage requirements for the DirectX shader compiler CLI tool. available if the SDK has this tool.

Result Variables

this module defines these variables:

  • Vulkan_FOUND โ€” boolean, tells you whether (the requested version of) Vulkan plus all required components were found. the vibe check of the whole operation โœจ
  • Vulkan_VERSION โ€” added in version 3.23. the version of Vulkan that was found. the value is retrieved from vulkan/vulkan_core.h.
  • Vulkan_INCLUDE_DIRS โ€” include directories you need to use the main Vulkan library.
  • Vulkan_LIBRARIES โ€” libraries you need to link against to use the main Vulkan library.
  • Vulkan_glslc_FOUND โ€” added in version 3.24. boolean, whether the SDK provides the glslc executable.
  • Vulkan_glslangValidator_FOUND โ€” added in version 3.24. boolean, whether the SDK provides the glslangValidator executable.
  • Vulkan_glslang_FOUND โ€” added in version 3.24. boolean, whether the SDK provides the glslang library.
  • Vulkan_shaderc_combined_FOUND โ€” added in version 3.24. boolean, whether the SDK provides the shaderc_combined library.
  • Vulkan_SPIRV-Tools_FOUND โ€” added in version 3.24. boolean, whether the SDK provides the SPIRV-Tools library.
  • Vulkan_MoltenVK_FOUND โ€” added in version 3.24. boolean, whether the SDK provides the MoltenVK library.
  • Vulkan_volk_FOUND โ€” added in version 3.25. boolean, whether the SDK provides the volk library.
  • Vulkan_dxc_lib_FOUND โ€” added in version 3.25. boolean, whether the SDK provides the DirectX shader compiler library.
  • Vulkan_dxc_exe_FOUND โ€” added in version 3.25. boolean, whether the SDK provides the DirectX shader compiler CLI tool.

Cache Variables

these cache variables may also be set:

  • Vulkan_INCLUDE_DIR โ€” the directory containing the Vulkan headers.
  • Vulkan_LIBRARY โ€” the path to the Vulkan library.
  • Vulkan_GLSLC_EXECUTABLE โ€” added in version 3.19. the path to the GLSL SPIR-V compiler.
  • Vulkan_GLSLANG_VALIDATOR_EXECUTABLE โ€” added in version 3.21. the path to the glslangValidator tool.
  • Vulkan_glslang_LIBRARY โ€” added in version 3.24. the path to the glslang library.
  • Vulkan_shaderc_combined_LIBRARY โ€” added in version 3.24. the path to the shaderc_combined library.
  • Vulkan_SPIRV-Tools_LIBRARY โ€” added in version 3.24. the path to the SPIRV-Tools library.
  • Vulkan_MoltenVK_LIBRARY โ€” added in version 3.24. the path to the MoltenVK library.
  • Vulkan_volk_LIBRARY โ€” added in version 3.25. the path to the volk library.
  • Vulkan_dxc_LIBRARY โ€” added in version 3.25. the path to the DirectX shader compiler library.
  • Vulkan_dxc_EXECUTABLE โ€” added in version 3.25. the path to the DirectX shader compiler CLI tool.
  • Vulkan_Layer_API_DUMP_LIBRARY โ€” added in version 4.4. path to the api_dump Vulkan Layer library.
  • Vulkan_Layer_CRASH_DIAGNOSTIC_LIBRARY โ€” added in version 4.4. path to the crash_diagnostic Vulkan Layer library.
  • Vulkan_Layer_GFXRECONSTRUCT_LIBRARY โ€” added in version 4.4. path to the gfxreconstruct Vulkan Layer library.
  • Vulkan_Layer_KHRONOS_PROFILES_LIBRARY โ€” added in version 4.4. path to the khronos_profiles Vulkan Layer library.
  • Vulkan_Layer_KHRONOS_SHADER_OBJECT_LIBRARY โ€” added in version 4.4. path to the khronos_shader_object Vulkan Layer library.
  • Vulkan_Layer_KHRONOS_SYNCHRONIZATION2_LIBRARY โ€” added in version 4.4. path to the khronos_synchronization2 Vulkan Layer library.
  • Vulkan_Layer_KHRONOS_VALIDATION_LIBRARY โ€” added in version 4.4. path to the khronos_validation Vulkan Layer library.
  • Vulkan_Layer_MONITOR_LIBRARY โ€” added in version 4.4. path to the monitor Vulkan Layer library.
  • Vulkan_Layer_SCREENSHOT_LIBRARY โ€” added in version 4.4. path to the screenshot Vulkan Layer library. yes there's a screenshot layer, we love a documentation moment ๐Ÿ“ธ

Hints

this module accepts the following variable:

  • VULKAN_SDK โ€” this environment variable can optionally be set to specify the location of the Vulkan SDK root directory for the given architecture. it's typically set by sourcing the toplevel setup-env.sh script of the Vulkan SDK directory into your shell environment. tldr: source the script, get the vibes ๐ŸŒˆ

Examples

finding the Vulkan library and linking it to a project target โ€” the classic:

find_package(Vulkan)
target_link_libraries(project_target PRIVATE Vulkan::Vulkan)

finding Vulkan plus extra components (in this case volk, because we're extra):

find_package(Vulkan COMPONENTS volk)
target_link_libraries(project_target PRIVATE Vulkan::Vulkan Vulkan::volk)

๐ŸŒธ FindWget

this module finds the wget command-line tool โ€” you know, the one for retrieving content from web servers:

find_package(Wget [...])

Result Variables

this module defines this variable:

  • Wget_FOUND โ€” added in version 3.3. boolean, tells you whether wget was found. just the one variable, she's lowkey and she knows it ๐ŸŽ€

Cache Variables

Like, sometimes you gotta set these cache vars yourself, bestie:

  • WGET_EXECUTABLE โ€” the full path to the wget tool. that's it, that's the whole vibe ๐ŸŽ€

Deprecated Variables

These ones are still here for backward-compat reasons (grandfathered in, no cap):

  • WGET_FOUND โ€” deprecated since version 4.2: use Wget_FOUND instead, it literally has the same value. Boolean that says whether wget was found. that's it. โœจ

Examples

Finding wget and then executing it in a process โ€” iconic combo, honestly:

find_package(Wget)
if(Wget_FOUND)
  execute_process(COMMAND ${WGET_EXECUTABLE} -h)
endif()

See Also

  • The file(DOWNLOAD) command to download the given URL to a local file. the way that just works ๐Ÿซถ

FindWish

Finds wish, which is a simple windowing shell command-line executable:

find_package(Wish [...])

This module is commonly used in conjunction with finding a TCL installation (see the FindTCL module). It helps determine where the TCL include paths and libraries are, as well as identifying the name of the TCL library. multitasking queen ๐Ÿ’…

If the UNIX variable is defined, the module will prioritize looking for the Cygwin version of the wish executable. not me prioritizing cygwin ๐Ÿ’€

Result Variables

This module defines the following variables:

  • Wish_FOUND โ€” added in version 4.2. Boolean indicating whether the wish executable was found. slay โœจ

Cache Variables

The following cache variables may also be set:

  • TK_WISH โ€” the path to the wish executable. ๐Ÿฆ‹

Examples

Finding wish:

find_package(Wish)
message(STATUS "Found wish at: ${TK_WISH}")

FindwxWidgets

Finds a wxWidgets installation and provides usage requirements for usage in projects:

find_package(wxWidgets [<version>] [COMPONENTS <components>...] [...])

wxWidgets (formerly known as wxWindows) is a widget toolkit and tools library for creating graphical user interfaces (GUIs) for cross-platform applications. it's giving cross-platform GUI royalty ๐Ÿ‘‘

Added in version 3.4: support for find_package() version argument.

Added in version 3.14: OPTIONAL_COMPONENTS support. we love an upgrade ๐ŸŒˆ

Components

wxWidgets is a modular library. This module supports components to specify which modules to use. Components can be specified with the find_package() command:

find_package(
  wxWidgets
  [COMPONENTS <components>...]
  [OPTIONAL_COMPONENTS <components>...]
)

Supported components include:

  • base โ€” finds the library that provides mandatory classes that any wxWidgets code depends on. This component is always required for applications implementing wxWidgets. no skipping, periodt.
  • core โ€” finds the library that provides basic GUI classes such as GDI classes or controls.
  • gl โ€” finds the OpenGL support. fancy โœจ
  • mono โ€” finds the wxWidgets monolithic library. one big slay.
  • aui โ€” finds the Advanced User Interface docking library.
  • net โ€” finds the library that provides network access. ๐ŸŒ
  • webview โ€” added in version 3.4. finds the library that provides rendering of web documents (HTML/CSS/JavaScript). it's giving browser-in-your-app ๐Ÿ’…

For a full list of supported wxWidgets components, refer to the upstream documentation. (iykyk, go read it)

If no components are specified, this module by default searches for core and base components. the defaults ate, honestly.

Imported Targets

This module provides the following Imported Targets:

  • wxWidgets::wxWidgets โ€” added in version 3.27. an interface imported target encapsulating the wxWidgets usage requirements for the found components, available if wxWidgets is found. main character target energy ๐Ÿ‘‘โœจ

Result Variables

This module defines the following variables:

  • wxWidgets_FOUND โ€” boolean indicating whether (the requested version of) wxWidgets and all its requested components were found. ๐Ÿซถ
  • wxWidgets_VERSION โ€” added in version 4.2. the version of the wxWidgets found. ๐ŸŽ€
  • wxWidgets_INCLUDE_DIRS โ€” include directories for WIN32, i.e., where to find <wx/wx.h> and <wx/setup.h>; possibly empty for Unix-like systems. lowkey empty on unix, that's fine.
  • wxWidgets_LIBRARIES โ€” path to the wxWidgets libraries. the whole point, bestie ๐Ÿ’œ
  • wxWidgets_LIBRARY_DIRS โ€” compile time link dirs, useful for setting rpath on Unix-like systems. typically an empty string in WIN32 environment. okay windows why are you like this ๐Ÿ˜ญ
  • wxWidgets_DEFINITIONS โ€” contains compile definitions required to compile/link against WX, e.g. WXUSINGDLL.
  • wxWidgets_DEFINITIONS_DEBUG โ€” contains compile definitions required to compile/link against WX debug builds, e.g. __WXDEBUG__.
  • wxWidgets_CXX_FLAGS โ€” include directories and compiler flags for Unix-like systems, empty on Windows. essentially the output of wx-config --cxxflags. literally just that output. โœจ

Hints

This module accepts the following variables before calling find_package(wxWidgets):

  • WX_CONFIG โ€” added in version 3.11. environment variable to manually specify the name of the wxWidgets library configuration provider executable that will be searched besides the default name wx-config. ๐ŸŒธ
  • WXRC_CMD โ€” added in version 3.11. environment variable to manually specify the name of the wxWidgets resource file compiler executable that will be searched besides the default name wxrc. ๐Ÿฆ‹

There are two search branches: a Windows style and a Unix style. For Windows, the following variables are searched for and set to defaults in case of multiple choices. Change them if the defaults are not desired (i.e., these are the only variables that should be changed to select a configuration):

  • wxWidgets_ROOT_DIR โ€” base wxWidgets directory (e.g., C:/wxWidgets-3.2.0). ๐Ÿ 
  • wxWidgets_LIB_DIR โ€” path to wxWidgets libraries (e.g., C:/wxWidgets-3.2.0/lib/vc_x64_lib).
  • wxWidgets_CONFIGURATION โ€” configuration to use (e.g., msw, mswd, mswu, mswunivud, etc.) the alphabet soup is real ๐Ÿ’€
  • wxWidgets_EXCLUDE_COMMON_LIBRARIES โ€” set to TRUE to exclude linking of commonly required libs (e.g., png, tiff, jpeg, zlib, webp, regex, expat, scintilla, lexilla, etc.). no cap, they mean all of those.

For Unix style this module uses the wx-config utility. Selecting between debug/release, unicode/ansi, universal/non-universal, and static/shared is possible in the QtDialog or ccmake interfaces by turning ON/OFF the following variables:

  • wxWidgets_USE_DEBUG โ€” if enabled, the wxWidgets debug build will be searched. ๐Ÿ›
  • wxWidgets_USE_UNICODE โ€” if enabled, the wxWidgets unicode build will be searched. ๐ŸŒ
  • wxWidgets_USE_UNIVERSAL โ€” if enabled, the wxWidgets universal build will be searched. ๐ŸŒˆ
  • wxWidgets_USE_STATIC โ€” if enabled, static wxWidgets libraries will be linked. ๐Ÿ”’
  • wxWidgets_CONFIG_OPTIONS โ€” this variable can be used for all other options that need to be passed to the wx-config utility. for example, to use the base toolkit found on the system at /usr install prefix, set the variable (before calling the find_package() command) as such:
set(wxWidgets_CONFIG_OPTIONS --toolkit=base --prefix=/usr)

Deprecated Variables

The following variables are provided for backward compatibility:

  • wxWidgets_VERSION_STRING โ€” deprecated since version 4.2: use wxWidgets_VERSION, which has the same value. added in version 3.4. the version of the wxWidgets found.
  • wxWidgets_USE_FILE โ€” deprecated since version 4.2: instead of using this variable, include the UsewxWidgets module directly:
include(UsewxWidgets)

the path to the UsewxWidgets module for using wxWidgets in the current directory. for example:

find_package(wxWidgets)
if(wxWidgets_FOUND)
  include(${wxWidgets_USE_FILE})
endif()

Examples

Example: Finding wxWidgets

Finding wxWidgets and making it required (if wxWidgets is not found, processing stops with an error message โ€” no wiggle room, bestie โœ‹):

find_package(wxWidgets REQUIRED)

Example: Using Imported Target

Finding wxWidgets and using imported target in a project:

find_package(wxWidgets)
target_link_libraries(example PRIVATE wxWidgets::wxWidgets)

Example: Using Components

Finding wxWidgets and specifying components:

find_package(wxWidgets COMPONENTS gl core base OPTIONAL_COMPONENTS net)
target_link_libraries(example PRIVATE wxWidgets::wxWidgets)

Example: Monolithic wxWidgets Build

Sample usage with monolithic wxWidgets build:

find_package(wxWidgets COMPONENTS mono)
target_link_libraries(example PRIVATE wxWidgets::wxWidgets)

Example: Using Variables

Finding and using wxWidgets in CMake versions prior to 3.27, when the imported target wasn't yet available. retro era ๐Ÿ’…:

# Note that for MinGW users the order of libs is important.
find_package(wxWidgets COMPONENTS gl core base OPTIONAL_COMPONENTS net)

if(wxWidgets_FOUND)
  include(UsewxWidgets)
  # and for each of the project dependent executable/library targets:
  target_link_libraries(example ${wxWidgets_LIBRARIES})
endif()

FindX11

Finds the X11 installation on Unix-like systems:

find_package(X11 [COMPONENTS <components>...] [...])

Result Variables

This module defines the following variables:

  • X11_FOUND โ€” boolean indicating whether X11 was found. ๐Ÿซถ
  • X11_<component>_FOUND โ€” boolean indicating whether the <component> was found. (yes, one of these per component you asked for โ€” very demure, very per-component โœจ)
  • X11_INCLUDE_DIR โ€” include directories needed to use X11.
  • X11_LIBRARIES โ€” libraries needed to link against to use X11. the actual goods ๐Ÿ’œ

and also the following more fine grained variables and targets:

Added in version 3.14: Imported targets. we been knew, iconic.

          X11_ICE_INCLUDE_PATH,            X11_ICE_LIB,            X11_ICE_FOUND,            X11::ICE
          X11_SM_INCLUDE_PATH,             X11_SM_LIB,             X11_SM_FOUND,             X11::SM
          X11_X11_INCLUDE_PATH,            X11_X11_LIB,                                      X11::X11
          X11_Xaccessrules_INCLUDE_PATH,
          X11_Xaccessstr_INCLUDE_PATH,                             X11_Xaccess_FOUND
          X11_Xau_INCLUDE_PATH,            X11_Xau_LIB,            X11_Xau_FOUND,            X11::Xau
          X11_xcb_INCLUDE_PATH,            X11_xcb_LIB,            X11_xcb_FOUND,            X11::xcb
          X11_X11_xcb_INCLUDE_PATH,        X11_X11_xcb_LIB,        X11_X11_xcb_FOUND,        X11::X11_xcb
          X11_xcb_composite_INCLUDE_PATH,  X11_xcb_composite_LIB,  X11_xcb_composite_FOUND,  X11::xcb_composite
          X11_xcb_cursor_INCLUDE_PATH,     X11_xcb_cursor_LIB,     X11_xcb_cursor_FOUND,     X11::xcb_cursor
          X11_xcb_damage_INCLUDE_PATH,     X11_xcb_damage_LIB,     X11_xcb_damage_FOUND,     X11::xcb_damage
          X11_xcb_dpms_INCLUDE_PATH,       X11_xcb_dpms_LIB,       X11_xcb_dpms_FOUND,       X11::xcb_dpms
          X11_xcb_dri2_INCLUDE_PATH,       X11_xcb_dri2_LIB,       X11_xcb_dri2_FOUND,       X11::xcb_dri2
          X11_xcb_dri3_INCLUDE_PATH,       X11_xcb_dri3_LIB,       X11_xcb_dri3_FOUND,       X11::xcb_dri3
          X11_xcb_errors_INCLUDE_PATH,     X11_xcb_errors_LIB,     X11_xcb_errors_FOUND,     X11::xcb_errors
          X11_xcb_ewmh_INCLUDE_PATH,       X11_xcb_ewmh_LIB,       X11_xcb_ewmh_FOUND,       X11::xcb_ewmh
          X11_xcb_glx_INCLUDE_PATH,        X11_xcb_glx_LIB,        X11_xcb_glx_FOUND,        X11::xcb_glx
          X11_xcb_icccm_INCLUDE_PATH,      X11_xcb_icccm_LIB,      X11_xcb_icccm_FOUND,      X11::xcb_icccm
          X11_xcb_image_INCLUDE_PATH,      X11_xcb_image_LIB,      X11_xcb_image_FOUND,      X11::xcb_image
          X11_xcb_keysyms_INCLUDE_PATH,    X11_xcb_keysyms_LIB,    X11_xcb_keysyms_FOUND,    X11::xcb_keysyms
          X11_xcb_present_INCLUDE_PATH,    X11_xcb_present_LIB,    X11_xcb_present_FOUND,    X11::xcb_present
          X11_xcb_randr_INCLUDE_PATH,      X11_xcb_randr_LIB,      X11_xcb_randr_FOUND,      X11::xcb_randr
          X11_xcb_record_INCLUDE_PATH,     X11_xcb_record_LIB,     X11_xcb_record_FOUND,     X11::xcb_record
          X11_xcb_render_INCLUDE_PATH,     X11_xcb_render_LIB,     X11_xcb_render_FOUND,     X11::xcb_render
          X11_xcb_render_util_INCLUDE_PATH,X11_xcb_render_util_LIB,X11_xcb_render_util_FOUND,X11::xcb_render_util
          X11_xcb_res_INCLUDE_PATH,        X11_xcb_res_LIB,        X11_xcb_res_FOUND,        X11::xcb_res
          X11_xcb_screensaver_INCLUDE_PATH,X11_xcb_screensaver_LIB,X11_xcb_screensaver_FOUND,X11::xcb_screensaver
          X11_xcb_shape_INCLUDE_PATH,      X11_xcb_shape_LIB,      X11_xcb_shape_FOUND,      X11::xcb_shape
          X11_xcb_shm_INCLUDE_PATH,        X11_xcb_shm_LIB,        X11_xcb_shm_FOUND,        X11::xcb_shm
          X11_xcb_sync_INCLUDE_PATH,       X11_xcb_sync_LIB,       X11_xcb_sync_FOUND,       X11::xcb_sync
          X11_xcb_util_INCLUDE_PATH,       X11_xcb_util_LIB,       X11_xcb_util_FOUND,       X11::xcb_util
          X11_xcb_xf86dri_INCLUDE_PATH,    X11_xcb_xf86dri_LIB,    X11_xcb_xf86dri_FOUND,    X11::xcb_xf86dri
          X11_xcb_xfixes_INCLUDE_PATH,     X11_xcb_xfixes_LIB,     X11_xcb_xfixes_FOUND,     X11::xcb_xfixes
          X11_xcb_xinerama_INCLUDE_PATH,   X11_xcb_xinerama_LIB,   X11_xcb_xinerama_FOUND,   X11::xcb_xinerama
          X11_xcb_xinput_INCLUDE_PATH,     X11_xcb_xinput_LIB,     X11_xcb_xinput_FOUND,     X11::xcb_xinput
          X11_xcb_xkb_INCLUDE_PATH,        X11_xcb_xkb_LIB,        X11_xcb_xkb_FOUND,        X11::xcb_xkb
          X11_xcb_xrm_INCLUDE_PATH,        X11_xcb_xrm_LIB,        X11_xcb_xrm_FOUND,        X11::xcb_xrm
          X11_xcb_xtest_INCLUDE_PATH,      X11_xcb_xtest_LIB,      X11_xcb_xtest_FOUND,      X11::xcb_xtest
          X11_xcb_xvmc_INCLUDE_PATH,       X11_xcb_xvmc_LIB,       X11_xcb_xvmc_FOUND,       X11::xcb_xvmc
          X11_xcb_xv_INCLUDE_PATH,         X11_xcb_xv_LIB,         X11_xcb_xv_FOUND          X11::xcb_xv
          X11_Xcomposite_INCLUDE_PATH,     X11_Xcomposite_LIB,     X11_Xcomposite_FOUND,     X11::Xcomposite
          X11_Xcursor_INCLUDE_PATH,        X11_Xcursor_LIB,        X11_Xcursor_FOUND,        X11::Xcursor
          X11_Xdamage_INCLUDE_PATH,        X11_Xdamage_LIB,        X11_Xdamage_FOUND,        X11::Xdamage
          X11_Xdmcp_INCLUDE_PATH,          X11_Xdmcp_LIB,          X11_Xdmcp_FOUND,          X11::Xdmcp
          X11_Xext_INCLUDE_PATH,           X11_Xext_LIB,           X11_Xext_FOUND,           X11::Xext
          X11_Xxf86misc_INCLUDE_PATH,      X11_Xxf86misc_LIB,      X11_Xxf86misc_FOUND,      X11::Xxf86misc
          X11_Xxf86vm_INCLUDE_PATH,        X11_Xxf86vm_LIB         X11_Xxf86vm_FOUND,        X11::Xxf86vm
          X11_Xfixes_INCLUDE_PATH,         X11_Xfixes_LIB,         X11_Xfixes_FOUND,         X11::Xfixes
          X11_Xft_INCLUDE_PATH,            X11_Xft_LIB,            X11_Xft_FOUND,            X11::Xft
          X11_Xi_INCLUDE_PATH,             X11_Xi_LIB,             X11_Xi_FOUND,             X11::Xi
          X11_Xinerama_INCLUDE_PATH,       X11_Xinerama_LIB,       X11_Xinerama_FOUND,       X11::Xinerama
          X11_Xkb_INCLUDE_PATH,
          X11_Xkblib_INCLUDE_PATH,                                 X11_Xkb_FOUND,            X11::Xkb
          X11_xkbcommon_INCLUDE_PATH,      X11_xkbcommon_LIB,      X11_xkbcommon_FOUND,      X11::xkbcommon
          X11_xkbcommon_X11_INCLUDE_PATH,  X11_xkbcommon_X11_LIB,  X11_xkbcommon_X11_FOUND,  X11::xkbcommon_X11
          X11_xkbfile_INCLUDE_PATH,        X11_xkbfile_LIB,        X11_xkbfile_FOUND,        X11::xkbfile
          X11_Xmu_INCLUDE_PATH,            X11_Xmu_LIB,            X11_Xmu_FOUND,            X11::Xmu
          X11_Xpm_INCLUDE_PATH,            X11_Xpm_LIB,            X11_Xpm_FOUND,            X11::Xpm
          X11_Xpresent_INCLUDE_PATH,       X11_Xpresent_LIB,       X11_Xpresent_FOUND,       X11::Xpresent
          X11_Xtst_INCLUDE_PATH,           X11_Xtst_LIB,           X11_Xtst_FOUND,           X11::Xtst
          X11_Xrandr_INCLUDE_PATH,         X11_Xrandr_LIB,         X11_Xrandr_FOUND,         X11::Xrandr
          X11_Xrender_INCLUDE_PATH,        X11_Xrender_LIB,        X11_Xrender_FOUND,        X11::Xrender
          X11_XRes_INCLUDE_PATH,           X11_XRes_LIB,           X11_XRes_FOUND,           X11::XRes
          X11_Xss_INCLUDE_PATH,            X11_Xss_LIB,            X11_Xss_FOUND,            X11::Xss
          X11_Xt_INCLUDE_PATH,             X11_Xt_LIB,             X11_Xt_FOUND,             X11::Xt
          X11_Xutil_INCLUDE_PATH,                                  X11_Xutil_FOUND,          X11::Xutil
          X11_Xv_INCLUDE_PATH,             X11_Xv_LIB,             X11_Xv_FOUND,             X11::Xv
          X11_dpms_INCLUDE_PATH,           (in X11_Xext_LIB),      X11_dpms_FOUND
          X11_Xdbe_INCLUDE_PATH,           (in X11_Xext_LIB),      X11_Xdbe_FOUND
          X11_XShm_INCLUDE_PATH,           (in X11_Xext_LIB),      X11_XShm_FOUND
          X11_Xshape_INCLUDE_PATH,         (in X11_Xext_LIB),      X11_Xshape_FOUND
          X11_XSync_INCLUDE_PATH,          (in X11_Xext_LIB),      X11_XSync_FOUND
          X11_Xaw_INCLUDE_PATH,            X11_Xaw_LIB             X11_Xaw_FOUND             X11::Xaw

bestie that's the whole rest of the list, copypasted with love, commas and no-commas exactly as they live in the docs (yes some lines are missing commas, and yes that's just how it is, don't come for me ๐Ÿ’…).

Added in version 3.14: Renamed Xxf86misc, X11_Xxf86misc, X11_Xxf86vm, X11_xkbfile, X11_Xtst, and X11_Xss libraries to match their file names. Deprecated the X11_Xinput library. Old names are still available for compatibility.

ok so the vibes here: some of these got renamed to look like their actual files, and X11_Xinput is officially deprecated ๐Ÿ˜ญ โ€” but don't panic, the old names still hang around for compat, they're not ghosting you.

Added in version 3.14: Added the X11_Xext_INCLUDE_PATH variable.

Added in version 3.18: Added the xcb, X11-xcb, xcb-icccm, xcb-xkb, xkbcommon, and xkbcommon-X11 libraries.

Added in version 3.19: Added the Xaw, xcb_util, and xcb_xfixes libraries.

Added in version 3.24: Added the xcb_randr, xcb_xtext, and xcb_keysyms libraries.

Added in version 3.27: Added the xcb_composite, xcb_cursor, xcb_damage, xcb_dpms, xcb_dri2, xcb_dri3, xcb_errors, xcb_ewmh, xcb_glx, xcb_image, xcb_present, xcb_record, xcb_render, xcb_render_util, xcb_res, xcb_screensaver, xcb_shape, xcb_shm, xcb_sync, xcb_xf86dri, xcb_xinerama, xcb_xinput, xcb_xrm, xcb_xvmc, and xcb_xv libraries.

Added in version 3.29: Added coverage of double buffer extension (variables X11_Xdbe_INCLUDE_PATH and X11_Xdbe_FOUND).


๐ŸŒˆ FindXalanC ๐ŸŒˆ

Added in version 3.5. โœจ

So this one finds the Apache Xalan-C++ XSL transform processor headers and libraries ๐ŸŽ€:

find_package(XalaxC [<version>] [...])
Note: the Xalan-C++ library depends on the Xerces-C++ library (that's the FindXercesC module, go look at it bestie), which must be found for this module to succeed. No Xerces, no Xalan, no slay ๐Ÿ’€.

โœจ Imported Targets โœจ

This module gives you the following imported targets:

  • XalanC::XalanC โ€” the target that wraps up all the Xalan-C++ library usage requirements. It's only there if Xalan-C++ actually gets found ๐Ÿซถ.

โœจ Result Variables โœจ

This module sets these variables:

  • XalanC_FOUND โ€” boolean, tells you whether (the version you asked for of) Xalan-C++ was found ๐Ÿ‘‘.
  • XalanC_VERSION โ€” the version of the Xalan-C++ library that got found.
  • XalanC_INCLUDE_DIRS โ€” the include directories you need to use the Xalan-C++ library. These contain the Xalan-C++ and the Xerces-C++ headers ๐ŸŽ€.
  • XalanC_LIBRARIES โ€” the libraries you need to link against Xalan-C++. These contain the Xalan-C++ and the Xerces-C++ libraries, two-for-one deal fr fr.
  • XalanC_LIBRARY โ€” the path to the Xalan-C++ library (xalan-c), either the release or the debug variant.

โœจ Cache Variables โœจ

These cache variables may also get set:

  • XalanC_INCLUDE_DIR โ€” the directory holding the Xalan-C++ headers.
  • XalanC_LIBRARY_RELEASE โ€” the path to a release (optimized) variant of the Xalan-C++ library ๐Ÿ”ฅ.
  • XalanC_LIBRARY_DEBUG โ€” the path to a debug variant of the Xalan-C++ library.

โœจ Examples โœจ

Finding the Xalan-C++ library and linking it to a project target โ€” literally this:

find_package(XalanC)
target_link_libraries(project_target PRIVATE XalanC::XalanC)

๐Ÿฆ‹ FindXCTest ๐Ÿฆ‹

Added in version 3.3. ๐ŸŽ€

This one finds the XCTest framework, the thing you use for writing unit tests in Xcode projects:

find_package(XCTest [...])
Note: Xcode 16 and later ships the Swift Testing framework for writing unit tests in the Swift programming language, and it supersedes XCTest. So if you're on the new-new, that's the vibe now ๐Ÿ‘€.

An XCTest bundle is a CFBundle (Core Foundation Bundle) with a special product type and a bundle extension ๐Ÿงš. Peep the Apple Developer Library, in the Testing with Xcode documentation, for more:

https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/

โœจ Result Variables โœจ

This module sets these variables:

  • XCTest_FOUND โ€” boolean, says whether the XCTest framework and the executable were found ๐Ÿ’–.
  • XCTest_INCLUDE_DIRS โ€” the include directories containing the XCTest framework headers you need to use XCTest.
  • XCTest_LIBRARIES โ€” the libraries you need to link against to use the XCTest framework.

โœจ Cache Variables โœจ

These cache variables may also get set:

  • XCTest_EXECUTABLE โ€” the path to the xctest command-line tool, the one used to execute XCTest bundles ๐Ÿ”ฅ.

โœจ Commands โœจ

When XCTest gets found, this module hands you the following commands to help create and run XCTest bundles โ€”

xctest_add_bundle

okay so this one creates an XCTest bundle to test a given target ๐ŸŽ€

xctest_add_bundle(<bundle> <testee> [<sources>...])

This command creates an XCTest bundle named <bundle> that will test the specified <testee> target. literally that's the whole vibe ๐Ÿ’…

The arguments are:

  • <bundle> โ€” name of the XCTest bundle to create. The XCTEST target property will be set on this bundle. (yes bestie, the property is just called XCTEST, iconic)
  • <testee> โ€” name of the target to test. Supported types for the testee are Frameworks and App Bundles. that's the whole guest list, no random types allowed ๐Ÿ™ˆ
  • <sources>... โ€” one or more source files to add to the bundle. If not provided, they must be added later using commands like target_sources(). so like, you can ghost the sources for now but you will have to come back for them ๐Ÿ’€
Note: the CMAKE_OSX_SYSROOT variable must be set before using this command. non-negotiable, set it first or it's giving chaos ๐ŸŒธ

xctest_add_test

this one adds an XCTest bundle to the project so it actually gets run during the CTest phase ๐Ÿ”ฅ

xctest_add_test(<name> <bundle>)

This command registers an XCTest bundle to be executed by ctest(1). The test will be named <name> and will run the specified <bundle>. slay, now your tests show up in the test runner ๐Ÿ’–

The arguments are:

  • <name> โ€” name of the test as it will appear in CTest. this is the name everybody sees, make it cute โœจ
  • <bundle> โ€” target name of the XCTest bundle. the actual bundle getting run, no cap

โœจ Examples โœจ

Finding XCTest and adding tests โ€” look at this whole little routine, it ate:

find_package(XCTest)

add_library(foo SHARED foo.c)

if(XCTest_FOUND)
  xctest_add_bundle(TestAppBundle foo source.swift)
  xctest_add_test(app.TestAppBundle TestAppBundle)
endif()

๐Ÿ” FindXercesC

Added in version 3.1. (so it's been around, a real elder ๐Ÿซถ)

Finds the Apache Xerces-C++ validating XML parser headers and libraries:

find_package(XercesC [<version>] [...])

Imported Targets

This module provides the following Imported Targets:

  • XercesC::XercesC โ€” Added in version 3.5. Target encapsulating the Xerces-C++ library (xerces-c) usage requirements, available only if Xerces-C++ is found. so if it's not found, this target simply does not exist, periodt ๐Ÿ’…

Result Variables

This module defines the following variables:

  • XercesC_FOUND โ€” Boolean indicating whether (the requested version of) Xerces-C++ was found. the vibe check โœ…
  • XercesC_VERSION โ€” the version of the found Xerces-C++ library.
  • XercesC_INCLUDE_DIRS โ€” include directories needed to use Xerces-C++.
  • XercesC_LIBRARIES โ€” libraries needed to link for using Xerces-C++.
  • XercesC_LIBRARY โ€” the path to the Xerces-C++ library (xerces-c), either release or debug variant. one path, your pick of flavor ๐Ÿ˜Œ

Cache Variables

The following cache variables may also be set:

  • XercesC_INCLUDE_DIR โ€” the directory containing the Xerces-C++ headers.
  • XercesC_LIBRARY_RELEASE โ€” Added in version 3.4. The path to a release (optimized) variant of the Xerces-C++ library. optimized, she's fast ๐Ÿ’จ
  • XercesC_LIBRARY_DEBUG โ€” Added in version 3.4. The path to a debug variant of the Xerces-C++ library. debug, she talks a lot ๐Ÿ˜ญ

โœจ Examples โœจ

Finding the Xerces-C++ library and linking it to a project target:

find_package(XercesC)
target_link_libraries(project_target PRIVATE XercesC::XercesC)

๐Ÿ” FindXMLRPC

Finds the native XML-RPC library for C and C++:

find_package(XMLRPC [...] [COMPONENTS <components>...] [...])

ngl XML-RPC is a standard network protocol that enables remote procedure calls (RPC) between systems. It encodes requests and responses in XML and uses HTTP as the transport mechanism. old-school but lowkey still working, iykyk ๐ŸŒˆ

Components

The XML-RPC C/C++ library consists of various features (modules) that provide specific functionality. The availability of these features depends on the installed XML-RPC library version and system configuration. Some features also have dependencies on others โ€” so like, some of these girlies refuse to show up unless their friends come too ๐Ÿ™ˆ

To list the available features on a system, the xmlrpc-c-config command-line utility can be used. go ask it directly bestie ๐Ÿ”

In CMake, these features can be specified as components with the find_package() command:

find_package(XMLRPC [COMPONENTS <components>...])

Components may be:

  • c++2 โ€” C++ wrapper API, replacing the legacy c++ feature. the upgrade, the main character ๐Ÿ‘‘
  • c++ โ€” the legacy C++ wrapper API (superseded by c++2). she's retired but still invited to the group chat ๐Ÿ’€
  • client โ€” XML-RPC client functions (also available as the legacy libwww-based feature named libwww-client). yes it has an alias, we don't judge ๐Ÿซถ
  • cgi-server โ€” CGI-based server functions.
  • abyss-server โ€” Abyss-based server functions.
  • pstream-server โ€” the pstream-based server functions.
  • server-util โ€” basic server functions (they are automatically included with *-server features). automatic, she just shows up โœจ
  • abyss โ€” Abyss HTTP server (not needed with abyss-server). redundant queen, skip her if you already have the server one ๐Ÿ™…
  • openssl โ€” OpenSSL convenience functions.

If no components are specified, this module searches for XML-RPC library and its include directories without additional features. no extras, just the base model, no cap ๐Ÿ˜Œ

Result Variables

This module defines the following variables:

  • XMLRPC_FOUND โ€” Boolean indicating whether the XML-RPC library and all its requested components were found. all of them, or it's a no ๐Ÿ’…
  • XMLRPC_INCLUDE_DIRS โ€” include directories containing xmlrpc.h and other headers needed to use the XML-RPC library.
  • XMLRPC_LIBRARIES โ€” list of libraries needed for linking to XML-RPC library and its requested features.

โœจ Examples โœจ

Finding XML-RPC library and its client feature, and conditionally creating an interface imported target that encapsulates its usage requirements for linking to a project target โ€” okay this one is a whole moment, look:

find_package(XMLRPC REQUIRED COMPONENTS client)

if(XMLRPC_FOUND AND NOT TARGET XMLRPC::XMLRPC)
  add_library(XMLRPC::XMLRPC INTERFACE IMPORTED)
  set_target_properties(
    XMLRPC::XMLRPC
    PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${XMLRPC_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${XMLRPC_LIBRARIES}"
  )
endif()

target_link_libraries(example PRIVATE XMLRPC::XMLRPC)

๐Ÿ” FindZLIB

Finds the native zlib data compression library โ€” the squeeze queen herself ๐Ÿ—œ๏ธโœจ

find_package(ZLIB [<version>] [...])

Imported Targets

This module provides the following Imported Targets:

  • ZLIB::ZLIB โ€” Added in version 3.1. Target that encapsulates the zlib usage requirements. It is available only when zlib is found. found only, otherwise she's simply not in the building ๐Ÿฆ‹

Result Variables

This module defines the following variables:

  • ZLIB_FOUND โ€” Boolean indicating whether (the requested version of) zlib was found.
  • ZLIB_VERSION โ€” Added in version 3.26. The version of zlib found.
  • ZLIB_INCLUDE_DIRS โ€” include directories containing zlib.h and other headers needed to use zlib.
  • ZLIB_LIBRARIES โ€” list of libraries needed to link to zlib.
Changed in version 3.4: Debug and Release library variants can be now found separately. two flavors, zero confusion ๐Ÿ’–

Hints

This module accepts the following variables:

  • ZLIB_ROOT โ€” a user may set this variable to a zlib installation root to help locate zlib in custom installation paths. your custom path era, we support it ๐Ÿซถ
  • ZLIB_USE_STATIC_LIBS โ€” Added in version 3.24. Set this variable to ON before calling find_package(ZLIB) to look for static libraries. Default is OFF. static mode, activate her manually โœจ

Deprecated Variables

The following variables are provided for backward compatibility โ€” they're still here for the old code, but like, they know they're legacy ๐Ÿ’€

  • ZLIB_VERSION_MAJOR โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The major version of zlib.
  • ZLIB_VERSION_MINOR โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The minor version of zlib.
  • ZLIB_VERSION_PATCH โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The patch version of zlib.
  • ZLIB_VERSION_TWEAK โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The tweak version of zlib.
  • ZLIB_VERSION_STRING โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The version of zlib found (x.y.z).
  • ZLIB_MAJOR_VERSION โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The major version of zlib.
  • ZLIB_MINOR_VERSION โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The minor version of zlib.
  • ZLIB_PATCH_VERSION โ€” Deprecated since version 3.26: Superseded by ZLIB_VERSION. The patch version of zlib.

โœจ Examples โœจ

Finding zlib and linking it to a project target โ€” short, sweet, zero drama:

find_package(ZLIB)
target_link_libraries(project_target PRIVATE ZLIB::ZLIB)

๐Ÿ’€ DEPRECATED MODULES ๐Ÿ’€

okay so this is the retired shelf. they still exist, they still work, but likeโ€ฆ respectfully, don't start anything new with them ๐Ÿ™ˆ

Deprecated Utility Modules

AddFileDependencies

Deprecated since version 3.20: Do not use this module in new code. fr fr, new code does not need this ๐Ÿšซ

Instead use the set_property() command to append to the OBJECT_DEPENDS source file property directly:

set_property(SOURCE <source> APPEND PROPERTY OBJECT_DEPENDS <files>...)

Load this module in a CMake project with:

include(AddFileDependencies)

Commands

This module provides the following command:

  • add_file_dependencies โ€” adds dependencies to a source file:
add_file_dependencies(<source> <files>...)

This command adds the given <files> to the dependencies of file <source>. simple as that, she's a one-trick icon ๐Ÿ’…


CMakeDetermineVSServicePack

Changed in version 4.1: This module is available only if policy CMP0196 is not set to NEW. so if you set that policy to NEW, this module literally vanishes, bye ๐Ÿ˜ญ

Deprecated since version 3.0: This module should no longer be used. The functionality of this module has been superseded by the CMAKE_<LANG>_COMPILER_VERSION variable that contains the compiler version number. that variable is the upgrade, use her instead โœจ

This module provides a command to determine the installed Visual Studio service pack version for Visual Studio 2012 and earlier. ancient era, but we keep the receipts ๐Ÿบ

Load this module in a CMake project with:

include(CMakeDetermineVSServicePack)

Commands

This module provides the following command:

  • DetermineVSServicePack โ€” determines the Visual Studio service pack version of the cl compiler in use:
DetermineVSServicePack(<variable>)

The result is stored in the specified internal cache variable <variable>, which is set to one of the following values, or to an empty string if the service pack cannot be determined:

  • vc80, vc80sp1
  • vc90, vc90sp1
  • vc100, vc100sp1
  • vc110, vc110sp1, vc110sp2, vc110sp3, vc110sp4

so like, it's giving dropdown menu of ancient service packs ๐Ÿ’€ no cap, that's the full list

โœจ Examples โœจ

Determining the Visual Studio service pack version in a project:

          if(MSVC)
            include(CMakeDetermineVSServicePack)
            DetermineVSServicePack(my_service_pack)
            if(my_service_pack)
              message(STATUS "Detected: ${my_service_pack}")
            endif()
          endif()

๐Ÿ’€ CMakeExpandImportedTargets

Deprecated since version 3.4: bestie, this module should no longer be used. Like, at all. It's giving Blockbuster membership card. ๐Ÿ˜ญ

Okay so history lesson real quick ๐Ÿ•ฐ๏ธ โ€” back in the day you needed this to replace Imported Targets with their actual on-disk libraries so you could pass them to try_compile() and try_run(). But those commands now support imported targets right in their LINK_LIBRARIES options (since CMake 2.8.11 for the try_compile() command and since CMake 3.2 for the try_run() command). So yeah. It ate its purpose and now it's just vibing. ๐Ÿ’…

You load it in a CMake project like:

include(CMakeExpandImportedTargets)
Note: โš ๏ธ This module does not support the CMP0022 NEW behavior, and it does not use the INTERFACE_LINK_LIBRARIES property โ€” and the reason is genuinely iconic: generator expressions cannot be evaluated at the configuration phase. Periodt. ๐Ÿซถ

Commands

This module provides the following command:

cmake_expand_imported_targets

Expands every imported target in a given list of libraries into its corresponding file paths on disk, and drops the resulting list into a local variable:

cmake_expand_imported_targets(
  <result-var>
  LIBRARIES <libs>...
  [CONFIGURATION <config>]
)

The arguments are, bestie:

  • <result-var> โ€” the name of a CMake variable that'll hold the resulting list of file paths. โœจ
  • LIBRARIES <libs>... โ€” a semicolon-separated list of system and imported targets. Imported targets in this list get replaced with their corresponding library file paths, including libraries from their link interfaces. ๐Ÿ’–
  • CONFIGURATION <config> โ€” if this option is given, it uses the respective build configuration of the imported targets if it exists. If omitted, it defaults to the first entry in the CMAKE_CONFIGURATION_TYPES variable, or falls back to CMAKE_BUILD_TYPE if CMAKE_CONFIGURATION_TYPES is not set. ๐ŸŒธ

Examples

Using this module to get a list of library paths, lowkey a classic:

include(CMakeExpandImportedTargets)
cmake_expand_imported_targets(
  expandedLibs
  LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}
  CONFIGURATION "${CMAKE_TRY_COMPILE_CONFIGURATION}"
)

๐Ÿฆ‹ CMakeFindFrameworks

Deprecated since version 3.31: this module does nothing, unless policy CMP0173 is set to OLD. It's giving ghost ๐Ÿ‘ป โ€” technically present, zero output.

Helper module to find OSX frameworks. ๐Ÿ“

This module reads hints about search locations from variables:

CMAKE_FIND_FRAMEWORK_EXTRA_LOCATIONS - Extra directories

That's it. That's the whole hint list. Short king. ๐Ÿ‘‘


๐Ÿ™ˆ CMakeForceCompiler

Deprecated since version 3.6: Do not use. Like, I'm not even gonna soften that one. ๐Ÿ™…โ€โ™€๏ธ

The commands this module provides were once intended for cross-compiling toolchain files back when CMake couldn't automatically detect the compiler identification. But since the introduction of this module, CMake's compiler identification capabilities have improved so much and can now be taught to recognize any compiler. And honestly? The suite of information CMake detects from a compiler is now too extensive to be provided by toolchain files using these macros. It outgrew them. ๐Ÿ’…

One common use case was skipping CMake's checks for a working compiler when using a cross-compiler that can't link binaries without special flags or custom linker scripts. That case is now supported by setting the CMAKE_TRY_COMPILE_TARGET_TYPE variable in the toolchain file instead. Slay, honestly. โœจ

You load this module in a CMake toolchain file:

include(CMakeForceCompiler)

Commands

This module provides the following commands:

  • cmake_force_c_compiler โ€” Sets the CMAKE_C_COMPILER variable to the given compiler and the CMAKE_C_COMPILER_ID variable to the given compiler-id:
cmake_force_c_compiler(<compiler> <compiler-id>)

This command also bypasses the check for working compiler and basic compiler information tests. ๐Ÿšจ

  • cmake_force_cxx_compiler โ€” Sets the CMAKE_CXX_COMPILER variable to the given compiler and the CMAKE_CXX_COMPILER_ID variable to the given compiler-id:
cmake_force_cxx_compiler(<compiler> <compiler-id>)

This command also bypasses the check for working compiler and basic compiler information tests. ๐Ÿšจ

  • cmake_force_fortran_compiler โ€” Sets the CMAKE_Fortran_COMPILER variable to the given compiler and the CMAKE_Fortran_COMPILER_ID variable to the given compiler-id:
cmake_force_fortran_compiler(<compiler> <compiler-id>)

This command also bypasses the check for working compiler and basic compiler information tests. ๐Ÿšจ

Examples

A simple toolchain file using this module could look like this ๐Ÿ‘‡

cmake/toolchains/example-toolchain.cmake

include(CMakeForceCompiler)
set(CMAKE_SYSTEM_NAME Generic)
cmake_force_c_compiler(chc12 MetrowerksHicross)
cmake_force_cxx_compiler(chc12 MetrowerksHicross)

In new CMake code, the compiler is detected automatically when setting the required variables instead โ€” look how much cleaner, I'm obsessed ๐Ÿ˜ญโœจ

cmake/toolchains/example-toolchain.cmake

set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_C_COMPILER chc12)
set(CMAKE_CXX_COMPILER chc12)

See Also


๐ŸŽ€ CMakeParseArguments

Deprecated since version 3.5.

This module once implemented the cmake_parse_arguments() command that is now implemented natively by CMake. So now? It's literally just an empty placeholder for compatibility with projects that include it to get the command from CMake 3.4 and lower. A shell of its former self. It's giving alumni returning to campus. ๐ŸŽ“


๐Ÿ’€ Dart

Deprecated since version 3.27: this module is available only if policy CMP0145 is not set to NEW. Do not use it in new code, fr fr. Use the CTest module instead. ๐Ÿซถ

Configure a project for testing with CTest or the old Dart Tcl Client. ๐Ÿ•ฐ๏ธ

This file is the backwards-compatibility version of the CTest module. It supports using the old Dart 1 Tcl client for driving dashboard submissions, as well as testing with CTest. This module should be included in the CMakeLists.txt file at the top of a project. Typical usage, bestie:

include(Dart)
if(BUILD_TESTING)
  # ... testing related CMake code ...
endif()

The BUILD_TESTING option is created by the Dart module to determine whether testing support should be enabled. The default is ON. โœ…


๐Ÿ“œ Documentation

Deprecated since version 3.18: this module does nothing, unless policy CMP0106 is set to OLD. Nothing! Zero! Nada! ๐Ÿ’€

This module provides support for the VTK documentation framework. It relies on several tools (Doxygen, Perl, etc). Cute historical artifact ngl. ๐Ÿบ


๐Ÿงš GetPrerequisites

Deprecated since version 3.16: use file(GET_RUNTIME_DEPENDENCIES) instead. That's the upgrade, bestie, take it. ๐Ÿ’…

This module provides commands to analyze and list the dependencies (prerequisites) of executable or shared library files. These commands list the shared libraries (.dll, .dylib, or .so files) required by an executable or shared library. ๐ŸŒˆ

Load this module in CMake with:

include(GetPrerequisites)

This module determines dependencies using the following platform-specific tools:

  • dumpbin (Windows)
  • objdump (MinGW on Windows)
  • ldd (Linux/Unix)
  • otool (Apple operating systems)
Changed in version 3.16: the tool specified by the CMAKE_OBJDUMP variable will be used, if set. โญ

Commands

This module provides the following commands:

  • get_prerequisites()
  • list_prerequisites()
  • list_prerequisites_by_glob()
  • gp_append_unique()
  • is_file_executable()
  • gp_item_default_embedded_path() (projects can override it with gp_item_default_embedded_path_override())
  • gp_resolve_item() (projects can override it with gp_resolve_item_override())
  • gp_resolved_file_type() (projects can override it with gp_resolved_file_type_override())
  • gp_file_type()

get_prerequisites

Gets the list of shared library files required by the specified target:

get_prerequisites(<target> <prerequisites-var> <exclude-system> <recurse>
                  <exepath> <dirs> [<rpaths>])

The list in the variable named <prerequisites-var> should be empty on first entry to this command. On exit, <prerequisites-var> will contain the list of required shared library files. ๐Ÿ™

The arguments are:

  • <target> โ€” the full path to an executable or shared library file. ๐ŸŽฏ
  • <prerequisites-var> โ€” the name of a CMake variable to contain the results.
  • <exclude-system> โ€” if set to 1, system prerequisites will be excluded; if set to 0 they will be included. ๐Ÿšฆ
  • <recurse> โ€” if set to 1, all prerequisites will be found recursively; if set to 0, only direct prerequisites are listed. ๐Ÿ”
  • <exepath> โ€” the path to the top level executable used for @executable_path replacement on Apple operating systems. ๐ŸŽ
  • <dirs> โ€” a list of paths where libraries might be found: these paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib... ๐Ÿ“‚
  • <rpaths> โ€” optional run-time search paths for an executable file or library to help find files.
Added in version 3.14: the variable GET_PREREQUISITES_VERBOSE can be set to true before calling this command to enable verbose output. ๐Ÿ—ฃ๏ธ

list_prerequisites

Prints a message listing the prerequisites of the specified target:

list_prerequisites(<target> [<recurse> [<exclude-system> [<verbose>]]])

The arguments are:

  • <target> โ€” the name of a shared library or executable target, or the full path to a shared library or executable file. ๐Ÿ“
  • <recurse> โ€” set it to 1 and every prerequisite gets found recursively (all the way down, no cap ๐Ÿ’…); set it to 0 and you only get the direct prerequisites, nothing deeper.
  • <exclude-system> โ€” set it to 1 and system prerequisites get left out; set it to 0 and they're included. Your call bestie.
  • <verbose> โ€” 0 means you get just the full path names of the prerequisites, nothing extra. 1 means you get extra information displayed on top of that. The way that extra info just shows up โœจ

list_prerequisites_by_glob

Prints the prerequisites of shared library and executable files matching a globbing pattern:

list_prerequisites_by_glob(<GLOB|GLOB_RECURSE>
                           <glob-exp>
                           [<optional-args>...])

The arguments are:

  • GLOB or GLOB_RECURSE โ€” the globbing mode: do you traverse only the match, or also its subdirectories recursively? Pick your fighter ๐Ÿซถ
  • <glob-exp> โ€” a globbing expression used with file(GLOB) <#glob> or file(GLOB_RECURSE) <#glob-recurse> to retrieve a list of matching files. If a matching file is executable, its prerequisites are listed. Only if it's executable, no cap.
  • <optional-args>... โ€” any additional (optional) arguments you provide get passed along as the optional arguments to the list_prerequisite() calls. Mmm, delegation ๐ŸŽ€

gp_append_unique

Appends the value to the list only if it is not already in the list:

gp_append_unique(<list-var> <value>)

The arguments are:

  • <value> โ€” the value to be appended to the list. That's it, that's the whole job ๐Ÿ’–
  • <list-var> โ€” the list variable name that will have the value appended only if it is not already in the list. No duplicates allowed, we don't do repeats here ๐Ÿšซ

is_file_executable

Checks if given file is a binary executable:

is_file_executable(<file> <result-var>)

This command sets the <result-var> to 1 if <file> is a binary executable; otherwise it sets it to 0. Binary executable or not, that's the whole vibe check โœ…

gp_item_default_embedded_path

Determines the reference path for the specified item:

gp_item_default_embedded_path(<item> <default-embedded-path-var>)

This command determines the reference path for <item> when it is embedded inside a bundle and stores it to a variable <default-embedded-path-var>.

Projects can override this command by defining a custom gp_item_default_embedded_path_override() command. Override privileges: granted ๐Ÿ‘‘

gp_resolve_item

Resolves a given item into an existing full path file and stores it to a variable:

gp_resolve_item(<context> <item> <exepath> <dirs> <resolved-item-var>
                [<rpaths>])

The arguments are:

  • <context> โ€” the path to the top level loading path used for @loader_path replacement on Apple operating systems. When resolving item, @loader_path references will be resolved relative to the directory of the given context value (presumably another library). Presumably ๐Ÿ’€
  • <item> โ€” the item to resolve. Short king of an argument.
  • <exepath> โ€” see the argument description in get_prerequisites().
  • <dirs> โ€” see the argument description in get_prerequisites().
  • <resolved-item-var> โ€” the result variable where the resolved item is stored into.
  • <rpaths> โ€” see the argument description in get_prerequisites().

Projects can override this command by defining a custom gp_resolve_item_override() command. Custom override era ๐Ÿ’…

gp_resolved_file_type

Determines the type of a given file:

gp_resolved_file_type(<original-file> <file> <exepath> <dirs> <type-var>
                      [<rpaths>])

This command determines the type of <file> with respect to the <original-file>. The resulting type of prerequisite is stored in the <type-var> variable.

Use <exepath> and <dirs> if necessary to resolve non-absolute <file> values โ€” but only for non-embedded items. Read that again, it matters ๐Ÿซถ

  • <rpaths> โ€” see the argument description in get_prerequisites().

The <type-var> variable will be set to one of the following values:

  • system
  • local
  • embedded
  • other

Pick one of those four, those are the options, periodt.

Projects can override this command by defining a custom gp_resolved_file_type_override() command.

gp_file_type

Determines the type of a given file:

gp_file_type(<original-file> <file> <type-var>)

This command determines the type of <file> with respect to the <original-file>. The resulting type of prerequisite is stored in the <type-var> variable.

The <type-var> variable will be set to one of the following values:

  • system
  • local
  • embedded
  • other

Same four vibes as before, just without the <exepath>/<dirs>/<rpaths> situation ๐Ÿฆ‹


Examples ๐ŸŒˆ

Example: Basic Usage

Printing all dependencies of a shared library, including system libraries, with verbose output:

include(GetPrerequisites)
list_prerequisites("path/to/libfoo.dylib" 1 0 1)

Example: Upgrading Code

For example:

include(GetPrerequisites)
# ...
gp_append_unique(keys "${key}")

the gp_append_unique() can be in new code replaced with:

if(NOT key IN_LIST keys)
  list(APPEND keys "${key}")
endif()

Glow-up complete ๐Ÿ’–


MacroAddFileDependencies

Deprecated since version 3.14: Do not use this module in new code. ๐Ÿšจ

Instead use the set_property() <#command:set_property> command to append to the OBJECT_DEPENDS <#prop_sf:OBJECT_DEPENDS> source file property directly:

set_property(SOURCE <source> APPEND PROPERTY OBJECT_DEPENDS <files>...)

Load this module in a CMake project with:

include(MacroAddFileDependencies)

Commands

This module provides the following command:

macro_add_file_dependencies

Adds dependencies to a source file:

macro_add_file_dependencies(<source> <files>...)

This command adds the given <files> to the dependencies of file <source>. Yeah. That's the whole thing ๐Ÿ˜ญ (please use set_property() instead though, i'm literally begging)


TestBigEndian

Deprecated since version 3.20: Superseded by the CMAKE_<LANG>_BYTE_ORDER <#variable:CMAKE_<LANG>_BYTE_ORDER> variable. ๐Ÿ’€

This module provides a command to check the endianness (byte order) of the target architecture.

Load this module in a CMake project with:

include(TestBigEndian)

Commands

This module provides the following command:

test_big_endian

Checks if the target architecture is big-endian or little-endian:

test_big_endian(<var>)

This command stores in variable <var> either 1 or 0 indicating whether the target architecture is big or little endian.

At least one of the supported languages must be enabled in CMake project when using this command. Don't skip this step bestie, it will Not work ๐Ÿ”ฅ

Supported languages are C, CXX.

Changed in version 3.20: This command is now mainly a wrapper around the CMAKE_<LANG>_BYTE_ORDER <#variable:CMAKE_<LANG>_BYTE_ORDER> where also OBJC, OBJCXX, and CUDA languages are supported. Modern era โœจ

Examples

Example: Checking Endianness

Checking endianness of the target architecture with this module and storing the result in a CMake variable WORDS_BIGENDIAN:

include(TestBigEndian)
test_big_endian(WORDS_BIGENDIAN)

Example: Checking Endianness in New Code

As of CMake 3.20, this module should be replaced with the CMAKE_<LANG>_BYTE_ORDER <#variable:CMAKE_<LANG>_BYTE_ORDER> variable. For example, in a project, where C language is one of the enabled languages:

if(CMAKE_C_BYTE_ORDER STREQUAL "BIG_ENDIAN")
  set(WORDS_BIGENDIAN TRUE)
elseif(CMAKE_C_BYTE_ORDER STREQUAL "LITTLE_ENDIAN")
  set(WORDS_BIGENDIAN FALSE)
else()
  set(WORDS_BIGENDIAN FALSE)
  message(WARNING "Endianness could not be determined.")
endif()

Look at that fallback branch handling the unknown case, we love a responsible queen ๐Ÿ‘‘


TestCXXAcceptsFlag

Deprecated since version 3.0: This module should no longer be used. It has been superseded by the CheckCXXCompilerFlag <#module:CheckCXXCompilerFlag> module. As of CMake 3.19, the CheckCompilerFlag <#module:CheckCompilerFlag> module is also available for checking flags across multiple languages. ๐Ÿšจ

This module provides a command to test whether the C++ (CXX) compiler supports specific flags.

Load this module in a CMake project with:

include(TestCXXAcceptsFlag)

Commands

This module provides the following command:

check_cxx_accepts_flag

Checks whether the CXX compiler accepts the specified flags:

check_cxx_accepts_flag(<flags> <result-variable>)
  • <flags> โ€” one or more compiler flags to test. For multiple flags, provide them as a space-separated string. Space. Separated. String. Not a list, bestie, i learned that the hard way ๐Ÿ˜ญ
  • <result-variable> โ€” name of an internal cache variable that stores the result. It is set to boolean true if the compiler accepts the flags and false otherwise. Internal cache variable, so it's giving secret keeper ๐ŸŽ€

Examples

Checking if the C++ compiler supports specific flags:

include(TestCXXAcceptsFlag)
check_cxx_accepts_flag("-fno-common -fstack-clash-protection" HAVE_FLAGS)

Migrating to the CheckCompilerFlag <#module:CheckCompilerFlag> module:

include(CheckCompilerFlag)
check_compiler_flag(CXX "-fno-common;-fstack-clash-protection" HAVE_FLAGS)

Notice the semicolon instead of the space up in there โ€” that's a list now, and that is Not the same thing ๐Ÿ‘€


Use_wxWindows

Deprecated since version 2.8.10: This module should no longer be used. Use find_package(wxWidgets) <#module:FindwxWidgets> instead. ๐Ÿ’…

This module serves as a convenience wrapper for finding the wxWidgets library (formerly known as wxWindows) and propagates its usage requirements, such as libraries, include directories, and compiler flags, into the current directory scope for use by targets.

Load this module in a CMake project with:

include(Use_wxWindows)

Examples

In earlier versions of CMake, wxWidgets (wxWindows) could be found and used in the current directory like this:

CMakeLists.txt

include(Use_wxWindows)

To request OpenGL support, the WXWINDOWS_USE_GL variable could be set before including this module:

CMakeLists.txt

set(WXWINDOWS_USE_GL ON)
include(Use_wxWindows)

add_library(example example.cxx)

Starting with CMake 3.0, wxWidgets can be found using the FindwxWidgets <#module:FindwxWidgets> module, which provides the wxWidgets usage requirements either using result variables or imported target as of CMake 3.27:

CMakeLists.txt

find_package(wxWidgets)

add_library(example example.cxx)

target_link_libraries(example PRIVATE wxWidgets::wxWidgets)

Imported target wxWidgets::wxWidgets โ€” the main character of this migration, honestly ๐ŸŒŸ

UseJavaClassFilelist ๐Ÿซถ

Changed in version 3.20: okay so this module was literally documented by mistake โ€” no cap, it was never meant for project code to include it directly ๐Ÿ˜ญ. See the UseJava module instead, bestie.


Changed in version 3.20: same situation, same energy โ€” this one got documented by accident too and was never meant for direct inclusion by project code ๐Ÿ’€. Go look at the UseJava module.


UsePkgConfig ๐ŸŽ€

Deprecated since version 3.0: bestie, put it down. This module should no longer be used. Use the FindPkgConfig module or the cmake_pkg_config() command instead โœจ

This module handed you a command for finding external packages by way of the pkg-config command-line utility. It's been replaced by the way more convenient FindPkgConfig module, which is what everyone actually uses in Find Modules ๐ŸŒธ.

And as of CMake 3.31, the built-in cmake_pkg_config() command gives you even more features for extracting package information ๐Ÿ‘‘.

Load this module in a CMake project with:

include(UsePkgConfig)

Commands ๐Ÿ’…

This module provides the following command:

pkgconfig

Finds an external package using pkg-config and sets the result variables:

pkgconfig(<package> <includedir> <libdir> <linkflags> <cflags>)

This command invokes the pkg-config command-line utility to pull the package information into the variables you specified. If pkg-config โ€” or the specified <package> โ€” is NOT found, the result variables just stay empty (no drama, but also no data ๐Ÿ™ˆ).

The arguments are:

  • <package> โ€” the name of the package as defined in its PC metadata file (<package>.pc).
  • <includedir> โ€” variable name to store the package's include directory.
  • <libdir> โ€” variable name to store the directory containing the package library.
  • <linkflags> โ€” variable name to store the linker flags for the package.
  • <cflags> โ€” variable name to store the compiler flags for the package.

Examples ๐ŸŒŸ

Using this module fills the desired info into the four given variables:

include(UsePkgConfig)
pkgconfig(
  libart-2.0
  LIBART_INCLUDEDIR
  LIBART_LIBDIR
  LIBART_LDFLAGS
  LIBART_CFLAGS
)

Migrating to FindPkgConfig would look something like this:

find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
  pkg_check_modules(LIBART QUIET libart-2.0)
endif()

message(STATUS "LIBART_INCLUDEDIR=${LIBART_INCLUDEDIR}")
message(STATUS "LIBART_LIBDIR=${LIBART_LIBDIR}")
message(STATUS "LIBART_LDFLAGS=${LIBART_LDFLAGS}")
message(STATUS "LIBART_CFLAGS=${LIBART_CFLAGS}")

WriteBasicConfigVersionFile ๐Ÿฆ‹

Deprecated since version 3.0: use the identical command write_basic_package_version_file() from module CMakePackageConfigHelpers instead, bestie ๐Ÿ’–
WRITE_BASIC_CONFIG_VERSION_FILE(filename
  [VERSION major.minor.patch]
  COMPATIBILITY (AnyNewerVersion|SameMajorVersion|SameMinorVersion|
                 SamePatchVersion|SameFullVersion|ExactVersion|
                 SemanticVersion)
  [ARCH_INDEPENDENT]
  )

WriteCompilerDetectionHeader ๐Ÿ’€

Deprecated since version 3.20: this module is only available if policy CMP0120 is not set to NEW. Do not use it in new code, fr fr ๐Ÿšซ

Added in version 3.1.

This module provides a command that generates a header full of preprocessor macros โœจ.

Load this module in a CMake project with:

include(WriteCompilerDetectionHeader)

Commands ๐ŸŽ€

This module provides the following command:

write_compiler_detection_header

This function can be used to generate a file that's suitable for preprocessor inclusion, containing macros you can use in your source code:

write_compiler_detection_header(
          FILE <file>
          PREFIX <prefix>
          [OUTPUT_FILES_VAR <output_files_var> OUTPUT_DIR <output_dir>]
          COMPILERS <compiler> [...]
          FEATURES <feature> [...]
          [BARE_FEATURES <feature> [...]]
          [VERSION <version>]
          [PROLOG <prolog>]
          [EPILOG <epilog>]
          [ALLOW_UNKNOWN_COMPILERS]
          [ALLOW_UNKNOWN_COMPILER_VERSIONS]
)

This generates the file <file> with macros that all carry the prefix <prefix> ๐Ÿ’….

By default, all the content is written straight into <file>. But you can specify OUTPUT_FILES_VAR to make the compiler-specific content get written to separate files instead. Those separate files then show up in <output_files_var> and can be consumed by the caller โ€” for installation, for example ๐Ÿ‘‘. OUTPUT_DIR specifies a relative path from the main <file> to those compiler-specific files. Like so:

write_compiler_detection_header(
  FILE climbingstats_compiler_detection.h
  PREFIX ClimbingStats
  OUTPUT_FILES_VAR support_files
  OUTPUT_DIR compilers
  COMPILERS GNU Clang MSVC Intel
  FEATURES cxx_variadic_templates
)
install(FILES
  ${CMAKE_CURRENT_BINARY_DIR}/climbingstats_compiler_detection.h
  DESTINATION include
)
install(FILES
  ${support_files}
  DESTINATION include/compilers
)

VERSION lets you specify the API version to generate. Future versions of CMake may introduce alternative APIs, and a given API is selected by any <version> value that's greater than or equal to the version of CMake that introduced that API and less than the version of CMake that introduced the API after it. If you don't specify an explicit version, the value of the CMAKE_MINIMUM_REQUIRED_VERSION variable gets used. (As of CMake version 4.4.5 there is only one API version โ€” so, one single icon, no competition ๐ŸŒˆ.)

PROLOG can be given as text content to write at the start of the header. EPILOG can be given as text content to write at the end of the header ๐ŸŒธ.

At least one <compiler> and one <feature> must be listed, periodt. Compilers that CMake knows about but that you did not specify get detected, and a preprocessor #error gets generated for them ๐Ÿ˜ญ. A preprocessor macro matching <PREFIX>_COMPILER_IS_<compiler> is generated for each compiler known to CMake, containing the value 0 or 1.

The possible compiler identifiers are documented with the CMAKE_<LANG>_COMPILER_ID variable. The features available in this version of CMake are listed in the CMAKE_C_KNOWN_FEATURES and CMAKE_CXX_KNOWN_FEATURES global properties. See the cmake-compile-features(7) manual for info on compile features ๐Ÿ“š.

Added in version 3.2: added MSVC and AppleClang compiler support ๐ŸŽ‰.

Added in version 3.6: added Intel compiler support.

Changed in version 3.8: the {c,cxx}_std_* meta-features are ignored if requested ๐Ÿ™ˆ.

Added in version 3.8: ALLOW_UNKNOWN_COMPILERS and ALLOW_UNKNOWN_COMPILER_VERSIONS cause the module to generate conditions that treat unknown compilers as simply lacking all features. Without these options, the default behavior is to generate a #error for unknown compilers and versions ๐Ÿ’€.

Added in version 3.12: BARE_FEATURES will define the compatibility macros with the name used in newer versions of the language standard, so the code can use the new feature name unconditionally โœจ.

Feature Test Macros ๐Ÿงš

For each compiler, a preprocessor macro is generated matching <PREFIX>_COMPILER_IS_<compiler>, which has the content either 0 or 1 depending on the compiler in use. Preprocessor macros for the compiler version components are generated matching <PREFIX>_COMPILER_VERSION_MAJOR, <PREFIX>_COMPILER_VERSION_MINOR and <PREFIX>_COMPILER_VERSION_PATCH, containing decimal values for the corresponding compiler version components โ€” if they're defined ๐Ÿ’–.

A preprocessor test gets generated based on the compiler version, denoting whether each feature is enabled. A preprocessor macro matching <PREFIX>_COMPILER_<FEATURE> โ€” where <FEATURE> is the upper-case <feature> name โ€” is generated to contain the value 0 or 1 depending on whether the compiler in use supports the feature:

write_compiler_detection_header(
  FILE climbingstats_compiler_detection.h
  PREFIX ClimbingStats
  COMPILERS GNU Clang AppleClang MSVC Intel
  FEATURES cxx_variadic_templates
)

#if ClimbingStats_COMPILER_CXX_VARIADIC_TEMPLATES
template<typename... T>
void someInterface(T t...) { /* ... */ }
#else
// Compatibility versions
template<typename T1>
void someInterface(T1 t1) { /* ... */ }
template<typename T1, typename T2>
void someInterface(T1 t1, T2 t2) { /* ... */ }
template<typename T1, typename T2, typename T3>
void someInterface(T1 t1, T2 t2, T3 t3) { /* ... */ }
#endif

Symbol Macros ๐Ÿ“

Some extra symbol-defines are created for particular features, for use as symbols that may be conditionally defined empty:

class MyClass ClimbingStats_FINAL
{
    ClimbingStats_CONSTEXPR int someInterface() { return 42; }
};

The ClimbingStats_FINAL macro will expand to final if the compiler (and its flags) support the cxx_final feature, and the ClimbingStats_CONSTEXPR macro will expand to constexpr if cxx_constexpr is supported ๐Ÿ”ฅ.

If BARE_FEATURES cxx_final was given as an argument, the final keyword will be defined for old compilers too, bestie ๐Ÿ’œ.

The following features generate corresponding symbol defines, and if they're available as BARE_FEATURES, they get that too:

  • c_restrict โ€” define: <PREFIX>_RESTRICT, symbol: restrict, bare: yes โœจ
  • cxx_constexpr โ€” define: <PREFIX>_CONSTEXPR, symbol: constexpr, bare: yes โœจ
  • cxx_deleted_functions โ€” define: <PREFIX>_DELETED_FUNCTION, symbol: = delete, bare: (nope, blank)
  • cxx_extern_templates โ€” define: <PREFIX>_EXTERN_TEMPLATE, symbol: extern, bare: (blank)
  • cxx_final โ€” define: <PREFIX>_FINAL, symbol: final, bare: yes โœจ
  • cxx_noexcept โ€” define: <PREFIX>_NOEXCEPT, symbol: noexcept, bare: yes โœจ
  • cxx_noexcept โ€” define: <PREFIX>_NOEXCEPT_EXPR(X), symbol: noexcept(X), bare: (blank)
  • cxx_override โ€” define: <PREFIX>_OVERRIDE, symbol: override, bare: yes โœจ

๐Ÿงš Compatibility Implementation Macros

Okay so some of these features are literally built to be wrapped in a macro that has a backward-compat implementation, for when the compiler just doesn't support the feature. No cap.

When the cxx_static_assert feature isn't provided by the compiler, there's a compatibility implementation waiting for you via the <PREFIX>_STATIC_ASSERT(COND) and <PREFIX>_STATIC_ASSERT_MSG(COND, MSG) function-like macros. These macros expand to static_assert where that compiler feature is available, and to a compatibility implementation otherwise. In the first form, the condition is stringified in the message field of static_assert. In the second form, the message MSG is passed to the message field of static_assert, or ignored if you're using the backward compatibility implementation.

The cxx_attribute_deprecated feature provides a macro definition <PREFIX>_DEPRECATED, which expands to either the standard [[deprecated]] attribute or a compiler-specific decorator such as __attribute__((__deprecated__)) used by GNU compilers. ๐Ÿ’…

The cxx_alignas feature provides a macro definition <PREFIX>_ALIGNAS which expands to either the standard alignas decorator or a compiler-specific decorator such as __attribute__ ((__aligned__)) used by GNU compilers.

The cxx_alignof feature provides a macro definition <PREFIX>_ALIGNOF which expands to either the standard alignof decorator or a compiler-specific decorator such as __alignof__ used by GNU compilers.

  • cxx_alignas โ€” define: <PREFIX>_ALIGNAS, symbol: alignas, bare: (blank)
  • cxx_alignof โ€” define: <PREFIX>_ALIGNOF, symbol: alignof, bare: (blank)
  • cxx_nullptr โ€” define: <PREFIX>_NULLPTR, symbol: nullptr, bare: yes โœจ
  • cxx_static_assert โ€” define: <PREFIX>_STATIC_ASSERT, symbol: static_assert, bare: (blank)
  • cxx_static_assert โ€” define: <PREFIX>_STATIC_ASSERT_MSG, symbol: static_assert, bare: (blank)
  • cxx_attribute_deprecated โ€” define: <PREFIX>_DEPRECATED, symbol: [[deprecated]], bare: (blank)
  • cxx_attribute_deprecated โ€” define: <PREFIX>_DEPRECATED_MSG, symbol: [[deprecated]], bare: (blank)
  • cxx_thread_local โ€” define: <PREFIX>_THREAD_LOCAL, symbol: thread_local, bare: (blank)

A use-case which arises with such deprecation macros is the deprecation of an entire library. In that case, all public API in the library may be decorated with the <PREFIX>_DEPRECATED macro. This results in very noisy build output when building the library itself, so the macro may be may be defined to empty in that case when building the deprecated library:

add_library(compat_support ${srcs})
target_compile_definitions(compat_support
  PRIVATE
    CompatSupport_DEPRECATED=
)

๐ŸŒˆ Example Usage

Note: This section was migrated from the cmake-compile-features(7) manual since it relies on the WriteCompilerDetectionHeader module which is removed by policy CMP0120.

Compile features may be preferred if available, without creating a hard requirement. For example, a library may provide alternative implementations depending on whether the cxx_variadic_templates feature is available:

#if Foo_COMPILER_CXX_VARIADIC_TEMPLATES
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();
  }
};
#else
template<int I1, int I2 = 0, int I3 = 0, int I4 = 0>
struct Interface
{
  static int accumulate() { return I1 + I2 + I3 + I4; }
};
#endif

Such an interface depends on using the correct preprocessor defines for the compiler features. CMake can generate a header file containing such defines using the WriteCompilerDetectionHeader module. The module contains the write_compiler_detection_header function which accepts parameters to control the content of the generated header file:

write_compiler_detection_header(
  FILE "${CMAKE_CURRENT_BINARY_DIR}/foo_compiler_detection.h"
  PREFIX Foo
  COMPILERS GNU
  FEATURES
    cxx_variadic_templates
)

Such a header file may be used internally in the source code of a project, and it may be installed and used in the interface of library code. ๐Ÿซถ

For each feature listed in FEATURES, a preprocessor definition is created in the header file, and defined to either 1 or 0.

Additionally, some features call for additional defines, such as the cxx_final and cxx_override features. Rather than being used in #ifdef code, the final keyword is abstracted by a symbol which is defined to either final, a compiler-specific equivalent, or to empty. That way, C++ code can be written to unconditionally use the symbol, and compiler support determines what it is expanded to:

struct Interface {
  virtual void Execute() = 0;
};

struct Concrete Foo_FINAL {
  void Execute() Foo_OVERRIDE;
};

In this case, Foo_FINAL will expand to final if the compiler supports the keyword, or to empty otherwise. Iconic behaviour honestly.

In this use-case, the project code may wish to enable a particular language standard if available from the compiler. The CXX_STANDARD target property may be set to the desired language standard for a particular target, and the CMAKE_CXX_STANDARD variable may be set to influence all following targets:

write_compiler_detection_header(
  FILE "${CMAKE_CURRENT_BINARY_DIR}/foo_compiler_detection.h"
  PREFIX Foo
  COMPILERS GNU
  FEATURES
    cxx_final cxx_override
)

# Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
# which will expand to 'final' if the compiler supports the requested
# CXX_STANDARD.
add_library(foo foo.cpp)
set_property(TARGET foo PROPERTY CXX_STANDARD 11)

# Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
# which will expand to 'final' if the compiler supports the feature,
# even though CXX_STANDARD is not set explicitly.  The requirement of
# cxx_constexpr causes CMake to set CXX_STANDARD internally, which
# affects the compile flags.
add_library(foo_impl foo_impl.cpp)
target_compile_features(foo_impl PRIVATE cxx_constexpr)

okay so here's the tea โ˜• โ€” write_compiler_detection_header also whips up compatibility code for other features that already have standard equivalents. Like, cxx_static_assert gets emulated with a template and then abstracted via the <PREFIX>_STATIC_ASSERT and <PREFIX>_STATIC_ASSERT_MSG function-macros. cute, right? ๐Ÿ’…


๐Ÿ’€ Deprecated Find Modules ๐Ÿ’€

FindBoost

Changed in version 3.30: This module is available only if policy CMP0167 is not set to NEW. Port projects to upstream Boost's BoostConfig.cmake package configuration file, for which find_package(Boost) now searches.

Find Boost include dirs and libraries ๐Ÿฆ‹

You use this module by invoking find_package() with the form:

find_package(Boost
  [version] [EXACT]      # Minimum or EXACT version e.g. 1.67.0
  [REQUIRED]             # Fail with error if Boost is not found
  [COMPONENTS <libs>...] # Boost libraries by their canonical name
                         # e.g. "date_time" for "libboost_date_time"
  [OPTIONAL_COMPONENTS <libs>...]
                         # Optional Boost libraries by their canonical name)
  )                      # e.g. "date_time" for "libboost_date_time"

So this module finds headers and requested component libraries OR a CMake package configuration file provided by a "Boost CMake" build. For the latter case, skip ahead to the Boost CMake section below โœจ

  • Added in version 3.7: bzip2 and zlib components (Windows only).
  • Added in version 3.11: The OPTIONAL_COMPONENTS option.
  • Added in version 3.13: stacktrace_* components.
  • Added in version 3.19: bzip2 and zlib components on all platforms.

โœจ Result Variables โœจ

This module defines the following variables, bestie โ€” memorize the vibes:

  • Boost_FOUND โ€” Boolean indicating whether headers and requested libraries were found. ๐ŸŽฏ
  • Boost_INCLUDE_DIRS โ€” Boost include directories.
  • Boost_LIBRARY_DIRS โ€” Link directories for Boost libraries.
  • Boost_LIBRARIES โ€” Boost component libraries to be linked.
  • Boost_<COMPONENT>_FOUND โ€” Boolean indicating whether the component <COMPONENT> was found (<COMPONENT> name is upper-case, iykyk).
  • Boost_<COMPONENT>_LIBRARY โ€” Libraries to link for component <COMPONENT> (may include target_link_libraries() debug/optimized keywords).
  • Boost_VERSION_MACRO โ€” BOOST_VERSION value from boost/version.hpp.
  • Boost_VERSION_STRING โ€” Boost version number in X.Y.Z format.
  • Boost_VERSION โ€” Boost version number in X.Y.Z format (same as Boost_VERSION_STRING).
Changed in version 3.15: In previous CMake versions, this variable used the raw version string from the Boost header (same as Boost_VERSION_MACRO). See policy CMP0093. ๐Ÿ˜ญ
  • Boost_LIB_VERSION โ€” Version string appended to library filenames.
  • Boost_VERSION_MAJOR, Boost_MAJOR_VERSION โ€” Boost major version number (X in X.Y.Z).
  • Boost_VERSION_MINOR, Boost_MINOR_VERSION โ€” Boost minor version number (Y in X.Y.Z).
  • Boost_VERSION_PATCH, Boost_SUBMINOR_VERSION โ€” Boost subminor version number (Z in X.Y.Z).
  • Boost_VERSION_COUNT โ€” Amount of version components (3).
  • Boost_LIB_DIAGNOSTIC_DEFINITIONS (Windows-specific) โ€” Pass to add_definitions() to have diagnostic information about Boost's automatic linking displayed during compilation. ๐Ÿฉบ

Added in version 3.15: The Boost_VERSION_<PART> variables.


๐ŸŽ€ Cache Variables ๐ŸŽ€

Search results get saved persistently in CMake cache entries, no cap:

  • Boost_INCLUDE_DIR โ€” Directory containing Boost headers.
  • Boost_LIBRARY_DIR_RELEASE โ€” Directory containing release Boost libraries.
  • Boost_LIBRARY_DIR_DEBUG โ€” Directory containing debug Boost libraries.
  • Boost_<COMPONENT>_LIBRARY_DEBUG โ€” Component <COMPONENT> library debug variant.
  • Boost_<COMPONENT>_LIBRARY_RELEASE โ€” Component <COMPONENT> library release variant.

Added in version 3.3: Per-configuration variables Boost_LIBRARY_DIR_RELEASE and Boost_LIBRARY_DIR_DEBUG. ๐Ÿซถ


๐ŸŒธ Hints ๐ŸŒธ

This module reads hints about search locations from these variables:

  • BOOST_ROOT, BOOSTROOT โ€” Preferred installation prefix.
  • BOOST_INCLUDEDIR โ€” Preferred include directory e.g. <prefix>/include.
  • BOOST_LIBRARYDIR โ€” Preferred library directory e.g. <prefix>/lib.
  • Boost_NO_SYSTEM_PATHS โ€” Set to ON to disable searching in locations not specified by these hint variables. Default is OFF.
  • Boost_ADDITIONAL_VERSIONS โ€” List of Boost versions not known to this module. (Boost install locations may contain the version.)

Users may set these hints or results as CACHE entries. Projects should not read these entries directly but instead use the above result variables. Note that some hint names start in upper-case BOOST โ€” yes, it's giving inconsistent, but that's the deal ๐Ÿ™ˆ. One may specify these as environment variables if they are not specified as CMake variables or cache entries.

This module first searches for the Boost header files using the above hint variables (excluding BOOST_LIBRARYDIR) and saves the result in Boost_INCLUDE_DIR. Then it searches for requested component libraries using the above hints (excluding BOOST_INCLUDEDIR and Boost_ADDITIONAL_VERSIONS), lib directories near Boost_INCLUDE_DIR, and the library name configuration settings below. It saves the library directories in Boost_LIBRARY_DIR_DEBUG and Boost_LIBRARY_DIR_RELEASE and individual library locations in Boost_<COMPONENT>_LIBRARY_DEBUG and Boost_<COMPONENT>_LIBRARY_RELEASE. When one changes settings used by previous searches in the same build tree (excluding environment variables) this module discards previous search results affected by the changes and searches again. ๐Ÿ”


๐Ÿ‘‘ Imported Targets ๐Ÿ‘‘

Added in version 3.5.

This module provides the following Imported Targets:

  • Boost::boost โ€” Target for header-only dependencies. (Boost include directory).
  • Boost::headers โ€” Added in version 3.15: Alias for Boost::boost.
  • Boost::<component> โ€” Target for specific component dependency (shared or static library); <component> name is lower-case.
  • Boost::diagnostic_definitions โ€” Interface target to enable diagnostic information about Boost's automatic linking during compilation (adds -DBOOST_LIB_DIAGNOSTIC).
  • Boost::disable_autolinking โ€” Interface target to disable automatic linking with MSVC (adds -DBOOST_ALL_NO_LIB).
  • Boost::dynamic_linking โ€” Interface target to enable dynamic linking with MSVC (adds -DBOOST_ALL_DYN_LINK).

Implicit dependencies such as Boost::filesystem requiring Boost::system will be automatically detected and satisfied, even if system is not specified when using find_package() and even if Boost::system is not added to target_link_libraries(). And if you're using Boost::thread, then Threads::Threads gets added automatically too. main character energy tbh ๐Ÿ”ฅ

It is important to note that the imported targets behave differently than variables created by this module: multiple calls to find_package(Boost) in the same directory or sub-directories with different options (e.g. static or shared) will not override the values of the targets created by the first call. ๐Ÿ’€

๐Ÿฆ‹ Other Variables ๐Ÿฆ‹

Boost libraries come in so many variants encoded in their file name. Users or projects may tell this module which variant to find by setting these variables:

  • Boost_USE_DEBUG_LIBS โ€” Added in version 3.10. Set to ON or OFF to specify whether to search and use the debug libraries. Default is ON.
  • Boost_USE_RELEASE_LIBS โ€” Added in version 3.10. Set to ON or OFF to specify whether to search and use the release libraries. Default is ON.
  • Boost_USE_MULTITHREADED โ€” Set to OFF to use the non-multithreaded libraries (mt tag). Default is ON.
  • Boost_USE_STATIC_LIBS โ€” Set to ON to force the use of the static libraries. Default is OFF.
  • Boost_USE_STATIC_RUNTIME โ€” Set to ON or OFF to specify whether to use libraries linked statically to the C++ runtime (s tag). Default is platform dependent.
  • Boost_USE_DEBUG_RUNTIME โ€” Set to ON or OFF to specify whether to use libraries linked to the MS debug C++ runtime (g tag). Default is ON.
  • Boost_USE_DEBUG_PYTHON โ€” Set to ON to use libraries compiled with a debug Python build (y tag). Default is OFF.
  • Boost_USE_STLPORT โ€” Set to ON to use libraries compiled with STLPort (p tag). Default is OFF.
  • Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS โ€” Set to ON to use libraries compiled with STLPort deprecated "native iostreams" (n tag). Default is OFF.
  • Boost_COMPILER โ€” Set to the compiler-specific library suffix (e.g. -gcc43). Default is auto-computed for the C++ compiler in use.
Changed in version 3.9: A list may be used if multiple compatible suffixes should be tested for, in decreasing order of preference. ๐Ÿ“
  • Boost_LIB_PREFIX โ€” Added in version 3.18. Set to the platform-specific library name prefix (e.g. lib) used by Boost static libs. This is needed only on platforms where CMake does not know the prefix by default.
  • Boost_ARCHITECTURE โ€” Added in version 3.13. Set to the architecture-specific library suffix (e.g. -x64). Default is auto-computed for the C++ compiler in use.
  • Boost_THREADAPI โ€” Suffix for thread component library name, such as pthread or win32. Names with and without this suffix will both be tried. โญ
  • Boost_NAMESPACE โ€” the alternate namespace you build boost with. Like, if you set it to myboost, it's gonna go hunting for myboost_thread instead of boost_thread. Slay, custom namespace.

Other variables you can set to boss this module around:

  • Boost_DEBUG โ€” set to ON and FindBoost goes full narrator mode with debug output. Pls pls pls turn this on before you file a bug report โ€” it makes everything so much easier, bestie.
  • Boost_REALPATH โ€” set to ON to resolve symlinks on the discovered libraries, which helps with packaging. Like, the "system" component library might resolve to /usr/lib/libboost_system.so.1.67.0 instead of /usr/lib/libboost_system.so. Heads up: this does not affect linking, so don't turn it on unless you actually need that info.
  • Boost_LIBRARY_DIR โ€” the default value for both Boost_LIBRARY_DIR_RELEASE and Boost_LIBRARY_DIR_DEBUG.
  • Boost_NO_WARN_NEW_VERSIONS โ€” Added in version 3.20. Set to ON to suppress the warning about unknown dependencies for new Boost versions. Shushing the vibes check ๐Ÿซถ

On Visual Studio and Borland compilers, Boost headers request automatic linking to the corresponding libraries. That means you need matching libraries linked explicitly, or at least sitting in the link library search path. So in this case, setting Boost_USE_STATIC_LIBS to OFF may not achieve dynamic linking. Boost automatic linking typically asks for static libraries, with a few exceptions (such as Boost.Python). Use this:

add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})

to ask Boost to report info about its automatic linking requests. iykyk ๐Ÿ”ฅ

๐ŸŒˆ Examples ๐ŸŒˆ

Find Boost headers only:

find_package(Boost 1.36.0)
if(Boost_FOUND)
  include_directories(${Boost_INCLUDE_DIRS})
  add_executable(foo foo.cc)
endif()

Find Boost libraries and use imported targets โ€” this is the main character move, honestly:

find_package(Boost 1.56 REQUIRED COMPONENTS
             date_time filesystem iostreams)
add_executable(foo foo.cc)
target_link_libraries(foo Boost::date_time Boost::filesystem
                          Boost::iostreams)

Find Boost Python 3.6 libraries and use imported targets:

find_package(Boost 1.67 REQUIRED COMPONENTS
             python36 numpy36)
add_executable(foo foo.cc)
target_link_libraries(foo Boost::python36 Boost::numpy36)

Find Boost headers and some static (release only) libraries:

set(Boost_USE_STATIC_LIBS        ON)  # only find static libs
set(Boost_USE_DEBUG_LIBS        OFF)  # ignore debug libs and
set(Boost_USE_RELEASE_LIBS       ON)  # only find release libs
set(Boost_USE_MULTITHREADED      ON)
set(Boost_USE_STATIC_RUNTIME    OFF)
find_package(Boost 1.66.0 COMPONENTS date_time filesystem system ...)
if(Boost_FOUND)
  include_directories(${Boost_INCLUDE_DIRS})
  add_executable(foo foo.cc)
  target_link_libraries(foo ${Boost_LIBRARIES})
endif()

๐Ÿงš Boost CMake ๐Ÿงš

If Boost was built using the boost-cmake project, or from Boost 1.70.0 on, it provides a package configuration file for use with find_package's config mode. This module looks for that package config file โ€” it's called BoostConfig.cmake or boost-config.cmake โ€” and stores the result in the CACHE entry Boost_DIR. If it finds it, the package config file gets loaded and this module returns with no further action. See the documentation of the Boost CMake package configuration for details on what it gives you.

Set Boost_NO_BOOST_CMAKE to ON to disable the search for boost-cmake. โœจ


๐ŸŽ€ FindCABLE ๐ŸŽ€

Changed in version 4.1: This module is available only if policy CMP0191 is not set to NEW.

Finds the CABLE installation and works out its include paths and libraries:

find_package(CABLE [...])

The package called CABLE (CABLE Automates Bindings for Language Extension) was initially developed by Kitware to generate bindings to C++ classes for use in interpreted languages, such as Tcl. It worked in conjunction with packages like GCC-XML. The CABLE package has since been superseded by the ITK CableSwig package. A whole era ๐Ÿ’€

Note: When building wrappers for interpreted languages, these packages are no longer necessary. The CastXML package now serves as the recommended tool for this purpose and can be found directly using the find_program() command. Glow-up, honestly ๐Ÿฆ‹

๐ŸŒธ Cache Variables ๐ŸŒธ

The following cache variables may also be set:

  • CABLE โ€” path to the cable executable.
  • CABLE_INCLUDE_DIR โ€” path to the include directory.
  • CABLE_TCL_LIBRARY โ€” path to the Tcl wrapper library.

๐ŸŒˆ Examples ๐ŸŒˆ

Finding CABLE to build a Tcl wrapper, by linking the library and adding the include directories:

find_package(CABLE)
target_link_libraries(tcl_wrapper_target PRIVATE ${CABLE_TCL_LIBRARY})
target_include_directories(tcl_wrapper_target PRIVATE ${CABLE_INCLUDE_DIR})

๐Ÿ’œ FindCUDA ๐Ÿ’œ

Changed in version 3.27: This module is available only if policy CMP0146 is not set to NEW. Port projects to CMake's first-class CUDA language support. Deprecated since version 3.10: Do not use this module in new code. fr fr, it's giving legacy.

It is no longer necessary to use this module or call find_package(CUDA) for compiling CUDA code. Instead, list CUDA among the languages named in the top-level call to the project() command, or call the enable_language() command with CUDA. Then you can add CUDA (.cu) sources directly to targets, just like any other language. Iconic behaviour, no cap.

Added in version 3.17: To find and use the CUDA toolkit libraries manually, use the FindCUDAToolkit module instead. It works regardless of whether the CUDA language is enabled. ๐Ÿ’…

๐Ÿซถ Documentation of Deprecated Usage ๐Ÿซถ

Tools for building CUDA C files: libraries and build dependencies.

This script locates the NVIDIA CUDA C tools. It should work on Linux, Windows, and macOS, and should be reasonably up to date with CUDA C releases.

Added in version 3.19: QNX support. We love to see it โœจ

This script makes use of the standard find_package() arguments of <VERSION>, REQUIRED and QUIET. CUDA_FOUND will report if an acceptable version of CUDA was found.

The script will prompt the user to specify CUDA_TOOLKIT_ROOT_DIR if the prefix can't be determined by the location of nvcc in the system path and REQUIRED is specified to find_package(). To use a different installed version of the toolkit, set the environment variable CUDA_BIN_PATH before running cmake (e.g. CUDA_BIN_PATH=/usr/local/cuda1.0 instead of the default /usr/local/cuda), or set CUDA_TOOLKIT_ROOT_DIR after configuring. If you change the value of CUDA_TOOLKIT_ROOT_DIR, various components that depend on the path will be relocated. So like, be sure before you commit ๐Ÿ˜ญ

It might be necessary to set CUDA_TOOLKIT_ROOT_DIR manually on certain platforms, or to use a CUDA runtime that isn't installed in the default location. In newer versions of the toolkit the CUDA library is included with the graphics driver โ€” be sure that the driver version matches what is needed by the CUDA runtime version. Match the vibes or suffer ๐Ÿ’€

โญ Input Variables โญ

The following variables affect the behavior of the macros in the script (in alphabetical order). Note that any of these flags can be changed multiple times in the same directory before calling cuda_add_executable(), cuda_add_library(), cuda_compile(), cuda_compile_ptx(), cuda_compile_fatbin(), cuda_compile_cubin() or cuda_wrap_srcs():

  • CUDA_64_BIT_DEVICE_CODE (Default: host bit size) โ€” set to ON to compile for 64 bit device code, OFF for 32 bit device code. Note that making this different from the host code when generating object or C files from CUDA code just won't work, because size_t gets defined by nvcc in the generated source. But if you compile to PTX and then load the file yourself, you can mix bit sizes between device and host. Mixing is allowed, just only there ๐Ÿฆ‹
  • CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE (Default: ON) โ€” set to ON if you want the custom build rule attached to the source file in Visual Studio. Turn it OFF if you add the same cuda file to multiple targets.

This lets the user build the target from the CUDA file; however, bad things can happen if the CUDA source file is added to multiple targets. When doing parallel builds it's possible for the custom build command to run more than once and in parallel, causing cryptic build errors. VS runs the rules for every source file in the target, and a source can have only one rule no matter how many projects it's added to. When the rule runs from multiple targets, race conditions can occur on the generated file. Eventually everything will get built, but if the user is unaware of this behavior there may be confusion. It would be nice if this script could detect the reuse of source files across multiple targets and turn the option off for the user, but no good solution could be found. ๐Ÿ˜ญ rip

  • CUDA_BUILD_CUBIN (Default: OFF) โ€” set to ON to enable an extra compilation pass with the -cubin option in Device mode. The output is parsed and register, shared memory usage is printed during build. Free diagnostics, we stan ๐Ÿ“Š
  • CUDA_BUILD_EMULATION (Default: OFF for device mode) โ€” set to ON for Emulation mode. -D_DEVICEEMU is defined for CUDA C files when CUDA_BUILD_EMULATION is TRUE.
  • CUDA_LINK_LIBRARIES_KEYWORD (Default: "") โ€” Added in version 3.9. The <PRIVATE|PUBLIC|INTERFACE> keyword to use for internal target_link_libraries() calls. The default is to use no keyword, which uses the old "plain" form of target_link_libraries(). Note that this matters because whatever is used inside the FindCUDA module must also be used outside โ€” the two forms of target_link_libraries() cannot be mixed. Pick a lane and stay in it, bestie ๐Ÿ’…
  • CUDA_GENERATED_OUTPUT_DIR (Default: CMAKE_CURRENT_BINARY_DIR) โ€” set to the path where you want the generated files placed. If it's blank, output files will be placed in CMAKE_CURRENT_BINARY_DIR. Intermediate files will always be placed in CMAKE_CURRENT_BINARY_DIR/CMakeFiles. No negotiating on that one ๐ŸŽ€
  • CUDA_HOST_COMPILATION_CPP (Default: ON) โ€” set to OFF for C compilation of host code.
  • CUDA_HOST_COMPILER (Default: CMAKE_C_COMPILER) โ€” this is the host compiler that nvcc gets to play with. It gets ignored if -ccbin or --compiler-bindir is already sitting in CUDA_NVCC_FLAGS or CUDA_NVCC_FLAGS_<CONFIG>. For Visual Studio targets, the host compiler is built out of one or more visual studio macros like $(VCInstallDir), which expands to the actual path when the command runs from inside VS. ikyk ๐Ÿ’…

Added in version 3.13: if the CUDAHOSTCXX environment variable is set, it gets used as the default. ๐Ÿซถ

  • CUDA_NVCC_FLAGS, CUDA_NVCC_FLAGS_<CONFIG> โ€” extra NVCC command line arguments. NOTE: multiple arguments must be semi-colon delimited (e.g. --compiler-options;-Wall). semicolons, bestie, not spaces ๐Ÿ˜ญ

Added in version 3.6: the contents of these variables may use generator expressions โ€” see cmake-generator-expressions(7). โœจ

  • CUDA_PROPAGATE_HOST_FLAGS (Default: ON) โ€” set to ON and your CMAKE_{C,CXX}_FLAGS and their configuration-dependent counterparts (e.g. CMAKE_C_FLAGS_DEBUG) get propagated automatically to the host compiler through nvcc's -Xcompiler flag. This helps the generated host code match the rest of the system better. vibe alignment, literally ๐Ÿฆ‹ Sometimes certain flags give nvcc problems, and this is the switch that helps you turn the flag propagation off. It does not affect the flags supplied directly to nvcc via CUDA_NVCC_FLAGS or through the OPTIONS flags specified through cuda_add_library(), cuda_add_executable(), or cuda_wrap_srcs(). Flags used for shared library compilation are not affected by this flag either. ๐Ÿ’€
  • CUDA_SEPARABLE_COMPILATION (Default: OFF) โ€” set it and you enable separable compilation for all CUDA runtime object files. If you use it outside of cuda_add_executable() and cuda_add_library() (e.g. calling cuda_wrap_srcs() directly), then cuda_compute_separable_compilation_object_file_name() and cuda_link_separable_compilation_objects() should be called. ๐Ÿ‘‘
  • CUDA_SOURCE_PROPERTY_FORMAT โ€” Added in version 3.3. If this source file property is set, it can override the format specified to cuda_wrap_srcs() (OBJ, PTX, CUBIN, or FATBIN). If an input source file is not a .cu file, setting this file will cause it to be treated as a .cu file. See the documentation for set_source_files_properties on how to set this property. ๐ŸŽ€
  • CUDA_USE_STATIC_CUDA_RUNTIME (Default: ON) โ€” Added in version 3.3. When enabled, the static version of the CUDA runtime library will be used in CUDA_LIBRARIES. If the version of CUDA configured doesn't support this option, then it will be silently disabled. no warning, no drama, just gone ๐Ÿ™ˆ
  • CUDA_VERBOSE_BUILD (Default: OFF) โ€” set to ON to see all the commands used when building the CUDA file. When using a Makefile generator the value defaults to VERBOSE (run make VERBOSE=1 to see output), although setting CUDA_VERBOSE_BUILD to ON will always print the output. ๐Ÿ”ฅ

โœจ Commands โœจ

The script creates the following functions and macros (in alphabetical order, because we're organized like that ๐Ÿ’…):

cuda_add_cufft_to_target(<cuda_target>)

Adds the cufft library to the target (can be any target). Handles whether you are in emulation mode or not. ๐ŸŒˆ

cuda_add_cublas_to_target(<cuda_target>)

Adds the cublas library to the target (can be any target). Handles whether you are in emulation mode or not. ๐ŸŒˆ

cuda_add_executable

cuda_add_executable(<cuda_target> <file>...
                    [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [OPTIONS ...])

Creates an executable <cuda_target> which is made up of the files specified. All of the non-CUDA C files are compiled using the standard build rules specified by CMake, and the CUDA files are compiled to object files using nvcc and the host compiler. In addition CUDA_INCLUDE_DIRS is added automatically to include_directories(). Some standard CMake target calls can be used on the target after calling this macro (e.g. set_target_properties() and target_link_libraries()), but setting properties that adjust compilation flags will not affect code compiled by nvcc. Such flags should be modified before calling cuda_add_executable(), cuda_add_library() or cuda_wrap_srcs(). ๐Ÿ˜ค

cuda_add_library

cuda_add_library(<cuda_target> <file>...
                 [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [OPTIONS ...])

Same as cuda_add_executable() except that a library is created. ๐ŸŽ€

cuda_build_clean_target()

Creates a convenience target that deletes all the dependency files generated. You should make clean after running this target to ensure the dependency files get regenerated. yes, both. it's a whole ritual ๐Ÿ•ฏ๏ธ

cuda_compile

cuda_compile(<generated_files> <file>... [STATIC | SHARED | MODULE]
             [OPTIONS ...])

Returns a list of generated files from the input source files, to be used with add_library() or add_executable(). โœจ

cuda_compile_ptx

cuda_compile_ptx(<generated_files> <file>... [OPTIONS ...])

Returns a list of PTX files generated from the input source files. ๐Ÿฆ‹

cuda_compile_fatbin

cuda_compile_fatbin(<generated_files> <file>... [OPTIONS ...])

Added in version 3.1. Returns a list of FATBIN files generated from the input source files. ๐Ÿ’œ

cuda_compile_cubin

cuda_compile_cubin(<generated_files> <file>... [OPTIONS ...])

Added in version 3.1. Returns a list of CUBIN files generated from the input source files. ๐Ÿ’œ

cuda_compute_separable_compilation_object_file_name

cuda_compute_separable_compilation_object_file_name(<output_file_var>
                                                    <cuda_target>
                                                    <object_files>)

Compute the name of the intermediate link file used for separable compilation. This file name is typically passed into CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS. output_file_var is produced based on cuda_target and the list of object files that need separable compilation as specified by <object_files>. If the <object_files> list is empty, then <output_file_var> will be empty. This function is called automatically for cuda_add_library() and cuda_add_executable(). Note that this is a function and not a macro. important distinction, don't @ me ๐Ÿ‘€

cuda_include_directories(path0 path1 ...)

Sets the directories that should be passed to nvcc (e.g. nvcc -Ipath0 -Ipath1 ...). These paths usually contain other .cu files. ๐Ÿ“

cuda_link_separable_compilation_objects(<output_file_var> <cuda_target>
                                        <nvcc_flags> <object_files>)

Generates the link object required by separable compilation from the given object files. This is called automatically for cuda_add_executable() and cuda_add_library(), but can be called manually when using cuda_wrap_srcs() directly. When called from cuda_add_library() or cuda_add_executable() the <nvcc_flags> passed in are the same as the flags passed in via the OPTIONS argument. The only nvcc flag added automatically is the bitness flag as specified by CUDA_64_BIT_DEVICE_CODE. Note that this is a function instead of a macro. ๐Ÿ’…

cuda_select_nvcc_arch_flags

cuda_select_nvcc_arch_flags(<out_variable> [<target_CUDA_architecture> ...])

Selects GPU arch flags for nvcc based on target_CUDA_architecture. ๐Ÿงš

Values for target_CUDA_architecture:

  • Auto: detects local machine GPU compute arch at runtime. ๐Ÿ”
  • Common and All: cover common and entire subsets of architectures. ๐ŸŒˆ
  • <name>: one of Fermi, Kepler, Maxwell, Kepler+Tegra, Kepler+Tesla, Maxwell+Tegra, Pascal. ๐Ÿ‘‘
  • <ver>, <ver>(<ver>), <ver>+PTX, where <ver> is one of 2.0, 2.1, 3.0, 3.2, 3.5, 3.7, 5.0, 5.2, 5.3, 6.0, 6.2. โญ

Returns a list of flags to be added to CUDA_NVCC_FLAGS in <out_variable>. Additionally, sets <out_variable>_readable to the resulting numeric list. ๐Ÿ“‹

Example:

cuda_select_nvcc_arch_flags(ARCH_FLAGS "3.0" "3.5+PTX" "5.2(5.0)" "Maxwell")
list(APPEND CUDA_NVCC_FLAGS ${ARCH_FLAGS})

More info on CUDA architectures: <https://en.wikipedia.org/wiki/CUDA>. Note that this is a function instead of a macro. ๐Ÿซถ

cuda_wrap_srcs

cuda_wrap_srcs(<cuda_target> <format> <generated_files> <file>...
               [STATIC | SHARED | MODULE] [OPTIONS ...])

This is where all the magic happens. โœจ cuda_add_executable(), cuda_add_library(), cuda_compile(), and cuda_compile_ptx() all call this function under the hood. main character energy, fr ๐Ÿ’–

Given the list of files <file>... this macro generates custom commands that generate either PTX or linkable objects (use PTX or OBJ for the <format> argument to switch). Files that don't end with .cu or have the HEADER_FILE_ONLY property are ignored. ๐Ÿ™ˆ

The arguments passed in after OPTIONS are extra command line options to give to nvcc. You can also specify per-configuration options by specifying the name of the configuration followed by the options. General options must precede configuration-specific options. Not all configurations need to be specified, only the ones provided will be used. For example:

cuda_add_executable(...
  OPTIONS -DFLAG=2 "-DFLAG_OTHER=space in flag"
  DEBUG -g
  RELEASE --use_fast_math
  RELWITHDEBINFO --use_fast_math;-g
  MINSIZEREL --use_fast_math)

For certain configurations (namely VS generating object files with CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE set to ON), no generated file will be produced for the given cuda file. This is because when you add the cuda file to Visual Studio it knows that this file produces an object file and will link in the resulting object file automatically. VS just knows things, okay ๐Ÿ’€

This script will also generate a separate cmake script that is used at build time to invoke nvcc. This is for several reasons:

  • nvcc can return negative numbers as return values, which confuses Visual Studio into thinking that the command succeeded. The script now checks the error codes and produces errors when there was a problem. ๐Ÿšจ
  • nvcc has been known to not delete incomplete results when it encounters problems. This confuses build systems into thinking the target was generated when in fact an unusable file exists. The script now deletes the output files if there was an error. ๐Ÿ—‘๏ธ
  • By putting all the options that affect the build into a file and then making the build rule dependent on the file, the output files will be regenerated when the options change. ๐Ÿ”

This script also looks at optional arguments STATIC, SHARED, or MODULE to determine when to target the object compilation for a shared library. BUILD_SHARED_LIBS is ignored in cuda_wrap_srcs(), but it is respected in cuda_add_library(). On some systems special flags are added for building objects intended for shared libraries. A preprocessor macro, <target_name>_EXPORTS is defined when a shared library compilation is detected. ๐Ÿ”ฅ

Flags</p> that get passed into add_definitions with -D or /D are handed straight along to nvcc. ๐Ÿซถ

โœจ Result Variables โœจ

The script defines these variables, bestie โ€” literally all of them:

  • CUDA_VERSION_MAJOR โ€” the major version of cuda, as reported by nvcc. ๐Ÿ’…
  • CUDA_VERSION_MINOR โ€” the minor version. That's it, that's the whole vibe.
  • CUDA_VERSION, CUDA_VERSION_STRING โ€” the full version in the X.Y format. Two names, one truth. ๐Ÿ‘‘
  • CUDA_HAS_FP16 โ€” Added in version 3.6: tells you whether a short float (float16, fp16) is supported. ๐Ÿงš
  • CUDA_TOOLKIT_ROOT_DIR โ€” path to the CUDA Toolkit (defined if not set).
  • CUDA_SDK_ROOT_DIR โ€” path to the CUDA SDK. Use this to find files in the SDK. Ngl this script will not directly support finding specific libraries or headers, because that isn't supported by NVIDIA. If you want to change libraries when the path changes, go peek at the FindCUDA.cmake script for an example of how to clear these variables. There are also examples of how to use CUDA_SDK_ROOT_DIR to locate headers or libraries, if you so choose (at your own risk). โš ๏ธ
  • CUDA_INCLUDE_DIRS โ€” include directory for cuda headers. Added automatically for cuda_add_executable() and cuda_add_library().
  • CUDA_LIBRARIES โ€” Cuda RT library.
  • CUDA_CUFFT_LIBRARIES โ€” device or emulation library for the Cuda FFT implementation (the alternative to the cuda_add_cufft_to_target() macro).
  • CUDA_CUBLAS_LIBRARIES โ€” device or emulation library for the Cuda BLAS implementation (the alternative to the cuda_add_cublas_to_target() macro).
  • CUDA_cudart_static_LIBRARY โ€” statically linkable cuda runtime library. Only available for CUDA version 5.5+.
  • CUDA_cudadevrt_LIBRARY โ€” Added in version 3.7: device runtime library. Required for separable compilation. ๐Ÿ› ๏ธ
  • CUDA_cupti_LIBRARY โ€” CUDA Profiling Tools Interface library. Only available for CUDA version 4.0+.
  • CUDA_curand_LIBRARY โ€” CUDA Random Number Generation library. Only available for CUDA version 3.2+.
  • CUDA_cusolver_LIBRARY โ€” Added in version 3.2: CUDA Direct Solver library. Only available for CUDA version 7.0+.
  • CUDA_cusparse_LIBRARY โ€” CUDA Sparse Matrix library. Only available for CUDA version 3.2+.
  • CUDA_npp_LIBRARY โ€” NVIDIA Performance Primitives lib. Only available for CUDA version 4.0+.
  • CUDA_nppc_LIBRARY โ€” NVIDIA Performance Primitives lib (core). Only available for CUDA version 5.5+.
  • CUDA_nppi_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 5.5 - 8.0.
  • CUDA_nppial_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppicc_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppicom_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0 - 10.2. Replaced by nvjpeg.
  • CUDA_nppidei_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppif_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppig_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppim_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppist_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppisu_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_nppitc_LIBRARY โ€” NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
  • CUDA_npps_LIBRARY โ€” NVIDIA Performance Primitives lib (signal processing). Only available for CUDA version 5.5+.
  • CUDA_nvcuvenc_LIBRARY โ€” CUDA Video Encoder library. Only available for CUDA version 3.2+. Windows only. ๐ŸชŸ
  • CUDA_nvcuvid_LIBRARY โ€” CUDA Video Decoder library. Only available for CUDA version 3.2+. Windows only. ๐ŸชŸ
  • CUDA_nvToolsExt_LIBRARY โ€” Added in version 3.16: NVIDA CUDA Tools Extension library. Available for CUDA version 5+.
  • CUDA_OpenCL_LIBRARY โ€” Added in version 3.16: NVIDA CUDA OpenCL library. Available for CUDA version 5+.

๐ŸŽ€ FindDart ๐ŸŽ€

Deprecated since version 3.27: this module is available only if policy CMP0145 <#policy:CMP0145> is not set to NEW. ๐Ÿซ 

Finds DART, like so:

find_package(DART [...] )

This module looks for the dart testing software and sets DART_ROOT to point to wherever it found it. ๐Ÿ“

Result Variables

This module defines the following variables:

  • Dart_FOUND โ€” Added in version 3.3. Boolean indicating whether DART was found. โœ…

Cache Variables

The following cache variables may also be set:

  • DART_ROOT โ€” the path to the Dart root installation.

๐ŸŒธ FindGCCXML ๐ŸŒธ

Changed in version 4.1: this module is available only if policy CMP0188 <#policy:CMP0188> is not set to NEW. Port projects to search for CastXML by calling find_program() <#command:find_program> directly. ๐Ÿ’€

Finds the GCC-XML front-end executable:

find_package(GCCXML [...] )

Cache Variables

The following cache variables may also be set:

  • GCCXML โ€” the GCC-XML front-end executable.

Examples

In new code, find CastXML with find_program() <#command:find_program> instead:

find_program(CASTXML_EXECUTABLE castxml)

๐Ÿฆ‹ FindGDAL ๐Ÿฆ‹

Deprecated since version 4.0: GDAL 3.5 and above provide a GDALConfig.cmake package configuration file. Call find_package(GDAL CONFIG) to find it directly and avoid using this find module. For further details, see GDAL's documentation on CMake integration <https://gdal.org/en/latest/development/cmake.html>. ๐Ÿ‘€

Finds Geospatial Data Abstraction Library (GDAL):

find_package(GDAL [<version>] [...] )

Imported Targets

This module provides the following Imported Targets <#imported-targets>:

  • GDAL::GDAL โ€” Added in version 3.14. Target encapsulating the GDAL usage requirements, available only if GDAL has been found. Slay. ๐Ÿ’…

Result Variables

This module defines the following variables:

  • GDAL_FOUND โ€” Boolean indicating whether (the requested version of) GDAL was found.
  • GDAL_VERSION โ€” Added in version 3.14. The version of GDAL found.
  • GDAL_INCLUDE_DIRS โ€” include directories for GDAL headers.
  • GDAL_LIBRARIES โ€” libraries to link to GDAL.

Cache Variables

The following cache variables may also be set:

  • GDAL_INCLUDE_DIR โ€” the directory containing <gdal.h>.
  • GDAL_LIBRARY โ€” the libgdal library file.

Hints

The following variables may be set to modify the search strategy:

  • GDAL_DIR or GDAL_ROOT โ€” set one of these environment variables to specify the GDAL installation prefix. ๐ŸŒˆ
  • FindGDAL_SKIP_GDAL_CONFIG โ€” if set, gdal-config will not be used. This can be useful if there are GDAL libraries built with autotools (which provide the tool) and CMake (which do not) in the same environment. Big mood.
  • GDAL_ADDITIONAL_LIBRARY_VERSIONS โ€” extra versions of library names to search for.

Examples

Finding GDAL in config mode without using this module, and linking its imported target to a project target:

find_package(GDAL CONFIG)
target_link_libraries(example PRIVATE GDAL::GDAL)

โญ FindITK โญ

This module no longer exists. ๐Ÿ˜ญ

It existed in versions of CMake prior to 3.1, but became only a thin wrapper around find_package(ITK NO_MODULE) to provide compatibility for projects using long-outdated conventions. Now find_package(ITK) will search for ITKConfig.cmake directly. Periodt.


๐Ÿ’œ FindPythonInterp ๐Ÿ’œ

Changed in version 3.27: this module is available only if policy CMP0148 <#policy:CMP0148> is not set to NEW.
Deprecated since version 3.12: use FindPython3 <#module:FindPython3>, FindPython2 <#module:FindPython2>, or FindPython <#module:FindPython> instead. ๐Ÿ™ˆ

Finds the Python interpreter and determines the location of its executable:

find_package(PythonInterp [<version>] [...] )
Note: when using both this and the FindPythonLibs <#module:FindPythonLibs> module, call find_package(PythonInterp) before find_package(PythonLibs). This ensures that the detected interpreter version is used to guide the selection of compatible libraries, resulting in a consistent PYTHON_LIBRARIES value. ๐Ÿซถ
Note: a call to find_package(PythonInterp ${V}) for Python version V may find a python executable with no version suffix. In this case no attempt is made to avoid Python executables from other versions. Use FindPython3 <#module:FindPython3>, FindPython2 <#module:FindPython2>, or FindPython <#module:FindPython> instead. ๐Ÿ’€

Result Variables

This module defines the following variables:

  • PythonInterp_FOUND โ€” Added in version 3.3. Boolean indicating whether the (requested version of) Python executable was found.
  • PYTHON_VERSION_STRING โ€” Python version found (e.g., 2.5.2).
  • PYTHON_VERSION_MAJOR โ€” Python major version found (e.g., 2).
  • PYTHON_VERSION_MINOR โ€” Python minor version found (e.g., 5).
  • PYTHON_VERSION_PATCH โ€” Python patch version found (e.g., 2). โœจ

Cache Variables

The following cache variables may also be set:

  • PYTHON_EXECUTABLE โ€” the path to the Python interpreter. ๐Ÿ“

Hints

This module accepts the following variables before calling find_package(PythonInterp):

  • Python_ADDITIONAL_VERSIONS โ€” this variable can be used to specify a list of version numbers that should be taken into account when searching for Python.

Deprecated Variables

The following variables are provided for backward compatibility:

  • PYTHONINTERP_FOUND โ€” Deprecated since version 3.12: use PythonInterp_FOUND, which has the same value. Boolean indicating whether the (requested version of) Python executable was found.

Examples

Finding the Python interpreter in earlier versions of CMake:

find_package(PythonInterp)
execute_process(COMMAND ${PYTHON_EXECUTABLE} --help)

Starting with CMake 3.12, the Python interpreter can be found using the FindPython <#module:FindPython> module. The equivalent example using the modern approach is:

find_package(Python)
execute_process(COMMAND ${Python_EXECUTABLE} --help)

(...and that's the rest of that example, bestie ๐Ÿ’… carry on)


๐ŸŒธ FindPythonLibs ๐ŸŒธ

Changed in version 3.27: This module is available only if policy CMP0148 is not set to NEW. So if you flipped that policy, this module straight up ghosts you ๐Ÿ’€
Deprecated since version 3.12: Use FindPython3, FindPython2, or FindPython instead. Like, this one's on its way out, no cap.

It finds the Python installation and figures out where its include directories and libraries live, plus the actual name of the library you link against:

find_package(PythonLibs [<version>] [...])
Note: If you're using both this module and FindPythonInterp, call find_package(PythonInterp) before find_package(PythonLibs). That's the move that keeps your detected interpreter version guiding the selection of compatible libraries, so your PYTHON_LIBRARIES stays consistent. Consistency is the whole vibe โœจ

Result Variables

This module sets up the following for you, bestie:

  • PythonLibs_FOUND โ€” Added in version 3.3. Boolean. Was the (requested version of the) Python libraries even found? True or false, that's it.
  • PYTHONLIBS_VERSION_STRING โ€” the version of the Python libraries that got found ๐ŸŽ€
  • PYTHON_LIBRARIES โ€” the libraries you need to link against to use Python.
  • PYTHON_INCLUDE_DIRS โ€” the include directories you need to use Python.

Cache Variables

These cache variables may also get set to pin down which Python installation to use:

  • PYTHON_LIBRARY โ€” the path to the Python library.
  • PYTHON_INCLUDE_DIR โ€” the directory holding the Python.h header file.

Hints

This module accepts the following variables before you call find_package(PythonLibs):

  • Python_ADDITIONAL_VERSIONS โ€” use this to hand over a list of version numbers that should be taken into account when searching for Python. Very "here's my wishlist" of it you ๐Ÿ™ˆ

Deprecated Variables

These are here purely for backward compatibility:

  • PYTHONLIBS_FOUND โ€” Deprecated since version 3.12: use PythonLibs_FOUND, which has the same value. Boolean indicating whether the (requested version of the) Python libraries were found.
  • PYTHON_DEBUG_LIBRARIES โ€” Deprecated since version 2.8.8: use PYTHON_LIBRARIES instead. Result variable holding the path to the debug library.
  • PYTHON_INCLUDE_PATH โ€” Deprecated since version 2.8.0: use PYTHON_INCLUDE_DIR or PYTHON_INCLUDE_DIRS instead. Result variable holding the path to the directory containing the Python.h header file.

Examples

In earlier versions of CMake, Python libraries were found and used in a project like this:

find_package(PythonLibs)
target_link_libraries(app PRIVATE ${PYTHON_LIBRARIES})
target_include_directories(app PRIVATE ${PYTHON_INCLUDE_DIRS})

Starting with CMake 3.12, Python libraries can be found using the FindPython module. Here's the equivalent example, the modern imported-target way โ€” lowkey iconic:

find_package(Python COMPONENTS Development)
target_link_libraries(app PRIVATE Python::Python)

๐Ÿฆ‹ FindQt ๐Ÿฆ‹

Deprecated since version 3.14: This module is available only if policy CMP0084 is not set to NEW. It supports only Qt3 and Qt4 โ€” periodt. For Qt5 or later versions, see cmake-qt(7).

Finds an installed version of Qt3 or Qt4:

find_package(Qt [...])

Qt is a cross-platform application development framework for creating graphical user interfaces and applications. It's giving "buttons and windows, but make it portable."

Only use this module if the project can actually work with both Qt3 and Qt4. If you need a specific version, go use FindQt4 or FindQt3 directly, bestie โ€” don't make this module guess.

Behavior:

  • If multiple Qt versions are found, the user has to set the preferred major Qt version with the DESIRED_QT_VERSION variable.
  • If only one Qt version is found, then DESIRED_QT_VERSION gets set automatically. Convenient ๐Ÿ’…
  • Once DESIRED_QT_VERSION is set, the corresponding FindQt3 or FindQt4 module gets included.

Result Variables

  • QT4_INSTALLED โ€” TRUE if Qt4 was found.
  • QT3_INSTALLED โ€” TRUE if Qt3 was found.

Hints

  • QT_REQUIRED โ€” if you set this to TRUE before calling find_package(Qt), CMake will raise an error if neither Qt3 nor Qt4 is found. Fair enough, honestly.
  • DESIRED_QT_VERSION โ€” specifies the Qt major version to use. Can be 3, 4, or empty, in which case it searches for the version automatically. Empty = "you pick, babe" ๐Ÿซถ

Examples

Finding the Qt3 or Qt4 version:

find_package(Qt)

โญ FindUnixCommands โญ

Deprecated since version 3.26: Use ${CMAKE_COMMAND} -E subcommands instead. Fr fr, that's the replacement.

Finds the Unix commands bash, cp, gzip, mv, rm, and tar โ€” including the ones from Cygwin or MSYS:

find_package(UnixCommands [...])

Result Variables

  • UnixCommands_FOUND โ€” Added in version 3.3. Boolean indicating whether the Unix commands were found.

Cache Variables

These cache variables may also get set:

  • BASH โ€” the path to the bash command-line executable.
  • CP โ€” the path to the cp command-line executable.
  • GZIP โ€” the path to the gzip command-line executable.
  • MV โ€” the path to the mv command-line executable.
  • RM โ€” the path to the rm command-line executable.
  • TAR โ€” the path to the tar command-line executable.

That's the whole lineup. Six little executables, all accounted for ๐ŸŽ€


๐Ÿ’€ FindVTK ๐Ÿ’€

This module no longer exists. Not "deprecated," not "discouraged" โ€” gone.

It existed in versions of CMake prior to 3.1, but became only a thin wrapper around find_package(VTK NO_MODULE) to provide compatibility for projects using long-outdated conventions. Now find_package(VTK) will search for VTKConfig.cmake directly. So like... the wrapper got unceremoniously uninvited ๐Ÿ˜ญ


๐Ÿ“ FindwxWindows ๐Ÿ“

Deprecated since version 3.0: Replaced by FindwxWidgets.

Finds the wxWidgets (formerly known as wxWindows) installation and determines where its include directories and libraries live, plus the name of the library:

find_package(wxWindows [...])

wxWidgets 2.6.x is supported for monolithic builds, such as those compiled in the wx/build/msw directory using:

nmake -f makefile.vc BUILD=debug SHARED=0 USE_OPENGL=1 MONOLITHIC=1

That's a whole mouthful of flags and yes, you do need all of them ๐Ÿ’…

Result Variables

  • WXWINDOWS_FOUND โ€” boolean indicating whether wxWidgets was found.
  • WXWINDOWS_LIBRARIES โ€” libraries needed to link against to use wxWidgets. This includes paths to the wxWidgets libraries and any additional linker flags, typically derived from the output of wx-config --libs on Unix/Linux systems.
  • CMAKE_WXWINDOWS_CXX_FLAGS โ€” compiler options needed to use wxWidgets (if any). On Linux, this corresponds to the output of wx-config --cxxflags.
  • WXWINDOWS_INCLUDE_DIR โ€” the directory containing the wx/wx.h and wx/setup.h header files.
  • WXWINDOWS_LINK_DIRECTORIES โ€” link directories, useful for setting rpath on Unix-like platforms.
  • WXWINDOWS_DEFINITIONS โ€” extra compile definitions needed to use wxWidgets (if any).

Hints

This module accepts the following variables before you call find_package(wxWindows):

  • WXWINDOWS_USE_GL โ€” set this to boolean true to require OpenGL support.
  • HAVE_ISYSTEM โ€” set this to boolean true to replace -I compiler options with -isystem when the C++ compiler is GNU (g++).

Deprecated Variables

Backward-compatibility corner, aka the nostalgia shelf:

  • CMAKE_WX_CAN_COMPILE โ€” Deprecated since version 1.8: replaced by the WXWINDOWS_FOUND variable with the same value.
  • WXWINDOWS_LIBRARY โ€” Deprecated since version 1.8: replaced by the WXWINDOWS_LIBRARIES variable with the same value.
  • CMAKE_WX_CXX_FLAGS โ€” Deprecated since version 1.8: replaced by the CMAKE_WXWINDOWS_CXX_FLAGS variable with the same value.
  • WXWINDOWS_INCLUDE_PATH โ€” Deprecated since version 1.8: replaced by the WXWINDOWS_INCLUDE_DIR variable with the same value.

Examples

Example: Finding wxWidgets in Earlier CMake Versions

In earlier versions of CMake, wxWidgets (wxWindows) could be found using:

find_package(wxWindows)

To request OpenGL support, the WXWINDOWS_USE_GL variable could be set before calling find_package():

set(WXWINDOWS_USE_GL ON)
find_package(wxWindows)

Using wxWidgets (wxWindows) in CMake was commonly done by including the Use_wxWindows module, which would find wxWidgets and set the appropriate libraries, include directories, and compiler flags:

include(Use_wxWindows)

Example: Finding wxWidgets as of CMake 3.0

Starting with CMake 3.0, wxWidgets can be found using the FindwxWidgets module:

find_package(wxWidgets)

Look at that glow-up ๐ŸŒˆ


๐Ÿงš Legacy CPack Modules ๐Ÿงš

These modules used to be mistakenly exposed to the user, and have been moved out of user visibility. They are for CPack internal use, and should never be used directly. Read that again. Never. Directly. ๐Ÿ™ˆ

CPackArchive

Added in version 3.9.

The documentation for the CPack Archive generator has moved here: CPack Archive Generator.

CPackBundle

The documentation for the CPack Bundle generator has moved here: CPack Bundle Generator.

CPackCygwin

The documentation for the CPack Cygwin generator has moved here: CPack Cygwin Generator.

CPackDeb

The documentation for the CPack DEB generator has moved here: CPack DEB Generator.

CPackDMG

The documentation for the CPack DragNDrop generator has moved here: CPack DragNDrop Generator.

CPackFreeBSD

Added in version 3.10.

The documentation for the CPack FreeBSD generator has moved here: CPack FreeBSD Generator.

CPackNSIS

The documentation for the CPack NSIS generator has moved here: CPack NSIS Generator.

CPackNuGet

Added in version 3.12.

The documentation for the CPack NuGet generator has moved here: CPack NuGet Generator.

CPackProductBuild

Added in version 3.7.

The documentation for the CPack productbuild generator has moved here: CPack productbuild Generator.

CPackRPM

The documentation for the CPack RPM generator has moved here: CPack RPM Generator.

CPackWIX

The documentation for the CPack WIX generator has moved here: CPack WIX Generator.

โœจ Miscellaneous Modules โœจ

Okay bestie, real talk: these modules are internal ๐Ÿ‘€ โ€” they are not meant to be included directly in your projects. Like, they're backstage crew, not the main character. Do not include() them, I'm begging ๐Ÿซถ


๐ŸŽ€ CMakeFindPackageMode

This one gets run by cmake when you invoke it with the --find-package option, and its whole job is to locate the package you asked for. Lowkey just a little errand-runner ๐Ÿงš

Note: this is an internal module and it is not meant to be included directly in your project. For the usage deets, go read the --find-package docs, iykyk ๐Ÿ’…

๐Ÿฆ‹ CMakeGraphVizOptions

Note: this module is not intended to be included in CMake projects directly. It once contained the information for using Graphviz in CMake. For Graphviz usage in CMake, refer to cmake --graphviz.

It's giving "retired legend" ngl โ€” it had its era, and now the flag does the work ๐ŸŒˆ

๐ŸŒธ CTestScriptMode

Note: this module is not intended to be included or invoked directly by project code. It is internally used by CTest running in script mode (-S) to determine the current system. For usage details refer to ctest -S.

So like... it's CTest's own little vibe check of your system. Not yours to touch ๐Ÿ™ˆ

๐Ÿ“ Findosg_functions

Note: this module is not intended to be included or invoked directly by project code during typical use of the find_package() command. It is internally used by OpenSceneGraph (OSG) find modules to assist with searching for OSG libraries and NodeKits. For usage details refer to the FindOpenSceneGraph module.

Translation: it's the assistant, not the star. The FindOpenSceneGraph module is where you actually look ๐Ÿ‘‘

๐Ÿ’œ SquishTestScript

Note: this module is not intended to be included directly in a CMake project. It is an internal CMake test script used to launch GUI tests with Squish. For usage details, refer to the squish_add_test() command documentation in the FindSquish module.

GUI tests with Squish?! Iconic behaviour honestly. Just don't call it yourself, fr fr ๐Ÿ’€


2000-2026 Kitware, Inc. and Contributors


And that's a wrap on the whole page, bestie!! ๐ŸŽ‰โœจ You made it to the very end โ€” main character energy fr ๐Ÿซถ This edition is 4.4.5, dated Oct 28, 2026, and it lives at CMAKE-MODULES(7). Go forth and find_package() responsibly ๐Ÿ’–๐ŸŽ€๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from