code:
Ninja Multi-Config
------------------

.. versionadded:: 3.17

Generates multiple ``build-<Config>.ninja`` files.

This generator is very much like the :generator:`Ninja` generator, but with
some key differences. Only these differences will be discussed in this
document.

Unlike the :generator:`Ninja` generator, ``Ninja Multi-Config`` generates
multiple configurations at once with :variable:`CMAKE_CONFIGURATION_TYPES`
instead of only one configuration with :variable:`CMAKE_BUILD_TYPE`. One
``build-<Config>.ninja`` file will be generated for each of these
configurations (with ``<Config>`` being the configuration name.) These files
are intended to be run with ``ninja -f build-<Config>.ninja``. A
``build.ninja`` file is also generated, using the configuration from either
:variable:`CMAKE_DEFAULT_BUILD_TYPE` or the first item from
:variable:`CMAKE_CONFIGURATION_TYPES`.

``cmake --build . --config <Config>`` will always use ``build-<Config>.ninja``
to build. If no :option:`--config <cmake--build --config>` argument is
specified, :option:`cmake --build . <cmake --build>` will use ``build.ninja``.

Each ``build-<Config>.ninja`` file contains ``<target>`` targets as well as
``<target>:<Config>`` targets, where ``<Config>`` is the same as the
configuration specified in ``build-<Config>.ninja`` Additionally, if
cross-config mode is enabled, ``build-<Config>.ninja`` may contain
``<target>:<OtherConfig>`` targets, where ``<OtherConfig>`` is a cross-config,
as well as ``<target>:all``, which builds the target in all cross-configs. See
below for how to enable cross-config mode.

The ``Ninja Multi-Config`` generator recognizes the following variables:

:variable:`CMAKE_CONFIGURATION_TYPES`
  Specifies the total set of configurations to build. Unlike with other
  multi-config generators, this variable has a value of
  ``Debug;Release;RelWithDebInfo`` by default.

:variable:`CMAKE_CROSS_CONFIGS`
  Specifies a :ref:`semicolon-separated list <CMake Language Lists>` of
  configurations available from all ``build-<Config>.ninja`` files.

:variable:`CMAKE_DEFAULT_BUILD_TYPE`
  Specifies the configuration to use by default in a ``build.ninja`` file.

:variable:`CMAKE_DEFAULT_CONFIGS`
  Specifies a :ref:`semicolon-separated list <CMake Language Lists>` of
  configurations to build for a target in ``build.ninja``
  if no ``:<Config>`` suffix is specified.

Consider the following example:

.. code-block:: cmake

  cmake_minimum_required(VERSION 3.16)
  project(MultiConfigNinja C)

  add_executable(generator generator.c)
  add_custom_command(OUTPUT generated.c COMMAND generator generated.c)
  add_library(generated ${CMAKE_BINARY_DIR}/generated.c)

Now assume you configure the project with ``Ninja Multi-Config`` and run one of
the following commands:

.. code-block:: shell

  ninja -f build-Debug.ninja generated
  # OR
  cmake --build . --config Debug --target generated

This would build the ``Debug`` configuration of ``generator``, which would be
used to generate ``generated.c``, which would be used to build the ``Debug``
configuration of ``generated``.

But if :variable:`CMAKE_CROSS_CONFIGS` is set to ``all``, and you run the
following instead:

.. code-block:: shell

  ninja -f build-Release.ninja generated:Debug
  # OR
  cmake --build . --config Release --target generated:Debug

This would build the ``Release`` configuration of ``generator``, which would be
used to generate ``generated.c``, which would be used to build the ``Debug``
configuration of ``generated``. This is useful for running a release-optimized
version of a generator utility while still building the debug version of the
targets built with the generated code.

Custom Commands
^^^^^^^^^^^^^^^

.. versionadded:: 3.20

The ``Ninja Multi-Config`` generator adds extra capabilities to
:command:`add_custom_command` and :command:`add_custom_target` through its
cross-config mode. The ``COMMAND``, ``DEPENDS``, and ``WORKING_DIRECTORY``
arguments can be evaluated in the context of either the "command config" (the
"native" configuration of the ``build-<Config>.ninja`` file in use) or the
"output config" (the configuration used to evaluate the ``OUTPUT`` and
``BYPRODUCTS``).

If either ``OUTPUT`` or ``BYPRODUCTS`` names a path that is common to
more than one configuration (e.g. it does not use any generator expressions),
all arguments are evaluated in the command config by default.
If all ``OUTPUT`` and ``BYPRODUCTS`` paths are unique to each configuration
(e.g. by using the :genex:`$<CONFIG>` generator expression), the first argument of
``COMMAND`` is still evaluated in the command config by default, while all
subsequent arguments, as well as the arguments to ``DEPENDS`` and
``WORKING_DIRECTORY``, are evaluated in the output config. These defaults can
be overridden with the :genex:`$<OUTPUT_CONFIG:...>` and :genex:`$<COMMAND_CONFIG:...>`
generator-expressions. Note that if a target is specified by its name in
``DEPENDS``, or as the first argument of ``COMMAND``, it is always evaluated
in the command config, even if it is wrapped in :genex:`$<OUTPUT_CONFIG:...>`
(because its plain name is not a generator expression).

As an example, consider the following:

.. code-block:: cmake

  add_custom_command(
    OUTPUT "$<CONFIG>.txt"
    COMMAND
      generator "$<CONFIG>.txt"
                "$<OUTPUT_CONFIG:$<CONFIG>>"
                "$<COMMAND_CONFIG:$<CONFIG>>"
    DEPENDS
      tgt1
      "$<TARGET_FILE:tgt2>"
      "$<OUTPUT_CONFIG:$<TARGET_FILE:tgt3>>"
      "$<COMMAND_CONFIG:$<TARGET_FILE:tgt4>>"
    )

Assume that ``generator``, ``tgt1``, ``tgt2``, ``tgt3``, and ``tgt4`` are all
executable targets, and assume that ``$<CONFIG>.txt`` is built in the ``Debug``
output config using the ``Release`` command config. The ``Release`` build of
the ``generator`` target is called with ``Debug.txt Debug Release`` as
arguments. The command depends on the ``Release`` builds of ``tgt1`` and
``tgt4``, and the ``Debug`` builds of ``tgt2`` and ``tgt3``.

``PRE_BUILD``, ``PRE_LINK``, and ``POST_BUILD`` custom commands for targets
only get run in their "native" configuration (the ``Release`` configuration in
the ``build-Release.ninja`` file) unless they have no ``BYPRODUCTS`` or their
``BYPRODUCTS`` are unique per config. Consider the following example:

.. code-block:: cmake

  add_executable(exe main.c)
  add_custom_command(
    TARGET exe
    POST_BUILD
    COMMAND
      ${CMAKE_COMMAND} -E echo "Running no-byproduct command"
    )
  add_custom_command(
    TARGET exe
    POST_BUILD
    COMMAND
      ${CMAKE_COMMAND} -E echo
      "Running separate-byproduct command for $<CONFIG>"
    BYPRODUCTS $<CONFIG>.txt
    )
  add_custom_command(
    TARGET exe
    POST_BUILD
    COMMAND
      ${CMAKE_COMMAND} -E echo
      "Running common-byproduct command for $<CONFIG>"
    BYPRODUCTS exe.txt
    )

In this example, if you build ``exe:Debug`` in ``build-Release.ninja``, the
first and second custom commands get run, since their byproducts are unique
per-config, but the last custom command does not. However, if you build
``exe:Release`` in ``build-Release.ninja``, all three custom commands get run.


code:
Ninja
-----

Generates ``build.ninja`` files.

A ``build.ninja`` file is generated into the build tree.  Use the ninja
program to build the project through the ``all`` target and install the
project through the ``install`` (or ``install/strip``) target.

For each subdirectory ``sub/dir`` of the project, additional targets
are generated:

``sub/dir/all``

  .. versionadded:: 3.6

    Depends on all targets required by the subdirectory.

``sub/dir/install``

  .. versionadded:: 3.7

    Runs the install step in the subdirectory, if any.

``sub/dir/install/strip``

  .. versionadded:: 3.7
    Runs the install step in the subdirectory followed by a ``CMAKE_STRIP`` command,
    if any.

    The ``CMAKE_STRIP`` variable will contain the platform's ``strip`` utility, which
    removes symbols information from generated binaries.

``sub/dir/test``

  .. versionadded:: 3.7

    Runs the test step in the subdirectory, if any.

``sub/dir/package``

  .. versionadded:: 3.7

    Runs the package step in the subdirectory, if any.

Fortran Support
^^^^^^^^^^^^^^^

.. versionadded:: 3.7

The ``Ninja`` generator conditionally supports Fortran when the ``ninja``
tool is at least version 1.10 (which has the required features).

Swift Support
^^^^^^^^^^^^^

.. versionadded:: 3.15

The Swift support is experimental, not considered stable, and may change
in future releases of CMake.

See Also
^^^^^^^^

.. versionadded:: 3.17
  The :generator:`Ninja Multi-Config` generator is similar to the ``Ninja``
  generator, but generates multiple configurations at once.

repo_name: lazytadpole/codenamesilverfish

license: mit


code:
Sublime Text 2
--------------

.. deprecated:: 3.27

  Support for :ref:`Extra Generators` is deprecated and will be removed from
  a future version of CMake.  IDEs may use the :manual:`cmake-file-api(7)`
  to view CMake-generated project build trees.

Generates Sublime Text 2 project files.

Project files for Sublime Text 2 will be created in the top directory
and in every subdirectory which features a ``CMakeLists.txt`` file
containing a :command:`project` call.  Additionally ``Makefiles``
(or ``build.ninja`` files) are generated into the build tree.
The appropriate make program can build the project through the default ``all``
target.  An ``install`` target is also provided.

This "extra" generator may be specified as:

``Sublime Text 2 - MinGW Makefiles``
 Generate with :generator:`MinGW Makefiles`.

``Sublime Text 2 - NMake Makefiles``
 Generate with :generator:`NMake Makefiles`.

``Sublime Text 2 - Ninja``
 Generate with :generator:`Ninja`.

``Sublime Text 2 - Unix Makefiles``
 Generate with :generator:`Unix Makefiles`.


code:
Unix Makefiles
--------------

Generates standard UNIX makefiles.

A hierarchy of UNIX makefiles is generated into the build tree.  Use
any standard UNIX-style make program to build the project through
the ``all`` target and install the project through the ``install``
(or ``install/strip``) target.

For each subdirectory ``sub/dir`` of the project a UNIX makefile will
be created, containing the following targets:

``all``
  Depends on all targets required by the subdirectory.

``install``
  Runs the install step in the subdirectory, if any.

``install/strip``
  Runs the install step in the subdirectory followed by a ``CMAKE_STRIP`` command,
  if any.

  The ``CMAKE_STRIP`` variable will contain the platform's ``strip`` utility, which
  removes symbols information from generated binaries.

``test``
  Runs the test step in the subdirectory, if any.

``package``
  Runs the package step in the subdirectory, if any.


code:
Visual Studio 10 2010
---------------------

