code:
build_name
----------

Disallowed since version 3.0.  See CMake Policy :policy:`CMP0036`.

Use ``${CMAKE_SYSTEM}`` and ``${CMAKE_CXX_COMPILER}`` instead.

.. code-block:: cmake

  build_name(variable)

Sets the specified variable to a string representing the platform and
compiler settings.  These values are now available through the
:variable:`CMAKE_SYSTEM` and
:variable:`CMAKE_CXX_COMPILER <CMAKE_<LANG>_COMPILER>` variables.


code:
cmake_file_api
--------------

.. versionadded:: 3.27

Enables interacting with the :manual:`CMake file API <cmake-file-api(7)>`.

.. signature::
  cmake_file_api(QUERY ...)

  The ``QUERY`` subcommand adds a file API query for the current CMake
  invocation.

  .. code-block:: cmake

    cmake_file_api(
      QUERY
      API_VERSION <version>
      [CODEMODEL <versions>...]
      [CACHE <versions>...]
      [CMAKEFILES <versions>...]
      [TOOLCHAINS <versions>...]
    )

  The ``API_VERSION`` must always be given.  Currently, the only supported
  value for ``<version>`` is 1.  See :ref:`file-api v1` for details of the
  reply content and location.

  Each of the optional keywords ``CODEMODEL``, ``CACHE``, ``CMAKEFILES`` and
  ``TOOLCHAINS`` correspond to one of the object kinds that can be requested
  by the project.  The ``configureLog`` object kind cannot be set with this
  command, since it must be set before CMake starts reading the top level
  ``CMakeLists.txt`` file.

  For each of the optional keywords, the ``<versions>`` list must contain one
  or more version values of the form ``major`` or ``major.minor``, where
  ``major`` and ``minor`` are integers.  Projects should list the versions they
  accept in their preferred order, as only the first supported value from the
  list will be selected.  The command will ignore versions with a ``major``
  version higher than any major version it supports for that object kind.
  It will raise an error if it encounters an invalid version number, or if none
  of the requested versions is supported.

  For each type of object kind requested, a query equivalent to a shared,
  stateless query will be added internally.  No query file will be created in
  the file system.  The reply *will* be written to the file system at
  generation time.

  It is not an error to add a query for the same thing more than once, whether
  from query files or from multiple calls to ``cmake_file_api(QUERY)``.
  The final set of queries will be a merged combination of all queries
  specified on disk and queries submitted by the project.

Example
^^^^^^^

A project may want to use replies from the file API at build time to implement
some form of verification task.  Instead of relying on something outside of
CMake to create a query file, the project can use ``cmake_file_api(QUERY)``
to request the required information for the current run.  It can then create
a custom command to run at build time, knowing that the requested information
should always be available.

.. code-block:: cmake

  cmake_file_api(
    QUERY
    API_VERSION 1
    CODEMODEL 2.3
    TOOLCHAINS 1
  )

  add_custom_target(verify_project
    COMMAND ${CMAKE_COMMAND}
      -D BUILD_DIR=${CMAKE_BINARY_DIR}
      -D CONFIG=$<CONFIG>
      -P ${CMAKE_CURRENT_SOURCE_DIR}/verify_project.cmake
  )

repo_name: lazytadpole/codenamesilverfish

license: mit


code:
cmake_host_system_information
-----------------------------

Query various host system information.

Synopsis
^^^^^^^^

.. parsed-literal::

  `Query host system specific information`_
    cmake_host_system_information(RESULT <variable> QUERY <key> ...)

  `Query Windows registry`_
    cmake_host_system_information(RESULT <variable> QUERY WINDOWS_REGISTRY <key> ...)

Query host system specific information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: cmake

  cmake_host_system_information(RESULT <variable> QUERY <key> ...)

Queries system information of the host system on which cmake runs.
One or more ``<key>`` can be provided to select the information to be
queried.  The list of queried values is stored in ``<variable>``.

``<key>`` can be one of the following values:

``NUMBER_OF_LOGICAL_CORES``
  Number of logical cores

``NUMBER_OF_PHYSICAL_CORES``
  Number of physical cores

``HOSTNAME``
  Hostname

``FQDN``
  Fully qualified domain name

