code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>Step 5: Installing and Testing — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/cmake.css" />

    <link rel="icon" href="../../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Step 6: Adding Support for a Testing Dashboard" href="Adding%20Support%20for%20a%20Testing%20Dashboard.html" />
    <link rel="prev" title="Step 4: Adding Generator Expressions" href="Adding%20Generator%20Expressions.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 5: Installing and Testing

Step 5: Installing and Testing¶

Exercise 1 - Install Rules¶

Often, it is not enough to only build an executable, it should also be
installable. With CMake, we can specify install rules using the
install() command. Supporting local installations for your builds in
CMake is often as simple as specifying an install location and the targets and
files to be installed.

Goal¶

Install the Tutorial executable and the MathFunctions library.

Helpful Materials¶

install()

Files to Edit¶

MathFunctions/CMakeLists.txt

CMakeLists.txt

Getting Started¶

The starting code is provided in the Step5 directory. In this
exercise, complete TODO 1 through TODO 4.

First, update MathFunctions/CMakeLists.txt to install the
MathFunctions and tutorial_compiler_flags libraries to the lib
directory. In that same file, specify the install rules needed to install
MathFunctions.h to the include directory.

Then, update the top level CMakeLists.txt to install
the Tutorial executable to the bin directory. Lastly, any header files
should be installed to the include directory. Remember that
TutorialConfig.h is in the PROJECT_BINARY_DIR.

Build and Run¶

Make a new directory called Step5_build. Run the
cmake executable or the
cmake-gui to configure the project and then build it
with your chosen build tool.

Then, run the install step by using the --install
option of the cmake command (introduced in 3.15, older
versions of CMake must use make install) from the command line. This step
will install the appropriate header files, libraries, and executables.
For example:

cmake --install .

For multi-configuration tools, don't forget to use the
--config argument to specify the configuration.

cmake --install . --config Release

If using an IDE, simply build the INSTALL target. You can build the same
install target from the command line like the following:

cmake --build . --target install --config Debug

The CMake variable CMAKE_INSTALL_PREFIX is used to determine the
root of where the files will be installed. If using the cmake --install
command, the installation prefix can be overridden via the
--prefix argument. For example:

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

Navigate to the install directory and verify that the installed Tutorial
runs.

Solution¶

The install rules for our project are fairly simple:

For MathFunctions, we want to install the libraries and header file to
the lib and include directories respectively.

For the Tutorial executable, we want to install the executable and
configured header file to the bin and include directories
respectively.

So to the end of MathFunctions/CMakeLists.txt we add:

TODO 1: Click to show/hide answer

TODO 1: MathFunctions/CMakeLists.txt¶

set(installable_libs MathFunctions tutorial_compiler_flags)
if(TARGET SqrtLibrary)
  list(APPEND installable_libs SqrtLibrary)
endif()
install(TARGETS ${installable_libs} DESTINATION lib)

and

TODO 2: Click to show/hide answer

TODO 2: MathFunctions/CMakeLists.txt¶

install(FILES MathFunctions.h DESTINATION include)

The install rules for the Tutorial executable and configured header file
are similar. To the end of the top-level CMakeLists.txt we add:

TODO 3,4: Click to show/hide answer

CMakeLists.txt¶

install(TARGETS Tutorial DESTINATION bin)
install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
  DESTINATION include
  )

That is all that is needed to create a basic local
install of the tutorial.

Exercise 2 - Testing Support¶

CTest offers a way to easily manage tests for your project. Tests can be
added through the add_test() command. Although it is not
explicitly covered in this tutorial, there is a lot of compatibility
between CTest and other testing frameworks such as GoogleTest.

Goal¶

Create unit tests for our executable using CTest.

Helpful Materials¶

enable_testing()

add_test()

function()

set_tests_properties()

ctest

Files to Edit¶

CMakeLists.txt

Getting Started¶

The starting source code is provided in the Step5 directory. In this
exercise, complete TODO 5 through TODO 9.

First, we need to enable testing. Next, begin adding tests to our project
using add_test(). We will work through adding 3 simple tests and
then you can add additional testing as you see fit.

Build and Run¶

Navigate to the build directory and rebuild the application. Then, run the
ctest executable: ctest -N and ctest -VV. For
multi-config generators (e.g. Visual Studio), the configuration type must be
specified with the -C <mode> flag.  For example, to run tests in Debug
mode use ctest -C Debug -VV from the build directory
(not the Debug subdirectory!). Release mode would be executed from the same
location but with a -C Release. Alternatively, build the RUN_TESTS
target from the IDE.

Solution¶

Let's test our application. At the end of the top-level CMakeLists.txt
file we first need to enable testing with the
enable_testing() command.

TODO 5: Click to show/hide answer

TODO 5: CMakeLists.txt¶

enable_testing()

With testing enabled, we will add a number of basic tests to verify
that the application is working correctly. First, we create a test using
add_test() which runs the Tutorial executable with the
parameter 25 passed in. For this test, we are not going to check the
executable's computed answer. This test will verify that
application runs, does not segfault or otherwise crash, and has a zero
return value. This is the basic form of a CTest test.

TODO 6: Click to show/hide answer

TODO 6: CMakeLists.txt¶

add_test(NAME Runs COMMAND Tutorial 25)

Next, let's use the PASS_REGULAR_EXPRESSION test property to
verify that the output of the test contains certain strings. In this case,
verifying that the usage message is printed when an incorrect number of
arguments are provided.

TODO 7: Click to show/hide answer

TODO 7: CMakeLists.txt¶

add_test(NAME Usage COMMAND Tutorial)
set_tests_properties(Usage
  PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
  )

The next test we will add verifies the computed value is truly the
square root.

TODO 8: Click to show/hide answer

TODO 8: CMakeLists.txt¶

add_test(NAME StandardUse COMMAND Tutorial 4)
set_tests_properties(StandardUse
  PROPERTIES PASS_REGULAR_EXPRESSION "4 is 2"
  )

This one test is not enough to give us confidence that it will
work for all values passed in. We should add more tests to verify this.
To easily add more tests, we make a function called do_test that runs the
application and verifies that the computed square root is correct for
given input. For each invocation of do_test, another test is added to
the project with a name, input, and expected results based on the passed
arguments.

TODO 9: Click to show/hide answer

TODO 9: CMakeLists.txt¶

function(do_test target arg result)
  add_test(NAME Comp${arg} COMMAND ${target} ${arg})
  set_tests_properties(Comp${arg}
    PROPERTIES PASS_REGULAR_EXPRESSION ${result}
    )
endfunction()

# do a bunch of result based tests
do_test(Tutorial 4 "4 is 2")
do_test(Tutorial 9 "9 is 3")
do_test(Tutorial 5 "5 is 2.236")
do_test(Tutorial 7 "7 is 2.645")
do_test(Tutorial 25 "25 is 5")
do_test(Tutorial -25 "-25 is (-nan|nan|0)")
do_test(Tutorial 0.0001 "0.0001 is 0.01")