Removed.  This once generated Visual Studio 10 2010 project files, but
the generator has been removed since CMake 3.25.  It is still possible
to build with VS 10 2010 tools using the :generator:`Visual Studio 14 2015`
(or above) generator with :variable:`CMAKE_GENERATOR_TOOLSET` set to
``v100``, or by using the :generator:`NMake Makefiles` generator.

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 10 2010.rst.txt


code:
Visual Studio 11 2012
---------------------

Removed.  This once generated Visual Studio 11 2012 project files, but
the generator has been removed since CMake 3.28.  It is still possible
to build with VS 11 2012 tools using the :generator:`Visual Studio 14 2015`
(or above) generator with :variable:`CMAKE_GENERATOR_TOOLSET` set to ``v110``,
or by using the :generator:`NMake Makefiles` generator.

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 11 2012.rst.txt


code:
Visual Studio 12 2013
---------------------

Deprecated.  Generates Visual Studio 12 (VS 2013) project files.

.. note::
  This generator is deprecated and will be removed in a future version
  of CMake.  It will still be possible to build with VS 12 2013 tools
  using the :generator:`Visual Studio 14 2015` (or above) generator
  with :variable:`CMAKE_GENERATOR_TOOLSET` set to ``v120``, or by
  using the :generator:`NMake Makefiles` generator.

For compatibility with CMake versions prior to 3.0, one may specify this
generator using the name "Visual Studio 12" without the year component.

Project Types
^^^^^^^^^^^^^

Only Visual C++ and C# projects may be generated (and Fortran with
Intel compiler integration).  Other types of projects (JavaScript,
Powershell, Python, etc.) are not supported.

Platform Selection
^^^^^^^^^^^^^^^^^^

The default target platform name (architecture) is ``Win32``.

.. versionadded:: 3.1
  The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps
  via the :option:`cmake -A` option, to specify a target platform
  name (architecture).  For example:

  * ``cmake -G "Visual Studio 12 2013" -A Win32``
  * ``cmake -G "Visual Studio 12 2013" -A x64``
  * ``cmake -G "Visual Studio 12 2013" -A ARM``

For compatibility with CMake versions prior to 3.1, one may specify
a target platform name optionally at the end of the generator name.
This is supported only for:

``Visual Studio 12 2013 Win64``
  Specify target platform ``x64``.

``Visual Studio 12 2013 ARM``
  Specify target platform ``ARM``.

Toolset Selection
^^^^^^^^^^^^^^^^^

The ``v120`` toolset that comes with Visual Studio 12 2013 is selected by
default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
via the :option:`cmake -T` option, to specify another toolset.

.. |VS_TOOLSET_HOST_ARCH_DEFAULT| replace::
   By default this generator uses the 32-bit variant even on a 64-bit host.

.. include:: VS_TOOLSET_HOST_ARCH_LEGACY.txt

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 12 2013.rst.txt


code:
Visual Studio 14 2015
---------------------

.. versionadded:: 3.1

Generates Visual Studio 14 (VS 2015) project files.

Project Types
^^^^^^^^^^^^^

Only Visual C++ and C# projects may be generated (and Fortran with
Intel compiler integration).  Other types of projects (JavaScript,
Powershell, Python, etc.) are not supported.

Platform Selection
^^^^^^^^^^^^^^^^^^

The default target platform name (architecture) is ``Win32``.

The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps
via the :option:`cmake -A` option, to specify a target platform
name (architecture).  For example:

* ``cmake -G "Visual Studio 14 2015" -A Win32``
* ``cmake -G "Visual Studio 14 2015" -A x64``
* ``cmake -G "Visual Studio 14 2015" -A ARM``

For compatibility with CMake versions prior to 3.1, one may specify
a target platform name optionally at the end of the generator name.
This is supported only for:

``Visual Studio 14 2015 Win64``
  Specify target platform ``x64``.

``Visual Studio 14 2015 ARM``
  Specify target platform ``ARM``.

Toolset Selection
^^^^^^^^^^^^^^^^^

The ``v140`` toolset that comes with Visual Studio 14 2015 is selected by
default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
via the :option:`cmake -T` option, to specify another toolset.

.. |VS_TOOLSET_HOST_ARCH_DEFAULT| replace::
   By default this generator uses the 32-bit variant even on a 64-bit host.

.. include:: VS_TOOLSET_HOST_ARCH_LEGACY.txt

.. _`Windows 10 SDK Maximum Version for VS 2015`:

Windows 10 SDK Maximum Version for VS 2015
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. versionadded:: 3.19

Microsoft stated in a "Windows 10 October 2018 Update" blog post that Windows
10 SDK versions (15063, 16299, 17134, 17763) are not supported by VS 2015 and
are only supported by VS 2017 and later.  Therefore by default CMake
automatically ignores Windows 10 SDKs beyond ``10.0.14393.0``.

However, there are other recommendations for certain driver/Win32 builds that
indicate otherwise.  A user can override this behavior by either setting the
:variable:`CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION_MAXIMUM` to a false value
or setting the :variable:`CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION_MAXIMUM` to
the string value of the required maximum (e.g. ``10.0.15063.0``).

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 14 2015.rst.txt


code:
Visual Studio 15 2017
---------------------

.. versionadded:: 3.7.1

Generates Visual Studio 15 (VS 2017) project files.

Project Types
^^^^^^^^^^^^^

Only Visual C++ and C# projects may be generated (and Fortran with
Intel compiler integration).  Other types of projects (JavaScript,
Powershell, Python, etc.) are not supported.

Instance Selection
^^^^^^^^^^^^^^^^^^

.. versionadded:: 3.11

VS 2017 supports multiple installations on the same machine.  The
:variable:`CMAKE_GENERATOR_INSTANCE` variable may be used to select one.

Platform Selection
^^^^^^^^^^^^^^^^^^

The default target platform name (architecture) is ``Win32``.

The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps
via the :option:`cmake -A` option, to specify a target platform
name (architecture).  For example:

* ``cmake -G "Visual Studio 15 2017" -A Win32``
* ``cmake -G "Visual Studio 15 2017" -A x64``
* ``cmake -G "Visual Studio 15 2017" -A ARM``
* ``cmake -G "Visual Studio 15 2017" -A ARM64``

For compatibility with CMake versions prior to 3.1, one may specify
a target platform name optionally at the end of the generator name.
This is supported only for:

``Visual Studio 15 2017 Win64``
  Specify target platform ``x64``.

``Visual Studio 15 2017 ARM``
  Specify target platform ``ARM``.

Toolset Selection
^^^^^^^^^^^^^^^^^

The ``v141`` toolset that comes with Visual Studio 15 2017 is selected by
default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
via the :option:`cmake -T` option, to specify another toolset.

.. |VS_TOOLSET_HOST_ARCH_DEFAULT| replace::
   By default this generator uses the 32-bit variant even on a 64-bit host.

.. include:: VS_TOOLSET_HOST_ARCH_LEGACY.txt

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 15 2017.rst.txt


code:
Visual Studio 16 2019
---------------------

.. versionadded:: 3.14

Generates Visual Studio 16 (VS 2019) project files.

Project Types
^^^^^^^^^^^^^

Only Visual C++ and C# projects may be generated (and Fortran with
Intel compiler integration).  Other types of projects (JavaScript,
Powershell, Python, etc.) are not supported.

Instance Selection
^^^^^^^^^^^^^^^^^^

VS 2019 supports multiple installations on the same machine.  The
:variable:`CMAKE_GENERATOR_INSTANCE` variable may be used to select one.

Platform Selection
^^^^^^^^^^^^^^^^^^

The default target platform name (architecture) is that of the host
and is provided in the :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable.

The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps
via the :option:`cmake -A` option, to specify a target platform
name (architecture).  For example:

* ``cmake -G "Visual Studio 16 2019" -A Win32``
* ``cmake -G "Visual Studio 16 2019" -A x64``
* ``cmake -G "Visual Studio 16 2019" -A ARM``
* ``cmake -G "Visual Studio 16 2019" -A ARM64``

Toolset Selection
^^^^^^^^^^^^^^^^^

The ``v142`` toolset that comes with Visual Studio 16 2019 is selected by
default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
via the :option:`cmake -T` option, to specify another toolset.

.. |VS_TOOLSET_HOST_ARCH_DEFAULT| replace::
   By default this generator uses the 64-bit variant on x64 hosts and
   the 32-bit variant otherwise.

.. include:: VS_TOOLSET_HOST_ARCH.txt

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 16 2019.rst.txt


code:
Visual Studio 17 2022
---------------------

.. versionadded:: 3.21

Generates Visual Studio 17 (VS 2022) project files.

Project Types
^^^^^^^^^^^^^

Only Visual C++ and C# projects may be generated (and Fortran with
Intel compiler integration).  Other types of projects (JavaScript,
Powershell, Python, etc.) are not supported.

Instance Selection
^^^^^^^^^^^^^^^^^^

VS 2022 supports multiple installations on the same machine.  The
:variable:`CMAKE_GENERATOR_INSTANCE` variable may be used to select one.

Platform Selection
^^^^^^^^^^^^^^^^^^

The default target platform name (architecture) is that of the host
and is provided in the :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable.

The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps
via the :option:`cmake -A` option, to specify a target platform
name (architecture).  For example:

* ``cmake -G "Visual Studio 17 2022" -A Win32``
* ``cmake -G "Visual Studio 17 2022" -A x64``
* ``cmake -G "Visual Studio 17 2022" -A ARM``
* ``cmake -G "Visual Studio 17 2022" -A ARM64``

Toolset Selection
^^^^^^^^^^^^^^^^^

The ``v143`` toolset that comes with VS 17 2022 is selected by default.
The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
via the :option:`cmake -T` option, to specify another toolset.

.. |VS_TOOLSET_HOST_ARCH_DEFAULT| replace::
   By default this generator uses the 64-bit variant on x64 hosts and
   the 32-bit variant otherwise.

.. include:: VS_TOOLSET_HOST_ARCH.txt

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 17 2022.rst.txt


code:
Visual Studio 6
---------------

Removed.  This once generated Visual Studio 6 project files, but the
generator has been removed since CMake 3.6.  It is still possible to
build with VS 6 tools using the :generator:`NMake Makefiles` generator.


code:
Visual Studio 7 .NET 2003
-------------------------

Removed.  This once generated Visual Studio .NET 2003 project files, but
the generator has been removed since CMake 3.9.  It is still possible to
build with VS 7.1 tools using the :generator:`NMake Makefiles` generator.

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 7 .NET 2003.rst.txt


code:
Visual Studio 7
---------------

Removed.  This once generated Visual Studio .NET 2002 project files, but
the generator has been removed since CMake 3.6.  It is still possible to
build with VS 7.0 tools using the :generator:`NMake Makefiles` generator.


code:
Visual Studio 8 2005
--------------------

Removed.  This once generated Visual Studio 8 2005 project files, but
the generator has been removed since CMake 3.12.  It is still possible to
build with VS 2005 tools using the :generator:`NMake Makefiles` generator.

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 8 2005.rst.txt


code:
Visual Studio 9 2008
--------------------

