Scroll to navigation

CMAKE-MODULES(7) CMake CMAKE-MODULES(7)

NAME

cmake-modules - CMake Modules Reference

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:

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:

Zero or more files needed for testing.
Absolute path where the data files are expected to be.
Zero or more libraries needed for testing.
Absolute path where the libraries are expected to be.
Absolute path to the on-device location where the data files are initially stored.
Absolute path to the root directory of the on-device test location.
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.

Load this module in 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()

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.
Added in version 3.6.

Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe").



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.


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.
Added in version 3.6.

Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe").



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.


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.


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.


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>.


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.


Gets RPATHS (run-time search paths) for the given item:

get_item_rpaths(<item> <rpaths-var>)


This command gets RPATHS of the <item> file name and stores them to the variable with provided name <rpaths-var>.


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.


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.

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.


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.

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.
Added in version 3.6.

Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe").



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>.


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:

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.


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.

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.

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.

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:

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.


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.
Added in version 3.6.

Optional list of file names to ignore (e.g. IGNORE_ITEM "vcredist_x86.exe;vcredist_x64.exe").



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.

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.

Load this module in a CMake project with:

include(CheckCCompilerFlag)


Commands

This module provides the following command:

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.

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.

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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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 support for the C compiler flag -fno-optimize-strlen, which 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. The $<COMPILE_LANGUAGE:...> generator expression ensures that the flag is added only to 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 for a more general command to check whether a compiler flag is supported.

CheckCompilerFlag

Added in version 3.19.

This module provides a command to check whether the compiler supports a given flag.

Load this module in a CMake project with:

include(CheckCompilerFlag)


Commands

This module provides the following command:

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 specified by <variable>.

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.

Added in version 3.21: Support for HIP language.

Added in version 3.26: Support for Swift language.

<flag>
Compiler flag(s) to check. Multiple flags can be specified in one argument as a string using a semicolon-separated list.
<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.

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.

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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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 support for the C compiler flag -fno-optimize-strlen, which 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. The $<COMPILE_LANGUAGE:...> generator expression ensures that 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 to check whether a linker flag is supported by the compiler.

CheckCSourceCompiles

This module provides a command to check whether a C source can be built.

Load this module in a CMake project with:

include(CheckCSourceCompiles)


Commands

This module provides the following command:

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>
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>
Variable name of an internal cache variable to store the result of the check, with boolean true for success and boolean false for failure.
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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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

Checking whether C source code containing 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.

Load this module in a CMake project with:

include(CheckCSourceRuns)


Commands

This module provides the following command:

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. 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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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.

Load this module in a CMake project with:

include(CheckCXXCompilerFlag)


Commands

This module provides the following command:

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.

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.

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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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 C++ compiler flag -fsycl. The result of the check is stored in the internal cache variable HAVE_FSYCL_FLAG, 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 CXX source files.

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:

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). The result of the check is 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.
<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.
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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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:

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. 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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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 check whether the C++ standard library is functional and std::vector works at runtime. If the source compiles, links, and runs successfully, internal cache variable HAVE_WORKING_STD_VECTOR will be set to boolean true value. Code is supplied using Bracket Argument for easier embedded quotes handling:

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 for a more general command syntax.
  • The CheckSourceCompiles module to check whether a source code can be built.

CheckCXXSymbolExists

This module provides a command to check whether a C++ symbol exists.

Load this module in a CMake project with:

include(CheckCXXSymbolExists)


Commands

This module provides the following command:

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 is considered available and assumed to work. If the symbol is declared as a function or variable, the check also ensures that it links successfully (i.e., the symbol must exist in a linked library or object file).

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 is 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, it is generally advised to use the CheckSourceCompiles module for checking any function symbol (unless it is certain the checked function is not overloaded on other systems or will not be so in the future).


Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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 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 to check 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.

Load this module in a CMake project with:

include(CheckFortranCompilerFlag)


Commands

This module provides the following command:

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 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.

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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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 Fortran compiler flag -fallow-argument-mismatch. The result of the check is stored in the internal cache variable HAVE_FORTRAN_FLAG, 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 Fortran source files.

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 for a more general command to check whether a compiler flag is supported.

CheckFortranFunctionExists

This module provides a command to check whether a Fortran function exists.

Load this module in a CMake project with:

include(CheckFortranFunctionExists)


Commands

This module provides the following command:

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 in which to store the check result. This variable will be created as an internal cache variable.

NOTE:

This command does not detect functions provided by Fortran modules. In general, it is recommended to use CheckSourceCompiles instead to determine whether a Fortran function or subroutine is available.


Variables Affecting the Check

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

Added in version 3.14.

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


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).

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 the following example, this module is used in combination 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 is stored in the internal cache variable PROJECT_HAVE_DGESV:

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 to check whether a C function exists.
  • The CheckSourceCompiles module to check whether source code can be compiled.

CheckFortranSourceCompiles

Added in version 3.1.

This module provides a command to check whether a Fortran source can be built.

Load this module in a CMake project with:

include(CheckFortranSourceCompiles)


Commands

This module provides the following command:

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 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>
Fortran 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>
Variable name of an internal cache variable to store the result of the check, with boolean true for success and boolean false for failure.
If this option is provided 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.
Added in version 3.7.

By default, the test source file used for the check will be given a .F file extension. This option can be used to override this with .<extension> instead - .F90 is a typical choice.


Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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

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")


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.

CheckFortranSourceRuns

Added in version 3.14.

This module provides a command to check whether a Fortran source can be built and run.

Load this module in a CMake project with:

include(CheckFortranSourceRuns)


Commands

This module provides the following command:

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 supplied in <code> must contain a Fortran program unit. 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.

The options are:

By default, the internal test source file used for the check will be given a .F90 file extension. This option can be used to change the extension to .<extension> instead.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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 shows how to use this module to check whether a Fortran source code runs and 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.

Load this module in a CMake project with:

include(CheckFunctionExists)


Commands

This module provides the following command:

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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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.

CheckIncludeFileCXX

This module provides a command to check a C++ header file.

Load this module in a CMake project with:

include(CheckIncludeFileCXX)


Commands

This module provides the following command:

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

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


This command checks once whether the given <include> header file exists and can be included in a CXX source file. The result of the check is stored in an internal cache variable named <variable>. The optional third argument may be used to add additional compilation flags to the check (or use the CMAKE_REQUIRED_FLAGS variable below).

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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 to check for single C header.
  • The CheckIncludeFiles module to check for one or more C or C++ headers at once.

CheckIncludeFile

This module provides a command to check C header file.

Load this module in a CMake project with:

include(CheckIncludeFile)


Commands

This module provides the following command:

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

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


This command checks once whether the given <include> header file exists and can be included in a C source file. The result of the check is stored in an internal cache variable named <variable>. The optional third argument may be used to add additional compilation flags to the check (or use the CMAKE_REQUIRED_FLAGS variable below).

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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

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 in combination 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 is 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).

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_files(ucontext.h HAVE_UCONTEXT_H) cmake_pop_check_state()


See Also

  • The CheckIncludeFileCXX module to check for single C++ header.
  • The CheckIncludeFiles module to check for one or more C or C++ headers at once.

CheckIncludeFiles

This module provides a command to check one or more C/C++ header files.

Load this module in a CMake project with:

include(CheckIncludeFiles)


Commands

This module provides the following command:

Checks once whether one or more header files can be included together in source code:

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


This command checks once whether the given <includes> list of header files exist and can be included together in a C or C++ source file. The result of the check is stored in an internal cache variable named <variable>. Specify the <includes> argument as a semicolon-separated list of header file names.

If LANGUAGE is set, the specified compiler will be used to perform the check. Acceptable values are C and CXX. If not set, the C compiler will be used if enabled. If the C compiler is not enabled, the C++ compiler will be used if enabled.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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 one or more C headers and storing the check result in cache variables:

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 can be used to specify 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 to check for a single C header.
  • The CheckIncludeFileCXX module to check for a single C++ header.

CheckIPOSupported

Added in version 3.9.

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

Load this module in a CMake project with:

include(CheckIPOSupported)


Interprocedural optimization is a compiler technique that performs optimizations across translation units (i.e., across source files), allowing the compiler to analyze and optimize the entire program as a whole rather than file-by-file. This can improve performance by enabling more aggressive inlining and dead code elimination. When these optimizations are applied at link time, the process is typically referred to as link-time optimization (LTO), which is a common form of IPO.

In CMake, interprocedural optimization can be enabled 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 to ensure the compiler supports IPO/LTO.

Commands

This module provides the following command:

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

check_ipo_supported(

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


Options are:

Set <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.
Set <output-var> variable with details about any error.
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.


NOTE:

To use check_ipo_supported(), policy CMP0069 must be set to NEW; otherwise, a fatal error will occur.


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 is not 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 supported by the compiler and to issue a warning if it is not. 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 useful when a project does not always require a specific language but may need to enable it for certain parts.

Commands

This module provides the following command:

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:

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.

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.

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.



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.

Load this module in a CMake project with:

include(CheckLibraryExists)


Commands

This module provides the following command:

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 is provided by either a system or user-provided <library>.

The arguments are:

<library>
The name of the library, a full path to a library file, or an Imported Target.
<function>
The name of a function that should be available in the system or user-provided library <library>.
<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.
<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 command is intended for performing basic sanity checks to verify that a library provides the expected functionality, or that the correct library is being located. However, it only verifies that a function symbol can be linked successfully - it does not ensure that the function is declared in library headers, nor can it detect functions that are inlined or defined as preprocessor macros. For more robust detection of function availability, prefer using CheckSymbolExists or CheckSourceCompiles.


Variables Affecting the Check

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

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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

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 library exists in 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 (for example, from the find_package() call) can be used:

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 to check whether a C symbol exists.

CheckLinkerFlag

Added in version 3.18.

This module provides a command to check whether a given link flag is supported by the compiler.

Load this module in a CMake project with:

include(CheckLinkerFlag)


Commands

This module provides the following command:

Checks once whether the compiler supports a given link flag:

check_linker_flag(<lang> <flag> <variable>)


This command checks once whether the linker flag <flag> is accepted by the <lang> compiler without producing a diagnostic message.

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.

<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.

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 one, is 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 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:

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.

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.

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.

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).

Added in version 3.31.

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


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

To pass options to the linker tool, each compiler driver has its own syntax. The LINKER: prefix and , separator can be used to specify, in a portable way, options to pass to the linker tool. LINKER: is replaced by the appropriate driver option and , by the appropriate driver separator. The driver prefix and driver separator are given by the values of the CMAKE_<LANG>_LINKER_WRAPPER_FLAG and CMAKE_<LANG>_LINKER_WRAPPER_FLAG_SEP variables.

For example, "LINKER:-z,defs" becomes -Xlinker -z -Xlinker defs for Clang and -Wl,-z,defs for GNU GCC.

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

The LINKER: prefix supports, as an alternative syntax, specification of arguments using the SHELL: prefix and space as separator. The 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.


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 the target_link_options(). The LINKER: prefix is used to pass the flag to the linker in a portable and compiler-independent way.

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 to check whether a compiler flag is supported.

CheckOBJCCompilerFlag

Added in version 3.16.

This module provides a command to check whether the Objective-C compiler supports a given flag.

Load this module in a CMake project with:

include(CheckOBJCCompilerFlag)


Commands

This module provides the following command:

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

check_objc_compiler_flag(<flag> <variable>)


This command checks once that the <flag> is accepted by the OBJC 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.

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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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 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 module provides a command to check whether an Objective-C source can be built.

Load this module in a CMake project with:

include(CheckOBJCSourceCompiles)


Commands

This module provides the following command:

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

check_objc_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>
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>
Variable name of an internal cache variable to store the result of the check, with boolean true for success and boolean false for failure.
If this option is provided 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.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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

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

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.

This module provides a command to check whether an Objective-C source can be built and run.

Load this module in a CMake project with:

include(CheckOBJCSourceRuns)


Commands

This module provides the following command:

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. 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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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.

Load this module in a CMake project with:

include(CheckOBJCXXCompilerFlag)


Commands

This module provides the following command:

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.

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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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.

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.

Load this module in a CMake project with:

include(CheckOBJCXXSourceCompiles)


Commands

This module provides the following command:

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>
Variable name of an internal cache variable to store the result of the check, with boolean true for success and boolean false for failure.
If this option is provided 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.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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

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 for a more general command to check whether source can be built.
  • The CheckSourceRuns module to check whether source can be built and run.

CheckOBJCXXSourceRuns

Added in version 3.16.

This module provides a command to check whether an Objective-C++ source can be built and run.

Load this module in a CMake project with:

include(CheckOBJCXXSourceRuns)


Commands

This module provides the following command:

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.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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(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 for a more general command syntax.
  • The CheckSourceCompiles module to check whether a source code can be built.

CheckPIESupported

Added in version 3.14.

This module provides the check_pie_supported() function to check whether the linker supports Position Independent Code (PIE) or No Position Independent Code (NO_PIE) for executables.

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.

check_pie_supported([OUTPUT_VARIABLE <output>]

[LANGUAGES <lang>...])


Options are:

Set <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.
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.


NOTE:

To use check_pie_supported(), policy CMP0083 must be set to NEW; otherwise, a fatal error will occur.



Variables

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

Set to true if PIE is supported by the linker and false otherwise.
Set to true if NO_PIE is supported by the linker and false otherwise.



Examples

To enable PIE on an executable target at link time as well, include this module and call check_pie_supported() before setting the POSITION_INDEPENDENT_CODE target property. This will determine whether the linker for each checked language supports PIE-related link options. For example:

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


Since not all linkers require or support PIE-related link options (for example, MSVC), retrieving any error messages might be useful for logging purposes:

add_executable(foo ...)
include(CheckPIESupported)
check_pie_supported(OUTPUT_VARIABLE output LANGUAGES C)
set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)
if(NOT CMAKE_C_LINK_PIE_SUPPORTED)

message(WARNING "PIE is not supported at link time:\n${output}"
"PIE link options will not be passed to linker.") endif()


Setting the POSITION_INDEPENDENT_CODE target property on an executable without this module will set PIE-related compile options but not PIE-related link options, which might not be sufficient in certain cases:

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


CheckPrototypeDefinition

This module provides a command to check if a C function has the expected prototype.

Load this module in a CMake project with:

include(CheckPrototypeDefinition)


Commands

This module provides the following command:

Checks if 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.
<prototype>
The expected prototype of the function, provided as a string.
<return>
The return value of the function. This will be used as a return value in the function definition body of the generated test program to verify that the function's return type matches the expected type.
<headers>
A semicolon-separated list of header file names required for checking the function prototype.
<variable>
The name of the variable to store the check result. This variable will be created as an internal cache variable.

This command generates a test program and verifies that it builds without errors. The generated test program includes specified <headers>, defines a function with given literal <prototype> and <return> value and then uses the specified <function>. The simplified test program can be illustrated as:

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


Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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

Checking if 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 source code can be built for a given language.

Load this module in a CMake project with:

include(CheckSourceCompiles)


Commands

This module provides the following command:

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 code language <lang>. The result of the check is stored in the internal cache variable specified by <variable>.

The arguments are:

<lang>
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 HIP language.

Added in version 3.26: Support for Swift language.

<code>
The 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>
Variable name of an internal cache variable to store the result of the check, with boolean true for success and boolean false for failure.
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.
By default, the internal test source file used for the check will be given a file extension that matches the requested language (e.g., .c for C, .cxx for C++, .F90 for Fortran, etc.). This option can be used to override this with the .<extension> instead.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


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

Example: Basic Usage

The following example demonstrates how to check whether the C++ compiler supports a specific language feature using this module. 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(CheckSourceCompiles)
check_source_compiles(CXX "

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


Example: Checking Code With Bracket Argument

The following example shows how to check whether the C compiler supports the noreturn attribute. Code is supplied using the Bracket Argument for easier embedded quotes handling:

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 the following example, this module is used to perform a compile-only check of Fortran source code, whether the compiler supports the pure procedure attribute:

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

In the following example, this module is used in combination with the CMakePushCheckState module to modify required libraries when checking whether the PostgreSQL PGVerbosity enum contains PQERRORS_SQLSTATE (available as of PostgreSQL version 12):

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 to check whether the source code can be built and also run.

CheckSourceRuns

Added in version 3.19.

This module provides a command to check whether a source code can be built and run.

Load this module in a CMake project with:

include(CheckSourceRuns)


Commands

This module provides the following command:

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

check_source_runs(<lang> <code> <variable> [SRC_EXT <extension>])


This command checks once that the <lang> source code 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 specified by <variable>.

The arguments are:

<lang>
The programming language of the source <code> to check. Supported languages are: C, CXX, CUDA, Fortran, HIP, OBJC, and OBJCXX.

Added in version 3.21: Support for 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).
<variable>
Name of the internal cache variable with 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.
By default, the internal test source file used for the check will be given a file extension that matches the requested language (e.g., .c for C, .cxx for C++, .F90 for Fortran, etc.). This option can be used to override this with the .<extension> instead.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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

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(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:

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

The following example demonstrates how to check whether the C++ standard library is functional and std::vector works at runtime. If the source compiles, links, and runs successfully, internal cache variable HAVE_WORKING_STD_VECTOR will be set to boolean true value. Code is supplied using 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

In the following example, this module is used in combination with the CMakePushCheckState module to modify required compile definitions and libraries when checking whether the C function sched_getcpu() is supported and operational at runtime. For example, on some systems, the sched_getcpu() function may be available at compile time but not actually implemented by the kernel. In such 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 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.

Load this module in a CMake project with:

include(CheckStructHasMember)


Commands

This module provides the following command:

Checks once if the given struct or class has the specified member variable:

check_struct_has_member(

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


This command checks once whether the struct or class <struct> contains the specified <member> after including the given header(s) <headers> where the prototype should be declared. Multiple header files can be specified in one argument as a string using a semicolon-separated list. The result is stored in an internal cache variable <variable>.

The options are:

Use the <language> compiler to perform the check. Acceptable values are C and CXX. If not specified, it defaults to C.

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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: Checking C Struct Member

In the following example, this module checks if the C struct timeval has a member variable tv_sec after including the <sys/select.h> header. The result of the check is stored in the internal cache variable HAVE_TIMEVAL_TV_SEC.

include(CheckStructHasMember)
check_struct_has_member(

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


Example: Checking C++ Struct Member

In the following example, this module checks if the C++ struct std::tm has a member variable tm_gmtoff after including the <ctime> header. The result of the check is stored in the internal cache variable HAVE_TM_GMTOFF.

include(CheckStructHasMember)
check_struct_has_member(

std::tm
tm_gmtoff
ctime
HAVE_TM_GMTOFF
LANGUAGE CXX )


Example: Isolated Check With Compile Definitions

In the following example, the check is performed with temporarily modified compile definitions using the CMakePushCheckState module:

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.

Load this module in a CMake project with:

include(CheckSymbolExists)


Commands

This module provides the following command:

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

check_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 is considered available and assumed to work. If the symbol is declared as a function or variable, the check also ensures that it links successfully (i.e., the symbol must exist in a linked library or object file). Compiler intrinsics may not be detected, as they are 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.

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

Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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 check for the presence of a preprocessor macro SEEK_SET and the C function fopen() from the <stdio.h> header using this module:

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 to check whether a C++ symbol exists.

CheckTypeSize

This module provides a command to check the size of a C/C++ type or expression.

Load this module in a CMake project with:

include(CheckTypeSize)


Commands

This module provides the following command:

Checks once whether the C/C++ type or expression exists and determines its size:

check_type_size(<type> <variable> [BUILTIN_TYPES_ONLY] [LANGUAGE <language>])


The arguments are:

<type>
The type or expression being checked.
<variable>
The name of the variable and a prefix used for storing the check results.
If given, only compiler-builtin types will be supported in the check. If not given, the command checks for common headers <sys/types.h>, <stdint.h>, and <stddef.h>, and saves results in HAVE_SYS_TYPES_H, HAVE_STDINT_H, and HAVE_STDDEF_H internal cache variables. The type size check automatically includes the available headers, thus supporting checks of types defined in the headers.
Uses the <language> compiler to perform the check. Acceptable values are C and CXX. If not specified, it defaults to C.

Result Variables

Results are reported in the following variables:

Internal cache variable that holds a boolean true or false value indicating whether the type or expression <type> exists.
<variable>
Internal cache variable that holds one of the following values:
<size>
If the type or expression exists, it will have a non-zero size <size> in bytes.
0
When type has architecture-dependent size; This may occur when CMAKE_OSX_ARCHITECTURES has multiple architectures. In this case <variable>_CODE contains preprocessor tests mapping from each architecture macro to the corresponding type size. The list of architecture macros is stored in <variable>_KEYS, and the value for each key is stored in <variable>-<key>.
"" (empty string)
When type or expression does not exist.

<variable>_CODE
CMake variable that holds preprocessor code to define the macro <variable> to the size of the type, or to leave the macro undefined if the type does not exist.

Despite the name of this command, it may also be used to determine the size of more complex expressions. For example, to check the size of a struct member:

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


Variables Affecting the Check

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

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


Added in version 3.1.

If this variable evaluates to a boolean true value, all status messages associated with the check will be suppressed.


A semicolon-separated list of extra header files to include when performing the check.


Examples

Consider the code:

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 the 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 SIZE_OF_LONG_KEYS)

message("key: ${key}")
message("value: ${SIZE_OF_LONG-${key}}") endforeach() message("SIZEOF_LONG_CODE: ${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 SIZE_OF_LONG 4
#elif defined(__x86_64)
# define SIZE_OF_LONG 8
#else
# error SIZE_OF_LONG unknown
#endif


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:

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 is stored in an internal cache variable <variable>.

NOTE:

Prefer using CheckSymbolExists or CheckSourceCompiles instead of this command for more robust detection. 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 following variables may be set before calling this command to modify the way the check is run:

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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 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 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 to check whether a C symbol exists.

CMakeAddFortranSubdirectory

This module provides a command to add a Fortran project located in a subdirectory.

Load it in a CMake project with:

include(CMakeAddFortranSubdirectory)


Commands

This module provides the following command:

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.

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. 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.

The options are:

The name of the Fortran project as defined in the top-level CMakeLists.txt located in <subdir>.
Directory where the project places .lib archive files. A relative path is interpreted as relative to CMAKE_CURRENT_BINARY_DIR.
Directory where the project places .dll runtime files. A relative path is interpreted as relative to CMAKE_CURRENT_BINARY_DIR.
Names of library targets to create or import into the current project.
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>.

Additional command-line flags passed to cmake(1) command when configuring the Fortran subproject.
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.




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)


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++).

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:

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.


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. This helps maintain a clean configuration interface by only displaying options that are relevant to the current settings.

Load this module in a CMake project with:

include(CMakeDependentOption)


Commands

This module provides the following command:

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.

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>
Specifies the conditions that determine whether <variable> is set and visible in the GUI.
  • If <condition> evaluates to boolean false, 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 option is shown in the GUI, allowing the user to enable or disable it.
  • If <condition> later evaluates to boolean false (on consecutive configuration run), 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 as used in an if(<condition>) clause. See policy CMP0127. This enables using entire condition syntax (such as grouping conditions with parens and similar).


<else-value>
The value assigned to a local variable named <variable>, when <condition> evaluates to boolean false.


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 demonstrates how the module allows 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. However, 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 following example, if the variable USE_BAR is ON and 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 the 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 fhe following example, if the condition evaluates to true, the option USE_FOO is available and set to ON. Otherwise, it is 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 demonstrates 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 to provide a boolean option that the user can optionally select.

CMakeFindDependencyMacro

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

find_dependency(<dep> [...])


It is designed to be used in a Package Configuration File (<PackageName>Config.cmake). find_dependency forwards the correct parameters for QUIET and REQUIRED which were passed to the original find_package() call. Any additional arguments specified are forwarded to find_package().

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:

The call to return() makes this macro unsuitable to call from Find Modules.



Package Dependency Search Optimizations

If find_dependency is called with arguments identical to a previous call in the same directory, perhaps due to diamond-shaped package dependencies, the underlying call to find_package() is optimized out. This optimization is important to support large package dependency graphs while avoiding a combinatorial explosion of repeated searches. However, the heuristic cannot account for ambient variables that affect package behavior, such as <PackageName>_USE_STATIC_LIBS, offered by some packages. Therefore 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 the optimization to support cases in which 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 to account for varying find_dependency call arguments.

CMakeFindPackageMode

This module is executed by cmake when invoked with the --find-package option to locate the requested package.

NOTE:

This is internal module and is not meant to be included directly in the project. For usage details, refer to the --find-package documentation.


CMakeGraphVizOptions

The builtin Graphviz support of CMake.

Generating Graphviz files

CMake can generate Graphviz files showing the dependencies between the targets in a project, as well as external libraries which are linked against.

When running CMake with the --graphviz=foo.dot option, it produces:

  • a foo.dot file, showing all dependencies in the project
  • a foo.dot.<target> file for each target, showing on which other targets it depends
  • a foo.dot.<target>.dependers file for each target, showing which other targets depend on it

Those .dot files can be converted to images using the dot command from the Graphviz package:

dot -Tpng -o foo.png foo.dot


Added in version 3.10: The different dependency types PUBLIC, INTERFACE and PRIVATE are represented as solid, dashed and dotted edges.

Variables specific to the Graphviz support

The resulting graphs can be huge. The look and content of the generated graphs can be controlled using the file CMakeGraphVizOptions.cmake. This file is first searched in CMAKE_BINARY_DIR, and then in CMAKE_SOURCE_DIR. If found, the variables set in it are used to adjust options for the generated Graphviz files.

The graph name.
  • Mandatory: NO
  • Default: value of CMAKE_PROJECT_NAME


The header written at the top of the Graphviz files.
  • Mandatory: NO
  • Default: "node [ fontsize = "12" ];"


The prefix for each node in the Graphviz files.
  • Mandatory: NO
  • Default: "node"


Set to FALSE to exclude executables from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to exclude static libraries from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to exclude shared libraries from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to exclude module libraries from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to exclude interface libraries from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to exclude object libraries from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to exclude unknown libraries from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to exclude external libraries from the generated graphs.
  • Mandatory: NO
  • Default: TRUE


Set to TRUE to include custom targets in the generated graphs.
  • Mandatory: NO
  • Default: FALSE


A list of regular expressions for names of targets to exclude from the generated graphs.
  • Mandatory: NO
  • Default: empty


Set to FALSE to not generate per-target graphs foo.dot.<target>.
  • Mandatory: NO
  • Default: TRUE


Set to FALSE to not generate depender graphs foo.dot.<target>.dependers.
  • Mandatory: NO
  • Default: TRUE


CMakePackageConfigHelpers

Helper functions for creating config files that can be included by other projects to find and use a package.

Generating a Package Configuration 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>]
)



configure_package_config_file() should be used instead of the plain configure_file() command when creating the <PackageName>Config.cmake or <PackageName>-config.cmake file for installing a project or library. It helps make the resulting package relocatable by avoiding hardcoded paths in the installed <PackageName>Config.cmake file.

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. This has the effect 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> given as PATH_VARS are the variables which contain install destinations. For each of them, the macro will create a helper variable PACKAGE_<var...>. These helper variables must be used in the FooConfig.cmake.in file for setting the installed location. They are calculated by configure_package_config_file() so that they are always relative to the installed location of the package. This works both for relative and also for absolute locations. For absolute locations, it works only if the absolute location is a subdirectory of INSTALL_PREFIX.

Added in version 3.30: The variable PACKAGE_PREFIX_DIR will always be defined after the @PACKAGE_INIT@ line. It will hold the value of the base install location. In general, variables defined via the PATH_VARS mechanism should be used instead, but PACKAGE_PREFIX_DIR can be used for those cases not easily handled by PATH_VARS, such as for files installed directly to the base install location rather than a subdirectory of it.

NOTE:

When consumers of the generated file use CMake 3.29 or older, the value of PACKAGE_PREFIX_DIR can be changed by a call to find_dependency() or find_package(). If a project relies on PACKAGE_PREFIX_DIR, it is the project's responsibility to ensure that the value of PACKAGE_PREFIX_DIR is preserved across any such calls, or any other calls which might include another file generated by configure_package_config_file().


Added in version 3.1: If the INSTALL_PREFIX argument is passed, this is used as the base path to calculate all the relative paths. The <path> argument must be an absolute path. If this argument is not passed, the CMAKE_INSTALL_PREFIX variable will be used instead. The default value is good when generating a FooConfig.cmake file to use your package from the install tree. When generating a FooConfig.cmake file to use your package from the build tree, this option should be used.

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

set_and_check() should be used instead of the normal set() command for setting directories and file locations. In addition to setting the variable, it also checks that the referenced file or directory actually exists and fails with a fatal error if it doesn't. This ensures that the generated FooConfig.cmake file does not contain wrong references. Add the NO_SET_AND_CHECK_MACRO option to prevent the generation of the set_and_check() macro in the FooConfig.cmake file.

check_required_components(<PackageName>) should be called at the end of the FooConfig.cmake file. This macro checks whether all requested, non-optional components have been found, and if this is not the case, it sets the Foo_FOUND variable to FALSE so that the package is considered to be not found. It does that by testing the Foo_<Component>_FOUND variables for all requested required components. This macro should be called even if the package doesn't provide any components to make sure users are not specifying components erroneously. Add the NO_CHECK_REQUIRED_COMPONENTS_MACRO option to prevent the generation of the check_required_components() macro in the FooConfig.cmake file.

See also Example Generating Package Files.

Generating a Package Version File

Create a version file for a project:

write_basic_package_version_file(<filename>

[VERSION <major.minor.patch>]
COMPATIBILITY <AnyNewerVersion|SameMajorVersion|SameMinorVersion|ExactVersion>
[ARCH_INDEPENDENT] )



Writes a file for use as a <PackageName>ConfigVersion.cmake file to <filename>. See the documentation of find_package() for details on such files.

<filename> is the output filename, which should be in the build tree. <major.minor.patch> is the version number of the project to be installed.

If no VERSION is given, the PROJECT_VERSION variable is used. If this hasn't been set, it errors out.

The COMPATIBILITY mode AnyNewerVersion means that the installed package version will be considered compatible if it is newer or exactly the same as the requested version. This mode should be used for packages which are fully backward compatible, also across major versions. If SameMajorVersion is used instead, then 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. This mode should be used for packages which 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 must be the same as requested, e.g version 0.2 will not be compatible if 0.1 is requested. If ExactVersion is used, then the package is only considered compatible if the requested version matches exactly its own version number (not considering the tweak version). For example, version 1.2.3 of a package is only considered compatible to requested version 1.2.3. This mode is for packages without compatibility guarantees. If your project has more elaborate version matching rules, you will need to write your own custom <PackageName>ConfigVersion.cmake file instead of using this macro.

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 architecture. Otherwise, an architecture check will be performed, and the package will be considered compatible only 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 is used on a 32-bit architecture, unless ARCH_INDEPENDENT is given, in which case the package is considered compatible on any architecture.

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 AnyNewerVersion, SameMajorVersion and SameMinorVersion arguments of COMPATIBILITY handle the version range, if one is specified (see find_package() command for the details). ExactVersion mode is incompatible with version ranges and will display an author warning if one is specified.

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 and you should 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

Added in version 3.29.

Create an Apple platform selection file:

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>]
)


Write a file that includes an Apple-platform-specific .cmake file, e.g., for use as <PackageName>Config.cmake. This can be used in conjunction 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.

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.
Path prefix to which the package will be installed by the caller. The <path> argument must be an absolute path. If this argument is not passed, the CMAKE_INSTALL_PREFIX variable will be used instead.
File to include if the platform is macOS.
File to include if the platform is iOS.
File to include if the platform is iOS Simulator.
Added in version 3.31.

File to include if the platform is iOS Catalyst.

File to include if the platform is tvOS.
File to include if the platform is tvOS Simulator.
File to include if the platform is watchOS.
File to include if the platform is watchOS Simulator.
File to include if the platform is visionOS.
File to include if the platform is visionOS Simulator.
If the consuming project is built for an unsupported platform, set <variable> to an error message. The includer may use this information to pretend the package was not found. If this option is not given, the default behavior is to issue a fatal error.

If any of the optional include files is not specified, and the consuming project is built for its corresponding platform, the generated file will consider the platform to be unsupported. The behavior is determined by the ERROR_VARIABLE option.


Generating an Apple Architecture Selection File

Added in version 3.29.

Create an Apple architecture selection file:

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>]
)


Write a file that includes an Apple-architecture-specific .cmake file based on CMAKE_OSX_ARCHITECTURES, e.g., for inclusion from an Apple-specific <PackageName>Config.cmake file.

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.
Path prefix to which the package will be installed by the caller. The <path> argument must be an absolute path. If this argument is not passed, the CMAKE_INSTALL_PREFIX variable will be used instead.
Architectures provided by entries of SINGLE_ARCHITECTURE_INCLUDE_FILES.
Architecture-specific files. One of them will be loaded when CMAKE_OSX_ARCHITECTURES contains a single architecture matching the corresponding entry of SINGLE_ARCHITECTURES.
Architectures provided by the UNIVERSAL_INCLUDE_FILE.

The list may include $(ARCHS_STANDARD) to support consumption using the Xcode generator, but the architectures should always be listed individually too.

A file to load when CMAKE_OSX_ARCHITECTURES contains a (non-strict) subset of the UNIVERSAL_ARCHITECTURES and does not match any one of the SINGLE_ARCHITECTURES.
If the consuming project is built for an unsupported architecture, set <variable> to an error message. The includer may use this information to pretend the package was not found. If this option is not given, the default behavior is to issue a fatal error.


Example Generating Package Files

Example using both the configure_package_config_file() and write_basic_package_version_file() commands:

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 provides convenience commands, primarily intended for debugging, to print the values of properties and variables.

Load this module in CMake with:

include(CMakePrintHelpers)


Commands

This module provides the following commands:

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. The scope keyword and its arguments must appear before the PROPERTIES keyword in the argument list.


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"


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.

Examples

Including this module in a project:

include(CMakePrintSystemInformation)


prints various internal CMake variables. For example:

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 various CMake check commands (e.g., check_symbol_exists(), etc.) are performed.

Load this module in CMake project with:

include(CMakePushCheckState)


This module provides the following commands, which are useful for scoped configuration, for example, in CMake modules or when performing checks in a controlled environment, ensuring that temporary modifications are isolated to the scope of the check and do not propagate into other parts of the build system:

  • 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:

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.

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.

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.

Added in version 3.14.

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


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).

Added in version 3.31.

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


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.6: Previously used already by the check_type_size() command; now also supported by this module.

A semicolon-separated list of extra header files to include when performing the check.


NOTE:

Other CMake variables, such as CMAKE_<LANG>_FLAGS, propagate to all checks regardless of commands provided by this module, as those fundamental variables are designed to influence the global state of the build system.


Commands

Pushes (saves) the current states of the above variables onto a stack:

cmake_push_check_state([RESET])


Use this command to preserve the current configuration before making temporary modifications for specific checks.

When this option is specified, the command not only saves the current states of the listed variables but also resets them to empty, allowing them to be reconfigured from a clean state.


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

cmake_reset_check_state()


Use this command when performing multiple sequential checks that require entirely new configurations, ensuring no previous configuration unintentionally carries over.


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

cmake_pop_check_state()


Use this command to revert temporary changes made during a check. To prevent unexpected behavior, pair each cmake_push_check_state() with a corresponding cmake_pop_check_state().


Examples

Example: Isolated Check With Compile Definitions

In the following example, a check for the C symbol memfd_create() is performed with an additional _GNU_SOURCE compile definition, without affecting global compile flags. The RESET option is used to ensure that any prior values of the check-related variables are explicitly cleared before the check.

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

In the following example, variable states are pushed onto the stack multiple times, allowing for sequential or nested checks. Each cmake_pop_check_state() restores the most recent pushed states.

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

Use this script to verify that embedded manifests and side-by-side manifests for a project match.

This script first recursively globs *.manifest files from the current directory and creates a list of allowed version. Additional versions can be passed by setting allow_versions from the invocation command. Next, the script globs *.exe and *.dll files. Each .exe and .dll file is scanned for embedded manifests and the versions of CRT are checked to be in the list of allowed version.

Example

To run this script, navigate to a directory and run the script with cmake -P.

cmake -Dallow_versions=8.0.50608.0 -PCMakeVerifyManifest.cmake


This call allows an embedded manifest of 8.0.50608.0 to be used in a project, even if that version was not found in a .manifest file.

CPack

Configure generators for binary installers and source packages.

Introduction

The CPack module generates the configuration files CPackConfig.cmake and CPackSourceConfig.cmake. They are 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 details.

The generated binary installers will contain all files that have been installed via CMake's install() command (and the deprecated commands install_files(), install_programs(), and install_targets()). Note that the DESTINATION option of the install() command must be a relative path; otherwise installed files are ignored by CPack.

Certain kinds of binary installers can be configured such that users can select 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 those 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 will 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. If you need per-cpack-generator logic to control other cpack settings, then you need a CPACK_PROJECT_CONFIG_FILE. If set, the CPACK_PROJECT_CONFIG_FILE is included automatically on a per-generator basis. It only need 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, one may 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 one may 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 your CMakeLists.txt file, there are a variety of variables that can be set to customize the resulting installers. The most commonly-used variables are:

The name of the package (or application). If not specified, it defaults to the project name.

The name of the package vendor. (e.g., "Kitware"). The default is "Humanity".

The directory in which CPack is doing its packaging. If it is not set then this will default (internally) to the build dir. This variable may be defined in a CPack config file or from the cpack command line option -B. If set, the command line option overrides the value found in the config file.

Package major version. This variable will always be set, but its default value depends on whether or not version details were given to the project() command in the top level CMakeLists.txt file. If version details were given, the default value will be CMAKE_PROJECT_VERSION_MAJOR. If no version details were given, a default version of 0.1.1 will be assumed, leading to CPACK_PACKAGE_VERSION_MAJOR having a default value of 0.

Package minor version. The default value is determined based on whether or not version details were given to the project() command in the top level CMakeLists.txt file. If version details were given, the default value will be CMAKE_PROJECT_VERSION_MINOR, but if no minor version component was specified then CPACK_PACKAGE_VERSION_MINOR will be left unset. If no project version was given at all, a default version of 0.1.1 will be assumed, leading to CPACK_PACKAGE_VERSION_MINOR having a default value of 1.

Package patch version. The default value is determined based on whether or not version details were given to the project() command in the top level CMakeLists.txt file. If version details were given, the default value will be CMAKE_PROJECT_VERSION_PATCH, but if no patch version component was specified then CPACK_PACKAGE_VERSION_PATCH will be left unset. If no project version was given at all, a default version of 0.1.1 will be assumed, leading to CPACK_PACKAGE_VERSION_PATCH having a default value of 1.

A description of the project, used in places such as the introduction screen of CPack-generated Windows installers. If not set, the value of this variable is populated from the file named by CPACK_PACKAGE_DESCRIPTION_FILE.

A text file used to describe the project when CPACK_PACKAGE_DESCRIPTION is not explicitly set. The default value for CPACK_PACKAGE_DESCRIPTION_FILE points to a built-in template file Templates/CPack.GenericDescription.txt.

Short description of the project (only a few words). If the CMAKE_PROJECT_DESCRIPTION variable is set, it is used as the default value, otherwise the default will be a string generated by CMake based on CMAKE_PROJECT_NAME.

Project homepage URL. The default value is taken from the CMAKE_PROJECT_HOMEPAGE_URL variable, which is set by the top level project() command, or else the default will be empty if no URL was provided to project().

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}



Installation directory on the target system. This may be used by some CPack generators like NSIS to create an installation directory e.g., "CMake 2.5" below the installation prefix. All installed elements will be put inside this directory.

A branding image that will be displayed inside the installer (used by GUI installers).

Added in version 3.7.

An algorithm that will be used to generate an additional file with the checksum of the package. The output file name will be:

${CPACK_PACKAGE_FILE_NAME}.${CPACK_PACKAGE_CHECKSUM}


Supported algorithms are those listed by the string(<HASH>) command.


CPack-time project CPack configuration file. This file is included at cpack time, once per generator after CPack has set CPACK_GENERATOR to the actual generator being used. It allows per-generator setting of CPACK_* variables at cpack time.

License to be embedded in the installer. It will typically be displayed to the user by the produced installer (often with an explicit "Accept" button, for graphical installers) prior to installation. This license file is NOT added to the installed files but is 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. If you want to install a license file (may be the same as this one) along with your project, you must add an appropriate CMake install() command in your CMakeLists.txt.

ReadMe file to be embedded in the installer. It typically describes in some detail the purpose of the project during the installation. Not all CPack generators use this file.

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.

Disables the component-based installation mechanism. When set, the component specification is ignored and all installed items are put in a single "MONOLITHIC" package. Some CPack generators do monolithic packaging by default and may be asked to do component packaging by setting CPACK_<GENNAME>_COMPONENT_INSTALL to TRUE.

List of CPack generators to use. If not specified, CPack will create a set of options following the naming pattern CPACK_BINARY_<GENNAME> (e.g. CPACK_BINARY_NSIS) allowing the user to enable/disable individual generators. If the -G option is given on the cpack command line, it will override this variable and any CPACK_BINARY_<GENNAME> options.

The name of the CPack binary configuration file. This file is the CPack configuration generated by the CPack module for binary installers. Defaults to CPackConfig.cmake.

Lists each of the executables and associated text label to be used to create Start Menu shortcuts. For example, setting this to the list ccmake;CMake will create a shortcut named "CMake" that will execute the installed executable ccmake. Not all CPack generators use it (at least NSIS, Inno Setup and WIX do).

List of files to be stripped. Starting with CMake 2.6.0, CPACK_STRIP_FILES will be a boolean variable which enables stripping of all files (a list of files evaluates to TRUE in CMake, so this change is compatible).

Added in version 3.4.

If set to TRUE, values of variables prefixed with CPACK_ will be 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 received by the cpack program. Defaults to FALSE for backwards compatibility.


Added in version 3.20.

Number of threads to use when performing parallelized operations, such as 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 will be used for compression.

A positive integer can be used to specify an exact desired thread count.

When given a negative integer CPack will use the absolute value as the upper limit but may choose a lower value based on the available hardware concurrency.

Given 0 CPack will 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:

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.

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.


Variables for Source Package Generators

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

The name of the source package. For example cmake-2.6.1.

List of files in the source tree that will be stripped. Starting with CMake 2.6.0, CPACK_SOURCE_STRIP_FILES will be a boolean variable which enables stripping of all files (a list of files evaluates to TRUE in CMake, so this change is compatible).

List of generators used for the source packages. As with CPACK_GENERATOR, if this is not specified then CPack will create a set of options (e.g. CPACK_SOURCE_ZIP) allowing users to select which packages will be generated.

The name of the CPack source configuration file. This file is the CPack configuration generated by the CPack module for source installers. Defaults to CPackSourceConfig.cmake.

Pattern of files in the source tree that won't be packaged when building a source package. This is a list of regular expression patterns (that must be properly escaped), e.g., /CVS/;/\\.svn/;\\.swp$;\\.#;/#;.*~;cscope.*

Variables for Advanced Use

The following variables are for advanced uses of CPack:

What CMake generator should be used if the project is a CMake project. Defaults to the value of CMAKE_GENERATOR. Few users will want to change this setting.

List of four values that specify what project to install. The four values are: Build directory, Project Name, Project Component, Directory. If omitted, CPack will build an installer that installs everything.

System name, defaults to the value of CMAKE_SYSTEM_NAME, except on Windows where it will be win32 or win64.

Package full version, used internally. By default, this is built from CPACK_PACKAGE_VERSION_MAJOR, CPACK_PACKAGE_VERSION_MINOR, and CPACK_PACKAGE_VERSION_PATCH.

Directory for the installed files.

Extra commands to install components. The environment variable CMAKE_INSTALL_PREFIX is set to the temporary install directory during execution.

Added in version 3.16.

Extra CMake scripts executed by CPack during its local staging installation. They are executed before installing the files to be packaged. The scripts are not called by a standalone install (e.g.: make install). For every script, the following variables will be set: CMAKE_CURRENT_SOURCE_DIR, CMAKE_CURRENT_BINARY_DIR and CMAKE_INSTALL_PREFIX (which is 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 can be used to specify scripts to be executed later in the packaging process.


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.


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.


Added in version 3.19.

List of package files created in the staging directory, with each file provided as a full absolute path. This variable is populated by CPack just before invoking the post-build scripts listed in CPACK_POST_BUILD_SCRIPTS. It is 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.


Extra directories to install.

Registry key used when installing this project. This is only used by installers for Windows. The default value is based on the installation directory.

List of desktop links to create. Each desktop link requires a corresponding start menu shortcut as created by CPACK_PACKAGE_EXECUTABLES.

CPack generated options for binary generators. The CPack.cmake module generates (when CPACK_GENERATOR is not set) a set of CMake options (see CMake option() command) which may then be used to select the CPack generator(s) to be used when building the package target or when running cpack without the -G option.

Added in version 3.25.

Specify the readelf executable path used by CPack. The default value will be taken from the CMAKE_READELF variable, if set, which may be populated CMake when enabling languages. If CMAKE_READELF is not set, CPack will use find_program() to determine the readelf path when needed.


Added in version 3.25.

Specify the objcopy executable path used by CPack. The default value will be taken from the CMAKE_OBJCOPY variable, if set, which may be populated by CMake when enabling languages. If CMAKE_OBJCOPY is not set, CPack will use find_program() to determine the objcopy path when needed.


Added in version 3.25.

Specify the objdump executable path used by CPack. The default value will be taken from the CMAKE_OBJDUMP variable, which may be populated by CMake when enabling languages. If CMAKE_OBJDUMP is not set, CPack will use find_program() to determine the objdump path when needed.


CPackComponent

Configure components for binary installers and source packages.

Introduction

This module is automatically included by CPack.

Certain binary installers (especially the graphical installers) generated by CPack allow users to select individual application components to install. This module allows developers to configure the packaging of such 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:

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, it is possible to obtain a list of all defined components and then remove the unwanted ones from the 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")



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. One can change the default behavior by setting this variable to 0/1 or OFF/ON.


Specify how components are grouped for multi-package component-aware CPack generators.

Some generators like RPM or ARCHIVE (TGZ, ZIP, ...) may generate several packages 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


The name to be displayed for a component.

The description of a component.

The group of a component.

The dependencies (list of components) on which this component depends.

True if this component is hidden from the user.

True if this component is required.

True if this component is not selected to be installed by default.

Commands

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 is the name of an installation component, as defined by the COMPONENT argument of one or more CMake install() commands. With the cpack_add_component command one can set a name, a description, and other attributes of an installation component. One can also assign a component to a component group.

DISPLAY_NAME is the displayed name of the component, used in graphical installers to display the component name. This value can be any string.

DESCRIPTION is 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.

HIDDEN indicates that this component will be hidden in the graphical installer, so that the user cannot directly change whether it is installed or not.

REQUIRED indicates that 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 indicates that 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.

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 installations types is selected, this component will automatically be selected. Installation types are described with the cpack_add_install_type command, detailed below.

DOWNLOADED indicates that 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


Describes a group of related CPack installation components.

cpack_add_component_group(groupname

[DISPLAY_NAME name]
[DESCRIPTION description]
[PARENT_GROUP parent]
[EXPANDED]
[BOLD_TITLE])


The cpack_add_component_group 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 is the displayed name of the component group, used in graphical installers to display the component group name. This value can be any string.

DESCRIPTION is 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.

Add installation 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 is 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


Configure CPack to download selected components on-the-fly as part of the installation process.

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:


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 is 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.

The ALL flag 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 (QtIFW).

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

Commands

The module defines the following commands:

Sets the arguments specific to the CPack IFW generator.

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 cpack_add_component() command.

if set, then the component will be packaged and installed as part of a group to which it belongs.
Added in version 3.6.

if set, then the package manager stays disabled until that component is updated.

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.

Added in version 3.8.

if set, then the component must always be installed. It is a equivalent of the REQUIRED option from the cpack_add_component() command.

Added in version 3.8.

set it if the component needs to be installed with elevated permissions.

NAME
is used to create domain-like identification for this component. By default used origin component name.
Added in version 3.8.

set to rewrite original name configured by cpack_add_component() command.

Added in version 3.8.

set to rewrite original description configured by cpack_add_component() command.

Added in version 3.8.

will be added to the component description if this is an update to the component.

is version of component. By default used CPACK_PACKAGE_VERSION.
Added in version 3.8.

keep empty to auto generate.

is a relative or absolute path to operations script for this component.
Added in version 3.8.

is priority of the component in the tree.

Deprecated since version 3.8: Old name for SORTING_PRIORITY.

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.

Added in version 3.8.

list of identifiers of component or component group in QtIFW style that this component has an automatic dependency on.

pair of <display_name> and <file_path> of license text for this component. You can specify more then one license.
Added in version 3.8.

Possible values are: TRUE, FALSE, and SCRIPT. Set to FALSE to disable the component in the installer or to SCRIPT to resolved during runtime (don't forget add the file of the script as a value of the SCRIPT option).

Added in version 3.7.

is a list of <file_path> ('.ui' files) representing pages to load.

Added in version 3.8.

is a list of <file_path> ('.qm' files) representing translations to load.

Added in version 3.10.

list of identifiers of component or component group to replace.

Added in version 3.10.

Possible values are: TRUE, FALSE. Set 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.



Sets the arguments specific to the CPack IFW generator.

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 cpack_add_component_group() command.

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.

Added in version 3.8.

if set, then the group must always be installed.

Added in version 3.8.

set it if the component group needs to be installed with elevated permissions.

NAME
is used to create domain-like identification for this component group. By default used origin component group name.
Added in version 3.8.

set to rewrite original name configured by cpack_add_component_group() command.

Added in version 3.8.

set to rewrite original description configured by cpack_add_component_group() command.

Added in version 3.8.

will be added to the component group description if this is an update to the component group.

is version of component group. By default used CPACK_PACKAGE_VERSION.
Added in version 3.8.

keep empty to auto generate.

is a relative or absolute path to operations script for this component group.
is priority of the component group in the tree.
Deprecated since version 3.8: Old name for SORTING_PRIORITY.

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.

Added in version 3.8.

list of identifiers of component or component group in QtIFW style that this component group has an automatic dependency on.

pair of <display_name> and <file_path> of license text for this component group. You can specify more then one license.
Added in version 3.8.

Possible values are: TRUE, FALSE, and SCRIPT. Set 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 resolved during runtime (don't forget add the file of the script as a value of the SCRIPT option).

Added in version 3.7.

is a list of <file_path> ('.ui' files) representing pages to load.

Added in version 3.8.

is a list of <file_path> ('.qm' files) representing translations to load.

Added in version 3.10.

list of identifiers of component or component group to replace.

Added in version 3.10.

Possible values are: TRUE, FALSE. Set 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.



Add QtIFW specific remote repository to binary installer.

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.

if set, then the repository will be disabled by default.
URL
is points to a list of available components.
is used as user on a protected repository.
is password to use on a protected repository.
is string to display instead of the URL.


Added in version 3.6.

Update QtIFW specific repository from 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.

URL
is points to a list of available components.
is points to a list that will replaced.
is points to a list that will replace to.
is used as user on a protected repository.
is password to use on a protected repository.
is string to display instead of the URL.


Added in version 3.7.

Add additional resources in the installer binary.

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


This command will also add the specified files to a variable CPACK_IFW_PACKAGE_RESOURCES.


CPackIFWConfigureFile

Added in version 3.8.

The module defines configure_file() similar command to configure file templates prepared in QtIFW/SDK/Creator style.

Commands

The module defines the following commands:

Copy a file to another location and modify its contents.

cpack_ifw_configure_file(<input> <output>)


Copies an <input> file to an <output> file and substitutes variable values referenced as %{VAR} or %VAR% in the input file content. Each variable reference will be replaced with the current value of the variable, or the empty string if the variable is not defined.


CSharpUtilities

Added in version 3.8.

This utility module is intended to simplify the configuration of CSharp/.NET targets and provides a collection of commands for managing CSharp targets with Visual Studio Generators, version 2010 and newer.

Load this module 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

Sets source file properties for use of Windows Forms:

csharp_set_windows_forms_properties([<files>...])


<files>...
A list of zero or more source files which are relevant for setting the VS_CSHARP_<tagname> source file properties. This typically includes files with .cs, .resx, and .Designer.cs extensions.

Use this command when a CSharp target in the project uses Windows Forms.

This command searches in the provided list of files for pairs of related files ending with .Designer.cs (designer files) or .resx (resource files). For each such file, a corresponding base .cs file is searched (with the same base name). When found, the VS_CSHARP_<tagname> source file properties are set as follows:

VS_CSHARP_SubType "Form"

  • VS_CSHARP_DependentUpon <cs-filename>
  • VS_CSHARP_DesignTime "" (tag is removed if previously defined)
  • VS_CSHARP_AutoGen "" (tag is removed if previously defined)

  • VS_RESOURCE_GENERATOR "" (tag is removed if previously defined)
  • VS_CSHARP_DependentUpon <cs-filename>
  • VS_CSHARP_SubType "Designer"



Sets source file properties for .Designer.cs files depending on sibling filenames:

csharp_set_designer_cs_properties([<files>...])


<files>...
A list of zero or more source files which are relevant 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).

This command searches through the provided list for files ending in .Designer.cs (designer files). For each such file, it looks for sibling files with the same base name but different extensions. If a matching file is found, the appropriate source file properties are set on the corresponding .Designer.cs file based on the matched extension:

If match is .resx file:

  • VS_CSHARP_AutoGen "True"
  • VS_CSHARP_DesignTime "True"
  • VS_CSHARP_DependentUpon <resx-filename>

If match is .cs file:

VS_CSHARP_DependentUpon <cs-filename>

If match is .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 are set according to the found matches and every match sets the VS_CSHARP_DependentUpon source file property, there should only be one match for each Designer.cs file.


Sets source file properties for use of 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 which are relevant for setting the VS_CSHARP_<tagname> source file properties. This typically includes files with .cs, .xaml, and .xaml.cs extensions.

This command searches the provided file list for files ending with .xaml.cs. For each such XAML code-behind file, a corresponding .xaml file with the same base name is searched. If found, the following source file property is set on the .xaml.cs file:

VS_CSHARP_DependentUpon <xaml-filename>


Helper Commands

These commands are used by the above main commands and typically aren't used directly:

Computes a normalized list of key values to identify source files independently of relative or absolute paths given in CMake and eliminates case sensitivity:

csharp_get_filename_keys(<variable> [<files>...])


<variable>
Name of the variable in which the list of computed keys is stored.
<files>...
Zero or more source file paths as given to CSharp target using commands like add_library(), or add_executable().

This command canonicalizes file paths to ensure consistent identification of source files. This is useful when source files are added to a target using different path forms. Without normalization, CMake may treat paths like myfile.Designer.cs and ${CMAKE_CURRENT_SOURCE_DIR}/myfile.Designer.cs as different files, which can cause issues when setting source file properties.

For example, the following code will fail to set properties because the file paths do not 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 )



Returns the full filepath and name without extension of a key:

csharp_get_filename_key_base(<base> <key>)


<base>
Name of the variable with the computed base value of the <key> without the file extension.
<key>
The key of which the base will be computed. Expected to be a uppercase full filename from csharp_get_filename_keys().


Computes a string which can be used as value for the source file property VS_CSHARP_<tagname> with <tagname> being DependentUpon:

csharp_get_dependentupon_name(<variable> <file>)


<variable>
Name of the variable with the result value. Value contains the name of the <file> without directory.
<file>
Filename to convert for using in the value of the VS_CSHARP_DependentUpon source file property.


CTest

Configure a project for testing with CTest/CDash

Include this module in 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 the following variables:

BUILD_TESTING

Option selecting whether include(CTest) calls enable_testing(). The option is ON by default when created by the module.


After including the module, use code like:

if(BUILD_TESTING)

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


to creating tests when testing is enabled.

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 provide the 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).

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 does not give details about the command invocation that produced a given problem. One may get more detailed reports by setting the CTEST_USE_LAUNCHERS variable:

set(CTEST_USE_LAUNCHERS 1)


in the CTestConfig.cmake file.

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:

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:

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.
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> must be one of GZIP, BZIP2, XZ, ZSTD, FROM_EXT, or 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, and .txz.

Specify the top-level source directory for the build. Default is the value of CTEST_SOURCE_DIRECTORY.
Specify the top-level build directory for the build. Default is the value of CTEST_BINARY_DIRECTORY.
Specify the full path to the gcov command on the machine. Default is the value of CTEST_COVERAGE_COMMAND.
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.
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).

Added in version 3.6.

Delete coverage files after they've been packaged into the .tar.

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" )


CTestScriptMode

This file is read by ctest in script mode (-S)

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

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

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.


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()

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.


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.


Fixes up a Qt4 executable:

fixup_qt4_executable(

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


This command copies Qt plugins, writes a Qt configuration file (if needed) and fixes up a Qt4 executable using the BundleUtilities module so it is standalone and can be drag-and-drop copied to another machine as long as all of the system libraries are compatible.

<executable> should point to the executable to be fixed-up.

<qtplugins> should contain a list of the names or paths of any Qt plugins to be installed.

<libs> will be passed to the BundleUtilities module and should be a list of any already installed plugins, libraries or executables to also be fixed-up.

<dirs> will be passed to the BundleUtilities module and should contain directories to be searched to find library dependencies.

<plugins-dir> allows a custom plugins directory to be used.

<request-qt-conf> will force a qt.conf file to be written even if not needed.


Installs a resolved Qt4 plugin:

install_qt4_plugin_path(

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


This command installs (or copies) a resolved <plugin> to the default plugins directory (or <plugins-dir>) relative to <executable> and stores the result in a variable <installed-plugin-path-var>.

If <copy> is set to TRUE then the plugins will be copied rather than installed. This is to allow this module to be used at CMake time rather than install time.

If <component> is set then anything installed will use this COMPONENT.


Installs an unresolved Qt4 plugin:

install_qt4_plugin(

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


This command installs (or copies) an unresolved <plugin> to the default plugins directory (or <plugins-dir>) relative to <executable> and stores the result in a variable <installed-plugin-path-var>. For other arguments, see also install_qt4_plugin_path().


Installs Qt plugins, writes a Qt configuration file (if needed) and fixes up a Qt4 executable:

install_qt4_executable(

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


This command uses the BundleUtilities module so executable is standalone and can be drag-and-drop copied to another machine as long as all of the system libraries are compatible. The executable will be fixed-up at install time. The <component> is the COMPONENT used for bundle fixup and plugin installation. For other arguments, see also fixup_qt4_executable().


ExternalData

Manage data files stored outside source tree

Introduction

Use this module to unambiguously reference data files stored outside the source tree and fetch them at build time from arbitrary local and remote content-addressed locations. Functions provided by this module recognize arguments with the syntax DATA{<name>} as references to external data, replace them with full paths to local copies of those data, and create build rules to fetch and update the local copies.

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 test MyTest runs the DATA{MyInput.png} argument will be replaced by the full path to a real instance of the data file MyInput.png on disk. If the source tree contains a content link such as MyInput.png.md5 then the MyData target creates a real MyInput.png in the build tree.

Module Functions

The ExternalData_Expand_Arguments function evaluates DATA{} references in its arguments and constructs a new list of arguments:

ExternalData_Expand_Arguments(

<target> # Name of data management target
<outVar> # Output variable
[args...] # Input arguments, DATA{} allowed
)


It replaces each DATA{} reference in an argument with the full path of a real data file on disk that will exist after the <target> builds.


The ExternalData_Add_Test function wraps around the CMake add_test() command but supports DATA{} references in its arguments:

ExternalData_Add_Test(

<target> # Name of data management target
... # Arguments of add_test(), DATA{} allowed
)


It passes its arguments through ExternalData_Expand_Arguments and then invokes the add_test() command using the results.

Changed in version 3.31: If the arguments after <target> define a test with an executable that is a CMake target, empty values in the TEST_LAUNCHER and CROSSCOMPILING_EMULATOR properties of that target are preserved. See policy CMP0178.


The ExternalData_Add_Target function creates a custom target to manage local instances of data files stored externally:

ExternalData_Add_Target(

<target> # Name of data management target
[SHOW_PROGRESS <ON|OFF>] # Show progress during the download
)


It creates custom commands in the target as necessary to make data files available for each DATA{} reference previously evaluated by other functions provided by this module. Data files may be fetched from one of the URL templates specified in the ExternalData_URL_TEMPLATES variable, or may be found locally in one of the paths specified in the ExternalData_OBJECT_STORES variable.

Added in version 3.20: The SHOW_PROGRESS argument may be passed to suppress progress information during the download of objects. If not provided, it defaults to OFF for Ninja and Ninja Multi-Config generators and ON otherwise.

Typically only one target is needed to manage all external data within a project. Call this function once at the end of configuration after all data references have been processed.


Module Variables

The following variables configure behavior. They should be set before calling any of the functions provided by this module.

The ExternalData_BINARY_ROOT variable may be set to the directory to hold the real data files named by expanded DATA{} references. The default is CMAKE_BINARY_DIR. The directory layout will mirror that of content links under ExternalData_SOURCE_ROOT.

Added in version 3.2.

Specify a full path to a .cmake custom fetch script identified by <key> in entries of the ExternalData_URL_TEMPLATES list. See Custom Fetch Scripts.


Added in version 4.0.

The ExternalData_HTTPHEADERS variable may be used to supply a list of headers, each element containing one header with the form Key: Value. See the file(DOWNLOAD) command's HTTPHEADER option.


The ExternalData_LINK_CONTENT variable may be set to the name of a supported hash algorithm to enable automatic conversion of real data files referenced by the DATA{} syntax into content links. For each such <file> a content link named <file><ext> is created. The original file is renamed to the form .ExternalData_<algo>_<hash> to stage it for future transmission to one of the locations in the list of URL templates (by means outside the scope of this module). The data fetch rule created for the content link will use the staged object if it cannot be found using any URL template.

Added in version 3.3.

The real data files named by expanded DATA{} references may be made available under ExternalData_BINARY_ROOT using symbolic links on some platforms. The ExternalData_NO_SYMLINKS variable may be set to disable use of symbolic links and enable use of copies instead.


The ExternalData_OBJECT_STORES variable may be set to a list of local directories that store objects using the layout <dir>/%(algo)/%(hash). These directories will be searched first for a needed object. If the object is not available in any store then it will be fetched remotely using the URL templates and added to the first local store listed. If no stores are specified the default is a location inside the build tree.


The ExternalData_SOURCE_ROOT variable may be set to the highest source directory containing any path named by a DATA{} reference. The default is CMAKE_SOURCE_DIR. ExternalData_SOURCE_ROOT and CMAKE_SOURCE_DIR must refer to directories within a single source distribution (e.g. they come together in one tarball).

The ExternalData_TIMEOUT_ABSOLUTE variable sets the download absolute timeout, in seconds, with a default of 300 seconds. Set to 0 to disable enforcement.

The ExternalData_TIMEOUT_INACTIVITY variable sets the download inactivity timeout, in seconds, with a default of 60 seconds. Set to 0 to disable enforcement.

Added in version 3.3.

Specify a custom URL component to be substituted for URL template placeholders of the form %(algo:<key>), where <key> is a valid C identifier, when fetching an object referenced via hash algorithm <algo>. If not defined, the default URL component is just <algo> for any <key>.


The ExternalData_URL_TEMPLATES may be set to provide a list of URL templates using the placeholders %(algo) and %(hash) in each template. Data fetch rules try each URL template in order by substituting the hash algorithm name for %(algo) and the hash value for %(hash). Alternatively one may use %(algo:<key>) with ExternalData_URL_ALGO_<algo>_<key> variables to gain more flexibility in remote URLs.

Referencing Files

Referencing Single Files

The DATA{} syntax is literal and the <name> is a full or relative path within the source tree. The source tree must contain either a real data file at <name> or a "content link" at <name><ext> containing a hash of the real file using a hash algorithm corresponding to <ext>. For example, the argument DATA{img.png} may be satisfied by either a real img.png file in the current source directory or a img.png.md5 file containing its MD5 sum.

Added in version 3.8: Multiple content links of the same name with different hash algorithms are supported (e.g. img.png.sha256 and img.png.sha1) so long as they all correspond to the same real file. This allows objects to be fetched from sources indexed by different hash algorithms.

Referencing File Series

The DATA{} syntax can be told to fetch a file series using the form DATA{<name>,:}, where the : is literal. If the source tree contains a group of files or content links named like a series then a reference to one member adds rules to fetch all of them. Although all members of a series are fetched, only the file originally named by the DATA{} argument is substituted for it. The default configuration 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 <number> and <suffix> parts from the end of <name>:

ExternalData_SERIES_PARSE - regex of the form (<number>)(<suffix>)$.


For more complicated cases set:

  • 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>.

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


Note that the <suffix> of a series does not include a hash-algorithm extension.

Referencing Associated Files

The DATA{} syntax can alternatively match files associated with the named file and contained in the same directory. Associated files may be specified by options using the syntax DATA{<name>,<opt1>,<opt2>,...}. Each option may specify one file by name or specify a regular expression to match file names using the syntax REGEX:<regex>. For example, the 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 ensure that the associated files are present next to them.

Referencing Directories

The DATA{} syntax may reference a directory using a trailing slash and 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. For example, the argument DATA{MyDataDir/,REGEX:.*} will pass the full path to a MyDataDir directory on the command line and ensure that the directory contains files corresponding to every file or content link in the MyDataDir source directory.

Added in version 3.3: In order to match associated files in subdirectories, specify a RECURSE: option, e.g. DATA{MyDataDir/,RECURSE:,REGEX:.*}.

Hash Algorithms

The following hash algorithms are supported:

%(algo) <ext> Description
MD5 .md5 Message-Digest Algorithm 5, RFC 1321
SHA1 .sha1 US Secure Hash Algorithm 1, RFC 3174
SHA224 .sha224 US Secure Hash Algorithms, RFC 4634
SHA256 .sha256 US Secure Hash Algorithms, RFC 4634
SHA384 .sha384 US Secure Hash Algorithms, RFC 4634
SHA512 .sha512 US Secure Hash Algorithms, RFC 4634
SHA3_224 .sha3-224 Keccak SHA-3
SHA3_256 .sha3-256 Keccak SHA-3
SHA3_384 .sha3-384 Keccak SHA-3
SHA3_512 .sha3-512 Keccak SHA-3


Added in version 3.8: Added the SHA3_* hash algorithms.

Note that the hashes are used only for unique data identification and download verification.

Custom Fetch Scripts

Added in version 3.2.

When a data file must be fetched from one of the URL templates specified in the ExternalData_URL_TEMPLATES variable, it is normally downloaded using the file(DOWNLOAD) command. One may specify usage of a custom fetch script by using a URL template of the form ExternalDataCustomScript://<key>/<loc>. The <key> must be a C identifier, and the <loc> must contain the %(algo) and %(hash) placeholders. A variable corresponding to the key, ExternalData_CUSTOM_SCRIPT_<key>, must be set to the full path to a .cmake script file. The script will be included to perform the actual fetch, and provided with the following variables:

When a custom fetch script is loaded, this variable is set to the location part of the URL, which will contain the substituted hash algorithm name and content hash value.

When a custom fetch script is loaded, this variable is set to the full path to a file in which the script must store the fetched content. The name of the file is unspecified and should not be interpreted in any way.

The custom fetch script is expected to store fetched content in the file or set a variable:

When a custom fetch script fails to fetch the requested content, it must set this variable to a short one-line message describing the reason for failure.

ExternalProject

External Project Definition

The ExternalProject_Add() function creates a custom target to drive download, update/patch, configure, build, install and test steps of an external project:

ExternalProject_Add(<name> [<option>...])


The individual steps within the process can be driven independently if required (e.g. for CDash submission) and extra custom steps can be defined, along with the ability to control the step dependencies. The directory structure used for the management of the external project can also be customized. The function supports a large number of options which can be used to tailor the external project behavior.


Directory Options

Most of the time, the default directory layout is sufficient. It is largely an implementation detail that the main project usually doesn't need to change. In some circumstances, however, control over the directory layout can be useful or necessary. The directory options are potentially more useful from the point of view that the main build can use the ExternalProject_Get_Property() command to retrieve their values, thereby allowing the main project to refer to build artifacts of the external project.

Root directory for the external project. Unless otherwise noted below, all other directories associated with the external project will be created under here.
Directory in which to store temporary files.
Directory in which to store the timestamps of each step. Log files from individual steps are also created in here unless overridden by LOG_DIR (see Logging Options below).
Added in version 3.14.

Directory in which to store the logs of each step.

Directory in which to store downloaded files before unpacking them. This directory is only used by the URL download method, all other download methods use SOURCE_DIR directly instead.
Source directory into which downloaded contents will be unpacked, or for non-URL download methods, the directory in which the repository should be checked out, cloned, etc. If no download method is specified, this must 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, stopping with an error if it is not empty. All other download methods silently discard any previous contents of the source directory.


Specify the build directory location. This option is ignored if BUILD_IN_SOURCE is enabled.
Installation prefix to be placed in the <INSTALL_DIR> placeholder. This does not actually configure the external project to install to the given prefix. That must be done by passing appropriate arguments to the external project configuration step, e.g. using <INSTALL_DIR>.

If any of the above ..._DIR options are not specified, their defaults are computed as follows. 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.

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.

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 are 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.

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, as it ensures the integrity of the downloaded content. It is also used as a check for a previously downloaded file, allowing connection to the remote location to be avoided altogether if the local directory already has a file from an earlier download that matches the specified hash.
Equivalent to URL_HASH MD5=<md5>.
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 is not normally used outside of code internal to the ExternalProject module.
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. Therefore, unless the file timestamps are significant to the project in some way, use a false value for this option. If DOWNLOAD_EXTRACT_TIMESTAMP is not given, the default is false. See policy CMP0135.

Added in version 3.6.

Allows the extraction part of the download step to be disabled by passing a boolean true value for this option. If this option is not given, the downloaded contents will be 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.

Can be used to disable logging the download progress. If this option is not given, download progress messages will be logged.
Maximum time allowed for file download operations.
Added in version 3.19.

Terminate the operation after a period of inactivity.

Added in version 3.7.

Username for the download operation if authentication is required.

Added in version 3.7.

Password for the download operation if authentication is required.

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.

Added in version 3.30.

Specify minimum TLS version for https:// URLs. If this option is not 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.

Specifies whether certificate verification should be performed for https:// URLs. If this option is not 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, although the default behavior is different. If none of the TLS_VERIFY option, CMAKE_TLS_VERIFY variable, or CMAKE_TLS_VERIFY environment variable is specified, the behavior will be determined by git's default (true) or a http.sslVerify git config option the user may have set at a global level.

Changed in version 3.6: Previously this option did not apply to git clone invocations.

Changed in version 3.30: Previously the CMAKE_TLS_VERIFY environment variable was not checked.

Specify a custom certificate authority file to use if TLS_VERIFY is enabled. If this option is not specified, the value of the CMAKE_TLS_CAINFO variable will be used instead (see file(DOWNLOAD))
Added in version 3.11.

Specify whether the .netrc file is to be used for operation. If this option is not specified, the value of the CMAKE_NETRC variable will be used instead (see file(DOWNLOAD)). Valid levels are:

The .netrc file is ignored. This is the default.
The .netrc file is optional, and information in the URL is preferred. The file will be scanned to find which ever information is not specified in the URL.
The .netrc file is required, and information in the URL is ignored.

Added in version 3.11.

Specify an alternative .netrc file to the one in your home directory if the NETRC level is OPTIONAL or REQUIRED. If this option is not specified, the value of the CMAKE_NETRC_FILE variable will be used instead (see file(DOWNLOAD))


Added in version 3.1: Added support for tbz2, .tar.xz, .txz, and .7z extensions.

Added in version 4.1: All archive types that cmake -E tar can extract are supported regardless of file extension.

Git

NOTE: A git version of 1.6.5 or later is required if this download method is used.

URL of the git repository. Any URL understood by the git command may be used.

Changed in version 3.27: A relative URL will be resolved based on the parent project's remote, subject to CMP0150. See the policy documentation for how the remote is selected, including conditions where the remote selection can fail. Local filesystem remotes should always use absolute paths.

Git branch name, tag or commit hash. Note that branch names and tags should generally be specified as remote names (i.e. origin/myBranch rather than simply myBranch). This ensures that if the remote end has its tag moved or branch rebased or history rewritten, the local clone will still be updated correctly. In general, however, specifying a commit hash should be preferred for a number of reasons:
  • If the local clone already has the commit corresponding to the hash, no git fetch needs to be performed to check for changes each time CMake is re-run. This can result in a significant speed up if many external projects are being used.
  • 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.

If GIT_SHALLOW is enabled then GIT_TAG works only with branch names and tags. A commit hash is not allowed.

Note that if not provided, GIT_TAG defaults to master, not the default Git branch name.

The optional name of the remote. If this option is not specified, it defaults to origin.
Specific git submodules that should also be updated. If this option is not provided, all git submodules will be 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.

Added in version 3.17.

Specify whether git submodules (if any) should update recursively by passing the --recursive flag to git submodule update. If not specified, the default is on.

Added in version 3.6.

When this option is enabled, the git clone operation will be given the --depth 1 option. This performs a shallow clone, which avoids downloading the whole history and instead retrieves just the commit denoted by the GIT_TAG option.

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 will be logged until the clone operation finishes. While this option can be used to provide progress to prevent the appearance of the build having stalled, it may also make the build overly noisy if lots of external projects are used.

Added in version 3.8.

Specify a list of config options to pass to git clone. Each option listed will be transformed into its own --config <option> on the git clone command line, with each option required to be in the form key=value.

Added in version 3.18.

When GIT_TAG refers to a remote branch, this option can be used to specify how the update step behaves. The <strategy> must be one of the following:

Ignore the local branch and always checkout the branch specified by GIT_TAG.
Try to rebase the current branch to 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 stashed changes fail, 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 to 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.
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 checkout GIT_TAG just like the CHECKOUT strategy. The message stored on the annotated tag will give information about what was attempted and the tag name will include a timestamp so that each failed run will add 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 is intended for the user to set. It is 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.


Subversion

URL of the Subversion repository.
Revision to checkout from the Subversion repository.
Username for the Subversion checkout and update.
Password for the Subversion checkout and update.
Specifies whether to trust the Subversion server site certificate. If enabled, the --trust-server-cert option is passed to the svn checkout and update commands.

Mercurial

URL of the mercurial repository.
Mercurial branch name, tag or commit id.

CVS

CVSROOT of the CVS repository.
Module to checkout from the CVS repository.
Tag to checkout from the CVS repository.

Update Step Options

Whenever CMake is re-run, by default the external project's sources will be updated if the download method supports updates (e.g. a git repository would be checked if the GIT_TAG does not refer to a specific commit).

Overrides the download method's update step with a custom command. The command may use generator expressions.
Added in version 3.2.

When enabled, this option causes the update step to be skipped (but see below for changed behavior where this is not the case). It does not prevent the download step. The update step can still be added as a step target (see ExternalProject_Add_StepTargets()) and called manually. This is useful if you want to allow developers to build the project when disconnected from the network (the network may still be needed for the download step though).

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 are changed. Furthermore, if using the git download/update method, the update logic will be modified to skip attempts to contact the remote. If the GIT_TAG mentions a ref that is not known locally, the update step will halt with a fatal error.

When this option is present, it is generally advisable to make the value a cache variable under the developer's control rather than hard-coding it. If this option is not present, the default value is taken from the EP_UPDATE_DISCONNECTED directory property. If that is 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 may be a more convenient method of giving 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).

This may cause a step target to be created automatically for the download step. See policy CMP0114.


Patch Step Options

Specifies a custom command to patch the sources after an update. By default, no patch command is defined. Note that it can be quite difficult to define an appropriate patch command that performs robustly, especially for download methods such as git where changing the GIT_TAG will not discard changes from a previous patch, but the patch command will be called again after updating to the new tag.

Configure Step Options

The configure step is run after the download and update steps. By default, the external project is assumed to be a CMake project, but this can be overridden if required.

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, the CONFIGURE_COMMAND option must be used to override the default configure command (generator expressions are supported). For projects that require no configure step, specify this option with an empty string as the command to execute.

Specify an alternative cmake executable for the configure step (use an absolute path). This is generally not recommended, since it is usually desirable to use the same CMake version throughout the whole build. This option is ignored if a custom configure command has been specified with CONFIGURE_COMMAND.
Override the CMake generator used for the configure step. Without this option, the same generator as the main build will be used. This option is ignored if a custom configure command has been specified with the CONFIGURE_COMMAND option.
Added in version 3.1.

Pass a generator-specific platform name to the CMake command (see CMAKE_GENERATOR_PLATFORM). It is an error to provide this option without the CMAKE_GENERATOR option.

Pass a generator-specific toolset name to the CMake command (see CMAKE_GENERATOR_TOOLSET). It is an error to provide this option without the CMAKE_GENERATOR option.
Added in version 3.11.

Pass a generator-specific instance selection to the CMake command (see CMAKE_GENERATOR_INSTANCE). It is an error to provide this option without the CMAKE_GENERATOR option.

The specified arguments are 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).

Added in version 3.3: Arguments may use generator expressions.

This is an alternate way of specifying cache variables where command line length issues may become a problem. The arguments are expected to be in the form -Dvar:STRING=value, which are then transformed into CMake 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 command line option.

Added in version 3.3: Arguments may use generator expressions.

Added in version 3.2.

This is the same as the CMAKE_CACHE_ARGS option except the set() commands do not include the FORCE keyword. This 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, as 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.

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 can be used to point 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 will be interpreted as being relative to SOURCE_DIR.

Added in version 3.14: When BUILD_IN_SOURCE option is enabled, the BUILD_COMMAND is used to point to an alternative directory within the source tree.

Added in version 3.20.

Enabling this option relaxes the dependencies of the configure step on other external projects to order-only. This means 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. This option can be enabled 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.


Build Step Options

If the configure step assumed the external project uses CMake as its build system, the build step will also. Otherwise, the build step will assume a Makefile-based build and simply run make with no arguments as the default build step. This can be overridden with custom build commands if required.

If both the main project and the external project use make as their build tool, the build step of the external project is invoked as a recursive make using $(MAKE). This will communicate some build tool settings from the main project to the external project. If either the main project or external project is not using make, no build tool settings will be passed to the external project other than those established by the configure step (i.e. running ninja -v in the main project will not pass -v to the external project's build step, even if it also uses ninja as its build tool).

Overrides the default build command (generator expressions are supported). If this option is not given, the default build command will be chosen to integrate with the main build in the most appropriate way (e.g. using recursive make for Makefile generators or cmake --build if the project uses a CMake build). This option can be specified with an empty string as the command to make the build step do nothing.
When this option is enabled, the build will be done directly within the external project's source tree. This should generally be avoided, the use of a separate build directory is usually preferred, but it can be useful when the external project assumes an in-source build. The BINARY_DIR option should not be specified if building in-source.
Enabling this option forces the build step to always be run. This can be the easiest way to robustly ensure that the external project's own build dependencies are evaluated rather than relying on the default success timestamp-based method. This option is not normally needed unless developers are expected to modify something the external project's build depends on in a way that is not detectable via the step target dependencies (e.g. SOURCE_DIR is used without a download method and developers might modify the sources in SOURCE_DIR).
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 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.

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 details. This option is relevant only when an explicit BUILD_COMMAND is specified.


Install Step Options

If the configure step assumed the external project uses CMake as its build system, the install step will also. Otherwise, the install step will assume a Makefile-based build and simply run make install as the default build step. This can be overridden with custom install commands if required.

The external project's own install step is invoked as part of the main project's build. It is done 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, these need to be specified in the main build as additional install() commands. The default install step builds the install target of the external project, but this can be overridden with a custom command using this option (generator expressions are supported). Passing an empty string as the <cmd> makes the install step do nothing.
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.

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 the following 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 due to 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.

Note also that ExternalProject does not check whether the CMAKE_INSTALL_MODE environment variable changes from one run to another.



Test Step Options

The test step is only defined if at least one of the following TEST_... options are provided.

Overrides the default test command (generator expressions are supported). If this option is not given, the default behavior of the test step is to build the external project's own test target. This option can be specified with <cmd> as an empty string, which allows the test step to still be defined, but it will do nothing. Do not specify any of the other TEST_... options if providing an empty string as the test command, but prefer to omit all TEST_... options altogether if the test step target is not needed.
When this option is enabled, the test step will be executed before the install step. The default behavior is for the test step to run after the install step.
This option is mainly useful as a way to indicate that the test step is desired but all default behavior is sufficient. Specifying this option with 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.
Added in version 3.2.

If enabled, the main build's default ALL target will not depend on the test step. This can be a useful way of ensuring the test step is defined but only gets invoked when manually requested. This may cause a step target to be created automatically for either the install or build step. See policy CMP0114.


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 the STAMP_DIR directory with step-specific file names.

When enabled, the output of the download step is logged to files.
When enabled, the output of the update step is logged to files.
Added in version 3.14.

When enabled, the output of the patch step is logged to files.

When enabled, the output of the configure step is logged to files.
When enabled, the output of the build step is logged to files.
When enabled, the output of the install step is logged to files.
When enabled, the output of the test step is logged to files.
Added in version 3.14.

When enabled, stdout and stderr will be merged for any step whose output is being logged to files.

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. Each step can be given access to the terminal individually via the following options:

Give the download step access to the terminal.
Give the update step access to the terminal.
Added in version 3.23.

Give the patch step access to the terminal.

Give the configure step access to the terminal.
Give the build step access to the terminal.
Give the install step access to the terminal.
Give the test step access to the terminal.

Target Options

Specify other targets on which the external project depends. The 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>.
When enabled, this option excludes the external project from the default ALL target of the main build.
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.
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 prevent 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

For any of the various ..._COMMAND options, and CMAKE_ARGS, 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}" )


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

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

The ExternalProject_Add() function on its own is often sufficient for incorporating an external project into the main build. Certain scenarios require additional work to implement desired behavior, such as adding in a custom step or making steps available as manually triggerable targets. The ExternalProject_Add_Step(), ExternalProject_Add_StepTargets() and ExternalProject_Add_StepDependencies functions provide the lower level control needed to implement such step-level capabilities.

The ExternalProject_Add_Step() function specifies an additional custom step for an external project defined by an earlier call to ExternalProject_Add():

ExternalProject_Add_Step(<name> <step> [<option>...])


<name> is the same as the name passed to the original call to ExternalProject_Add(). The specified <step> must not be one of the pre-defined steps (mkdir, download, update, patch, configure, build, install or test). The supported options are:

The command line to be executed by this custom step (generator expressions are supported). This option can be repeated multiple times to specify multiple commands to be executed in order.
Text to be printed when the custom step executes.
Other steps (custom or pre-defined) on which this step depends.
Other steps (custom or pre-defined) that depend on this new custom step.
Files on which this custom step depends.
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.

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.

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 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, which has additional documentation.

When enabled, this option specifies that the custom step should always be run (i.e. that it is always considered out of date).
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.

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.
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 the CMAKE_CURRENT_BINARY_DIR at the point where ExternalProject_Add_Step() was called.
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.
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.


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. 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.

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.

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.

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 may be specified immediately after the <name> and before the first step. If the NO_DEPENDS option is specified, the step target will not depend on the dependencies of the external project (i.e. on any dependencies of the <name> custom target created by ExternalProject_Add()). This is usually safe for the download, update and patch steps, since they do not typically require that the dependencies are updated and built. Using NO_DEPENDS for any of the other pre-defined steps, however, may break parallel builds. Only use NO_DEPENDS where it is certain that the named steps genuinely do not have dependencies. For custom steps, consider whether or not the custom commands require the dependencies to be 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 specified steps.


Added in version 3.2.

The ExternalProject_Add_StepDependencies() function can be used to add dependencies to a step. The dependencies added must be targets CMake already knows about (these can be ordinary executable or library targets, custom targets or even step targets of another external project):

ExternalProject_Add_StepDependencies(<name> <step> <target1> [<target2>...])


This function takes care to set both target and file level dependencies and will ensure that parallel builds will not break. It should be used instead of add_dependencies() whenever adding a dependency for some of the step targets generated by the ExternalProject module.


Examples

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, also define a second hypothetical external project called SecretSauce, which is downloaded from a web server. Two URLs are given to 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 is only required 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. This could be enforced like so:

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. This would mean 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 many 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 that secretsauce provides a script called makedoc which can be used to generate its own documentation. Further suppose that 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

Functions for generating a summary of enabled/disabled features.

These functions can be used to generate a summary of enabled and disabled packages and/or features for a build tree such as:

-- 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

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. The type of a package 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.


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.

The default value for this global property is REQUIRED.


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 of some package, its type will be set to this value.

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.


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 not set, default string <TYPE> packages is used.


Functions

feature_summary([FILENAME <file>]

[APPEND]
[VAR <variable_name>]
[INCLUDE_QUIET_PACKAGES]
[FATAL_ON_MISSING_REQUIRED_PACKAGES]
[DESCRIPTION <description> | DEFAULT_DESCRIPTION]
[QUIET_ON_EMPTY]
WHAT (ALL
| PACKAGES_FOUND | PACKAGES_NOT_FOUND
| <TYPE>_PACKAGES_FOUND | <TYPE>_PACKAGES_NOT_FOUND
| ENABLED_FEATURES | DISABLED_FEATURES)
)


This function can be used to print information about enabled or disabled packages and features of a project. By default, only the names of the features/packages will be printed and their required version when one was specified. Use set_package_properties() to add more useful information, like e.g. a homepage URL for the respective package or their purpose in the project.

The options are:

This is the only mandatory option. It specifies what information will be printed:
Print everything.
The list of all features which are enabled.
The list of all features which are disabled.
The list of all packages which have been found.
The list of all packages which have not been found.

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> which have not been found.

Changed in version 3.1: The WHAT option is now a multi-value keyword, so that these values can be combined, with the exception of the ALL value, in order to customize the output. For example:

feature_summary(WHAT ENABLED_FEATURES DISABLED_FEATURES)


If this option is given, the information is printed into this file instead of the terminal. Relative <file> path is interpreted as being relative to the current source directory (i.e. CMAKE_CURRENT_SOURCE_DIR).
If this option is given, the output is appended to the <file> provided by the FILENAME option, otherwise the file is overwritten if it already exists.
If this option is given, the information is stored into the specified variable <variable_name> instead of the terminal.
A description or headline which will be printed above the actual content. Without this option, if only one package type was requested, no title is printed, unless a custom string is explicitly set using this option or DEFAULT_DESCRIPTION option is used that outputs a default title for the requested type.
Added in version 3.9.

The default description or headline to be printed above the content as opposed to the customizable DESCRIPTION <description>.

If this option is given, packages which have been searched with find_package(... QUIET) will also be listed. By default they are skipped.
If this option is given, CMake will abort with fatal error if a package which is marked as one of the package types listed in the FeatureSummary_REQUIRED_PKG_TYPES global property has not been found.

The FeatureSummary_DEFAULT_PKG_TYPE global property can be modified to change the default package type assigned when not explicitly assigned by the user.

Added in version 3.8.

If this option is given, when only one package type was requested, and no packages belonging to that category were found, then no output (including the DESCRIPTION) is printed nor added to the FILENAME, or the VAR variable.


Example 1, append everything to a file:

include(FeatureSummary)
feature_summary(WHAT ALL

FILENAME ${CMAKE_BINARY_DIR}/all.log APPEND)


Example 2, print the enabled features into the variable enabledFeaturesText, including the QUIET packages:

include(FeatureSummary)
feature_summary(WHAT ENABLED_FEATURES

INCLUDE_QUIET_PACKAGES
DESCRIPTION "Enabled Features:"
VAR enabledFeaturesText) message(STATUS "${enabledFeaturesText}")


Example 3, add custom package type and print only the categories that are not empty:

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)



set_package_properties(<name> PROPERTIES

[URL <url>]
[DESCRIPTION <description>]
[TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED)]
[PURPOSE <purpose>]
)


Use this function to configure and provide information about the package named <name>, which can then be displayed using the feature_summary() command. This can be performed either directly within the corresponding Find module or in the project that uses the module after invoking the find_package() call. The features for which information can be set are determined automatically after the find_package() command.

URL <url>
This should be the homepage of the package, or something similar. Ideally this is set already directly in the Find module.
A short description what that package is, at most one sentence. Ideally this is set already directly in the Find module.
What type of dependency has the using project on that package. Default is OPTIONAL. In this case it is a package which can be used by the project when available at buildtime, but it also work without. RECOMMENDED is similar to OPTIONAL, i.e. the project will build if the package is not present, but the functionality of the resulting binaries will be severely limited. If a REQUIRED package is not 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, a RUNTIME package is a package which is 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. 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), lower TYPEs are ignored. The TYPE property is project-specific, so it cannot be set by the Find module, but must be set in the project. The accepted types can be changed by setting the FeatureSummary_PKG_TYPES global property.
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 are appended to a list of purposes of the package in the project. As the TYPE property, also the PURPOSE property is project-specific, so it cannot be set by the Find module, but must be set in the project.

Example for setting the info for a package:

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")



add_feature_info(<name> <enabled> <description>)


Use this function to add information about a feature identified with a given <name>. The <enabled> contains whether this feature is enabled or not. It can be a variable or a list of conditions. <description> is a text describing the feature. The information can be displayed using feature_summary() for ENABLED_FEATURES and DISABLED_FEATURES respectively.

Changed in version 3.8: <enabled> can be a list of conditions.

Changed in version 4.0: Full Condition Syntax is now supported for <enabled>. See policy CMP0183.

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:

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" )


Example for setting feature info depending on a full condition syntax:

Unlike semicolon-separated list of conditions, this enables using entire condition syntax as being the if clause argument, such as grouping conditions with parens and similar.

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" )



Deprecated Functions

The following legacy and deprecated functions are provided for backward compatibility with previous CMake versions:

Deprecated since version 3.8.

set_package_info(<name> <description> [ <url> [<purpose>] ])


Set up information about the package <name>, which can then be displayed via feature_summary(). This can be done either directly in the Find module or in the project which uses the FeatureSummary module after the find_package() call. The features for which information can be set are added automatically by the find_package() command.

This function is deprecated. Use the set_package_properties(), and add_feature_info() functions instead.


Deprecated since version 3.8.

set_feature_info(<name> <description> [<url>])


Does the same as:

set_package_info(<name> <description> [<url>])



Deprecated since version 3.8.

print_enabled_features()


Does the same as:

feature_summary(WHAT ENABLED_FEATURES DESCRIPTION "Enabled features:")



Deprecated since version 3.8.

print_disabled_features()


Does the same as:

feature_summary(WHAT DISABLED_FEATURES DESCRIPTION "Disabled features:")



FetchContent

Added in version 3.11.

NOTE:

The Using Dependencies Guide provides a high-level introduction to this general topic. It provides 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. Whereas ExternalProject_Add() downloads at build time, the FetchContent module makes content available immediately, allowing the configure step to use the content in commands like add_subdirectory(), include() or file() operations.

Content population details should be defined separately from the command that performs the actual population. This separation ensures that all the dependency details are defined before anything might try to use them to populate content. This is particularly important in more complex project hierarchies where dependencies may be shared between multiple projects.

The following shows a typical example of declaring content details for some dependencies and then ensuring they are 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)


The FetchContent_MakeAvailable() command ensures the named dependencies have been populated, either by an earlier call, or by populating them itself. When performing the population, it will also add them to the main build, if possible, so that the main build can use the populated projects' targets, etc. See the command's documentation for how these steps are performed.

When using a 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 to be 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(

<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 will be ignored. 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 provide the defaults for their corresponding content options, just like they do for ExternalProject_Add(). Previously, these variables were ignored by the FetchContent module.

Added in version 3.24:

This option is for scenarios where the FetchContent_MakeAvailable() command may first try a call to find_package() to satisfy the dependency for <name>. By default, such a call would be simply find_package(<name>), but FIND_PACKAGE_ARGS can be used to provide additional arguments to be appended after the <name>. FIND_PACKAGE_ARGS can also be given with nothing after it, which indicates that find_package() can still be called if FETCHCONTENT_TRY_FIND_PACKAGE_MODE is set to OPT_IN, or is not set.

It would not normally be appropriate to specify REQUIRED as one of the additional arguments after FIND_PACKAGE_ARGS. Doing so would mean the find_package() call must succeed, so none of the other details specified in the FetchContent_Declare() call would get a chance to be used as a fall-back.

Everything after the FIND_PACKAGE_ARGS keyword is appended to the find_package() call, so all other <contentOptions> must come before the FIND_PACKAGE_ARGS keyword. 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 if it was not already specified. It will also be appended if FIND_PACKAGE_ARGS was not given, but FETCHCONTENT_TRY_FIND_PACKAGE_MODE was set to ALWAYS.

OVERRIDE_FIND_PACKAGE cannot be used when FIND_PACKAGE_ARGS is given.

Dependency Providers discusses another way that FetchContent_MakeAvailable() calls can be redirected. FIND_PACKAGE_ARGS is intended for project control, whereas dependency providers allow users to override project behavior.

When a FetchContent_Declare(<name> ...) call includes this option, subsequent calls to find_package(<name> ...) will ensure that FetchContent_MakeAvailable(<name>) has been called, then use the config package files in the CMAKE_FIND_PACKAGE_REDIRECTS_DIR directory (which are usually created by FetchContent_MakeAvailable()). This effectively makes FetchContent_MakeAvailable() override find_package() for the named dependency, allowing the former to satisfy the package requirements of the latter. FIND_PACKAGE_ARGS cannot be used when OVERRIDE_FIND_PACKAGE is given.

If a dependency provider has been set and the project calls find_package() for the <name> dependency, OVERRIDE_FIND_PACKAGE will not prevent the provider from seeing that call. Dependency providers always have the opportunity to intercept any direct call to find_package(), except if that call contains the BYPASS_PROVIDER option.


Added in version 3.25:

If the SYSTEM argument is provided, the SYSTEM directory property of a subdirectory added by FetchContent_MakeAvailable() will be set to true. This will affect non-imported targets created as part of that command. See the SYSTEM target property documentation for a more detailed discussion of the effects.

Added in version 3.28:

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 may be excluded from IDE project files. See the documentation for the directory property EXCLUDE_FROM_ALL for a detailed discussion of the effects.


Added in version 3.14.

FetchContent_MakeAvailable(<name1> [<name2>...])


This command ensures 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 will control how that dependency will be made available, as described below.

If <lowercaseName>_SOURCE_DIR 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 were not part of the original declared arguments, they will 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() will consider that dependency handled, skip the remaining steps below, and move 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 determines whether FetchContent_MakeAvailable() can call find_package(). 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.


If the dependency was not 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.
  • 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: Ensure the CMAKE_FIND_PACKAGE_REDIRECTS_DIR directory contains a <lowercaseName>-config.cmake and a <lowercaseName>-config-version.cmake file (or equivalently, <name>Config.cmake and <name>ConfigVersion.cmake). The directory that the CMAKE_FIND_PACKAGE_REDIRECTS_DIR variable points to is cleared at the start of every CMake run. If no config file exists after populating the dependency in the previous step, a minimal one will be written which includes any <lowercaseName>-extra.cmake or <name>Extra.cmake file with the OPTIONAL flag (so the files can be missing and won't generate a warning). Similarly, if no config version file exists, a very simple one will be written which sets PACKAGE_VERSION_COMPATIBLE and PACKAGE_VERSION_EXACT to true. This ensures all future calls to find_package() for the dependency will use the redirected config file, regardless of any version requirements. CMake cannot automatically determine an arbitrary dependency's version, so it cannot set PACKAGE_VERSION. When a dependency is 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 also sets PACKAGE_VERSION. The dependency may also write a <lowercaseName>-extra.cmake or <name>Extra.cmake file to perform custom processing, or define any variables that their normal (installed) package config file would otherwise usually define (many projects don't do any custom processing or set any variables and therefore have no need to do this). If required, the main project can write these files instead if the dependency project doesn't do so. This allows the main project to add 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, call add_subdirectory() to add it to the main build. It is not an error for there to be no CMakeLists.txt file, which allows the command to be used for dependencies that make downloaded content available at a known location, but which do not 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 provided with SOURCE_SUBDIR must be relative, and it will be treated as relative to the top directory. It can also point to a directory that does not contain a CMakeLists.txt file, or even to a directory that doesn't exist. This can be used to 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().


Projects should aim to declare the details of all dependencies they might use before they call FetchContent_MakeAvailable() for any of them. This ensures that if any of the dependencies are also sub-dependencies of one or more of the others, the main project still controls the details that will be used (because it will declare them first before the dependencies get a chance to). 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)


Note that CMAKE_VERIFY_INTERFACE_HEADER_SETS is explicitly set to false upon entry to FetchContent_MakeAvailable(), and is restored to its original value before the command returns. 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 variable provides that intuitive behavior. You can use variables like CMAKE_PROJECT_INCLUDE or CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE to turn verification back on for all or some dependencies. You can also set the VERIFY_INTERFACE_HEADER_SETS property of individual targets.


The FetchContent_Populate() command is a self-contained call which can be used to perform content population as an isolated operation. It is rarely the right command to use, projects should almost always use FetchContent_Declare() and FetchContent_MakeAvailable() instead. The main use case for FetchContent_Populate() is in CMake script 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 is interpreted differently (see below). The supported options for FetchContent_Populate() are the same as those for FetchContent_Declare(), with a few exceptions. The following 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:

The QUIET option can be given to hide the output associated with populating the specified content. If the population fails, the output will be shown regardless of whether this option was given or not so that the cause of the failure can be diagnosed. The FETCHCONTENT_QUIET variable has no effect on FetchContent_Populate() calls of this form where the content details are provided directly.

Changed in version 3.30: The QUIET option and 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).

The SUBBUILD_DIR argument can be provided to change the location of the sub-build created to perform the population. The default value is ${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild, and it would be unusual to need to override this default. If a relative path is specified, it will be interpreted as relative to CMAKE_CURRENT_BINARY_DIR. This option should not be confused with the SOURCE_SUBDIR option, which 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.

The SOURCE_DIR and BINARY_DIR arguments are supported by ExternalProject_Add(), but different default values are used by FetchContent_Populate(). SOURCE_DIR defaults to ${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src, and BINARY_DIR defaults to ${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build. If a relative path is specified, it will be interpreted as relative to CMAKE_CURRENT_BINARY_DIR.

In addition to the above explicit options, any other unrecognized options are passed through unmodified to ExternalProject_Add() to set up the download, patch, and update steps. The following options are explicitly prohibited (they are disabled by the FetchContent_Populate() command):

  • CONFIGURE_COMMAND
  • BUILD_COMMAND
  • INSTALL_COMMAND
  • TEST_COMMAND

With this form, the FETCHCONTENT_FULLY_DISCONNECTED and FETCHCONTENT_UPDATES_DISCONNECTED variables and policy CMP0170 are ignored.

When this form of FetchContent_Populate() returns, the following variables will be set in the scope of the caller:

<lowercaseName>_SOURCE_DIR
The location where the populated content can be found upon return.
<lowercaseName>_BINARY_DIR
A directory originally intended for use as a corresponding build directory, but is unlikely to be relevant when using this form of the command.

If using FetchContent_Populate() within CMake script mode, be aware that the implementation sets up a sub-build which therefore requires a CMake generator and build tool to be available. If these cannot be found by default, then the CMAKE_GENERATOR and potentially the CMAKE_MAKE_PROGRAM variables will need to be set appropriately on the command line invoking the script.

Changed in version 3.30: If policy CMP0168 is set to NEW, no sub-build is used. Within CMake script mode, that allows FetchContent_Populate() to be called without any build tool or CMake generator.

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 provides backward compatibility for projects that still need to use this form, but projects should be updated to use FetchContent_MakeAvailable() instead.

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(). The details are stored in a global property, so they are unaffected by things like variable or directory scope. 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() (see policy CMP0168 for important behavioral aspects of how that is 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.
<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 the three variables can also be retrieved from anywhere in the project hierarchy using the FetchContent_GetProperties() command.

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. 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.



When 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. 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.

This command is rarely needed when using FetchContent_MakeAvailable(). It is 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()



Added in version 3.24.

NOTE:

This command should only be called by dependency providers. Calling it in any other context is unsupported and future CMake versions may halt with a fatal error in such cases.


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. 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.


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.


In most cases, the saved details do not specify any options relating to the directories to use for the internal sub-build, final source, and build areas. It is generally best to leave these decisions up to the FetchContent module to handle on the project's behalf. 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.

The logging output during population can be quite verbose, making the configure stage quite noisy. This cache option (ON by default) hides all population output unless an error is encountered. If 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 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).


When this option is enabled, no attempt is made to download or update any content. It is 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. 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 and populate the dependency from local content instead.


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.


This is a less severe download/update control compared to FETCHCONTENT_FULLY_DISCONNECTED. Instead of bypassing all download and update logic, FETCHCONTENT_UPDATES_DISCONNECTED only prevents the update step from making connections to remote servers when using the git or hg download methods. Updates still occur if details about the update step change, but the update is attempted with only the information already available locally (so switching to a different tag or commit that is already fetched locally will succeed, but switching to an unknown commit hash will fail). The download step is not affected, so if content has not been downloaded previously, 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. FETCHCONTENT_UPDATES_DISCONNECTED is OFF by default.

Added in version 3.24.

This variable modifies the details that FetchContent_Declare() records for a given dependency. While it ultimately controls the behavior of FetchContent_MakeAvailable(), it is 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 will 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 the following values:

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.
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.
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 is 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:

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, as changes to sources in the default location can be lost when content population details are changed by the project.

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 will 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:

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. 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.

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 is 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

If the sub-project's CMakeLists.txt file is not at the top level of its source tree, the SOURCE_SUBDIR option can be used to tell FetchContent where to find it. The following example shows how to use that option, and it also sets a variable which is meaningful to the subproject before pulling it into the main build (set as an INTERNAL cache variable to avoid problems with policy CMP0077):

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 be more complicated. 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. 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:

  • 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, 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 is not used until the 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. 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 functions intended to be used in Find Modules implementing find_package(<PackageName>) calls.

This command handles the REQUIRED, QUIET and version-related arguments of find_package(). It also sets the <PackageName>_FOUND variable. The package is considered found if all variables listed contain valid results, e.g. valid filepaths.

There are two signatures:

find_package_handle_standard_args(<PackageName>

(DEFAULT_MSG|<custom-failure-message>)
<required-var>...
) find_package_handle_standard_args(<PackageName>
[FOUND_VAR <result-var>]
[REQUIRED_VARS <required-var>...]
[VERSION_VAR <version-var>]
[HANDLE_VERSION_RANGE]
[HANDLE_COMPONENTS]
[CONFIG_MODE]
[NAME_MISMATCHED]
[REASON_FAILURE_MESSAGE <reason-failure-message>]
[FAIL_MESSAGE <custom-failure-message>]
)


The <PackageName>_FOUND variable will be set to TRUE if all the variables <required-var>... are valid 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() call.

The options are:

(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.
Deprecated since version 3.3.

Specifies either <PackageName>_FOUND or <PACKAGENAME>_FOUND as the result variable. This exists only for compatibility with older versions of CMake and is now ignored. Result variables of both names are now always set for compatibility also with or without this option.

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.

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() 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.
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.

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()) are missing.
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.
Added in version 3.16.

Specify a custom message of the reason for the failure which will be appended to the default generated message.

Specify a custom failure message instead of using the default generated message. Not recommended.
Added in version 3.17.

Indicate that the <PackageName> does not match ${CMAKE_FIND_PACKAGE_NAME}. This is usually a mistake and raises a warning, but it may be intentional for usage of the command for components of a larger package.



Example for the simple signature:

find_package_handle_standard_args(LibXml2 DEFAULT_MSG

LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)


The LibXml2 package is considered to be found if both LIBXML2_LIBRARY and LIBXML2_INCLUDE_DIR are valid. Then also LibXml2_FOUND is set to TRUE. If it is not found and REQUIRED was used, it fails with a message(FATAL_ERROR), independent whether QUIET was used or not. If it is found, success will be reported, including the content of the first <required-var>. On repeated CMake runs, the same message will not be printed again.

NOTE:

If <PackageName> does not match CMAKE_FIND_PACKAGE_NAME for the calling module, a warning that there is a mismatch is given. The FPHSA_NAME_MISMATCHED variable may be set to bypass the warning if using the old signature and the NAME_MISMATCHED argument using the new signature. To avoid forcing the caller to require newer versions of CMake for usage, the variable's value will be used if defined when the NAME_MISMATCHED argument is not passed for the new signature (but using both is an error)..


Example for the full signature:

find_package_handle_standard_args(LibArchive

REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR
VERSION_VAR LibArchive_VERSION)


In this case, the LibArchive package is considered to be found if both LibArchive_LIBRARY and LibArchive_INCLUDE_DIR are valid. Also the version of LibArchive will be checked by using the version contained in LibArchive_VERSION. Since no FAIL_MESSAGE is given, the default messages will be printed.

Another example for the full signature:

find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4)
find_package_handle_standard_args(Automoc4  CONFIG_MODE)


In this case, a FindAutmoc4.cmake module wraps a call to find_package(Automoc4 NO_MODULE) and adds an additional search directory for automoc4. Then the call to find_package_handle_standard_args produces a proper success/failure message.

Added in version 3.19.

Helper function which can be used to check if a <version> is valid against version-related arguments of find_package().

find_package_check_version(<version> <result-var>

[HANDLE_VERSION_RANGE]
[RESULT_MESSAGE_VARIABLE <message-var>]
)


The <result-var> will hold a boolean value giving the result of the check.

The options are:

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.
Specify a variable to get back a message describing the result of the check.


Example for the usage:

find_package_check_version(1.2.3 result HANDLE_VERSION_RANGE

RESULT_MESSAGE_VARIABLE reason) if(result)
message(STATUS "${reason}") else()
message(FATAL_ERROR "${reason}") endif()


FindPackageMessage

This module provides a command for printing find result messages and is intended for use in Find Modules.

Load it in a CMake find module with:

include(FindPackageMessage)


Commands

This module provides the following command:

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 <details> string changes in a subsequent configuration phase, the message will be displayed again.

If find_package() was called with the QUIET option, the <message> is not printed.


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:

FindFoo.cmake

# ...
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(

Foo
REQUIRED_VARS Foo_LIBRARY Foo_INCLUDE_DIR )


FortranCInterface

Fortran/C Interface Detection

This module automatically detects the API by which C and Fortran languages interact.

Module Variables

Variables that indicate if the mangling is found:

Global subroutines and functions.
Module subroutines and functions (declared by "MODULE PROCEDURE").

This module also provides the following variables to specify the detected mangling, though a typical use case does not need to reference them and can use the Module Functions below.

Prefix for a global symbol without an underscore.
Suffix for a global symbol without an underscore.
The case for a global symbol without an underscore, either UPPER or LOWER.
Prefix for a global symbol with an underscore.
Suffix for a global symbol with an underscore.
The case for a global symbol with an underscore, either UPPER or LOWER.
Prefix for a module symbol without an underscore.
Middle of a module symbol without an underscore that appears between the name of the module and the name of the symbol.
Suffix for a module symbol without an underscore.
The case for a module symbol without an underscore, either UPPER or LOWER.
Added in version 4.1.

Order of components for module symbols without an underscore:

The module name appears before the symbol name, i.e., <PREFIX><module><MIDDLE><symbol><SUFFIX>.
The module name appears after the symbol name, i.e., <PREFIX><symbol><MIDDLE><module><SUFFIX>.

Prefix for a module symbol with an underscore.
Middle of a module symbol with an underscore that appears between the name of the module and the name of the symbol.
Suffix for a module symbol with an underscore.
The case for a module symbol with an underscore, either UPPER or LOWER.
Added in version 4.1.

Order of components for module symbols with an underscore:

The module name appears before the symbol name, i.e., <PREFIX><module><MIDDLE><symbol><SUFFIX>.
The module name appears after the symbol name, i.e., <PREFIX><symbol><MIDDLE><module><SUFFIX>.


Module Functions

The FortranCInterface_HEADER function is provided to generate a C header file containing macros to mangle symbol names:

FortranCInterface_HEADER(<file>

[MACRO_NAMESPACE <macro-ns>]
[SYMBOL_NAMESPACE <ns>]
[SYMBOLS [<module>:]<function> ...])


It generates in <file> definitions of the following 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 mangling for a category is not known, its macro is left undefined. All macros require raw names in both lower case and upper case.

The options are:

Replace the default FortranCInterface_ prefix with a given namespace <macro-ns>.
List symbols to mangle automatically with C preprocessor definitions:

<function>          ==> #define <ns><function> ...
<module>:<function> ==> #define <ns><module>_<function> ...


If the mangling for some symbol is not known then no preprocessor definition is created, and a warning is displayed.

Prefix all preprocessor definitions generated by the SYMBOLS option with a given namespace <ns>.


The FortranCInterface_VERIFY function is provided to verify that the Fortran and C/C++ compilers work together:

FortranCInterface_VERIFY([CXX] [QUIET])


It tests whether a simple test executable using Fortran and C (and C++ when the CXX option is given) compiles and links successfully. The result is stored 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 function terminates with a fatal error message describing the problem. The purpose of this check is to stop a build early for incompatible compiler combinations. The test is built in the Release configuration.


Example Usage

include(FortranCInterface)
FortranCInterface_HEADER(FC.h MACRO_NAMESPACE "FC_")


This creates a "FC.h" header that defines mangling macros FC_GLOBAL(), FC_GLOBAL_(), FC_MODULE(), and FC_MODULE_().

include(FortranCInterface)
FortranCInterface_HEADER(FCMangle.h

MACRO_NAMESPACE "FC_"
SYMBOL_NAMESPACE "FC_"
SYMBOLS mysub mymod:my_sub)


This creates a "FCMangle.h" header that defines the same FC_*() mangling macros as the previous example plus preprocessor symbols FC_mysub and FC_mymod_my_sub.

Additional Manglings

FortranCInterface is aware of possible GLOBAL and MODULE manglings for many Fortran compilers, but it also provides an interface to specify new possible manglings. Set the variables:

FortranCInterface_GLOBAL_SYMBOLS
FortranCInterface_MODULE_SYMBOLS


before including FortranCInterface to specify manglings of the symbols MySub, My_Sub, MyModule:MySub, and My_Module:My_Sub. For example, the code:

set(FortranCInterface_GLOBAL_SYMBOLS mysub_ my_sub__ MYSUB_)

# ^^^^^ ^^^^^^ ^^^^^ set(FortranCInterface_MODULE_SYMBOLS
__mymodule_MOD_mysub __my_module_MOD_my_sub)
# ^^^^^^^^ ^^^^^ ^^^^^^^^^ ^^^^^^ include(FortranCInterface)


tells FortranCInterface to try given GLOBAL and MODULE manglings. (The carets point at raw symbol names for clarity in this example but are not needed.)

GenerateExportHeader

This module provides commands for generating a header file containing preprocessor macro definitions to control C/C++ symbol visibility.

Load this module in 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.

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.

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 related convenience variables CMAKE_<LANG>_VISIBILITY_PRESET and CMAKE_VISIBILITY_INLINES_HIDDEN to enable it for all targets in 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

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


If specified, it overrides the default file name and macro names.
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).
If specified, it overrides the default macro name for the export directive.
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.
If specified, the following names will be used:
  • <deprecated-macro-name> (macro for marking deprecated symbols)
  • <deprecated-macro-name>_EXPORT (macro for deprecated symbols with export markers)
  • <deprecated-macro-name>_NO_EXPORT (macro for deprecated symbols with no-export markers)

instead of the default names in format of <MACRO>_DEPRECATED{,_EXPORT,_NO_EXPORT}.

If specified, this will define a macro named <MACRO>_NO_DEPRECATED.
Used in combination with DEFINE_NO_DEPRECATED option. If specified, then a macro named <no-deprecated-macro-name> is used instead of the default <MACRO>_NO_DEPRECATED.
If specified, the <static-define> macro name will be used instead of the default <MACRO>_STATIC_DEFINE. This macro controls the symbol export behavior in the generated header for static libraries. It is typically used when building both shared and static variants of a library from the same sources using a single generated export header. When this macro is defined for static library, the export-related macros will expand to nothing. This is important also on Windows, where symbol decoration is required only for shared libraries, not for static ones.
If specified, the additional <prefix> is prepended to all generated macro names.
Added in version 3.7.

If specified, the content from the <variable> value is appended to the generated header file content after the preprocessor macros definitions.

Added in version 3.11.

If specified, the <include-guard-name> is used as the preprocessor macro name to guard multiple inclusions of the generated header instead of the default name <export-macro-name>_H.

<base-name-lowercase>_export.h

#ifndef <include-guard-name>
#define <include-guard-name>
// ...
#endif /* <include-guard-name> */




Deprecated Command

Deprecated since version 3.0: Set the target properties CXX_VISIBILITY_PRESET and VISIBILITY_INLINES_HIDDEN instead.

Adds C++ compiler options -fvisibility=hidden (and -fvisibility-inlines-hidden, if supported) to hide all symbols by default to either CMAKE_CXX_FLAGS variable or to a specified variable:

add_compiler_export_flags([<output_variable>])


This command is a no-op on Windows which does not need extra compiler flags for exporting support.

<output-variable>
Optional variable name that will be populated with a string of space-separated C++ compile options required to enable visibility support for the compiler/architecture in use. If this argument is specified, the CMAKE_CXX_FLAGS variable will not be modified.


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 is installed along with the library's other public headers:

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 $<TARGET_PROPERTY:example,BINARY_DIR>
FILES ${CMAKE_CURRENT_BINARY_DIR}/example_export.h ) target_include_directories(example PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) 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.

add_library(example example.cxx)
include(GenerateExportHeader)
generate_export_header(example BASE_NAME "other_name")


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 other macros and the generated header file name are set to their default values:

add_library(example example.cxx)
include(GenerateExportHeader)
generate_export_header(example EXPORT_MACRO_NAME "OTHER_NAME_EXPORT")


The following example creates KDE_DEPRECATED macro instead of 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:

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.

include(GenerateExportHeader)
generate_export_header(somelib PREFIX_NAME "VTK_")


Appending additional content to 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 ensure the same generated export header works for both:

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, add_compiler_export_flags() command was used to add symbol visibility compile options:

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:

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 to customize 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 is used by another project (e.g., after installation).
  • 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 and provides a command to compute installation-related absolute paths.

Load this module in a CMake project with:

include(GNUInstallDirs)


Result Variables

Inclusion of this module defines the following variables:

Destination for files of a given type. This value may be passed to the DESTINATION options of install() commands for the corresponding file type. It should be a path relative to the installation prefix so that it can be converted to an absolute path in a relocatable way. However, there are some special cases as documented below.

While absolute paths are allowed, they are not recommended as they do not work with the cmake --install command's --prefix option, or with the cpack installer generators. In particular, there is no need to make paths absolute by prepending CMAKE_INSTALL_PREFIX; this prefix is used by default if the DESTINATION is a relative path.

The absolute path generated from the corresponding CMAKE_INSTALL_<dir> value. If the value is not already an absolute path, an absolute path is constructed typically by prepending the value of the CMAKE_INSTALL_PREFIX variable, except in special cases as documented below.

These variables shouldn't be used in install() commands as they do not work with the cmake --install command's --prefix option, or with the cpack installer generators.


where <dir> is one of:

user executables (bin)
system admin executables (sbin)
program executables (libexec)
read-only single-machine data (etc)

Changed in version 4.1: If the CMAKE_INSTALL_PREFIX falls into the special cases, the default paths for are the absolute path variants as described there. See policy CMP0192.

modifiable architecture-independent data (com)
modifiable single-machine data (var)

Changed in version 4.1: If the CMAKE_INSTALL_PREFIX falls into the special cases, the default paths for are the absolute path variants as described there. See policy CMP0192.

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 for are the absolute path variants as described there. See policy CMP0192.

object code libraries (lib or lib64)

On Debian, this may be lib/<multiarch-tuple> when CMAKE_INSTALL_PREFIX is /usr.

C header files (include)
C header files for non-gcc (/usr/include)
read-only architecture-independent data root (share)
read-only architecture-independent data (DATAROOTDIR)
info documentation (DATAROOTDIR/info)
locale-dependent data (DATAROOTDIR/locale)
man documentation (DATAROOTDIR/man)
documentation root (DATAROOTDIR/doc/PROJECT_NAME)

If the includer does not define a value the above-shown default will be used and the value will appear in the cache for editing by the user.

If a default value for the CMAKE_INSTALL_<dir> is used and the CMAKE_INSTALL_PREFIX is changed, the new default value will be used calculated on the new CMAKE_INSTALL_PREFIX value. Using --prefix in cmake --install will not alter these values.

Special Cases

Added in version 3.4.

The following values of CMAKE_INSTALL_PREFIX are special:

/

For <dir> other than the SYSCONFDIR, LOCALSTATEDIR and RUNSTATEDIR, the value of CMAKE_INSTALL_<dir> is prefixed with usr/ if it is not user-specified as an absolute path. For example, the INCLUDEDIR value include becomes usr/include. This is required by the GNU Coding Standards, 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 is not already an absolute path. For example, the SYSCONFDIR value etc becomes /etc. This is required by the GNU Coding Standards.

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 is not already an absolute path. For example, the SYSCONFDIR value etc becomes /etc/opt/.... This is defined by the Filesystem Hierarchy Standard.

This behavior does not apply to paths under /opt/homebrew/....

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.



Commands

This module provides the following command:

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 GNU standard installation directories. If the input path is relative, it is 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 is also exposed publicly for users to create additional custom installation path variables and compute absolute paths where necessary, using the same logic.


See Also

The install() command.

GoogleTest

Added in version 3.9.

This module defines functions to help use the Google Test infrastructure. 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 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 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.

More details can be found in the documentation of the respective functions.

Both commands are intended to replace use of add_test() to register tests, and will create a separate CTest test for each Google Test test case. Note that this is in some cases less efficient, as common set-up and tear-down logic cannot be shared by multiple test cases executing in the same instance. However, it provides more fine-grained pass/fail information to CTest, which is usually considered as more beneficial. 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.

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 attempts to identify tests by scanning source files. Although this is generally effective, it uses only a basic regular expression match, which can be defeated by atypical test declarations, and is 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, this means that CMake is re-run when any test source file is changed, but see SKIP_DEPENDENCY). However, it has the advantage of declaring tests at CMake time, which somewhat simplifies setting additional properties on tests, and always works in a cross-compiling environment.

The options are:

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.
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.
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.

Specifies the directory in which to run the discovered test cases. If this option is not provided, the current binary directory is used.
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.
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.
Normally, the function creates a dependency which will cause CMake to be re-run if any of the sources being scanned are changed. This is to ensure that the list of discovered tests is updated. If this behavior is not desired (as may be the case while actually writing the test cases), this option can be used to prevent the dependency from being added.
The variable named by outVar will be populated in the calling scope with the list of discovered test cases. This allows the caller to 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:

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...)


The path to the test executable or the name of a CMake target.
A ;-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.
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)



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 ensures that the full list of tests, including instantiations of parameterized tests, is obtained. Since test discovery occurs at build or test time, it is not necessary to re-run CMake when the list of tests changes. However, it requires that CROSSCOMPILING_EMULATOR is properly set in order to function in a cross-compiling environment.

Additionally, 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 more fine-grained test control is needed, 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:

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.
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.

Specifies the directory in which to run the discovered test cases. If this option is not provided, the current binary directory is used.
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.
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.
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.

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 this behavior.
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 this behavior.
Specifies additional properties to be set on all tests discovered by this invocation of gtest_discover_tests().
Make the list of tests available in the variable var, rather than the default <target>_TESTS. This can be useful when the same test executable is being used in multiple calls to gtest_discover_tests(). Note that this variable is only available in CTest.

Due to a limitation of CMake's parsing rules, any test with a square bracket in its name will be omitted from the list of tests stored in this variable. Such tests will still be defined and executed by ctest as normal though.

Added in version 3.10.3.

Specifies how long (in seconds) CMake will wait for the test to enumerate available tests. If the test takes longer than this, discovery (and your build) will fail. Most test executables will enumerate their tests very quickly, but under some exceptional circumstances, a test may require a longer timeout. The default is 5. See also the TIMEOUT option of execute_process().

NOTE:

In CMake versions 3.10.1 and 3.10.2, this option was called TIMEOUT. This 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. The keyword was changed to DISCOVERY_TIMEOUT in CMake 3.10.3 to address this problem. The ambiguous behavior of the TIMEOUT keyword in 3.10.1 and 3.10.2 has not been preserved.


Added in version 3.18.

If specified, the parameter is passed along with --gtest_output=xml: to test executable. The actual file name is the same as the test target, including prefix and suffix. This should be used instead of EXTRA_ARGS --gtest_output=xml to avoid race conditions writing the XML result output when using parallel test execution.

Added in version 3.18.

Provides greater control over when gtest_discover_tests() performs test discovery. By default, POST_BUILD sets up a post-build command to perform test discovery at build time. In certain scenarios, like cross-compiling, this POST_BUILD behavior is not desirable. By contrast, PRE_TEST delays test discovery until just prior to test execution. This way test discovery occurs 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 is not passed when calling gtest_discover_tests(). This provides a mechanism for globally selecting a preferred test discovery behavior without having to modify each call site.

Added in version 3.31.

Any extra arguments to pass on the command line for the discovery command.


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

Include this module to search for compiler-provided system runtime libraries and add install rules for them. Some optional variables may be set prior to including the module to adjust behavior:

Specify additional runtime libraries that may not be detected. After inclusion any detected libraries will be appended to this.
Set to TRUE to skip calling the install(PROGRAMS) command to allow the includer to specify its own install rule, using the value of CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS to get the list of libraries.
Set to TRUE to install the debug runtime libraries when available with MSVC tools.
Set to TRUE to install only the debug runtime libraries with MSVC tools even if the release runtime libraries are also available.
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: One 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.

Set to TRUE to install the MSVC MFC runtime libraries.
Set to TRUE to install the MSVC OpenMP runtime libraries
Specify the install(PROGRAMS) command DESTINATION option. If not specified, the default is bin on Windows and lib elsewhere.
Set to TRUE to disable warnings about required library files that do not exist. (For example, Visual Studio Express editions may not provide the redistributable files.)
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.

ProcessorCount

This module provides a command to determine the number of processors/cores.

Load this module in CMake with:

include(ProcessorCount)


Commands

This module provides the following command:

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 cannot be determined, it is set to 0.

Currently, this functionality is implemented for AIX, Cygwin, FreeBSD, Haiku, HPUX, Linux, macOS, QNX, Sun and Windows.

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 is 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.

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 be also obtained with the 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 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()


SelectLibraryConfigurations

This module is intended for use in Find Modules and provides a command to automatically set library variables when package is available with multiple Build Configurations.

Load it in a CMake find module with:

include(SelectLibraryConfigurations)


Supported build configurations are Release and Debug as these are the most common ones in such packages.

NOTE:

This module has been available since early versions of CMake, 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.


Commands

This module provides the following command:

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 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 storing the full path to the Release build of the library. If not set or found, this command will set its value to <basename>_LIBRARY_RELEASE-NOTFOUND.
<basename>_LIBRARY_DEBUG
A cache variable storing the full path to the Debug build of the library. If not set or found, this command will set its value to <basename>_LIBRARY_DEBUG-NOTFOUND.

This command then sets the following local result variables:

<basename>_LIBRARY
A result variable that is set to the value of <basename>_LIBRARY_RELEASE variable if found, otherwise it is set to the value of <basename>_LIBRARY_DEBUG variable if found. If both are found, the release library value takes precedence. If both are not found, it is set to value <basename>_LIBRARY-NOTFOUND.

If the CMake Generator in use supports build configurations, then this variable will be a list of found libraries each prepended with the optimized or debug keywords specifying which library should be linked for the given configuration. These keywords are used by the target_link_libraries() command. If a build configuration has not been set or the generator in use does not support build configurations, then this variable value will not contain these keywords.

<basename>_LIBRARIES
A result variable that is set to the same value as the <basename>_LIBRARY variable.

NOTE:

The select_library_configurations() command should be called before handling standard find module arguments with find_package_handle_standard_args() to ensure that the <PackageName>_FOUND result variable is correctly set based on <basename>_LIBRARY or other related variables.



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 ... )


When 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 as follows:

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)


In early C++ (pre-C++98), variables declared in for(<init-statement> ...) could remain accessible outside the loop after its body (for() { <body> }).

This module defines the following cache variable:

A cache variable containing the result of the check. It will be set to value 0 if the for-init-statement has restricted scope (C++ 98 and newer), and to value 1 if not (ANSI C++).

NOTE:

As of the C++ 98 standard, variables declared in a for-init-statement are restricted to the loop body, making this behavior obsolete.


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 (e.g. <iostream>).

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.

This module defines the following cache variable:

A cache variable containing the result of the check. It will be set to value 0 if the standard headers can be included without the .h extension (C++ 98 and newer), and to value 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.


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" )


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 functions correctly.

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.

This module defines the following cache variables:

A cache variable indicating whether the <sstream> header is available. It will be set to value 0 if <sstream> is available (C++ 98 and newer), and to value 1 if <sstream> is missing (ANSI C++).
A cache variable that is the opposite of CMAKE_NO_ANSI_STRING_STREAM (true if <sstream> is available and false if <sstream> is missing).

NOTE:

The <sstream> header was formally introduced in the C++ 98 standard, making this check obsolete for modern compilers.


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 of 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 available globally.

This module defines the following cache variable:

A cache variable containing the result of the check. It will be set to value 0 if the std namespace is supported (C++ 98 and newer), and to value 1 if not (ANSI C++).

NOTE:

The std namespace got formally introduced in C++ 98 standard, making this issue obsolete.


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 this module in CMake project with:

include(UseEcos)


Commands

This module provides the following commands:

Building an eCos Application

Adds the eCos include directories for the current CMakeLists.txt file:

ecos_add_include_directories()



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.


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().

This command also sets the ECOS_DEFINITIONS local variable, holding some common compile definitions.


Selecting the Toolchain

Enables the ARM ELF toolchain for the directory where it is called:

ecos_use_arm_elf_tools()


Use this command, when compiling for the xscale processor.


Enables the i386 ELF toolchain for the directory where it is called:

ecos_use_i386_elf_tools()



Enables the PowerPC toolchain for the directory where it is called:

ecos_use_ppc_eabi_tools()



Variables

This module also defines the following variables:

Cache variable that contains a path to the ecosconfig executable (the eCos configuration program).
A local variable that defaults to ecos.ecc. If eCos configuration file has a different name, adjust this variable before calling the ecos_add_executable().

Examples

The following example demonstrates 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 is assumed that FindJava has already been loaded. See FindJava for information on how to load Java into your CMake project.

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

Creates a jar file containing java objects and, optionally, resources:

add_jar(<target_name>

[SOURCES] <source1> [<source2>...] [<resource1>...]
[RESOURCES NAMESPACE <ns1> <resource1>... [NAMESPACE <nsX> <resourceX>...]... ]
[INCLUDE_JARS <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 given <source> files and adds the given <resource> files to the jar file. Source files can be java files or listing files (prefixed by @). If only resource files are given then just a jar file is created.

Compiles the specified source files and adds the result in the jar file.

Added in version 3.4: Support for response files, prefixed by @.

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.

For example:

RESOURCES NAMESPACE "/com/my/namespace" "a/path/to/resource.txt"


results in a resource accessible via /com/my/namespace/resource.txt within the jar.

Resources may be added without adjusting the namespace by adding them to the list of SOURCES (original behavior), in this 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.

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.


The list of jars are 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 first version of this module).
Defines an entry point in the jar file.
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)


Defines a custom manifest for the jar.
Specify a different output name for the target.
Sets the directory where the jar file will be generated. If not specified, CMAKE_CURRENT_BINARY_DIR is used as the output directory.
Added in version 3.11.

Generates native header files for methods declared as native. These files provide the connective glue that allow your Java and C code to interact. An INTERFACE target will be created for an easy usage of generated files. 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 an optimum usage of this option, it is 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: DESTINATION sub-option now supports the possibility to specify different output directories for BUILD and INSTALL steps. If BUILD directory is not specified, a default directory will be used.

To export the interface target generated by GENERATE_NATIVE_HEADERS option, 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:

Specify additional flags to java compiler.
Specify additional paths to the class path.
If the target is a JNI library, sets this boolean variable to TRUE to enable creation of a JNI symbolic link (see also install_jni_symlink()).
If multiple jars should be produced from the same java source filetree, to prevent the accumulation of duplicate class files in subsequent jars, set/reset CMAKE_JAR_CLASSES_PREFIX prior to calling the add_jar():

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>:

The files which should be installed. This is used by install_jar().
The JNI symlink which should be installed. This is used by install_jni_symlink().
The location of the jar file so that you can include it.
The directory where the class files can be found. For example to use them with javah.
Added in version 3.20.

The directory where native headers are generated. Defined when option GENERATE_NATIVE_HEADERS is specified.



This command installs the jar file to the given destination:

install_jar(<target_name> <destination>)
install_jar(<target_name> DESTINATION <destination> [COMPONENT <component>])


This command installs the <target_name> file to the given <destination>. It should be called in the same scope as add_jar() or it will fail.

Added in version 3.4: The second signature with DESTINATION and COMPONENT options.

Specify the directory on disk to which a file will be installed.
Specify an installation component name with which the install rule is associated, such as "runtime" or "development".

The install_jar() command sets the following target properties on <target_name>:

Holds the <destination> as described above, and is used by install_jar_exports().


Installs JNI symlinks for 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>. It should be called in the same scope as add_jar() or it will fail.

Added in version 3.4: The second signature with DESTINATION and COMPONENT options.

Specify the directory on disk to which a file will be installed.
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

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 due to the suppression of javah tool. The add_jar(GENERATE_NATIVE_HEADERS) command should be used instead.

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 signature returns generated files through 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 same options.

Specifies Java classes used to generate headers.
Specifies various paths to look up classes. Here .class files, jar files or targets created by command add_jar can be used.
Targets on which the javah target depends.
Concatenates the resulting header files for all the classes listed by option CLASSES into <path>. Same behavior as option -o of javah tool.
Sets the directory where the header files will be generated. Same behavior as option -d of javah tool. If not specified, CMAKE_CURRENT_BINARY_DIR is used as the output directory.


Exporting JAR Targets

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).

List of targets created by add_jar() command.
Added in version 3.9.

The <namespace> value will be prepend to the target names as they are written to the import file.

Specify name of the export file.
Specify the directory on disk to which a file will be installed.
Specify an installation component name with which the install rule is associated, such as "runtime" or "development".


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().

List of targets created by add_jar() command.
Added in version 3.9.

The <namespace> value will be prepend to the target names as they are written to the import file.

Specify name of the export file.


Finding JARs

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 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.

Specify one or more possible names for the jar file.
Specify directories to search in addition to the default locations. The ENV var sub-option reads paths from a system environment variable.
Specify jar versions.
Specify the documentation string for the <VAR> cache entry.


Creating Java Documentation

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.

Specify java packages.
Specify java source files. If relative paths are specified, they are relative to CMAKE_CURRENT_SOURCE_DIR.
Specify the directory where to look for packages. By default, CMAKE_CURRENT_SOURCE_DIR directory is used.
Specify where to find user class files. Same behavior as option -classpath of javadoc tool.
Specify where to install the java documentation. If you specified, the documentation will be installed to ${CMAKE_INSTALL_PREFIX}/share/javadoc/<VAR>.
Specify the title to place near the top of the overview summary file. Same behavior as option -doctitle of javadoc tool.
Specify the title to be placed in the HTML <title> tag. Same behavior as option -windowtitle of javadoc tool.
When value TRUE is specified, includes the @author text in the generated docs. Same behavior as option -author of javadoc tool.
When value TRUE is specified, creates class and package usage pages. Includes one Use page for each documented class and package. Same behavior as option -use of javadoc tool.
When value TRUE is specified, includes the version text in the generated docs. Same behavior as option -version of javadoc tool.


UseSWIG

This file provides support for SWIG. It is assumed that FindSWIG module has already been loaded.

CMake Commands

The following command is defined for use with SWIG:

Added in version 3.8.

Define swig module with given name and specified language:

swig_add_library(<name>

[TYPE <SHARED|MODULE|STATIC|USE_BUILD_SHARED_LIBS>]
LANGUAGE <language>
[NO_PROXY]
[OUTPUT_DIR <directory>]
[OUTFILE_DIR <directory>]
SOURCES <file>...
)


Targets created with the swig_add_library command have the same capabilities as targets created with the add_library() command, so those targets can be used with any command expecting a target (e.g. target_link_libraries()).

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 will choose a different target name and store it in the SWIG_MODULE_<name>_REAL_NAME variable.

Changed in version 3.15: Alternate library name (set with the OUTPUT_NAME property, for example) will be passed on to Python and CSharp wrapper libraries.

Changed in version 3.21: Generated library use standard naming conventions for CSharp language when policy CMP0122 is set to NEW. Otherwise, the legacy behavior is applied.

NOTE:

For multi-config generators, this module does not support configuration-specific files generated by SWIG. All build configurations must result in the same generated source file.


NOTE:

For Makefile Generators, if, for some sources, the USE_SWIG_DEPENDENCIES property is FALSE, swig_add_library does not track file dependencies, so depending on the <name>_swig_compilation custom target is required for targets which require the swig-generated files to exist. Other generators may depend on the source files that would be generated by SWIG.


SHARED, MODULE and STATIC have the same semantic as for the add_library() command. If USE_BUILD_SHARED_LIBS is specified, the library type will be STATIC or SHARED based on whether the current value of the BUILD_SHARED_LIBS variable is ON. If no type is specified, MODULE will be used.
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.

Added in version 3.12.

Prevent the generation of the wrapper layer (swig -noproxy option).

Added in version 3.12.

Specify where to write the language specific files (swig -outdir option). If not given, the CMAKE_SWIG_OUTDIR variable will be used. If neither is specified, the default depends on the value of the UseSWIG_MODULE_VERSION variable as follows:

  • 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 will be used. The path of this directory can be retrieved from the SWIG_SUPPORT_FILES_DIRECTORY target property.

Added in version 3.12.

Specify an output directory name where the generated source file will be placed (swig -o option). If not specified, the SWIG_OUTFILE_DIR variable will be used. If neither is specified, OUTPUT_DIR or CMAKE_SWIG_OUTDIR is used instead.

List of sources for the library. Files with extension .i will be identified as sources for the SWIG tool. Other files will be handled in the standard way.

Added in version 3.14: This behavior can be overridden by specifying the variable SWIG_SOURCE_FILE_EXTENSIONS.


NOTE:

If UseSWIG_MODULE_VERSION is set to 2, it is strongly recommended to use a dedicated directory unique to the target when either the OUTPUT_DIR option or the CMAKE_SWIG_OUTDIR variable are specified. The output directory contents are 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.



Properties on Source Files

Source file properties on module files must be set before the invocation of the swig_add_library command to specify special behavior of SWIG and ensure generated files will receive the required settings.

Call SWIG in c++ mode. For example:

set_property(SOURCE mymod.i PROPERTY CPLUSPLUS ON)
swig_add_library(mymod LANGUAGE python SOURCES mymod.i)


Deprecated since version 3.12: Replaced with the fine-grained properties that follow.

Pass custom flags to the SWIG executable.

Added in version 3.12.

Add custom flags to SWIG compiler and have same semantic as properties INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_OPTIONS.

Added in version 3.13.

If set to TRUE, contents of target property INCLUDE_DIRECTORIES will be forwarded to SWIG compiler. If set to FALSE target property INCLUDE_DIRECTORIES will be ignored. If not set, target property SWIG_USE_TARGET_INCLUDE_DIRECTORIES will be considered.

Added in version 3.12.

Add custom flags to the C/C++ generated source. They will fill, respectively, properties INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_OPTIONS of generated C/C++ file.

Added in version 3.12.

Specify additional dependencies to the source file.

Added in version 3.20.

If set to TRUE, implicit dependencies are 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 Xcode generator.

Added in version 3.22: Added the support of Visual Studio Generators.

Specify the actual import name of the module in the target language. This is required if it cannot be scanned automatically from source or 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> is passed to SWIG compiler.

Added in version 3.19.

Specify where to write the language specific files (swig -outdir option) for the considered source file. If not specified, the other ways to define the output directory applies (see OUTPUT_DIR option of swig_add_library() command).

Added in version 3.19.

Specify an output directory where the generated source file will be placed (swig -o option) for the considered source file. If not specified, OUTPUT_DIR source property will be used. If neither are specified, the other ways to define output file directory applies (see OUTFILE_DIR option of swig_add_library() command).


Properties on Targets

Target library properties can be set to apply same configuration to all SWIG input files.

Added in version 3.12.

These properties will be applied to all SWIG input files and have same semantic as target properties INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_OPTIONS.

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)


Added in version 3.13.

If set to TRUE, contents of target property INCLUDE_DIRECTORIES will be forwarded to SWIG compiler. If set to FALSE or not defined, target property INCLUDE_DIRECTORIES will be ignored. This behavior can be overridden by specifying source property USE_TARGET_INCLUDE_DIRECTORIES.

Added in version 3.12.

These properties will populate, respectively, properties INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and COMPILE_FLAGS of all generated C/C++ files.

Added in version 3.12.

Add dependencies to all SWIG input files.


Read-only Target Properties

The following target properties are output properties and can be used to get information about support files generated by SWIG interface compilation.

Added in version 3.12.

This output property list of 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 most principal support files are listed. In case some advanced features of SWIG are used (for example %template), associated support files may not be listed. Prefer to use the SWIG_SUPPORT_FILES_DIRECTORY property to handle support files.


Added in version 3.12.

This output property specifies the directory where support files will be generated.

NOTE:

When source property OUTPUT_DIR is defined, multiple directories can be specified as part of SWIG_SUPPORT_FILES_DIRECTORY.



CMake Variables

Some variables can be set to customize the behavior of swig_add_library as well as SWIG:

Added in version 3.12.

Specify different behaviors for UseSWIG module.

  • Set to 1 or 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.

Add flags to all swig calls.
Specify where to write the language specific files (swig -outdir option).
Added in version 3.8.

Specify an output directory name where the generated source file will be placed. If not specified, CMAKE_SWIG_OUTDIR is used.

Specify extra dependencies for the generated module for <name>.
Added in version 3.14.

Specify a list of source file extensions to override the default behavior of considering only .i files as sources for the SWIG tool. For example:

set(SWIG_SOURCE_FILE_EXTENSIONS ".i" ".swg")


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.

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 Xcode generator.

Added in version 3.22: Added the support of Visual Studio Generators.


Deprecated Commands

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.

Link libraries to swig module:

swig_link_libraries(<name> <item>...)


This command has same capabilities as target_link_libraries() command.

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.




UsewxWidgets

This module calls include_directories() and link_directories(), sets compile definitions for the current directory and appends some compile flags to use wxWidgets library after calling the find_package(wxWidgets).

Examples

Include UsewxWidgets module in project's CMakeLists.txt:

# Note that for MinGW users the order of libraries is important.
find_package(wxWidgets REQUIRED net gl core base)
# Above also sets the wxWidgets_USE_FILE variable that points to this module.
include(${wxWidgets_USE_FILE})
# Link wxWidgets libraries for each dependent executable/library target.
target_link_libraries(<ProjectTarget> ${wxWidgets_LIBRARIES})


As of CMake 3.27, a better approach is to link only the wxWidgets::wxWidgets IMPORTED target to specific targets that require it, rather than including this module. Imported targets provide better control of the package usage properties, such as include directories and compile flags, by applying them only to the targets they are linked to, avoiding unnecessary propagation to all targets in the current directory.

# CMakeLists.txt
find_package(wxWidgets)
# Link the imported target for each dependent executable/library target.
target_link_libraries(<ProjectTarget> wxWidgets::wxWidgets)


FIND MODULES

These modules search for third-party software. They are normally called through the find_package() command.

FindALSA

Finds the Advanced Linux Sound Architecture (ALSA) library (asound).

Imported Targets

This module provides the following Imported Targets:

Added in version 3.12.

Target encapsulating the ALSA library usage requirements. This target is available only if ALSA is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the ALSA library is found.
List of libraries needed for linking to use ALSA library.
Include directories containing headers needed to use ALSA library.

Cache Variables

The following cache variables may also be set:

The ALSA include directory.
The absolute path of the asound library.

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. Armadillo is a library for linear algebra and scientific computing.

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 sets the following variables:

Set to true if the library is found. For backward compatibility, the ARMADILLO_FOUND variable is also set to the same value.
List of required include directories.
List of libraries to be linked.
Version as a string (ex: 1.0.4).
Major version number.
Minor version number.
Patch version number.
Name of the version (ex: Antipodean Antileech).

Examples

Using Armadillo:

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.

Components

This module supports the following components:

Added in version 4.1.

Finds the Aspell library and its include paths.

Added in version 4.1.

Finds the Aspell command-line interactive spell checker executable.


Components can be specified using the standard CMake syntax:

find_package(ASPELL [COMPONENTS <components>...])


If no COMPONENTS are specified, the module searches for both the ASPELL and Executable components by default.

Imported Targets

This module provides the following Imported Targets when CMAKE_ROLE is PROJECT:

Added in version 4.1.

Target encapsulating the Aspell library usage requirements. It is available only when the ASPELL component is found.

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:

Boolean indicating whether the requested Aspell components have been found.
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.

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.

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.


Cache Variables

The following cache variables may also be set:

The directory containing the aspell.h header file when using the Executable component.
Added in version 4.1.

The path to the Aspell library when using the ASPELL component.

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 AVIFile library and include paths.

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.

Result Variables

This module defines the following variables:

True if AVIFile is found. For backward compatibility, the AVIFILE_FOUND variable is also set to the same value.
The libraries to link against.
Definitions to use when compiling.

Cache Variables

The following cache variables may be also set:

Directory containing avifile.h and other AVIFile headers.

Examples

Finding AVIFile:

find_package(AVIFile)


FindBacktrace

Finds backtrace(3), a library that provides functions for application self-debugging.

This module checks whether backtrace(3) is supported, either through the standard C library (libc), or a separate library.

Imported Targets

Added in version 3.30.

This module provides the following Imported Targets:

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:

The include directories needed to use backtrace(3) header.
The libraries (linker flags) needed to use backtrace(3), if any.
Boolean indicating whether the backtrace(3) support is available.

Cache Variables

The following cache variables are also available to set or use:

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.
The external library providing backtrace, if any.
The directory holding the backtrace(3) header.

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:

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:

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.

Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) Bison is found.
The version of Bison found.

Cache Variables

The following cache variables may also be set:

The path to the bison command-line program.

Commands

This module provides the following command if bison is found:

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.

<name>
String used as an identifier for this command invocation.
<input-yacc-file>
The path to an input Yacc source file (.y). If given as a relative path, it will be interpreted relative to the current source directory (CMAKE_CURRENT_SOURCE_DIR).
<output-parser-file>
The path of the output parser file to be generated by Bison. If given as a relative path, it will be interpreted relative to the current Bison working directory.
Added in version 3.4.

By default, Bison can generate a header file containing the list of tokens. This option allows specifying a custom <header> file to be generated by Bison. If given as a relative path, it will be interpreted relative to the current Bison working directory.

Enables generation of a verbose grammar and parser report. By default, the report file is created in the current Bison working directory and named <output-parser-filename>.output.
<file>
Deprecated since version 3.7: Use VERBOSE REPORT_FILE <file>.

Specifies the path to which the report file should be copied. This argument is retained for backward compatibility and only works when the <output-parser-file> is specified as an absolute path.


Added in version 3.7.

Used in combination with VERBOSE to specify a custom path for the report output <file>, overriding the default location. If given as a relative path, it will be interpreted relative to the current Bison working directory.

Added in version 4.0.

A semicolon-separated list of extra options added to the bison command line.

Deprecated since version 4.0: Superseded by OPTIONS <options>....

A string of space-separated extra options added to the bison command line. A semicolon-separated list will not work.


Command variables

This command also defines the following variables:

Boolean indicating whether this command was successfully invoked.
The input source file, an alias for <input-yacc-file>.
The output parser file generated by bison.
The header file generated by bison, if any.
A list of files generated by bison, including the output parser file, header file, and report file.
Added in version 4.0.

A list of command-line options used for the bison command.

Deprecated since version 4.0: Superseded by BISON_<name>_OPTIONS variable with the same value.

A list of command-line options used for the bison command.



Examples

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 (if Bison is not found, processing stops with an error message):

find_package(BISON 2.1.3 REQUIRED)


Example: Generating Parser

Finding Bison and adding input Yacc source file parser.y to be processed by Bison into parser.cpp source file with header parser.h 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})


Examples: Command-line Options

Adding additional command-line options to the bison executable can be passed 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 in the OPTIONS <options>... argument. 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 to find Flex scanner generator.

FindBLAS

Find Basic Linear Algebra Subprograms (BLAS) library

This module finds an installed Fortran library that implements the BLAS linear-algebra interface.

At least one of the C, CXX, or Fortran languages must be enabled.

Input Variables

The following variables may be set to influence this module's behavior:

if ON use static linkage
Set to one of the BLAS/LAPACK Vendors to search for BLAS only from the specified vendor. If not set, all vendors are considered.
if ON tries to find the BLAS95 interfaces
Added in version 3.11.

if set pkg-config will be used to search for a BLAS library first and if one is found that is preferred

Added in version 3.25.

If set, the pkg-config method will look for this module name instead of just blas.

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.
Search for any BLAS/LAPACK. Most likely, a BLAS/LAPACK with 32-bit integer interfaces will be found.

Added in version 4.1.

Specify the BLAS/LAPACK threading model:

Sequential model
OpenMP model
Search for any BLAS/LAPACK, if both are available most likely OMP will be found.

This is currently only supported by NVIDIA NVPL.


Imported Targets

This module defines the following IMPORTED targets:

Added in version 3.18.

The libraries to use for BLAS, if found.


Result Variables

This module defines the following variables:

library implementing the BLAS interface is found
uncached list of required linker flags (excluding -l and -L).
uncached list of libraries (using full path name) to link against to use BLAS (may be empty if compiler implicitly links BLAS)
uncached list of libraries (using full path name) to link against to use BLAS95 interface
library implementing the BLAS95 interface is found

BLAS/LAPACK Vendors

Generic reference implementation
AMD Core Math Library
Added in version 3.27.

AMD Optimizing CPU Libraries

Apple BLAS (Accelerate), and Apple NAS (vecLib)
Added in version 3.18.

Arm Performance Libraries

Automatically Tuned Linear Algebra Software
Compaq/Digital Extended Math Library
Added in version 3.20.

Elbrus Math Library

Added in version 3.11.

BLIS Framework

Added in version 3.19.

Added in version 3.20.

Fujitsu SSL2 serial and parallel blas/lapack with SVE instructions

GotoBLAS

IBMESSL, IBMESSL_SMP

IBM Engineering and Scientific Subroutine Library


Intel MKL 32 bit and 64 bit obsolete versions
Intel MKL v10 32 bit, threaded code
Intel MKL v10+ 64 bit, threaded code, lp64 model
Intel MKL v10+ 64 bit, sequential code, lp64 model
Added in version 3.13.

Intel MKL v10+ 64 bit, threaded code, ilp64 model

Added in version 3.13.

Intel MKL v10+ 64 bit, sequential code, ilp64 model

Added in version 3.17.

Intel MKL v10+ 64 bit, single dynamic library

Added in version 3.30.

A BLAS/LAPACK demuxing library using PLT trampolines

Added in version 4.1.

NVIDIA Performance Libraries

Added in version 3.21.

NVIDIA HPC SDK

Added in version 3.6.

Portable High Performance ANSI C (PHiPAC)
Scientific Computing Software Library
SGI Scientific Mathematical Library
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. Set BLA_VENDOR to an Intel MKL variant either on the command-line as -DBLA_VENDOR=Intel10_64lp or in project code:

set(BLA_VENDOR Intel10_64lp)
find_package(BLAS)


In order to build a project using Intel MKL, and end user must first establish an Intel MKL environment:

Source the full Intel environment script:

. /opt/intel/oneapi/setvars.sh


Or, source the MKL component environment script:

. /opt/intel/oneapi/mkl/latest/env/vars.sh


Source the full Intel environment script:

. /opt/intel/bin/compilervars.sh intel64


Or, source the MKL component environment script:

. /opt/intel/mkl/bin/mklvars.sh intel64



The above environment scripts set the MKLROOT environment variable to the top of the MKL installation. They also add the location of the runtime libraries to the dynamic library loader environment variable for your platform (e.g. LD_LIBRARY_PATH). This is necessary for programs linked against MKL to run.

NOTE:

As of Intel oneAPI 2021.2, loading only the MKL component does not make all of its dependencies available. In particular, the iomp5 library must be available separately, or provided by also loading the compiler component environment:

. /opt/intel/oneapi/compiler/latest/env/vars.sh




FindBullet

Finds the Bullet physics engine.

Result Variables

This module defines the following variables:

Boolean true if Bullet was found. For backward compatibility, the BULLET_FOUND variable is also set to the same value.
The Bullet include directories.
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:

Can be set to Bullet install path or Windows build path to specify where to find Bullet.

Examples

Finding Bullet:

find_package(Bullet)


FindBZip2

Finds the BZip2 data compression library (libbz2):

find_package(BZip2 [<version>] [...])


Imported Targets

This module provides the following Imported Targets:

Added in version 3.12.

Target encapsulating the usage requirements of BZip2 library. This target is available only when BZip2 is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the BZip2 library is found. For backward compatibility, the BZIP2_FOUND variable is also set to the same value.
Added in version 3.12.

Include directories needed to use BZip2 library.

Libraries needed for linking to use BZip2.
Added in version 3.26.

The version of BZip2 found.


Cache Variables

The following cache variables may also be set:

The directory containing the BZip2 headers.
The path to the BZip2 library for release configurations.
The path to the BZip2 library for debug configurations.
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()).

Legacy Variables

The following variables are provided for backward compatibility:

Changed in version 3.26: Superseded by BZIP2_VERSION.

The version of BZip2 found.


Examples

Finding BZip2 library and linking it to a project target:

find_package(BZip2)
target_link_libraries(project_target PRIVATE BZip2::BZip2)


FindCoin3D

Finds Coin3D (Open Inventor).

Coin3D is an implementation of the Open Inventor API. It provides data structures and algorithms for 3D visualization.

Result Variables

This module defines the following variables:

True if Coin3D, Open Inventor was found. For backward compatibility, the COIN3D_FOUND variable is also set to the same value.

Cache Variables

The following cache variables may also be set:

Directory containing the Open Inventor header files (Inventor/So.h).
Coin3D libraries required for linking.

Examples

Finding Coin3D:

find_package(Coin3D)


FindCUDAToolkit

Added in version 3.17.

This script locates the NVIDIA CUDA toolkit and the associated libraries, but does not require the CUDA language be enabled for a given project. This module does not search for the NVIDIA CUDA Samples.

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 will 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.

4.
If the CUDA_PATH environment variable is defined, it will be searched for nvcc.
5.
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.
6.
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.
7.
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:
Platform Search Pattern
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.




Arguments

[<version>]
The [<version>] argument requests a version with which the package found should be compatible. See find_package version format for more details.

Options

If specified, configuration will error if a suitable CUDA Toolkit is not found.
If specified, the search for a suitable CUDA Toolkit will not produce any messages.
If specified, the CUDA Toolkit is considered found only if the exact VERSION specified is recovered.

Imported Targets

An imported target named CUDA::toolkit is provided.

This module defines IMPORTED targets for each of the following 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

CUDA Runtime Library

The CUDA Runtime library (cudart) are 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) are used by applications that use calls such as cuMemAlloc, and cuMemFree.

Targets Created:

CUDA::cuda_driver

cuBLAS

The CUDA Basic Linear Algebra Subroutine library.

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.

Targets Created:

CUDA::cudla starting in CUDA 11.6

cuFile

Added in version 3.25.

The NVIDIA GPUDirect Storage cuFile library.

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.

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.

Targets Created:

  • CUDA::curand
  • CUDA::curand_static

cuSOLVER

A GPU accelerated linear system solver library.

Targets Created:

  • CUDA::cusolver
  • CUDA::cusolver_static

cuSPARSE

The CUDA sparse matrix library.

Targets Created:

  • CUDA::cusparse
  • CUDA::cusparse_static

cupti

The NVIDIA CUDA Profiling Tools Interface.

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.

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. This is a shared library only.

Targets Created:

CUDA::nvblas

nvGRAPH

A GPU-accelerated graph analytics library. Removed starting in CUDA 11.0

Targets Created:

  • CUDA::nvgraph
  • CUDA::nvgraph_static

nvJPEG

A GPU-accelerated JPEG codec library. Introduced in CUDA 10.

Targets Created:

  • CUDA::nvjpeg
  • CUDA::nvjpeg_static

nvPTX Compiler

Added in version 3.25.

The PTX Compiler APIs. These are a set of APIs which can be used to compile a PTX program into GPU assembly code. Introduced in CUDA 11.1 This is a static library only.

Targets Created:

CUDA::nvptxcompiler_static starting in CUDA 11.1

nvRTC

A runtime compilation library for CUDA.

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.

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.

Targets Created:

  • CUDA::nvfatbin starting in CUDA 12.4
  • CUDA::nvfatbin_static starting in CUDA 12.4

nvidia-ML

The NVIDIA Management Library.

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

The legacy NVIDIA Tools Extension. This is a shared library only.

Targets Created:

CUDA::nvToolsExt

nvtx3

Added in version 3.25.

The header-only NVIDIA Tools Extension library. 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.


OpenCL

The NVIDIA Open Computing Language library. 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.

Result variables

A boolean specifying whether or not the CUDA Toolkit was found.
The exact version of the CUDA Toolkit found (as reported by nvcc --version, version.txt, or version.json).
The major version of the CUDA Toolkit.
The minor version of the CUDA Toolkit.
The patch version of the CUDA Toolkit.
The path to the CUDA Toolkit library directory that contains the CUDA executable nvcc.
List of paths to all the CUDA Toolkit folders containing header files required to compile a project linking against CUDA.
The path to the CUDA Toolkit library directory that contains the CUDA Runtime library cudart.
Added in version 3.18.

The path to the CUDA Toolkit directory containing the nvvm directory and either version.txt or version.json.

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.
The path to the NVIDIA CUDA compiler nvcc. Note that this path may not be the same as CMAKE_CUDA_COMPILER. nvcc must be found to determine the CUDA Toolkit version as well as determining other features of the Toolkit. This variable is set for the convenience of modules that depend on this one.

FindCups

Finds the Common UNIX Printing System (CUPS).

Imported Targets

This module provides the following Imported Targets:

Added in version 3.15.

Target encapsulating the CUPS usage requirements, available only if CUPS is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the CUPS is found. For backward compatibility, the CUPS_FOUND variable is also set to the same value.
Include directories needed for using CUPS.
The version of CUPS found.

Cache Variables

The following cache variables may also be set:

The directory containing the CUPS headers.
Libraries needed to link against to use CUPS.

Hints

This module accepts the following variables:

Set this variable to TRUE to require CUPS version which features the ippDeleteAttribute() function (i.e. at least of CUPS 1.1.19).

Examples

Finding CUPS and linking it 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.

Added in version 3.17: If curl is built using its CMake-based build system, it will provide its own CMake Package Configuration file (CURLConfig.cmake) for use with the find_package() command in config mode. By default, this module searches for this file and, if found, returns the results without further action. If the upstream configuration file is not found, this module falls back to module mode and searches standard locations.

Added in version 3.13: Debug and Release library variants are found separately.

Components

Added in version 3.14.

This module supports optional components to detect the protocols and features available in the installed curl (these can vary based 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


Components can be specified with the find_package() command as required for curl to be considered found:

find_package(CURL [COMPONENTS <protocols>... <features>...])


Or to check for them optionally, allowing conditional handling in the code:

find_package(CURL [OPTIONAL_COMPONENTS <protocols>... <features>...])


Refer to the curl documentation for more information on supported protocols and features. Component names are case-sensitive and follow the upstream curl naming conventions.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.12.

Target encapsulating the curl usage requirements, available if curl is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) curl and all required components are found.
Added in version 4.0.

The version of curl found. This supersedes CURL_VERSION_STRING.

Added in version 3.14.

Boolean indicating whether the specified component (curl protocol or feature) is found.

Include directories containing the curl/curl.h and other headers needed to use curl.

NOTE:

When curl is found via config mode, this variable is available only with curl version 8.9 or newer.


List of libraries needed 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 available only with curl version 8.9 or newer and contains a list of imported targets.



Hints

This module accepts the following variables:

Added in version 3.17.

Set this variable to TRUE to disable searching for curl via config mode.

Added in version 3.28.

Set this variable to TRUE to use static libraries. This is meaningful only when curl is not found via config mode.


Deprecated Variables

The following variables are provided for backward compatibility:

Deprecated since version 4.0: Superseded by CURL_VERSION.

The version of curl found.


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 if 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.

Curses is a terminal control library for Unix-like systems, used to build text user interface (TUI) applications. Originally developed in 1978, it has since evolved into multiple implementations, most notably ncurses (new curses), BSD curses, and PDCurses (a public domain curses library for non-Unix platforms).

Result Variables

This module defines the following variables:

Boolean indicating whether the Curses is found. For backward compatibility, the CURSES_FOUND variable is also set to the same value.
Added in version 3.1.

The include directories needed to use Curses.

The libraries needed to use Curses.
Added in version 3.16.

Compiler flags which ought be given to C/C++ compilers when using Curses.

Boolean indicating whether curses.h is available.
Boolean indicating whether ncurses.h is available.
Boolean indicating whether ncurses/ncurses.h is available.
Boolean indicating whether ncurses/curses.h is available.

Hints

This module accepts the following variables:

Set this variable to TRUE before calling find_package(Curses) if the the ncurses implementation functionality is specifically required.
Added in version 3.10.

Set this variable to TRUE before calling find_package(Curses) if Unicode (wide character) support is required.


Deprecated Variables

The following legacy variables are provided for backward compatibility:

Deprecated since version 3.1: Use the CURSES_INCLUDE_DIRS variable instead.

Path to a Curses include directory.

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).

Result Variables

This module defines the following variables:

True if the command-line client was found.

Cache Variables

The following cache variables may also be set:

Path to 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, a C++ unit testing framework suite, and provides a helper command to create test runners and integrate them with CTest.

Result Variables

This module defines the following variables:

Boolean indicating whether the CxxTest framework is found.
Include directories containing headers needed to use CxxTest.
The path to the found CxxTest test generator script (Perl- or Python-based), selected based on the found interpreter or user-specified preference.
The path to the found Perl or Python interpreter used to run the test generator script, if needed (e.g., on platforms where script shebang lines are not supported).

Cache Variables

The following cache variables may also be set:

The path to the Perl-based CxxTest test generator script.
The path to the Python-based CxxTest test generator script.

Hints

This module accepts the following variables before calling find_package(CxxTest):

This variable can be set to specify a semicolon-separated list of command-line options to pass to the CxxTest code generator. If not set, the default value is --error-printer.

Commands

This module provides the following command if CxxTest is found:

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:

<test-name>
The name of the test executable target to be created and registered as a test in the CTest suite.
<gen-source-file>
The name of the source file to be generated by the CxxTest code generator. This must be a relative path. It is 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, to be included in the test runner. These must be given as absolute paths.


Deprecated Variables

The following variables are deprecated and provided for backward compatibility:

Deprecated since version 2.8.3: In earlier versions of CMake, this hint variable was used to force the use of the Python-based test generator instead of the Perl one, regardless of which scripting language was installed. It is now 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. This variable is only relevant when using CxxTest version 3.


Examples

The following example demonstrates how CxxTest can be used in CMake with this module. If CxxTest is found:

  • Additional interface imported target is created manually in the project to encapsulate the CxxTest usage requirements and link it to specified tests. Such target is useful, for example, when dealing with multiple tests.
  • Test generator is 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.

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, a POSIX-compatible environment that runs natively on Microsoft Windows.

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 Cygwin and is usable from Windows.


Result Variables

This module defines the following variables:

The path to the Cygwin root installation directory.

Examples

Finding the Cygwin installation and using its path in 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 MSYS path in a similar way.

FindDCMTK

Find DICOM ToolKit (DCMTK) libraries and applications

The module defines the following variables:

DCMTK_INCLUDE_DIRS  - Directories to include to use DCMTK
DCMTK_LIBRARIES     - Files to link against to use DCMTK
DCMTK_FOUND         - If false, don't try to use DCMTK
DCMTK_DIR           - (optional) Source directory for DCMTK


Compatibility

This module is able to find a version of DCMTK that does or does not export a DCMTKConfig.cmake file. It applies a two step process:

  • Step 1: Attempt to find DCMTK version providing a DCMTKConfig.cmake file.
  • Step 2: If step 1 failed, rely on FindDCMTK.cmake to set DCMTK_* variables details below.

Recent DCMTK provides a DCMTKConfig.cmake package configuration file. To exclusively use the package configuration file (recommended when possible), pass the NO_MODULE option to find_package(). For example, find_package(DCMTK NO_MODULE). This requires official DCMTK snapshot 3.6.1_20140617 or newer.

Until all clients update to the more recent DCMTK, build systems will need to support different versions of DCMTK.

On any given system, the following combinations of DCMTK versions could be considered:

SYSTEM DCMTK LOCAL DCMTK Supported ?
Case A NA [ ] DCMTKConfig YES
Case B NA [X] DCMTKConfig YES
Case C [ ] DCMTKConfig NA YES
Case D [X] DCMTKConfig NA YES
Case E [ ] DCMTKConfig [ ] DCMTKConfig YES (*)
Case F [X] DCMTKConfig [ ] DCMTKConfig NO
Case G [ ] DCMTKConfig [X] DCMTKConfig YES
Case H [X] DCMTKConfig [X] DCMTKConfig YES
(*) See Troubleshooting section.


Legend:

NA ...............: Means that no System or Local DCMTK is available

[ ] DCMTKConfig ..: Means that the version of DCMTK does NOT export a DCMTKConfig.cmake file.

[X] DCMTKConfig ..: Means that the version of DCMTK exports a DCMTKConfig.cmake file.



Troubleshooting

What to do if my project finds a different version of DCMTK?

Remove DCMTK entry from the CMake cache per find_package() documentation.

FindDevIL

Finds the Developer's Image Library, DevIL.

The DevIL package internally consists of the following libraries, all distributed as part of the same release:

  • The core Image Library (IL)

    This library is always required when working with DevIL, as it provides the main image loading and manipulation functionality.

  • The Image Library Utilities (ILU)

    This library depends on IL and provides image filters and effects. It is only required if the application uses this extended functionality.

  • The Image Library Utility Toolkit (ILUT)

    This library depends on both IL and ILU, and additionally provides an interface to OpenGL. It is only needed if the application uses DevIL together with OpenGL.


Imported Targets

This module provides the following Imported Targets:

Added in version 3.21.

Target encapsulating the core Image Library (IL) usage requirements, available if the DevIL package is found.

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, as ILU depends on the core IL library.

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.


Result Variables

This module defines the following variables:

Boolean indicating whether the DevIL package is found, including the IL and ILU libraries.
Added in version 3.21.

Boolean indicating whether the ILUT library is found. On most systems, ILUT is found when both IL and ILU are available.


Cache Variables

The following cache variables may also be set:

The directory containing the il.h, ilu.h and ilut.h header files.
The full path to the core Image Library (IL).
The full path to the ILU library.
The full path to the ILUT library.

Examples

Finding the DevIL package and linking against the core Image Library (IL):

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, a source code documentation generator, along with some optional supporting tools, and provides a command for integrating Doxygen-based documentation into CMake projects:

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:

Added in version 3.9.

Finds the doxygen executable. This component is always automatically implied, even if not requested.

Added in version 3.9.

Finds the Graphviz dot utility, used for rendering graphs and diagrams as part of the documentation.

Added in version 3.9.

Finds the Message Chart Generator utility used by Doxygen's \msc and \mscfile commands.

Added in version 3.9.

Finds the 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:

Added in version 3.9.

Imported executable target encapsulating the doxygen executable usage requirements, available if Doxygen is found.

Added in version 3.9.

Imported executable target encapsulating the dot executable usage requirements, available if the above dot component is found.

Added in version 3.9.

Imported executable target encapsulating the mscgen executable usage requirements, available if the above mscgen component is found.

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.

Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) doxygen executable and all requested required components are found. For backward compatibility, the DOXYGEN_FOUND variable is also set, except it has boolean value of YES or NO.
The version of Doxygen found (as reported by doxygen --version).

Commands

This module provides the following command:

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 only need to specify input files or directories. Additional behavior and configuration can be customized using 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 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.

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.

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.

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.

Note also 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 for more details.

If provided, the <comment> string will be passed as the COMMENT argument to the underlying add_custom_target() command used to create the custom target internally. This appears in the build system output, when the target is built.
Added in version 3.27.

If specified, the given file provided with full-path will be used as Doxygen configuration file instead of the default Doxyfile.<target-name>.


Variables for customizing Doxygen configuration

The doxygen_add_docs() command generates a Doxygen configuration file containing configuration tags. 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, these tags can be modified by setting input variables in form of DOXYGEN_<tag>, where <tag> is one of the configuration tags listed in the Doxygen manual.

For example, to modify the GENERATE_HTML and GENERATE_MAN configuration tags, the following variables can be set 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 several of Doxygen's settings to better suit typical CMake projects. Each of the following variables is explicitly set unless already defined prior to calling doxygen_add_docs(), with a few exceptions noted below:

Set to YES if the dot component was requested and found, NO otherwise. Any existing value of DOXYGEN_HAVE_DOT is ignored.
Set to YES by this module (note that this requires a dot version newer than 1.8.10). This option is only meaningful if DOXYGEN_HAVE_DOT is also set to YES.
Set to NO by this module.
For Visual Studio based generators, this is set to the form recognized by the Visual Studio IDE: $file($line) : $text. For all other generators, Doxygen's default value is not overridden.
Populated with the name of the current project (i.e. PROJECT_NAME).
Populated with the version of the current project (i.e. PROJECT_VERSION).
Populated with the description of the current project (i.e. PROJECT_DESCRIPTION).
This variable is automatically populated with the list of files and directories passed to doxygen_add_docs(). For consistent behavior with other built-in commands like add_executable(), add_library(), and add_custom_target(), projects should not set this variable manually. If a variable named DOXYGEN_INPUT is set by the project, it will be ignored and a warning will be issued.
Set to YES by this module.
If the <files-or-dirs> argument of doxygen_add_docs() contains directories, this variable will specify patterns used to exclude files from them. The following patterns are added by default to ensure CMake-specific files and directories are not included in the input. If the project sets this variable, those contents are merged with these additional patterns rather than replacing them:

*/.git/*
*/.svn/*
*/.hg/*
*/CMakeFiles/*
*/_CPack_Packages/*
DartConfiguration.tcl
CMakeLists.txt
CMakeCache.txt


Set to CMAKE_CURRENT_BINARY_DIR by this module. If the project provides its own value for this and it is a relative path, it will be interpreted relative to the current binary directory (CMAKE_CURRENT_BINARY_DIR). This is necessary because Doxygen will normally be run from a directory within the source tree so that relative source paths work as expected. If this directory does not exist, it will be recursively created prior to executing Doxygen.

Lists

A number of Doxygen config tags accept lists of values, and Doxygen requires them to be separated by whitespace, while in CMake a list is a string with items separated by semicolons.

The doxygen_add_docs() specifically checks for the following Doxygen config tags and converts their associated CMake DOXYGEN_<tag> variable values into the Doxygen-formatted lists if set:

  • 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, a usual semicolon-separated list can be set 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 will produce a Doxygen list of patterns separated by spaces in the generated configuration file:

Doxyfile.<target-name>

# ...
FILE_PATTERNS          = *.c *.cxx *.h *.hxx


Automatic quoting

If a Doxygen single-value tag contains spaces, their values must be surrounded by double quotes ("..."). doxygen_add_docs() automatically quotes values of the following Doxygen tags when generating 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


Added in version 3.11.

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 using this variable, the project is then responsible for ensuring that those variables' values make sense when placed directly in 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.

For certain Doxygen tags, such as ALIASES, automatic quoting done by doxygen_add_docs() may interfere with correct syntax (e.g., embedded quotes).

For example, the following will quote DOXYGEN_PROJECT_BRIEF, but skip each item in the DOXYGEN_ALIASES list (bracket syntax is used to make working with embedded quotes easier):

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()


The resultant Doxyfile configuration will contain the following lines:

Doxyfile.project_docs

PROJECT_BRIEF = "String with spaces"
ALIASES       = somealias="@some_command param" anotherAlias=@foobar




Deprecated Variables

For compatibility with previous versions of CMake, the following variables are also defined but they are deprecated and should no longer be used:

Deprecated since version 3.9: Use Doxygen::doxygen imported target instead of referring to the doxygen executable directly.

Cache variable containing the path to the doxygen command.

Deprecated since version 3.9.

Boolean result variable indicating whether dot executable is found.

Deprecated since version 3.9: Use Doxygen::dot imported target instead of referring to the dot executable directly.

Cache variable containing the path to the dot command-line executable.

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 this value is needed, get the IMPORTED_LOCATION property of the Doxygen::dot target and use get_filename_component() to extract the directory part of that path. Consider also using file(TO_NATIVE_PATH) to prepare the path for a Doxygen configuration file.

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.


Examples

Examples: Finding Doxygen

Finding Doxygen:

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 not found, processing stops with an error message):

find_package(Doxygen REQUIRED)


Or, finding Doxygen as required and specifying dot tool as 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

The following example demonstrates how to find Doxygen and create documentation from source files at build phase. Once project is built, generated documentation files will be located in the html directory inside the project binary directory:

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), 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

In the following example, a custom Doxyfile configuration file is created in the current binary directory (CMAKE_CURRENT_BINARY_DIR) prior to calling the doxygen_add_doxs(). This allows project-specific configuration tags to be customized as needed:

CMakeLists.txt

find_package(Doxygen)
if(Doxygen_FOUND)

configure_file(Doxyfile.in Doxyfile)
doxygen_add_doxs(
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 is commonly used in High-Performance Computing (HPC) environments to support multiple software versions or configurations.

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 -S). It may also be used in a CMake Script (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, as the environment changes will not be available during the build phase. In such a case, load the desired environment before invoking CMake or the generated build system.


Result Variables

This module defines the following variables:

Boolean indicating whether a compatible Environment Modules framework is found.

Cache Variables

The following cache variables may also be set:

The path to a low level module command to use.

Hints

This module accepts the following variables before calling the find_package(EnvModules):

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:

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:

The module sub-command and arguments to execute as if passed directly to the module command in the shell environment.
Stores the standard output of the executed module command in the specified variable.
Stores the return code of the executed module command in the specified variable.


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:

Stores the standard output of the executed module command in the specified variable.
Stores the return code of the executed module command in the specified variable.


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 variable.


Retrieves the list of available modules:

env_module_avail([<mod-prefix>] <out-var>)


This is functionally equivalent to the module avail <mod-prefix> shell command. The result is stored in <out-var> as a properly formatted CMake semicolon-separated list variable.


Examples

In the following example, this module is used in a CTest script to configure the compiler and libraries for a Cray Programming Environment. After the Environment Modules system is found, the env_module() command is used to load the necessary compiler, MPI, and scientific libraries to set up the build environment. The CRAYPE_LINK_TYPE environment variable is set to dynamic to specify dynamic linking. This instructs the Cray Linux Environment compiler driver to link against dynamic libraries at runtime, rather than linking static libraries at compile time. As a result, 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. Expat is a stream-oriented XML parser library written in C.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.10.

Target encapsulating the Expat library (expat) usage requirements. This target is available only if Expat is found.


Result Variables

This module sets the following variables:

Include directories containing expat.h and related headers needed to use Expat.
Libraries needed to link against to use Expat.
Boolean indicating whether the Expat is found.

Hints

This module accepts the following variables:

Added in version 3.28.

Set to TRUE to use static libraries.

Added in version 3.31: Implemented on non-Windows platforms.


Examples

Finding Expat library and linking it to a project target:

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 provides 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, such as input handling, buffer management, and error reporting.

Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) Flex is found.
The version of Flex found.
The include directories containing headers for using Flex library.
The libraries needed to link against to use Flex library.

Cache Variables

The following cache variables may also be set:

The path to the flex executable.

Commands

This module provides the following commands if flex is found:

Generating Scanners

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 is set to NEW, flex runs in the CMAKE_CURRENT_BINARY_DIR directory.

<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).
<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.
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.

Added in version 4.0.

A semicolon-separated list of extra options added to the flex command line.

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 will not work.


Command variables

This command also defines the following variables:

Boolean indicating whether this command was successfully invoked.
The Flex source file, an alias for <input-lex-file>.
Added in version 3.5.

The header file generated by flex, if any.

A list of files generated by flex, including the output scanner file, and the header file.
Added in version 4.0.

A list of command-line options used for the flex command.



Adding Dependency Between Scanner and Parser

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.

This command adds 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> ...) commands.


Examples

Examples: Finding Flex

Finding Flex:

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):

find_package(FLEX 2.5.13 REQUIRED)


Example: Generating Scanner

Finding Flex and generating 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 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 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 in CMake:

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 Bison parser generator.

FindFLTK

Finds the Fast Light Toolkit (FLTK), a cross-platform toolkit for GUI development.

FLTK uses CMake-based build system and provides a package configuration file for projects to find it. As of its 1.4.0 version it also provides 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. See also to the official FLTK documentation for more information, how to use FLTK with CMake.

Added in version 3.11: Debug and Release library variants are found separately and use per-configuration variables.

Result Variables

This module defines the following variables:

Boolean indicating whether FLTK is found.
Libraries needed to link against to use FLTK.
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 if it is needed and available.

Cache Variables

The following cache variables are also available to set or use:

The path to the fluid binary tool.
The include directory containing header files needed to use FLTK.
Added in version 3.11.

The path to the release (optimized) FLTK base library.

Added in version 3.11.

The path to the debug FLTK base library.

Added in version 3.11.

The path to the release (optimized) FLTK GL library.

Added in version 3.11.

The path to the debug FLTK GL library.

Added in version 3.11.

The path to the release (optimized) FLTK Forms library.

Added in version 3.11.

The path to the debug FLTK Forms library.

Added in version 3.11.

The path to the release (optimized) FLTK Images protobuf library.

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:

Set to boolean true to mark the fluid executable as optional.
Set to boolean true to mark the FLTK Forms library as optional; it will therefore not be included in the FLTK_LIBRARIES result variable.
Set to boolean true to mark the FLTK Image library as optional; it will therefore not be included in the FLTK_LIBRARIES result variable.
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. 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 instead.


Finds the Fast Light Toolkit (FLTK) version 2.x, a cross-platform toolkit for GUI development.

Result Variables

This module defines the following variables:

Boolean indicating whether FLTK 2.x is found.
Libraries needed to link against to use FLTK 2.x.
Boolean indicating whether the fluid2 executable is found. This variable can be used, for example, to conditionally invoke the fltk_wrap_ui() command if it is needed and available.

Cache Variables

The following cache variables may also be set:

The path to the fluid2 binary tool.
The directory containing header files needed to use FLTK 2.x.
The path to the FLTK 2.x library (fltk2).
The path to the FLTK 2.x OpenGL compatibility library (fltk2_gl).
The path to the FLTK 2.x Images library (fltk2_images).

Examples

Finding FLTK version 2:

find_package(FLTK2)


See Also

The 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.

Imported Targets

This module provides the following Imported Targets:

Target encapsulating the Fontconfig usage requirements, available if Fontconfig is found.

Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) Fontconfig is found.
The version of Fontconfig found.
The libraries to link against to use Fontconfig.
The include directories containing headers needed to use Fontconfig.
Compiler options needed to use Fontconfig. These should be passed to 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.

Imported Targets

This module provides the following Imported Targets:

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:

Boolean indicating whether the (requested version of) Freetype is found. For backward compatibility, the FREETYPE_FOUND variable is also set to the same value.
Include directories containing headers needed to use Freetype. This is the concatenation of FREETYPE_INCLUDE_DIR_ft2build and FREETYPE_INCLUDE_DIR_freetype2 variables.
Libraries needed to link against for using Freetype.
The version of Freetype found.

Added in version 3.7: Debug and Release library variants are found separately.

Cache Variables

The following cache variables may also be set:

The directory containing the main Freetype API configuration header.
The directory containing Freetype public headers.

Hints

This module accepts the following variables:

The user may set this environment variable to the root directory of a Freetype installation to find Freetype in non-standard locations.

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:

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, which abstracts libintl handling across various implementations.

Common file types used with gettext:

Portable Object Template (.pot) files used as the source template for translations.
Portable Object (.po) files containing human-readable translations.
Machine Object (.mo) files compiled from .po files for runtime use.

Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) gettext is found. For backward compatibility, the GETTEXT_FOUND variable is also set to the same value.
The version of gettext found.

Cache Variables

The following cache variables may also be set:

The full path to the msgmerge tool for merging message catalog and template.
The full path to the msgfmt tool for compiling message catalog to a binary format.

Commands

This module provides the following commands to work with gettext in CMake, if gettext is found:

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, to which all subsequent invocations contribute. This target can be used to build all translation files collectively or referenced in other CMake commands.

This command should be invoked separately for each language locale to generate the appropriate .mo files per locale.

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.

This option adds the generated target to the default CMake build target so that translations are built by default.
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.
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).


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.

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).
Adds the generated target to the default CMake build target so that the files are built by default.
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.
A list of one or more translatable language locales (e.g., en_US, fr, de_DE, zh_CN, etc.).


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.

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).
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.



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).

Imported Targets

This module provides the following Imported Targets:

Added in version 3.14.

Target that encapsulates the usage requirements of the GIF library, available when the library is found.


Result Variables

This module sets the following variables:

Boolean indicating whether the GIF library was found.
Include directories needed to use the GIF library.
Libraries needed to link to the GIF library.
Version string of the GIF library found (for example, 5.1.4). For GIF library versions prior to 4.1.6, version string will be set only to 3 or 4 as these versions did not provide version information in their headers.

Cache Variables

The following cache variables may also be set:

Directory containing the gif_lib.h and other GIF library headers.
Path to the GIF library.

Hints

This module accepts the following variables:

Environment variable that can be set to help locate a GIF library installed in a custom location. It should point to the installation destination that was used when configuring, building, and installing GIF library: ./configure --prefix=$GIF_DIR.

Examples

Finding GIF library 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.

Imported Targets

This module provides the following Imported Targets when the CMAKE_ROLE is PROJECT:

Added in version 3.14.

Target that encapsulates Git command-line client executable. It can be used in generator expressions, and commands like add_custom_target() and add_custom_command(). This target is available only if Git is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the Git was found. For backward compatibility, the GIT_FOUND variable is also set to the same value.
The version of Git found.

Cache Variables

The following cache variables may also be set:

Path to the git command-line client executable.

Examples

Finding Git and retrieving the latest commit from the project repository:

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).

GLEW is a cross-platform C/C++ library that helps manage OpenGL extensions by providing efficient run-time mechanisms to query and load OpenGL functionality beyond the core specification.

Added in version 3.7: Debug and Release library variants are found separately.

Added in version 3.15: If GLEW is built using its CMake-based build system, it provides a CMake package configuration file (GLEWConfig.cmake). This module now takes that into account and first attempts to find GLEW in config mode. If the configuration file is not available, it falls back to module mode and searches standard locations.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.1.

The main imported target encapsulating the GLEW usage requirements, available if GLEW is found. It maps usage requirements of either GLEW::glew or GLEW::glew_s target depending on their availability.

Added in version 3.15.

Target encapsulating the usage requirements for a shared GLEW library. This target is available if GLEW is found and static libraries aren't requested via the GLEW_USE_STATIC_LIBS hint variable (see below).

Added in version 3.15.

Target encapsulating the usage requirements for a static GLEW library. This target is available if GLEW is found and the GLEW_USE_STATIC_LIBS hint variable is set to boolean true.


Result Variables

This module defines the following variables:

Boolean indicating whether GLEW is found.
Added in version 3.15.

The version of GLEW found.

Added in version 3.15.

The major version of GLEW found.

Added in version 3.15.

The minor version of GLEW found.

Added in version 3.15.

The micro version of GLEW found.

Include directories needed to use GLEW library.
Libraries needed to link against to use GLEW library (shared or static depending on configuration).
Added in version 3.15.

Libraries needed to link against to use shared GLEW library.

Added in version 3.15.

Libraries needed to link against to use static GLEW library.


Hints

This module accepts the following variables before calling find_package(GLEW) to influence this module's behavior:

Added in version 3.15.

Set to boolean true to find static GLEW library and create the GLEW::glew_s imported target for static linkage.

Added in version 3.15.

Set to boolean true to output a detailed log of this module. Can be used, for example, for debugging.


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 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, which provides a simple API for creating windows, handling input, and managing events in OpenGL applications.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.1.

Target encapsulating the GLUT usage requirements, available if GLUT is found.


Result Variables

This module defines the following variables:

Boolean indicating whether GLUT is found.
Added in version 3.23.

Include directories needed to use GLUT. Starting with CMake 3.23, this variable is intended to be used in target usage requirements instead of the cache variable GLUT_INCLUDE_DIR, which is intended for finding GLUT.

List of libraries needed to link against for using GLUT.

Cache Variables

This module may set the following cache variables depending on platform. These variables may optionally be set to help this module find the correct files, but should not be used as result variables:

The full path to the directory containing GL/glut.h (without the GL/).
The full path to the glut library.
The full path to the dependent Xi (X Input Device Extension) library on some systems.
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 for generating two- and three-dimensional plots (gnuplot).

Result Variables

This module sets the following variables:

Boolean indicating whether Gnuplot has been found. For backward compatibility, the GNUPLOT_FOUND variable is also set to the same value.
The version of Gnuplot found.

NOTE:

Version detection is available only for Gnuplot 4 and later. Earlier versions did not provide version output.



Cache Variables

The following cache variables may also be set:

Absolute path to the gnuplot executable.

Examples

Finding Gnuplot:

find_package(Gnuplot)


FindGnuTLS

Finds the GNU Transport Layer Security library (GnuTLS). The GnuTLS package includes the main libraries (libgnutls and libdane), as well as the optional gnutls-openssl compatibility extra library. They are all distributed as part of the same release. This module checks for the presence of the main libgnutls library and provides usage requirements for integrating GnuTLS into CMake projects.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.16.

Target encapsulating the GnuTLS usage requirements, available if GnuTLS is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) GnuTLS is found. For backward compatibility, the GNUTLS_FOUND variable is also set to the same value.
Added in version 3.16.

The version of GnuTLS found.

Include directories needed to use GnuTLS.
Libraries needed to link against to use GnuTLS.
Compiler options required for using GnuTLS.

Cache Variables

The following cache variables may also be set:

The directory containing the gnutls/gnutls.h header file.
The path to the GnuTLS library.

Deprecated Variables

These variables are provided for backward compatibility:

Deprecated since version 3.16: Superseded by GNUTLS_VERSION.

The version of GnuTLS found.


Examples

Finding GnuTLS and linking it to a project target:

find_package(GnuTLS)
target_link_libraries(project_target PRIVATE GnuTLS::GnuTLS)


FindGSL

Added in version 3.2.

Finds the native GNU Scientific Library (GSL) includes and libraries.

The GNU Scientific Library (GSL) is a numerical library for C and C++ programmers. It is free software under the GNU General Public License.

Imported Targets

If GSL is found, this module defines the following Imported Targets:

The main GSL library that provides all usage requirements to use GSL.
The CBLAS support library used by GSL. It is linked also into the GSL::gsl target but provided separately for granularity.

Result Variables

This module will set the following variables in the project:

True if GSL is found on the local system.
Directory containing GSL header files.
The GSL libraries.
The version of the discovered GSL installation.

Hints

Set this variable to a directory that contains a GSL installation.

If this variable is not set, this module will use pkg-config and default paths to find GSL. If this variable is provided, then this module expects to find libraries at ${GSL_ROOT_DIR}/lib and the GSL headers at ${GSL_ROOT_DIR}/include/gsl.

The library directory may optionally provide Release and Debug folders. If available, the libraries named gsld, gslblasd or cblasd are recognized as debug libraries. For Unix-like systems, this module will also use gsl-config (if found) to aid in the discovery of GSL.


Cache Variables

This module may set the following variables depending on platform and type of GSL installation discovered. These variables may optionally be set to help this module find the correct files:

Location of the GSL CBLAS library.
Location of the debug GSL CBLAS library (if any).
Location of the gsl-config script (if any).
Location of the GSL library.
Location of the debug GSL library (if any).

Examples

Finding GSL and linking it to a project target:

find_package(GSL)
target_link_libraries(project_target PRIVATE GSL::gsl)


FindGTest

Finds GoogleTest, the Google C++ testing and mocking framework:

find_package(GTest [...])


The GoogleTest framework also includes GoogleMock, a library for writing and using C++ mock classes. On some systems, GoogleMock may be distributed as a separate package.

When both debug and release (optimized) variants of the GoogleTest and GoogleMock libraries are available, this module selects the appropriate variants based on the current Build Configuration.

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 found, returns the results without further action. If the upstream configuration file is not found, this module falls back to Module mode and searches standard locations.

Imported Targets

This module provides the following Imported Targets:

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.

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, allowing tests to be run without defining one manually.

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.

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++.

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, allowing GoogleMock tests to be run without defining one manually.

Only link to GTest::gmock_main if GoogleTest should supply the main() function for the executable. If project is supplying its own main() implementation, link only to GTest::gmock.


Result Variables

This module defines the following variables:

Boolean indicating whether GoogleTest is found.

Hints

This module accepts the following variables before calling find_package(GTest):

The root directory of the GoogleTest installation (may also be set as an environment variable). This variable is used only when GoogleTest is found in Module mode.
When compiling with MSVC, this variable controls which GoogleTest build variant to search for, based on the runtime library linkage model. This variable is used only when GoogleTest is found in Module mode and accepts one of the following values:
(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).
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:

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.

Result variable that provides include directories containing headers needed to use GoogleTest. This variable is only guaranteed to be available when GoogleTest is found in Module mode.

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.

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.

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.


Deprecated Imported Targets

For backward compatibility, this module also provides the following imported targets (available since CMake 3.5):

Deprecated since version 3.20: Use the GTest::gtest imported target instead.

Imported target linking the GTest::gtest library.

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 not found, processing stops with an error message):

find_package(GoogleTest REQUIRED)


Examples: Using Imported Targets

In the following example, the GTest::gtest imported target is linked to a project target, which enables using the core GoogleTest testing framework:

find_package(GTest REQUIRED)
target_link_libraries(foo PRIVATE GTest::gtest)


In the next example, the GTest::gtest_main imported target is also linked to the executable, and a test is registered. The GTest::gtest_main library provides a main() function, so there is no need to write one manually. The GTest::gtest library is still linked because the test code directly uses things provided by GTest::gtest, and good practice is to link directly to libraries used directly.

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 with the GoogleTest module, which provides gtest_discover_tests() and gtest_add_tests() commands to help integrate 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.

FindGTK

Finds GTK, glib and GTKGLArea.

GTK is a multi-platform toolkit for creating graphical user interfaces.

NOTE:

This module works only on Unix-like systems and was intended for early GTK branch of 1.x, which is no longer maintained. Use the latest supported GTK version and 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)




Result Variables

This module defines the following variables:

Boolean indicating whether GTK is found.
Boolean indicating whether GTK's GL features are found.
Include directories containing headers needed to use GTK.
Libraries needed to link against for using GTK.

Examples

Finding GTK 1.x and creating an interface imported target that encapsulates its usage requirements for linking 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 to find GTK version 2.

FindGTK2

Finds the GTK widget libraries and several of its other optional components.

GTK is a multi-platform toolkit for creating graphical user interfaces.

NOTE:

This module is specifically for GTK version 2.x, which is obsolete and no longer maintained. Use the latest supported GTK version and 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)




Components

This module supports optional components, which can be specified 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 no components are specified, module by default searches for the gtk component.

Imported Targets

This module provides the following Imported Targets (subject to component selection):

Target encapsulating the specified GTK component usage requirements, available if GTK and this component are found. The <component> should be written in the same case, as listed above. For example, use GTK2::gtk for the gtk component, or GTK2::gdk_pixbuf for the gdk_pixbuf component, etc.
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.


Result Variables

This module defines the following variables:

Boolean indicating whether GTK and all specified components are found.
The version of GTK found (x.y.z).
The major version of GTK found.
The minor version of GTK found.
The patch version of GTK found.
Include directories containing headers needed to use GTK.
Libraries needed to link against to use GTK.
Added in version 3.5.

A list of all defined imported targets.

Additional compiler flags needed to use GTK.

Input Variables

This module accepts the following optional variables before calling the find_package(GTK2):

Boolean variable that enables verbose debugging output of this module.
A list of additional path suffixes to search for include files.
Added in version 3.5.

When this variable is set to boolean true, GTK2_LIBRARIES variable will contain a list imported targets instead of library paths.


Examples

Examples: Finding GTK version 2

Call find_package() once. Here are some examples to pick from.

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), a library for reading and writing self-describing array data:

find_package(HDF5 [<version>] ... [COMPONENTS <components>...] ...)


If the HDF5 library is built using its CMake-based build system, it will as of HDF5 version 1.8.15 provide its own CMake Package Configuration file (hdf5-config.cmake) for use with the find_package() command in config mode. By default, this module searches for this file and, if found, returns the results based on the found configuration.

If the upstream configuration file is not found, this module falls back to module mode and invokes the HDF5 wrapper compiler 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 is 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.

In addition to 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.

Components

This module supports optional components, which can be specified with the find_package() command:

find_package(HDF5 [COMPONENTS <components>...])


Supported components include:

Finds the HDF5 C library (C bindings).
Finds the HDF5 C++ library (C++ bindings).
Finds the HDF5 Fortran library (Fortran bindings).
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.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.19.

Target encapsulating the usage requirements for all found HDF5 libraries (HDF5_LIBRARIES), available if HDF5 and all required components are found.

Added in version 3.19.

Target encapsulating the usage requirements for the HDF5 C library, available if HDF5 library and its C component are found.

Added in version 3.19.

Target encapsulating the usage requirements for the HDF5 C and C++ libraries, available if HDF5 library, and its C and CXX components are found.

Added in version 3.19.

Target encapsulating the usage requirements for the HDF5 Fortran library, available if HDF5 library and its Fortran component are found.

Added in version 3.19.

Target encapsulating the usage requirements for the HDF5 high-level C library, available if HDF5 library and its C, and HL components are found.

Added in version 3.19.

High-level C++ library.

Target encapsulating the usage requirements for the HDF5 high-level C and high-level C++ libraries, available if HDF5 library and its C, CXX, and HL components are found.

Added in version 3.19.

Target encapsulating the usage requirements for the HDF5 high-level Fortran library, available if HDF5 library and its Fortran, and HL components are found.

Added in version 3.19.

Imported executable target encapsulating the usage requirements for the h5diff executable, available if h5diff is found.


Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) HDF5 is found.
Added in version 3.3.

The version of HDF5 library found.

Include directories containing header files needed to use HDF5.
Required compiler definitions for using HDF5.
Libraries of all requested bindings needed to link against to use HDF5.
Required libraries for the HDF5 high-level API for all bindings, if the HL component is enabled.
Boolean indicating whether the HDF5 library has parallel IO support.

For each enabled language binding component, a corresponding HDF5_<LANG>_LIBRARIES variable, and potentially HDF5_<LANG>_DEFINITIONS, will be defined. If the HL component is enabled, then HDF5_<LANG>_HL_LIBRARIES variables will also be defined:

Required compiler definitions for HDF5 C bindings.
Required compiler definitions for HDF5 C++ bindings.
Required compiler definitions for HDF5 Fortran bindings.
Required include directories for HDF5 C bindings.
Required include directories for HDF5 C++ bindings.
Required include directories for HDF5 Fortran bindings.
Required libraries for the HDF5 C bindings.
Required libraries for the HDF5 C++ bindings.
Required libraries for the HDF5 Fortran bindings.
Required libraries for the high-level C bindings, if the HL component is enabled.
Required libraries for the high-level C++ bindings, if the HL component is enabled.
Required libraries for the high-level Fortran bindings, if the HL component is enabled.

Cache Variables

The following cache variables may also be set:

The path to the HDF5 C wrapper compiler.
The path to the HDF5 C++ wrapper compiler.
The path to the HDF5 Fortran wrapper compiler.
Added in version 3.6.

The path to the primary C compiler which is also the HDF5 wrapper. This variable is used only in module mode.

Added in version 3.6.

The path to the primary C++ compiler which is also the HDF5 wrapper. This variable is used only in module mode.

Added in version 3.6.

The path to the primary Fortran compiler which is also the HDF5 wrapper. This variable is used only in module mode.

The path to the HDF5 dataset comparison tool (h5diff).

Hints

The following variables can be set before calling the find_package(HDF5) to guide the search for HDF5 library:

Added in version 3.4.

Set this to boolean true to prefer parallel HDF5 (by default, serial is preferred). This variable is used only in module mode.

Added in version 3.9.

Set this to boolean true to get extra debugging output by this module.

Added in version 3.8.

Set this to boolean true to skip finding and using CMake package configuration file (hdf5-config.cmake).

Set this to boolean value to determine whether or not to prefer a static link to 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:

find_package(HDF5)


Specifying a minimum required version of HDF5 to find:

find_package(HDF5 1.8.15)


Finding HDF5 and making it required (if HDF5 is not found, processing stops with an error message):

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:

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 provides a command for extracting information from a Mercurial working copy:

find_package(Hg [<version>] [...])


Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) Mercurial client is found. For backward compatibility, the HG_FOUND variable is also set to the same value.
The version of Mercurial found.

Cache Variables

The following cache variables may also be set:

Absolute path to the Mercurial command-line client (hg).

Commands

This module provides the following command when Mercurial client (hg) is found:

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 Mercurial client on working copy located at a given location <dir> succeeds; otherwise a SEND_ERROR message is generated:

<var-prefix>_WC_CHANGESET
Current changeset.
<var-prefix>_WC_REVISION
Current revision.


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 Hebrew spell-checker (Hspell) and morphology engine.

Result Variables

This module defines the following variables:

Boolean indicating whether the Hspell is found.
The version of Hspell found (x.y).
The major version of Hspell.
The minor version of Hspell.

Cache Variables

The following cache variables may also be set:

The Hspell include directory.
The libraries needed to use Hspell.

Examples

Finding Hspell:

find_package(HSPELL)


FindHTMLHelp

This module finds the Microsoft HTML Help Compiler and its API. It is part of the HTML Help Workshop.

NOTE:

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.


Cache Variables

This module may set the following cache variables:

Full path to the HTML Help Compiler (hhc.exe), used to compile .chm files.
Directory containing htmlhelp.h, required for applications integrating the HTML Help API.
Full path to htmlhelp.lib library, required for linking applications that use the HTML Help API.

Examples

Finding 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. Ice is an open-source remote procedure call (RPC) framework developed by ZeroC and provides SDKs for various languages to develop network applications.

Added in version 3.4: Imported targets for components and many new *_EXECUTABLE variables.

Added in version 3.7: Debug and Release library variants are found separately.

Added in version 3.10: Ice 3.7 support, including new components, programs and the Nuget package.

Components

Ice consists of several libraries and programs (executables). This find module supports components, which can be specified using the find_package() command, to select specific Ice libraries for use in a CMake project. Executables provided by Ice installation are always searched automatically, regardless of the specified components.

The list of available components depends on the Ice version in use. To successfully find Ice, at least one component must be specified:

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 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:

Added in version 3.4.

Target encapsulating the usage requirements for the specified Ice component (library), available if that component is found. The <component> should be written in the same case, as listed above. For example, use Ice::Glacier2 for the Ice Glacier2 library, or Ice::Ice++11 for the Ice++11 library, etc.


Result Variables

This module defines the following variables:

Boolean indicating whether the main programs, libraries and all requested components for using Ice were found.
The version of Ice release found.
The include directories containing headers needed to use Ice.
Component libraries needed to link against to use Ice.
The data directories containing interface definitions (*.ice files) for Slice (Specification Language for Ice).

Ice component libraries are stored in:

Boolean indicating whether the specified Ice component is found. The <COMPONENT> should be written in uppercase.
Libraries provided by the specified Ice component. The <COMPONENT> should be written in uppercase.

Slice programs are stored in:

Added in version 3.14.

The path to the slice2confluence executable.

The path to the slice2cpp executable.
The path to the slice2cs executable.
The path to the slice2freezej executable.
The path to the slice2freeze executable.
The path to the slice2html executable.
The path to the slice2java executable.
Added in version 3.4.

The path to the slice2js executable.

Added in version 3.14.

The path to the slice2matlab executable.

Added in version 3.10.

The path to the slice2objc executable.

The path to the slice2php executable.
The path to the slice2py executable.
The path to the slice2rb executable.

Ice programs are stored in:

Added in version 3.4.

The path to the glacier2router executable.

Added in version 3.4.

The path to the icebox executable.

Added in version 3.10.

The path to the icebox++11 executable.

Added in version 3.4.

The path to the iceboxadmin executable.

Added in version 3.4.

The path to the iceboxd executable.

Added in version 3.4.

The path to the iceboxnet executable.

Added in version 3.10.

The path to the icebridge executable.

Added in version 3.4.

The path to the icegridadmin executable.

Added in version 3.10.

The path to the icegriddb executable.

Added in version 3.4.

The path to the icegridnode executable.

Added in version 3.4.

The path to the icegridnoded executable.

Added in version 3.4.

The path to the icegridregistry executable.

Added in version 3.4.

The path to the icegridregistryd executable.

The path to the icepatch2calc executable.
Added in version 3.4.

The path to the icepatch2client executable.

Added in version 3.4.

The path to the icepatch2server executable.

Added in version 3.4.

The path to the iceserviceinstall executable.

Added in version 3.4.

The path to the icestormadmin executable.

Added in version 3.10.

The path to the icestormdb executable.

Added in version 3.4.

The path to the icestormmigrate executable.


Ice database programs are stored in the following variables (on Windows, they are included with the Ice installation; on other platforms, they are usually available through standard Berkeley DB packages):

Added in version 3.4.

The path to the db_archive executable.

Added in version 3.4.

The path to the db_checkpoint executable.

Added in version 3.4.

The path to the db_deadlock executable.

Added in version 3.4.

The path to the db_dump executable.

Added in version 3.4.

The path to the db_hotbackup executable.

Added in version 3.4.

The path to the db_load executable.

Added in version 3.4.

The path to the db_log_verify executable.

Added in version 3.4.

The path to the db_printlog executable.

Added in version 3.4.

The path to the db_recover executable.

Added in version 3.4.

The path to the db_stat executable.

Added in version 3.4.

The path to the db_tuner executable.

Added in version 3.4.

The path to the db_upgrade executable.

Added in version 3.4.

The path to the db_verify executable.

Added in version 3.4.

The path to the dumpdb executable.

Added in version 3.4.

The path to the transformdb executable.


Cache Variables

The following cache variables may also be set:

The path to the specified <PROGRAM> executable; The <PROGRAM> is the uppercase name of the Ice program as listed in above result variables of executables.
The directory containing Ice headers.
The data directory containing interface definitions for Slice.
The path to the library for the specified component. The <COMPONENT> should be written in uppercase.

Hints

This module accepts the following variables:

Set this CMake variable to the root of the Ice installation in order to search for Ice in a custom location.

NOTE:

On Windows, Ice 3.7.0 and later provide libraries via the NuGet package manager. Appropriate NuGet packages will be searched for using CMAKE_PREFIX_PATH, or alternatively Ice_HOME may be set to the location of a specific NuGet package to restrict the search.


Environment variable (uppercased) may also be set to the root of the Ice installation; The Ice_HOME CMake variable takes precedence.
Set this variable to boolean true to enable debug output from this module.

NOTE:

In most cases, none of the above variables need to be set unless multiple Ice versions are installed and a specific one is required. 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). All other variables default based on the value of Ice_HOME, if set.

It's also possible to 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 are not sufficient to identify the correct programs and libraries for the specific Visual Studio version.



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 Ice core library and IceSSL library, and linking them to a project target:

find_package(Ice COMPONENTS Ice IceSSL)
target_link_libraries(project_target PRIVATE Ice::Ice Ice::IceSSL)


Finding Ice core library as required component and Ice Freeze library as optional:

find_package(Ice COMPONENTS Ice OPTIONAL_COMPONENTS Freeze)


FindIconv

Added in version 3.11.

This module finds the iconv() POSIX.1 functions on the system. These functions might be provided in the standard C library or externally in the form of an additional library.

Imported Targets

This module provides the following Imported Targets:

Target encapsulating the iconv usage requirements, available only if iconv is found.

Result Variables

This module defines the following variables:

Boolean indicating if the iconv support was found.
The include directories containing the iconv headers.
The iconv libraries to be linked.
Added in version 3.21.

The version of iconv found (x.y).

NOTE:

Some libiconv implementations don't embed the version in their header files. In this case the variables Iconv_VERSION* will be empty.


Added in version 3.21.

The major version of iconv.

Added in version 3.21.

The minor version of iconv.

A boolean variable indicating whether iconv support is stemming from the C standard library or not. Even if the C library provides iconv(), the presence of an external libiconv implementation might lead to this being false.

Cache Variables

The following cache variables may also be set:

The directory containing the iconv headers.
The iconv library (if not implicitly given in the C library).

NOTE:

On POSIX platforms, iconv might be part of the C library and the cache variables Iconv_INCLUDE_DIR and Iconv_LIBRARY might be empty.


Examples

Finding iconv and linking it to a project target:

find_package(Iconv)
target_link_libraries(project_target PRIVATE Iconv::Iconv)


FindIcotool

Finds icotool, command-line program for converting and creating Win32 icon and cursor files.

Result Variables

This module defines the following variables:

True if icotool has been found. For backward compatibility, the ICOTOOL_FOUND variable is also set to the same value.
The version of icotool found.

Cache Variables

The following cache variables may also be set:

The full path to the icotool tool.

Examples

Finding icotool and executing it in a process to create .ico icon from the source .png image located in the current source directory:

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.

Added in version 3.11: Support for static libraries on Windows.

Components

This module supports the following components:

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 will be automatically selected.
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 will be automatically selected.
Finds the ICU Stream and I/O (Unicode stdio) library.
Finds the deprecated ICU Layout Engine library, which has been removed as of ICU version 58.
Finds the ICU Layout Extensions Engine library, used for paragraph layout.
Finds the ICU test suits.
Finds the ICU Tool Utility library.
Finds the base ICU Common and Data libraries. This library is required by all other ICU libraries and is recommended to include when working with ICU components.

At least one component should be specified for this module to successfully find ICU:

find_package(ICU COMPONENTS <components>...)


Imported Targets

This module provides the following Imported Targets:

ICU::<component>

Target encapsulating the usage requirements for the specified ICU component, available only if that component is found. The <component> should be written in lowercase, as listed above. For example, use ICU::i18n for the Internationalization library.


Result Variables

This module defines the following variables:

Boolean indicating whether the main programs and libraries were found.
The include directories containing the ICU headers.
Component libraries to be linked.
The version of the ICU release found.

ICU programs are defined in the following variables:

The path to the gencnval executable.
The path to the icuinfo executable.
The path to the genbrk executable.
The path to the icu-config executable.
The path to the genrb executable.
The path to the gendict executable.
The path to the derb executable.
The path to the pkgdata executable.
The path to the uconv executable.
The path to the gencfu executable.
The path to the makeconv executable.
The path to the gennorm2 executable.
The path to the genccode executable.
The path to the gensprep executable.
The path to the icupkg executable.
The path to the gencmn executable.

ICU component libraries are defined in the following variables:

Boolean indicating whether the ICU component was found; The <COMPONENT> should be written in uppercase.
Libraries for component; The <COMPONENT> should be written in uppercase.

ICU datafiles are defined in the following variables:

The path to the Makefile.inc file.
The path to the pkgdata.inc file.

Cache Variables

The following cache variables may also be set:

The path to executable <PROGRAM>; The <PROGRAM> should be written in uppercase. These variables correspond to the ICU program result variables listed above.
The directory containing the ICU headers.
The library for the ICU component. The <COMPONENT> should be written in uppercase.

Hints

This module reads hints about search results from:

The root of the ICU installation. The environment variable ICU_ROOT may also be used; the ICU_ROOT variable takes precedence.

NOTE:

In most cases, none of the above variables will need to be set, unless multiple versions of ICU are available and a specific version is required.


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, a software suite for displaying, converting, and manipulating raster images.

Added in version 3.9: Support for ImageMagick 7.

Components

This module supports components and searches for a set of ImageMagick tools. Typical components include the names of ImageMagick executables, but are not limited to the following (future versions of ImageMagick may provide additional components not listed here):

  • animate
  • compare
  • composite
  • conjure
  • convert
  • display
  • identify
  • import
  • mogrify
  • montage
  • stream

There are also components for the following ImageMagick APIs:

Finds the ImageMagick C++ API.
Finds the ImageMagick MagickWand C API.
Finds the ImageMagick MagickCore low-level C API.

Components can be specified using the find_package() command:

find_package(ImageMagick [COMPONENTS <components>...])


If no components are specified, the module only searches for the ImageMagick executable directory.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.26.

Target encapsulating the ImageMagick C++ API usage requirements, available if ImageMagick C++ is found.

Added in version 3.26.

Target encapsulating the ImageMagick MagickWand C API usage requirements, available if MagickWand is found.

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:

Boolean indicating whether ImageMagick and all its requested components are found.
The version of ImageMagick found.

NOTE:

Version detection is available only for ImageMagick 6 and later.


All include directories needed to use ImageMagick.
Libraries needed to link against to use ImageMagick.
Added in version 3.26.

Compile options of all libraries.

Boolean indicating whether the ImageMagick <component> is found.
The full path to <component> executable.
Include directories containing headers needed to use the ImageMagick <component>.
Added in version 3.26.

Compile options of the ImageMagick <component>.

Added in version 3.31.

Libraries needed to link against to use the ImageMagick <component>.


Cache Variables

The following cache variables may also be set:

The full path to directory containing ImageMagick executables.

Examples

Finding ImageMagick with its component Magick++ and linking it to a project target:

find_package(ImageMagick COMPONENTS Magick++)
target_link_libraries(example PRIVATE ImageMagick::Magick++)


FindIntl

Added in version 3.2.

Finds internationalization support that includes message translation functions such as gettext(). These functions originate from the GNU libintl library, which is part of the GNU gettext utilities, but may also be provided by the standard C library.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.20.

Target encapsulating the Intl usage requirements, available if Intl is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the Intl is found.
Include directories containing headers needed to use Intl.
The libraries needed to link against to use Intl.
Added in version 3.21.

The version of the found Intl implementation or library, in the format x.y.z.

NOTE:

Some Intl implementations don't embed the version in their header files. In this case the variables Intl_VERSION* will be empty.


Added in version 3.21.

The major version of Intl found.

Added in version 3.21.

The minor version of Intl found.

Added in version 3.21.

The patch version of Intl found.


Cache Variables

The following cache variables may also be set:

The directory containing the libintl.h header file.
The path to the Intl library (if any).
Added in version 3.20.

Boolean indicating whether the found Intl functionality is provided by the standard C library rather than a separate libintl library.


NOTE:

On some platforms, such as Linux with GNU libc, the gettext functions are present in the C standard library and libintl is not required. The Intl_LIBRARY and Intl_INCLUDE_DIR will be empty in this case.


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 for handling image data in a variety of formats, such as the JPEG-2000.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.22.

Target encapsulating the JasPer library usage requirements, available only if the library is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the JasPer is found. For backward compatibility, the JASPER_FOUND variable is also set to the same value.
Added in version 3.22.

The include directories needed to use the JasPer library.

The libraries needed to use JasPer.
The version of JasPer found.

Cache Variables

The following cache variables may also be set:

The directory containing the jasper/jasper.h and other headers needed to use the JasPer library.
The path to the release (optimized) variant of the JasPer library.
The path to the debug variant of the JasPer library.

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 the Java installation and determines its runtime tools and development components.

Added in version 3.10: Support for Java 9+ version parsing.

Components

This module supports the following components:

Finds the Java Runtime Environment used to execute Java byte-compiled applications.
Finds development tools (java, javac, javah, jar, and javadoc). Specifying this component also implies the Runtime component.
Added in version 3.4.

Finds the Interface Description Language (IDL) to Java compiler.

Added in version 3.4.

Finds the signer and verifier tool for Java Archive (JAR) files.


Components can optionally be specified using the standard syntax with:

find_package(Java [COMPONENTS <components>...])


If no COMPONENTS are specified, the module searches for the Runtime component by default.

Result Variables

This module defines the following variables:

Boolean indicating whether Java with all specified components is found.
Boolean indicating whether the <component> is found.
Version of Java found. This is set to: <major>[.<minor>[.<patch>[.<tweak>]]].
The major version of Java found.
The minor version of Java found.
The patch version of Java found.
The tweak version of Java found (part after the underscore character _).
Version of Java found, e.g., 1.6.0_12.

NOTE:

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.




Cache Variables

The following cache variables may also be set:

The full path to the Java runtime.
The full path to the Java compiler.
The full path to the Java header generator.
The full path to the Java documentation generator.
Added in version 3.4.

The full path to the Java idl compiler.

The full path to the Java archiver.
Added in version 3.4.

The full path to the Java jar signer.


Hints

This module accepts the following variables:

The caller can set this variable to specify the installation directory of Java explicitly.

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 (if Java is not found, processing stops with an error message):

find_package(Java 1.8 REQUIRED)


Specifying the needed Java components 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.

JNI enables Java code running in a Java Virtual Machine (JVM) or Dalvik Virtual Machine (DVM) on Android to call and be called by native applications and libraries written in other languages such as C and C++.

This module finds if 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 using Android NDK, the corresponding package version is reported and a specific release can be requested. At Android API level 31 and above, the additional NativeHelper component can be requested. NativeHelper is also exposed as an implicit dependency of the JVM component (only if this does not cause a conflict) which provides a uniform access to JVM functions.

Components

This module supports optional components, which can be specified with the find_package() command:

find_package(JNI [COMPONENTS <components>...])


Supported components include:

Added in version 3.24.

Finds the Java Abstract Window Toolkit (AWT).

Added in version 3.24.

Finds the Java Virtual Machine (JVM).

Added in version 3.24.

Finds the NativeHelper library on Android (libnativehelper.so), which exposes JVM functions such as JNI_CreateJavaVM().


If no components are specified, the module defaults are:

  • When targeting Android with API level 31 and above: module looks for the NativeHelper component. For other Android API levels, components are by default not set.
  • When targeting other systems: module looks for AWT and JVM components.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.24.

Main target encapsulating all JNI usage requirements, available if jni.h is found.

Added in version 3.24.

Target encapsulating the Java AWT Native Interface (JAWT) library usage requirements, available if the AWT component is found.

Added in version 3.24.

Target encapsulating the Java Virtual Machine (JVM) library usage requirements, available if component JVM is found.

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:

Boolean indicating whether the JNI is found.
Added in version 3.24.

Boolean indicating whether the <component> is found.

Full Android NDK package version (including suffixes such as -beta3 and -rc1) or undefined otherwise.
Added in version 3.24.

Android NDK major version or undefined otherwise.

Added in version 3.24.

Android NDK minor version or undefined otherwise.

Added in version 3.24.

Android NDK patch version or undefined otherwise.

The include directories needed to use the JNI.
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:

The directory containing the jni.h header.
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.
The directory containing the jawt.h header.
The path to the Java AWT Native Interface (JAWT) library.
The path to the Java Virtual Machine (JVM) library.

Hints

This module accepts the following variables:

The caller can set this variable to specify the installation directory of Java explicitly.

Examples

Finding JNI and linking it to a project target:

find_package(JNI)
target_link_libraries(project_target PRIVATE JNI::JNI)


Finding JNI with 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:

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).

Changed in version 3.12: Debug and Release JPEG library variants are now found separately.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.12.

Target encapsulating the JPEG library usage requirements. It is available only when JPEG is found.


Result Variables

This module sets the following variables:

Boolean indicating whether the JPEG is found.
Include directories containing headers needed to use JPEG.
Libraries needed to link to JPEG.
Added in version 3.12.

The version of the JPEG library found.


Cache Variables

The following cache variables may also be set:

Directory containing the jpeglib.h and related header files.
Added in version 3.12.

Path to the release (optimized) variant of the JPEG library.

Added in version 3.12.

Path to the debug variant of the JPEG library.


Obsolete Variables

The following legacy variables are provided for backward compatibility:

Changed in version 3.12: This variable has been superseded by the JPEG_LIBRARY_RELEASE and JPEG_LIBRARY_DEBUG variables.

Path to the JPEG library.


Examples

Finding 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.


This module finds KDE 3 include directories, libraries, and KDE-specific preprocessor tools. It 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:

Boolean indicating whether KDE 3 is found.
Compiler definitions required for compiling KDE 3 software.
The KDE and the Qt include directories, for use with the target_include_directories() command.
The directory containing the installed KDE 3 libraries, for use with the target_link_directories() command.
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:

The directory containing KDE 3 header files.
The path to the dcopidl executable.
The path to the dcopidl2cpp executable.
The path to the kconfig_compiler executable.

Hints

This module accepts the following variables:

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:

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.


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.


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.


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.


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.


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.


Creates and installs a libtool file:

kde3_install_libtool_file(<target>)


This command creates and installs a basic libtool file for the given target <target>.


Adds KDE executable:

kde3_add_executable(<name> <sources>...)


This command is functionally identical to the built-in add_executable() command. It was originally intended to support additional features in future versions of this module.


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.

If the WITH_PREFIX option is given, the resulting plugin name will be prefixed with lib. Otherwise, no prefix is added.


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.


Examples

Finding KDE 3:

find_package(KDE3)


FindKDE4

Find KDE4 and provide all necessary variables and macros to compile software for it. It looks for KDE 4 in the following directories in the given order:

CMAKE_INSTALL_PREFIX
KDEDIRS
/opt/kde4


Please look in FindKDE4Internal.cmake and KDE4Macros.cmake for more information. They are installed with the KDE 4 libraries in $KDEDIRS/share/apps/cmake/modules/.

Author: Alexander Neundorf <neundorf@kde.org>

FindLAPACK

Find Linear Algebra PACKage (LAPACK) library

This module finds an installed Fortran library that implements the LAPACK linear-algebra interface.

At least one of the C, CXX, or Fortran languages must be enabled.

Input Variables

The following variables may be set to influence this module's behavior:

if ON use static linkage
Set to one of the BLAS/LAPACK Vendors to search for BLAS only from the specified vendor. If not set, all vendors are considered.
if ON tries to find the BLAS95/LAPACK95 interfaces
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

Added in version 3.25.

If set, the pkg-config method will look for this module name instead of just lapack.

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.
Search for any BLAS/LAPACK. Most likely, a BLAS/LAPACK with 32-bit integer interfaces will be found.

Added in version 4.1.

Specify the BLAS/LAPACK threading model:

Sequential model
OpenMP model
Search for any BLAS/LAPACK, if both are available most likely OMP will be found.

This is currently only supported by NVIDIA NVPL.


Imported Targets

This module defines the following IMPORTED targets:

Added in version 3.18.

The libraries to use for LAPACK, if found.


Result Variables

This module defines the following variables:

library implementing the LAPACK interface is found
uncached list of required linker flags (excluding -l and -L).
uncached list of libraries (using full path name) to link against to use LAPACK
uncached list of libraries (using full path name) to link against to use LAPACK95
library implementing the LAPACK95 interface is found

Intel MKL

To use the Intel MKL implementation of LAPACK, a project must enable at least one of the C or CXX languages. Set BLA_VENDOR to an Intel MKL variant either on the command-line as -DBLA_VENDOR=Intel10_64lp or in project code:

set(BLA_VENDOR Intel10_64lp)
find_package(LAPACK)


In order to build a project using Intel MKL, and end user must first establish an Intel MKL environment. See the FindBLAS module section on Intel MKL for details.

FindLATEX

Finds LaTeX compiler and Latex-related software like BibTeX. LaTeX is a typesetting system for the production of technical and scientific documentation.

Components

Added in version 3.2.

Components can be optionally specified using a standard CMake syntax:

find_package(LATEX [COMPONENTS <component>...])


Supported components are:

Finds the PdfLaTeX compiler.
Finds the XeLaTeX compiler.
Finds the LuaLaTeX compiler.
Finds the BibTeX compiler.
Finds the Biber compiler.
Finds the MakeIndex compiler.
Find the xindy compiler.
Finds the DVI-to-PostScript (DVIPS) converter.
Finds the DVIPDF converter.
Finds the the PS2PDF converter.
Finds the PDF-to-PostScript converter.
Finds the converter for converting LaTeX documents to HTML.
Finds htlatex compiler.

Result Variables

This module defines the following variables:

Boolean indicating whether the LaTex compiler and all its required components are found.
Boolean indicating whether the LaTeX <component> is found.

Cache Variables

The following cache variables may also be set:

The path to the LaTeX compiler.
The path to the PdfLaTeX compiler.
The path to the XeLaTeX compiler.
The path to the LuaLaTeX compiler.
The path to the BibTeX compiler.
The path to the Biber compiler.
The path to the MakeIndex compiler.
The path to the xindy compiler.
The path to the DVIPS converter.
The path to the DVIPDF converter.
The path to the PS2PDF converter.
The path to the pdftops converter.
The path to the LaTeX2Html converter.
The path to the htlatex compiler.

Examples

Finding LaTeX in a project:

find_package(LATEX)


Finding LaTeX compiler and specifying which additional LaTeX components are required for LaTeX to be considered found:

find_package(LATEX COMPONENTS PDFLATEX)
if(LATEX_FOUND)

execute_process(COMMAND ${LATEX_COMPILER} ...)
execute_process(COMMAND ${PDFLATEX_COMPILER} ...) endif()


Or finding LaTeX compiler and specifying multiple components:

find_package(LATEX COMPONENTS BIBTEX PS2PDF)
if(LATEXT_FOUND)

# ... endif()


FindLibArchive

Finds the libarchive library and include directories. Libarchive is a multi-format archive and compression library.

Import Targets

This module defines the following Imported Targets:

Added in version 3.17.

A target for linking against libarchive.


Result Variables

This module defines the following variables:

Boolean indicating whether libarchive was found.
Include search path for using libarchive.
Libraries to link against libarchive.
A 3-component version string (major.minor.patch) of libarchive 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 will be set only for libarchive versions 3.1 and earlier. In CMake 3.6 and newer, this variable will be set for all libarchive versions.


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 which handles input devices in Wayland compositors and provides a generic X.Org input driver.

Imported Targets

This module provides the following Imported Targets:

Target encapsulating the libinput library usage requirements, available only if library is found.

Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) libinput library is found.
The version of the libinput found.
The libraries to link against to use the libinput library.
The include directories containing headers needed to use the libinput library.
Compile options needed to use the libinput library. These can be passed to the target_compile_options() command, when not using the Libinput::Libinput imported target.

Examples

Finding the libinput library and linking it to a project target:

find_package(Libinput)
target_link_libraries(project_target PRIVATE Libinput::Libinput)


FindLibLZMA

Finds the data compression library that implements the LZMA (Lempel–Ziv–Markov chain algorithm) - liblzma.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.14.

Target encapsulating the liblzma library usage requirements, available only if liblzma is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the liblzma is found. For backward compatibility, the LIBLZMA_FOUND variable is also set to the same value.
Include directories containing headers needed to use liblzma.
Libraries needed to link against to use liblzma.
Added in version 3.26.

The version of liblzma found (available as a string, for example, 5.0.3).


Cache Variables

The following cache variables may also be set:

Boolean sanity check result indicating whether the lzma_auto_decoder() function (automatic decoder functionality) is found in liblzma (required).
Boolean sanity check result indicating whether the lzma_easy_encoder() function (basic encoder API) is found in liblzma (required).
Boolean sanity check result indicating whether the lzma_lzma_preset() function (preset compression configuration) is found in liblzma (required).

Legacy Variables

The following variables are provided for backward compatibility:

The major version of liblzma found.
The minor version of liblzma found.
The patch version of liblzma found.
The version of liblzma found.

Changed in version 3.26: Superseded by LIBLZMA_VERSION.


Examples

Finding the liblzma library and linking it to a project target:

find_package(LibLZMA)
target_link_libraries(project_target PRIVATE LibLZMA::LibLZMA)


FindLibXml2

Finds the XML processing library (libxml2).

Imported Targets

This module provides the following Imported Targets:

Added in version 3.12.

Target encapsulating the libxml2 library usage requirements, available only if library is found.

Added in version 3.17.

Target encapsulating the xmllint command-line executable, available only if xmllint executable is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the libxml2 library is found.
Include directories needed to use the libxml2 library.
Libraries needed to link against to use the libxml2 library.
The compiler switches required for using libxml2.
The version of the libxml2 found.

Cache Variables

The following cache variables may also be set:

The include directory containing libxml2 headers.
The path to the libxml2 library.
The path to the XML checking tool xmllint coming with libxml2.

Examples

Finding the libxml2 library and linking it to a project target:

find_package(LibXml2)
target_link_libraries(project_target PRIVATE LibXml2::LibXml2)


FindLibXslt

Finds the XSL Transformations, Extensible Stylesheet Language Transformations (XSLT) library (libxslt).

Imported Targets

Added in version 3.18.

This module provides the following Imported Targets:

Target encapsulating the usage requirements of the libxslt library. This target is available only if libxslt is found.
Target encapsulating the usage requirements for the libexslt library. Part of the libxslt package, libexslt provides optional extensions to XSLT on top of libxslt. This target is available only if the main libxslt library is found.
Target encapsulating the command-line XSLT processor (xsltproc). This tool, part of the libxslt package, applies XSLT stylesheets to XML documents as a command-line alternative to the libxslt library. This target is available only if the xsltproc executable is found.

Result Variables

This module sets the following variables:

Boolean indicating whether the libxslt is found. For backward compatibility, the LIBXSLT_FOUND variable is also set to the same value.
Libraries needed to link to libxslt.
Compiler switches required for using libxslt.
Version of libxslt found.
Libraries needed when linking against the exslt library. These are available and needed only when using exslt library.

Cache Variables

The following cache variables may also be set:

Directory containing libxslt/xslt.h and other libxslt header files.
Added in version 3.18.

Directory containing libexslt/exslt.h and other exslt-related headers. These are needed only when using exslt (extensions to XSLT).

Full path to the XSLT processor executable xsltproc if found. This path is optional.

Examples

Finding libxslt library and linking it to a project target:

find_package(LibXslt)
target_link_libraries(foo PRIVATE LibXslt::LibXslt)


When project also needs the extensions to XSLT (exslt) library, both targets should be linked:

find_package(LibXslt)
target_link_libraries(foo PRIVATE LibXslt::LibXslt LibXslt::LibExslt)


Example, how to use XSLT processor in a custom command build rule:

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 (Linux Trace Toolkit: next generation) user space tracing library (LTTng-UST).

Imported Targets

This module defines the following Imported Targets:

Target providing the LTTng-UST library usage requirements. This target is available only when LTTng-UST is found.

Result Variables

This module sets the following variables:

Boolean indicating whether the LTTng-UST library is found. For backward compatibility, the LTTNGUST_FOUND variable is also set to the same value.
The LTTng-UST version.
TRUE if the tracef() API is available in the system's LTTng-UST.
TRUE if the tracelog() API is available in the system's LTTng-UST.

Cache Variables

The following cache variables may also be set:

The LTTng-UST include directories.
The libraries needed to use LTTng-UST.

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. Lua is a embeddable scripting language.

Added in version 3.18: Support for Lua 5.4.

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>


This is because, the location of Lua headers may differ across platforms and may exist in locations other than lua/.

Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) Lua is found. For backward compatibility, the LUA_FOUND variable is also set to the same value.
The version of Lua found.
The major version of Lua found.
The minor version of Lua found.
The patch version of Lua found.
Libraries needed to link against to use Lua. This list includes both lua and lualib libraries.

Cache Variables

The following cache variables may also be set:

The directory containing the Lua header files, such as lua.h, lualib.h, and lauxlib.h, needed to use Lua.

Examples

Finding the Lua library and creating an interface imported target that encapsulates its usage requirements for linking to a project target:

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 specifically for Lua version branch 5.0, which is obsolete and not maintained anymore. In new code use the latest supported Lua version and the version-agnostic module FindLua instead.


Finds the Lua library. 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>


This is because, the location of Lua headers may differ across platforms and may exist in locations other than lua/.

Result Variables

This module defines the following variables:

Boolean indicating whether Lua is found. For backward compatibility, the LUA50_FOUND variable is also set to the same value.

Cache Variables

The following cache variables may also be set:

The directory containing the Lua header files, such as lua.h, lualib.h, and lauxlib.h, needed to use Lua.
Libraries needed to link against to use Lua. This list includes both lua and lualib libraries.

Examples

Finding the Lua 5.0 library and creating an interface imported target that encapsulates its usage requirements for linking to a project target:

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 to find Lua in version-agnostic way.

FindLua51

NOTE:

This module is 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 module FindLua instead.


Finds the Lua library. 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>


This is because, the location of Lua headers may differ across platforms and may exist in locations other than lua/.

Result Variables

This module defines the following variables:

Boolean indicating whether Lua is found. For backward compatibility, the LUA51_FOUND variable is also set to the same value.
The version of Lua found.

Cache Variables

The following cache variables may also be set:

The directory containing the Lua header files, such as lua.h, lualib.h, and lauxlib.h, needed to use Lua.
Libraries needed to link against to use Lua.

Examples

Finding the Lua 5.1 library and creating an interface imported target that encapsulates its usage requirements for linking to a project target:

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 to find Lua in version-agnostic way.

FindMatlab

Finds Matlab or Matlab Compiler Runtime (MCR) and provides Matlab tools, libraries and compilers to CMake.

This package primary purpose is to find the libraries associated with Matlab or the MCR in order to be able to build Matlab extensions (mex files). It can also be used:

  • to run specific commands in Matlab in case Matlab is available
  • for declaring Matlab unit test
  • to retrieve various information from Matlab (mex extensions, versions and release queries, ...)

Added in version 3.12: Added Matlab Compiler Runtime (MCR) support.

The module supports the following components:

  • ENG_LIBRARY and MAT_LIBRARY: respectively the ENG and MAT libraries of Matlab
  • MAIN_PROGRAM 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 the MEX compiler.
  • MCC_COMPILER the MCC compiler, included with the Matlab Compiler add-on.
  • SIMULINK the Simulink environment.

Added in version 3.7: Added the MAT_LIBRARY component.

Added in version 3.13: Added the ENGINE_LIBRARY, DATAARRAY_LIBRARY and MCC_COMPILER components.

Changed in version 3.14: Removed the MX_LIBRARY, ENGINE_LIBRARY and DATAARRAY_LIBRARY components. These libraries are found unconditionally.

Added in version 3.30: Added support for specifying a version range to find_package() and added support for specifying REGISTRY_VIEW to find_package(), matlab_extract_all_installed_versions_from_registry() and matlab_get_all_valid_matlab_roots_from_registry(). The default behavior remained unchanged, by using the registry view TARGET.

NOTE:

The version given to the find_package() directive 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() provide a mapping between the release name and the version.


The variable Matlab_ROOT_DIR may be specified in order to give the path of the desired Matlab version. Otherwise, the behavior is platform specific:

  • 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.

Additional information is provided when MATLAB_FIND_DEBUG is set. 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.

The mapping of the release names and the version of Matlab is performed by defining pairs (name, version). The variable MATLAB_ADDITIONAL_VERSIONS may be provided before the call to the find_package() in order to handle additional versions.

A Matlab scripts can be added to the set of tests using the matlab_add_unit_test(). By default, the Matlab unit test framework will be used (>= 2013a) to run this script, but regular .m files returning an exit code can be used as well (0 indicating a success).

Module Input Variables

Users or projects may set the following variables to configure the module behavior:

Added in version 3.25.

Default value for Matlab_ROOT_DIR, the root of the Matlab installation.

Matlab_ROOT_DIR
The root of the Matlab installation.
MATLAB_FIND_DEBUG
outputs debug information
MATLAB_ADDITIONAL_VERSIONS
additional versions of Matlab for the automatic retrieval of the installed versions.

Imported Targets

Added in version 3.22.

This module defines the following IMPORTED targets:

The mex library, always available for MATLAB installations. Available for MCR installations if provided by MCR.
The mx library of Matlab (arrays), always available for MATLAB installations. Available for MCR installations if provided by MCR.
Matlab engine library. Available only if the ENG_LIBRARY component is requested.
Matlab matrix library. Available only if the MAT_LIBRARY component is requested.
Matlab C++ engine library, always available for MATLAB R2018a and newer. Available for MCR installations if provided by MCR.
Matlab C++ data array library, always available for MATLAB R2018a and newer. Available for MCR installations if provided by MCR.

Variables defined by the module

Result variables

TRUE if the Matlab installation is found, FALSE otherwise. All variable below are defined if Matlab is found.
Added in version 3.27.

the numerical version (e.g. 23.2.0) of Matlab found. Not to be confused with Matlab release name (e.g. R2023b) that can be obtained with matlab_get_release_name_from_version().

Matlab_ROOT_DIR
the final root of the Matlab installation determined by the FindMatlab module.
the Matlab binary program. Available only if the component MAIN_PROGRAM is given in the find_package() directive.
the path of the Matlab libraries headers
library for mex, always available for MATLAB installations. Available for MCR installations if provided by MCR.
mx library of Matlab (arrays), always available for MATLAB installations. Available for MCR installations if provided by MCR.
Matlab engine library. Available only if the component ENG_LIBRARY is requested.
Matlab matrix library. Available only if the component MAT_LIBRARY is requested.
Added in version 3.13.

Matlab C++ engine library, always available for MATLAB R2018a and newer. Available for MCR installations if provided by MCR.

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.

the whole set of libraries of Matlab
the mex compiler of Matlab. Currently not used. Available only if the component MEX_COMPILER is requested.
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.


Cached variables

the extension of the mex files for the current platform (given by Matlab).
Matlab_ROOT_DIR
the location of the root of the Matlab installation found. If this value is changed by the user, the result variables are recomputed.

Provided commands

returns the version from the Matlab release name
returns the release name from the Matlab version
adds a target compiling a MEX file.
adds a Matlab unit test file as a test to the project.
parses the registry for all Matlab versions. Available on Windows only. The part of the registry parsed is dependent on the host processor
returns all the possible Matlab or MCR paths, according to a previously given list. Only the existing/accessible paths are kept. This is mainly useful for the searching all possible Matlab installation.
returns the suffix to be used for the mex files (platform/architecture dependent)
returns the version of Matlab/MCR, given the full directory of the Matlab/MCR installation path.

Known issues

By default, every symbols 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 your 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.

in case your 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).

Reference

The root folder of the Matlab installation. If set before the call to find_package(), the module will look for the components in that path. If not set, then an automatic search of Matlab will be performed. If set, it should point to a valid version of Matlab.

If set, the lookup of Matlab and the intermediate configuration steps are outputted to the console.

If set, specifies additional versions of Matlab that may be looked for. The variable should be a list of strings, organized by pairs of release name and versions, such as follows:

set(MATLAB_ADDITIONAL_VERSIONS

"release_name1=corresponding_version1"
"release_name2=corresponding_version2"
...
)


Example:

set(MATLAB_ADDITIONAL_VERSIONS

"R2013b=8.2"
"R2013a=8.1"
"R2012b=8.0")


The order of entries in this list matters when several versions of Matlab are installed. The priority is set according to the ordering in this list.


matlab_get_version_from_release_name(release version)


  • Input: release is the release name (e.g. R2023b)
  • Output: version is the version of Matlab (e.g. 23.2.0)

Returns the version of Matlab from a release name

NOTE:

This command provides correct versions mappings for Matlab but not MCR.



matlab_get_release_name_from_version(version release_name)


  • Input: version is the version of Matlab (e.g. 23.2.0)
  • Output: release_name is the release name (R2023b)

Returns the release name from the version of Matlab

NOTE:

This command provides correct version mappings for Matlab but not MCR.



This function parses the Windows registry and finds the Matlab versions that are installed. The found versions are stored in a given <versions-var>.
Added in version 3.30.

  • Output: <versions-var> is a list of all the versions of Matlab found
  • Input: REGISTRY_VIEW Optional registry view to use for registry interaction. The argument is passed (or omitted) to cmake_host_system_information() without further checks or modification.


  • Input: win64 is a boolean to search for the 64 bit version of Matlab. Set to ON to use the 64bit registry view or OFF to use the 32bit registry view. If finer control is needed, see signature above.
  • Output: <versions-var> is a list of all the versions of Matlab found


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).

NOTE:

Only the versions are provided. No check is made over the existence of the installation referenced in the registry,



Populates the Matlab root with valid versions of Matlab or Matlab Runtime (MCR). The returned matlab_roots is organized in triplets (type,version_number,matlab_root_path), where type indicates either MATLAB or MCR.

matlab_get_all_valid_matlab_roots_from_registry(matlab_versions matlab_roots [REGISTRY_VIEW view])


  • Input: matlab_versions of each of the Matlab or MCR installations
  • Output: matlab_roots location of each of the Matlab or MCR installations
  • Input: REGISTRY_VIEW Optional registry view to use for registry interaction. The argument is passed (or omitted) to cmake_host_system_information() without further checks or modification.

Added in version 3.30: The optional REGISTRY_VIEW argument was added to provide a more precise interface on how to interact with the Windows Registry.


Returns the extension of the mex files (the suffixes). This function should not be called before the appropriate Matlab root has been found.

matlab_get_mex_suffix(matlab_root mex_suffix)


  • Input: matlab_root root of Matlab/MCR install e.g. Matlab_ROOT_DIR
  • Output: mex_suffix variable name in which the suffix will be returned.


This function runs Matlab program specified on arguments and extracts its version. If the path provided for the Matlab installation points to an MCR installation, the version is extracted from the installed files.

matlab_get_version_from_matlab_run(matlab_binary_path matlab_list_versions)


  • Input: matlab_binary_path path of the matlab binary executable
  • Output: matlab_list_versions the version extracted from Matlab


Adds a Matlab unit test to the test set of cmake/ctest. 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 function 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 (eg. CONFIGURATION <config> ...).

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 path1 [path2 ...]]
[MATLAB_ADDITIONAL_STARTUP_OPTIONS option1 [option2 ...]]
[TEST_ARGS arg1 [arg2 ...]]
[NO_UNITTEST_FRAMEWORK]
)


Function Parameters:

NAME
name of the unittest in ctest.
the matlab unittest file. Its path will be automatically added to the Matlab path.
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.
Matlab script command to be ran before the file containing the test (eg. GPU device initialization based on CMake variables).
the test timeout in seconds. Defaults to 180 seconds as the Matlab unit test may hang.
a list of paths to add to the Matlab path prior to running the unit test.
a list of additional option in order to run Matlab from the command line. -nosplash -nodesktop -nodisplay are always added.
Additional options provided to the add_test command. These options are added to the default options (eg. "CONFIGURATIONS Release")
when set, indicates that the test should not use the unittest framework of Matlab (available for versions >= R2013a).
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.


Adds a Matlab MEX target. This commands 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.

matlab_add_mex(

NAME <name>
[EXECUTABLE | MODULE | SHARED]
SRC src1 [src2 ...]
[OUTPUT_NAME output_name]
[DOCUMENTATION file.txt]
[LINK_TO target1 target2 ...]
[R2017b | R2018a]
[EXCLUDE_FROM_ALL]
[NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES]
[...] )


Function Parameters:

NAME
name of the target.
list of source files.
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.
if given, overrides the default name. The default name is the name of the target without any prefix and with Matlab_MEX_EXTENSION suffix.
if given, the file file.txt 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.
Added in version 3.14.

May be given to specify the version of the C API to use: R2017b specifies the traditional (separate complex) C API, and corresponds to the -R2017b flag for the mex command. R2018a specifies the new interleaved complex C API, and corresponds to the -R2018a flag for the mex command. Ignored if MATLAB version prior to R2018a. Defaults to R2017b.

Added in version 3.7.

May be given to specify the type of library to be created.

Added in version 3.7.

May be given to create an executable instead of a library. If no type is given explicitly, the type is SHARED.

This option has the same meaning as for EXCLUDE_FROM_ALL and is forwarded to add_library() or add_executable() commands.
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.


The documentation file is not processed and should be in the following format:

% This is the documentation
function ret = mex_target_output_name(input1)



FindMFC

Finds the native Microsoft Foundation Class Library (MFC) for developing MFC applications on Windows.

NOTE:

MFC is an optional component in Visual Studio and must be installed separately for this module to succeed.


Once the MFC libraries and headers are found, no additional manual linking is needed, as they are part of the development environment.

Result Variables

This module defines the following variables:

Boolean indicating whether MFC support is 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.

Result Variables

This module defines the following variables:

Boolean indicating whether the Motif was found. For backward compatibility, the MOTIF_FOUND variable is also set to the same value.

Cache Variables

The following cache variables may also be set:

Libraries needed to link to Motif.
Include directories needed to use Motif.

Examples

Finding Motif:

find_package(Motif)


FindMPEG

Finds the native MPEG library (libmpeg2).

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.



Result Variables

This module defines the following variables:

Boolean indicating whether the libmpeg2 library is found.
Libraries needed to link against to use libmpeg2.

Cache Variables

The following cache variables may be also set:

The directory containing the mpeg2.h and related headers needed to use libmpeg2 library.
The path to the libmpeg2 library.
The path to the vo (Video Out) library.

Examples

Finding libmpeg2 library and creating an imported interface target for linking it to a project target:

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

Finds the native MPEG2 library (libmpeg2).

NOTE:

Depending on how the native libmpeg2 library is 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.


Result Variables

This module defines the following variables:

Boolean indicating whether the libmpeg2 library is found.
Libraries needed to link against to use libmpeg2.

Cache Variables

The following cache variables may be also set:

The directory containing the mpeg2.h and related headers needed to use libmpeg2 library.
The path to the libmpeg2 library.
The path to the vo (Video Out) library.

Examples

Finding libmpeg2 library and creating an imported interface target for linking it to a project target:

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

Find a Message Passing Interface (MPI) implementation.

The Message Passing Interface (MPI) is a library used to write high-performance distributed-memory parallel applications, and is typically deployed on a cluster. MPI is a standard interface (defined by the MPI forum) for which many implementations are available.

Added in version 3.10: Major overhaul of the module: many new variables, per-language components, support for a wider variety of runtimes.

Variables for using MPI

The module exposes the components C, CXX, MPICXX and Fortran. Each of these controls the various MPI languages to search for. The difference between CXX and MPICXX is that CXX refers to the MPI C API being usable from C++, whereas MPICXX refers to the MPI-2 C++ API that was removed again in MPI-3.

Depending on the enabled components the following variables will be set:

Variable indicating that MPI settings for all requested languages have been found. If no components are specified, this is true if MPI settings for all enabled languages were detected. Note that the MPICXX component does not affect this variable.
Minimal version of MPI detected among the requested languages, or all enabled languages if no components were specified.

This module will set the following variables per language in your project, where <lang> is one of C, CXX, or Fortran:

Variable indicating the MPI settings for <lang> were found and that simple MPI test programs compile with the provided settings.
MPI compiler for <lang> if such a program exists.
Compilation options for MPI programs in <lang>, given as a ;-list.
Compilation definitions for MPI programs in <lang>, given as a ;-list.
Include path(s) for MPI header.
Linker flags for MPI programs.
All libraries to link MPI programs against.

Added in version 3.9: Additionally, the following IMPORTED targets are defined:

Target for using MPI from <lang>.

The following variables indicating which bindings are present will be defined:

Variable indicating whether the MPI-2 C++ bindings are present (introduced in MPI-2, removed with MPI-3).
True if the Fortran 77 header mpif.h is available.
True if the Fortran 90 module mpi can be used for accessing MPI (MPI-2 and higher only).
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.

Major version of MPI implemented for <lang> by the MPI distribution.
Minor version of MPI implemented for <lang> by the MPI distribution.
MPI version 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.

For running MPI programs, the module sets the following variables

Executable for running MPI programs, if such exists.
Flag to pass to mpiexec before giving it the number of processors to run on.
Number of MPI processors to utilize. Defaults to the number of processors detected on the host system.
Flags to pass to mpiexec directly before the executable to run.
Flags to pass to mpiexec after other flags.

Variables for locating MPI

This module performs a four step search for an MPI implementation:

1.
Search for MPIEXEC_EXECUTABLE and, if found, use its base directory.
2.
Check 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.
Attempt to find an MPI compiler wrapper and determine the compiler information from it.
4.
Try 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, the following variables may be set:

Manually specify the location of mpiexec.
Specify the base directory of the MPI installation.
Environment variable to specify the base directory of the MPI installation.
Environment variable to specify the base directory of the MPI installation.

For controlling the compiler wrapper step, the following variables may be set:

Search for the specified compiler wrapper and use it.
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.
Used to initialize MPI_<lang>_COMPILER_FLAGS if no language specific flag has been given. Empty by default.
A suffix which is appended to all names that are being looked for. For instance you may set this to .mpich or .openmpi to prefer the one or the other on Debian and its derivatives.

In order to control the guessing step, the following variable may be set:

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 MPI_SKIP_COMPILER_WRAPPER to true, which may be overridden.

Each of the search steps may be skipped with the following control variables:

If true, the module assumes that the compiler itself does not provide an MPI implementation and skips to step 2.
If true, no compiler wrapper will be searched for.
If true, the guessing step will be skipped.

Additionally, the following control variable is available to change search behavior:

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.

If the find procedure fails for a 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.

If all of these parameters were not sufficient to find the right MPI implementation, a user may disable the entire autodetection process by specifying both a list of libraries in MPI_<lang>_LIBRARIES and a list of include directories in MPI_<lang>_ADDITIONAL_INCLUDE_DIRS. Any other variable may be set in addition to these two. The module will then validate the MPI settings and store the settings in the cache.

Cache variables for MPI

The variable MPI_<lang>_INCLUDE_DIRS will be assembled from the following variables. For C and CXX:

Location of the mpi.h header on disk.

For Fortran:

Location of the Fortran 77 header mpif.h, if it exists.
Location of the mpi or mpi_f08 modules, if available.

For all languages the following variables are additionally considered:

A ;-list of paths needed in addition to the normal include directories.
Path variables for include folders referred to by <include_name>.
A ;-list of <include_name> that will be added to the include locations of <lang>.

The variable MPI_<lang>_LIBRARIES will be assembled from the following variables:

The location of a library called <lib_name> for use with MPI.
A ;-list of <lib_name> that will be added to the include locations of <lang>.

Usage of mpiexec

When using MPIEXEC_EXECUTABLE to execute MPI applications, you should typically use all of the MPIEXEC_EXECUTABLE flags as follows:

${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} ${MPIEXEC_MAX_NUMPROCS}

${MPIEXEC_PREFLAGS} EXECUTABLE ${MPIEXEC_POSTFLAGS} ARGS


where EXECUTABLE is the MPI program, and ARGS are the arguments to pass to the MPI program.

Advanced variables for using MPI

The module can perform some advanced feature detections upon explicit request.

Important notice: The following checks cannot be performed without executing an MPI test program. Consider the special considerations for the behavior of try_run() during cross compilation. Moreover, running an MPI program can cause additional issues, like a firewall notification on some systems. You should only enable these detections if you absolutely need the information.

If the following variables are set to true, the respective search will be performed:

Determine for all available Fortran bindings what the values of MPI_SUBARRAYS_SUPPORTED and MPI_ASYNC_PROTECTS_NONBLOCKING are and make their values available as MPI_Fortran_<binding>_SUBARRAYS and MPI_Fortran_<binding>_ASYNCPROT, where <binding> is one of F77_HEADER, F90_MODULE and F08_MODULE.
For each language, find the output of MPI_Get_library_version and make it available as MPI_<lang>_LIBRARY_VERSION_STRING. This information 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.

Backward Compatibility

Deprecated since version 3.10.

For backward compatibility with older versions of FindMPI, these variables are set:

MPI_COMPILER        MPI_LIBRARY        MPI_EXTRA_LIBRARY
MPI_COMPILE_FLAGS   MPI_INCLUDE_PATH   MPI_LINK_FLAGS
MPI_LIBRARIES


In new projects, please use the MPI_<lang>_XXX equivalents. Additionally, the following variables are deprecated:

Use MPI_<lang>_COMPILE_OPTIONS and MPI_<lang>_COMPILE_DEFINITIONS instead.
For consumption use MPI_<lang>_INCLUDE_DIRS and for specifying folders use MPI_<lang>_ADDITIONAL_INCLUDE_DIRS instead.
Use MPIEXEC_EXECUTABLE instead.

FindMsys

Added in version 3.21.

Finds MSYS, a POSIX-compatible environment that runs natively on Microsoft Windows.

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:

The path to the MSYS root installation directory.

Examples

Finding the MSYS installation and using its path in a custom find module:

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. 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.

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 ODBC library provided by unixODBC or iODBC implementations of 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 ODBC header and library in standard locations.

Imported Targets

This module provides the following Imported Targets:

Target encapsulating the ODBC usage requirements, available if ODBC is found.

Result Variables

This module defines the following variables:

Boolean indicating whether ODBC is found.
Include directories containing headers needed to use ODBC.
Libraries needed to link against to use ODBC.

Cache Variables

The following cache variables may also be set:

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.
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.
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.

Examples

Finding and using ODBC

Finding ODBC and linking it to a project target:

CMakeLists.txt

find_package(ODBC)
target_link_libraries(project_target PRIVATE ODBC::ODBC)


Finding a custom ODBC installation on Unix-like systems

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).

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.

Detect OpenACC support by the compiler.

This module can be used to detect OpenACC support in a compiler. 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.

Imported Targets

Added in version 3.16.

The module provides IMPORTED targets:

Target for using OpenACC from <lang>.

Variables

The module defines the following variables:

Added in version 3.25.

Variable indicating that OpenACC flags for at least one languages have been found.


This module will set the following variables per language in your project, where <lang> is one of C, CXX, or Fortran:

Variable indicating if OpenACC support for <lang> was detected.
OpenACC compiler flags for <lang>, separated by spaces.
Added in version 3.16.

OpenACC compiler flags for <lang>, as a list. Suitable for usage with target_compile_options or target_link_options.


The module will also try to provide the OpenACC version variables:

Date of the OpenACC specification implemented by the <lang> compiler.
Major version of OpenACC implemented by the <lang> compiler.
Minor version of OpenACC implemented by the <lang> compiler.
OpenACC version implemented by the <lang> compiler.

The specification date is formatted as given in the OpenACC standard: yyyymm where yyyy and mm represents the year and month of the OpenACC specification implemented by the <lang> compiler.

Input Variables

OpenACC_ACCEL_TARGET=<target> If set, will the correct target accelerator flag set to the <target> will be returned with OpenACC_<lang>_FLAGS.

FindOpenAL

Finds the Open Audio Library (OpenAL).

OpenAL is a cross-platform 3D audio API designed for efficient rendering of multichannel three-dimensional positional audio. It is commonly used in games and multimedia applications to provide immersive and spatialized sound.

Projects using this module should include the OpenAL header file using #include <al.h>, and not #include <AL/al.h>. The reason for this is that the latter is not portable. For example, Windows/Creative Labs does not by default put OpenAL headers in AL/ and macOS uses the convention of <OpenAL/al.h>.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.25.

Target encapsulating the OpenAL library usage requirements, available only if the OpenAL library is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the OpenAL is found. For backward compatibility, the OPENAL_FOUND variable is also set to the same value.
Human-readable string containing the version of OpenAL found.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use the OpenAL library.
The path to the OpenAL library.

Hints

This module accepts the following variables:

Environment variable which can be used to set the installation prefix of OpenAL to be found in non-standard locations.

OpenAL is searched in the following order:

1.
By default on macOS, system framework is searched first: /System/Library/Frameworks, whose priority can be changed by setting the CMAKE_FIND_FRAMEWORK variable.
2.
Environment variable ENV{OPENALDIR}.
3.
System paths.
4.
User-compiled framework: ~/Library/Frameworks.
5.
Manually compiled framework: /Library/Frameworks.
6.
Add-on package: /opt.


Examples

Finding the OpenAL library and linking 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).

Added in version 3.10: Detection of OpenCL 2.1 and 2.2.

Imported Targets

Added in version 3.7.

This module provides the following Imported Targets, if OpenCL has been found:

Target providing OpenCL usage requirements.

Result Variables

This module defines the following variables:

True if OpenCL was found.
Include directories needed to use OpenCL.
Libraries needed to link to OpenCL.
Highest supported OpenCL version (e.g., 1.2).
The major version of the OpenCL implementation.
The minor version of the OpenCL implementation.

Cache Variables

The following cache variables may also be set:

The OpenCL include directory.
The path to the OpenCL library.

Examples

Finding OpenCL and linking it to a project target:

find_package(OpenCL)
target_link_libraries(project_target PRIVATE OpenCL::OpenCL)


FindOpenGL

FindModule for OpenGL and OpenGL Utility Library (GLU).

Changed in version 3.2: X11 is no longer added as a dependency on Unix/Linux systems.

Added in version 3.10: GLVND support on Linux. See the Linux-specific section below.

Optional COMPONENTS

Added in version 3.10.

This module respects several optional COMPONENTS:

The EGL interface between OpenGL, OpenGL ES and the underlying windowing system.
An extension to X that interfaces OpenGL, OpenGL ES with X window system.
The cross platform API for 3D graphics.
Added in version 3.27.

A subset of OpenGL API for embedded systems with limited capabilities.

Added in version 3.27.

A subset of OpenGL API for embedded systems with more capabilities.


Imported Targets

Added in version 3.8.

This module defines the IMPORTED targets:

Defined to the platform-specific OpenGL libraries if the system has OpenGL.
Defined if the system has OpenGL Utility Library (GLU).

Added in version 3.10: Additionally, the following GLVND-specific library targets are defined:

Defined to libOpenGL if the system is GLVND-based.
Defined if the system has OpenGL Extension to the X Window System (GLX).
Defined if the system has EGL.
Added in version 3.27.

Defined if the system has GLES2.

Added in version 3.27.

Defined if the system has GLES3.


Result Variables

This module sets the following variables:

True, if the system has OpenGL and all components are found.
True, if the system has XMESA.
True, if the system has GLU.
True, if the system has an OpenGL library.
True, if the system has GLX.
True, if the system has EGL.
Defined if the system has GLES2.
Defined if the system has GLES3.
Path to the OpenGL include directory. The OPENGL_INCLUDE_DIRS variable is preferred.
Path to the EGL include directory.
Paths to the OpenGL library, windowing system libraries, and GLU libraries. On Linux, this assumes GLX and is never correct for EGL-based targets. Clients are encouraged to use the OpenGL::* import targets instead.
Added in version 3.29.

Paths to the OpenGL include directories.


Added in version 3.10: Variables for GLVND-specific libraries OpenGL, EGL and GLX.

Cache variables

The following cache variables may also be set:

Path to the EGL library.
Path to the GLU library.
Path to the GLVND 'GLX' library.
Path to the GLVND 'OpenGL' library
Path to the OpenGL library. New code should prefer the OpenGL::* import targets.
Added in version 3.27.

Path to the OpenGL GLES2 library.

Added in version 3.27.

Path to the OpenGL GLES3 library.

Added in version 3.29.

Path to the OpenGL GLU include directory.


Added in version 3.10: Variables for GLVND-specific libraries OpenGL, EGL and GLX.

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 OPENGL_LIBRARIES variable) to use legacy GL interfaces. These will use the legacy GL library located by OPENGL_gl_LIBRARY, if available. If OPENGL_gl_LIBRARY is empty or not found and GLVND is available, the OpenGL::GL target will use GLVND OpenGL::OpenGL and OpenGL::GLX (and the OPENGL_LIBRARIES variable will use the corresponding libraries). Thus, for non-EGL-based Linux targets, the OpenGL::GL target is most portable.

A OpenGL_GL_PREFERENCE variable may be set to specify the preferred way to provide legacy GL interfaces in case multiple choices are available. The value may be one of:

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).

Prefer to use the legacy libGL library, if available.

For EGL targets the client must rely on GLVND support on the user's system. Linking should use the OpenGL::OpenGL OpenGL::EGL targets. Using GLES* libraries is theoretically possible in place of OpenGL::OpenGL, but this module does not currently support that; contributions welcome.

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. 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.

FindOpenMP

Finds Open Multi-Processing (OpenMP) support.

This module can be used to detect OpenMP support in a compiler. 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.

Added in version 3.5: Clang support.

Input Variables

The following variables may be set to influence this module's behavior:

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

Added in version 3.10: The module exposes the components C, CXX, and Fortran. Each of these controls the various languages to search OpenMP support for.

Added in version 3.31: The CUDA language component is supported when using a CUDA compiler that supports OpenMP on the host.

Depending on the enabled components the following variables will be set:

Variable indicating that OpenMP flags for all requested languages have been found. If no components are specified, this is true if OpenMP settings for all enabled languages were detected.
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 your project, where <lang> is one of C, CXX, CUDA, or Fortran:

Variable indicating if OpenMP support for <lang> was detected.
OpenMP compiler flags for <lang>, separated by spaces.
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:

;-list of libraries for OpenMP programs for <lang>.
Location of the individual libraries needed for OpenMP support in <lang>.
A list of libraries needed to link with OpenMP code written in <lang>.

Additionally, the module provides IMPORTED targets:

Target for using OpenMP from <lang>.

Specifically for Fortran, the module sets the following variables:

Boolean indicating if OpenMP is accessible through omp_lib.h.
Boolean indicating if OpenMP is accessible through the omp_lib Fortran module.

The module will also try to provide the OpenMP version variables:

Added in version 3.7.

Date of the OpenMP specification implemented by the <lang> compiler.

Major version of OpenMP implemented by the <lang> compiler.
Minor version of OpenMP implemented by the <lang> compiler.
OpenMP version implemented by the <lang> compiler.

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.

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.

FindOpenSceneGraph

Finds OpenSceneGraph (OSG), a 3D graphics application programming interface.

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.


This module searches for the OpenSceneGraph core osg library, its dependency OpenThreads, and additional OpenSceneGraph libraries, some of which are also known as NodeKits, if specified.

When working with OpenSceneGraph, its core library headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>


Headers for the OpenSceneGraph libraries and NodeKits follow a similar inclusion structure, for example:

example.cxx

#include <osgAnimation/Animation>
#include <osgDB/DatabasePager>
#include <osgFX/BumpMapping>
// ...


Components

OpenSceneGraph toolkit consists of the core library osg, and additional libraries, which can be optionally specified as components with the find_package() command:

find_package(OpenSceneGraph [COMPONENTS <components>...])


Supported components include:

Finds the core osg library (libosg), required to use OpenSceneGraph. This component is always automatically implied.
Finds the dependent OpenThreads library (libOpenThreads) via the FindOpenThreads module. This component is always automatically implied as it is required to use OpenSceneGraph.
Finds the osgAnimation library, which provides general purpose utility classes for animation.
Finds the osgDB library for reading and writing scene graphs support.
Finds the osgFX NodeKit, which provides a framework for implementing special effects.
Finds the osgGA (GUI Abstraction) library, which provides facilities to work with varying window systems.
Finds the osgIntrospection library, which provides 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.


Finds the osgManipulator NodeKit, which provides support for 3D interactive manipulators.
Finds the osgParticle NodeKit, which provides support for particle effects.
Finds the osgPresentation NodeKit, which provides support for 3D scene graph based presentations.

NOTE:

This NodeKit has been added in OpenSceneGraph 3.0.0.


Finds the osgProducer utility library, which provides functionality for window management and event handling.

NOTE:

The osgProducer has been removed from early versions of OpenSceneGraph toolkit 1.x, and has been superseded by the osgViewer library.


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.


Finds the osgShadow NodeKit, which provides support for a range of shadow techniques.
Finds the osgSim NodeKit, which adds support for simulation features like navigation lights and OpenFlight-style movement controls.
Finds the osgTerrain NodeKit, which provides geospecifc terrain rendering support.
Finds the osgText NodeKit, which provides high quality text support.
Finds the osgUtil library, which provides general-purpose utilities like update, cull, and draw traversals, as well as scene graph tools such as optimization, triangle stripping, and tessellation.
Finds the osgViewer library, which provides high level viewer functionality.
Finds the osgVolume NodeKit, which provides volume rendering support.
Finds the osgWidget NodeKit, which provides support for 2D and 3D GUI widget sets.

If no components are specified, this module searches for the osg and OpenThreads components by default.

Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) OpenSceneGraph with all specified components is found. For backward compatibility, the OPENSCENEGRAPH_FOUND variable is also set to the same value.
The version of the OSG which was found.
Include directories containing headers needed to use OpenSceneGraph.
Libraries needed to link against to use OpenSceneGraph.

Hints

This module accepts the following variables:

Set this variable to boolean true to enable debugging output by this module.
Set this variable to boolean true to mark cache variables of this module as advanced automatically.

To help this module find OpenSceneGraph and its various components installed in custom location, CMAKE_PREFIX_PATH variable can be used. Additionally, the following variables are also respected:

<COMPONENT>_DIR
Environment or CMake variable that can be set to the root of the OSG common installation, where <COMPONENT> is the uppercase form of component listed above. For example, OSGVOLUME_DIR to find the osgVolume component.
Environment or CMake variable that can be set to influence detection of OpenSceneGraph installation root location as a whole.
Environment variable treated the same as OSG_DIR.
Environment variable treated the same as OSG_DIR.

Examples

Finding the OpenSceneGraph with osgDB and osgUtil libraries specified as components and creating an interface imported target that encapsulates its usage requirements for linking 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 are used internally by this module when 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, they can be useful for advanced scenarios where finer control over component detection is needed. For example, to find them explicitly and override or bypass 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. OpenSP is an open-source implementation of the SGML (Standard Generalized Markup Language) parser.

Imported Targets

This module provides the following Imported Targets:

Target encapsulating the OpenSP library usage requirements, available only if the OpenSP is found.

Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) OpenSP is available.
The version of found OpenSP.
The major version of OpenSP.
The minor version of OpenSP.
The patch version of OpenSP.
The include directories containing headers needed to use the OpenSP library.
Libraries required to link against to use OpenSP. These can be passed to the target_link_libraries() command when not using the OpenSP::OpenSP imported target.

Cache Variables

The following cache variables may also be set:

The OpenSP include directory.
The absolute path of the osp library.
True if SP_MULTI_BYTE was found to be defined in OpenSP's config.h header file, which indicates that the OpenSP library was compiled with support for multi-byte characters. The consuming target needs to define the SP_MULTI_BYTE preprocessor macro to match this value in order to avoid issues with character decoding.

Examples

Finding the OpenSP library and linking it to a project target:

find_package(OpenSP)
target_link_libraries(project_target PRIVATE OpenSP::OpenSP)


FindOpenSSL

Finds the installed OpenSSL encryption library and determines its version.

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 as before, and now also a version range can be used. For a detailed description of version range usage and capabilities, refer to the find_package() command.

Added in version 3.18: Support for OpenSSL 3.0.

Components

This module supports the following optional components:

Added in version 3.12.

Ensures that the OpenSSL crypto library is found.

Added in version 3.12.

Ensures that the OpenSSL ssl library is found.


Components can be optionally specified using a standard syntax:

find_package(OpenSSL [COMPONENTS <components>...])


If no components are requested, module by default searches for the Crypto as required and SSL as optional component.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.4.

Target encapsulating the OpenSSL crypto library usage requirements, available only if the crypto library is found.

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.

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 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 different MSVC runtime configuration. Linking this target on platforms other than MSVC has no effect.

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 ensure that it is linked only once in the entire dependency graph of any library or executable:

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, as both the ISO C and ISO C++ standards place very few requirements on how linking should behave.




Result Variables

This module defines the following variables:

Boolean indicating whether the OpenSSL library has been found. For backward compatibility, the OPENSSL_FOUND variable is also set to the same value.
The OpenSSL include directory.
The OpenSSL crypto library.
The OpenSSL crypto library and its dependencies.
The OpenSSL ssl library.
The OpenSSL ssl library and its dependencies.
All OpenSSL libraries and their dependencies.
The OpenSSL version found. This is set to <major>.<minor>.<revision><patch> (e.g. 0.9.8s).
The sources in the target OpenSSL::applink mentioned above. This variable is only defined if 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:

Set to the root directory of an OpenSSL installation to search for the OpenSSL libraries in custom locations.
Added in version 3.4.

Set to TRUE to prefer static OpenSSL libraries over shared ones.

Added in version 3.5.

Set to TRUE to search for the OpenSSL libraries built with the MSVC static runtime (MT).

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.

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:

find_package(OpenSSL COMPONENTS SSL)
target_link_libraries(project_target PRIVATE OpenSSL::SSL)


FindOpenThreads

Finds the OpenThreads C++ based threading library.

OpenThreads header files are intended to be included as:

example.cxx

#include <OpenThreads/Thread>


Result Variables

This module defines the following variables:

Boolean indicating whether OpenThreads library is found. For backward compatibility, the OPENTHREADS_FOUND variable is also set to the same value.
Libraries needed to link against to use OpenThreads. This provides either 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:

The directory containing the header files needed to use OpenThreads.

Hints

This module accepts the following variables:

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 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 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:

May be set as an environment or CMake variable. Treated the same as OPENTHREADS_DIR.
Environment variable treated the same as OPENTHREADS_DIR.

Examples

Finding the OpenThreads library and creating an interface imported target that encapsulates its usage requirements for linking to a project target:

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:

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 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:

Boolean indicating whether osg library is found. For backward compatibility, the OSG_FOUND variable is also set to the same value.
The libraries needed to link against to use osg library.
A result variable that is set to the same value as the OSG_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osg library.
The path to the osg debug library.

Hints

This module accepts the following variables:

Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osg 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.

Examples

Finding the osg 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(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 to find OpenSceneGraph toolkit.

Findosg_functions

NOTE:

This module is not intended to be included or invoked directly by project code during typical use of 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.


FindosgAnimation

Finds the osgAnimation library from the OpenSceneGraph toolkit.

NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgAnimation as a component. This will automatically handle 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. However, 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 bypass automatic component detection:

find_package(osgAnimation)


OpenSceneGraph and osgAnimation headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgAnimation/Animation>
// ...


When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgAnimation library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGANIMATION_FOUND variable is also set to the same value.
The libraries needed to link against to use osgAnimation.
A result variable that is set to the same value as the OSGANIMATION_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osgAnimation.
The path to the osgAnimation debug library.

Hints

This module accepts the following variables:

Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgAnimation 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.

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 to find 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. This will automatically handle 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 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:

Boolean indicating whether the osgDB library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGDB_FOUND variable is also set to the same value.
The libraries needed to link against to use osgDB.
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:

The include directory containing headers needed to use osgDB.
The path to the osgDB debug library.

Hints

This module accepts the following variables:

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.

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 to find OpenSceneGraph toolkit.

FindosgFX

Finds the osgFX NodeKit from the OpenSceneGraph toolkit.

NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgFX as a component. This will automatically handle 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:

Boolean indicating whether the osgFX NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGFX_FOUND variable is also set to the same value.
The libraries needed to link against to use osgFX.
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:

The include directory containing headers needed to use osgFX.
The path to the osgFX debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgFX explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

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 to find OpenSceneGraph toolkit.

FindosgGA

Finds the osgGA library from the OpenSceneGraph toolkit.

NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgGA as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:

find_package(OpenSceneGraph COMPONENTS osgGA)




This module is used internally by FindOpenSceneGraph to find the osgGA 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 osgGA explicitly or bypass automatic component detection:

find_package(osgGA)


OpenSceneGraph and osgGA headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgGA/FlightManipulator>
// ...


When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgGA library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGGA_FOUND variable is also set to the same value.
The libraries needed to link against to use osgGA.
A result variable that is set to the same value as the OSGGA_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osgGA.
The path to the osgGA debug library.

Hints

This module accepts the following variables:

Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgGA 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.

Examples

Finding osgGA explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

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 to find OpenSceneGraph toolkit.

FindosgIntrospection

Finds the osgIntrospection library from the OpenSceneGraph toolkit.

NOTE:

The osgIntrospection library has been removed from the OpenSceneGraph toolkit as of OpenSceneGraph version 3.0.


NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgIntrospection as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:

find_package(OpenSceneGraph COMPONENTS osgIntrospection)




This module is used internally by FindOpenSceneGraph to find the osgIntrospection 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 osgIntrospection explicitly or bypass automatic component detection:

find_package(osgIntrospection)


OpenSceneGraph and osgIntrospection headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgIntrospection/Reflection>
// ...


When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgIntrospection library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGINTROSPECTION_FOUND variable is also set to the same value.
The libraries needed to link against to use osgIntrospection.
A result variable that is set to the same value as the OSGINTROSPECTION_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osgIntrospection.
The path to the osgIntrospection debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgIntrospection explicitly with this module and creating an interface imported target 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 to find OpenSceneGraph toolkit.

FindosgManipulator

Finds the osgManipulator NodeKit from the OpenSceneGraph toolkit.

NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgManipulator as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:

find_package(OpenSceneGraph COMPONENTS osgManipulator)




This module is used internally by FindOpenSceneGraph to find the osgManipulator 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 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.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgManipulator NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGMANIPULATOR_FOUND variable is also set to the same value.
The libraries needed to link against to use osgManipulator.
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:

The include directory containing headers needed to use osgManipulator.
The path to the osgManipulator debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgManipulator explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

find_package(osgManipulator)
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 to find OpenSceneGraph toolkit.

FindosgParticle

Finds the osgParticle NodeKit from the OpenSceneGraph toolkit.

NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgParticle as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:

find_package(OpenSceneGraph COMPONENTS osgParticle)




This module is used internally by FindOpenSceneGraph to find the osgParticle 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 osgParticle explicitly or bypass automatic component detection:

find_package(osgParticle)


OpenSceneGraph and osgParticle headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgParticle/FireEffect>
// ...


When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgParticle NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGPARTICLE_FOUND variable is also set to the same value.
The libraries needed to link against to use the osgParticle NodeKit
A result variable that is set to the same value as the OSGPARTICLE_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osgParticle NodeKit.
The path to the osgParticle debug library.

Hints

This module accepts the following variables:

Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgParticle 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.

Examples

Finding osgParticle explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking 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 to find OpenSceneGraph toolkit.

FindosgPresentation

Finds the osgPresentation NodeKit from the OpenSceneGraph toolkit, available since OpenSceneGraph version 3.0.0.

NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgPresentation as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:

find_package(OpenSceneGraph COMPONENTS osgPresentation)




This module is used internally by FindOpenSceneGraph to find the osgPresentation 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 osgPresentation explicitly or bypass automatic component detection:

find_package(osgPresentation)


OpenSceneGraph and osgPresentation headers are intended to be included in C++ project source code as:

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:

Boolean indicating whether the osgPresentation NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGPRESENTATION_FOUND variable is also set to the same value.
The libraries needed to link against to use osgPresentation.
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:

The include directory containing headers needed to use osgPresentation.
The path to the osgPresentation debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgPresentation explicitly with this module and creating an interface imported target 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 to find OpenSceneGraph toolkit.

FindosgProducer

Finds the osgProducer utility library from the OpenSceneGraph toolkit.

NOTE:

The osgProducer library has been removed from the OpenSceneGraph toolkit in early OpenSceneGraph versions (pre 1.0 release) and replaced with osgViewer. Its development has shifted at time to a standalone project and repository Producer, which can be found with FindProducer module.


NOTE:

In most cases, it's recommended to use the 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 to find the osgProducer 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 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.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgProducer library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGPRODUCER_FOUND variable is also set to the same value.
The libraries needed to link against to use osgProducer.
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:

The include directory containing headers needed to use osgProducer.
The path to the osgProducer debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgProducer explicitly with this module and creating an interface imported target 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 to find OpenSceneGraph toolkit.
  • The FindProducer module, which finds the standalone Producer library that evolved from the legacy osgProducer.

FindosgQt

Finds the osgQt utility library from the OpenSceneGraph toolkit.

NOTE:

In most cases, it's recommended to use the FindOpenSceneGraph module instead and list osgQt as a component. This will automatically handle dependencies such as the OpenThreads and core osg libraries:

find_package(OpenSceneGraph COMPONENTS osgQt)




This module is used internally by FindOpenSceneGraph to find the osgQt 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 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.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgQt library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGQT_FOUND variable is also set to the same value.
The libraries needed to link against to use osgQt.
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:

The include directory containing headers needed to use osgQt.
The path to the osgQt debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgQt explicitly with this module and creating an interface imported target that encapsulates its usage requirements for linking it to a project target:

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 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 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 to find the osgShadow 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 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:

Boolean indicating whether the osgShadow NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGSHADOW_FOUND variable is also set to the same value.
The libraries needed to link against to use osgShadow.
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:

The include directory containing headers needed to use osgShadow.
The path to the osgShadow debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgShadow explicitly with this module and creating an interface imported target 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 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 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 to find the osgSim 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 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:

Boolean indicating whether the osgSim NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGSIM_FOUND variable is also set to the same value.
The libraries needed to link against to use osgSim.
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:

The include directory containing headers needed to use osgSim.
The path to the osgSim debug library.

Hints

This module accepts the following variables:

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.

Examples

Finding osgSim explicitly with this module and creating an interface imported target 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 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 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)




This module is used internally by FindOpenSceneGraph to find the osgTerrain 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 osgTerrain explicitly or bypass automatic component detection:

find_package(osgTerrain)


OpenSceneGraph and osgTerrain headers are intended to be included in C++ project source code as:

example.cxx

#include <osg/PositionAttitudeTransform>
#include <osgTerrain/Terrain>
// ...


When working with the OpenSceneGraph toolkit, other libraries such as OpenGL may also be required.

Result Variables

This module defines the following variables:

Boolean indicating whether the osgTerrain NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGTERRAIN_FOUND variable is also set to the same value.
The libraries needed to link against to use osgTerrain.
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:

The include directory containing headers needed to use osgTerrain.
The path to the osgTerrain debug library.

Hints

This module accepts the following variables:

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.

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:

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. For example, to find the osgText explicitly or bypass automatic component detection:

find_package(osgText)


OpenSceneGraph and osgText headers are intended to be included in C++ project source code as:

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:

Boolean indicating whether the osgText NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGTEXT_FOUND variable is also set to the same value.
The libraries needed to link against to use osgText.
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:

The include directory containing headers needed to use osgText.
The path to the osgText debug library.

Hints

This module accepts the following variables:

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.

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:

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)


OpenSceneGraph and osgUtil headers are intended to be included in C++ project source code as:

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:

Boolean indicating whether the osgUtil library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGUTIL_FOUND variable is also set to the same value.
The libraries needed to link against to use osgUtil.
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:

The include directory containing headers needed to use osgUtil.
The path to the osgUtil debug library.

Hints

This module accepts the following variables:

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.

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:

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)


OpenSceneGraph and osgViewer headers are intended to be included in C++ project source code as:

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:

Boolean indicating whether the osgViewer library of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGVIEWER_FOUND variable is also set to the same value.
The libraries needed to link against to use osgViewer.
A result variable that is set to the same value as the OSGVIEWER_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osgViewer.
The path to the osgViewer debug library.

Hints

This module accepts the following variables:

Environment variable that can be set to help locate the OpenSceneGraph toolkit, including its osgViewer 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.

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:

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 OpenSceneGraph toolkit.

FindosgVolume

Finds the osgVolume NodeKit from the OpenSceneGraph toolkit.

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:

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:

Boolean indicating whether the osgVolume NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGVOLUME_FOUND variable is also set to the same value.
The libraries needed to link against to use osgVolume.
A result variable that is set to the same value as the OSGVOLUME_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osgVolume.
The path to the osgVolume debug library.

Hints

This module accepts the following variables:

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.

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 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:

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:

Boolean indicating whether the osgWidget NodeKit of the OpenSceneGraph toolkit is found. For backward compatibility, the OSGWIDGET_FOUND variable is also set to the same value.
The libraries needed to link against to use osgWidget.
A result variable that is set to the same value as the OSGWIDGET_LIBRARIES variable.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use osgWidget.
The path to the osgWidget debug library.

Hints

This module accepts the following variables:

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.

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 OpenSceneGraph toolkit.

FindPatch

Added in version 3.10.

Finds the patch command-line executable for applying diff patches to original files.

Imported Targets

This module provides the following Imported Targets:

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:

Boolean indicating whether the patch command-line executable is found.

Cache Variables

The following cache variables may also be set:

The path to the patch command-line executable.

Examples

Finding 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. Perl is a general-purpose, interpreted, dynamic programming language.

Result Variables

This module defines the following variables:

True if the Perl executable was found. For backward compatibility, the PERL_FOUND variable is also set to the same value.
The version of Perl found.

Cache Variables

The following cache variables may also be set:

Full path to the perl executable.

Examples

Finding the Perl interpreter:

find_package(Perl)


FindPerlLibs

Finds Perl libraries. Perl is a general-purpose, interpreted, dynamic programming language. This module detects whether Perl is installed and determines the locations of include paths, libraries, and the library name.

Result Variables

This module sets the following variables:

True if perl.h and libperl were found. For backward compatibility, the PERLLIBS_FOUND variable is also set to the same value.
Path to the sitesearch install directory (-V:installsitesearch).
Path to the sitelib install directory (-V:installsitearch).
Path to the sitelib install directory (-V:installsitelib).
Path to the vendor arch install directory (-V:installvendorarch).
Path to the vendor lib install directory (-V:installvendorlib).
Path to the core arch lib install directory (-V:archlib).
Path to the core priv lib install directory (-V:privlib).
Path to the update arch lib install directory (-V:installarchlib).
Path to the update priv lib install directory (-V:installprivlib).
Compilation flags used to build Perl.

Cache Variables

The following cache variables may also be set:

Directory containing perl.h and other Perl header files.
Path to the libperl.
Full path to the perl executable.

Examples

Finding Perl libraries and specifying the minimum required version:

find_package(PerlLibs 6.0)


FindPHP4

Finds PHP version 4, a general-purpose scripting language.

NOTE:

This module is specifically for PHP version 4, which is obsolete and no longer supported. For modern development, use a newer PHP version.


This module checks if PHP 4 is installed and determines the locations of the include directories and the PHP command-line interpreter.

Cache Variables

The following cache variables may also be set:

The directory containing php.h and other headers needed to use PHP.
The full path to the php command-line interpreter executable.

Examples

Finding PHP:

find_package(PHP4)


FindPhysFS

Finds the PhysicsFS library (PhysFS) for file I/O abstraction.

Result Variables

This module defines the following variables:

Boolean indicating whether PhysicsFS library is found. For backward compatibility, the PHYSFS_FOUND variable is also set to the same value.

Cache Variables

The following cache variables may also be set:

Path to the PhysicsFS library needed to link against.
Directory containing the physfs.h and related headers needed for using the library.

Hints

This module accepts the following variables:

Environment variable that can be 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 PhysicsFS library: ./configure --prefix=$PHYSFSDIR.

Examples

Finding the PhysicsFS library:

find_package(PhysFS)


FindPike

Finds the Pike compiler and interpreter. Pike is interpreted, general purpose, high-level, dynamic programming language.

Cache Variables

The following cache variables may also be set:

The directory containing program.h.
Full path to the pike binary.

Examples

Finding Pike:

find_package(Pike)


FindPkgConfig

A pkg-config module for CMake.

Finds the pkg-config executable and adds the pkg_get_variable(), pkg_check_modules() and pkg_search_module() commands. The following variables will also be set:

True if a pkg-config executable was found.
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 may be overridden by the user. See Variables Affecting Behavior for how these variables are initialized.

Checks for all the given modules, setting a variety of result variables in the calling scope.

pkg_check_modules(<prefix>

[REQUIRED] [QUIET]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[IMPORTED_TARGET [GLOBAL]]
<moduleSpec> [<moduleSpec>...])


When the REQUIRED argument is given, the command will fail with an error if module(s) could not be found.

When the QUIET argument is given, no status messages will be printed.

Added in version 3.3: The CMAKE_PREFIX_PATH, CMAKE_FRAMEWORK_PATH, and CMAKE_APPBUNDLE_PATH cache and environment variables will be 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 environment variables respectively. The PKG_CONFIG_USE_CMAKE_PREFIX_PATH variable set to FALSE disables this behavior globally.

Added in version 3.7: The IMPORTED_TARGET argument will create an imported target named PkgConfig::<prefix> that can be passed directly as an argument to target_link_libraries().

Added in version 3.13: The GLOBAL argument will make 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 target property.

Changed in version 3.18: Include directories specified with -isystem are stored in the INTERFACE_INCLUDE_DIRECTORIES target property. Previous versions of CMake left them in the INTERFACE_COMPILE_OPTIONS property.

Each <moduleSpec> can be either a bare module name or it can be a module name with a version constraint (operators =, <, >, <= and >= are supported). The following are 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.

The following variables may be set upon return. Two sets of values exist: One for the common case (<XXX> = <prefix>) and another for the information pkg-config provides when called with the --static option (<XXX> = <prefix>_STATIC).

<XXX>_FOUND
set to 1 if module(s) exist
<XXX>_LIBRARIES
only the libraries (without the '-l')
<XXX>_LINK_LIBRARIES
the libraries and their absolute paths
<XXX>_LIBRARY_DIRS
the paths of the libraries (without the '-L')
<XXX>_LDFLAGS
all required linker flags
<XXX>_LDFLAGS_OTHER
all other linker flags
<XXX>_INCLUDE_DIRS
the '-I' preprocessor flags (without the '-I')
<XXX>_CFLAGS
all required cflags
<XXX>_CFLAGS_OTHER
the other compiler flags

All but <XXX>_FOUND may be a ;-list if the associated variable returned from pkg-config has multiple values.

Changed in version 3.18: Include directories specified with -isystem are stored in the <XXX>_INCLUDE_DIRS variable. Previous versions of CMake left them in <XXX>_CFLAGS_OTHER.

There are some special variables whose prefix depends on the number of <moduleSpec> given. When there is only one <moduleSpec>, <YYY> will simply be <prefix>, but if two or more <moduleSpec> items are given, <YYY> will be <prefix>_<moduleName>.

<YYY>_VERSION
version of the module
<YYY>_PREFIX
prefix directory of the module
<YYY>_INCLUDEDIR
include directory of the module
<YYY>_LIBDIR
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 and returned the first successful result.

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, pass it through as -l<name>. Previous versions of CMake failed in this case.

Examples:

pkg_check_modules (GLIB2 glib-2.0)


Looks for any version of glib2. If found, the output variable GLIB2_VERSION will hold the actual version found.

pkg_check_modules (GLIB2 glib-2.0>=2.10)


Looks for at least version 2.10 of glib2. If found, the output variable GLIB2_VERSION will hold the actual version found.

pkg_check_modules (FOO glib-2.0>=2.10 gtk+-2.0)


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. The FOO_glib-2.0_VERSION and FOO_gtk+-2.0_VERSION variables will be set to their respective found module versions.

pkg_check_modules (XRENDER REQUIRED xrender)


Requires any version of xrender. Example output variables set by a successful call:

XRENDER_LIBRARIES=Xrender;X11
XRENDER_STATIC_LIBRARIES=Xrender;X11;pthread;Xau;Xdmcp



The behavior of this command is the same as pkg_check_modules(), except that rather than checking for all the specified modules, it searches for just the first successful match.

pkg_search_module(<prefix>

[REQUIRED] [QUIET]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[IMPORTED_TARGET [GLOBAL]]
<moduleSpec> [<moduleSpec>...])


Added in version 3.16: If a module is found, the <prefix>_MODULE_NAME variable will contain the name of the matching module. This variable can be used if you need to run pkg_get_variable().

Example:

pkg_search_module (BAR libxml-2.0 libxml2 libxml>=2)



Added in version 3.4.

Retrieves the value of a pkg-config variable varName and stores it in the result variable resultVar in the calling scope.

pkg_get_variable(<resultVar> <moduleName> <varName>

[DEFINE_VARIABLES <key>=<value>...])


If pkg-config returns multiple values for the specified variable, resultVar will contain a ;-list.

Options:

Added in version 3.28.

Specify key-value pairs to redefine variables affecting the variable retrieved with pkg-config.


For example:

pkg_get_variable(GI_GIRDIR gobject-introspection-1.0 girdir)



Variables Affecting Behavior

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.

Added in version 3.1: The PKG_CONFIG environment variable can be used as a hint if PKG_CONFIG_EXECUTABLE has not yet been set.

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.


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 not provided, it will be initialized from the PKG_CONFIG environment variable, if 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.


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, disabled otherwise.


FindPNG

Finds libpng, the official reference library for the PNG image format.

NOTE:

The PNG library depends on the ZLib compression library, which must be found for this module to succeed.


Imported Targets

Added in version 3.5.

This module defines the following Imported Targets:

The libpng library, if found.

Result Variables

This module sets the following variables:

Directory containing the PNG headers (e.g., png.h).
PNG libraries required for linking.
Compile definitions for using PNG, if any. They can be added with target_compile_definitions() command when not using the PNG::PNG imported target.
True if PNG library is found.
The version of the PNG library found.

Obsolete Variables

The following variables may also be set for backward compatibility:

Path to the PNG library.
Directory containing the PNG headers (same as PNG_INCLUDE_DIRS).

Examples

Finding PNG library and using it in a project:

find_package(PNG)
target_link_libraries(project_target PRIVATE PNG::PNG)


FindPostgreSQL

Finds the PostgreSQL installation - the client library (libpq) and optionally the server.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.14.

Target encapsulating all usage requirements of the required libpq client library and the optionally requested PostgreSQL server component. This target is available only if PostgreSQL is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the minimum required version and components of PostgreSQL have been found.
The PostgreSQL libraries needed for linking.
The include directories containing PostgreSQL headers.
The directories containing PostgreSQL libraries.
The version of PostgreSQL found.
The include directory containing PostgreSQL server headers.

Components

This module supports the following additional components:

Added in version 3.20.

Ensures that server headers are also found. Note that PostgreSQL_TYPE_INCLUDE_DIR variable is set regardless of whether this component is specified in the find_package() call.


Examples

Finding the PostgreSQL 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 PostgreSQL client library and requiring server headers using the Server component provides an imported target with all usage requirements, which can then be linked to a project target:

find_package(PostgreSQL COMPONENTS Server)
target_link_libraries(project_target PRIVATE PostgreSQL::PostgreSQL)


When 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:

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) library 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.


This module finds the Producer library, a windowing and event handling library designed primarily for real-time graphics applications.

Producer library headers are intended to be included in C++ project source code as:

example.cxx

#include <Producer/CameraGroup>


Result Variables

This module defines the following variables:

Boolean indicating whether Producer is found. For backward compatibility, the PRODUCER_FOUND variable is also set to the same value.

Cache Variables

The following cache variables may also be set:

The include directory containing headers needed to use Producer.
The path to the Producer library needed to link against for usage.

Hints

This module accepts the following variables:

Environment variable that can be 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 the following environment variables as equivalents to PRODUCER_DIR for convenience to specify common installation root for multiple OpenSceneGraph-related libraries at once:

Environment variable treated the same as PRODUCER_DIR.
Environment variable treated the same as PRODUCER_DIR.

Examples

Finding the Producer library and creating an imported target that encapsulates its usage requirements for linking 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 for use with the find_package() command in config mode:

find_package(Protobuf CONFIG)


In this case, imported targets and CMake commands such as protobuf_generate() are provided by the upstream package rather than this module. Additionally, some variables documented here are not available in config mode, as imported targets are preferred. For usage details, refer to the upstream documentation, which is 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 is 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>).

Changed in version 3.6: All input and output variables use the Protobuf_ prefix. Variables with PROTOBUF_ prefix are supported for backward compatibility.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.9.

Target encapsulating the Protobuf library usage requirements, available if Protobuf library is found.

Added in version 3.9.

Target encapsulating the protobuf-lite library usage requirements, available if Protobuf and its lite library are found.

Added in version 3.9.

Target encapsulating the protoc library usage requirements, available if Protobuf and its protoc library are found.

Added in version 3.10.

Imported executable target encapsulating the protoc compiler usage requirements, available if Protobuf and protoc are found.


Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) Protobuf library is found.
Added in version 3.6.

The version of Protobuf found.

Include directories needed to use Protobuf.
Libraries needed to link against to use Protobuf.
Libraries needed to link against to use the protoc library.
Libraries needed to link against to use the protobuf-lite library.

Cache Variables

The following cache variables may also be set:

The include directory containing Protobuf headers.
The path to the protobuf library.
The path to the protoc library.
The path to the protoc compiler.
The path to the protobuf debug library.
The path to the protoc debug library.
The path to the protobuf-lite library.
The path to the protobuf-lite debug library.
When compiling with MSVC, if this cache variable is set, the protobuf-default Visual Studio project build locations will be searched for libraries and binaries:
  • <Protobuf_SRC_ROOT_FOLDER>/vsprojects/{Debug,Release}, or
  • <Protobuf_SRC_ROOT_FOLDER>/vsprojects/x64/{Debug,Release}


Hints

This module accepts the following optional variables before calling the find_package(Protobuf):

Added in version 3.6.

Boolean variable that enables debug messages of this module to be printed for debugging purposes.

Added in version 3.9.

Set to ON to force the use of the static libraries. Default is OFF.


Commands

This module provides the following commands if Protobuf is found:

Generating Source Files

Added in version 3.13.

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] )


The CMake target to which the generated files are added as sources. This option is required when OUT_VAR <variable> is not used.
A single value: cpp or python. Determines the kind of source files to generate. Defaults to cpp. For other languages, use the GENERATE_EXTENSIONS option.
The name of a CMake variable that will be populated with the paths to the generated source files.
The name of a preprocessor macro applied to all generated Protobuf message classes and extern variables. This can be used, for example, to declare DLL exports. The macro should expand to __declspec(dllexport) or __declspec(dllimport), depending on what is being compiled.

This option is only used when LANGUAGE is cpp.

The output directory for generated source files. Defaults to: CMAKE_CURRENT_BINARY_DIR.
Added in version 3.21.

An optional plugin executable. This could be, for example, the path to grpc_cpp_plugin.

Added in version 3.28.

Additional options passed to the plugin, such as generate_mock_code=true for the gRPC C++ plugin.

Added in version 3.28.

Dependencies on which the generation of files depends on. These are forwarded to the underlying add_custom_command(DEPENDS) invocation.

Changed in version 4.1: This argument now accepts multiple values (DEPENDENCIES a b c...). Previously, only a single value could be specified (DEPENDENCIES "a;b;c;...").

A list of .proto schema files to process. If <target> is also specified, these will be combined with all .proto source files from that target.
A list of one or more common parent directories for the schema files. For example, if the schema file is proto/helloworld/helloworld.proto and the import directory is proto/, then the generated files will be <out-dir>/helloworld/helloworld.pb.h and <out-dir>/helloworld/helloworld.pb.cc.
If specified, the base paths of all proto schema files are appended to IMPORT_DIRS (it causes protoc to be invoked with -I argument for each directory containing a .proto file).
If LANGUAGE is omitted, this must be set to specify the extensions generated by protoc.
Added in version 3.28.

A list of additional command-line options passed directly to the protoc compiler.

Added in version 4.0.

The command-line program, path, or CMake executable used to generate Protobuf bindings. If omitted, protobuf::protoc imported target is used by default.

If specified, a command-line option --descriptor_set_out=<proto-file> is appended to protoc compiler for each .proto source file, enabling the creation of self-describing messages. 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 provided for backward compatibility.

NOTE:

The protobuf_generate_cpp() and protobuf_generate_python() commands work correctly only within the same directory scope, where find_package(Protobuf ...) is called.


NOTE:

If Protobuf is found in config mode, the protobuf_generate_cpp() and protobuf_generate_python() commands 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 calling find_package(Protobuf ...).


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.
Added in version 3.10.

Name of the variable to define, which will contain a list of generated descriptor files if requested.

NOTE:

This option is not available when Protobuf is found in config mode.


Name of a macro that should expand to __declspec(dllexport) or __declspec(dllimport), depending on what is being compiled.
<proto-files>...
One of more .proto files to be processed.


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.



----



The protobuf_generate_cpp() and protobuf_generate_python() commands accept the following optional variables before being invoked:

Deprecated since version 4.1.

A list of additional directories to search for imported .proto files.

Deprecated since version 4.1: Use protobuf_generate(APPEND_PATH) command option.

A boolean variable that, if set to boolean true, causes protoc to be invoked with -I argument for each directory containing a .proto file. By default, it is set to boolean true.


Examples

Examples: Finding Protobuf

Finding Protobuf library:

find_package(Protobuf)


Or, finding Protobuf and specifying a minimum required version:

find_package(Protobuf 30)


Or, finding Protobuf and making it required (if not found, processing stops with an error message):

find_package(Protobuf REQUIRED)


Example: Finding Protobuf in Config Mode

When Protobuf library is built and installed using its CMake-based build system, it can be found in config mode:

find_package(Protobuf CONFIG)


However, some Protobuf installations might still not provide package configuration file. The following example shows, how to use the CMAKE_FIND_PACKAGE_PREFER_CONFIG variable to find Protobuf in config mode and falling back to module mode if config file is not found:

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:

find_package(Protobuf)
target_link_libraries(example PRIVATE protobuf::libprotobuf)


Example: Processing Proto Schema Files

The following example demonstrates how to process all *.proto schema source files added to a target 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

The following example shows how to use Protobuf and gRPC:

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

The following example shows how to process .proto files to C++ code, using a deprecated command and its modern replacement:

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)


The following example shows how to process .proto files to Python code, using a deprecated command and its modern replacement:

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.

Find Python interpreter, compiler and development environment (include directories and libraries).

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. This component is available only for version 3.2 and upper.

NumPy: search for NumPy include directories.

Added in version 3.14: Added the NumPy component.

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 defines the following Imported Targets:

Changed in version 3.14: Imported Targets are only created when CMAKE_ROLE is PROJECT.

Python interpreter. This target is defined only if the Interpreter component is found.
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.

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. This target is defined only if the Compiler component is found.
Added in version 3.15.

Python library for Python module. Target defined if component Development.Module is found.

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 library for Python embedding. Target defined if component Development.Embed is found.
Added in version 3.14.

NumPy Python library. Target defined if component NumPy is found.


Result Variables

This module will set the following variables in your project (see Standard Variable Names):

System has the Python requested components.
System has the Python interpreter.
Path to the Python interpreter.
Added in version 3.30.

Path to the debug Python interpreter. It is only defined on the Windows platform.

Added in version 3.30.

Path to the Python interpreter, defined as a generator expression selecting the Python_EXECUTABLE or Python_EXECUTABLE_DEBUG variable based on the context (platform, configuration).

  • Python
  • ActivePython
  • Anaconda
  • Canopy
  • IronPython
  • PyPy


Standard platform independent installation directory.

Information returned by sysconfig.get_path('stdlib').

Standard platform dependent installation directory.

Information returned by sysconfig.get_path('platstdlib').

Third-party platform independent installation directory.

Information returned by sysconfig.get_path('purelib').

Third-party platform dependent installation directory.

Information returned by sysconfig.get_path('platlib').

Added in version 3.17.

Extension suffix for modules.

Information computed from sysconfig.get_config_var('EXT_SUFFIX') or sysconfig.get_config_var('SOABI') or python3-config --extension-suffix.

Added in version 3.26.

Extension suffix for modules using the Stable Application Binary Interface.

Information computed from importlib.machinery.EXTENSION_SUFFIXES if the COMPONENT Interpreter was specified. Otherwise, the extension is abi3 except for Windows, MSYS and CYGWIN for which this is an empty string.

System has the Python compiler.
Path to the Python compiler. Only offered by IronPython.

Added in version 3.18.

The .Net interpreter. Only used by IronPython implementation.

System has the Python development artifacts.
Added in version 3.18.

System has the Python development artifacts for Python module.

Added in version 3.26.

System has the Python development artifacts for Python module using the Stable Application Binary Interface.

Added in version 3.18.

System has the Python development artifacts for Python embedding.


Python_INCLUDE_DIRS

The Python include directories.


Added in version 3.30.3.

The Python preprocessor definitions.

Added in version 3.30.

Postfix of debug python module. This variable can be used to define the DEBUG_POSTFIX target property.

Added in version 3.19.

The Python link options. Some configurations require specific link options for a correct build and execution.

The Python libraries.
The Python library directories.
The Python runtime library directories.
Added in version 3.26.

The Python libraries for the Stable Application Binary Interface.

Added in version 3.26.

The Python SABI library directories.

Added in version 3.26.

The Python runtime SABI library directories.

Python version.
Python major version.
Python minor version.
Python patch version.
Added in version 3.18.

Python PyPy version.

Added in version 3.14.

System has the NumPy.

Added in version 3.14.

The NumPy include directories.

Added in version 3.14.

The NumPy version.


Hints

Define the root directory of a Python installation.
  • 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 will be ignored on Windows because static libraries are not available on this platform.


Added in version 3.16.

This variable defines which ABIs, as defined in PEP 3149, should be searched.

NOTE:

This hint will be honored only when searched for Python version 3.


The Python_FIND_ABI variable is a 4-tuple specifying, in that 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.

Each element can be set to one of the following:

  • ON: Corresponding flag is selected.
  • OFF: Corresponding flag is not selected.
  • ANY: The two possibilities (ON and OFF) will be searched.

NOTE:

If Python3_FIND_ABI is not defined, any ABI, excluding the gil_disabled flag, will be searched.


From this 4-tuple, various ABIs will be searched starting from the most specialized to the most general. Moreover, when ANY is specified for pydebug and gil_disabled, debug and free threaded versions will be searched after non-debug and non-gil-disabled ones.

For example, if we have:

set (Python_FIND_ABI "ON" "ANY" "ANY" "ON")


The following flags combinations will be appended, in that order, to the artifact names: tdmu, tdm, tdu, and td.

And to search any possible ABIs:

set (Python_FIND_ABI "ANY" "ANY" "ANY" "ANY")


The following combinations, in that order, will be used: mu, m, u, <empty>, dmu, dm, du, d, tmu, tm, tu, t, tdmu, tdm, tdu, and td.

NOTE:

This hint is useful only on POSIX systems except for the gil_disabled flag. So, on Windows systems, when Python_FIND_ABI is defined, Python distributions from python.org will be found only if the value for each flag is OFF or ANY except for the fourth one (gil_disabled).


Added in version 3.15.

This variable defines how lookup will be done. The Python_FIND_STRATEGY variable can be set to one of the following:

  • 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.

Added in version 3.13.

On Windows the Python_FIND_REGISTRY variable determine the order of preference between registry and environment variables. the Python_FIND_REGISTRY variable can be set to one of the following:

  • 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.

Added in version 3.15.

On macOS the Python_FIND_FRAMEWORK variable determine the order of preference between Apple-style and unix-style package components. This variable can take same values as CMAKE_FIND_FRAMEWORK variable.

NOTE:

Value ONLY is not supported so FIRST will be used instead.


If Python_FIND_FRAMEWORK is not defined, CMAKE_FIND_FRAMEWORK variable will be used, if any.

Added in version 3.15.

This variable defines the handling of virtual environments managed by virtualenv or conda. It is meaningful only when a virtual environment is active (i.e. the activate script has been evaluated). In this case, it takes precedence over Python_FIND_REGISTRY and CMAKE_FIND_FRAMEWORK variables. The Python_FIND_VIRTUALENV variable can be set to one of the following:

  • 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.


Added in version 3.18.

This variable defines, in an ordered list, the different implementations which will be searched. The Python_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.
  • PyPy: This implementation use RPython language and RPython translation toolchain to produce the python interpreter. See PyPy.

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 Python_FIND_STRATEGY=LOCATION, each location will be search first for IronPython and second for CPython.


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.


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. The Python_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 python2.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 Python_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:

The path to the interpreter.
The path to the compiler.
Added in version 3.18.

The .Net interpreter. Only used by IronPython implementation.

The path to the library. It will be used to compute the variables Python_LIBRARIES, Python_LIBRARY_DIRS and Python_RUNTIME_LIBRARY_DIRS.
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.

The path to the directory of the Python headers. It will be used to compute the variable Python_INCLUDE_DIRS.
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 be ignored.


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.



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:

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.

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. 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 library type is MODULE, to target Python::Module or Python::SABIModule (when 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 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 <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 was introduced. Specifying only major version 3 is equivalent to 3.2.

When 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 Python_DEBUG_POSTFIX variable if defined.

FindPython2

Added in version 3.12.

Find Python 2 interpreter, compiler and development environment (include directories and libraries).

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.

NumPy: search for NumPy include directories.

Added in version 3.14: Added the NumPy component.

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 (Python2 COMPONENTS Interpreter Development)


This module looks only for version 2 of Python. This module can be used concurrently with FindPython3 module to use both Python versions.

The FindPython module can be used if Python version does not matter for you.

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 defines the following Imported Targets:

Changed in version 3.14: Imported Targets are only created when CMAKE_ROLE is PROJECT.

Python 2 interpreter. This target is defined only if the Interpreter component is found.
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.

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

Python 2 compiler. This target is defined only if the Compiler component is found.
Added in version 3.15.

Python 2 library for Python module. Target defined if component Development.Module is found.

Python 2 library for Python embedding. Target defined if component Development.Embed is found.
Added in version 3.14.

NumPy library for Python 2. Target defined if component NumPy is found.


Result Variables

This module will set the following variables in your project (see Standard Variable Names):

System has the Python 2 requested components.
System has the Python 2 interpreter.
Path to the Python 2 interpreter.
Added in version 3.30.

Path to the debug Python 2 interpreter. It is only defined on the Windows platform.

Added in version 3.30.

Path to the Python 2 interpreter, defined as a generator expression selecting the Python2_EXECUTABLE or Python2_EXECUTABLE_DEBUG variable based on the context (platform, configuration).

  • Python
  • ActivePython
  • Anaconda
  • Canopy
  • IronPython
  • PyPy


Standard platform independent installation directory.

Information returned by sysconfig.get_path('stdlib') or else distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True).

Standard platform dependent installation directory.

Information returned by sysconfig.get_path('platstdlib') or else distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True).

Third-party platform independent installation directory.

Information returned by sysconfig.get_path('purelib') or else distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False).

Third-party platform dependent installation directory.

Information returned by sysconfig.get_path('platlib') or else distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False).

System has the Python 2 compiler.
Path to the Python 2 compiler. Only offered by IronPython.

Added in version 3.18.

The .Net interpreter. Only used by IronPython implementation.

System has the Python 2 development artifacts.
Added in version 3.18.

System has the Python 2 development artifacts for Python module.

Added in version 3.18.

System has the Python 2 development artifacts for Python embedding.

The Python 2 include directories.
Added in version 3.30.

Postfix of debug python module. This variable can be used to define the DEBUG_POSTFIX target property.

Added in version 3.19.

The Python 2 link options. Some configurations require specific link options for a correct build and execution.

The Python 2 libraries.
The Python 2 library directories.
The Python 2 runtime library directories.
Python 2 version.
Python 2 major version.
Python 2 minor version.
Python 2 patch version.
Added in version 3.18.

Python 2 PyPy version.

Added in version 3.14.

System has the NumPy.

Added in version 3.14.

The NumPy include directories.

Added in version 3.14.

The NumPy version.


Hints

Define the root directory of a Python 2 installation.
  • 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 will be ignored on Windows because static libraries are not available on this platform.


Added in version 3.15.

This variable defines how lookup will be done. The Python2_FIND_STRATEGY variable can be set to one of the following:

  • 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 Python2_FIND_UNVERSIONED_NAMES.

Added in version 3.13.

On Windows the Python2_FIND_REGISTRY variable determine the order of preference between registry and environment variables. the Python2_FIND_REGISTRY variable can be set to one of the following:

  • 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.

Added in version 3.15.

On macOS the Python2_FIND_FRAMEWORK variable determine the order of preference between Apple-style and unix-style package components. This variable can take same values as CMAKE_FIND_FRAMEWORK variable.

NOTE:

Value ONLY is not supported so FIRST will be used instead.


If Python2_FIND_FRAMEWORK is not defined, CMAKE_FIND_FRAMEWORK variable will be used, if any.

Added in version 3.15.

This variable defines the handling of virtual environments managed by virtualenv or conda. It is meaningful only when a virtual environment is active (i.e. the activate script has been evaluated). In this case, it takes precedence over Python2_FIND_REGISTRY and CMAKE_FIND_FRAMEWORK variables. The Python2_FIND_VIRTUALENV variable can be set to one of the following:

  • 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 Python2_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.


Added in version 3.18.

This variable defines, in an ordered list, the different implementations which will be searched. The Python2_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.
  • PyPy: This implementation use RPython language and RPython translation toolchain to produce the python interpreter. See PyPy.

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 Python2_FIND_STRATEGY=LOCATION, each location will be search first for IronPython and second for CPython.


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.


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. The Python2_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 python2.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 Python2_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:

The path to the interpreter.
The path to the compiler.
Added in version 3.18.

The .Net interpreter. Only used by IronPython implementation.

The path to the library. It will be used to compute the variables Python2_LIBRARIES, Python2_LIBRARY_DIRS and Python2_RUNTIME_LIBRARY_DIRS.
The path to the directory of the Python headers. It will be used to compute the variable Python2_INCLUDE_DIRS.
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 ignored.


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.



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:

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.

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(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 library type is MODULE, to target Python2::Module and takes care of Python module naming rules:

Python2_add_library (<name> [STATIC | SHARED | MODULE]

<source1> [<source2> ...])


If 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 Python2_DEBUG_POSTFIX variable if defined.

FindPython3

Added in version 3.12.

Find Python 3 interpreter, compiler and development environment (include directories and libraries).

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.

NumPy: search for NumPy include directories.

Added in version 3.14: Added the NumPy component.

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 FindPython2 module to use both Python versions.

The FindPython module can be used if Python version does not matter for you.

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 defines the following Imported Targets:

Changed in version 3.14: Imported Targets are only created when CMAKE_ROLE is PROJECT.

Python 3 interpreter. This target is defined only if the Interpreter component is found.
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.

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

Python 3 compiler. This target is defined only if the Compiler component is found.
Added in version 3.15.

Python 3 library for Python module. Target defined if component Development.Module is found.

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.

Python 3 library for Python embedding. Target defined if component Development.Embed is found.
Added in version 3.14.

NumPy library for Python 3. Target defined if component NumPy is found.


Result Variables

This module will set the following variables in your project (see Standard Variable Names):

System has the Python 3 requested components.
System has the Python 3 interpreter.
Path to the Python 3 interpreter.
Added in version 3.30.

Path to the debug Python 3 interpreter. It is only defined on Windows platform.

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).

  • Python
  • ActivePython
  • Anaconda
  • Canopy
  • IronPython
  • PyPy


Standard platform independent installation directory.

Information returned by sysconfig.get_path('stdlib').

Standard platform dependent installation directory.

Information returned by sysconfig.get_path('platstdlib').

Third-party platform independent installation directory.

Information returned by sysconfig.get_path('purelib').

Third-party platform dependent installation directory.

Information returned by sysconfig.get_path('platlib').

Added in version 3.17.

Extension suffix for modules.

Information computed from sysconfig.get_config_var('EXT_SUFFIX') or sysconfig.get_config_var('SOABI') or python3-config --extension-suffix.

Added in version 3.26.

Extension suffix for modules using the Stable Application Binary Interface.

Information computed from importlib.machinery.EXTENSION_SUFFIXES if the COMPONENT Interpreter was specified. Otherwise, the extension is abi3 except for Windows, MSYS and CYGWIN for which this is an empty string.

System has the Python 3 compiler.
Path to the Python 3 compiler. Only offered by IronPython.

Added in version 3.18.

The .Net interpreter. Only used by IronPython implementation.


Python3_Development_FOUND

System has the Python 3 development artifacts.


Added in version 3.18.

System has the Python 3 development artifacts for Python module.

Added in version 3.26.

System has the Python 3 development artifacts for Python module using the Stable Application Binary Interface.

Added in version 3.18.

System has the Python 3 development artifacts for Python embedding.


Python3_INCLUDE_DIRS

The Python 3 include directories.


Added in version 3.30.3.

The Python 3 preprocessor definitions.

Added in version 3.30.

Postfix of debug python module. This variable can be used to define the DEBUG_POSTFIX target property.

Added in version 3.19.

The Python 3 link options. Some configurations require specific link options for a correct build and execution.

The Python 3 libraries.
The Python 3 library directories.
The Python 3 runtime library directories.
Added in version 3.26.

The Python 3 libraries for the Stable Application Binary Interface.

Added in version 3.26.

The Python 3 SABI library directories.

Added in version 3.26.

The Python 3 runtime SABI library directories.

Python 3 version.
Python 3 major version.
Python 3 minor version.
Python 3 patch version.
Added in version 3.18.

Python 3 PyPy version.

Added in version 3.14.

System has the NumPy.

Added in version 3.14.

The NumPy include directories.

Added in version 3.14.

The NumPy version.


Hints

Define the root directory of a Python 3 installation.
  • 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 will be ignored on Windows because static libraries are not available on this platform.


Added in version 3.16.

This variable defines which ABIs, as defined in PEP 3149, should be searched.

The Python3_FIND_ABI variable is a 4-tuple specifying, in that 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.

Each element can be set to one of the following:

  • ON: Corresponding flag is selected.
  • OFF: Corresponding flag is not selected.
  • ANY: The two possibilities (ON and OFF) will be searched.

NOTE:

If Python3_FIND_ABI is not defined, any ABI, excluding the gil_disabled flag, will be searched.


From this 4-tuple, various ABIs will be searched starting from the most specialized to the most general. Moreover, when ANY is specified for pydebug and gil_disabled, debug and free threaded versions will be searched after non-debug and non-gil-disabled ones.

For example, if we have:

set (Python3_FIND_ABI "ON" "ANY" "ANY" "ON")


The following flags combinations will be appended, in that order, to the artifact names: tdmu, tdm, tdu, and td.

And to search any possible ABIs:

set (Python3_FIND_ABI "ANY" "ANY" "ANY" "ANY")


The following combinations, in that order, will be used: mu, m, u, <empty>, dmu, dm, du, d, tmu, tm, tu, t, tdmu, tdm, tdu, and td.

NOTE:

This hint is useful only on POSIX systems except for the gil_disabled flag. So, on Windows systems, when Python_FIND_ABI is defined, Python distributions from python.org will be found only if the value for each flag is OFF or ANY except for the fourth one (gil_disabled).


Added in version 3.15.

This variable defines how lookup will be done. The Python3_FIND_STRATEGY variable can be set to one of the following:

  • 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 Python3_FIND_UNVERSIONED_NAMES.

Added in version 3.13.

On Windows the Python3_FIND_REGISTRY variable determine the order of preference between registry and environment variables. The Python3_FIND_REGISTRY variable can be set to one of the following:

  • 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.

Added in version 3.15.

On macOS the Python3_FIND_FRAMEWORK variable determine the order of preference between Apple-style and unix-style package components. This variable can take same values as CMAKE_FIND_FRAMEWORK variable.

NOTE:

Value ONLY is not supported so FIRST will be used instead.


If Python3_FIND_FRAMEWORK is not defined, CMAKE_FIND_FRAMEWORK variable will be used, if any.

Added in version 3.15.

This variable defines the handling of virtual environments managed by virtualenv or conda. It is meaningful only when a virtual environment is active (i.e. the activate script has been evaluated). In this case, it takes precedence over Python3_FIND_REGISTRY and CMAKE_FIND_FRAMEWORK variables. The Python3_FIND_VIRTUALENV variable can be set to one of the following:

  • 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 Python3_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.


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.
  • PyPy: This implementation use RPython language and RPython translation toolchain to produce the python interpreter. See PyPy.

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.


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.


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:

The path to the interpreter.
The path to the compiler.
Added in version 3.18.

The .Net interpreter. Only used by IronPython implementation.

The path to the library. It will be used to compute the variables Python3_LIBRARIES, Python3_LIBRARY_DIRS and Python3_RUNTIME_LIBRARY_DIRS.
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.

The path to the directory of the Python headers. It will be used to compute the variable Python3_INCLUDE_DIRS.
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.


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.



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:

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.

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 was introduced. Specifying only major version 3 is equivalent to 3.2.

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

This module finds Qt3, a cross-platform application development framework for creating graphical user interfaces and applications.

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.


Result Variables

This module sets the following variables:

True if Qt3 has been found.
True if Qt3 has been found. This variable is for compatibility with other Qt find modules.
The version of Qt3 that was found.
Libraries needed to link against for using Qt3.
A list of compile definitions to use when compiling code that uses Qt3.

Cache Variables

The following cache variables may also be set:

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:

Path to the moc tool.
Path to the uic tool.
Path to the Qt3 library.
Path to the qtmain library. This is only required by Qt3 on Windows.

Hints

To search for the multithreaded version of Qt3, set this variable to TRUE before looking for Qt3.

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

This module finds Qt4, a cross-platform application development framework for creating graphical user interfaces and applications. It 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 using Imported Targets, the qtmain.lib static library is automatically linked on Windows for WIN32 executables. To disable this globally, set the QT4_NO_LINK_QTMAIN variable before finding Qt4. To disable this for a particular executable, set the QT4_NO_LINK_QTMAIN target property to TRUE on that executable.


Qt Build Tools

Qt relies on some bundled tools for code generation, such as moc for meta-object code generation, uic for widget layout and population, and rcc for virtual filesystem content generation. These tools may be automatically invoked by cmake(1) if the appropriate conditions are met. See cmake-qt(7) for more.

Imported Targets

Qt libraries can be linked using their corresponding IMPORTED target with the target_link_libraries() command:

target_link_libraries(myexe Qt4::QtGui Qt4::QtXml)


Linking to an imported target automatically applies the correct include directories and compile definitions when building myexe.

Imported targets also manage their dependencies, so listing Qt4::QtCore is unnecessary if another Qt library depends on it. Likewise, Qt4::QtGui is automatically included when linking Qt4::QtDeclarative. Targets can be checked for existence using if(TARGET) command.

If both debug and release versions of a Qt toolkit library are available, CMake selects the appropriate one based on the build configuration.

This module provides the following imported targets, if found:

The QtCore target
The QtGui target
The Qt3Support target
The QtAssistant target
The QtAssistantClient target
The QAxContainer target (Windows only)
The QAxServer target (Windows only)
The QtDBus target
The QtDeclarative target
The QtDesigner target
The QtDesignerComponents target
The QtHelp target
The QtMotif target
The QtMultimedia target
The QtNetwork target
The QtNsPlugin target
The QtOpenGL target
The QtScript target
The QtScriptTools target
The QtSql target
The QtSvg target
The QtTest target
The QtUiTools target
The QtWebKit target
The QtXml target
The QtXmlPatterns target
The phonon target

Result Variables

This module sets the following variables:

Boolean whether Qt4 has been found. If false, don't try to use Qt4.
Boolean whether Qt4 has been found. If false, don't try to use Qt4. This variable is for compatibility with other Qt find modules.
Boolean whether Qt4 has been found. If false, don't try to use Qt4. This variable is for backward compatibility only.
The major version of Qt found.
The minor version of Qt found.
The patch version of Qt found.

Hints

If set to boolean true before finding Qt4, it globally disables linking qtmain.lib static library on Windows.

Macros

In some cases it can be necessary or useful to invoke the Qt build tools in a more-manual way. This module provides the following macros to add targets for such uses:

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.
If specified, the INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS target properties from the <target> are passed to moc.
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.



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.
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.



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.
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.



Creates a build rule that generates 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, e.g. because a custom filename is needed for the moc file or similar.

If specified, the INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS target properties from the <target> are passed to moc.


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>).

Additional parameters can be passed to the qdbusxml2cpp call by setting the following source file properties on the input file <interface-file>:

The given file will be included in the generate interface header.
The name of the generated class.
The generated class will not be wrapped in a namespace.


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.


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>.


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 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.
A list of options that may be given to qdbuscpp2xml, such as those found when executing qdbuscpp2xml --help.


Creates build rules for generating TS and QM files:

qt4_create_translation(<qm-files-var> <directories>... <sources>...

<ts-files>... [OPTIONS <options>...])


This macro creates build rules to generate TS (Translation Source files .ts) files via lupdate and QM (Qt Message files .qm) files via lrelease from the given <directories> and/or <sources>. The TS files are created and/or updated in the source tree (unless given with full paths). The QM files are generated in the build tree.

<qm-files-var>
A list of generated QM files is stored in this variable. Updating the translations can be done by adding the <qm-files-var> to the source list of the project library/executable, so they are always updated, or by adding a custom target to control when they get updated/generated.
<directories>
A list of directories containing source files.
<sources>
A list of source files.
<ts-files>
A list of TS (Translation Source) files.
Optional list of flags passed to lupdate, such as -extensions, to specify file extensions for directory scanning.


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 stores a list of generated filenames of QM files in the <qm-files-var> variable. The <ts-files> must exist and are not updated in any way.


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), the #include "foo.moc" can be inserted in foo.cpp and then foo.cpp given as 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, file will be ignored by this macro.

If specified, the INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS target properties from the <target> are passed to moc.


Deprecated since version 2.8.11: Use target_link_libraries() with Imported Targets instead.

Provides Qt modules to a project for linking 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 to link to the library, add the relevant include directories for the module, and add the relevant compiler defines for using the module. Modules are roughly equivalent to Qt4 components.

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.


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.

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.


Result Variables

This module defines the following variables:

Boolean indicating whether the QuickTime is found. For backward compatibility, the QUICKTIME_FOUND variable is also set to the same value.

Cache Variables

The following cache variables may also be set:

The path to the QuickTime library.
Directory containing QuickTime headers.

Hints

This module accepts the following variables:

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 QuickTime library: ./configure --prefix=$QUICKTIME_DIR.

Examples

Finding QuickTime library:

find_package(QuickTime)


FindRTI

Finds HLA RTI standard libraries and their include directories.

RTI (Run-Time Infrastructure) is a simulation infrastructure standardized by IEEE and SISO, required when implementing HLA (High Level Architecture). It provides a well-defined C++ API, ensuring that M&S (Modeling and Simulation) applications remain independent of a particular RTI implementation.

Result Variables

This module defines the following variables:

Set to FALSE if any HLA RTI was not found.
The libraries to link against to use RTI.
Compile definitions for using RTI. Default value is set to -DRTI_USES_STD_FSTREAM.

Cache Variables

The following cache variables may also be set:

Directory where RTI include files are found.

Examples

Finding RTI:

find_package(RTI)


FindRuby

This module determines if Ruby is installed and finds the locations of its include files and libraries. Ruby 1.8 through 3.4 are supported.

The minimum required version of Ruby can be specified using the standard syntax, e.g.

find_package(Ruby 3.2.6 EXACT REQUIRED)
# OR
find_package(Ruby 3.2)


Virtual environments, such as RVM or RBENV, are supported.

Result Variables

This module will set the following variables in your project:

set to true if ruby was found successfully
full path to the ruby binary
include dirs to be used when using the ruby library
Added in version 3.18: libraries needed to use ruby from C.

the version of ruby which was found, e.g. "3.2.6"
Ruby major version.
Ruby minor version.
Ruby patch version.

Changed in version 3.18: Previous versions of CMake used the RUBY_ prefix for all variables.

Deprecated since version 4.0: The following variables are deprecated. See policy CMP0185.

same as Ruby_EXECUTABLE.
same as Ruby_INCLUDE_DIRS.
same as Ruby_INCLUDE_DIRS.
same as Ruby_LIBRARY.
same as Ruby_VERSION.
same as Ruby_FOUND.

Hints

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:

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:

Requires that the MY_RUBY_HOME environment environment is defined.
Requires that rbenv is installed in ~/.rbenv/bin or that the RBENV_ROOT environment variable is defined.


FindSDL

Finds the SDL (Simple DirectMedia Layer) library. SDL is a cross-platform library for developing multimedia software, such as games and emulators.

NOTE:

This module is specifically intended for SDL version 1. Starting with version 2, SDL provides a CMake package configuration file when built with CMake and should be found using find_package(SDL2). Similarly, SDL version 3 can be found using find_package(SDL3). These newer versions provide separate Imported Targets that encapsulate usage requirements. Refer to the official SDL documentation for more information.


Note that the include path for the SDL header has changed in recent SDL 1 versions from SDL/SDL.h to simply SDL.h. This change aligns with SDL's convention of using #include "SDL.h" for portability, as not all systems install the headers in a SDL/ subdirectory (e.g., FreeBSD).

When targeting macOS and using the SDL framework, be sure to include both SDLmain.h and SDLmain.m in the project. For other platforms, the SDLmain library is typically linked using -lSDLmain, which this module will attempt to locate automatically. Additionally, for macOS, this module will add the -framework Cocoa flag as needed.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.19.

Target encapsulating the SDL library usage requirements, available if SDL is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) SDL is found.
Added in version 3.19.

The human-readable string containing the version of SDL found.

Added in version 3.19.

The major version of SDL found.

Added in version 3.19.

The minor version of SDL found.

Added in version 3.19.

The patch version of SDL found.

Added in version 3.19.

Include directories needed to use SDL.

Added in version 3.19.

Libraries needed to link against to use SDL.


Cache Variables

These variables may optionally be set to help this module find the correct files:

The directory containing the SDL.h header file.
A list of libraries containing the path to the SDL library and libraries needed to link against to use SDL.

Hints

This module accepts the following variables:

When set to boolean true, the SDL_main library will be excluded from linking, as it is not required when building the SDL library itself (only applications need main() function). If not set, this module assumes an application is being built and attempts to locate and include the appropriate SDL_main link flags in the returned SDL_LIBRARY variable.
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 to modify the search paths.


Troubleshooting

In case the SDL library is not found automatically, the SDL_LIBRARY_TEMP variable may be empty, and SDL_LIBRARY will not be set. This typically means that CMake could not locate the SDL library (e.g., SDL.dll, libSDL.so, SDL.framework, etc.). To resolve this, manually set SDL_LIBRARY_TEMP to the correct path and reconfigure the project. Similarly, if SDLMAIN_LIBRARY is unset, it may also need to be specified manually. These variables are used to construct the final SDL_LIBRARY value. If they are not set, SDL_LIBRARY will remain undefined.

Deprecated Variables

These variables are obsolete and provided for backwards compatibility:

Deprecated since version 3.19: Superseded by the SDL_VERSION with the same value.

The human-readable string containing the version of SDL if found.


Examples

Finding SDL library and linking it to a project target:

find_package(SDL)
target_link_libraries(project_target PRIVATE SDL::SDL)


When working with SDL version 2, the upstream package provides the SDL2::SDL2 imported target directly. It can be used in a project without using this module:

find_package(SDL2)
target_link_libraries(project_target PRIVATE SDL2::SDL2)


Similarly, for SDL version 3:

find_package(SDL3)
target_link_libraries(project_target PRIVATE SDL3::SDL3)


See Also

  • The FindSDL_gfx module to find the SDL_gfx library.
  • The FindSDL_image module to find the SDL_image library.
  • The FindSDL_mixer module to find the SDL_mixer library.
  • The FindSDL_net module to find the SDL_net library.
  • The FindSDL_sound module to find the SDL_sound library.
  • The FindSDL_ttf module to find the SDL_ttf library.

FindSDL_gfx

Added in version 3.25.

Finds the SDL_gfx library that provides graphics support in SDL (Simple DirectMedia Layer) applications.

NOTE:

This module is for SDL_gfx version 1. For version 2 or newer usage refer to the upstream documentation.


Imported Targets

This module provides the following Imported Targets:

Target encapsulating the SDL_gfx library usage requirements, available if SDL_gfx is found.

Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) SDL_gfx library is found. For backward compatibility, the SDL_GFX_FOUND variable is also set to the same value.
The human-readable string containing the version of SDL_gfx found.

Cache Variables

The following cache variables may also be set:

The directory containing the headers needed to use SDL_gfx.
The path to the SDL_gfx library needed to link against to use SDL_gfx.

Hints

This module accepts the following variables:

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.

Examples

Finding 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 to find the main SDL library.

FindSDL_image

Finds the SDL_image library that loads images of various formats as SDL (Simple DirectMedia Layer) surfaces.

NOTE:

This module is specifically intended for SDL_image version 1. Starting with version 2.6, SDL_image provides a CMake package configuration file when built with CMake and should be found using find_package(SDL2_image). Similarly, SDL_image version 3 can be found using find_package(SDL3_image). These newer versions provide Imported Targets that encapsulate usage requirements. Refer to the official SDL documentation for more information.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) SDL_image library is found. For backward compatibility, the SDL_IMAGE_FOUND variable is also set to the same value.
The human-readable string containing the version of SDL_image found.
Include directories containing headers needed to use the SDL_image library.
Libraries needed to link against to use the SDL_image library.

Hints

This module accepts the following variables:

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

For backward compatibility the following variables are also set:

Deprecated since version 2.8.10: Use the SDL_image_FOUND, which has the same value.

Deprecated since version 2.8.10: Use the SDL_IMAGE_INCLUDE_DIRS, which has the same value.

Deprecated since version 2.8.10: Use the SDL_IMAGE_LIBRARIES, which has the same value.


Examples

Finding SDL_image library and creating an imported interface target for linking it to a project target:

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 working with SDL_image version 2, the upstream package provides the SDL2_image::SDL2_image imported target directly. It can be used in a project without using this module:

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 to find the main SDL library.

FindSDL_mixer

Finds the SDL_mixer library that provides an audio mixer with support for various file formats in SDL (Simple DirectMedia Layer) applications.

NOTE:

This module is specifically intended for SDL_mixer version 1. 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 that encapsulate usage requirements. Refer to the official SDL documentation for more information.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) SDL_mixer library is found. For backward compatibility, the SDL_MIXER_FOUND variable is also set to the same value.
The human-readable string containing the version of SDL_mixer found.
Include directories containing headers needed to use the SDL_mixer library.
Libraries needed to link against to use SDL_mixer.

Hints

This module accepts the following variables:

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

For backward compatibility the following variables are also set:

Deprecated since version 2.8.10: Use SDL_mixer_FOUND, which has the same value.

Deprecated since version 2.8.10: Use SDL_MIXER_INCLUDE_DIRS, which has the same value.

Deprecated since version 2.8.10: Use SDL_MIXER_LIBRARIES, which has the same value.


Examples

Finding SDL_mixer library and creating an imported interface target for linking it to a project target:

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 to find the main SDL library.

FindSDL_net

Finds the SDL_net library, a cross-platform network library for use with the SDL (Simple DirectMedia Layer) applications.

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 that encapsulate usage requirements. Refer to the official SDL documentation for more information.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) SDL_net library is found. For backward compatibility, the SDL_NET_FOUND variable is also set to the same value.
The human-readable string containing the version of SDL_net found.
Include directories containing headers needed to use the SDL_net library.
Libraries needed to link against to use the SDL_net library.

Deprecated Variables

For backward compatibility the following variables are also set:

Deprecated since version 2.8.10: Use the SDL_net_FOUND, which has the same value.

Deprecated since version 2.8.10: Use the SDL_NET_INCLUDE_DIRS, which has the same value.

Deprecated since version 2.8.10: Use the SDL_NET_LIBRARIES, which has the same value.


Hints

This module accepts the following variables:

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.

Examples

Finding 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 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.

NOTE:

This module is specifically intended for SDL_sound version 1. 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 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).

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:

Boolean indicating whether the (requested version of) SDL_sound library is found. For backward compatibility, the SDL_SOUND_FOUND variable is also set to the same value.
The human-readable string containing the version of SDL_sound found.
Libraries needed to link against to use the SDL_sound library.

Cache Variables

The following cache variables may also be set:

The directory containing the SDL_sound.h and other headers needed to use the 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.
The path to the dependent MikMod library.
The path to the dependent ModPlug library (libmodplug).
The path to the dependent Ogg library.
The path to the dependent Vorbis library.
The path to the dependent SMPEG library.
The path to the dependent FLAC library.
The path to the dependent Speex library.

Hints

This module accepts the following variables:

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 to modify the search paths.

Environment variable that works the same as SDLDIR.
This is an optional cache variable that can be used to add additional flags that are prepended to the SDL_SOUND_LIBRARIES result variable. This is available mostly for cases this module failed to anticipate for and additional flags must be added.

Examples

Finding SDL_sound library and creating an imported interface target for linking it to a project target:

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 working with SDL_sound version 2, the upstream package provides the SDL2_sound::SDL2_sound imported target directly. It can be used in a project without using this module:

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.

FindSDL_ttf

Finds the SDL_ttf library that provides support for rendering text with TrueType fonts in SDL (Simple DirectMedia Layer) applications.

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.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) SDL_ttf library is found. For backward compatibility, the SDL_TTF_FOUND variable is also set to the same value.
The human-readable string containing the version of SDL_ttf found.
Include directories containing headers needed to use SDL_ttf library.
Libraries needed to link against to use SDL_ttf.

Deprecated Variables

For backward compatibility the following variables are also set:

Deprecated since version 2.8.10: Replaced with SDL_ttf_FOUND, which has the same value.

Deprecated since version 2.8.10: Replaced with SDL_TTF_INCLUDE_DIRS, which has the same value.

Deprecated since version 2.8.10: Replaced with SDL_TTF_LIBRARIES, which has the same value.


Hints

This module accepts the following variables:

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.

Examples

Finding 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.

FindSelfPackers

Finds UPX, the Ultimate Packer for eXecutables.

This module searches for executable packers-tools that compress executables or shared libraries into on-the-fly, self-extracting versions. It currently supports UPX.

Cache Variables

The following cache variables may be set:

Path to the executable packer for compressing executables.
Path to the executable packer for compressing shared libraries.
Command-line options to use when compressing executables.
Command-line options to use when compressing shared libraries.

Examples

Finding UPX:

find_package(SelfPackers)


FindSquish

Finds Squish, a cross-platform automated GUI testing framework for applications built on various GUI technologies. Squish supports testing of both native and cross-platform toolkits, such as Qt, Java, and Tk.

Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) Squish is found. For backward compatibility, the SQUISH_FOUND variable is also set to the same value.
The full version of the Squish found.
The major version of the Squish found.
The minor version of the Squish found.
The patch version of the Squish found.
Boolean indicating whether the Squish installation directory is found.
Boolean indicating whether the Squish server executable is found.
Boolean indicating whether the Squish client executable is found.

Cache Variables

The following cache variables may also be set:

The Squish installation directory containing bin, lib, etc.
The path to the squishserver executable.
The path to the squishrunner executable.

Commands

This module provides the following commands, if Squish is found:

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.

The arguments are:

<name>
The name of the test. This is passed as the first argument to the add_test() command.
The name of the CMake target to be used as the AUT (Application Under Test), i.e., the executable that will be tested.
Either the full path to the Squish test suite or just the suite name (i.e., the last directory name of the suite). In the latter case, the CMakeLists.txt invoking squish_add_test() must reside in the parent directory of the suite.
The name of the Squish test, corresponding to the subdirectory of the test within the suite directory.
An optional command to execute before starting the Squish test. Pass it as a string. This may be a single command, or a semicolon-separated list of command and arguments.
An optional command to execute after the Squish test has completed. Pass it as a string. This may be a single command, or a semicolon-separated list of command and arguments.
Deprecated since version 3.18: This argument is now ignored. It was previously used to specify a settings group name for executing the test instead of the default value CTest_<username>.


Changed in version 3.18: In previous CMake versions, this command was named squish_v4_add_test().


Adds a Squish test to the project, when using 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. Use a newer Squish version, and squish_add_test() command.


The arguments are:

<name>
The name of the test.
<application-under-test>
The path to the executable used as the AUT (Application Under Test), i.e., the executable that will be tested.
<squish-test-case-name>
The name of the Squish test, corresponding to 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 needed by the test case.


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()


FindSQLite3

Added in version 3.14.

Finds the SQLite 3 library. SQLite is a small, fast, self-contained, high-reliability, and full-featured SQL database engine written in C, intended for embedding in applications.

Imported Targets

This module provides the following Imported Targets:

Target encapsulating SQLite library usage requirements. It is available only when SQLite is found.

Result Variables

This module sets the following variables:

Include directories containing the sqlite3.h and related headers needed to use SQLite.
Libraries needed to link against to use SQLite.
Version of the SQLite library found.
Boolean indicating whether the SQLite library is found.

Examples

Finding the SQLite library and linking it to a project target:

find_package(SQLite3)
target_link_libraries(project_target PRIVATE SQLite::SQLite3)


FindSubversion

Finds a Subversion command-line client executable (svn) and provides commands for extracting information from a Subversion working copy:

find_package(Subversion [<version>] [...])


Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) Subversion command-line client is found. For backward compatibility, the SUBVERSION_FOUND variable is also set to the same value.
Version of the svn command-line client found.

Cache Variables

The following cache variables may also be set:

Path to the svn command-line client.

Commands

This module provides the following commands if the Subversion command-line client is found:

Extracts information from a Subversion working copy located 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 is generated:

<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:

Added in version 3.13.

When specified, errors from Subversion operation will not trigger a SEND_ERROR message. In case of an error, the <var-prefix>_* variables remain undefined.



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>.


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 (if not found, processing stops with an error message):

find_package(Subversion REQUIRED)


Example: Using Subversion

Finding Subversion and retrieving information 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

Find the Simplified Wrapper and Interface Generator (SWIG) executable.

This module finds an installed SWIG and determines its version.

Added in version 3.18: If a COMPONENTS or OPTIONAL_COMPONENTS argument is given to the find_package() command, it will also determine supported target languages.

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 module defines the following variables:

Whether SWIG and any required components were found on the system.
Path to the SWIG executable.
Path to the installed SWIG Lib directory (result of swig -swiglib).
SWIG executable version (result of swig -version).
If COMPONENTS or OPTIONAL_COMPONENTS are requested, each available target language <lang> (lowercase) will be set to TRUE.

Any COMPONENTS given to find_package should be the names of supported target languages as provided to the LANGUAGE argument of swig_add_library, such as python or perl5. Language names must be lowercase.

All information is collected from the SWIG_EXECUTABLE, so the version to be found can be changed from the command line by means of setting SWIG_EXECUTABLE.

Example usage requiring SWIG 4.0 or higher and 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()


FindTCL

Finds the Tcl (Tool Command Language), dynamic programming language.

This module locates a Tcl installation, including its include directories and libraries, and determines the appropriate Tcl library name for linking. As part of the Tcl ecosystem, it also finds Tk, a GUI toolkit that provides a library of basic widgets for building graphical user interfaces.

Result Variables

This module defines the following variables:

Boolean indicating whether the Tcl is found.
Boolean indicating whether the Tk is found.
Boolean indicating whether both Tcl and Tk are found.

Cache Variables

The following cache variables may also be set:

The path to the Tcl library (e.g., tcl, etc.).
The directory containing tcl.h and other Tcl-related headers needed to use Tcl.
The path to the tclsh command-line executable.
The path to the Tk library (e.g., tk, etc.).
The directory containing tk.h and other Tk-related headers needed to use Tk.
The path to the wish windowing shell command-line executable.

Other Libraries

The Tcl Stub Library can be found using the separate FindTclStub module.

Examples

Finding Tcl:

find_package(TCL)


See Also

  • The FindTclsh module to find the Tcl shell command-line executable.
  • The FindTclStub module to find the Tcl Stubs Library.
  • The 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.

Result Variables

This module defines the following variables:

Boolean indicating whether the tclsh executable (and the requested version, if specified) is found. For backward compatibility, the TCLSH_FOUND variable is also set to the same value.

Cache Variables

The following cache variables may also be set:

The path to the tclsh executable.

Examples

Finding the tclsh command-line executable:

find_package(Tclsh)


See Also

  • The FindTCL module to find the Tcl installation.
  • The FindTclStub module to find the Tcl Stubs Library.

FindTclStub

Finds the Tcl Stub Library, which is used for building version-independent Tcl extensions.

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.

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 to locate Tcl installation and then attempts to find the stub libraries corresponding to the located Tcl version.

Cache Variables

The following cache variables may also be set:

The path to the Tcl stub library.
The path to the Tk stub library.
The path to the ttk stub library.

Examples

Finding Tcl Stubs Library:

find_package(TclStub)


See Also

  • The FindTCL module to find the Tcl installation.
  • The FindTclsh module to find the Tcl shell command-line executable.

Online references:

  • How to Use the Tcl Stubs Library
  • Practical Programming in Tcl and Tk

FindThreads

This module determines the thread library of the system.

Imported Targets

Added in version 3.1.

This module defines the following IMPORTED target:

The thread library, if found.

Result Variables

The following variables are set:

If a supported thread library was found.
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.
If the found thread library is the win32 one.
If the found thread library is pthread compatible.
If the found thread library is the HP thread library.

Variables Affecting Behavior

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 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.


FindTIFF

Finds the TIFF library (libtiff). This module also takes into account the upstream TIFF library's exported CMake package configuration, if available.

Components

This module supports the following components:

Added in version 3.19.

Optional component that ensures that the C++ wrapper library (libtiffxx) is found.


Components can be specified using the standard syntax:

find_package(TIFF [COMPONENTS <components>...])


Imported Targets

This module provides the following Imported Targets:

Added in version 3.5.

Target encapsulating the TIFF library usage requirements, available only if the TIFF is found.

Added in version 3.19.

Target encapsulating the usage requirements for the 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:

Boolean indicating whether the TIFF is found.
The version of the TIFF library found.
The directory containing the TIFF headers.
TIFF libraries to be linked.

Cache Variables

The following cache variables may also be set:

The directory containing the TIFF headers.
Added in version 3.4.

The path to the TIFF library for release configurations.

Added in version 3.4.

The path to the TIFF library for debug configurations.

Added in version 3.19.

The path to the TIFFXX library for release configurations.

Added in version 3.19.

The path to the TIFFXX library for debug configurations.


Examples

Finding TIFF library and linking it to a project target:

find_package(TIFF)
target_link_libraries(project_target PRIVATE TIFF::TIFF)


Finding TIFF and TIFFXX libraries by specifying the CXX component:

find_package(TIFF COMPONENTS CXX)
target_link_libraries(project_target PRIVATE TIFF::CXX)


FindVulkan

Added in version 3.7.

Finds Vulkan, a low-overhead, cross-platform 3D graphics and computing API, along with related development tools typically provided by the Vulkan SDK. This includes commonly used utilities such as shader compilers and SPIR-V tools (e.g., DXC, glslc, glslang, etc.) that support Vulkan-based development workflows.

Components

Added in version 3.24.

This module supports several optional components that can be specified with the find_package() command:

find_package(Vulkan [COMPONENTS <components>...])


Each component provides a corresponding imported target. Supported components include:

Added in version 3.24.

Finds the SPIR-V compiler. This optional component is always implied automatically for backward compatibility, even if not requested.

Added in version 3.24.

Finds the glslangValidator tool that is used to compile GLSL and HLSL shaders into SPIR-V. This optional component is always implied automatically for backward compatibility, even if not requested.

Added in version 3.24.

Finds the Khronos-reference front-end shader parser and SPIR-V code generation library (glslang).

Added in version 3.24.

Finds the Google static library used for Vulkan shader compilation.

Added in version 3.24.

Finds Khronos library for analyzing and transforming SPIR-V modules.

Added in version 3.24.

Finds the Khronos MoltenVK library, which is available on macOS, and implements a subset of Vulkan API over Apple Metal graphics framework.

Added in version 3.25.

Finds the DirectX Shader Compiler (DXC), including the library and command-line tool. Note that Visual Studio also provides a DXC tool, but the version included with the Vulkan SDK is typically required for Vulkan development, as it has Vulkan capability enabled.

Added in version 3.25.

Finds the Vulkan meta-loader volk library, a vector-optimized library of kernels.


Imported Targets

This module provides the following Imported Targets:

Target encapsulating the main Vulkan library usage requirements, available if Vulkan is found.
Added in version 3.19.

Imported executable target encapsulating the GLSLC SPIR-V compiler usage requirements, available if glslc is found.

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. This is useful for applications that load the Vulkan library dynamically at runtime. This target is available if Vulkan is found.

Added in version 3.21.

Imported executable target encapsulating the glslangValidator usage requirements, available if this tool is found.

Added in version 3.24.

Target encapsulating the glslang library usage requirements, available if glslang is found in the SDK.

Added in version 3.24.

Target encapsulating the shaderc_combined library usage requirements, available if this library is found in the SDK.

Added in version 3.24.

Target encapsulating the SPIRV-Tools library usage requirements, available if this library is found in the SDK.

Added in version 3.24.

Target encapsulating the MoltenVK library usage requirements, available if this library is found in the SDK.

Added in version 3.25.

Target encapsulating the volk library usage requirements, available if volk is found in the SDK.

Added in version 3.25.

Target encapsulating the usage requirements for the DirectX shader compiler library, available if DXC library is found in the SDK.

Added in version 3.25.

Imported executable target providing usage requirements for the DirectX shader compiler CLI tool, available if SDK has this tool.


Result Variables

This module defines the following variables:

Boolean indicating whether (the requested version of) Vulkan and all required components are found.
Added in version 3.23.

The version of Vulkan found. Value is retrieved from vulkan/vulkan_core.h.

Include directories needed to use the main Vulkan library.
Libraries needed to link against to use the main Vulkan library.
Added in version 3.24.

Boolean indicating whether the SDK provides the glslc executable.

Added in version 3.24.

Boolean indicating whether the SDK provides the glslangValidator executable.

Added in version 3.24.

Boolean indicating whether the SDK provides the glslang library.

Added in version 3.24.

Boolean indicating whether the SDK provides the shaderc_combined library.

Added in version 3.24.

Boolean indicating whether the SDK provides the SPIRV-Tools library.

Added in version 3.24.

Boolean indicating whether the SDK provides the MoltenVK library.

Added in version 3.25.

Boolean indicating whether the SDK provides the volk library.

Added in version 3.25.

Boolean indicating whether the SDK provides the DirectX shader compiler library.

Added in version 3.25.

Boolean indicating whether the SDK provides the DirectX shader compiler CLI tool.


Cache Variables

The following cache variables may also be set:

The directory containing Vulkan headers.
The path to the Vulkan library.
Added in version 3.19.

The path to the GLSL SPIR-V compiler.

Added in version 3.21.

The path to the glslangValidator tool.

Added in version 3.24.

The path to the glslang library.

Added in version 3.24.

The path to the shaderc_combined library.

Added in version 3.24.

The path to the SPIRV-Tools library.

Added in version 3.24.

The path to the MoltenVK library.

Added in version 3.25.

The path to the volk library.

Added in version 3.25.

The path to the DirectX shader compiler library.

Added in version 3.25.

The path to the DirectX shader compiler CLI tool.


Hints

This module accepts the following variables:

This environment variable can be optionally set to specify the location of the Vulkan SDK root directory for the given architecture. It is typically set by sourcing the toplevel setup-env.sh script of the Vulkan SDK directory into the shell environment.

Examples

Finding the Vulkan library and linking it to a project target:

find_package(Vulkan)
target_link_libraries(project_target PRIVATE Vulkan::Vulkan)


Finding the Vulkan library along with additional components:

find_package(Vulkan COMPONENTS volk)
target_link_libraries(project_target PRIVATE Vulkan::Vulkan Vulkan::volk)


FindWget

This module finds the wget command-line tool for retrieving content from web servers.

Result Variables

This module defines the following local variables:

True if wget has been found.

Cache Variables

The following cache variables may also be set:

The full path to the wget tool.

Examples

Finding wget and executing it in a process:

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.

FindWish

Finds wish, a simple windowing shell command-line executable.

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.

If the UNIX variable is defined, the module will prioritize looking for the Cygwin version of wish executable.

Cache Variables

The following cache variables may be set:

The path to the wish executable.

Examples

Finding wish:

find_package(Wish)
message(STATUS "Found wish at: ${TK_WISH}")


FindwxWidgets

Find a wxWidgets (a.k.a., wxWindows) installation.

This module finds if wxWidgets is installed and selects a default configuration to use. wxWidgets is a modular library. To specify the modules that you will use, you need to name them as components to the package:

find_package(wxWidgets COMPONENTS core base ... OPTIONAL_COMPONENTS net ...)

Added in version 3.4: Support for find_package() version argument; webview component.

Added in version 3.14: OPTIONAL_COMPONENTS support.

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 you should change 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.) wxWidgets_EXCLUDE_COMMON_LIBRARIES
- Set to TRUE to exclude linking of
commonly required libs (e.g., png tiff
jpeg zlib regex expat scintilla lexilla).


For unix style it uses the wx-config utility. You can select between debug/release, unicode/ansi, universal/non-universal, and static/shared in the QtDialog or ccmake interfaces by turning ON/OFF the following variables:

wxWidgets_USE_DEBUG
wxWidgets_USE_UNICODE
wxWidgets_USE_UNIVERSAL
wxWidgets_USE_STATIC


There is also a wxWidgets_CONFIG_OPTIONS variable for all other options that need to be passed to the wx-config utility. For example, to use the base toolkit found in the /usr/local path, set the variable (before calling the FIND_PACKAGE command) as such:

set(wxWidgets_CONFIG_OPTIONS --toolkit=base --prefix=/usr)


The following are set after the configuration is done for both windows and unix style:

wxWidgets_FOUND            - Set to TRUE if wxWidgets was found.
wxWidgets_INCLUDE_DIRS     - Include directories for WIN32

i.e., where to find "wx/wx.h" and
"wx/setup.h"; possibly empty for unices. wxWidgets_LIBRARIES - Path to the wxWidgets libraries. wxWidgets_LIBRARY_DIRS - compile time link dirs, useful for
rpath on UNIX. Typically an empty string
in WIN32 environment. wxWidgets_DEFINITIONS - Contains defines required to compile/link
against WX, e.g. WXUSINGDLL wxWidgets_DEFINITIONS_DEBUG- Contains defines required to compile/link
against WX debug builds, e.g. __WXDEBUG__ wxWidgets_CXX_FLAGS - Include dirs and compiler flags for
unices, empty on WIN32. Essentially
"`wx-config --cxxflags`". wxWidgets_USE_FILE - Convenience include file.


Added in version 3.11: The following environment variables can be used as hints: WX_CONFIG, WXRC_CMD.

Sample usage:

# 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(${wxWidgets_USE_FILE})
# and for each of your dependent executable/library targets:
target_link_libraries(<YourTarget> ${wxWidgets_LIBRARIES}) endif()


If wxWidgets is required (i.e., not an optional part):

find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
# and for each of your dependent executable/library targets:
target_link_libraries(<YourTarget> ${wxWidgets_LIBRARIES})


Imported Targets

Added in version 3.27.

This module defines the following IMPORTED targets:

An interface library providing usage requirements for the found components.

FindX11

Find X11 installation

Try to find X11 on UNIX systems. The following values are defined

X11_FOUND        - True if X11 is available
X11_INCLUDE_DIR  - include directories to use X11
X11_LIBRARIES    - link against these to use X11


and also the following more fine grained variables and targets:

Added in version 3.14: Imported targets.

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


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.

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.

Finds the Apache Xalan-C++ XSL transform processor headers and libraries.

NOTE:

The Xalan-C++ library depends on the Xerces-C++ library, which must be found for this module to succeed.


Imported Targets

This module provides the following Imported Targets:

Target encapsulating the Xalan-C++ library usage requirements, available only if Xalan-C++ is found.

Result Variables

This module defines the following variables:

Boolean indicating whether the Xalan-C++ is found.
The version of the found Xalan-C++ library.
Include directories needed for using Xalan-C++ library. These contain the Xalan-C++ and Xerces-C++ headers.
Libraries needed to link against Xalan-C++. These contain the Xalan-C++ and Xerces-C++ libraries.
The path to the Xalan-C++ library (xalan-c), either release or debug variant.

Cache Variables

The following cache variables may also be set:

The directory containing the Xalan-C++ headers.
The path to a release (optimized) variant of the Xalan-C++ library.
The path to a debug variant of the Xalan-C++ library.

Examples

Finding Xalan-C++ library and linking it to a project target:

find_package(XalanC)
target_link_libraries(project_target PRIVATE XalanC::XalanC)


FindXCTest

Added in version 3.3.

Finds the XCTest framework for writing unit tests in Xcode projects.

NOTE:

Xcode 16 and later includes the Swift Testing framework for writing unit tests in the Swift programming language, which supersedes XCTest.


An XCTest bundle is a CFBundle (Core Foundation Bundle) with a special product type and bundle extension. See the Apple Developer Library for more information in the Testing with Xcode documentation.

Result Variables

This module defines the following variables:

Boolean indicating whether the XCTest framework and executable are found.
Include directories containing the XCTest framework headers needed to use XCTest.
Libraries needed to link against to use XCTest framework.

Cache Variables

The following cache variables may also be set:

The path to the xctest command-line tool used to execute XCTest bundles.

Commands

When XCTest is found, this module provides the following commands to help create and run XCTest bundles:

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.

The arguments are:

<bundle>
Name of the XCTest bundle to create. The XCTEST target property will be set on this bundle.
<testee>
Name of the target to test. Supported types for the testee are Frameworks and App Bundles.
<sources>...
One or more source files to add to the bundle. If not provided, they must be added later using commands like target_sources().

NOTE:

The CMAKE_OSX_SYSROOT variable must be set before using this command.



Adds an XCTest bundle to the project to be 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>.

The arguments are:

<name>
Name of the test as it will appear in CTest.
<bundle>
Target name of the XCTest bundle.


Examples

Finding XCTest and adding tests:

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.

Finds the Apache Xerces-C++ validating XML parser headers and libraries.

Imported Targets

This module defines the following Imported Targets:

Added in version 3.5.

Target encapsulating the Xerces-C++ library (xerces-c) usage requirements, available only if Xerces-C++ is found.


Result Variables

This module defines the following variables:

Boolean indicating whether the Xerces-C++ is found.
The version of the found Xerces-C++ library.
Include directories needed to use Xerces-C++.
Libraries needed to link for using Xerces-C++.
The path to the Xerces-C++ library (xerces-c), either release or debug variant.

Cache Variables

The following cache variables may also be set:

The directory containing the Xerces-C++ headers.
Added in version 3.4.

The path to a release (optimized) variant of the Xerces-C++ library.

Added in version 3.4.

The path to a debug variant of the Xerces-C++ library.


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++. 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.

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.

To list the available features on a system, the xmlrpc-c-config command-line utility can be used.

In CMake, these features can be specified as components with the find_package() command:

find_package(XMLRPC [COMPONENTS <components>...])


Components may be:

C++ wrapper API, replacing the legacy c++ feature.
The legacy C++ wrapper API (superseded by c++2).
XML-RPC client functions (also available as the legacy libwww-based feature named libwww-client).
CGI-based server functions.
Abyss-based server functions.
The pstream-based server functions.
Basic server functions (they are automatically included with *-server features).
Abyss HTTP server (not needed with abyss-server).
OpenSSL convenience functions.

Result Variables

This module defines the following variables:

Include directories containing xmlrpc.h and other headers needed to use the XML-RPC library.
List of libraries needed for linking to XML-RPC library and its requested features.
Boolean indicating whether the XML-RPC library and all its requested components are found.

Examples

Finding XML-RPC library and its client feature to use in the project:

find_package(XMLRPC REQUIRED COMPONENTS client)


FindZLIB

Finds the native zlib data compression library.

Imported Targets

This module provides the following Imported Targets:

Added in version 3.1.

Target that encapsulates the zlib usage requirements. It is available only when zlib is found.


Result Variables

This module defines the following variables:

Include directories containing zlib.h and other headers needed to use zlib.
List of libraries needed to link to zlib.

Changed in version 3.4: Debug and Release library variants can be now found separately.

True if zlib is found.
Added in version 3.26.

The version of zlib found.


Legacy Variables

The following variables are provided for backward compatibility:

The major version of zlib.

Changed in version 3.26: Superseded by ZLIB_VERSION.

The minor version of zlib.

Changed in version 3.26: Superseded by ZLIB_VERSION.

The patch version of zlib.

Changed in version 3.26: Superseded by ZLIB_VERSION.

The tweak version of zlib.

Changed in version 3.26: Superseded by ZLIB_VERSION.

The version of zlib found (x.y.z).

Changed in version 3.26: Superseded by ZLIB_VERSION.

The major version of zlib. Superseded by ZLIB_VERSION_MAJOR.
The minor version of zlib. Superseded by ZLIB_VERSION_MINOR.
The patch version of zlib. Superseded by ZLIB_VERSION_PATCH.

Hints

This module accepts the following variables:

A user may set this variable to a zlib installation root to help locate zlib in custom installation paths.
Added in version 3.24.

Set this variable to ON before calling find_package(ZLIB) to look for static libraries. Default is OFF.


Examples

Finding zlib and linking it to a project target:

find_package(ZLIB)
target_link_libraries(project_target PRIVATE ZLIB::ZLIB)


DEPRECATED MODULES

Deprecated Utility Modules

AddFileDependencies

Deprecated since version 3.20.

Add dependencies to a source file.

add_file_dependencies(<source> <files>...)


Adds the given <files> to the dependencies of file <source>.

Do not use this command in new code. It is just a wrapper around:

set_property(SOURCE <source> APPEND PROPERTY OBJECT_DEPENDS <files>...)


Instead use the set_property() command to append to the OBJECT_DEPENDS source file property directly.

CMakeDetermineVSServicePack

Changed in version 4.1: This module is available only if policy CMP0196 is not set to NEW.

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.

This module provides a command to determine the installed Visual Studio service pack version for Visual Studio 2012 and earlier.

Load this module in a CMake project with:

include(CMakeDetermineVSServicePack)


Commands

This module provides the following command:

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


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: This module should no longer be used.

It was once needed to replace Imported Targets with their underlying libraries referenced on disk for use with the try_compile() and try_run() commands. These commands now support imported targets in their LINK_LIBRARIES options (since CMake 2.8.11 for try_compile() command and since CMake 3.2 for try_run() command).

Load this module in a CMake project with:

include(CMakeExpandImportedTargets)


NOTE:

This module does not support the policy CMP0022 NEW behavior, nor does it use the INTERFACE_LINK_LIBRARIES property, because generator expressions cannot be evaluated at the configuration phase.


Commands

This module provides the following command:

Expands all imported targets in a given list of libraries to their corresponding file paths on disk and stores the resulting list in a local variable:

cmake_expand_imported_targets(

<result-var>
LIBRARIES <libs>...
[CONFIGURATION <config>] )


The arguments are:

<result-var>
Name of a CMake variable containing the resulting list of file paths.
A semicolon-separated list of system and imported targets. Imported targets in this list are replaced with their corresponding library file paths, including libraries from their link interfaces.
If this option is given, it uses the respective build configuration <config> 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:

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.

helper module to find OSX frameworks

This module reads hints about search locations from variables:

CMAKE_FIND_FRAMEWORK_EXTRA_LOCATIONS - Extra directories


CMakeForceCompiler

Deprecated since version 3.6: Do not use.

The macros provided by this module were once intended for use by cross-compiling toolchain files when CMake was not able to automatically detect the compiler identification. Since the introduction of this module, CMake's compiler identification capabilities have improved and can now be taught to recognize any compiler. Furthermore, the suite of information CMake detects from a compiler is now too extensive to be provided by toolchain files using these macros.

One common use case for this module was to skip CMake's checks for a working compiler when using a cross-compiler that cannot link binaries without special flags or custom linker scripts. This case is now supported by setting the CMAKE_TRY_COMPILE_TARGET_TYPE variable in the toolchain file instead.


----



Macro CMAKE_FORCE_C_COMPILER has the following signature:

CMAKE_FORCE_C_COMPILER(<compiler> <compiler-id>)


It sets CMAKE_C_COMPILER to the given compiler and the cmake internal variable CMAKE_C_COMPILER_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.

Macro CMAKE_FORCE_CXX_COMPILER has the following signature:

CMAKE_FORCE_CXX_COMPILER(<compiler> <compiler-id>)


It sets CMAKE_CXX_COMPILER to the given compiler and the cmake internal variable CMAKE_CXX_COMPILER_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.

Macro CMAKE_FORCE_Fortran_COMPILER has the following signature:

CMAKE_FORCE_Fortran_COMPILER(<compiler> <compiler-id>)


It sets CMAKE_Fortran_COMPILER to the given compiler and the cmake internal variable CMAKE_Fortran_COMPILER_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.

So a simple toolchain file could look like this:

include (CMakeForceCompiler)
set(CMAKE_SYSTEM_NAME Generic)
CMAKE_FORCE_C_COMPILER   (chc12 MetrowerksHicross)
CMAKE_FORCE_CXX_COMPILER (chc12 MetrowerksHicross)


CMakeParseArguments

Deprecated since version 3.5.

This module once implemented the cmake_parse_arguments() command that is now implemented natively by CMake. It is now an empty placeholder for compatibility with projects that include it to get the command from CMake 3.4 and lower.

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. Use the CTest module instead.

Configure a project for testing with CTest or 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:

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.

This module provides support for the VTK documentation framework. It relies on several tools (Doxygen, Perl, etc).

GetPrerequisites

Deprecated since version 3.16: Use file(GET_RUNTIME_DEPENDENCIES) instead.

This module provides functions to analyze and list the dependencies (prerequisites) of executable or shared library files. These functions list the shared libraries (.dll, .dylib, or .so files) required by an executable or shared library.

It 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.

The following functions are provided by this module:

  • 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()

Functions

get_prerequisites(<target> <prerequisites-var> <exclude-system> <recurse>

<exepath> <dirs> [<rpaths>])


Gets the list of shared library files required by <target>. The list in the variable named <prerequisites-var> should be empty on first entry to this function. 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 function to enable verbose output.


list_prerequisites(<target> [<recurse> [<exclude-system> [<verbose>]]])


Prints a message listing the prerequisites of <target>.

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>
If set to 1 all prerequisites will be found recursively, if set to 0 only direct prerequisites are listed.
<exclude-system>
If set to 1 system prerequisites will be excluded, if set to 0 they will be included.
<verbose>
If set to 0 only the full path names of the prerequisites are printed. If set to 1 extra information will be displayed.


list_prerequisites_by_glob(<GLOB|GLOB_RECURSE>

<glob-exp>
[<optional-args>...])


Prints the prerequisites of shared library and executable files matching a globbing pattern.

The arguments are:

The globbing mode, whether to traverse only the match or also its subdirectories recursively.
<glob-exp>
A globbing expression used with file(GLOB) or file(GLOB_RECURSE) to retrieve a list of matching files. If a matching file is executable, its prerequisites are listed.
<optional-args>...
Any additional (optional) arguments provided are passed along as the optional arguments to the list_prerequisite() calls.


gp_append_unique(<list-var> <value>)


Appends <value> to the list variable <list-var> only if the value is not already in the list.


is_file_executable(<file> <result-var>)


Sets <result-var> to 1 if <file> is a binary executable; otherwise sets it to 0.


gp_item_default_embedded_path(<item> <default-embedded-path-var>)


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 function by defining a custom gp_item_default_embedded_path_override() function.


gp_resolve_item(<context> <item> <exepath> <dirs> <resolved-item-var>

[<rpaths>])


Resolves a given <item> into an existing full path file and stores it to a <resolved-item-var> variable.

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).
<item>
The item to resolve.
<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 function by defining a custom gp_resolve_item_override() function.


gp_resolved_file_type(<original-file> <file> <exepath> <dirs> <type-var>

[<rpaths>])


Determines the type of <file> with respect to <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.

<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

Projects can override this function by defining a custom gp_resolved_file_type_override() function.


gp_file_type(<original-file> <file> <type-var>)


Determines the type of <file> with respect to <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


Examples

Printing all dependencies of a shared library, including system libraries, with verbose output:

include(GetPrerequisites)
list_prerequisites("path/to/libfoo.dylib" 1 0 1)


MacroAddFileDependencies

Deprecated since version 3.14.

macro_add_file_dependencies(<source> <files>...)


Do not use this command in new code. It is just a wrapper around:

set_property(SOURCE <source> APPEND PROPERTY OBJECT_DEPENDS <files>...)


Instead use the set_property() command to append to the OBJECT_DEPENDS source file property directly.

SquishTestScript

Deprecated since version 3.0.

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.


TestBigEndian

Deprecated since version 3.20: Supserseded by the CMAKE_<LANG>_BYTE_ORDER variable.

Check if the target architecture is big endian or little endian.

test_big_endian(<var>)


Stores in variable <var> either 1 or 0 indicating whether the target architecture is big or little endian.


TestCXXAcceptsFlag

Deprecated since version 3.0: This module should no longer be used. It has been superseded by the CheckCXXCompilerFlag module. As of CMake 3.19, the CheckCompilerFlag module is also available for checking flags across multiple languages.

This module provides a macro to test whether the C++ (CXX) compiler supports specific flags.

Macros

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.
<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.


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:

include(CheckCompilerFlag)
check_compiler_flag(CXX "-fno-common;-fstack-clash-protection" HAVE_FLAGS)


Use_wxWindows

Deprecated since version 2.8.10: Use find_package(wxWidgets) instead.

This convenience include finds if wxWindows library is installed and sets the appropriate libraries, include directories, flags, etc.

Examples

Include Use_wxWindows module in project's CMakeLists.txt:

# CMakeLists.txt
include(Use_wxWindows)


When the GL support is required, set WXWINDOWS_USE_GL before including this module:

set(WXWINDOWS_USE_GL ON)
include(Use_wxWindows)


UseJavaClassFilelist

Changed in version 3.20: This module was previously documented by mistake and was never meant for direct inclusion by project code. See the UseJava module.

Changed in version 3.20: This module was previously documented by mistake and was never meant for direct inclusion by project code. See the UseJava module.

UsePkgConfig

Deprecated since version 3.0: This module should no longer be used. Instead, use the FindPkgConfig module or the cmake_pkg_config() command.

This module provided a macro for finding external packages using pkg-config command-line utility. It has been replaced by the more convenient FindPkgConfig module, which is commonly used in Find Modules.

As of CMake 3.31, the built-in cmake_pkg_config() command provides even more features to extract package information.

Macros

This module defines the following macro:

Finds external package using pkg-config and sets result variables:

pkgconfig(<package> <includedir> <libdir> <linkflags> <cflags>)


This macro invokes pkg-config command-line utility to retrieve the package information into specified variables. If pkg-config or the specified package <package> is NOT found, the result variables remain empty.

The arguments are:

<package>
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 information into the four given variables:

include(UsePkgConfig)
pkgconfig(

libart-2.0
LIBART_INCLUDEDIR
LIBART_LIBDIR
LIBART_LDFLAGS
LIBART_CFLAGS )


Migrating to the FindPkgConfig would look something like this:

find_package(PkgConfig QUIET)
if(PKG_CONFIG_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.

WRITE_BASIC_CONFIG_VERSION_FILE(filename

[VERSION major.minor.patch]
COMPATIBILITY (AnyNewerVersion|SameMajorVersion|SameMinorVersion|ExactVersion)
[ARCH_INDEPENDENT]
)


WriteCompilerDetectionHeader

Deprecated since version 3.20: This module is available only if policy CMP0120 is not set to NEW. Do not use it in new code.

Added in version 3.1.

This module provides the function write_compiler_detection_header().

This function can be used to generate a file suitable for preprocessor inclusion which contains macros to be used in 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 which all have the prefix <prefix>.

By default, all content is written directly to the <file>. The OUTPUT_FILES_VAR may be specified to cause the compiler-specific content to be written to separate files. The separate files are then available in the <output_files_var> and may be consumed by the caller for installation for example. The OUTPUT_DIR specifies a relative path from the main <file> to the compiler-specific files. For example:

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 may be used to specify the API version to be generated. Future versions of CMake may introduce alternative APIs. A given API is selected by any <version> value greater than or equal to the version of CMake that introduced the given API and less than the version of CMake that introduced its succeeding API. The value of the CMAKE_MINIMUM_REQUIRED_VERSION variable is used if no explicit version is specified. (As of CMake version 4.1.0 there is only one API version.)

PROLOG may be specified as text content to write at the start of the header. EPILOG may be specified as text content to write at the end of the header

At least one <compiler> and one <feature> must be listed. Compilers which are known to CMake, but not specified are detected and a preprocessor #error is generated for them. A preprocessor macro matching <PREFIX>_COMPILER_IS_<compiler> is generated for each compiler known to CMake to contain the value 0 or 1.

Possible compiler identifiers are documented with the CMAKE_<LANG>_COMPILER_ID variable. Available features 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 information 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 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 defined.

A preprocessor test is 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 additional symbol-defines are created for particular features for use as symbols which 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 argument the final keyword will be defined for old compilers, too.

The following features generate corresponding symbol defines and if they are available as BARE_FEATURES:

Feature Define Symbol bare
c_restrict <PREFIX>_RESTRICT restrict yes
cxx_constexpr <PREFIX>_CONSTEXPR constexpr yes
cxx_deleted_functions <PREFIX>_DELETED_FUNCTION = delete
cxx_extern_templates <PREFIX>_EXTERN_TEMPLATE extern
cxx_final <PREFIX>_FINAL final yes
cxx_noexcept <PREFIX>_NOEXCEPT noexcept yes
cxx_noexcept <PREFIX>_NOEXCEPT_EXPR(X) noexcept(X)
cxx_override <PREFIX>_OVERRIDE override yes

Compatibility Implementation Macros

Some features are suitable for wrapping in a macro with a backward compatibility implementation if the compiler does not support the feature.

When the cxx_static_assert feature is not provided by the compiler, a compatibility implementation is available via the <PREFIX>_STATIC_ASSERT(COND) and <PREFIX>_STATIC_ASSERT_MSG(COND, MSG) function-like macros. The 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 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.

Feature Define Symbol bare
cxx_alignas <PREFIX>_ALIGNAS alignas
cxx_alignof <PREFIX>_ALIGNOF alignof
cxx_nullptr <PREFIX>_NULLPTR nullptr yes
cxx_static_assert <PREFIX>_STATIC_ASSERT static_assert
cxx_static_assert <PREFIX>_STATIC_ASSERT_MSG static_assert
cxx_attribute_deprecated <PREFIX>_DEPRECATED [[deprecated]]
cxx_attribute_deprecated <PREFIX>_DEPRECATED_MSG [[deprecated]]
cxx_thread_local <PREFIX>_THREAD_LOCAL thread_local

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.

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)


The write_compiler_detection_header function also creates compatibility code for other features which have standard equivalents. For example, the cxx_static_assert feature is emulated with a template and abstracted via the <PREFIX>_STATIC_ASSERT and <PREFIX>_STATIC_ASSERT_MSG function-macros.

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

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"


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 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:

True if headers and requested libraries were found.
Boost include directories.
Link directories for Boost libraries.
Boost component libraries to be linked.
True if component <COMPONENT> was found (<COMPONENT> name is upper-case).
Libraries to link for component <COMPONENT> (may include target_link_libraries() debug/optimized keywords).
BOOST_VERSION value from boost/version.hpp.
Boost version number in X.Y.Z format.
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.

Version string appended to library filenames.
Boost major version number (X in X.Y.Z).
Boost minor version number (Y in X.Y.Z).
Boost subminor version number (Z in X.Y.Z).
Amount of version components (3).
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 are saved persistently in CMake cache entries:

Directory containing Boost headers.
Directory containing release Boost libraries.
Directory containing debug Boost libraries.
Component <COMPONENT> library debug variant.
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 variables:

Preferred installation prefix.
Preferred include directory e.g. <prefix>/include.
Preferred library directory e.g. <prefix>/lib.
Set to ON to disable searching in locations not specified by these hint variables. Default is OFF.
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. 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 defines the following IMPORTED targets:

Target for header-only dependencies. (Boost include directory).
Added in version 3.15: Alias for Boost::boost.

Target for specific component dependency (shared or static library); <component> name is lower-case.
Interface target to enable diagnostic information about Boost's automatic linking during compilation (adds -DBOOST_LIB_DIAGNOSTIC).
Interface target to disable automatic linking with MSVC (adds -DBOOST_ALL_NO_LIB).
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 if Boost::system is not added to target_link_libraries(). If using Boost::thread, then Threads::Threads will also be added automatically.

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 many variants encoded in their file name. Users or projects may tell this module which variant to find by setting variables:

Added in version 3.10.

Set to ON or OFF to specify whether to search and use the debug libraries. Default is ON.

Added in version 3.10.

Set to ON or OFF to specify whether to search and use the release libraries. Default is ON.

Set to OFF to use the non-multithreaded libraries ("mt" tag). Default is ON.
Set to ON to force the use of the static libraries. Default is OFF.
Set to ON or OFF to specify whether to use libraries linked statically to the C++ runtime ("s" tag). Default is platform dependent.
Set to ON or OFF to specify whether to use libraries linked to the MS debug C++ runtime ("g" tag). Default is ON.
Set to ON to use libraries compiled with a debug Python build ("y" tag). Default is OFF.
Set to ON to use libraries compiled with STLPort ("p" tag). Default is OFF.
Set to ON to use libraries compiled with STLPort deprecated "native iostreams" ("n" tag). Default is OFF.
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.

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.

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.

Suffix for thread component library name, such as pthread or win32. Names with and without this suffix will both be tried.
Alternate namespace used to build boost with e.g. if set to myboost, will search for myboost_thread instead of boost_thread.

Other variables one may set to control this module are:

Set to ON to enable debug output from FindBoost. Please enable this before filing any bug report.
Set to ON to resolve symlinks for discovered libraries to assist with packaging. For example, the "system" component library may be resolved to /usr/lib/libboost_system.so.1.67.0 instead of /usr/lib/libboost_system.so. This does not affect linking and should not be enabled unless the user needs this information.
Default value for Boost_LIBRARY_DIR_RELEASE and Boost_LIBRARY_DIR_DEBUG.
Added in version 3.20.

Set to ON to suppress the warning about unknown dependencies for new Boost versions.


On Visual Studio and Borland compilers Boost headers request automatic linking to corresponding libraries. This requires matching libraries to be linked explicitly or available in the link library search path. In this case setting Boost_USE_STATIC_LIBS to OFF may not achieve dynamic linking. Boost automatic linking typically requests static libraries with a few exceptions (such as Boost.Python). Use:

add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})


to ask Boost to report information about automatic linking requests.

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:

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 the package configuration file called BoostConfig.cmake or boost-config.cmake and stores the result in CACHE entry Boost_DIR. If found, the package configuration file is loaded and this module returns with no further action. See documentation of the Boost CMake package configuration for details on what it provides.

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 determines its include paths and libraries.

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.

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.


Cache Variables

The following cache variables may be set when using this module:

Path to the cable executable.
Path to the include directory.
Path to the Tcl wrapper library.

Examples

Finding CABLE to build Tcl wrapper, by linking 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.

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 one can add CUDA (.cu) sources directly to targets similar to other languages.

Added in version 3.17: To find and use the CUDA toolkit libraries manually, use the FindCUDAToolkit module instead. It works regardless of the CUDA language being 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.

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 cannot 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.

It might be necessary to set CUDA_TOOLKIT_ROOT_DIR manually on certain platforms, or to use a CUDA runtime not 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.

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():

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. If you compile to PTX and then load the file yourself, you can mix bit sizes between device and host.
Set to ON if you want the custom build rule to be attached to the source file in Visual Studio. Turn OFF if you add the same cuda file to multiple targets.

This allows the user to build the target from the CUDA file; however, bad things can happen if the CUDA source file is added to multiple targets. When performing parallel builds it is possible for the custom build command to be 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 is added to. When the rule is run 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.

Set to ON to enable and extra compilation pass with the -cubin option in Device mode. The output is parsed and register, shared memory usage is printed during build.
Set to ON for Emulation mode. -D_DEVICEEMU is defined for CUDA C files when CUDA_BUILD_EMULATION is TRUE.
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 is matters because whatever is used inside the FindCUDA module must also be used outside - the two forms of target_link_libraries() cannot be mixed.

Set to the path you wish to have the generated files placed. If it is blank output files will be placed in CMAKE_CURRENT_BINARY_DIR. Intermediate files will always be placed in CMAKE_CURRENT_BINARY_DIR/CMakeFiles.
Set to OFF for C compilation of host code.
Set the host compiler to be used by nvcc. Ignored if -ccbin or --compiler-bindir is already present in the CUDA_NVCC_FLAGS or CUDA_NVCC_FLAGS_<CONFIG> variables. For Visual Studio targets, the host compiler is constructed with one or more visual studio macros such as $(VCInstallDir), that expands out to the path when the command is run from within VS.

Added in version 3.13: If the CUDAHOSTCXX environment variable is set it will be used as the default.

Additional NVCC command line arguments. NOTE: multiple arguments must be semi-colon delimited (e.g. --compiler-options;-Wall)

Added in version 3.6: Contents of these variables may use generator expressions.

Set to ON to propagate CMAKE_{C,CXX}_FLAGS and their configuration dependent counterparts (e.g. CMAKE_C_FLAGS_DEBUG) automatically to the host compiler through nvcc's -Xcompiler flag. This helps make the generated host code match the rest of the system better. Sometimes certain flags give nvcc problems, and this will help you turn the flag propagation off. This does not affect the flags supplied directly to nvcc via CUDA_NVCC_FLAGS or through the OPTION 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.
If set this will enable separable compilation for all CUDA runtime object files. If used outside of cuda_add_executable() and cuda_add_library() (e.g. calling cuda_wrap_srcs() directly), cuda_compute_separable_compilation_object_file_name() and cuda_link_separable_compilation_objects() should be called.
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 documentation for set_source_files_properties on how to set this property.

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.

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):

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_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_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.

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(<generated_files> <file>... [OPTIONS ...])


Returns a list of PTX files generated from the input source files.

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(<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(<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 the list of objects 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.

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(<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 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_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.

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.

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 make 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 passed into add_definitions with -D or /D are passed along to nvcc.

Result Variables

The script defines the following variables:

The major version of cuda as reported by nvcc.
The minor version.
Full version in the X.Y format.
Added in version 3.6: Whether a short float (float16, fp16) is supported.

Path to the CUDA Toolkit (defined if not set).
Path to the CUDA SDK. Use this to find files in the SDK. This script will not directly support finding specific libraries or headers, as that isn't supported by NVIDIA. If you want to change libraries when the path changes see the FindCUDA.cmake script for an example of how to clear these variables. There are also examples of how to use the CUDA_SDK_ROOT_DIR to locate headers or libraries, if you so choose (at your own risk).
Include directory for cuda headers. Added automatically for cuda_add_executable() and cuda_add_library().
Cuda RT library.
Device or emulation library for the Cuda FFT implementation (alternative to cuda_add_cufft_to_target() macro)
Device or emulation library for the Cuda BLAS implementation (alternative to cuda_add_cublas_to_target() macro).
Statically linkable cuda runtime library. Only available for CUDA version 5.5+.
Added in version 3.7: Device runtime library. Required for separable compilation.

CUDA Profiling Tools Interface library. Only available for CUDA version 4.0+.
CUDA Random Number Generation library. Only available for CUDA version 3.2+.
Added in version 3.2: CUDA Direct Solver library. Only available for CUDA version 7.0+.

CUDA Sparse Matrix library. Only available for CUDA version 3.2+.
NVIDIA Performance Primitives lib. Only available for CUDA version 4.0+.
NVIDIA Performance Primitives lib (core). Only available for CUDA version 5.5+.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 5.5 - 8.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0 - 10.2. Replaced by nvjpeg.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (image processing). Only available for CUDA version 9.0.
NVIDIA Performance Primitives lib (signal processing). Only available for CUDA version 5.5+.
CUDA Video Encoder library. Only available for CUDA version 3.2+. Windows only.
CUDA Video Decoder library. Only available for CUDA version 3.2+. Windows only.
Added in version 3.16: NVIDA CUDA Tools Extension library. Available for CUDA version 5+.

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 is not set to NEW.

Find DART

This module looks for the dart testing software and sets DART_ROOT to point to where it found it.

FindGCCXML

Changed in version 4.1: This module is available only if policy CMP0188 is not set to NEW. Port projects to search for CastXML by calling find_program directly.

Find the GCC-XML front-end executable.

This module will define the following variables:

The GCC-XML front-end executable.

FindGDAL

Find Geospatial Data Abstraction Library (GDAL).

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.

Imported Targets

Added in version 3.14.

This module defines IMPORTED target GDAL::GDAL if GDAL has been found.

Result Variables

This module will set the following variables in your project:

True if GDAL is found.
Include directories for GDAL headers.
Libraries to link to GDAL.
Added in version 3.14: The version of GDAL found.


Cache variables

The following cache variables may also be set:

The libgdal library file.
The directory containing gdal.h.

Hints

Set GDAL_DIR or GDAL_ROOT in the environment to specify the GDAL installation prefix.

The following variables may be set to modify the search strategy:

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.
Extra versions of library names to search for.

FindITK

This module no longer exists.

This module 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.

FindPythonInterp

Changed in version 3.27: This module is available only if policy CMP0148 is not set to NEW.

Deprecated since version 3.12: Use FindPython3, FindPython2, or FindPython instead.

This module finds the Python interpreter and determines the location of its executable.

NOTE:

When using both this and the 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, FindPython2, or FindPython instead.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) Python executable is found. For backward compatibility, the PYTHONINTERP_FOUND variable is also set to the same value.
Python version found (e.g., 2.5.2).
Python major version found (e.g., 2).
Python minor version found (e.g., 5).
Python patch version found (e.g., 2).

Cache Variables

The following cache variables may also be set:

The path to the Python interpreter.

Hints

This module accepts the following variables before calling find_package(PythonInterp):

This variable can be used to specify a list of version numbers that should be taken into account when searching for Python.

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. The equivalent example using the modern approach is:

find_package(Python)
execute_process(COMMAND ${Python_EXECUTABLE} --help)


FindPythonLibs

Changed in version 3.27: This module is available only if policy CMP0148 is not set to NEW.

Deprecated since version 3.12: Use FindPython3, FindPython2, or FindPython instead.

This module finds the Python installation and determines the location of its include directories and libraries, as well as the name of the Python library to link against.

NOTE:

When using both this and the FindPythonInterp 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.


Result Variables

This module defines the following variables:

Boolean indicating whether the (requested version of) Python libraries have been found. For backward compatibility, the PYTHONLIBS_FOUND variable is also set to the same value.
The version of the Python libraries found.
Libraries needed to link against to use Python.
Include directories needed to use Python.

Cache Variables

The following cache variables may also be set to specify the Python installation to use:

The path to the Python library.
The directory containing the Python.h header file.

Hints

This module accepts the following variables before calling find_package(PythonLibs):

This variable can be used to specify a list of version numbers that should be taken into account when searching for Python.

Deprecated Variables

These variables are provided for backward compatibility:

Deprecated since version 2.8.8: Use PYTHON_LIBRARIES instead.

Result variable that holds the path to the debug library.

Deprecated since version 2.8.0: Use PYTHON_INCLUDE_DIR or PYTHON_INCLUDE_DIRS instead.

Result variable that holds 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. The equivalent example using the modern approach with an imported target is:

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. For Qt5 or later versions see cmake-qt(7).

This module finds an installed version of Qt3 or Qt4. Qt is a cross-platform application development framework for creating graphical user interfaces and applications.

Use this module only if the project can work with both Qt3 and Qt4 versions. If a specific version is required, use FindQt4 or FindQt3 module directly.

Behavior:

  • If multiple Qt versions are found, the user must set the preferred major Qt version with the DESIRED_QT_VERSION variable.
  • If only one Qt version is found, then the DESIRED_QT_VERSION is set automatically.
  • Once the DESIRED_QT_VERSION variable is set, the corresponding FindQt3 or FindQt4 module is included.

Result Variables

This module sets the following variables:

TRUE if Qt4 is found.
TRUE if Qt3 is found.

Hints

If this variable is set to TRUE before calling find_package(Qt), CMake will raise an error if neither Qt3 nor Qt4 is found.
Specifies the Qt major version to use. Can be either 3, 4, or empty, to search for version automatically.

Examples

Finding Qt3 or Qt4 version:

find_package(Qt)


FindUnixCommands

Deprecated since version 3.26: Use ${CMAKE_COMMAND} -E subcommands instead.

Find Unix commands, including the ones from Cygwin

This module looks for the Unix commands bash, cp, gzip, mv, rm, and tar and stores the result in the variables BASH, CP, GZIP, MV, RM, and TAR.

FindVTK

This module no longer exists.

This module 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.

FindwxWindows

Deprecated since version 3.0: Replaced by FindwxWidgets.

Finds the wxWidgets (formerly known as wxWindows) installation and determines the locations of its include directories and libraries, as well as the name of the library.

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


Result Variables

This module defines the following variables:

Boolean indicating whether the wxWidgets is found.
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.
Compiler options needed to use wxWidgets (if any). On Linux, this corresponds to the output of wx-config --cxxflags.
The directory containing the wx/wx.h and wx/setup.h header files.
Link directories, useful for setting rpath on Unix-like platforms.
Extra compile definitions needed to use wxWidgets (if any).

Hints

This module accepts the following variables before calling the find_package(wxWindows):

Set this variable to boolean true to require OpenGL support.
Set this variable to boolean true to replace -I compiler options with -isystem when the C++ compiler is GNU (g++).

Deprecated Variables

These variables are provided for backward compatibility:

Deprecated since version 1.8: Replaced by the WXWINDOWS_FOUND variable with the same value.

Deprecated since version 1.8: Replaced by the WXWINDOWS_LIBRARIES variable with the same value.

Deprecated since version 1.8: Replaced by the CMAKE_WXWINDOWS_CXX_FLAGS variable with the same value.

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)


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.

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

COPYRIGHT

2000-2025 Kitware, Inc. and Contributors

August 12, 2025 4.1.0