Table of Contents

Step 5: Installing and Testing

Exercise 1 - Install Rules

Goal

Helpful Materials

Files to Edit

Getting Started

Build and Run

Solution

Exercise 2 - Testing Support

Goal

Helpful Materials

Files to Edit

Getting Started

Build and Run

Solution

Previous topic

Step 4: Adding Generator Expressions

Next topic

Step 6: Adding Support for a Testing Dashboard

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 5: Installing and Testing

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>Step 12: Packaging Debug and Release — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/cmake.css" />

    <link rel="icon" href="../../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="User Interaction Guide" href="../user-interaction/index.html" />
    <link rel="prev" title="Step 11: Adding Export Configuration" href="Adding%20Export%20Configuration.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 12: Packaging Debug and Release

Step 12: Packaging Debug and Release¶

Note: This example is valid for single-configuration generators and will
not work for multi-configuration generators (e.g. Visual Studio).

By default, CMake's model is that a build directory only contains a single
configuration, be it Debug, Release, MinSizeRel, or RelWithDebInfo. It is
possible, however, to setup CPack to bundle multiple build directories and
construct a package that contains multiple configurations of the same project.

First, we want to ensure that the debug and release builds use different names
for the libraries that will be installed. Let's use d as the
postfix for the debug libraries.

Set CMAKE_DEBUG_POSTFIX near the beginning of the top-level
CMakeLists.txt file:

CMakeLists.txt¶

set(CMAKE_DEBUG_POSTFIX d)

add_library(tutorial_compiler_flags INTERFACE)

And the DEBUG_POSTFIX property on the tutorial executable:

CMakeLists.txt¶

add_executable(Tutorial tutorial.cxx)
set_target_properties(Tutorial PROPERTIES DEBUG_POSTFIX ${CMAKE_DEBUG_POSTFIX})

target_link_libraries(Tutorial PUBLIC MathFunctions tutorial_compiler_flags)

Let's also add version numbering to the MathFunctions library. In
MathFunctions/CMakeLists.txt, set the VERSION and
SOVERSION properties:

MathFunctions/CMakeLists.txt¶

set_property(TARGET MathFunctions PROPERTY VERSION "1.0.0")
set_property(TARGET MathFunctions PROPERTY SOVERSION "1")

From the Step12 directory, create debug and release
subdirectories. The layout will look like:

- Step12
   - debug
   - release

Now we need to setup debug and release builds. We can use
CMAKE_BUILD_TYPE to set the configuration type:

cd debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
cmake --build .
cd ../release
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build .

Now that both the debug and release builds are complete, we can use a custom
configuration file to package both builds into a single release. In the
Step12 directory, create a file called MultiCPackConfig.cmake. In this
file, first include the default configuration file that was created by the
cmake executable.

Next, use the CPACK_INSTALL_CMAKE_PROJECTS variable to specify which
projects to install. In this case, we want to install both debug and release.

MultiCPackConfig.cmake¶

include("release/CPackConfig.cmake")

set(CPACK_INSTALL_CMAKE_PROJECTS
    "debug;Tutorial;ALL;/"
    "release;Tutorial;ALL;/"
    )

From the Step12 directory, run cpack specifying our
custom configuration file with the config option:

cpack --config MultiCPackConfig.cmake

Previous topic

Step 11: Adding Export Configuration

Next topic

User Interaction Guide

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 12: Packaging Debug and Release

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.

repo_name: lazytadpole/codenamesilverfish

path: buildtools/windows/cmake/doc/cmake/html/guide/tutorial/Packaging Debug and Release.html

license: mit


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>Step 9: Packaging an Installer — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/cmake.css" />

    <link rel="icon" href="../../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Step 10: Selecting Static or Shared Libraries" href="Selecting%20Static%20or%20Shared%20Libraries.html" />
    <link rel="prev" title="Step 8: Adding a Custom Command and Generated File" href="Adding%20a%20Custom%20Command%20and%20Generated%20File.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 9: Packaging an Installer

Step 9: Packaging an Installer¶

Next suppose that we want to distribute our project to other people so that
they can use it. We want to provide both binary and source distributions on a
variety of platforms. This is a little different from the install we did
previously in Installing and Testing, where we were
installing the binaries that we had built from the source code. In this
example we will be building installation packages that support binary
installations and package management features. To accomplish this we will use
CPack to create platform specific installers. Specifically we need to add a
few lines to the bottom of our top-level CMakeLists.txt file.

CMakeLists.txt¶

include(InstallRequiredSystemLibraries)
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
set(CPACK_SOURCE_GENERATOR "TGZ")
include(CPack)

That is all there is to it. We start by including
InstallRequiredSystemLibraries. This module will include any runtime
libraries that are needed by the project for the current platform. Next we set
some CPack variables to where we have stored the license and version
information for this project. The version information was set earlier in this
tutorial and the License.txt has been included in the top-level source
directory for this step.  The CPACK_SOURCE_GENERATOR variable
selects a file format for the source package.

Finally we include the CPack module which will use these
variables and some other properties of the current system to setup an
installer.

The next step is to build the project in the usual manner and then run the
cpack executable. To build a binary distribution, from the
binary directory run:

cpack

To specify the generator, use the -G option. For multi-config builds,
use -C to specify the configuration. For example:

cpack -G ZIP -C Debug

For a list of available generators, see cpack-generators(7) or call
cpack --help. An archive generator
like ZIP creates a compressed archive of all installed files.

To create an archive of the full source tree you would type:

cpack --config CPackSourceConfig.cmake

Alternatively, run make package or right click the Package target and
Build Project from an IDE.

Run the installer found in the binary directory. Then run the installed
executable and verify that it works.

Previous topic

Step 8: Adding a Custom Command and Generated File

Next topic

Step 10: Selecting Static or Shared Libraries

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 9: Packaging an Installer

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>Step 10: Selecting Static or Shared Libraries — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/cmake.css" />

    <link rel="icon" href="../../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Step 11: Adding Export Configuration" href="Adding%20Export%20Configuration.html" />
    <link rel="prev" title="Step 9: Packaging an Installer" href="Packaging%20an%20Installer.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 10: Selecting Static or Shared Libraries

Step 10: Selecting Static or Shared Libraries¶

In this section we will show how the BUILD_SHARED_LIBS variable can
be used to control the default behavior of add_library(),
and allow control over how libraries without an explicit type (STATIC,
SHARED, MODULE or OBJECT) are built.

To accomplish this we need to add BUILD_SHARED_LIBS to the
top-level CMakeLists.txt. We use the option() command as it allows
users to optionally select if the value should be ON or OFF.

CMakeLists.txt¶

option(BUILD_SHARED_LIBS "Build using shared libraries" ON)

Next, we need to specify output directories for our static and shared
libraries.

CMakeLists.txt¶

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")

option(BUILD_SHARED_LIBS "Build using shared libraries" ON)

Finally, update MathFunctions/MathFunctions.h to use dll export defines:

MathFunctions/MathFunctions.h¶

#if defined(_WIN32)
#  if defined(EXPORTING_MYMATH)
#    define DECLSPEC __declspec(dllexport)
#  else
#    define DECLSPEC __declspec(dllimport)
#  endif
#else // non windows
#  define DECLSPEC
#endif

namespace mathfunctions {
double DECLSPEC sqrt(double x);
}

At this point, if you build everything, you may notice that linking fails
as we are combining a static library without position independent code with a
library that has position independent code. The solution to this is to
explicitly set the POSITION_INDEPENDENT_CODE target property of
SqrtLibrary to be True when building shared libraries.

MathFunctions/CMakeLists.txt¶

  # state that SqrtLibrary need PIC when the default is shared libraries
  set_target_properties(SqrtLibrary PROPERTIES
                        POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}
                        )

Define EXPORTING_MYMATH stating we are using declspec(dllexport) when
building on Windows.

MathFunctions/CMakeLists.txt¶

# define the symbol stating we are using the declspec(dllexport) when
# building on windows
target_compile_definitions(MathFunctions PRIVATE "EXPORTING_MYMATH")

Exercise: We modified MathFunctions.h to use dll export defines.
Using CMake documentation can you find a helper module to simplify this?

Previous topic

Step 9: Packaging an Installer

Next topic

Step 11: Adding Export Configuration

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial »

Step 10: Selecting Static or Shared Libraries

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.

path: buildtools/windows/cmake/doc/cmake/html/guide/tutorial/Selecting Static or Shared Libraries.html


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>CMake Tutorial — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/cmake.css" />

    <link rel="icon" href="../../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Step 1: A Basic Starting Point" href="A%20Basic%20Starting%20Point.html" />
    <link rel="prev" title="CPack WIX Generator" href="../../cpack_gen/wix.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial

CMake Tutorial¶

Introduction¶

The CMake tutorial provides a step-by-step guide that covers common build
system issues that CMake helps address. Seeing how various topics all
work together in an example project can be very helpful.

Steps¶

The tutorial documentation and source code examples can be found in
the Help/guide/tutorial directory of the CMake source code tree.
Each step has its own subdirectory containing code that may be used as a
starting point. The tutorial examples are progressive so that each step
provides the complete solution for the previous step.

Step 1: A Basic Starting Point

Exercise 1 - Building a Basic Project

Exercise 2 - Specifying the C++ Standard

Exercise 3 - Adding a Version Number and Configured Header File

Step 2: Adding a Library

Exercise 1 - Creating a Library

Exercise 2 - Adding an Option

Step 3: Adding Usage Requirements for a Library

Exercise 1 - Adding Usage Requirements for a Library

Exercise 2 - Setting the C++ Standard with Interface Libraries

Step 4: Adding Generator Expressions

Exercise 1 - Adding Compiler Warning Flags with Generator Expressions

Step 5: Installing and Testing

Exercise 1 - Install Rules

Exercise 2 - Testing Support

Step 6: Adding Support for a Testing Dashboard

Exercise 1 - Send Results to a Testing Dashboard

Step 7: Adding System Introspection

Exercise 1 - Assessing Dependency Availability

Step 8: Adding a Custom Command and Generated File

Step 9: Packaging an Installer

Step 10: Selecting Static or Shared Libraries

Step 11: Adding Export Configuration

Step 12: Packaging Debug and Release

Table of Contents

CMake Tutorial

Introduction

Steps

Previous topic

CPack WIX Generator

Next topic

Step 1: A Basic Starting Point

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

CMake Tutorial

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>User Interaction Guide — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/cmake.css" />

    <link rel="icon" href="../../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Using Dependencies Guide" href="../using-dependencies/index.html" />
    <link rel="prev" title="Step 12: Packaging Debug and Release" href="../tutorial/Packaging%20Debug%20and%20Release.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

User Interaction Guide

User Interaction Guide¶

Contents

User Interaction Guide

Introduction

Command Line cmake tool

cmake-gui tool

Generating a Buildsystem

Command line environment

Command line -G option

Choosing a generator in cmake-gui

Setting Build Variables

Setting variables on the command line

Setting variables with cmake-gui

The CMake Cache

Presets

Using presets on the command-line

Using presets in cmake-gui

Invoking the Buildsystem

Selecting a Target

Specifying a Build Program

Software Installation

Running Tests

Introduction¶

Where a software package supplies a CMake-based buildsystem
with the source of their software, the consumer of the
software is required to run a CMake user interaction tool
in order to build it.

Well-behaved CMake-based buildsystems do not create any
output in the source directory, so typically, the user
performs an out-of-source build and performs the build
there.  First, CMake must be instructed to generate a
suitable buildsystem, then the user invokes a build tool
to process that generated buildsystem.  The generated
buildsystem is specific to the machine used to generate
it and is not redistributable.  Each consumer of a provided
source software package is required to use CMake to
generate a buildsystem specific to their system.

Generated buildsystems should generally be treated as
read-only. The CMake files as a primary artifact should
completely specify the buildsystem and there should be no
reason to populate properties manually in an IDE for
example after generating the buildsystem.  CMake will
periodically rewrite the generated buildsystem, so
modifications by users will be overwritten.

The features and user interfaces described in this manual
are available for all CMake-based build systems by virtue
of providing CMake files.

The CMake tooling may report errors to the user when
processing provided CMake files, such as reporting that
the compiler is not supported, or the compiler does not
support a required compile option, or a dependency can
not be found.  These errors must be resolved by the user
by choosing a different compiler,
installing dependencies,
or instructing CMake where to find them, etc.

Command Line cmake tool¶

A simple but typical use of cmake(1) with a fresh
copy of software source code is to create a build directory
and invoke cmake there:

$ cd some_software-1.4.2
$ mkdir build
$ cd build
$ cmake .. -DCMAKE_INSTALL_PREFIX=/opt/the/prefix
$ cmake --build .
$ cmake --build . --target install

It is recommended to build in a separate directory to the
source because that keeps the source directory pristine,
allows for building a single source with multiple
toolchains, and allows easy clearing of build artifacts by
simply deleting the build directory.

The CMake tooling may report warnings which are intended
for the provider of the software, not intended for the
consumer of the software.  Such warnings end with "This
warning is for project developers".  Users may disable
such warnings by passing the -Wno-dev
flag to cmake(1).

cmake-gui tool¶

Users more accustomed to GUI interfaces may use the
cmake-gui(1) tool to invoke CMake and generate
a buildsystem.

The source and binary directories must first be
populated.  It is always advised to use different
directories for the source and the build.

Generating a Buildsystem¶

There are several user interface tools which may be used
to generate a buildsystem from CMake files.  The
ccmake(1) and cmake-gui(1) tools guide
the user through setting the various necessary options.
The cmake(1) tool can be invoked to specify
options on the command line.  This manual describes options
which may be set using any of the user interface tools,
though the mode of setting an option is different for each
tool.

Command line environment¶