Deprecated.  Generates Visual Studio 9 2008 project files.

.. note::
  This generator is deprecated and will be removed in a future version
  of CMake.  It will still be possible to build with VS 9 2008 tools
  using the :generator:`Visual Studio 14 2015` generator (or above,
  and with VS 10 2010 also installed) with
  :variable:`CMAKE_GENERATOR_TOOLSET` set to ``v90``,
  or by using the :generator:`NMake Makefiles` generator.

Platform Selection
^^^^^^^^^^^^^^^^^^

The default target platform name (architecture) is ``Win32``.

.. versionadded:: 3.1
  The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps
  via the :option:`cmake -A` option, to specify a target platform
  name (architecture).  For example:

  * ``cmake -G "Visual Studio 9 2008" -A Win32``
  * ``cmake -G "Visual Studio 9 2008" -A x64``
  * ``cmake -G "Visual Studio 9 2008" -A Itanium``
  * ``cmake -G "Visual Studio 9 2008" -A <WinCE-SDK>``
    (Specify a target platform matching a Windows CE SDK name.)

For compatibility with CMake versions prior to 3.1, one may specify
a target platform name optionally at the end of the generator name.
This is supported only for:

``Visual Studio 9 2008 Win64``
  Specify target platform ``x64``.

``Visual Studio 9 2008 IA64``
  Specify target platform ``Itanium``.

``Visual Studio 9 2008 <WinCE-SDK>``
  Specify target platform matching a Windows CE SDK name.

path: buildtools/windows/cmake/doc/cmake/html/_sources/generator/Visual Studio 9 2008.rst.txt


code:
Watcom WMake
------------

Generates Watcom WMake makefiles.


code:
Xcode
-----

Generate Xcode project files.

.. versionchanged:: 3.15
  This generator supports Xcode 5.0 and above.

.. _`Xcode Build System Selection`:

Toolset and Build System Selection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default Xcode is allowed to select its own default toolchain.
The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
via the :option:`cmake -T` option, to specify another toolset.

.. versionadded:: 3.19
  This generator supports toolset specification using one of these forms:

* ``toolset``
* ``toolset[,key=value]*``
* ``key=value[,key=value]*``

The ``toolset`` specifies the toolset name.  The selected toolset name
is provided in the :variable:`CMAKE_XCODE_PLATFORM_TOOLSET` variable.

The ``key=value`` pairs form a comma-separated list of options to
specify generator-specific details of the toolset selection.
Supported pairs are:

``buildsystem=<variant>``
  Specify the buildsystem variant to use.
  See the :variable:`CMAKE_XCODE_BUILD_SYSTEM` variable for allowed values.

  For example, to select the original build system under Xcode 12,
  run :manual:`cmake(1)` with the option :option:`-T buildsystem=1 <cmake -T>`.

Swift Support
^^^^^^^^^^^^^

.. versionadded:: 3.4

When using the ``Xcode`` generator with Xcode 6.1 or higher,
one may enable the ``Swift`` language with the :command:`enable_language`
command or the :command:`project`.

Limitations
^^^^^^^^^^^

The Xcode generator does not support per-configuration sources.
Code like the following will result in a generation error:

.. code-block:: cmake

  add_executable(MyApp mymain-$<CONFIG>.cpp)


code:
IDE Integration Guide
*********************

.. only:: html

  .. contents::

Introduction
============

Integrated development environments (IDEs) may want to integrate with CMake to
improve the development experience for CMake users. This document lays out the
recommended best practices for such integration.

Bundling
========

Many IDE vendors will want to bundle a copy of CMake with their IDE. IDEs that
bundle CMake should present the user with the option of using an external CMake
installation instead of the bundled one, in case the bundled copy becomes
outdated and the user wants to use a newer version.

While IDE vendors may be tempted to bundle different versions of CMake with
their application, such practice is not recommended. CMake has strong
guarantees of backwards compatibility, and there is no reason not to use a
newer version of CMake than what a project requires, or indeed, the very latest
version. Therefore, it is recommended that IDE vendors that bundle CMake with
their application always include the very latest patch version of CMake
available at the time of release.

As a suggestion, IDEs may also ship a copy of the Ninja buildsystem alongside
CMake. Ninja is highly performant and well-supported on all platforms that
support CMake. IDEs that bundle Ninja should use Ninja 1.10 or later, which
contains features needed to support Fortran builds.

Presets
=======

CMake supports a file format called ``CMakePresets.json``, and its
user-specific counterpart, ``CMakeUserPresets.json``. This file contains
information on the various configure presets that a user may want. Each preset
may have a different compiler, build flags, etc. The details of this format are
explained in the :manual:`cmake(1)` manual.

IDE vendors are encouraged to read and evaluate this file the same way CMake
does, and present the user with the presets listed in the file. Users should be
able to see (and possibly edit) the CMake cache variables, environment
variables, and command line options that are defined for a given preset. The
IDE should then construct the list of appropriate :manual:`cmake(1)` command
line arguments based on these settings, rather than using the
:option:`--preset= <cmake --preset>` option directly. The
:option:`--preset= <cmake --preset>` option is intended only as a convenient
frontend for command line users, and should not be used by the IDE.

For example, if a preset named ``ninja`` specifies ``Ninja`` as the generator
and ``${sourceDir}/build`` as the build directory, instead of running:

.. code-block:: console

  cmake -S /path/to/source --preset=ninja

the IDE should instead calculate the settings of the ``ninja`` preset, and then
run:

.. code-block:: console

  cmake -S /path/to/source -B /path/to/source/build -G Ninja

In cases where a preset contains lots of cache variables, and passing all of
them as :option:`-D <cmake -D>` flags would cause the command line length limit
of the platform to be exceeded, the IDE should instead construct a temporary
cache script and pass it with the :option:`-C <cmake -C>` flag.

While reading, parsing, and evaluating the contents of ``CMakePresets.json`` is
straightforward, it is not trivial. In addition to the documentation, IDE
vendors may also wish to refer to the CMake source code and test cases for a
better understanding of how to implement the format.
:download:`This file <../../manual/presets/schema.json>` provides a
machine-readable JSON schema for the ``CMakePresets.json`` format that IDE
vendors may find useful for validation and providing editing assistance.

Configuring
===========

IDEs that invoke :manual:`cmake(1)` to run the configure step may wish to
receive information about the artifacts that the build will produce, as well
as the include directories, compile definitions, etc. used to build the
artifacts. Such information can be obtained by using the
:manual:`File API <cmake-file-api(7)>`. The manual page for the File API
contains more information about the API and how to invoke it.
:manual:`Server mode <cmake-server(7)>` was removed as of CMake 3.20 and
should not be used on CMake 3.14 or later.

IDEs should avoid creating more build trees than necessary, and only create
multiple build trees if the user wishes to switch to a different compiler,
use different compile flags, etc. In particular, IDEs should NOT create
multiple single-config build trees which all have the same properties except
for a differing :variable:`CMAKE_BUILD_TYPE`, effectively creating a
multi-config environment. Instead, the :generator:`Ninja Multi-Config`
generator, in conjunction with the :manual:`File API <cmake-file-api(7)>` to
get the list of build configurations, should be used for this purpose.

IDEs should not use the "extra generators" with Makefile or Ninja generators,
which generate IDE project files in addition to the Makefile or Ninja files.
Instead the :manual:`File API <cmake-file-api(7)>` should be used to get the
list of build artifacts.

Building
========

If a Makefile or Ninja generator is used to generate the build tree, it is not
recommended to invoke ``make`` or ``ninja`` directly. Instead, it is
recommended that the IDE invoke :manual:`cmake(1)` with the
:option:`--build <cmake --build>` argument, which will in turn invoke the
appropriate build tool.

If an IDE project generator is used, such as :generator:`Xcode` or one of the
Visual Studio generators, and the IDE understands the project format used, the
IDE should read the project file and build it the same way it would otherwise.

The :manual:`File API <cmake-file-api(7)>` can be used to obtain a list of
build configurations from the build tree, and the IDE should present this list
to the user to select a build configuration.

Testing
=======

:manual:`ctest(1)` supports outputting a JSON format with information about the
available tests and test configurations. IDEs which want to run CTest should
obtain this information and use it to present the user with a list of tests.

IDEs should not invoke the ``test`` target of the generated buildsystem.
Instead, they should invoke :manual:`ctest(1)` directly.

IDEs with CMake integration
===========================

The following IDEs support CMake natively:

* `CLion`_
* `KDevelop`_
* `QtCreator`_
* `Vim`_ (via a plugin)
* `Visual Studio`_
* `VSCode`_ (via a plugin)

.. _CLion: https://www.jetbrains.com/clion/
.. _KDevelop: https://kdevelop.org/
.. _QtCreator: https://www.qt.io/product/development-tools
.. _Vim: https://www.vim.org/
.. _Visual Studio: https://visualstudio.microsoft.com/
.. _VSCode: https://code.visualstudio.com/

Additionally, CMake has builtin support for some IDEs:

* :ref:`IDE Build Tool Generators`:
  Generate IDE native build systems such as Visual Studio or Xcode.
* :ref:`Extra Generators`:
  Extend :ref:`Command-Line Build Tool Generators` to generate IDE
  project files that hook into the command-line build system.
  Superseded by the :manual:`File API <cmake-file-api(7)>`.


code:
Importing and Exporting Guide
*****************************

.. only:: html

   .. contents::

Introduction
============

In this guide, we will present the concept of :prop_tgt:`IMPORTED` targets
and demonstrate how to import existing executable or library files from disk
into a CMake project. We will then show how CMake supports exporting targets
from one CMake-based project and importing them into another. Finally, we
will demonstrate how to package a project with a configuration file to allow
for easy integration into other CMake projects. This guide and the complete
example source code can be found in the ``Help/guide/importing-exporting``
directory of the CMake source code tree.

Importing Targets
=================

:prop_tgt:`IMPORTED` targets are used to convert files outside of a CMake
project into logical targets inside of the project. :prop_tgt:`IMPORTED`
targets are created using the ``IMPORTED`` option of the
:command:`add_executable` and :command:`add_library` commands. No build
files are generated for :prop_tgt:`IMPORTED` targets. Once imported,
:prop_tgt:`IMPORTED` targets may be referenced like any other target within
the project and provide a convenient, flexible reference to outside
executables and libraries.

By default, the :prop_tgt:`IMPORTED` target name has scope in the directory in
which it is created and below. We can use the ``GLOBAL`` option to extended
visibility so that the target is accessible globally in the build system.

Details about the :prop_tgt:`IMPORTED` target are specified by setting
properties whose names begin in ``IMPORTED_`` and ``INTERFACE_``. For example,
:prop_tgt:`IMPORTED_LOCATION` contains the full path to the target on
disk.

Importing Executables
---------------------

To start, we will walk through a simple example that creates an
:prop_tgt:`IMPORTED` executable target and then references it from the
:command:`add_custom_command` command.

We'll need to do some setup to get started. We want to create an executable
that when run creates a basic ``main.cc`` file in the current directory. The
details of this project are not important. Navigate to
``Help/guide/importing-exporting/MyExe``, create a build directory, run
:manual:`cmake <cmake(1)>` and build and install the project.