``TOTAL_VIRTUAL_MEMORY``
  Total virtual memory in MiB [#mebibytes]_

``AVAILABLE_VIRTUAL_MEMORY``
  Available virtual memory in MiB [#mebibytes]_

``TOTAL_PHYSICAL_MEMORY``
  Total physical memory in MiB [#mebibytes]_

``AVAILABLE_PHYSICAL_MEMORY``
  Available physical memory in MiB [#mebibytes]_

``IS_64BIT``
  .. versionadded:: 3.10

  One if processor is 64Bit

``HAS_FPU``
  .. versionadded:: 3.10

  One if processor has floating point unit

``HAS_MMX``
  .. versionadded:: 3.10

  One if processor supports MMX instructions

``HAS_MMX_PLUS``
  .. versionadded:: 3.10

  One if processor supports Ext. MMX instructions

``HAS_SSE``
  .. versionadded:: 3.10

  One if processor supports SSE instructions

``HAS_SSE2``
  .. versionadded:: 3.10

  One if processor supports SSE2 instructions

``HAS_SSE_FP``
  .. versionadded:: 3.10

  One if processor supports SSE FP instructions

``HAS_SSE_MMX``
  .. versionadded:: 3.10

  One if processor supports SSE MMX instructions

``HAS_AMD_3DNOW``
  .. versionadded:: 3.10

  One if processor supports 3DNow instructions

``HAS_AMD_3DNOW_PLUS``
  .. versionadded:: 3.10

  One if processor supports 3DNow+ instructions

``HAS_IA64``
  .. versionadded:: 3.10

  One if IA64 processor emulating x86

``HAS_SERIAL_NUMBER``
  .. versionadded:: 3.10

  One if processor has serial number

``PROCESSOR_SERIAL_NUMBER``
  .. versionadded:: 3.10

  Processor serial number

``PROCESSOR_NAME``
  .. versionadded:: 3.10

  Human readable processor name

``PROCESSOR_DESCRIPTION``
  .. versionadded:: 3.10

  Human readable full processor description

``OS_NAME``
  .. versionadded:: 3.10

  See :variable:`CMAKE_HOST_SYSTEM_NAME`

``OS_RELEASE``
  .. versionadded:: 3.10

  The OS sub-type e.g. on Windows ``Professional``

``OS_VERSION``
  .. versionadded:: 3.10

  The OS build ID

``OS_PLATFORM``
  .. versionadded:: 3.10

  See :variable:`CMAKE_HOST_SYSTEM_PROCESSOR`

``MSYSTEM_PREFIX``
  .. versionadded:: 3.28

  Available only on Windows hosts.  In a MSYS or MinGW development
  environment that sets the ``MSYSTEM`` environment variable, this
  is its installation prefix.  Otherwise, this is the empty string.

``DISTRIB_INFO``
  .. versionadded:: 3.22

  Read :file:`/etc/os-release` file and define the given ``<variable>``
  into a list of read variables

``DISTRIB_<name>``
  .. versionadded:: 3.22

  Get the ``<name>`` variable (see `man 5 os-release`_) if it exists in the
  :file:`/etc/os-release` file

  Example:

  .. code-block:: cmake

      cmake_host_system_information(RESULT PRETTY_NAME QUERY DISTRIB_PRETTY_NAME)
      message(STATUS "${PRETTY_NAME}")

      cmake_host_system_information(RESULT DISTRO QUERY DISTRIB_INFO)

      foreach(VAR IN LISTS DISTRO)
        message(STATUS "${VAR}=`${${VAR}}`")
      endforeach()

  Output::

    -- Ubuntu 20.04.2 LTS
    -- DISTRO_BUG_REPORT_URL=`https://bugs.launchpad.net/ubuntu/`
    -- DISTRO_HOME_URL=`https://www.ubuntu.com/`
    -- DISTRO_ID=`ubuntu`
    -- DISTRO_ID_LIKE=`debian`
    -- DISTRO_NAME=`Ubuntu`
    -- DISTRO_PRETTY_NAME=`Ubuntu 20.04.2 LTS`
    -- DISTRO_PRIVACY_POLICY_URL=`https://www.ubuntu.com/legal/terms-and-policies/privacy-policy`
    -- DISTRO_SUPPORT_URL=`https://help.ubuntu.com/`
    -- DISTRO_UBUNTU_CODENAME=`focal`
    -- DISTRO_VERSION=`20.04.2 LTS (Focal Fossa)`
    -- DISTRO_VERSION_CODENAME=`focal`
    -- DISTRO_VERSION_ID=`20.04`

If :file:`/etc/os-release` file is not found, the command tries to gather OS
identification via fallback scripts.  The fallback script can use `various
distribution-specific files`_ to collect OS identification data and map it
into `man 5 os-release`_ variables.

Fallback Interface Variables
""""""""""""""""""""""""""""

.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_SCRIPTS

  In addition to the scripts shipped with CMake, a user may append full
  paths to his script(s) to the this list.  The script filename has the
  following format: ``NNN-<name>.cmake``, where ``NNN`` is three digits
  used to apply collected scripts in a specific order.

.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname>

  Variables collected by the user provided fallback script
  ought to be assigned to CMake variables using this naming
  convention.  Example, the ``ID`` variable from the manual becomes
  ``CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID``.

.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_RESULT

  The fallback script ought to store names of all assigned
  ``CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname>`` variables in this list.

Example:

.. code-block:: cmake

  # Try to detect some old distribution
  # See also
  # - http://linuxmafia.com/faq/Admin/release-files.html
  #
  if(NOT EXISTS "${CMAKE_SYSROOT}/etc/foobar-release")
    return()
  endif()
  # Get the first string only
  file(
      STRINGS "${CMAKE_SYSROOT}/etc/foobar-release" CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT
      LIMIT_COUNT 1
    )
  #
  # Example:
  #
  #   Foobar distribution release 1.2.3 (server)
  #
  if(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT MATCHES "Foobar distribution release ([0-9\.]+) .*")
    set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME Foobar)
    set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME "${CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT}")
    set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID foobar)
    set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION ${CMAKE_MATCH_1})
    set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID ${CMAKE_MATCH_1})
    list(
        APPEND CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
        CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME
        CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME
        CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID
        CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION
        CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID
      )
  endif()
  unset(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT)

.. rubric:: Footnotes

.. [#mebibytes] One MiB (mebibyte) is equal to 1024x1024 bytes.

.. _man 5 os-release: https://www.freedesktop.org/software/systemd/man/latest/os-release.html
.. _various distribution-specific files: http://linuxmafia.com/faq/Admin/release-files.html

.. _Query Windows registry:

Query Windows registry
^^^^^^^^^^^^^^^^^^^^^^

.. versionadded:: 3.24

::

  cmake_host_system_information(RESULT <variable>
                                QUERY WINDOWS_REGISTRY <key> [VALUE_NAMES|SUBKEYS|VALUE <name>]
                                [VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)]
                                [SEPARATOR <separator>]
                                [ERROR_VARIABLE <result>])

Performs query operations on local computer registry subkey. Returns a list of
subkeys or value names that are located under the specified subkey in the
registry or the data of the specified value name. The result of the queried
entity is stored in ``<variable>``.

.. note::

  Querying registry for any other platforms than ``Windows``, including
  ``CYGWIN``, will always returns an empty string and sets an error message in
  the variable specified with sub-option ``ERROR_VARIABLE``.

``<key>`` specify the full path of a subkey on the local computer. The
``<key>`` must include a valid root key. Valid root keys for the local computer
are:

* ``HKLM`` or ``HKEY_LOCAL_MACHINE``
* ``HKCU`` or ``HKEY_CURRENT_USER``
* ``HKCR`` or ``HKEY_CLASSES_ROOT``
* ``HKU`` or ``HKEY_USERS``
* ``HKCC`` or ``HKEY_CURRENT_CONFIG``

And, optionally, the path to a subkey under the specified root key. The path
separator can be the slash or the backslash. ``<key>`` is not case sensitive.
For example:

.. code-block:: cmake

  cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM")
  cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware")
  cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKCU\\SOFTWARE\\Kitware")

``VALUE_NAMES``
  Request the list of value names defined under ``<key>``. If a default value
  is defined, it will be identified with the special name ``(default)``.

``SUBKEYS``
  Request the list of subkeys defined under ``<key>``.

``VALUE <name>``
  Request the data stored in value named ``<name>``. If ``VALUE`` is not
  specified or argument is the special name ``(default)``, the content of the
  default value, if any, will be returned.

  .. code-block:: cmake

     # query default value for HKLM/SOFTWARE/Kitware key
     cmake_host_system_information(RESULT result
                                   QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware")

     # query default value for HKLM/SOFTWARE/Kitware key using special value name
     cmake_host_system_information(RESULT result
                                   QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware"
                                   VALUE "(default)")

  Supported types are:

  * ``REG_SZ``.
  * ``REG_EXPAND_SZ``. The returned data is expanded.
  * ``REG_MULTI_SZ``. The returned is expressed as a CMake list. See also
    ``SEPARATOR`` sub-option.
  * ``REG_DWORD``.
  * ``REG_QWORD``.

  For all other types, an empty string is returned.

``VIEW``
  Specify which registry views must be queried. When not specified, ``BOTH``
  view is used.

  ``64``
    Query the 64bit registry. On ``32bit Windows``, returns always an empty
    string.

  ``32``
    Query the 32bit registry.

  ``64_32``
    For ``VALUE`` sub-option or default value, query the registry using view
    ``64``, and if the request failed, query the registry using view ``32``.
    For ``VALUE_NAMES`` and ``SUBKEYS`` sub-options, query both views (``64``
    and ``32``) and merge the results (sorted and duplicates removed).

  ``32_64``
    For ``VALUE`` sub-option or default value, query the registry using view
    ``32``, and if the request failed, query the registry using view ``64``.
    For ``VALUE_NAMES`` and ``SUBKEYS`` sub-options, query both views (``32``
    and ``64``) and merge the results (sorted and duplicates removed).

  ``HOST``
    Query the registry matching the architecture of the host: ``64`` on ``64bit
    Windows`` and ``32`` on ``32bit Windows``.

  ``TARGET``
    Query the registry matching the architecture specified by
    :variable:`CMAKE_SIZEOF_VOID_P` variable. If not defined, fallback to
    ``HOST`` view.

  ``BOTH``
    Query both views (``32`` and ``64``). The order depends of the following
    rules: If :variable:`CMAKE_SIZEOF_VOID_P` variable is defined. Use the
    following view depending of the content of this variable:

    * ``8``: ``64_32``
    * ``4``: ``32_64``

    If :variable:`CMAKE_SIZEOF_VOID_P` variable is not defined, rely on
    architecture of the host:

    * ``64bit``: ``64_32``
    * ``32bit``: ``32``

``SEPARATOR``
  Specify the separator character for ``REG_MULTI_SZ`` type. When not
  specified, the character ``\0`` is used.

``ERROR_VARIABLE <result>``
  Returns any error raised during query operation. In case of success, the
  variable holds an empty string.


code:
cmake_language
--------------

.. versionadded:: 3.18

Call meta-operations on CMake commands.

Synopsis
^^^^^^^^

.. parsed-literal::

  cmake_language(`CALL`_ <command> [<arg>...])
  cmake_language(`EVAL`_ CODE <code>...)
  cmake_language(`DEFER`_ <options>... CALL <command> [<arg>...])
  cmake_language(`SET_DEPENDENCY_PROVIDER`_ <command> SUPPORTED_METHODS <methods>...)
  cmake_language(`GET_MESSAGE_LOG_LEVEL`_ <out-var>)
  cmake_language(`EXIT`_ <exit-code>)

Introduction
^^^^^^^^^^^^

This command will call meta-operations on built-in CMake commands or
those created via the :command:`macro` or :command:`function` commands.

``cmake_language`` does not introduce a new variable or policy scope.

Calling Commands
^^^^^^^^^^^^^^^^

.. signature::
  cmake_language(CALL <command> [<arg>...])

  Calls the named ``<command>`` with the given arguments (if any).
  For example, the code:

  .. code-block:: cmake

    set(message_command "message")
    cmake_language(CALL ${message_command} STATUS "Hello World!")

  is equivalent to

  .. code-block:: cmake

    message(STATUS "Hello World!")

  .. note::
    To ensure consistency of the code, the following commands are not allowed:

    * ``if`` / ``elseif`` / ``else`` / ``endif``
    * ``block`` / ``endblock``
    * ``while`` / ``endwhile``
    * ``foreach`` / ``endforeach``
    * ``function`` / ``endfunction``
    * ``macro`` / ``endmacro``

Evaluating Code
^^^^^^^^^^^^^^^

.. signature::
  cmake_language(EVAL CODE <code>...)
  :target: EVAL

  Evaluates the ``<code>...`` as CMake code.

  For example, the code:

  .. code-block:: cmake

    set(A TRUE)
    set(B TRUE)
    set(C TRUE)
    set(condition "(A AND B) OR C")

    cmake_language(EVAL CODE "
      if (${condition})
        message(STATUS TRUE)
      else()
        message(STATUS FALSE)
      endif()"
    )

  is equivalent to

  .. code-block:: cmake

    set(A TRUE)
    set(B TRUE)
    set(C TRUE)
    set(condition "(A AND B) OR C")

    file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/eval.cmake "
      if (${condition})
        message(STATUS TRUE)
      else()
        message(STATUS FALSE)
      endif()"
    )

    include(${CMAKE_CURRENT_BINARY_DIR}/eval.cmake)

Deferring Calls
^^^^^^^^^^^^^^^

.. versionadded:: 3.19

.. signature::
  cmake_language(DEFER <options>... CALL <command> [<arg>...])

  Schedules a call to the named ``<command>`` with the given arguments (if any)
  to occur at a later time.  By default, deferred calls are executed as if
  written at the end of the current directory's ``CMakeLists.txt`` file,
  except that they run even after a :command:`return` call.  Variable
  references in arguments are evaluated at the time the deferred call is
  executed.

  The options are:

  ``DIRECTORY <dir>``
    Schedule the call for the end of the given directory instead of the
    current directory.  The ``<dir>`` may reference either a source
    directory or its corresponding binary directory.  Relative paths are
    treated as relative to the current source directory.

    The given directory must be known to CMake, being either the top-level
    directory or one added by :command:`add_subdirectory`.  Furthermore,
    the given directory must not yet be finished processing.  This means
    it can be the current directory or one of its ancestors.

  ``ID <id>``
    Specify an identification for the deferred call.
    The ``<id>`` may not be empty and may not begin with a capital letter ``A-Z``.
    The ``<id>`` may begin with an underscore (``_``) only if it was generated
    automatically by an earlier call that used ``ID_VAR`` to get the id.

  ``ID_VAR <var>``
    Specify a variable in which to store the identification for the
    deferred call.  If ``ID <id>`` is not given, a new identification
    will be generated and the generated id will start with an underscore (``_``).

  The currently scheduled list of deferred calls may be retrieved:

  .. code-block:: cmake

    cmake_language(DEFER [DIRECTORY <dir>] GET_CALL_IDS <var>)

  This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
  Lists>` of deferred call ids.  The ids are for the directory scope in which
  the calls have been deferred to (i.e. where they will be executed), which can
  be different to the scope in which they were created.  The ``DIRECTORY``
  option can be used to specify the scope for which to retrieve the call ids.
  If that option is not given, the call ids for the current directory scope
  will be returned.

  Details of a specific call may be retrieved from its id:

  .. code-block:: cmake

    cmake_language(DEFER [DIRECTORY <dir>] GET_CALL <id> <var>)

  This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
  Lists>` in which the first element is the name of the command to be
  called, and the remaining elements are its unevaluated arguments (any
  contained ``;`` characters are included literally and cannot be distinguished
  from multiple arguments).  If multiple calls are scheduled with the same id,
  this retrieves the first one.  If no call is scheduled with the given id in
  the specified ``DIRECTORY`` scope (or the current directory scope if no
  ``DIRECTORY`` option is given), this stores an empty string in the variable.

  Deferred calls may be canceled by their id:

  .. code-block:: cmake

    cmake_language(DEFER [DIRECTORY <dir>] CANCEL_CALL <id>...)

  This cancels all deferred calls matching any of the given ids in the specified
  ``DIRECTORY`` scope (or the current directory scope if no ``DIRECTORY`` option
  is given).  Unknown ids are silently ignored.

Deferred Call Examples
""""""""""""""""""""""

For example, the code:

.. code-block:: cmake

  cmake_language(DEFER CALL message "${deferred_message}")
  cmake_language(DEFER ID_VAR id CALL message "Canceled Message")
  cmake_language(DEFER CANCEL_CALL ${id})
  message("Immediate Message")
  set(deferred_message "Deferred Message")

prints::

  Immediate Message
  Deferred Message

The ``Canceled Message`` is never printed because its command is
canceled.  The ``deferred_message`` variable reference is not evaluated
until the call site, so it can be set after the deferred call is scheduled.

In order to evaluate variable references immediately when scheduling a
deferred call, wrap it using ``cmake_language(EVAL)``.  However, note that
arguments will be re-evaluated in the deferred call, though that can be
avoided by using bracket arguments.  For example:

.. code-block:: cmake

  set(deferred_message "Deferred Message 1")
  set(re_evaluated [[${deferred_message}]])
  cmake_language(EVAL CODE "
    cmake_language(DEFER CALL message [[${deferred_message}]])
    cmake_language(DEFER CALL message \"${re_evaluated}\")
  ")
  message("Immediate Message")
  set(deferred_message "Deferred Message 2")

also prints::

  Immediate Message
  Deferred Message 1
  Deferred Message 2

.. _dependency_providers:

Dependency Providers
^^^^^^^^^^^^^^^^^^^^

.. versionadded:: 3.24

.. note:: A high-level introduction to this feature can be found in the
          :ref:`Using Dependencies Guide <dependency_providers_overview>`.

.. signature::
  cmake_language(SET_DEPENDENCY_PROVIDER <command>
                 SUPPORTED_METHODS <methods>...)

  When a call is made to :command:`find_package` or
  :command:`FetchContent_MakeAvailable`, the call may be forwarded to a
  dependency provider which then has the opportunity to fulfill the request.
  If the request is for one of the ``<methods>`` specified when the provider
  was set, CMake calls the provider's ``<command>`` with a set of
  method-specific arguments.  If the provider does not fulfill the request,
  or if the provider doesn't support the request's method, or no provider
  is set, the built-in :command:`find_package` or
  :command:`FetchContent_MakeAvailable` implementation is used to fulfill
  the request in the usual way.

  One or more of the following values can be specified for the ``<methods>``
  when setting the provider:

  ``FIND_PACKAGE``
    The provider command accepts :command:`find_package` requests.

  ``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
    The provider command accepts :command:`FetchContent_MakeAvailable`
    requests.  It expects each dependency to be fed to the provider command
    one at a time, not the whole list in one go.

  Only one provider can be set at any point in time.  If a provider is already
  set when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called, the new
  provider replaces the previously set one.  The specified ``<command>`` must
  already exist when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called.
  As a special case, providing an empty string for the ``<command>`` and no
  ``<methods>`` will discard any previously set provider.

  The dependency provider can only be set while processing one of the files
  specified by the :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable.
  Thus, dependency providers can only be set as part of the first call to
  :command:`project`.  Calling ``cmake_language(SET_DEPENDENCY_PROVIDER)``
  outside of that context will result in an error.

  .. note::
    The choice of dependency provider should always be under the user's control.
    As a convenience, a project may choose to provide a file that users can
    list in their :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable, but
    the use of such a file should always be the user's choice.

Provider commands
"""""""""""""""""

Providers define a single ``<command>`` to accept requests.  The name of
the command should be specific to that provider, not something overly
generic that another provider might also use.  This enables users to compose
different providers in their own custom provider.  The recommended form is
``xxx_provide_dependency()``, where ``xxx`` is the provider-specific part
(e.g. ``vcpkg_provide_dependency()``, ``conan_provide_dependency()``,
``ourcompany_provide_dependency()``, and so on).

.. code-block:: cmake

  xxx_provide_dependency(<method> [<method-specific-args>...])

Because some methods expect certain variables to be set in the calling scope,
the provider command should typically be implemented as a macro rather than a
function.  This ensures it does not introduce a new variable scope.

The arguments CMake passes to the dependency provider depend on the type of
request.  The first argument is always the method, and it will only ever
be one of the ``<methods>`` that was specified when setting the provider.

``FIND_PACKAGE``
  The ``<method-specific-args>`` will be everything passed to the
  :command:`find_package` call that requested the dependency.  The first of
  these ``<method-specific-args>`` will therefore always be the name of the
  dependency.  Dependency names are case-sensitive for this method because
  :command:`find_package` treats them case-sensitively too.

  If the provider command fulfills the request, it must set the same variable
  that :command:`find_package` expects to be set.  For a dependency named
  ``depName``, the provider must set ``depName_FOUND`` to true if it fulfilled
  the request.  If the provider returns without setting this variable, CMake
  will assume the request was not fulfilled and will fall back to the
  built-in implementation.

  If the provider needs to call the built-in :command:`find_package`
  implementation as part of its processing, it can do so by including the
  ``BYPASS_PROVIDER`` keyword as one of the arguments.

``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
  The ``<method-specific-args>`` will be everything passed to the
  :command:`FetchContent_Declare` call that corresponds to the requested
  dependency, with the following exceptions:

  * If ``SOURCE_DIR`` or ``BINARY_DIR`` were not part of the original
    declared arguments, they will be added with their default values.
  * If :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is set to ``NEVER``,
    any ``FIND_PACKAGE_ARGS`` will be omitted.
  * The ``OVERRIDE_FIND_PACKAGE`` keyword is always omitted.

  The first of the ``<method-specific-args>`` will always be the name of the
  dependency.  Dependency names are case-insensitive for this method because
  :module:`FetchContent` also treats them case-insensitively.

  If the provider fulfills the request, it should call
  :command:`FetchContent_SetPopulated`, passing the name of the dependency as
  the first argument.  The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments to that
  command should only be given if the provider makes the dependency's source
  and build directories available in exactly the same way as the built-in
  :command:`FetchContent_MakeAvailable` command.

  If the provider returns without calling :command:`FetchContent_SetPopulated`
  for the named dependency, CMake will assume the request was not fulfilled
  and will fall back to the built-in implementation.

  Note that empty arguments may be significant for this method (e.g. an empty
  string following a ``GIT_SUBMODULES`` keyword).  Therefore, if forwarding
  these arguments on to another command, extra care must be taken to avoid such
  arguments being silently dropped.

  If ``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` is set, then the
  dependency provider will never see requests for the ``<depName>`` dependency
  for this method. When the user sets such a variable, they are explicitly
  overriding where to get that dependency from and are taking on the
  responsibility that their overriding version meets any requirements for that
  dependency and is compatible with whatever else in the project uses it.
  Depending on the value of :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE`
  and whether the ``OVERRIDE_FIND_PACKAGE`` option was given to
  :command:`FetchContent_Declare`, having
  ``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` set may also prevent the
  dependency provider from seeing requests for a ``find_package(depName)``
  call too.

Provider Examples
"""""""""""""""""

This first example only intercepts :command:`find_package` calls.  The
provider command runs an external tool which copies the relevant artifacts
into a provider-specific directory, if that tool knows about the dependency.
It then relies on the built-in implementation to then find those artifacts.
:command:`FetchContent_MakeAvailable` calls would not go through the provider.

.. code-block:: cmake
  :caption: mycomp_provider.cmake

  # Always ensure we have the policy settings this provider expects
  cmake_minimum_required(VERSION 3.24)

  set(MYCOMP_PROVIDER_INSTALL_DIR ${CMAKE_BINARY_DIR}/mycomp_packages
    CACHE PATH "The directory this provider installs packages to"
  )
  # Tell the built-in implementation to look in our area first, unless
  # the find_package() call uses NO_..._PATH options to exclude it
  list(APPEND CMAKE_MODULE_PATH ${MYCOMP_PROVIDER_INSTALL_DIR}/cmake)
  list(APPEND CMAKE_PREFIX_PATH ${MYCOMP_PROVIDER_INSTALL_DIR})

  macro(mycomp_provide_dependency method package_name)
    execute_process(
      COMMAND some_tool ${package_name} --installdir ${MYCOMP_PROVIDER_INSTALL_DIR}
      COMMAND_ERROR_IS_FATAL ANY
    )
  endmacro()

  cmake_language(
    SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
    SUPPORTED_METHODS FIND_PACKAGE
  )

The user would then typically use the above file like so::

  cmake -DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=/path/to/mycomp_provider.cmake ...

The next example demonstrates a provider that accepts both methods, but
only handles one specific dependency.  It enforces providing Google Test
using :module:`FetchContent`, but leaves all other dependencies to be
fulfilled by CMake's built-in implementation.  It accepts a few different
names, which demonstrates one way of working around projects that hard-code
an unusual or undesirable way of adding this particular dependency to the
build.  The example also demonstrates how to use the :command:`list` command
to preserve variables that may be overwritten by a call to
:command:`FetchContent_MakeAvailable`.

.. code-block:: cmake
  :caption: mycomp_provider.cmake

  cmake_minimum_required(VERSION 3.24)

  # Because we declare this very early, it will take precedence over any
  # details the project might declare later for the same thing
  include(FetchContent)
  FetchContent_Declare(
    googletest
    GIT_REPOSITORY https://github.com/google/googletest.git
    GIT_TAG        e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0
  )

  # Both FIND_PACKAGE and FETCHCONTENT_MAKEAVAILABLE_SERIAL methods provide
  # the package or dependency name as the first method-specific argument.
  macro(mycomp_provide_dependency method dep_name)
    if("${dep_name}" MATCHES "^(gtest|googletest)$")
      # Save our current command arguments in case we are called recursively
      list(APPEND mycomp_provider_args ${method} ${dep_name})

      # This will forward to the built-in FetchContent implementation,
      # which detects a recursive call for the same thing and avoids calling
      # the provider again if dep_name is the same as the current call.
      FetchContent_MakeAvailable(googletest)

      # Restore our command arguments
      list(POP_BACK mycomp_provider_args dep_name method)

      # Tell the caller we fulfilled the request
      if("${method}" STREQUAL "FIND_PACKAGE")
        # We need to set this if we got here from a find_package() call
        # since we used a different method to fulfill the request.
        # This example assumes projects only use the gtest targets,
        # not any of the variables the FindGTest module may define.
        set(${dep_name}_FOUND TRUE)
      elseif(NOT "${dep_name}" STREQUAL "googletest")
        # We used the same method, but were given a different name to the
        # one we populated with. Tell the caller about the name it used.
        FetchContent_SetPopulated(${dep_name}
          SOURCE_DIR "${googletest_SOURCE_DIR}"
          BINARY_DIR "${googletest_BINARY_DIR}"
        )
      endif()
    endif()
  endmacro()

  cmake_language(
    SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
    SUPPORTED_METHODS
      FIND_PACKAGE
      FETCHCONTENT_MAKEAVAILABLE_SERIAL
  )

The final example demonstrates how to modify arguments to a
:command:`find_package` call.  It forces all such calls to have the
``QUIET`` keyword.  It uses the ``BYPASS_PROVIDER`` keyword to prevent
calling the provider command recursively for the same dependency.

.. code-block:: cmake
  :caption: mycomp_provider.cmake

  cmake_minimum_required(VERSION 3.24)

  macro(mycomp_provide_dependency method)
    find_package(${ARGN} BYPASS_PROVIDER QUIET)
  endmacro()

  cmake_language(
    SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
    SUPPORTED_METHODS FIND_PACKAGE
  )

Getting current message log level
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. versionadded:: 3.25

.. _query_message_log_level:

.. signature::
  cmake_language(GET_MESSAGE_LOG_LEVEL <output_variable>)

  Writes the current :command:`message` logging level
  into the given ``<output_variable>``.

  See :command:`message` for the possible logging levels.

  The current message logging level can be set either using the
  :option:`--log-level <cmake --log-level>`
  command line option of the :manual:`cmake(1)` program or using
  the :variable:`CMAKE_MESSAGE_LOG_LEVEL` variable.

  If both the command line option and the variable are set, the command line
  option takes precedence. If neither are set, the default logging level
  is returned.

Terminating Scripts
^^^^^^^^^^^^^^^^^^^

.. versionadded:: 3.29

.. signature::
  cmake_language(EXIT <exit-code>)

  Terminate the current :option:`cmake -P` script and exit with ``<exit-code>``.

  This command works only in :ref:`script mode <Script Processing Mode>`.

  The ``<exit-code>`` should be non-negative.
  If ``<exit-code>`` is negative then the behavior
  is unspecified (e.g., on Windows the error code -1
  becomes ``0xffffffff``, and on Linux it becomes ``255``).


code:
cmake_minimum_required
----------------------

Require a minimum version of cmake.

.. code-block:: cmake

  cmake_minimum_required(VERSION <min>[...<policy_max>] [FATAL_ERROR])

.. versionadded:: 3.12
  The optional ``<policy_max>`` version.

Sets the minimum required version of cmake for a project.
Also updates the policy settings as explained below.

``<min>`` and the optional ``<policy_max>`` are each CMake versions of the
form ``major.minor[.patch[.tweak]]``, and the ``...`` is literal.

If the running version of CMake is lower than the ``<min>`` required
version it will stop processing the project and report an error.
The optional ``<policy_max>`` version, if specified, must be at least the
``<min>`` version and affects policy settings as described in `Policy Settings`_.
If the running version of CMake is older than 3.12, the extra ``...``
dots will be seen as version component separators, resulting in the
``...<max>`` part being ignored and preserving the pre-3.12 behavior
of basing policies on ``<min>``.

This command will set the value of the
:variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable to ``<min>``.

The ``FATAL_ERROR`` option is accepted but ignored by CMake 2.6 and
higher.  It should be specified so CMake versions 2.4 and lower fail
with an error instead of just a warning.

.. note::
  Call the ``cmake_minimum_required()`` command at the beginning of
  the top-level ``CMakeLists.txt`` file even before calling the
  :command:`project` command.  It is important to establish version
  and policy settings before invoking other commands whose behavior
  they may affect.  See also policy :policy:`CMP0000`.

  Calling ``cmake_minimum_required()`` inside a :command:`function`
  limits some effects to the function scope when invoked.  For example,
  the :variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable won't be set
  in the calling scope.  Functions do not introduce their own policy
  scope though, so policy settings of the caller *will* be affected
  (see below).  Due to this mix of things that do and do not affect the
  calling scope, calling ``cmake_minimum_required()`` inside a function
  is generally discouraged.

.. _`Policy Settings`:

Policy Settings
^^^^^^^^^^^^^^^

The ``cmake_minimum_required(VERSION)`` command implicitly invokes the
:command:`cmake_policy(VERSION)` command to specify that the current
project code is written for the given range of CMake versions.
All policies known to the running version of CMake and introduced
in the ``<min>`` (or ``<max>``, if specified) version or earlier will
be set to use ``NEW`` behavior.  All policies introduced in later
versions will be unset.  This effectively requests behavior preferred
as of a given CMake version and tells newer CMake versions to warn
about their new policies.

When a ``<min>`` version higher than 2.4 is specified the command
implicitly invokes

.. code-block:: cmake

  cmake_policy(VERSION <min>[...<max>])

which sets CMake policies based on the range of versions specified.
When a ``<min>`` version 2.4 or lower is given the command implicitly
invokes

.. code-block:: cmake

  cmake_policy(VERSION 2.4[...<max>])

which enables compatibility features for CMake 2.4 and lower.

.. include:: DEPRECATED_POLICY_VERSIONS.txt

See Also
^^^^^^^^

* :command:`cmake_policy`


code:
cmake_parse_arguments
---------------------

Parse function or macro arguments.

.. code-block:: cmake

  cmake_parse_arguments(<prefix> <options> <one_value_keywords>
                        <multi_value_keywords> <args>...)

  cmake_parse_arguments(PARSE_ARGV <N> <prefix> <options>
                        <one_value_keywords> <multi_value_keywords>)

.. versionadded:: 3.5
  This command is implemented natively.  Previously, it has been defined in the
  module :module:`CMakeParseArguments`.

This command is for use in macros or functions.
It processes the arguments given to that macro or function,
and defines a set of variables which hold the values of the
respective options.

The first signature reads processes arguments passed in the ``<args>...``.
This may be used in either a :command:`macro` or a :command:`function`.

.. versionadded:: 3.7
  The ``PARSE_ARGV`` signature is only for use in a :command:`function`
  body.  In this case the arguments that are parsed come from the
  ``ARGV#`` variables of the calling function.  The parsing starts with
  the ``<N>``-th argument, where ``<N>`` is an unsigned integer.
  This allows for the values to have special characters like ``;`` in them.

The ``<options>`` argument contains all options for the respective macro,
i.e.  keywords which can be used when calling the macro without any value
following, like e.g.  the ``OPTIONAL`` keyword of the :command:`install`
command.

The ``<one_value_keywords>`` argument contains all keywords for this macro
which are followed by one value, like e.g. ``DESTINATION`` keyword of the
:command:`install` command.

The ``<multi_value_keywords>`` argument contains all keywords for this
macro which can be followed by more than one value, like e.g. the
``TARGETS`` or ``FILES`` keywords of the :command:`install` command.

.. versionchanged:: 3.5
  All keywords shall be unique. I.e. every keyword shall only be specified
  once in either ``<options>``, ``<one_value_keywords>`` or
  ``<multi_value_keywords>``. A warning will be emitted if uniqueness is
  violated.

When done, ``cmake_parse_arguments`` will consider for each of the
keywords listed in ``<options>``, ``<one_value_keywords>`` and
``<multi_value_keywords>`` a variable composed of the given ``<prefix>``
followed by ``"_"`` and the name of the respective keyword.  These
variables will then hold the respective value from the argument list
or be undefined if the associated option could not be found.
For the ``<options>`` keywords, these will always be defined,
to ``TRUE`` or ``FALSE``, whether the option is in the argument list or not.

All remaining arguments are collected in a variable
``<prefix>_UNPARSED_ARGUMENTS`` that will be undefined if all arguments
were recognized. This can be checked afterwards to see
whether your macro was called with unrecognized parameters.

.. versionadded:: 3.15
   ``<one_value_keywords>`` and ``<multi_value_keywords>`` that were given no
   values at all are collected in a variable
   ``<prefix>_KEYWORDS_MISSING_VALUES`` that will be undefined if all keywords
   received values. This can be checked to see if there were keywords without
   any values given.

Consider the following example macro, ``my_install()``, which takes similar
arguments to the real :command:`install` command:

.. code-block:: cmake

   macro(my_install)
       set(options OPTIONAL FAST)
       set(oneValueArgs DESTINATION RENAME)
       set(multiValueArgs TARGETS CONFIGURATIONS)
       cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}"
                             "${multiValueArgs}" ${ARGN} )

       # ...

Assume ``my_install()`` has been called like this:

.. code-block:: cmake

   my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub CONFIGURATIONS)

After the ``cmake_parse_arguments`` call the macro will have set or undefined
the following variables::

   MY_INSTALL_OPTIONAL = TRUE
   MY_INSTALL_FAST = FALSE # was not used in call to my_install
   MY_INSTALL_DESTINATION = "bin"
   MY_INSTALL_RENAME <UNDEFINED> # was not used
   MY_INSTALL_TARGETS = "foo;bar"
   MY_INSTALL_CONFIGURATIONS <UNDEFINED> # was not used
   MY_INSTALL_UNPARSED_ARGUMENTS = "blub" # nothing expected after "OPTIONAL"
   MY_INSTALL_KEYWORDS_MISSING_VALUES = "CONFIGURATIONS"
            # No value for "CONFIGURATIONS" given

You can then continue and process these variables.

Keywords terminate lists of values, e.g. if directly after a
``one_value_keyword`` another recognized keyword follows, this is
interpreted as the beginning of the new option.  E.g.
``my_install(TARGETS foo DESTINATION OPTIONAL)`` would result in
``MY_INSTALL_DESTINATION`` set to ``"OPTIONAL"``, but as ``OPTIONAL``
is a keyword itself ``MY_INSTALL_DESTINATION`` will be empty (but added
to ``MY_INSTALL_KEYWORDS_MISSING_VALUES``) and ``MY_INSTALL_OPTIONAL`` will
therefore be set to ``TRUE``.

See Also
^^^^^^^^

* :command:`function`
* :command:`macro`


code:
cmake_path
----------

.. versionadded:: 3.20

This command is for the manipulation of paths.  Only syntactic aspects of
paths are handled, there is no interaction of any kind with any underlying
file system.  The path may represent a non-existing path or even one that
is not allowed to exist on the current file system or platform.
For operations that do interact with the filesystem, see the :command:`file`
command.

.. note::

  The ``cmake_path`` command handles paths in the format of the build system
  (i.e. the host platform), not the target system.  When cross-compiling,
  if the path contains elements that are not representable on the host
  platform (e.g. a drive letter when the host is not Windows), the results
  will be unpredictable.

Synopsis
^^^^^^^^

.. parsed-literal::

  `Conventions`_

  `Path Structure And Terminology`_

  `Normalization`_

  `Decomposition`_
    cmake_path(`GET`_ <path-var> :ref:`ROOT_NAME <GET_ROOT_NAME>` <out-var>)
    cmake_path(`GET`_ <path-var> :ref:`ROOT_DIRECTORY <GET_ROOT_DIRECTORY>` <out-var>)
    cmake_path(`GET`_ <path-var> :ref:`ROOT_PATH <GET_ROOT_PATH>` <out-var>)
    cmake_path(`GET`_ <path-var> :ref:`FILENAME <GET_FILENAME>` <out-var>)
    cmake_path(`GET`_ <path-var> :ref:`EXTENSION <GET_EXTENSION>` [LAST_ONLY] <out-var>)
    cmake_path(`GET`_ <path-var> :ref:`STEM <GET_STEM>` [LAST_ONLY] <out-var>)
    cmake_path(`GET`_ <path-var> :ref:`RELATIVE_PART <GET_RELATIVE_PART>` <out-var>)
    cmake_path(`GET`_ <path-var> :ref:`PARENT_PATH <GET_PARENT_PATH>` <out-var>)

  `Query`_
    cmake_path(`HAS_ROOT_NAME`_ <path-var> <out-var>)
    cmake_path(`HAS_ROOT_DIRECTORY`_ <path-var> <out-var>)
    cmake_path(`HAS_ROOT_PATH`_ <path-var> <out-var>)
    cmake_path(`HAS_FILENAME`_ <path-var> <out-var>)
    cmake_path(`HAS_EXTENSION`_ <path-var> <out-var>)
    cmake_path(`HAS_STEM`_ <path-var> <out-var>)
    cmake_path(`HAS_RELATIVE_PART`_ <path-var> <out-var>)
    cmake_path(`HAS_PARENT_PATH`_ <path-var> <out-var>)
    cmake_path(`IS_ABSOLUTE`_ <path-var> <out-var>)
    cmake_path(`IS_RELATIVE`_ <path-var> <out-var>)
    cmake_path(`IS_PREFIX`_ <path-var> <input> [NORMALIZE] <out-var>)
    cmake_path(`COMPARE`_ <input1> <OP> <input2> <out-var>)

  `Modification`_
    cmake_path(:ref:`SET <cmake_path-SET>` <path-var> [NORMALIZE] <input>)
    cmake_path(`APPEND`_ <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
    cmake_path(`APPEND_STRING`_ <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
    cmake_path(`REMOVE_FILENAME`_ <path-var> [OUTPUT_VARIABLE <out-var>])
    cmake_path(`REPLACE_FILENAME`_ <path-var> <input> [OUTPUT_VARIABLE <out-var>])
    cmake_path(`REMOVE_EXTENSION`_ <path-var> [LAST_ONLY] [OUTPUT_VARIABLE <out-var>])
    cmake_path(`REPLACE_EXTENSION`_ <path-var> [LAST_ONLY] <input> [OUTPUT_VARIABLE <out-var>])

  `Generation`_
    cmake_path(`NORMAL_PATH`_ <path-var> [OUTPUT_VARIABLE <out-var>])
    cmake_path(`RELATIVE_PATH`_ <path-var> [BASE_DIRECTORY <input>] [OUTPUT_VARIABLE <out-var>])
    cmake_path(`ABSOLUTE_PATH`_ <path-var> [BASE_DIRECTORY <input>] [NORMALIZE] [OUTPUT_VARIABLE <out-var>])

  `Native Conversion`_
    cmake_path(`NATIVE_PATH`_ <path-var> [NORMALIZE] <out-var>)
    cmake_path(`CONVERT`_ <input> `TO_CMAKE_PATH_LIST`_ <out-var> [NORMALIZE])
    cmake_path(`CONVERT`_ <input> `TO_NATIVE_PATH_LIST`_ <out-var> [NORMALIZE])

  `Hashing`_
    cmake_path(`HASH`_ <path-var> <out-var>)

Conventions
^^^^^^^^^^^

The following conventions are used in this command's documentation:

``<path-var>``
  Always the name of a variable.  For commands that expect a ``<path-var>``
  as input, the variable must exist and it is expected to hold a single path.

``<input>``
  A string literal which may contain a path, path fragment, or multiple paths
  with a special separator depending on the command.  See the description of
  each command to see how this is interpreted.

``<input>...``
  Zero or more string literal arguments.

``<out-var>``
  The name of a variable into which the result of a command will be written.

.. _Path Structure And Terminology:

Path Structure And Terminology
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A path has the following structure (all components are optional, with some
constraints):

::

  root-name root-directory-separator (item-name directory-separator)* filename

``root-name``
  Identifies the root on a filesystem with multiple roots (such as ``"C:"``
  or ``"//myserver"``). It is optional.

``root-directory-separator``
  A directory separator that, if present, indicates that this path is
  absolute.  If it is missing and the first element other than the
  ``root-name`` is an ``item-name``, then the path is relative.

``item-name``
  A sequence of characters that aren't directory separators.  This name may
  identify a file, a hard link, a symbolic link, or a directory.  Two special
  cases are recognized:

    * The item name consisting of a single dot character ``.`` is a
      directory name that refers to the current directory.

    * The item name consisting of two dot characters ``..`` is a
      directory name that refers to the parent directory.

  The ``(...)*`` pattern shown above is to indicate that there can be zero
  or more item names, with multiple items separated by a
  ``directory-separator``.  The ``()*`` characters are not part of the path.

``directory-separator``
  The only recognized directory separator is a forward slash character ``/``.
  If this character is repeated, it is treated as a single directory
  separator.  In other words, ``/usr///////lib`` is the same as ``/usr/lib``.

.. _FILENAME_DEF:
.. _EXTENSION_DEF:
.. _STEM_DEF:

``filename``
  A path has a ``filename`` if it does not end with a ``directory-separator``.
  The ``filename`` is effectively the last ``item-name`` of the path, so it
  can also be a hard link, symbolic link or a directory.

  A ``filename`` can have an *extension*.  By default, the extension is
  defined as the sub-string beginning at the left-most period (including
  the period) and until the end of the ``filename``.  In commands that
  accept a ``LAST_ONLY`` keyword, ``LAST_ONLY`` changes the interpretation
  to the sub-string beginning at the right-most period.

  The following exceptions apply to the above interpretation:

    * If the first character in the ``filename`` is a period, that period is
      ignored (i.e. a ``filename`` like ``".profile"`` is treated as having
      no extension).

    * If the ``filename`` is either ``.`` or ``..``, it has no extension.

  The *stem* is the part of the ``filename`` before the extension.

Some commands refer to a ``root-path``.  This is the concatenation of
``root-name`` and ``root-directory-separator``, either or both of which can
be empty.  A ``relative-part`` refers to the full path with any ``root-path``
removed.

Creating A Path Variable
^^^^^^^^^^^^^^^^^^^^^^^^

While a path can be created with care using an ordinary :command:`set`
command, it is recommended to use :ref:`cmake_path(SET) <cmake_path-SET>`
instead, as it automatically converts the path to the required form where
required.  The :ref:`cmake_path(APPEND) <APPEND>` subcommand may
be another suitable alternative where a path needs to be constructed by
joining fragments.  The following example compares the three methods for
constructing the same path:

.. code-block:: cmake

  set(path1 "${CMAKE_CURRENT_SOURCE_DIR}/data")

  cmake_path(SET path2 "${CMAKE_CURRENT_SOURCE_DIR}/data")

  cmake_path(APPEND path3 "${CMAKE_CURRENT_SOURCE_DIR}" "data")

`Modification`_ and `Generation`_ sub-commands can either store the result
in-place, or in a separate variable named after an ``OUTPUT_VARIABLE``
keyword.  All other sub-commands store the result in a mandatory ``<out-var>``
variable.

.. _Normalization:

Normalization
^^^^^^^^^^^^^

Some sub-commands support *normalizing* a path.  The algorithm used to
normalize a path is as follows:

1. If the path is empty, stop (the normalized form of an empty path is
   also an empty path).
2. Replace each ``directory-separator``, which may consist of multiple
   separators, with a single ``/`` (``/a///b  --> /a/b``).
3. Remove each solitary period (``.``) and any immediately following
   ``directory-separator`` (``/a/./b/. --> /a/b``).
4. Remove each ``item-name`` (other than ``..``) that is immediately
   followed by a ``directory-separator`` and a ``..``, along with any
   immediately following ``directory-separator`` (``/a/b/../c --> a/c``).
5. If there is a ``root-directory``, remove any ``..`` and any
   ``directory-separators`` immediately following them.  The parent of the
   root directory is treated as still the root directory (``/../a --> /a``).
6. If the last ``item-name`` is ``..``, remove any trailing
   ``directory-separator`` (``../ --> ..``).
7. If the path is empty by this stage, add a ``dot`` (normal form of ``./``
   is ``.``).

.. _Path Decomposition:

Decomposition
^^^^^^^^^^^^^

.. _GET:
.. _GET_ROOT_NAME:
.. _GET_ROOT_DIRECTORY:
.. _GET_ROOT_PATH:
.. _GET_FILENAME:
.. _GET_EXTENSION:
.. _GET_STEM:
.. _GET_RELATIVE_PART:
.. _GET_PARENT_PATH:

The following forms of the ``GET`` subcommand each retrieve a different
component or group of components from a path.  See
`Path Structure And Terminology`_ for the meaning of each path component.

.. code-block:: cmake

  cmake_path(GET <path-var> ROOT_NAME <out-var>)
  cmake_path(GET <path-var> ROOT_DIRECTORY <out-var>)
  cmake_path(GET <path-var> ROOT_PATH <out-var>)
  cmake_path(GET <path-var> FILENAME <out-var>)
  cmake_path(GET <path-var> EXTENSION [LAST_ONLY] <out-var>)
  cmake_path(GET <path-var> STEM [LAST_ONLY] <out-var>)
  cmake_path(GET <path-var> RELATIVE_PART <out-var>)
  cmake_path(GET <path-var> PARENT_PATH <out-var>)

If a requested component is not present in the path, an empty string will be
stored in ``<out-var>``.  For example, only Windows systems have the concept
of a ``root-name``, so when the host machine is non-Windows, the ``ROOT_NAME``
subcommand will always return an empty string.

For ``PARENT_PATH``, if the `HAS_RELATIVE_PART`_ subcommand returns false,
the result is a copy of ``<path-var>``.  Note that this implies that a root
directory is considered to have a parent, with that parent being itself.
Where `HAS_RELATIVE_PART`_ returns true, the result will essentially be
``<path-var>`` with one less element.

Root examples
"""""""""""""

.. code-block:: cmake

  set(path "c:/a")

  cmake_path(GET path ROOT_NAME rootName)
  cmake_path(GET path ROOT_DIRECTORY rootDir)
  cmake_path(GET path ROOT_PATH rootPath)

  message("Root name is \"${rootName}\"")
  message("Root directory is \"${rootDir}\"")
  message("Root path is \"${rootPath}\"")

::

  Root name is "c:"
  Root directory is "/"
  Root path is "c:/"

Filename examples
"""""""""""""""""

.. code-block:: cmake

  set(path "/a/b")
  cmake_path(GET path FILENAME filename)
  message("First filename is \"${filename}\"")

  # Trailing slash means filename is empty
  set(path "/a/b/")
  cmake_path(GET path FILENAME filename)
  message("Second filename is \"${filename}\"")

::

  First filename is "b"
  Second filename is ""

Extension and stem examples
"""""""""""""""""""""""""""

.. code-block:: cmake

  set(path "name.ext1.ext2")

  cmake_path(GET path EXTENSION fullExt)
  cmake_path(GET path STEM fullStem)
  message("Full extension is \"${fullExt}\"")
  message("Full stem is \"${fullStem}\"")

  # Effect of LAST_ONLY
  cmake_path(GET path EXTENSION LAST_ONLY lastExt)
  cmake_path(GET path STEM LAST_ONLY lastStem)
  message("Last extension is \"${lastExt}\"")
  message("Last stem is \"${lastStem}\"")

  # Special cases
  set(dotPath "/a/.")
  set(dotDotPath "/a/..")
  set(someMorePath "/a/.some.more")
  cmake_path(GET dotPath EXTENSION dotExt)
  cmake_path(GET dotPath STEM dotStem)
  cmake_path(GET dotDotPath EXTENSION dotDotExt)
  cmake_path(GET dotDotPath STEM dotDotStem)
  cmake_path(GET dotMorePath EXTENSION someMoreExt)
  cmake_path(GET dotMorePath STEM someMoreStem)
  message("Dot extension is \"${dotExt}\"")
  message("Dot stem is \"${dotStem}\"")
  message("Dot-dot extension is \"${dotDotExt}\"")
  message("Dot-dot stem is \"${dotDotStem}\"")
  message(".some.more extension is \"${someMoreExt}\"")
  message(".some.more stem is \"${someMoreStem}\"")

::

  Full extension is ".ext1.ext2"
  Full stem is "name"
  Last extension is ".ext2"
  Last stem is "name.ext1"
  Dot extension is ""
  Dot stem is "."
  Dot-dot extension is ""
  Dot-dot stem is ".."
  .some.more extension is ".more"
  .some.more stem is ".some"

Relative part examples
""""""""""""""""""""""

.. code-block:: cmake

  set(path "c:/a/b")
  cmake_path(GET path RELATIVE_PART result)
  message("Relative part is \"${result}\"")

  set(path "c/d")
  cmake_path(GET path RELATIVE_PART result)
  message("Relative part is \"${result}\"")

  set(path "/")
  cmake_path(GET path RELATIVE_PART result)
  message("Relative part is \"${result}\"")

::

  Relative part is "a/b"
  Relative part is "c/d"
  Relative part is ""

Path traversal examples
"""""""""""""""""""""""

.. code-block:: cmake

  set(path "c:/a/b")
  cmake_path(GET path PARENT_PATH result)
  message("Parent path is \"${result}\"")

  set(path "c:/")
  cmake_path(GET path PARENT_PATH result)
  message("Parent path is \"${result}\"")

::

  Parent path is "c:/a"
  Parent path is "c:/"

.. _Path Query:

Query
^^^^^

Each of the ``GET`` subcommands has a corresponding ``HAS_...``
subcommand which can be used to discover whether a particular path
component is present.  See `Path Structure And Terminology`_ for the
meaning of each path component.

.. _HAS_ROOT_NAME:
.. _HAS_ROOT_DIRECTORY:
.. _HAS_ROOT_PATH:
.. _HAS_FILENAME:
.. _HAS_EXTENSION:
.. _HAS_STEM:
.. _HAS_RELATIVE_PART:
.. _HAS_PARENT_PATH:

.. code-block:: cmake

  cmake_path(HAS_ROOT_NAME <path-var> <out-var>)
  cmake_path(HAS_ROOT_DIRECTORY <path-var> <out-var>)
  cmake_path(HAS_ROOT_PATH <path-var> <out-var>)
  cmake_path(HAS_FILENAME <path-var> <out-var>)
  cmake_path(HAS_EXTENSION <path-var> <out-var>)
  cmake_path(HAS_STEM <path-var> <out-var>)
  cmake_path(HAS_RELATIVE_PART <path-var> <out-var>)
  cmake_path(HAS_PARENT_PATH <path-var> <out-var>)

Each of the above follows the predictable pattern of setting ``<out-var>``
to true if the path has the associated component, or false otherwise.
Note the following special cases:

* For ``HAS_ROOT_PATH``, a true result will only be returned if at least one
  of ``root-name`` or ``root-directory`` is non-empty.

* For ``HAS_PARENT_PATH``, the root directory is also considered to have a
  parent, which will be itself.  The result is true except if the path
  consists of just a :ref:`filename <FILENAME_DEF>`.

.. _IS_ABSOLUTE:

.. code-block:: cmake

  cmake_path(IS_ABSOLUTE <path-var> <out-var>)

Sets ``<out-var>`` to true if ``<path-var>`` is absolute.  An absolute path
is a path that unambiguously identifies the location of a file without
reference to an additional starting location.  On Windows, this means the
path must have both a ``root-name`` and a ``root-directory-separator`` to be
considered absolute.  On other platforms, just a ``root-directory-separator``
is sufficient.  Note that this means on Windows, ``IS_ABSOLUTE`` can be
false while ``HAS_ROOT_DIRECTORY`` can be true.

.. _IS_RELATIVE:

.. code-block:: cmake

  cmake_path(IS_RELATIVE <path-var> <out-var>)

This will store the opposite of ``IS_ABSOLUTE`` in ``<out-var>``.

.. _IS_PREFIX:

.. code-block:: cmake

  cmake_path(IS_PREFIX <path-var> <input> [NORMALIZE] <out-var>)

Checks if ``<path-var>`` is the prefix of ``<input>``.

When the ``NORMALIZE`` option is specified, ``<path-var>`` and ``<input>``
are :ref:`normalized <Normalization>` before the check.

.. code-block:: cmake

  set(path "/a/b/c")
  cmake_path(IS_PREFIX path "/a/b/c/d" result) # result = true
  cmake_path(IS_PREFIX path "/a/b" result)     # result = false
  cmake_path(IS_PREFIX path "/x/y/z" result)   # result = false

  set(path "/a/b")
  cmake_path(IS_PREFIX path "/a/c/../b" NORMALIZE result)   # result = true

.. _Path COMPARE:
.. _COMPARE:

.. code-block:: cmake

  cmake_path(COMPARE <input1> EQUAL <input2> <out-var>)
  cmake_path(COMPARE <input1> NOT_EQUAL <input2> <out-var>)

Compares the lexical representations of two paths provided as string literals.
No normalization is performed on either path, except multiple consecutive
directory separators are effectively collapsed into a single separator.
Equality is determined according to the following pseudo-code logic:

::

  if(NOT <input1>.root_name() STREQUAL <input2>.root_name())
    return FALSE

  if(<input1>.has_root_directory() XOR <input2>.has_root_directory())
    return FALSE

  Return FALSE if a relative portion of <input1> is not lexicographically
  equal to the relative portion of <input2>. This comparison is performed path
  component-wise. If all of the components compare equal, then return TRUE.

.. note::
  Unlike most other ``cmake_path()`` subcommands, the ``COMPARE`` subcommand
  takes literal strings as input, not the names of variables.

.. _Path Modification:

Modification
^^^^^^^^^^^^

.. _cmake_path-SET:

.. code-block:: cmake

  cmake_path(SET <path-var> [NORMALIZE] <input>)

Assign the ``<input>`` path to ``<path-var>``.  If ``<input>`` is a native
path, it is converted into a cmake-style path with forward-slashes
(``/``). On Windows, the long filename marker is taken into account.

When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` after the conversion.

For example:

.. code-block:: cmake

  set(native_path "c:\\a\\b/..\\c")
  cmake_path(SET path "${native_path}")
  message("CMake path is \"${path}\"")

  cmake_path(SET path NORMALIZE "${native_path}")
  message("Normalized CMake path is \"${path}\"")

Output::

  CMake path is "c:/a/b/../c"
  Normalized CMake path is "c:/a/c"

.. _APPEND:

.. code-block:: cmake

  cmake_path(APPEND <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])

Append all the ``<input>`` arguments to the ``<path-var>`` using ``/`` as
the ``directory-separator``.  Depending on the ``<input>``, the previous
contents of ``<path-var>`` may be discarded.  For each ``<input>`` argument,
the following algorithm (pseudo-code) applies:

::

  # <path> is the contents of <path-var>

  if(<input>.is_absolute() OR
     (<input>.has_root_name() AND
      NOT <input>.root_name() STREQUAL <path>.root_name()))
    replace <path> with <input>
    return()
  endif()

  if(<input>.has_root_directory())
    remove any root-directory and the entire relative path from <path>
  elseif(<path>.has_filename() OR
         (NOT <path-var>.has_root_directory() OR <path>.is_absolute()))
    append directory-separator to <path>
  endif()

  append <input> omitting any root-name to <path>

.. _APPEND_STRING:

.. code-block:: cmake

  cmake_path(APPEND_STRING <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])

Append all the ``<input>`` arguments to the ``<path-var>`` without adding any
``directory-separator``.

.. _REMOVE_FILENAME:

.. code-block:: cmake

  cmake_path(REMOVE_FILENAME <path-var> [OUTPUT_VARIABLE <out-var>])

Removes the :ref:`filename <FILENAME_DEF>` component (as returned by
:ref:`GET ... FILENAME <GET_FILENAME>`) from ``<path-var>``.  After removal,
any trailing ``directory-separator`` is left alone, if present.

If ``OUTPUT_VARIABLE`` is not given, then after this function returns,
`HAS_FILENAME`_ returns false for ``<path-var>``.

For example:

.. code-block:: cmake

  set(path "/a/b")
  cmake_path(REMOVE_FILENAME path)
  message("First path is \"${path}\"")

  # filename is now already empty, the following removes nothing
  cmake_path(REMOVE_FILENAME path)
  message("Second path is \"${result}\"")

Output::

  First path is "/a/"
  Second path is "/a/"

.. _REPLACE_FILENAME:

.. code-block:: cmake

  cmake_path(REPLACE_FILENAME <path-var> <input> [OUTPUT_VARIABLE <out-var>])

Replaces the :ref:`filename <FILENAME_DEF>` component from ``<path-var>``
with ``<input>``.  If ``<path-var>`` has no filename component (i.e.
`HAS_FILENAME`_ returns false), the path is unchanged.  The operation is
equivalent to the following:

.. code-block:: cmake

  cmake_path(HAS_FILENAME path has_filename)
  if(has_filename)
    cmake_path(REMOVE_FILENAME path)
    cmake_path(APPEND path input);
  endif()

.. _REMOVE_EXTENSION:

.. code-block:: cmake

  cmake_path(REMOVE_EXTENSION <path-var> [LAST_ONLY]
                                         [OUTPUT_VARIABLE <out-var>])

Removes the :ref:`extension <EXTENSION_DEF>`, if any, from ``<path-var>``.

.. _REPLACE_EXTENSION:

.. code-block:: cmake

  cmake_path(REPLACE_EXTENSION <path-var> [LAST_ONLY] <input>
                               [OUTPUT_VARIABLE <out-var>])

Replaces the :ref:`extension <EXTENSION_DEF>` with ``<input>``.  Its effect
is equivalent to the following:

.. code-block:: cmake

  cmake_path(REMOVE_EXTENSION path)
  if(NOT "input" MATCHES "^\\.")
    cmake_path(APPEND_STRING path ".")
  endif()
  cmake_path(APPEND_STRING path "input")

.. _Path Generation:

Generation
^^^^^^^^^^

.. _NORMAL_PATH:

.. code-block:: cmake

  cmake_path(NORMAL_PATH <path-var> [OUTPUT_VARIABLE <out-var>])

Normalize ``<path-var>`` according the steps described in :ref:`Normalization`.

.. _cmake_path-RELATIVE_PATH:
.. _RELATIVE_PATH:

.. code-block:: cmake

  cmake_path(RELATIVE_PATH <path-var> [BASE_DIRECTORY <input>]
                                      [OUTPUT_VARIABLE <out-var>])

Modifies ``<path-var>`` to make it relative to the ``BASE_DIRECTORY`` argument.
If ``BASE_DIRECTORY`` is not specified, the default base directory will be
:variable:`CMAKE_CURRENT_SOURCE_DIR`.

For reference, the algorithm used to compute the relative path is the same
as that used by C++
`std::filesystem::path::lexically_relative
<https://en.cppreference.com/w/cpp/filesystem/path/lexically_normal>`_.

.. _ABSOLUTE_PATH:

.. code-block:: cmake

  cmake_path(ABSOLUTE_PATH <path-var> [BASE_DIRECTORY <input>] [NORMALIZE]
                                      [OUTPUT_VARIABLE <out-var>])

If ``<path-var>`` is a relative path (`IS_RELATIVE`_ is true), it is evaluated
relative to the given base directory specified by ``BASE_DIRECTORY`` option.
If ``BASE_DIRECTORY`` is not specified, the default base directory will be
:variable:`CMAKE_CURRENT_SOURCE_DIR`.

When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` after the path computation.

Because ``cmake_path()`` does not access the filesystem, symbolic links are
not resolved and any leading tilde is not expanded.  To compute a real path
with symbolic links resolved and leading tildes expanded, use the
:command:`file(REAL_PATH)` command instead.

Native Conversion
^^^^^^^^^^^^^^^^^

For commands in this section, *native* refers to the host platform, not the
target platform when cross-compiling.

.. _cmake_path-NATIVE_PATH:
.. _NATIVE_PATH:

.. code-block:: cmake

  cmake_path(NATIVE_PATH <path-var> [NORMALIZE] <out-var>)

Converts a cmake-style ``<path-var>`` into a native path with
platform-specific slashes (``\`` on Windows hosts and ``/`` elsewhere).

When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.

.. _CONVERT:
.. _cmake_path-TO_CMAKE_PATH_LIST:
.. _TO_CMAKE_PATH_LIST:

.. code-block:: cmake

  cmake_path(CONVERT <input> TO_CMAKE_PATH_LIST <out-var> [NORMALIZE])

Converts a native ``<input>`` path into a cmake-style path with forward
slashes (``/``).  On Windows hosts, the long filename marker is taken into
account.  The input can be a single path or a system search path like
``$ENV{PATH}``.  A search path will be converted to a cmake-style list
separated by ``;`` characters (on non-Windows platforms, this essentially
means ``:`` separators are replaced with ``;``).  The result of the
conversion is stored in the ``<out-var>`` variable.

When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.

.. note::
  Unlike most other ``cmake_path()`` subcommands, the ``CONVERT`` subcommand
  takes a literal string as input, not the name of a variable.

.. _cmake_path-TO_NATIVE_PATH_LIST:
.. _TO_NATIVE_PATH_LIST:

.. code-block:: cmake

  cmake_path(CONVERT <input> TO_NATIVE_PATH_LIST <out-var> [NORMALIZE])

Converts a cmake-style ``<input>`` path into a native path with
platform-specific slashes (``\`` on Windows hosts and ``/`` elsewhere).
The input can be a single path or a cmake-style list.  A list will be
converted into a native search path (``;``-separated on Windows,
``:``-separated on other platforms).  The result of the conversion is
stored in the ``<out-var>`` variable.

When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.

.. note::
  Unlike most other ``cmake_path()`` subcommands, the ``CONVERT`` subcommand
  takes a literal string as input, not the name of a variable.

For example:

.. code-block:: cmake

  set(paths "/a/b/c" "/x/y/z")
  cmake_path(CONVERT "${paths}" TO_NATIVE_PATH_LIST native_paths)
  message("Native path list is \"${native_paths}\"")

Output on Windows::

  Native path list is "\a\b\c;\x\y\z"

Output on all other platforms::

  Native path list is "/a/b/c:/x/y/z"

Hashing
^^^^^^^

.. _HASH:

.. code-block:: cmake

    cmake_path(HASH <path-var> <out-var>)

Compute a hash value of ``<path-var>`` such that for two paths ``p1`` and
``p2`` that compare equal (:ref:`COMPARE ... EQUAL <COMPARE>`), the hash
value of ``p1`` is equal to the hash value of ``p2``.  The path is always
:ref:`normalized <Normalization>` before the hash is computed.


code:
cmake_policy
------------

Manage CMake Policy settings.  See the :manual:`cmake-policies(7)`
manual for defined policies.

As CMake evolves it is sometimes necessary to change existing behavior
in order to fix bugs or improve implementations of existing features.
The CMake Policy mechanism is designed to help keep existing projects
building as new versions of CMake introduce changes in behavior.  Each
new policy (behavioral change) is given an identifier of the form
``CMP<NNNN>`` where ``<NNNN>`` is an integer index.  Documentation
associated with each policy describes the ``OLD`` and ``NEW`` behavior
and the reason the policy was introduced.  Projects may set each policy
to select the desired behavior.  When CMake needs to know which behavior
to use it checks for a setting specified by the project.  If no
setting is available the ``OLD`` behavior is assumed and a warning is
produced requesting that the policy be set.

Setting Policies by CMake Version
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The ``cmake_policy`` command is used to set policies to ``OLD`` or ``NEW``
behavior.  While setting policies individually is supported, we
encourage projects to set policies based on CMake versions:

.. signature:: cmake_policy(VERSION <min>[...<max>])
  :target: VERSION

.. versionadded:: 3.12
  The optional ``<max>`` version.

``<min>`` and the optional ``<max>`` are each CMake versions of the form
``major.minor[.patch[.tweak]]``, and the ``...`` is literal.  The ``<min>``
version must be at least ``2.4`` and at most the running version of CMake.
The ``<max>`` version, if specified, must be at least the ``<min>`` version
but may exceed the running version of CMake.  If the running version of
CMake is older than 3.12, the extra ``...`` dots will be seen as version
component separators, resulting in the ``...<max>`` part being ignored and
preserving the pre-3.12 behavior of basing policies on ``<min>``.

This specifies that the current CMake code is written for the given
range of CMake versions.  All policies known to the running version of CMake
and introduced in the ``<min>`` (or ``<max>``, if specified) version
or earlier will be set to use ``NEW`` behavior.  All policies
introduced in later versions will be unset (unless the
:variable:`CMAKE_POLICY_DEFAULT_CMP<NNNN>` variable sets a default).
This effectively requests behavior preferred as of a given CMake
version and tells newer CMake versions to warn about their new policies.

Note that the :command:`cmake_minimum_required(VERSION)`
command implicitly calls ``cmake_policy(VERSION)`` too.

.. include:: DEPRECATED_POLICY_VERSIONS.txt

Setting Policies Explicitly
^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. signature:: cmake_policy(SET CMP<NNNN> NEW|OLD)
  :target: SET

Tell CMake to use the ``OLD`` or ``NEW`` behavior for a given policy.
Projects depending on the old behavior of a given policy may silence a
policy warning by setting the policy state to ``OLD``.  Alternatively
one may fix the project to work with the new behavior and set the
policy state to ``NEW``.

.. include:: ../policy/DEPRECATED.txt

Checking Policy Settings
^^^^^^^^^^^^^^^^^^^^^^^^

.. signature:: cmake_policy(GET CMP<NNNN> <variable>)
  :target: GET

Check whether a given policy is set to ``OLD`` or ``NEW`` behavior.
The output ``<variable>`` value will be ``OLD`` or ``NEW`` if the
policy is set, and empty otherwise.

CMake Policy Stack
^^^^^^^^^^^^^^^^^^

CMake keeps policy settings on a stack, so changes made by the
``cmake_policy`` command affect only the top of the stack.  A new entry on
the policy stack is managed automatically for each subdirectory to
protect its parents and siblings.  CMake also manages a new entry for
scripts loaded by :command:`include` and :command:`find_package` commands
except when invoked with the ``NO_POLICY_SCOPE`` option
(see also policy :policy:`CMP0011`).
The ``cmake_policy`` command provides an interface to manage custom
entries on the policy stack:

.. signature:: cmake_policy(PUSH)
  :target: PUSH

  Create a new entry on the policy stack.

.. signature:: cmake_policy(POP)
  :target: POP

  Remove the last policy stack entry created with ``cmake_policy(PUSH)``.

Each ``PUSH`` must have a matching ``POP`` to erase any changes.
This is useful to make temporary changes to policy settings.
Calls to the :command:`cmake_minimum_required(VERSION)`,
:command:`cmake_policy(VERSION)`, or :command:`cmake_policy(SET)` commands
influence only the current top of the policy stack.

.. versionadded:: 3.25
  The :command:`block(SCOPE_FOR POLICIES)` command offers a more flexible
  and more secure way to manage the policy stack. The pop action is done
  automatically when leaving the block scope, so there is no need to
  precede each :command:`return` with a call to :command:`cmake_policy(POP)`.

  .. code-block:: cmake

    # stack management with cmake_policy()
    function(my_func)
      cmake_policy(PUSH)
      cmake_policy(SET ...)
      if (<cond1>)
        ...
        cmake_policy(POP)
        return()
      elseif(<cond2>)
        ...
        cmake_policy(POP)
        return()
      endif()
      ...
      cmake_policy(POP)
    endfunction()

    # stack management with block()/endblock()
    function(my_func)
      block(SCOPE_FOR POLICIES)
        cmake_policy(SET ...)
        if (<cond1>)
          ...
          return()
        elseif(<cond2>)
          ...
          return()
        endif()
        ...
      endblock()
    endfunction()

Commands created by the :command:`function` and :command:`macro`
commands record policy settings when they are created and
use the pre-record policies when they are invoked.  If the function or
macro implementation sets policies, the changes automatically
propagate up through callers until they reach the closest nested
policy stack entry.

See Also
^^^^^^^^

* :command:`cmake_minimum_required`


code:
configure_file
--------------

.. only:: html

   .. contents::

Copy a file to another location and modify its contents.

.. code-block:: cmake

  configure_file(<input> <output>
                 [NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS |
                  FILE_PERMISSIONS <permissions>...]
                 [COPYONLY] [ESCAPE_QUOTES] [@ONLY]
                 [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])

Copies an ``<input>`` file to an ``<output>`` file while performing
`transformations`_ of the input file content.

If the input file is modified the build system will re-run CMake to
re-configure the file and generate the build system again.
The generated file is modified and its timestamp updated on subsequent
cmake runs only if its content is changed.

Options
^^^^^^^

The options are:

``<input>``
  Path to the input file.  A relative path is treated with respect to
  the value of :variable:`CMAKE_CURRENT_SOURCE_DIR`.  The input path
  must be a file, not a directory.

``<output>``
  Path to the output file or directory.  A relative path is treated
  with respect to the value of :variable:`CMAKE_CURRENT_BINARY_DIR`.
  If the path names an existing directory the output file is placed
  in that directory with the same file name as the input file.
  If the path contains non-existent directories, they are created.

``NO_SOURCE_PERMISSIONS``
  .. versionadded:: 3.19

  Do not transfer the permissions of the input file to the output file.
  The copied file permissions default to the standard 644 value
  (-rw-r--r--).

``USE_SOURCE_PERMISSIONS``
  .. versionadded:: 3.20

  Transfer the permissions of the input file to the output file.
  This is already the default behavior if none of the three permissions-related
  keywords are given (``NO_SOURCE_PERMISSIONS``, ``USE_SOURCE_PERMISSIONS``
  or ``FILE_PERMISSIONS``).  The ``USE_SOURCE_PERMISSIONS`` keyword mostly
  serves as a way of making the intended behavior clearer at the call site.

``FILE_PERMISSIONS <permissions>...``
  .. versionadded:: 3.20

  Ignore the input file's permissions and use the specified ``<permissions>``
  for the output file instead.

``COPYONLY``
  Copy the file without replacing any variable references or other
  content.  This option may not be used with ``NEWLINE_STYLE``.

``ESCAPE_QUOTES``
  Escape any substituted quotes with backslashes (C-style).

``@ONLY``
  Restrict variable replacement to references of the form ``@VAR@``.
  This is useful for configuring scripts that use ``${VAR}`` syntax.

``NEWLINE_STYLE <style>``
  Specify the newline style for the output file.  Specify
  ``UNIX`` or ``LF`` for ``\n`` newlines, or specify
  ``DOS``, ``WIN32``, or ``CRLF`` for ``\r\n`` newlines.
  This option may not be used with ``COPYONLY``.

Transformations
^^^^^^^^^^^^^^^

:ref:`Variables <CMake Language Variables>` referenced in the input
file content as ``@VAR@``, ``${VAR}``, ``$CACHE{VAR}``, and
:ref:`environment variables <CMake Language Environment Variables>`
referenced as ``$ENV{VAR}``, will each be replaced with the current value
of the variable, or the empty string if the variable is not defined.
Furthermore, input lines of the form

.. code-block:: c

  #cmakedefine VAR ...

will be replaced with either

.. code-block:: c

  #define VAR ...

or

.. code-block:: c

  /* #undef VAR */

depending on whether ``VAR`` is set in CMake to any value not considered
a false constant by the :command:`if` command.  The "..." content on the
line after the variable name, if any, is processed as above.

Unlike lines of the form ``#cmakedefine VAR ...``, in lines of the form
``#cmakedefine01 VAR``, ``VAR`` itself will expand to ``VAR 0`` or ``VAR 1``
rather than being assigned the value ``...``. Therefore, input lines of the form

.. code-block:: c

  #cmakedefine01 VAR

will be replaced with either

.. code-block:: c

  #define VAR 0

or

.. code-block:: c

  #define VAR 1

Input lines of the form ``#cmakedefine01 VAR ...`` will expand
as ``#cmakedefine01 VAR ... 0`` or ``#cmakedefine01 VAR ... 1``,
which may lead to undefined behavior.

.. versionadded:: 3.10
  The result lines (with the exception of the ``#undef`` comments) can be
  indented using spaces and/or tabs between the ``#`` character
  and the ``cmakedefine`` or ``cmakedefine01`` words. This whitespace
  indentation will be preserved in the output lines:

  .. code-block:: c

    #  cmakedefine VAR
    #  cmakedefine01 VAR

  will be replaced, if ``VAR`` is defined, with

  .. code-block:: c

    #  define VAR
    #  define VAR 1

Example
^^^^^^^

Consider a source tree containing a ``foo.h.in`` file:

.. code-block:: c

  #cmakedefine FOO_ENABLE
  #cmakedefine FOO_STRING "@FOO_STRING@"

An adjacent ``CMakeLists.txt`` may use ``configure_file`` to
configure the header:

.. code-block:: cmake

  option(FOO_ENABLE "Enable Foo" ON)
  if(FOO_ENABLE)
    set(FOO_STRING "foo")
  endif()
  configure_file(foo.h.in foo.h @ONLY)

This creates a ``foo.h`` in the build directory corresponding to
this source directory.  If the ``FOO_ENABLE`` option is on, the
configured file will contain:

.. code-block:: c

  #define FOO_ENABLE
  #define FOO_STRING "foo"

Otherwise it will contain:

.. code-block:: c

  /* #undef FOO_ENABLE */
  /* #undef FOO_STRING */

One may then use the :command:`target_include_directories` command to
specify the output directory as an include directory:

.. code-block:: cmake

  target_include_directories(<target> [SYSTEM] <INTERFACE|PUBLIC|PRIVATE> "${CMAKE_CURRENT_BINARY_DIR}")

so that sources may include the header as ``#include <foo.h>``.

See Also
^^^^^^^^

* :command:`file(GENERATE)`


code:
continue
--------

.. versionadded:: 3.2

Continue to the top of enclosing foreach or while loop.

.. code-block:: cmake

  continue()

The ``continue()`` command allows a cmake script to abort the rest of the
current iteration of a :command:`foreach` or :command:`while` loop, and start
at the top of the next iteration.

See also the :command:`break` command.


code:
create_test_sourcelist
----------------------

Create a test driver program that links together many small tests into a
single executable.  This is useful when building static executables with
large libraries to shrink the total required size.

.. signature::
  create_test_sourcelist(<sourceListName> <driverName> <test>... <options>...)
  :target: original

  Generate a test driver source file from a list of individual test sources
  and provide a combined list of sources that can be built as an executable.

  The options are:

  ``<sourceListName>``
    The name of a variable in which to store the list of source files needed
    to build the test driver.  The list will contain the ``<test>...`` sources
    and the generated ``<driverName>`` source.

    .. versionchanged:: 3.29

      The test driver source is listed by absolute path in the build tree.
      Previously it was listed only as ``<driverName>``.

  ``<driverName>``
    Name of the test driver source file to be generated into the build tree.
    The source file will contain a ``main()`` program entry point that
    dispatches to whatever test is named on the command line.

  ``<test>...``
    Test source files to be added to the driver binary.  Each test source
    file must have a function in it that is the same name as the file with the
    extension removed.  For example, a ``foo.cxx`` test source might contain:

    .. code-block:: c++

      int foo(int argc, char** argv)

  ``EXTRA_INCLUDE <header>``
    Specify a header file to ``#include`` in the generated test driver source.

  ``FUNCTION <function>``
    Specify a function to be called with pointers to ``argc`` and ``argv``.
    The function may be provided in the ``EXTRA_INCLUDE`` header:

    .. code-block:: c++

      void function(int* pargc, char*** pargv)

    This can be used to add extra command line processing to each test.

Additionally, some CMake variables affect test driver generation:

.. variable:: CMAKE_TESTDRIVER_BEFORE_TESTMAIN

  Code to be placed directly before calling each test's function.

.. variable:: CMAKE_TESTDRIVER_AFTER_TESTMAIN

  Code to be placed directly after the call to each test's function.


code:
ctest_build
-----------

Perform the :ref:`CTest Build Step` as a :ref:`Dashboard Client`.

.. code-block:: cmake

  ctest_build([BUILD <build-dir>] [APPEND]
              [CONFIGURATION <config>]
              [PARALLEL_LEVEL <parallel>]
              [FLAGS <flags>]
              [PROJECT_NAME <project-name>]
              [TARGET <target-name>]
              [NUMBER_ERRORS <num-err-var>]
              [NUMBER_WARNINGS <num-warn-var>]
              [RETURN_VALUE <result-var>]
              [CAPTURE_CMAKE_ERROR <result-var>]
              )

Build the project and store results in ``Build.xml``
for submission with the :command:`ctest_submit` command.

The :variable:`CTEST_BUILD_COMMAND` variable may be set to explicitly
specify the build command line.  Otherwise the build command line is
computed automatically based on the options given.

The options are:

``BUILD <build-dir>``
  Specify the top-level build directory.  If not given, the
  :variable:`CTEST_BINARY_DIRECTORY` variable is used.

``APPEND``
  Mark ``Build.xml`` for append to results previously submitted to a
  dashboard server since the last :command:`ctest_start` call.
  Append semantics are defined by the dashboard server in use.
  This does *not* cause results to be appended to a ``.xml`` file
  produced by a previous call to this command.

``CONFIGURATION <config>``
  Specify the build configuration (e.g. ``Debug``).  If not
  specified the ``CTEST_BUILD_CONFIGURATION`` variable will be checked.
  Otherwise the :option:`-C \<cfg\> <ctest -C>` option given to the
  :manual:`ctest(1)` command will be used, if any.

``PARALLEL_LEVEL <parallel>``
  .. versionadded:: 3.21

  Specify the parallel level of the underlying build system.  If not
  specified, the :envvar:`CMAKE_BUILD_PARALLEL_LEVEL` environment
  variable will be checked.

``FLAGS <flags>``
  Pass additional arguments to the underlying build command.
  If not specified the ``CTEST_BUILD_FLAGS`` variable will be checked.
  This can, e.g., be used to trigger a parallel build using the
  ``-j`` option of ``make``. See the :module:`ProcessorCount` module
  for an example.

``PROJECT_NAME <project-name>``
  Ignored since CMake 3.0.

  .. versionchanged:: 3.14
    This value is no longer required.

``TARGET <target-name>``
  Specify the name of a target to build.  If not specified the
  ``CTEST_BUILD_TARGET`` variable will be checked.  Otherwise the
  default target will be built.  This is the "all" target
  (called ``ALL_BUILD`` in :ref:`Visual Studio Generators`).

``NUMBER_ERRORS <num-err-var>``
  Store the number of build errors detected in the given variable.

``NUMBER_WARNINGS <num-warn-var>``
  Store the number of build warnings detected in the given variable.

``RETURN_VALUE <result-var>``
  Store the return value of the native build tool in the given variable.

``CAPTURE_CMAKE_ERROR <result-var>``
  .. versionadded:: 3.7

  Store in the ``<result-var>`` variable -1 if there are any errors running
  the command and prevent ctest from returning non-zero if an error occurs.

``QUIET``
  .. versionadded:: 3.3

  Suppress any CTest-specific non-error output that would have been
  printed to the console otherwise.  The summary of warnings / errors,
  as well as the output from the native build tool is unaffected by
  this option.


code:
ctest_configure
---------------

Perform the :ref:`CTest Configure Step` as a :ref:`Dashboard Client`.

.. code-block:: cmake

  ctest_configure([BUILD <build-dir>] [SOURCE <source-dir>] [APPEND]
                  [OPTIONS <options>] [RETURN_VALUE <result-var>] [QUIET]
                  [CAPTURE_CMAKE_ERROR <result-var>])

Configure the project build tree and record results in ``Configure.xml``
for submission with the :command:`ctest_submit` command.

The options are:

``BUILD <build-dir>``
  Specify the top-level build directory.  If not given, the
  :variable:`CTEST_BINARY_DIRECTORY` variable is used.

``SOURCE <source-dir>``
  Specify the source directory.  If not given, the
  :variable:`CTEST_SOURCE_DIRECTORY` variable is used.

``APPEND``
  Mark ``Configure.xml`` for append to results previously submitted to a
  dashboard server since the last :command:`ctest_start` call.
  Append semantics are defined by the dashboard server in use.
  This does *not* cause results to be appended to a ``.xml`` file
  produced by a previous call to this command.

``OPTIONS <options>``
  Specify command-line arguments to pass to the configuration tool.

``RETURN_VALUE <result-var>``
  Store in the ``<result-var>`` variable the return value of the native
  configuration tool.

``CAPTURE_CMAKE_ERROR <result-var>``
  .. versionadded:: 3.7

  Store in the ``<result-var>`` variable -1 if there are any errors running
  the command and prevent ctest from returning non-zero if an error occurs.

``QUIET``
  .. versionadded:: 3.3

  Suppress any CTest-specific non-error messages that would have
  otherwise been printed to the console.  Output from the underlying
  configure command is not affected.


code:
ctest_coverage
--------------

Perform the :ref:`CTest Coverage Step` as a :ref:`Dashboard Client`.

.. code-block:: cmake

  ctest_coverage([BUILD <build-dir>] [APPEND]
                 [LABELS <label>...]
                 [RETURN_VALUE <result-var>]
                 [CAPTURE_CMAKE_ERROR <result-var>]
                 [QUIET]
                 )

Collect coverage tool results and stores them in ``Coverage.xml``
for submission with the :command:`ctest_submit` command.

The options are:

``BUILD <build-dir>``
  Specify the top-level build directory.  If not given, the
  :variable:`CTEST_BINARY_DIRECTORY` variable is used.

``APPEND``
  Mark ``Coverage.xml`` for append to results previously submitted to a
  dashboard server since the last :command:`ctest_start` call.
  Append semantics are defined by the dashboard server in use.
  This does *not* cause results to be appended to a ``.xml`` file
  produced by a previous call to this command.

``LABELS``
  Filter the coverage report to include only source files labeled
  with at least one of the labels specified.

``RETURN_VALUE <result-var>``
  Store in the ``<result-var>`` variable ``0`` if coverage tools
  ran without error and non-zero otherwise.

``CAPTURE_CMAKE_ERROR <result-var>``
  .. versionadded:: 3.7

  Store in the ``<result-var>`` variable -1 if there are any errors running
  the command and prevent ctest from returning non-zero if an error occurs.

``QUIET``
  .. versionadded:: 3.3

  Suppress any CTest-specific non-error output that would have been
  printed to the console otherwise.  The summary indicating how many
  lines of code were covered is unaffected by this option.


code:
ctest_empty_binary_directory
----------------------------

empties the binary directory

.. code-block:: cmake

  ctest_empty_binary_directory(<directory>)

Removes a binary directory.  This command will perform some checks
prior to deleting the directory in an attempt to avoid malicious or
accidental directory deletion.


code:
ctest_memcheck
--------------

Perform the :ref:`CTest MemCheck Step` as a :ref:`Dashboard Client`.

.. code-block:: cmake

  ctest_memcheck([BUILD <build-dir>] [APPEND]
                 [START <start-number>]
                 [END <end-number>]
                 [STRIDE <stride-number>]
                 [EXCLUDE <exclude-regex>]
                 [INCLUDE <include-regex>]
                 [EXCLUDE_LABEL <label-exclude-regex>]
                 [INCLUDE_LABEL <label-include-regex>]
                 [EXCLUDE_FIXTURE <regex>]
                 [EXCLUDE_FIXTURE_SETUP <regex>]
                 [EXCLUDE_FIXTURE_CLEANUP <regex>]
                 [PARALLEL_LEVEL <level>]
                 [RESOURCE_SPEC_FILE <file>]
                 [TEST_LOAD <threshold>]
                 [SCHEDULE_RANDOM <ON|OFF>]
                 [STOP_ON_FAILURE]
                 [STOP_TIME <time-of-day>]
                 [RETURN_VALUE <result-var>]
                 [CAPTURE_CMAKE_ERROR <result-var>]
                 [REPEAT <mode>:<n>]
                 [OUTPUT_JUNIT <file>]
                 [DEFECT_COUNT <defect-count-var>]
                 [QUIET]
                 )

Run tests with a dynamic analysis tool and store results in
``MemCheck.xml`` for submission with the :command:`ctest_submit`
command.

Most options are the same as those for the :command:`ctest_test` command.

The options unique to this command are:

``DEFECT_COUNT <defect-count-var>``
  .. versionadded:: 3.8

  Store in the ``<defect-count-var>`` the number of defects found.


code:
ctest_read_custom_files
-----------------------

read CTestCustom files.

.. code-block:: cmake

  ctest_read_custom_files(<directory>...)

Read all the CTestCustom.ctest or CTestCustom.cmake files from the
given directory.

By default, invoking :manual:`ctest(1)` without a script will read custom
files from the binary directory.


code:
ctest_run_script
----------------

runs a :option:`ctest -S` script

.. code-block:: cmake

  ctest_run_script([NEW_PROCESS] script_file_name script_file_name1
              script_file_name2 ... [RETURN_VALUE var])

Runs a script or scripts much like if it was run from :option:`ctest -S`.
If no argument is provided then the current script is run using the current
settings of the variables.  If ``NEW_PROCESS`` is specified then each
script will be run in a separate process.If ``RETURN_VALUE`` is specified
the return value of the last script run will be put into ``var``.


code:
ctest_sleep
-----------

sleeps for some amount of time

.. code-block:: cmake

  ctest_sleep(<seconds>)

Sleep for given number of seconds.

.. code-block:: cmake

  ctest_sleep(<time1> <duration> <time2>)

Sleep for t=(time1 + duration - time2) seconds if t > 0.


code:
ctest_start
-----------

Starts the testing for a given model

.. code-block:: cmake

  ctest_start(<model> [<source> [<binary>]] [GROUP <group>] [QUIET])

  ctest_start([<model> [<source> [<binary>]]] [GROUP <group>] APPEND [QUIET])

Starts the testing for a given model.  The command should be called
after the binary directory is initialized.

The parameters are as follows:

``<model>``
  Set the dashboard model. Must be one of ``Experimental``, ``Continuous``, or
  ``Nightly``. This parameter is required unless ``APPEND`` is specified.

``<source>``
  Set the source directory. If not specified, the value of
  :variable:`CTEST_SOURCE_DIRECTORY` is used instead.

``<binary>``
  Set the binary directory. If not specified, the value of
  :variable:`CTEST_BINARY_DIRECTORY` is used instead.

``GROUP <group>``
  If ``GROUP`` is used, the submissions will go to the specified group on the
  CDash server. If no ``GROUP`` is specified, the name of the model is used by
  default.

  .. versionchanged:: 3.16
    This replaces the deprecated option ``TRACK``. Despite the name
    change its behavior is unchanged.

``APPEND``
  If ``APPEND`` is used, the existing ``TAG`` is used rather than creating a new
  one based on the current time stamp. If you use ``APPEND``, you can omit the
  ``<model>`` and ``GROUP <group>`` parameters, because they will be read from
  the generated ``TAG`` file. For example:

  .. code-block:: cmake

    ctest_start(Experimental GROUP GroupExperimental)

  Later, in another :option:`ctest -S` script:

  .. code-block:: cmake

    ctest_start(APPEND)

  When the second script runs ``ctest_start(APPEND)``, it will read the
  ``Experimental`` model and ``GroupExperimental`` group from the ``TAG`` file
  generated by the first ``ctest_start()`` command. Please note that if you
  call ``ctest_start(APPEND)`` and specify a different model or group than
  in the first ``ctest_start()`` command, a warning will be issued, and the
  new model and group will be used.

``QUIET``
  .. versionadded:: 3.3

  If ``QUIET`` is used, CTest will suppress any non-error messages that it
  otherwise would have printed to the console.

The parameters for ``ctest_start()`` can be issued in any order, with the
exception that ``<model>``, ``<source>``, and ``<binary>`` have to appear
in that order with respect to each other. The following are all valid and
equivalent:

.. code-block:: cmake

  ctest_start(Experimental path/to/source path/to/binary GROUP SomeGroup QUIET APPEND)

  ctest_start(GROUP SomeGroup Experimental QUIET path/to/source APPEND path/to/binary)

  ctest_start(APPEND QUIET Experimental path/to/source GROUP SomeGroup path/to/binary)

However, for the sake of readability, it is recommended that you order your
parameters in the order listed at the top of this page.

If the :variable:`CTEST_CHECKOUT_COMMAND` variable (or the
:variable:`CTEST_CVS_CHECKOUT` variable) is set, its content is treated as
command-line.  The command is invoked with the current working directory set
to the parent of the source directory, even if the source directory already
exists.  This can be used to create the source tree from a version control
repository.