When invoking cmake(1) with a command line
buildsystem such as Makefiles or Ninja, it is
necessary to use the correct build environment to
ensure that build tools are available. CMake must be
able to find the appropriate
build tool,
compiler, linker and other tools as needed.

On Linux systems, the appropriate tools are often
provided in system-wide locations and may be readily
installed through the system package manager. Other
toolchains provided by the user or installed in
non-default locations can also be used.

When cross-compiling, some platforms may require
environment variables to be set or may provide
scripts to set the environment.

Visual Studio ships multiple command prompts and
vcvarsall.bat scripts for setting up the
correct environments for command line buildsystems. While
not strictly necessary to use a corresponding
command line environment when using a Visual Studio
generator, doing so has no disadvantages.

When using Xcode, there can be more than one Xcode
version installed.  Which one to use can be selected
in a number of different ways, but the most common
methods are:

Setting the default version in the preferences
of the Xcode IDE.

Setting the default version via the xcode-select
command line tool.

Overriding the default version by setting the
DEVELOPER_DIR environment variable when running
CMake and the build tool.

For convenience, cmake-gui(1) provides an
environment variable editor.

Command line -G option¶

CMake chooses a generator by default based on the
platform.  Usually, the default generator is sufficient
to allow the user to proceed to build the software.

The user may override the default generator with
the -G option:

$ cmake .. -G Ninja

The output of cmake --help includes a list of
generators available
for the user to choose from.  Note that generator
names are case sensitive.

On Unix-like systems (including Mac OS X), the
Unix Makefiles generator is used by
default.  A variant of that generator can also be used
on Windows in various environments, such as the
NMake Makefiles and
MinGW Makefiles generator.  These generators
generate a Makefile variant which can be executed
with make, gmake, nmake or similar tools.
See the individual generator documentation for more
information on targeted environments and tools.

The Ninja generator is available on all
major platforms. ninja is a build tool similar
in use-cases to make, but with a focus on
performance and efficiency.

On Windows, cmake(1) can be used to generate
solutions for the Visual Studio IDE.  Visual Studio
versions may be specified by the product name of the
IDE, which includes a four-digit year.  Aliases are
provided for other means by which Visual Studio
versions are sometimes referred to, such as two
digits which correspond to the product version of the
VisualC++ compiler, or a combination of the two:

$ cmake .. -G "Visual Studio 2019"
$ cmake .. -G "Visual Studio 16"
$ cmake .. -G "Visual Studio 16 2019"

Visual Studio generators can target different architectures.
One can specify the target architecture using the
-A option:

cmake .. -G "Visual Studio 2019" -A x64
cmake .. -G "Visual Studio 16" -A ARM
cmake .. -G "Visual Studio 16 2019" -A ARM64

On Apple, the Xcode generator may be used to
generate project files for the Xcode IDE.

Some IDEs such as KDevelop4, QtCreator and CLion have
native support for CMake-based buildsystems.  Those IDEs
provide user interface for selecting an underlying
generator to use, typically a choice between a Makefile
or a Ninja based generator.

Note that it is not possible to change the generator
with -G after the first invocation of CMake.
To change the generator, the build directory must be
deleted and the build must be started from scratch.

When generating Visual Studio project and solutions
files several other options are available to use when
initially running cmake(1).

The Visual Studio toolset can be specified with the
cmake -T option:

$ # Build with the clang-cl toolset
$ cmake.exe .. -G "Visual Studio 16 2019" -A x64 -T ClangCL
$ # Build targeting Windows XP
$ cmake.exe .. -G "Visual Studio 16 2019" -A x64 -T v120_xp

Whereas the -A option specifies the _target_
architecture, the -T option can be used to specify
details of the toolchain used.  For example, -Thost=x64
can be given to select the 64-bit version of the host
tools.  The following demonstrates how to use 64-bit
tools and also build for a 64-bit target architecture:

$ cmake .. -G "Visual Studio 16 2019" -A x64 -Thost=x64

Choosing a generator in cmake-gui¶

The "Configure" button triggers a new dialog to
select the CMake generator to use.

All generators available on the command line are also
available in cmake-gui(1).

When choosing a Visual Studio generator, further options
are available to set an architecture to generate for.

Setting Build Variables¶

Software projects often require variables to be
set on the command line when invoking CMake.  Some of
the most commonly used CMake variables are listed in
the table below:

Variable

Meaning

CMAKE_PREFIX_PATH

Path to search for
dependent packages

CMAKE_MODULE_PATH

Path to search for additional CMake modules

CMAKE_BUILD_TYPE

Build configuration, such as
Debug or Release, determining
debug/optimization flags.  This is only
relevant for single-configuration buildsystems such
as Makefile and Ninja.  Multi-configuration
buildsystems such as those for Visual Studio and Xcode
ignore this setting.

CMAKE_INSTALL_PREFIX

Location to install the
software to with the
install build target

CMAKE_TOOLCHAIN_FILE

File containing cross-compiling
data such as
toolchains and sysroots.

BUILD_SHARED_LIBS

Whether to build shared
instead of static libraries
for add_library()
commands used without a type

CMAKE_EXPORT_COMPILE_COMMANDS

Generate a compile_commands.json
file for use with clang-based tools

Other project-specific variables may be available
to control builds, such as enabling or disabling
components of the project.

There is no convention provided by CMake for how
such variables are named between different
provided buildsystems, except that variables with
the prefix CMAKE_ usually refer to options
provided by CMake itself and should not be used
in third-party options, which should use
their own prefix instead.  The
cmake-gui(1) tool can display options
in groups defined by their prefix, so it makes
sense for third parties to ensure that they use a
self-consistent prefix.

Setting variables on the command line¶

CMake variables can be set on the command line either
when creating the initial build:

$ mkdir build
$ cd build
$ cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Debug

or later on a subsequent invocation of
cmake(1):

$ cd build
$ cmake . -DCMAKE_BUILD_TYPE=Debug

The -U flag may be used to unset variables
on the cmake(1) command line:

$ cd build
$ cmake . -UMyPackage_DIR

A CMake buildsystem which was initially created
on the command line can be modified using the
cmake-gui(1) and vice-versa.

The cmake(1) tool allows specifying a
file to use to populate the initial cache using
the -C option.  This can be useful to simplify
commands and scripts which repeatedly require the
same cache entries.

Setting variables with cmake-gui¶

Variables may be set in the cmake-gui using the "Add Entry"
button.  This triggers a new dialog to set the value of
the variable.

The main view of the cmake-gui(1) user interface
can be used to edit existing variables.

The CMake Cache¶

When CMake is executed, it needs to find the locations of
compilers, tools and dependencies.  It also needs to be
able to consistently re-generate a buildsystem to use the
same compile/link flags and paths to dependencies.  Such
parameters are also required to be configurable by the
user because they are paths and options specific to the
users system.