.. code-block:: console

  $ cd Help/guide/importing-exporting/MyExe
  $ mkdir build
  $ cd build
  $ cmake ..
  $ cmake --build .
  $ cmake --install . --prefix <install location>
  $ <install location>/myexe
  $ ls
  [...] main.cc [...]

Now we can import this executable into another CMake project. The source code
for this section is available in ``Help/guide/importing-exporting/Importing``.
In the CMakeLists file, use the :command:`add_executable` command to create a
new target called ``myexe``. Use the ``IMPORTED`` option to tell CMake that
this target references an executable file located outside of the project. No
rules will be generated to build it and the :prop_tgt:`IMPORTED` target
property will be set  to ``true``.

.. literalinclude:: Importing/CMakeLists.txt
  :language: cmake
  :start-after: # Add executable
  :end-before: # Set imported location

Next, set the :prop_tgt:`IMPORTED_LOCATION` property of the target using
the :command:`set_property` command. This will tell CMake the location of the
target on disk. The location may need to be adjusted to the
``<install location>`` specified in the previous step.

.. literalinclude:: Importing/CMakeLists.txt
  :language: cmake
  :start-after: # Set imported location
  :end-before: # Add custom command

We can now reference this :prop_tgt:`IMPORTED` target just like any target
built within the project. In this instance, let's imagine that we want to use
the generated source file in our project. Use the :prop_tgt:`IMPORTED`
target in the :command:`add_custom_command` command:

.. literalinclude:: Importing/CMakeLists.txt
  :language: cmake
  :start-after: # Add custom command
  :end-before: # Use source file

As ``COMMAND`` specifies an executable target name, it will automatically be
replaced by the location of the executable given by the
:prop_tgt:`IMPORTED_LOCATION` property above.

Finally, use the output from :command:`add_custom_command`:

.. literalinclude:: Importing/CMakeLists.txt
  :language: cmake
  :start-after: # Use source file

Importing Libraries
-------------------

In a similar manner, libraries from other projects may be accessed through
:prop_tgt:`IMPORTED` targets.

Note: The full source code for the examples in this section is not provided
and is left as an exercise for the reader.

In the CMakeLists file, add an :prop_tgt:`IMPORTED` library and specify its
location on disk:

.. code-block:: cmake

  add_library(foo STATIC IMPORTED)
  set_property(TARGET foo PROPERTY
               IMPORTED_LOCATION "/path/to/libfoo.a")

Then use the :prop_tgt:`IMPORTED` library inside of our project:

.. code-block:: cmake

  add_executable(myexe src1.c src2.c)
  target_link_libraries(myexe PRIVATE foo)

On Windows, a .dll and its .lib import library may be imported together:

.. code-block:: cmake

  add_library(bar SHARED IMPORTED)
  set_property(TARGET bar PROPERTY
               IMPORTED_LOCATION "c:/path/to/bar.dll")
  set_property(TARGET bar PROPERTY
               IMPORTED_IMPLIB "c:/path/to/bar.lib")
  add_executable(myexe src1.c src2.c)
  target_link_libraries(myexe PRIVATE bar)

A library with multiple configurations may be imported with a single target:

.. code-block:: cmake

  find_library(math_REL NAMES m)
  find_library(math_DBG NAMES md)
  add_library(math STATIC IMPORTED GLOBAL)
  set_target_properties(math PROPERTIES
    IMPORTED_LOCATION "${math_REL}"
    IMPORTED_LOCATION_DEBUG "${math_DBG}"
    IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
  )
  add_executable(myexe src1.c src2.c)
  target_link_libraries(myexe PRIVATE math)

The generated build system will link ``myexe`` to ``m.lib`` when built in the
release configuration, and ``md.lib`` when built in the debug configuration.

Exporting Targets
=================

While :prop_tgt:`IMPORTED` targets on their own are useful, they still
require that the project that imports them knows the locations of the target
files on disk. The real power of :prop_tgt:`IMPORTED`  targets is when the
project providing the target files also provides a CMake file to help import
them. A project can be setup to produce the necessary information so that it
can easily be used by other CMake projects be it from a build directory, a
local install or when packaged.

In the remaining sections, we will walk through a set of example projects
step-by-step. The first project will create and install a library and
corresponding CMake configuration and package files. The second project will
use the generated package.

Let's start by looking at the ``MathFunctions`` project in the
``Help/guide/importing-exporting/MathFunctions`` directory. Here we have a
header file ``MathFunctions.h`` that declares a ``sqrt`` function:

.. literalinclude:: MathFunctions/MathFunctions.h
  :language: c++

And a corresponding source file ``MathFunctions.cxx``:

.. literalinclude:: MathFunctions/MathFunctions.cxx
  :language: c++

Don't worry too much about the specifics of the C++ files, they are just meant
to be a simple example that will compile and run on many build systems.

Now we can create a ``CMakeLists.txt`` file for the ``MathFunctions``
project. Start by specifying the :command:`cmake_minimum_required` version and
:command:`project` name:

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :end-before: # create library

The :module:`GNUInstallDirs` module is included in order to provide the
project with the flexibility to install into different platform layouts by
making the directories available as cache variables.

Create a library called ``MathFunctions`` with the :command:`add_library`
command:

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # create library
  :end-before: # add include directories

And then use the :command:`target_include_directories` command to specify the
include directories for the target:

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # add include directories
  :end-before: # install the target and create export-set

We need to tell CMake that we want to use different include directories
depending on if we're building the library or using it from an installed
location. If we don't do this, when CMake creates the export information it
will export a path that is specific to the current build directory
and will not be valid for other projects. We can use
:manual:`generator expressions <cmake-generator-expressions(7)>` to specify
that if we're building the library include the current source directory.
Otherwise, when installed, include the ``include`` directory. See the `Creating
Relocatable Packages`_ section for more details.

The :command:`install(TARGETS)` and :command:`install(EXPORT)` commands
work together to install both targets (a library in our case) and a CMake
file designed to make it easy to import the targets into another CMake project.

First, in the :command:`install(TARGETS)` command we will specify the target,
the ``EXPORT`` name and the destinations that tell CMake where to install the
targets.

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # install the target and create export-set
  :end-before: # install header file

Here, the ``EXPORT`` option tells CMake to create an export called
``MathFunctionsTargets``. The generated :prop_tgt:`IMPORTED` targets have
appropriate properties set to define their
:ref:`usage requirements <Target Usage Requirements>`, such as
:prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES`,
:prop_tgt:`INTERFACE_COMPILE_DEFINITIONS` and other relevant built-in
``INTERFACE_`` properties.  The ``INTERFACE`` variant of user-defined
properties listed in :prop_tgt:`COMPATIBLE_INTERFACE_STRING` and other
:ref:`Compatible Interface Properties` are also propagated to the
generated :prop_tgt:`IMPORTED` targets. For example, in this case, the
:prop_tgt:`IMPORTED` target will have its
:prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` property populated with
the directory specified by the ``INCLUDES DESTINATION`` property. As a
relative path was given, it is treated as relative to the
:variable:`CMAKE_INSTALL_PREFIX`.

Note, we have *not* asked CMake to install the export yet.

We don't want to forget to install the ``MathFunctions.h`` header file with the
:command:`install(FILES)` command. The header file should be installed to the
``include`` directory, as specified by the
:command:`target_include_directories` command above.

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # install header file
  :end-before: # generate and install export file

Now that the ``MathFunctions`` library and header file are installed, we also
need to explicitly install the ``MathFunctionsTargets``  export details. Use
the :command:`install(EXPORT)` command to export the targets in
``MathFunctionsTargets``, as defined by the  :command:`install(TARGETS)`
command.

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # generate and install export file
  :end-before: # include CMakePackageConfigHelpers macro

This command generates the ``MathFunctionsTargets.cmake`` file and arranges
to install it to ``${CMAKE_INSTALL_LIBDIR}/cmake/MathFunctions``. The file
contains code suitable for use by downstreams to import all targets listed in
the install command from the installation tree.

The ``NAMESPACE`` option will prepend ``MathFunctions::`` to  the target names
as they are written to the export file. This convention of double-colons
gives CMake a hint that the name is an  :prop_tgt:`IMPORTED` target when it
is used by downstream projects. This way, CMake can issue a diagnostic
message if the package providing it was not found.

The generated export file contains code that creates an :prop_tgt:`IMPORTED` library.

.. code-block:: cmake

  # Create imported target MathFunctions::MathFunctions
  add_library(MathFunctions::MathFunctions STATIC IMPORTED)

  set_target_properties(MathFunctions::MathFunctions PROPERTIES
    INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
  )

This code is very similar to the example we created by hand in the
`Importing Libraries`_ section. Note that ``${_IMPORT_PREFIX}`` is computed
relative to the file location.

An outside project may load this file with the :command:`include` command and
reference the ``MathFunctions`` library from the installation tree as if it
were built in its own tree. For example:

.. code-block:: cmake
  :linenos:

   include(GNUInstallDirs)
   include(${INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/cmake/MathFunctions/MathFunctionTargets.cmake)
   add_executable(myexe src1.c src2.c )
   target_link_libraries(myexe PRIVATE MathFunctions::MathFunctions)

Line 2 loads the target CMake file. Although we only exported a single
target, this file may import any number of targets. Their locations are
computed relative to the file location so that the install tree may be
easily moved. Line 4 references the imported ``MathFunctions`` library. The
resulting build system will link to the library from its installed location.

Executables may also be exported and imported using the same process.

Any number of target installations may be associated with the same
export name. Export names are considered global so any directory may
contribute a target installation. The :command:`install(EXPORT)` command only
needs to be called once to install a file that references all targets. Below
is an example of how multiple exports may be combined into a single
export file, even if they are in different subdirectories of the project.

.. code-block:: cmake

  # A/CMakeLists.txt
  add_executable(myexe src1.c)
  install(TARGETS myexe DESTINATION lib/myproj
          EXPORT myproj-targets)

  # B/CMakeLists.txt
  add_library(foo STATIC foo1.c)
  install(TARGETS foo DESTINATION lib EXPORTS myproj-targets)

  # Top CMakeLists.txt
  add_subdirectory (A)
  add_subdirectory (B)
  install(EXPORT myproj-targets DESTINATION lib/myproj)

Creating Packages
-----------------

At this point, the ``MathFunctions`` project is exporting the target
information required to be used by other projects. We can make this project
even easier for other projects to use by generating a configuration file so
that the CMake :command:`find_package` command can find our project.

To start, we will need to make a few additions to the ``CMakeLists.txt``
file. First, include the :module:`CMakePackageConfigHelpers` module to get
access to some helper functions for creating config files.

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # include CMakePackageConfigHelpers macro
  :end-before: # set version

Then we will create a package configuration file and a package version file.

Creating a Package Configuration File
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Use the :command:`configure_package_config_file` command provided by the
:module:`CMakePackageConfigHelpers` to generate the package configuration
file. Note that this command should be used instead of the plain
:command:`configure_file` command. It helps to ensure that the resulting
package is relocatable by avoiding hardcoded paths in the installed
configuration file. The path given to ``INSTALL_DESTINATION`` must  be the
destination where the ``MathFunctionsConfig.cmake`` file will be installed.
We will examine the contents of the package configuration file in the next
section.

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # create config file
  :end-before: # install config files

Install the generated configuration files with the :command:`INSTALL(files)`
command. Both ``MathFunctionsConfigVersion.cmake`` and
``MathFunctionsConfig.cmake`` are installed to the same location, completing
the package.

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # install config files
  :end-before: # generate the export targets for the build tree

Now we need to create the package configuration file itself. In this case, the
``Config.cmake.in`` file is very simple but sufficient to allow downstreams
to use the :prop_tgt:`IMPORTED` targets.

.. literalinclude:: MathFunctions/Config.cmake.in

The first line of the file contains only the string ``@PACKAGE_INIT@``. This
expands when the file is configured and allows the use of relocatable paths
prefixed with ``PACKAGE_``. It also provides the ``set_and_check()`` and
``check_required_components()`` macros.

The ``check_required_components`` helper macro ensures that all requested,
non-optional components have been found by checking the
``<Package>_<Component>_FOUND`` variables for all required components. This
macro should be called at the end of the package configuration file even if the
package does not have any components. This way, CMake can make sure that the
downstream project hasn't specified any non-existent components. If
``check_required_components`` fails, the ``<Package>_FOUND`` variable is set to
FALSE, and the package is considered to be not found.

The ``set_and_check()`` macro should be used in configuration files instead
of the normal ``set()`` command for setting directories and file locations.
If a referenced file or directory does not exist, the macro will fail.

If any macros should be provided by the ``MathFunctions`` package, they should
be in a separate file which is installed to the same location as the
``MathFunctionsConfig.cmake`` file, and included from there.

**All required dependencies of a package must also be found in the package
configuration file.** Let's imagine that we require the ``Stats`` library in
our project. In the CMakeLists file, we would add:

.. code-block:: cmake

  find_package(Stats 2.6.4 REQUIRED)
  target_link_libraries(MathFunctions PUBLIC Stats::Types)

As the ``Stats::Types`` target is a ``PUBLIC`` dependency of ``MathFunctions``,
downstreams must also find the ``Stats`` package and link to the
``Stats::Types`` library.  The ``Stats`` package should be found in the
configuration file to ensure this.

.. code-block:: cmake

  include(CMakeFindDependencyMacro)
  find_dependency(Stats 2.6.4)

The ``find_dependency`` macro from the :module:`CMakeFindDependencyMacro`
module helps by propagating  whether the package is ``REQUIRED``, or
``QUIET``, etc. The ``find_dependency`` macro also sets
``MathFunctions_FOUND`` to ``False`` if the dependency is not found, along
with a diagnostic that the ``MathFunctions`` package cannot be used without
the ``Stats`` package.

**Exercise:** Add a required library to the ``MathFunctions`` project.

Creating a Package Version File
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The :module:`CMakePackageConfigHelpers` module provides the
:command:`write_basic_package_version_file` command for creating a simple
package version file.  This file is read by CMake when :command:`find_package`
is called to determine the compatibility with the requested version, and to set
some version-specific variables such as ``<PackageName>_VERSION``,
``<PackageName>_VERSION_MAJOR``, ``<PackageName>_VERSION_MINOR``, etc. See
:manual:`cmake-packages <cmake-packages(7)>` documentation for more details.

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # set version
  :end-before: # create config file

In our example, ``MathFunctions_MAJOR_VERSION`` is defined as a
:prop_tgt:`COMPATIBLE_INTERFACE_STRING` which means that it must be
compatible among the dependencies of any depender. By setting this
custom defined user property in this version and in the next version of
``MathFunctions``, :manual:`cmake <cmake(1)>` will issue a diagnostic if
there is an attempt to use version 3 together with version 4.  Packages can
choose to employ such a pattern if different major versions of the package
are designed to be incompatible.

Exporting Targets from the Build Tree
-------------------------------------

Typically, projects are built and installed before being used by an outside
project. However, in some cases, it is desirable to export targets directly
from a build tree. The targets may then be used by an outside project that
references the build tree with no installation involved. The :command:`export`
command is used to generate a file exporting targets from a project build tree.

If we want our example project to also be used from a build directory we only
have to add the following to ``CMakeLists.txt``:

.. literalinclude:: MathFunctions/CMakeLists.txt
  :language: cmake
  :start-after: # generate the export targets for the build tree

Here we use the :command:`export` command to generate the export targets for
the build tree. In this case, we'll create a file called
``MathFunctionsTargets.cmake`` in the ``cmake`` subdirectory of the build
directory. The generated file contains the required code to import the target
and may be loaded by an outside project that is aware of the project build
tree. This file is specific to the build-tree, and **is not relocatable**.

It is possible to create a suitable package configuration file and package
version file to define a package for the build tree which may be used without
installation.  Consumers of the build tree can simply ensure that the
:variable:`CMAKE_PREFIX_PATH` contains the build directory, or set the
``MathFunctions_DIR`` to ``<build_dir>/MathFunctions`` in the cache.

An example application of this feature is for building an executable on a host
platform when cross-compiling. The project containing the executable may be
built on the host platform and then the project that is being cross-compiled
for another platform may load it.

Building and Installing a Package
---------------------------------

At this point, we have generated a relocatable CMake configuration for our
project that can be used after the project has been installed. Let's try to
build the ``MathFunctions`` project:

.. code-block:: console

  mkdir MathFunctions_build
  cd MathFunctions_build
  cmake ../MathFunctions
  cmake --build .

In the build directory, notice that the file ``MathFunctionsTargets.cmake``
has been created in the ``cmake`` subdirectory.

Now install the project:

.. code-block:: console

    $ cmake --install . --prefix "/home/myuser/installdir"

Creating Relocatable Packages
=============================

Packages created by :command:`install(EXPORT)` are designed to be relocatable,
using paths relative to the location of the package itself. They must not
reference absolute paths of files on the machine where the package is built
that will not exist on the machines where the package may be installed.

When defining the interface of a target for ``EXPORT``, keep in mind that the
include directories should be specified as relative paths to the
:variable:`CMAKE_INSTALL_PREFIX` but should not explicitly include the
:variable:`CMAKE_INSTALL_PREFIX`:

.. code-block:: cmake

  target_include_directories(tgt INTERFACE
    # Wrong, not relocatable:
    $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include/TgtName>
  )

  target_include_directories(tgt INTERFACE
    # Ok, relocatable:
    $<INSTALL_INTERFACE:include/TgtName>
  )

The :genex:`$<INSTALL_PREFIX>` generator expression may be used as
a placeholder for the install prefix without resulting in a non-relocatable
package.  This is necessary if complex generator expressions are used:

.. code-block:: cmake

  target_include_directories(tgt INTERFACE
    # Ok, relocatable:
    $<INSTALL_INTERFACE:$<INSTALL_PREFIX>/include/TgtName>
  )

This also applies to paths referencing external dependencies.
It is not advisable to populate any properties which may contain
paths, such as :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` or
:prop_tgt:`INTERFACE_LINK_LIBRARIES`, with paths relevant to dependencies.
For example, this code may not work well for a relocatable package:

.. code-block:: cmake

  target_link_libraries(MathFunctions INTERFACE
    ${Foo_LIBRARIES} ${Bar_LIBRARIES}
    )
  target_include_directories(MathFunctions INTERFACE
    "$<INSTALL_INTERFACE:${Foo_INCLUDE_DIRS};${Bar_INCLUDE_DIRS}>"
    )

The referenced variables may contain the absolute paths to libraries
and include directories **as found on the machine the package was made on**.
This would create a package with hard-coded paths to dependencies not
suitable for relocation.

Ideally such dependencies should be used through their own
:ref:`IMPORTED targets <Imported Targets>` that have their own
:prop_tgt:`IMPORTED_LOCATION` and usage requirement properties
such as :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` populated
appropriately.  Those imported targets may then be used with
the :command:`target_link_libraries` command for ``MathFunctions``:

.. code-block:: cmake

  target_link_libraries(MathFunctions INTERFACE Foo::Foo Bar::Bar)

With this approach the package references its external dependencies
only through the names of :ref:`IMPORTED targets <Imported Targets>`.
When a consumer uses the installed package, the consumer will run the
appropriate :command:`find_package` commands (via the ``find_dependency``
macro described above) to find the dependencies and populate the
imported targets with appropriate paths on their own machine.

Using the Package Configuration File
====================================

Now we're ready to create a project to use the installed ``MathFunctions``
library. In this section we will be using source code from
``Help\guide\importing-exporting\Downstream``. In this directory, there is a
source file called ``main.cc`` that uses the ``MathFunctions`` library to
calculate the square root of a given number and then prints the results:

.. literalinclude:: Downstream/main.cc
  :language: c++

As before, we'll start with the :command:`cmake_minimum_required` and
:command:`project` commands in the ``CMakeLists.txt`` file. For this project,
we'll also specify the C++ standard.

.. literalinclude:: Downstream/CMakeLists.txt
  :language: cmake
  :end-before: # find MathFunctions

We can use the :command:`find_package` command:

.. literalinclude:: Downstream/CMakeLists.txt
  :language: cmake
  :start-after: # find MathFunctions
  :end-before: # create executable

Create an executable:

.. literalinclude:: Downstream/CMakeLists.txt
  :language: cmake
  :start-after: # create executable
  :end-before: # use MathFunctions library

And link to the ``MathFunctions`` library:

.. literalinclude:: Downstream/CMakeLists.txt
  :language: cmake
  :start-after: # use MathFunctions library

That's it! Now let's try to build the ``Downstream`` project.

.. code-block:: console

  mkdir Downstream_build
  cd Downstream_build
  cmake ../Downstream
  cmake --build .

A warning may have appeared during CMake configuration:

.. code-block:: console

  CMake Warning at CMakeLists.txt:4 (find_package):
    By not providing "FindMathFunctions.cmake" in CMAKE_MODULE_PATH this
    project has asked CMake to find a package configuration file provided by
    "MathFunctions", but CMake did not find one.

    Could not find a package configuration file provided by "MathFunctions"
    with any of the following names:

      MathFunctionsConfig.cmake
      mathfunctions-config.cmake

    Add the installation prefix of "MathFunctions" to CMAKE_PREFIX_PATH or set
    "MathFunctions_DIR" to a directory containing one of the above files.  If
    "MathFunctions" provides a separate development package or SDK, be sure it
    has been installed.

Set the ``CMAKE_PREFIX_PATH`` to where MathFunctions was installed previously
and try again. Ensure that the newly created executable runs as expected.

Adding Components
=================

Let's edit the ``MathFunctions`` project to use components. The source code for
this section can be found in
``Help\guide\importing-exporting\MathFunctionsComponents``. The CMakeLists file
for this project adds two subdirectories: ``Addition`` and ``SquareRoot``.

.. literalinclude:: MathFunctionsComponents/CMakeLists.txt
  :language: cmake
  :end-before: # include CMakePackageConfigHelpers macro

Generate and install the package configuration and package version files:

.. literalinclude:: MathFunctionsComponents/CMakeLists.txt
  :language: cmake
  :start-after: # include CMakePackageConfigHelpers macro

If ``COMPONENTS`` are specified when the downstream uses
:command:`find_package`, they are listed in the
``<PackageName>_FIND_COMPONENTS`` variable. We can use this variable to verify
that all necessary component targets are included in ``Config.cmake.in``. At
the same time, this function will act as a custom ``check_required_components``
macro to ensure that the downstream only attempts to use supported components.

.. literalinclude:: MathFunctionsComponents/Config.cmake.in

Here, the ``MathFunctions_NOT_FOUND_MESSAGE`` is set to a diagnosis that the
package could not be found because an invalid component was specified. This
message variable can be set for any case where the ``_FOUND`` variable is set
to ``False``, and will be displayed to the user.

The ``Addition`` and ``SquareRoot`` directories are similar. Let's look at one
of the CMakeLists files:

.. literalinclude:: MathFunctionsComponents/SquareRoot/CMakeLists.txt
  :language: cmake

Now we can build the project as described in earlier sections. To test using
this package, we can use the project in
``Help\guide\importing-exporting\DownstreamComponents``. There's two
differences from the previous ``Downstream`` project. First, we need to find
the package components. Change the ``find_package`` line from:

.. literalinclude:: Downstream/CMakeLists.txt
  :language: cmake
  :start-after: # find MathFunctions
  :end-before: # create executable

To:

.. literalinclude:: DownstreamComponents/CMakeLists.txt
  :language: cmake
  :start-after: # find MathFunctions
  :end-before: # create executable

and the ``target_link_libraries`` line from:

.. literalinclude:: Downstream/CMakeLists.txt
  :language: cmake
  :start-after: # use MathFunctions library

To:

.. literalinclude:: DownstreamComponents/CMakeLists.txt
  :language: cmake
  :start-after: # use MathFunctions library
  :end-before: # Workaround for GCC on AIX to avoid -isystem

In ``main.cc``, replace ``#include MathFunctions.h`` with:

.. literalinclude:: DownstreamComponents/main.cc
  :language: c
  :start-after: #include <string>
  :end-before: int main

Finally, use the ``Addition`` library:

.. literalinclude:: DownstreamComponents/main.cc
  :language: c
  :start-after: // calculate sum
  :end-before: return 0;

Build the ``Downstream`` project and confirm that it can find and use the
package components.


code:
Step 1: A Basic Starting Point
==============================

Where do I start with CMake? This step will provide an introduction to some of
CMake's basic syntax, commands, and variables. As these concepts are
introduced, we will work through three exercises and create a simple CMake
project.

Each exercise in this step will start with some background information. Then, a
goal and list of helpful resources are provided. Each file in the
``Files to Edit`` section is in the ``Step1`` directory and contains one or
more ``TODO`` comments. Each ``TODO`` represents a line or two of code to
change or add. The ``TODO`` s are intended to be completed in numerical order,
first complete  ``TODO 1`` then ``TODO 2``, etc. The ``Getting Started``
section will give some helpful hints and guide you through the exercise. Then
the ``Build and Run`` section will walk step-by-step through how to build and
test the exercise. Finally, at the end of each exercise the intended solution
is discussed.

Also note that each step in the tutorial builds on the next. So, for example,
the starting code for ``Step2`` is the complete solution to ``Step1``.

Exercise 1 - Building a Basic Project
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The most basic CMake project is an executable built from a single source code
file. For simple projects like this, a ``CMakeLists.txt`` file with three
commands is all that is required.

**Note:** Although upper, lower and mixed case commands are supported by CMake,
lower case commands are preferred and will be used throughout the tutorial.

Any project's top most CMakeLists.txt must start by specifying a minimum CMake
version using the :command:`cmake_minimum_required` command. This establishes
policy settings and ensures that the following CMake functions are run with a
compatible version of CMake.

To start a project, we use the :command:`project` command to set the project
name. This call is required with every project and should be called soon after
:command:`cmake_minimum_required`. As we will see later, this command can
also be used to specify other project level information such as the language
or version number.

Finally, the :command:`add_executable` command tells CMake to create an
executable using the specified source code files.

Goal
----

Understand how to create a simple CMake project.

Helpful Resources
-----------------

* :command:`add_executable`
* :command:`cmake_minimum_required`
* :command:`project`

Files to Edit
-------------

* ``CMakeLists.txt``

Getting Started
----------------

The source code for ``tutorial.cxx`` is provided in the
``Help/guide/tutorial/Step1`` directory and can be used to compute the square
root of a number. This file does not need to be edited in this step.

In the same directory is a ``CMakeLists.txt`` file which you will complete.
Start with ``TODO 1`` and work through ``TODO 3``.

Build and Run
-------------

Once ``TODO 1`` through ``TODO 3`` have been completed, we are ready to build
and run our project! First, run the :manual:`cmake <cmake(1)>` executable or the
:manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
with your chosen build tool.

For example, from the command line we could navigate to the
``Help/guide/tutorial`` directory of the CMake source code tree and create a
build directory:

.. code-block:: console

  mkdir Step1_build

Next, navigate to that build directory and run
:manual:`cmake <cmake(1)>` to configure the project and generate a native build
system:

.. code-block:: console

  cd Step1_build
  cmake ../Step1

Then call that build system to actually compile/link the project:

.. code-block:: console

  cmake --build .

For multi-config generators (e.g. Visual Studio), first navigate to the
appropriate subdirectory, for example:

.. code-block:: console

  cd Debug

Finally, try to use the newly built ``Tutorial``:

.. code-block:: console

  Tutorial 4294967296
  Tutorial 10
  Tutorial

**Note:** Depending on the shell, the correct syntax may be ``Tutorial``,
``./Tutorial`` or ``.\Tutorial``. For simplicity, the exercises will use
``Tutorial`` throughout.

Solution
--------

As mentioned above, a three line ``CMakeLists.txt`` is all that we need to get
up and running. The first line is to use :command:`cmake_minimum_required` to
set the CMake version as follows:

.. raw:: html

  TODO 1: Click to show/hide answer

.. literalinclude:: Step2/CMakeLists.txt
  :caption: TODO 1: CMakeLists.txt
  :name: CMakeLists.txt-cmake_minimum_required
  :language: cmake
  :end-before: # set the project name and version

.. raw:: html

The next step to make a basic project is to use the :command:`project`
command as follows to set the project name:

.. raw:: html

  TODO 2: Click to show/hide answer

.. code-block:: cmake
  :caption: TODO 2: CMakeLists.txt
  :name: CMakeLists.txt-project

  project(Tutorial)

.. raw:: html

The last command to call for a basic project is
:command:`add_executable`. We call it as follows:

.. raw:: html

  TODO 3: Click to show/hide answer

.. literalinclude:: Step2/CMakeLists.txt
  :caption: TODO 3: CMakeLists.txt
  :name: CMakeLists.txt-add_executable
  :language: cmake
  :start-after: # add the executable
  :end-before: # TODO 3:

.. raw:: html

Exercise 2 - Specifying the C++ Standard
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

CMake has some special variables that are either created behind the scenes or
have meaning to CMake when set by project code. Many of these variables start
with ``CMAKE_``. Avoid this naming convention when creating variables for your
projects. Two of these special user settable variables are
:variable:`CMAKE_CXX_STANDARD` and :variable:`CMAKE_CXX_STANDARD_REQUIRED`.
These may be used together to specify the C++ standard needed to build the
project.

Goal
----

Add a feature that requires C++11.

Helpful Resources
-----------------

* :variable:`CMAKE_CXX_STANDARD`
* :variable:`CMAKE_CXX_STANDARD_REQUIRED`
* :command:`set`

Files to Edit
-------------

* ``CMakeLists.txt``
* ``tutorial.cxx``

Getting Started
---------------

Continue editing files in the ``Step1`` directory. Start with ``TODO 4`` and
complete through ``TODO 6``.

First, edit ``tutorial.cxx`` by adding a feature that requires C++11. Then
update ``CMakeLists.txt`` to require C++11.

Build and Run
-------------

Let's build our project again. Since we already created a build directory and
ran CMake for Exercise 1, we can skip to the build step:

.. code-block:: console

  cd Step1_build
  cmake --build .

Now we can try to use the newly built ``Tutorial`` with same commands as
before:

.. code-block:: console

  Tutorial 4294967296
  Tutorial 10
  Tutorial

Solution
--------

We start by adding some C++11 features to our project by replacing
``atof`` with ``std::stod`` in ``tutorial.cxx``. This looks like
the following:

.. raw:: html

  TODO 4: Click to show/hide answer

.. literalinclude:: Step2/tutorial.cxx
  :caption: TODO 4: tutorial.cxx
  :name: tutorial.cxx-cxx11
  :language: c++
  :start-after: // convert input to double
  :end-before: // TODO 6:

.. raw:: html

To complete ``TODO 5``, simply remove ``#include <cstdlib>``.

We will need to explicitly state in the CMake code that it should use the
correct flags. One way to enable support for a specific C++ standard in CMake
is by using the :variable:`CMAKE_CXX_STANDARD` variable. For this tutorial, set
the :variable:`CMAKE_CXX_STANDARD` variable in the ``CMakeLists.txt`` file to
``11`` and :variable:`CMAKE_CXX_STANDARD_REQUIRED` to ``True``. Make sure to
add the :variable:`CMAKE_CXX_STANDARD` declarations above the call to
:command:`add_executable`.

.. raw:: html

  TODO 6: Click to show/hide answer

.. literalinclude:: Step2/CMakeLists.txt
  :caption: TODO 6: CMakeLists.txt
  :name: CMakeLists.txt-CXX_STANDARD
  :language: cmake
  :start-after: # specify the C++ standard
  :end-before: # configure a header file

.. raw:: html

Exercise 3 - Adding a Version Number and Configured Header File
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Sometimes it may be useful to have a variable that is defined in your
``CMakelists.txt`` file also be available in your source code. In this case, we
would like to print the project version.

One way to accomplish this is by using a configured header file. We create an
input file with one or more variables to replace. These variables have special
syntax which looks like ``@VAR@``.
Then, we use the :command:`configure_file` command to copy the input file to a
given output file and replace these variables with the current value of ``VAR``
in the ``CMakelists.txt`` file.

While we could edit the version directly in the source code, using this
feature is preferred since it creates a single source of truth and avoids
duplication.

Goal
----

Define and report the project's version number.

Helpful Resources
-----------------

* :variable:`<PROJECT-NAME>_VERSION_MAJOR`
* :variable:`<PROJECT-NAME>_VERSION_MINOR`
* :command:`configure_file`
* :command:`target_include_directories`

Files to Edit
-------------

* ``CMakeLists.txt``
* ``tutorial.cxx``

Getting Started
---------------

Continue to edit files from ``Step1``. Start on ``TODO 7`` and complete through
``TODO 12``. In this exercise, we start by adding a project version number in
``CMakeLists.txt``. In that same file, use :command:`configure_file` to copy a
given input file to an output file and substitute some variable values in the
input file content.

Next, create an input header file ``TutorialConfig.h.in`` defining version
numbers which will accept variables passed from :command:`configure_file`.

Finally, update ``tutorial.cxx`` to print out its version number.

Build and Run
-------------

Let's build our project again. As before, we already created a build directory
and ran CMake so we can skip to the build step:

.. code-block:: console

  cd Step1_build
  cmake --build .

Verify that the version number is now reported when running the executable
without any arguments.

Solution
--------

In this exercise, we improve our executable by printing a version number.
While we could do this exclusively in the source code, using ``CMakeLists.txt``
lets us maintain a single source of data for the version number.

First, we modify the ``CMakeLists.txt`` file to use the
:command:`project` command to set both the project name and version number.
When the :command:`project` command is called, CMake defines
``Tutorial_VERSION_MAJOR`` and ``Tutorial_VERSION_MINOR`` behind the scenes.

.. raw:: html

  TODO 7: Click to show/hide answer

.. literalinclude:: Step2/CMakeLists.txt
  :caption: TODO 7: CMakeLists.txt
  :name: CMakeLists.txt-project-VERSION
  :language: cmake
  :start-after: # set the project name and version
  :end-before: # specify the C++ standard

.. raw:: html

Then we used :command:`configure_file` to copy the input file with the
specified CMake variables replaced:

.. raw:: html

  TODO 8: Click to show/hide answer

.. literalinclude:: Step2/CMakeLists.txt
  :caption: TODO 8: CMakeLists.txt
  :name: CMakeLists.txt-configure_file
  :language: cmake
  :start-after: # to the source code
  :end-before: # TODO 2:

.. raw:: html

Since the configured file will be written into the project binary
directory, we must add that directory to the list of paths to search for
include files.

**Note:** Throughout this tutorial, we will refer to the project build and
the project binary directory interchangeably. These are the same and are not
meant to refer to a `bin/` directory.

We used :command:`target_include_directories` to specify
where the executable target should look for include files.

.. raw:: html

  TODO 9: Click to show/hide answer

.. literalinclude:: Step2/CMakeLists.txt
  :caption: TODO 9: CMakeLists.txt
  :name: CMakeLists.txt-target_include_directories
  :language: cmake
  :start-after: # so that we will find TutorialConfig.h

.. raw:: html

``TutorialConfig.h.in`` is the input header file to be configured.
When :command:`configure_file` is called from our ``CMakeLists.txt``, the
values for ``@Tutorial_VERSION_MAJOR@`` and ``@Tutorial_VERSION_MINOR@`` will
be replaced with the corresponding version numbers from the project in
``TutorialConfig.h``.

.. raw:: html

  TODO 10: Click to show/hide answer

.. literalinclude:: Step2/TutorialConfig.h.in
  :caption: TODO 10: TutorialConfig.h.in
  :name: TutorialConfig.h.in
  :language: c++

.. raw:: html

Next, we need to modify ``tutorial.cxx`` to include the configured header file,
``TutorialConfig.h``.

.. raw:: html

  TODO 11: Click to show/hide answer

.. code-block:: c++
  :caption: TODO 11: tutorial.cxx

  #include "TutorialConfig.h"

.. raw:: html

Finally, we print out the executable name and version number by updating
``tutorial.cxx`` as follows:

.. raw:: html

  TODO 12: Click to show/hide answer

.. literalinclude:: Step2/tutorial.cxx
  :caption: TODO 12 : tutorial.cxx
  :name: tutorial.cxx-print-version
  :language: c++
  :start-after: {
  :end-before: // convert input to double

.. raw:: html

path: buildtools/windows/cmake/doc/cmake/html/_sources/guide/tutorial/A Basic Starting Point.rst.txt


code:
Step 11: Adding Export Configuration
====================================

During :guide:`tutorial/Installing and Testing` of the tutorial we added the
ability for CMake to install the library and headers of the project. During
:guide:`tutorial/Packaging an Installer` we added the ability to package up
this information so it could be distributed to other people.

The next step is to add the necessary information so that other CMake projects
can use our project, be it from a build directory, a local install or when
packaged.

The first step is to update our :command:`install(TARGETS)` commands to not
only specify a ``DESTINATION`` but also an ``EXPORT``. The ``EXPORT`` keyword
generates a CMake file containing code to import all targets listed in the
install command from the installation tree. So let's go ahead and explicitly
``EXPORT`` the ``MathFunctions`` library by updating the ``install`` command
in ``MathFunctions/CMakeLists.txt`` to look like:

.. literalinclude:: Complete/MathFunctions/CMakeLists.txt
  :caption: MathFunctions/CMakeLists.txt
  :name: MathFunctions/CMakeLists.txt-install-TARGETS-EXPORT
  :language: cmake
  :start-after: # install libs

Now that we have ``MathFunctions`` being exported, we also need to explicitly
install the generated ``MathFunctionsTargets.cmake`` file. This is done by
adding the following to the bottom of the top-level ``CMakeLists.txt``:

.. literalinclude:: Complete/CMakeLists.txt
  :caption: CMakeLists.txt
  :name: CMakeLists.txt-install-EXPORT
  :language: cmake
  :start-after: # install the configuration targets
  :end-before: include(CMakePackageConfigHelpers)

At this point you should try and run CMake. If everything is setup properly
you will see that CMake will generate an error that looks like:

.. code-block:: console

  Target "MathFunctions" INTERFACE_INCLUDE_DIRECTORIES property contains
  path:

    "/Users/robert/Documents/CMakeClass/Tutorial/Step11/MathFunctions"

  which is prefixed in the source directory.

What CMake is trying to say is that during generating the export information
it will export a path that is intrinsically tied to the current machine and
will not be valid on other machines. The solution to this is to update the
``MathFunctions`` :command:`target_include_directories` to understand that it
needs different ``INTERFACE`` locations when being used from within the build
directory and from an install / package. This means converting the
:command:`target_include_directories` call for ``MathFunctions`` to look like:

.. literalinclude:: Step12/MathFunctions/CMakeLists.txt
  :caption: MathFunctions/CMakeLists.txt
  :name: MathFunctions/CMakeLists.txt-target_include_directories
  :language: cmake
  :start-after: # to find MathFunctions.h, while we don't.
  :end-before: # should we use our own math functions

Once this has been updated, we can re-run CMake and verify that it doesn't
warn anymore.

At this point, we have CMake properly packaging the target information that is
required but we will still need to generate a ``MathFunctionsConfig.cmake`` so
that the CMake :command:`find_package` command can find our project. So let's go
ahead and add a new file to the top-level of the project called
``Config.cmake.in`` with the following contents:

.. literalinclude:: Step12/Config.cmake.in
  :caption: Config.cmake.in
  :name: Config.cmake.in

Then, to properly configure and install that file, add the following to the
bottom of the top-level ``CMakeLists.txt``:

.. literalinclude:: Step12/CMakeLists.txt
  :caption: CMakeLists.txt
  :name: CMakeLists.txt-install-Config.cmake
  :language: cmake
  :start-after: # install the configuration targets
  :end-before: # generate the config file

Next, we execute the :command:`configure_package_config_file`.  This command
will configure a provided file but with a few specific differences from the
standard :command:`configure_file` way.
To properly utilize this function, the input file should have a single line
with the text ``@PACKAGE_INIT@`` in addition to the content that is desired.
That variable will be replaced with a block of code which turns set values into
relative paths.  These values which are new can be referenced by the same name
but prepended with a ``PACKAGE_`` prefix.

.. literalinclude:: Step12/CMakeLists.txt
  :caption: CMakeLists.txt
  :name: CMakeLists.txt-configure-package-config.cmake
  :language: cmake
  :start-after: # install the configuration targets
  :end-before: # generate the version file

The :command:`write_basic_package_version_file` is next.  This command writes
a file which is used by :command:`find_package`, documenting the version and
compatibility of the desired package.  Here, we use the ``Tutorial_VERSION_*``
variables and say that it is compatible with ``AnyNewerVersion``, which
denotes that this version or any higher one are compatible with the requested
version.

.. literalinclude:: Step12/CMakeLists.txt
  :caption: CMakeLists.txt
  :name: CMakeLists.txt-basic-version-file.cmake
  :language: cmake
  :start-after: # generate the version file
  :end-before: # install the generated configuration files

Finally, set both generated files to be installed:

.. literalinclude:: Step12/CMakeLists.txt
  :caption: CMakeLists.txt
  :name: CMakeLists.txt-install-configured-files.cmake
  :language: cmake
  :start-after: # install the generated configuration files
  :end-before: # generate the export

At this point, we have generated a relocatable CMake Configuration for our
project that can be used after the project has been installed or packaged. If
we want our project to also be used from a build directory we only have to add
the following to the bottom of the top level ``CMakeLists.txt``:

.. literalinclude:: Step12/CMakeLists.txt
  :caption: CMakeLists.txt
  :name: CMakeLists.txt-export
  :language: cmake
  :start-after: # needs to be after the install(TARGETS) command

With this export call we now generate a ``MathFunctionsTargets.cmake``, allowing the
configured ``MathFunctionsConfig.cmake`` in the build directory to be used by
other projects, without needing it to be installed.


code:
Step 4: Adding Generator Expressions
=====================================

:manual:`Generator expressions <cmake-generator-expressions(7)>` are evaluated
during build system generation to produce information specific to each build
configuration.

:manual:`Generator expressions <cmake-generator-expressions(7)>` are allowed in
the context of many target properties, such as :prop_tgt:`LINK_LIBRARIES`,
:prop_tgt:`INCLUDE_DIRECTORIES`, :prop_tgt:`COMPILE_DEFINITIONS` and others.
They may also be used when using commands to populate those properties, such as
:command:`target_link_libraries`, :command:`target_include_directories`,
:command:`target_compile_definitions` and others.

:manual:`Generator expressions <cmake-generator-expressions(7)>`  may be used
to enable conditional linking, conditional definitions used when compiling,
conditional include directories and more. The conditions may be based on the
build configuration, target properties, platform information or any other
queryable information.

There are different types of
:manual:`generator expressions <cmake-generator-expressions(7)>` including
Logical, Informational, and Output expressions.

Logical expressions are used to create conditional output. The basic
expressions are the ``0`` and ``1`` expressions. A ``$<0:...>`` results in the
empty string, and ``$<1:...>`` results in the content of ``...``.  They can also
be nested.

Exercise 1 - Adding Compiler Warning Flags with Generator Expressions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A common usage of
:manual:`generator expressions <cmake-generator-expressions(7)>` is to
conditionally add compiler flags, such as those for language levels or
warnings. A nice pattern is to associate this information to an ``INTERFACE``
target allowing this information to propagate.

Goal
----

Add compiler warning flags when building but not for installed versions.

Helpful Resources
-----------------

* :manual:`cmake-generator-expressions(7)`
* :command:`cmake_minimum_required`
* :command:`set`
* :command:`target_compile_options`

Files to Edit
-------------

* ``CMakeLists.txt``

Getting Started
---------------

Open the file ``Step4/CMakeLists.txt`` and complete ``TODO 1`` through
``TODO 4``.

First, in the top level ``CMakeLists.txt`` file, we need to set the
:command:`cmake_minimum_required` to ``3.15``. In this exercise we are going
to use a generator expression which was introduced in CMake 3.15.

Next we add the desired compiler warning flags that we want for our project.
As warning flags vary based on the compiler, we use the
``COMPILE_LANG_AND_ID`` generator expression to control which flags to apply
given a language and a set of compiler ids.

Build and Run
-------------

Make a new directory called ``Step4_build``, run the :manual:`cmake <cmake(1)>`
executable or the :manual:`cmake-gui <cmake-gui(1)>` to configure the project
and then build it with your chosen build tool or by using ``cmake --build .``
from the build directory.

.. code-block:: console

  mkdir Step4_build
  cd Step4_build
  cmake ../Step4
  cmake --build .

Solution
--------

Update the :command:`cmake_minimum_required` to require at least CMake
version ``3.15``:

.. raw:: html

  TODO 1: Click to show/hide answer

.. literalinclude:: Step5/CMakeLists.txt
  :caption: TODO 1: CMakeLists.txt
  :name: MathFunctions-CMakeLists.txt-minimum-required-step4
  :language: cmake
  :end-before: # set the project name and version

.. raw:: html

Next we determine which compiler our system is currently using to build
since warning flags vary based on the compiler we use. This is done with
the ``COMPILE_LANG_AND_ID`` generator expression. We set the result in the
variables ``gcc_like_cxx`` and ``msvc_cxx`` as follows:

.. raw:: html

  TODO 2: Click to show/hide answer

.. literalinclude:: Step5/CMakeLists.txt
  :caption: TODO 2: CMakeLists.txt
  :name: CMakeLists.txt-compile_lang_and_id
  :language: cmake
  :start-after: # the BUILD_INTERFACE genex
  :end-before: target_compile_options(tutorial_compiler_flags INTERFACE

.. raw:: html

Next we add the desired compiler warning flags that we want for our project.
Using our variables ``gcc_like_cxx`` and ``msvc_cxx``, we can use another
generator expression to apply the respective flags only when the variables are
true. We use :command:`target_compile_options` to apply these flags to our
interface library.

.. raw:: html

  TODO 3: Click to show/hide answer

.. code-block:: cmake
  :caption: TODO 3: CMakeLists.txt
  :name: CMakeLists.txt-compile_flags

  target_compile_options(tutorial_compiler_flags INTERFACE
    "$<${gcc_like_cxx}:-Wall;-Wextra;-Wshadow;-Wformat=2;-Wunused>"
    "$<${msvc_cxx}:-W3>"
  )

.. raw:: html

Lastly, we only want these warning flags to be used during builds. Consumers
of our installed project should not inherit our warning flags. To specify
this, we wrap our flags from TODO 3 in a generator expression using the
``BUILD_INTERFACE`` condition. The resulting full code looks like the following:

.. raw:: html

  TODO 4: Click to show/hide answer

.. literalinclude:: Step5/CMakeLists.txt
  :caption: TODO 4: CMakeLists.txt
  :name: CMakeLists.txt-target_compile_options-genex
  :language: cmake
  :start-after: set(msvc_cxx "$<COMPILE_LANG_AND_ID:CXX,MSVC>")
  :end-before: # configure a header file to pass some of the CMake settings

.. raw:: html


code:
Step 6: Adding Support for a Testing Dashboard
==============================================

Adding support for submitting our test results to a dashboard is simple. We
already defined a number of tests for our project in
:ref:`Testing Support <Tutorial Testing Support>`. Now we just have to run
those tests and submit them to CDash.

Exercise 1 - Send Results to a Testing Dashboard
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Goal
----

Display our CTest results with CDash.

Helpful Resources
-----------------

* :manual:`ctest(1)`
* :command:`include`
* :module:`CTest`

Files to Edit
-------------

* ``CMakeLists.txt``

Getting Started
---------------

For this exercise, complete ``TODO 1`` in the top-level ``CMakeLists.txt`` by
including the :module:`CTest` module. This will enable testing with CTest as
well as dashboard submissions to CDash, so we can safely remove the call to
:command:`enable_testing`.

We will also need to acquire a ``CTestConfig.cmake`` file to be placed in the
top-level directory. When run, the :manual:`ctest <ctest(1)>` executable will
read this file to gather information about the testing dashboard. It contains:

* The project name

* The project "Nightly" start time

  *  The time when a 24 hour "day" starts for this project.

* The URL of the CDash instance where the submission's generated documents
  will be sent

For this tutorial, a public dashboard server is used and its corresponding
``CTestConfig.cmake`` file is provided for you in this step's root directory.
In practice, this file would be downloaded from a project's ``Settings`` page
on the CDash instance intended to host the test results. Once downloaded from
CDash, the file should not be modified locally.

.. literalinclude:: Step7/CTestConfig.cmake
  :caption: CTestConfig.cmake
  :name: CTestConfig.cmake
  :language: cmake

Build and Run
-------------

Note that as part of the CDash submission some information about your
development system (e.g. site name or full pathnames) may displayed publicly.

To create a simple test dashboard, run the :manual:`cmake <cmake(1)>`
executable or the :manual:`cmake-gui <cmake-gui(1)>` to configure the project
but do not build it yet. Instead, navigate to the build directory and run:

.. code-block:: console

  ctest [-VV] -D Experimental

Remember, for multi-config generators (e.g. Visual Studio), the configuration
type must be specified:

.. code-block:: console

  ctest [-VV] -C Debug -D Experimental

Or, from an IDE, build the ``Experimental`` target.

The :manual:`ctest <ctest(1)>` executable will build the project, run any
tests, and submit the results to Kitware's public dashboard:
https://my.cdash.org/index.php?project=CMakeTutorial.

Solution
--------

The only CMake code changed needed in this step was to enable dashboard
submissions to CDash by including the :module:`CTest` module in our top-level
``CMakeLists.txt``:

.. raw:: html

  <details><summary>TODO 1: Click to show/hide answer</summary>

.. literalinclude:: Step7/CMakeLists.txt
  :caption: TODO 1: CMakeLists.txt
  :name: CMakeLists.txt-include-CTest
  :language: cmake
  :start-after: # enable testing
  :end-before: # does the application run

.. raw:: html

  </details>

path: buildtools/windows/cmake/doc/cmake/html/_sources/guide/tutorial/Adding Support for a Testing Dashboard.rst.txt


code:
Step 7: Adding System Introspection
===================================

Let us consider adding some code to our project that depends on features the
target platform may not have. For this example, we will add some code that
depends on whether or not the target platform has the ``log`` and ``exp``
functions. Of course almost every platform has these functions but for this
tutorial assume that they are not common.

Exercise 1 - Assessing Dependency Availability
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Goal
----

Change implementation based on available system dependencies.

Helpful Resources
-----------------

* :module:`CheckCXXSourceCompiles`
* :command:`target_compile_definitions`

Files to Edit
-------------

* ``MathFunctions/CMakeLists.txt``
* ``MathFunctions/mysqrt.cxx``

Getting Started
---------------

The starting source code is provided in the ``Step7`` directory. In this
exercise, complete ``TODO 1`` through ``TODO 5``.

Start by editing ``MathFunctions/CMakeLists.txt``. Include the
:module:`CheckCXXSourceCompiles` module. Then, use
``check_cxx_source_compiles`` to determine whether ``log`` and ``exp`` are
available from ``cmath``. If they are available, use
:command:`target_compile_definitions` to specify ``HAVE_LOG`` and ``HAVE_EXP``
as compile definitions.

In the ``MathFunctions/mysqrt.cxx``, include ``cmath``. Then, if the system has
``log`` and ``exp``, use them to compute the square root.

Build and Run
-------------

Make a new directory called ``Step7_build``. Run the
:manual:`cmake  <cmake(1)>` executable or the
:manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
with your chosen build tool and run the ``Tutorial`` executable.

This can look like the following:

.. code-block:: console

  mkdir Step7_build
  cd Step7_build
  cmake ../Step7
  cmake --build .

Which function gives better results now, ``sqrt`` or ``mysqrt``?

Solution
--------

In this exercise we will use functions from the
:module:`CheckCXXSourceCompiles` module so first we must include it in
``MathFunctions/CMakeLists.txt``.

.. raw:: html

  TODO 1: Click to show/hide answer

.. literalinclude:: Step8/MathFunctions/CMakeLists.txt
  :caption: TODO 1: MathFunctions/CMakeLists.txt
  :name: MathFunctions/CMakeLists.txt-include-check_cxx_source_compiles
  :language: cmake
  :start-after: # does this system provide the log and exp functions?
  :end-before: check_cxx_source_compiles

.. raw:: html

Then test for the availability of
``log`` and ``exp`` using ``check_cxx_compiles_source``. This function
lets us try compiling simple code with the required dependency prior to
the true source code compilation. The resulting variables ``HAVE_LOG``
and ``HAVE_EXP`` represent whether those dependencies are available.

.. raw:: html

  TODO 2: Click to show/hide answer

.. literalinclude:: Step8/MathFunctions/CMakeLists.txt
  :caption: TODO 2: MathFunctions/CMakeLists.txt
  :name: MathFunctions/CMakeLists.txt-check_cxx_source_compiles
  :language: cmake
  :start-after: include(CheckCXXSourceCompiles)
  :end-before: # add compile definitions

.. raw:: html

Next, we need to pass these CMake variables to our source code. This way,
our source code can tell what resources are available. If both ``log`` and
``exp`` are available, use :command:`target_compile_definitions` to specify
``HAVE_LOG`` and ``HAVE_EXP`` as ``PRIVATE`` compile definitions.

.. raw:: html

  TODO 3: Click to show/hide answer

.. literalinclude:: Step8/MathFunctions/CMakeLists.txt
  :caption: TODO 3: MathFunctions/CMakeLists.txt
  :name: MathFunctions/CMakeLists.txt-target_compile_definitions
  :language: cmake
  :start-after: # add compile definitions
  :end-before: # state

.. raw:: html

Since we may be using ``log`` and ``exp``, we need to modify
``mysqrt.cxx`` to include ``cmath``.

.. raw:: html

  TODO 4: Click to show/hide answer

.. literalinclude:: Step8/MathFunctions/mysqrt.cxx
  :caption: TODO 4: MathFunctions/mysqrt.cxx
  :name: MathFunctions/mysqrt.cxx-include-cmath
  :language: c++
  :start-after: #include "mysqrt.h"
  :end-before: include <iostream>

.. raw:: html

If ``log`` and ``exp`` are available on the system, then use them to
compute the square root in the ``mysqrt`` function. The ``mysqrt`` function in
``MathFunctions/mysqrt.cxx`` will look as follows:

.. raw:: html

  TODO 5: Click to show/hide answer

.. literalinclude:: Step8/MathFunctions/mysqrt.cxx
  :caption: TODO 5: MathFunctions/mysqrt.cxx
  :name: MathFunctions/mysqrt.cxx-ifdef
  :language: c++
  :start-after: // if we have both log and exp then use them
  :end-before: return result;

.. raw:: html