When it is first executed, CMake generates a
CMakeCache.txt file in the build directory containing
key-value pairs for such artifacts.  The cache file can be
viewed or edited by the user by running the
cmake-gui(1) or ccmake(1) tool.  The
tools provide an interactive interface for re-configuring
the provided software and re-generating the buildsystem,
as is needed after editing cached values.  Each cache
entry may have an associated short help text which is
displayed in the user interface tools.

The cache entries may also have a type to signify how it
should be presented in the user interface.  For example,
a cache entry of type BOOL can be edited by a
checkbox in a user interface, a STRING can be edited
in a text field, and a FILEPATH while similar to a
STRING should also provide a way to locate filesystem
paths using a file dialog.  An entry of type STRING
may provide a restricted list of allowed values which are
then provided in a drop-down menu in the
cmake-gui(1) user interface (see the
STRINGS cache property).

The CMake files shipped with a software package may also
define boolean toggle options using the option()
command.  The command creates a cache entry which has a
help text and a default value.  Such cache entries are
typically specific to the provided software and affect
the configuration of the build, such as whether tests
and examples are built, whether to build with exceptions
enabled etc.

Presets¶

CMake understands a file, CMakePresets.json, and its
user-specific counterpart, CMakeUserPresets.json, for
saving presets for commonly-used configure settings. These
presets can set the build directory, generator, cache
variables, environment variables, and other command-line
options. All of these options can be overridden by the
user. The full details of the CMakePresets.json format
are listed in the cmake-presets(7) manual.

Using presets on the command-line¶

When using the cmake(1) command line tool, a
preset can be invoked by using the --preset
option. If --preset is specified,
the generator and build directory are not required, but can be
specified to override them. For example, if you have the following
CMakePresets.json file:

{
  "version": 1,
  "configurePresets": [
    {
      "name": "ninja-release",
      "binaryDir": "${sourceDir}/build/${presetName}",
      "generator": "Ninja",
      "cacheVariables": {
        "CMAKE_BUILD_TYPE": "Release"
      }
    }
  ]
}

and you run the following:

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

This will generate a build directory in
/path/to/source/build/ninja-release with the
Ninja generator, and with
CMAKE_BUILD_TYPE set to Release.

If you want to see the list of available presets, you can
run:

cmake -S /path/to/source --list-presets

This will list the presets available in
/path/to/source/CMakePresets.json and
/path/to/source/CMakeUsersPresets.json without
generating a build tree.

Using presets in cmake-gui¶

If a project has presets available, either through
CMakePresets.json or CMakeUserPresets.json, the
list of presets will appear in a drop-down menu in
cmake-gui(1) between the source directory and
the binary directory. Choosing a preset sets the binary
directory, generator, environment variables, and cache
variables, but all of these options can be overridden after
a preset is selected.

Invoking the Buildsystem¶

After generating the buildsystem, the software can be
built by invoking the particular build tool.  In the
case of the IDE generators, this can involve loading
the generated project file into the IDE to invoke the
build.

CMake is aware of the specific build tool needed to invoke
a build so in general, to build a buildsystem or project
from the command line after generating, the following
command may be invoked in the build directory:

$ cmake --build .

The --build flag enables a
particular mode of operation for the cmake(1)
tool.  It invokes the  CMAKE_MAKE_PROGRAM
command associated with the
generator, or
the build tool configured by the user.

The --build mode also accepts
the parameter --target to
specify a particular target to build, for example a
particular library, executable or custom target, or a
particular special target like install:

$ cmake --build . --target myexe

The --build mode also accepts a
--config parameter
in the case of multi-config generators to specify which
particular configuration to build:

$ cmake --build . --target myexe --config Release

The --config option has no
effect if the generator generates a buildsystem specific
to a configuration which is chosen when invoking cmake
with the CMAKE_BUILD_TYPE variable.

Some buildsystems omit details of command lines invoked
during the build.  The --verbose
flag can be used to cause those command lines to be shown:

$ cmake --build . --target myexe --verbose

The --build mode can also pass
particular command line options to the underlying build
tool by listing them after --.  This can be useful
to specify options to the build tool, such as to continue the
build after a failed job, where CMake does not
provide a high-level user interface.

For all generators, it is possible to run the underlying
build tool after invoking CMake.  For example, make
may be executed after generating with the
Unix Makefiles generator to invoke the build,
or ninja after generating with the Ninja
generator etc.  The IDE buildsystems usually provide
command line tooling for building a project which can
also be invoked.

Selecting a Target¶

Each executable and library described in the CMake files
is a build target, and the buildsystem may describe
custom targets, either for internal use, or for user
consumption, for example to create documentation.

CMake provides some built-in targets for all buildsystems
providing CMake files.

all

The default target used by Makefile and Ninja
generators.  Builds all targets in the buildsystem,
except those which are excluded by their
EXCLUDE_FROM_ALL target property or
EXCLUDE_FROM_ALL directory property.  The
name ALL_BUILD is used for this purpose for the
Xcode and Visual Studio generators.

help

Lists the targets available for build.  This target is
available when using the Unix Makefiles or
Ninja generator, and the exact output is
tool-specific.

clean

Delete built object files and other output files.  The
Makefile based generators create a clean target
per directory, so that an individual directory can be
cleaned.  The Ninja tool provides its own granular
-t clean system.

test

Runs tests.  This target is only automatically available
if the CMake files provide CTest-based tests.  See also
Running Tests.

install

Installs the software.  This target is only automatically
available if the software defines install rules with the
install() command.  See also
Software Installation.

package

Creates a binary package.  This target is only
automatically available if the CMake files provide
CPack-based packages.

package_source

Creates a source package.  This target is only
automatically available if the CMake files provide
CPack-based packages.

For Makefile based systems, /fast variants of binary
build targets are provided. The /fast variants are used
to build the specified target without regard for its
dependencies.  The dependencies are not checked and
are not rebuilt if out of date.  The Ninja
generator is sufficiently fast at dependency checking that
such targets are not provided for that generator.

Makefile based systems also provide build-targets to
preprocess, assemble and compile individual files in a
particular directory.

$ make foo.cpp.i
$ make foo.cpp.s
$ make foo.cpp.o

The file extension is built into the name of the target
because another file with the same name but a different
extension may exist.  However, build-targets without the
file extension are also provided.

$ make foo.i
$ make foo.s
$ make foo.o

In buildsystems which contain foo.c and foo.cpp,
building the foo.i target will preprocess both files.

Specifying a Build Program¶

The program invoked by the --build
mode is determined by the CMAKE_MAKE_PROGRAM variable.
For most generators, the particular program does not need to be
configured.

Generator

Default make program

Alternatives

XCode

xcodebuild

Unix Makefiles

make

NMake Makefiles

nmake

jom

NMake Makefiles JOM

jom

nmake

MinGW Makefiles

mingw32-make

MSYS Makefiles

make

Ninja

ninja

Visual Studio

msbuild

Watcom WMake

wmake

The jom tool is capable of reading makefiles of the
NMake flavor and building in parallel, while the
nmake tool always builds serially.  After generating
with the NMake Makefiles generator a user
can run jom instead of nmake.  The
--build
mode would also use jom if the
CMAKE_MAKE_PROGRAM was set to jom while
using the NMake Makefiles generator, and
as a convenience, the NMake Makefiles JOM
generator is provided to find jom in the normal way
and use it as the CMAKE_MAKE_PROGRAM. For
completeness, nmake is an alternative tool which
can process the output of the
NMake Makefiles JOM generator, but doing
so would be a pessimization.

Software Installation¶

The CMAKE_INSTALL_PREFIX variable can be
set in the CMake cache to specify where to install the
provided software.  If the provided software has install
rules, specified using the install() command,
they will install artifacts into that prefix.  On Windows,
the default installation location corresponds to the
ProgramFiles system directory which may be
architecture specific.  On Unix hosts, /usr/local is
the default installation location.

The CMAKE_INSTALL_PREFIX variable always
refers to the installation prefix on the target
filesystem.

In cross-compiling or packaging scenarios where the
sysroot is read-only or where the sysroot should otherwise
remain pristine, the CMAKE_STAGING_PREFIX
variable can be set to a location to actually install
the files.

The commands:

$ cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local \
  -DCMAKE_SYSROOT=$HOME/root \
  -DCMAKE_STAGING_PREFIX=/tmp/package
$ cmake --build .
$ cmake --build . --target install

result in files being installed to paths such
as /tmp/package/lib/libfoo.so on the host machine.
The /usr/local location on the host machine is
not affected.

Some provided software may specify uninstall rules,
but CMake does not generate such rules by default itself.

Running Tests¶

The ctest(1) tool is shipped with the CMake
distribution to execute provided tests and report
results.  The test build-target is provided to run
all available tests, but the ctest(1) tool
allows granular control over which tests to run, how to
run them, and how to report results.  Executing
ctest(1) in the build directory is equivalent
to running the test target:

$ ctest

A regular expression can be passed to run only tests
which match the expression.  To run only tests with
Qt in their name:

$ ctest -R Qt

Tests can be excluded by regular expression too.  To
run only tests without Qt in their name:

$ ctest -E Qt

Tests can be run in parallel by passing -j
arguments to ctest(1):

$ ctest -R Qt -j8

The environment variable CTEST_PARALLEL_LEVEL
can alternatively be set to avoid the need to pass
-j.

By default ctest(1) does not print the output
from the tests. The command line argument -V
(or --verbose) enables verbose mode to print the
output from all tests.
The --output-on-failure
option prints the test output for failing tests only.
The environment variable CTEST_OUTPUT_ON_FAILURE
can be set to 1 as an alternative to passing the
--output-on-failure
option to ctest(1).

Table of Contents

User Interaction Guide

Introduction

Command Line cmake tool

cmake-gui tool

Generating a Buildsystem

Command line environment

Command line -G option

Choosing a generator in cmake-gui

Setting Build Variables

Setting variables on the command line

Setting variables with cmake-gui

The CMake Cache

Presets

Using presets on the command-line

Using presets in cmake-gui

Invoking the Buildsystem

Selecting a Target

Specifying a Build Program

Software Installation

Running Tests

Previous topic

Step 12: Packaging Debug and Release

Next topic

Using Dependencies Guide

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

User Interaction Guide

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>Using Dependencies Guide — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/cmake.css" />

    <link rel="icon" href="../../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Importing and Exporting Guide" href="../importing-exporting/index.html" />
    <link rel="prev" title="User Interaction Guide" href="../user-interaction/index.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

Using Dependencies Guide

Using Dependencies Guide¶

Contents

Using Dependencies Guide

Introduction

Using Pre-built Packages With find_package()

Config-file packages

Find Module Files

Imported Targets

Downloading And Building From Source With FetchContent

FetchContent And find_package() Integration

Dependency Providers

Introduction¶

Projects will frequently depend on other projects, assets, and artifacts.
CMake provides a number of ways to incorporate such things into the build.
Projects and users have the flexibility to choose between methods that
best suit their needs.

The primary methods of bringing dependencies into the build are the
find_package() command and the FetchContent module.
The FindPkgConfig module is also sometimes used, although it
lacks some of the integration of the other two and is not discussed any
further in this guide.

Dependencies can also be made available by a custom
dependency provider.
This might be a third party package manager, or it might be custom code
implemented by the developer.  Dependency providers co-operate with the
primary methods mentioned above to extend their flexibility.

Using Pre-built Packages With find_package()¶

A package needed by the project may already be built and available at some
location on the user's system.  That package might have also been built by
CMake, or it could have used a different build system entirely.  It might
even just be a collection of files that didn't need to be built at all.
CMake provides the find_package() command for these scenarios.
It searches well-known locations, along with additional hints and paths
provided by the project or user.  It also supports package components and
packages being optional.  Result variables are provided to allow the project
to customize its own behavior according to whether the package or specific
components were found.

In most cases, projects should generally use the Basic Signature.
Most of the time, this will involve just the package name, maybe a version
constraint, and the REQUIRED keyword if the dependency is not optional.
A set of package components may also be specified.

Examples of find_package() basic signature¶

find_package(Catch2)
find_package(GTest REQUIRED)
find_package(Boost 1.79 COMPONENTS date_time)

The find_package() command supports two main methods for carrying
out the search:

Config mode

With this method, the command looks for files that are typically provided
by the package itself.  This is the more reliable method of the two, since
the package details should always be in sync with the package.

Module mode

Not all packages are CMake-aware. Many don't provide the files needed to
support config mode.  For such cases, a Find module file can be provided
separately, either by the project or by CMake.  A Find module is typically
a heuristic implementation which knows what the package normally provides
and how to present that package to the project.  Since Find modules are
usually distributed separately from the package, they are not as reliable.
They are typically maintained separately, and they are likely to follow
different release schedules, so they can easily become out-of-date.

Depending on the arguments used, find_package() may use one or both
of the above methods.  By restricting the options to just the basic signature,
both config mode and module mode can be used to satisfy the dependency.
The presence of other options may restrict the call to using only one of the
two methods, potentially reducing the command's ability to find the dependency.
See the find_package() documentation for full details about this
complex topic.

For both search methods, the user can also set cache variables on the
cmake(1) command line or in the ccmake(1) or
cmake-gui(1) UI tools to influence and override where to find
packages. See the User Interaction Guide
for more on how to set cache variables.

Config-file packages¶

The preferred way for a third party to provide executables, libraries,
headers, and other files for use with CMake is to provide
config files.  These are text files shipped
with the package, which define CMake targets, variables, commands, and so on.
The config file is an ordinary CMake script, which is read in by the
find_package() command.

The config files can usually be found in a directory whose name matches the
pattern lib/cmake/<PackageName>, although they may be in other locations
instead (see Config Mode Search Procedure).  The <PackageName> is usually the
first argument to the find_package() command, and it may even be the
only argument.  Alternative names can also be specified with the NAMES
option:

Providing alternative names when finding a package¶

find_package(SomeThing
  NAMES
    SameThingOtherName   # Another name for the package
    SomeThing            # Also still look for its canonical name
)

The config file must be named either <PackageName>Config.cmake or
<LowercasePackageName>-config.cmake (the former is used for the remainder
of this guide, but both are supported).  This file is the entry point
to the package for CMake.  A separate optional file named
<PackageName>ConfigVersion.cmake or
<LowercasePackageName>-config-version.cmake may also exist in the same
directory.  This file is used by CMake to determine whether the version of
the package satisfies any version constraint included in the call to
find_package().  It is optional to specify a version when calling
find_package(), even if a <PackageName>ConfigVersion.cmake
file is present.

If the <PackageName>Config.cmake file is found and any version constraint
is satisfied, the find_package() command considers the package to be
found, and the entire package is assumed to be complete as designed.

There may be additional files providing CMake commands or
Imported Targets for you to use.  CMake does not enforce any naming
convention for these files.  They are related to the primary
<PackageName>Config.cmake file by use of the CMake include()
command.  The <PackageName>Config.cmake file would typically include
these for you, so they won't usually require any additional step other than
the call to find_package().

If the location of the package is in a
directory known to CMake, the
find_package() call should succeed.  The directories known to CMake
are platform-specific.  For example, packages installed on Linux with a
standard system package manager will be found in the /usr prefix
automatically.  Packages installed in Program Files on Windows will
similarly be found automatically.

Packages will not be found automatically without help if they are in
locations not known to CMake, such as /opt/mylib or $HOME/dev/prefix.
This is a normal situation, and CMake provides several ways for users to
specify where to find such libraries.

The CMAKE_PREFIX_PATH variable may be
set when invoking CMake.
It is treated as a list of base paths in which to search for
config files.  A package installed in
/opt/somepackage will typically install config files such as
/opt/somepackage/lib/cmake/somePackage/SomePackageConfig.cmake.
In that case, /opt/somepackage should be added to
CMAKE_PREFIX_PATH.

The environment variable CMAKE_PREFIX_PATH may also be populated with
prefixes to search for packages.  Like the PATH environment variable,
this is a list, but it needs to use the platform-specific environment variable
list item separator (: on Unix and ; on Windows).

The CMAKE_PREFIX_PATH variable provides convenience in cases
where multiple prefixes need to be specified, or when multiple packages
are available under the same prefix.  Paths to packages may also be
specified by setting variables matching <PackageName>_DIR, such as
SomePackage_DIR.  Note that this is not a prefix, but should be a full
path to a directory containing a config-style package file, such as
/opt/somepackage/lib/cmake/SomePackage in the above example.
See the find_package() documentation for other CMake variables and
environment variables that can affect the search.

Find Module Files¶

Packages which do not provide config files can still be found with the
find_package() command, if a FindSomePackage.cmake file is
available.  These Find module files are different to config files in that:

Find module files should not be provided by the package itself.

The availability of a Find<PackageName>.cmake file does not indicate
the availability of the package, or any particular part of the package.

CMake does not search the locations specified in the
CMAKE_PREFIX_PATH variable for Find<PackageName>.cmake
files.  Instead, CMake searches for such files in the locations given
by the CMAKE_MODULE_PATH variable.  It is common for users to
set the CMAKE_MODULE_PATH when running CMake, and it is common
for CMake projects to append to CMAKE_MODULE_PATH to allow use
of local Find module files.

CMake ships Find<PackageName>.cmake files for some
third party packages.  These files are a
maintenance burden for CMake, and it is not unusual for these to fall
behind the latest releases of the packages they are associated with.
In general, new Find modules are not added to CMake any more.  Projects
should encourage the upstream packages to provide a config file where
possible.  If that is unsuccessful, the project should provide its own
Find module for the package.

See Find Modules for a detailed discussion of how to write a
Find module file.

Imported Targets¶

Both config files and Find module files can define Imported Targets.
These will typically have names of the form SomePrefix::ThingName.
Where these are available, the project should prefer to use them instead of
any CMake variables that may also be provided.  Such targets typically carry
usage requirements and apply things like header search paths, compiler
definitions, etc. automatically to other targets that link to them (e.g. using
target_link_libraries()).  This is both more robust and more
convenient than trying to apply the same things manually using variables.
Check the documentation for the package or Find module to see what imported
targets it defines, if any.

Imported targets should also encapsulate any configuration-specific paths.
This includes the location of binaries (libraries, executables), compiler
flags, and any other configuration-dependent quantities.  Find modules may
be less reliable in providing these details than config files.

A complete example which finds a third party package and uses a library
from it might look like the following:

cmake_minimum_required(VERSION 3.10)
project(MyExeProject VERSION 1.0.0)

# Make project-provided Find modules available
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

find_package(SomePackage REQUIRED)
add_executable(MyExe main.cpp)
target_link_libraries(MyExe PRIVATE SomePrefix::LibName)

Note that the above call to find_package() could be resolved by
a config file or a Find module.  It uses only the basic arguments supported
by the Basic Signature.  A FindSomePackage.cmake file in the
${CMAKE_CURRENT_SOURCE_DIR}/cmake directory would allow the
find_package() command to succeed using module mode, for example.
If no such module file is present, the system would be searched for a config
file.

Downloading And Building From Source With FetchContent¶

Dependencies do not necessarily have to be pre-built in order to use them
with CMake.  They can be built from sources as part of the main project.
The FetchContent module provides functionality to download
content (typically sources, but can be anything) and add it to the main
project if the dependency also uses CMake.  The dependency's sources will
be built along with the rest of the project, just as though the sources were
part of the project's own sources.

The general pattern is that the project should first declare all the
dependencies it wants to use, then ask for them to be made available.
The following demonstrates the principle (see Examples
for more):

include(FetchContent)
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)
FetchContent_Declare(
  Catch2
  GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  GIT_TAG        605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
)
FetchContent_MakeAvailable(googletest Catch2)

Various download methods are supported, including downloading and extracting
archives from a URL (a range of archive formats are supported), and a number
of repository formats including Git, Subversion, and Mercurial.
Custom download, update, and patch commands can also be used to support
arbitrary use cases.

When a dependency is added to the project with FetchContent, the
project links to the dependency's targets just like any other target from the
project.  If the dependency provides namespaced targets of the form
SomePrefix::ThingName, the project should link to those rather than to
any non-namespaced targets.  See the next section for why this is recommended.

Not all dependencies can be brought into the project this way.  Some
dependencies define targets whose names clash with other targets from the
project or other dependencies.  Concrete executable and library targets
created by add_executable() and add_library() are global,
so each one must be unique across the whole build.  If a dependency would
add a clashing target name, it cannot be brought directly into the build
with this method.

FetchContent And find_package() Integration¶

New in version 3.24.

Some dependencies support being added by either find_package() or
FetchContent.  Such dependencies must ensure they define the same
namespaced targets in both installed and built-from-source scenarios.
A consuming project then links to those namespaced targets and can handle
both scenarios transparently, as long as the project does not use anything
else that isn't provided by both methods.

The project can indicate it is happy to accept a dependency by either method
using the FIND_PACKAGE_ARGS option to FetchContent_Declare().
This allows FetchContent_MakeAvailable() to try satisfying the
dependency with a call to find_package() first, using the arguments
after the FIND_PACKAGE_ARGS keyword, if any.  If that doesn't find the
dependency, it is built from source as described previously instead.

include(FetchContent)
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  FIND_PACKAGE_ARGS NAMES GTest
)
FetchContent_MakeAvailable(googletest)

add_executable(ThingUnitTest thing_ut.cpp)
target_link_libraries(ThingUnitTest GTest::gtest_main)

The above example calls
find_package(googletest NAMES GTest) first.
CMake provides a FindGTest module, so if that finds a GTest package
installed somewhere, it will make it available, and the dependency will not be
built from source.  If no GTest package is found, it will be built from
source.  In either case, the GTest::gtest_main target is expected to be
defined, so we link our unit test executable to that target.

High-level control is also available through the
FETCHCONTENT_TRY_FIND_PACKAGE_MODE variable.  This can be set to
NEVER to disable all redirection to find_package().  It can be
set to ALWAYS to try find_package() even if FIND_PACKAGE_ARGS
was not specified (this should be used with caution).

The project might also decide that a particular dependency must be built from
source.  This might be needed if a patched or unreleased version of the
dependency is required, or to satisfy some policy that requires all
dependencies to be built from source.  The project can enforce this by adding
the OVERRIDE_FIND_PACKAGE keyword to FetchContent_Declare().
A call to find_package() for that dependency will then be redirected
to FetchContent_MakeAvailable() instead.

include(FetchContent)
FetchContent_Declare(
  Catch2
  URL https://intranet.mycomp.com/vendored/Catch2_2.13.4_patched.tgz
  URL_HASH MD5=abc123...
  OVERRIDE_FIND_PACKAGE
)

# The following is automatically redirected to FetchContent_MakeAvailable(Catch2)
find_package(Catch2)

For more advanced use cases, see the
CMAKE_FIND_PACKAGE_REDIRECTS_DIR variable.

Dependency Providers¶

New in version 3.24.

The preceding section discussed techniques that projects can use to specify
their dependencies.  Ideally, the project shouldn't really care where a
dependency comes from, as long as it provides the things it expects (often
just some imported targets).  The project says what it needs and may also
specify where to get it from, in the absence of any other details, so that it
can still be built out-of-the-box.

The developer, on the other hand, may be much more interested in controlling
how a dependency is provided to the project.  You might want to use a
particular version of a package that you built yourself.  You might want
to use a third party package manager.  You might want to redirect some
requests to a different URL on a system you control for security or
performance reasons.  CMake supports these sort of scenarios through
Dependency Providers.

A dependency provider can be set to intercept find_package() and
FetchContent_MakeAvailable() calls.  The provider is given an
opportunity to satisfy such requests before falling back to the built-in
implementation if the provider doesn't fulfill it.

Only one dependency provider can be set, and it can only be set at a very
specific point early in the CMake run.
The CMAKE_PROJECT_TOP_LEVEL_INCLUDES variable lists CMake files
that will be read while processing the first project() call (and
only that call).  This is the only time a dependency provider may be set.
At most, one single provider is expected to be used throughout the whole
project.

For some scenarios, the user wouldn't need to know the details of how the
dependency provider is set.  A third party may provide a file that can be
added to CMAKE_PROJECT_TOP_LEVEL_INCLUDES, which will set up
the dependency provider on the user's behalf.  This is the recommended
approach for package managers.  The developer can use such a file like so:

cmake -DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=/path/to/package_manager/setup.cmake ...

For details on how to implement your own custom dependency provider, see the
cmake_language(SET_DEPENDENCY_PROVIDER) command.

Table of Contents

Using Dependencies Guide

Introduction

Using Pre-built Packages With find_package()

Config-file packages

Find Module Files

Imported Targets

Downloading And Building From Source With FetchContent

FetchContent And find_package() Integration

Dependency Providers

Previous topic

User Interaction Guide

Next topic

Importing and Exporting Guide

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.29.0-rc3 Documentation »

Using Dependencies Guide

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.


code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

  <title>CMake Reference Documentation — CMake 3.29.0-rc3 Documentation</title>

    <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="_static/cmake.css" />

    <link rel="icon" href="_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="cmake(1)" href="manual/cmake.1.html" />

Navigation

          index

          next |

    CMake »

    3.29.0-rc3 Documentation »

CMake Reference Documentation

Introduction¶

CMake is a tool to manage building of source code.  Originally, CMake was
designed as a generator for various dialects of Makefile, today
CMake generates modern buildsystems such as Ninja as well as project
files for IDEs such as Visual Studio and Xcode.

CMake is widely used for the C and C++ languages, but it may be used to
build source code of other languages too.

People encountering CMake for the first time may have different initial
goals.  To learn how to build a source code package downloaded from the
internet, start with the User Interaction Guide.
This will detail the steps needed to run the cmake(1) or
cmake-gui(1) executable and how to choose a generator, and
how to complete the build.

The Using Dependencies Guide is aimed at developers
wishing to get started using a third-party library.

For developers starting a project using CMake, the CMake Tutorial
is a suitable starting point.  The cmake-buildsystem(7)
manual is aimed at developers expanding their knowledge of maintaining
a buildsystem and becoming familiar with the build targets that
can be represented in CMake.  The cmake-packages(7) manual
explains how to create packages which can easily be consumed by
third-party CMake-based buildsystems.

Command-Line Tools¶

cmake(1)

ctest(1)

cpack(1)

Interactive Dialogs¶

cmake-gui(1)

ccmake(1)

Reference Manuals¶

cmake-buildsystem(7)

cmake-commands(7)

cmake-compile-features(7)

cmake-configure-log(7)

cmake-cxxmodules(7)

cmake-developer(7)

cmake-env-variables(7)

cmake-file-api(7)

cmake-generator-expressions(7)

cmake-generators(7)

cmake-language(7)

cmake-modules(7)

cmake-packages(7)

cmake-policies(7)

cmake-presets(7)

cmake-properties(7)

cmake-qt(7)

cmake-server(7)

cmake-toolchains(7)

cmake-variables(7)

cpack-generators(7)

Guides¶

CMake Tutorial

User Interaction Guide

Using Dependencies Guide

Importing and Exporting Guide

IDE Integration Guide

Release Notes¶

CMake Release Notes

Index and Search¶

Index

Search Page

Table of Contents

Introduction

Command-Line Tools

Interactive Dialogs

Reference Manuals

Guides

Release Notes

Index and Search

Next topic

cmake(1)

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          next |

    CMake »

    3.29.0-rc3 Documentation »

CMake Reference Documentation

        © Copyright 2000-2024 Kitware, Inc. and Contributors.
      Created using Sphinx 6.2.1.