User Interaction Guide — CMake 4.0.0-rc5 Documentation (2025)

Introduction

Where a software package supplies a CMake-based buildsystemwith the source of their software, the consumer of thesoftware is required to run a CMake user interaction toolin order to build it.

Well-behaved CMake-based buildsystems do not create anyoutput in the source directory, so typically, the userperforms an out-of-source build and performs the buildthere. First, CMake must be instructed to generate asuitable buildsystem, then the user invokes a build toolto process that generated buildsystem. The generatedbuildsystem is specific to the machine used to generateit and is not redistributable. Each consumer of a providedsource software package is required to use CMake togenerate a buildsystem specific to their system.

Generated buildsystems should generally be treated asread-only. The CMake files as a primary artifact shouldcompletely specify the buildsystem and there should be noreason to populate properties manually in an IDE forexample after generating the buildsystem. CMake willperiodically rewrite the generated buildsystem, somodifications by users will be overwritten.

The features and user interfaces described in this manualare available for all CMake-based build systems by virtueof providing CMake files.

The CMake tooling may report errors to the user whenprocessing provided CMake files, such as reporting thatthe compiler is not supported, or the compiler does notsupport a required compile option, or a dependency cannot be found. These errors must be resolved by the userby 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 freshcopy of software source code is to create a build directoryand 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 thesource because that keeps the source directory pristine,allows for building a single source with multipletoolchains, and allows easy clearing of build artifacts bysimply deleting the build directory.

The CMake tooling may report warnings which are intendedfor the provider of the software, not intended for theconsumer of the software. Such warnings end with "Thiswarning is for project developers". Users may disablesuch warnings by passing the -Wno-devflag to cmake(1).

cmake-gui tool

Users more accustomed to GUI interfaces may use thecmake-gui(1) tool to invoke CMake and generatea buildsystem.

The source and binary directories must first bepopulated. It is always advised to use differentdirectories for the source and the build.

User Interaction Guide — CMake 4.0.0-rc5 Documentation (1)

Generating a Buildsystem

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

Command line environment

When invoking cmake(1) with a command linebuildsystem such as Makefiles or Ninja, it isnecessary to use the correct build environment toensure that build tools are available. CMake must beable to find the appropriatebuild tool,compiler, linker and other tools as needed.

On Linux systems, the appropriate tools are oftenprovided in system-wide locations and may be readilyinstalled through the system package manager. Othertoolchains provided by the user or installed innon-default locations can also be used.

When cross-compiling, some platforms may requireenvironment variables to be set or may providescripts to set the environment.

Visual Studio ships multiple command prompts andvcvarsall.bat scripts for setting up thecorrect environments for command line buildsystems. Whilenot strictly necessary to use a correspondingcommand line environment when using a Visual Studiogenerator, doing so has no disadvantages.

When using Xcode, there can be more than one Xcodeversion installed. Which one to use can be selectedin a number of different ways, but the most commonmethods are:

  • Setting the default version in the preferencesof the Xcode IDE.

  • Setting the default version via the xcode-selectcommand line tool.

  • Overriding the default version by setting theDEVELOPER_DIR environment variable when runningCMake and the build tool.

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

Command line -G option

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

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

$ cmake .. -G Ninja

The output of cmake --help includes a list ofgenerators availablefor the user to choose from. Note that generatornames are case sensitive.

On Unix-like systems (including Mac OS X), theUnix Makefiles generator is used bydefault. A variant of that generator can also be usedon Windows in various environments, such as theNMake Makefiles andMinGW Makefiles generator. These generatorsgenerate a Makefile variant which can be executedwith make, gmake, nmake or similar tools.See the individual generator documentation for moreinformation on targeted environments and tools.

The Ninja generator is available on allmajor platforms. ninja is a build tool similarin use-cases to make, but with a focus onperformance and efficiency.

On Windows, cmake(1) can be used to generatesolutions for the Visual Studio IDE. Visual Studioversions may be specified by the product name of theIDE, which includes a four-digit year. Aliases areprovided for other means by which Visual Studioversions are sometimes referred to, such as twodigits which correspond to the product version of theVisualC++ 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 x64cmake .. -G "Visual Studio 16" -A ARMcmake .. -G "Visual Studio 16 2019" -A ARM64

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

Some IDEs such as KDevelop4, QtCreator and CLion havenative support for CMake-based buildsystems. Those IDEsprovide user interface for selecting an underlyinggenerator to use, typically a choice between a Makefileor a Ninja based generator.

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

When generating Visual Studio project and solutionsfiles several other options are available to use wheninitially running cmake(1).

The Visual Studio toolset can be specified with thecmake -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 specifydetails of the toolchain used. For example, -Thost=x64can be given to select the 64-bit version of the hosttools. The following demonstrates how to use 64-bittools 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 toselect the CMake generator to use.

User Interaction Guide — CMake 4.0.0-rc5 Documentation (2)

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

User Interaction Guide — CMake 4.0.0-rc5 Documentation (3)

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

User Interaction Guide — CMake 4.0.0-rc5 Documentation (4)

Setting Build Variables

Software projects often require variables to beset on the command line when invoking CMake. Some ofthe most commonly used CMake variables are listed inthe table below:

Variable

Meaning

CMAKE_PREFIX_PATH

Path to search fordependent packages

CMAKE_MODULE_PATH

Path to search for additional CMake modules

CMAKE_BUILD_TYPE

Build configuration, such asDebug or Release, determiningdebug/optimization flags. This is onlyrelevant for single-configuration buildsystems suchas Makefile and Ninja. Multi-configurationbuildsystems such as those for Visual Studio and Xcodeignore this setting.

CMAKE_INSTALL_PREFIX

Location to install thesoftware to with theinstall build target

CMAKE_TOOLCHAIN_FILE

File containing cross-compilingdata such astoolchains and sysroots.

BUILD_SHARED_LIBS

Whether to build sharedinstead of static librariesfor add_library()commands used without a type

CMAKE_EXPORT_COMPILE_COMMANDS

Generate a compile_commands.jsonfile for use with clang-based tools

CMAKE_EXPORT_BUILD_DATABASE

Generate a build_database.jsonfile for use with clang-based tools

Other project-specific variables may be availableto control builds, such as enabling or disablingcomponents of the project.

There is no convention provided by CMake for howsuch variables are named between differentprovided buildsystems, except that variables withthe prefix CMAKE_ usually refer to optionsprovided by CMake itself and should not be usedin third-party options, which should usetheir own prefix instead. Thecmake-gui(1) tool can display optionsin groups defined by their prefix, so it makessense for third parties to ensure that they use aself-consistent prefix.

Setting variables on the command line

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

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

or later on a subsequent invocation ofcmake(1):

$ cd build$ cmake . -DCMAKE_BUILD_TYPE=Debug

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

$ cd build$ cmake . -UMyPackage_DIR

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

The cmake(1) tool allows specifying afile to use to populate the initial cache usingthe -C option. This can be useful to simplifycommands and scripts which repeatedly require thesame 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 ofthe variable.

User Interaction Guide — CMake 4.0.0-rc5 Documentation (5)

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

The CMake Cache

When CMake is executed, it needs to find the locations ofcompilers, tools and dependencies. It also needs to beable to consistently re-generate a buildsystem to use thesame compile/link flags and paths to dependencies. Suchparameters are also required to be configurable by theuser because they are paths and options specific to theusers system.

When it is first executed, CMake generates aCMakeCache.txt file in the build directory containingkey-value pairs for such artifacts. The cache file can beviewed or edited by the user by running thecmake-gui(1) or ccmake(1) tool. Thetools provide an interactive interface for re-configuringthe provided software and re-generating the buildsystem,as is needed after editing cached values. Each cacheentry may have an associated short help text which isdisplayed in the user interface tools.

The cache entries may also have a type to signify how itshould be presented in the user interface. For example,a cache entry of type BOOL can be edited by acheckbox in a user interface, a STRING can be editedin a text field, and a FILEPATH while similar to aSTRING should also provide a way to locate filesystempaths using a file dialog. An entry of type STRINGmay provide a restricted list of allowed values which arethen provided in a drop-down menu in thecmake-gui(1) user interface (see theSTRINGS cache property).

The CMake files shipped with a software package may alsodefine boolean toggle options using the option()command. The command creates a cache entry which has ahelp text and a default value. Such cache entries aretypically specific to the provided software and affectthe configuration of the build, such as whether testsand examples are built, whether to build with exceptionsenabled etc.

Presets

CMake understands a file, CMakePresets.json, and itsuser-specific counterpart, CMakeUserPresets.json, forsaving presets for commonly-used configure settings. Thesepresets can set the build directory, generator, cachevariables, environment variables, and other command-lineoptions. All of these options can be overridden by theuser. The full details of the CMakePresets.json formatare listed in the cmake-presets(7) manual.

Using presets on the command-line

When using the cmake(1) command line tool, apreset can be invoked by using the --presetoption. If --preset is specified,the generator and build directory are not required, but can bespecified to override them. For example, if you have the followingCMakePresets.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 theNinja generator, and withCMAKE_BUILD_TYPE set to Release.

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

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 withoutgenerating a build tree.

Using presets in cmake-gui

If a project has presets available, either throughCMakePresets.json or CMakeUserPresets.json, thelist of presets will appear in a drop-down menu incmake-gui(1) between the source directory andthe binary directory. Choosing a preset sets the binarydirectory, generator, environment variables, and cachevariables, but all of these options can be overridden aftera preset is selected.

Invoking the Buildsystem

After generating the buildsystem, the software can bebuilt by invoking the particular build tool. In thecase of the IDE generators, this can involve loadingthe generated project file into the IDE to invoke thebuild.

CMake is aware of the specific build tool needed to invokea build so in general, to build a buildsystem or projectfrom the command line after generating, the followingcommand may be invoked in the build directory:

$ cmake --build .

The --build flag enables aparticular mode of operation for the cmake(1)tool. It invokes the CMAKE_MAKE_PROGRAMcommand associated with thegenerator, orthe build tool configured by the user.

The --build mode also acceptsthe parameter --target tospecify a particular target to build, for example aparticular library, executable or custom target, or aparticular special target like install:

$ cmake --build . --target myexe

The --build mode also accepts a--config parameterin the case of multi-config generators to specify whichparticular configuration to build:

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

The --config option has noeffect if the generator generates a buildsystem specificto a configuration which is chosen when invoking cmakewith the CMAKE_BUILD_TYPE variable.

Some buildsystems omit details of command lines invokedduring the build. The --verboseflag can be used to cause those command lines to be shown:

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

The --build mode can also passparticular command line options to the underlying buildtool by listing them after --. This can be usefulto specify options to the build tool, such as to continue thebuild after a failed job, where CMake does notprovide a high-level user interface.

For all generators, it is possible to run the underlyingbuild tool after invoking CMake. For example, makemay be executed after generating with theUnix Makefiles generator to invoke the build,or ninja after generating with the Ninjagenerator etc. The IDE buildsystems usually providecommand line tooling for building a project which canalso be invoked.

Selecting a Target

Each executable and library described in the CMake filesis a build target, and the buildsystem may describecustom targets, either for internal use, or for userconsumption, for example to create documentation.

CMake provides some built-in targets for all buildsystemsproviding CMake files.

all

The default target used by Makefile and Ninjagenerators. Builds all targets in the buildsystem,except those which are excluded by theirEXCLUDE_FROM_ALL target property orEXCLUDE_FROM_ALL directory property. Thename ALL_BUILD is used for this purpose for theXcode and Visual Studio generators.

help

Lists the targets available for build. This target isavailable when using the Unix Makefiles orNinja generator, and the exact output istool-specific.

clean

Delete built object files and other output files. TheMakefile based generators create a clean targetper directory, so that an individual directory can becleaned. The Ninja tool provides its own granular-t clean system.

test

Runs tests. This target is only automatically availableif the CMake files provide CTest-based tests. See alsoRunning Tests.

install

Installs the software. This target is only automaticallyavailable if the software defines install rules with theinstall() command. See alsoSoftware Installation.

package

Creates a binary package. This target is onlyautomatically available if the CMake files provideCPack-based packages.

package_source

Creates a source package. This target is onlyautomatically available if the CMake files provideCPack-based packages.

For Makefile based systems, /fast variants of binarybuild targets are provided. The /fast variants are usedto build the specified target without regard for itsdependencies. The dependencies are not checked andare not rebuilt if out of date. The Ninjagenerator is sufficiently fast at dependency checking thatsuch targets are not provided for that generator.

Makefile based systems also provide build-targets topreprocess, assemble and compile individual files in aparticular directory.

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

The file extension is built into the name of the targetbecause another file with the same name but a differentextension may exist. However, build-targets without thefile 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 --buildmode is determined by the CMAKE_MAKE_PROGRAM variable.For most generators, the particular program does not need to beconfigured.

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 theNMake flavor and building in parallel, while thenmake tool always builds serially. After generatingwith the NMake Makefiles generator a usercan run jom instead of nmake. The--buildmode would also use jom if theCMAKE_MAKE_PROGRAM was set to jom whileusing the NMake Makefiles generator, andas a convenience, the NMake Makefiles JOMgenerator is provided to find jom in the normal wayand use it as the CMAKE_MAKE_PROGRAM. Forcompleteness, nmake is an alternative tool whichcan process the output of theNMake Makefiles JOM generator, but doingso would be a pessimization.

Software Installation

The CMAKE_INSTALL_PREFIX variable can beset in the CMake cache to specify where to install theprovided software. If the provided software has installrules, specified using the install() command,they will install artifacts into that prefix. On Windows,the default installation location corresponds to theProgramFiles system directory which may bearchitecture specific. On Unix hosts, /usr/local isthe default installation location.

The CMAKE_INSTALL_PREFIX variable alwaysrefers to the installation prefix on the targetfilesystem.

In cross-compiling or packaging scenarios where thesysroot is read-only or where the sysroot should otherwiseremain pristine, the CMAKE_STAGING_PREFIXvariable can be set to a location to actually installthe 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 suchas /tmp/package/lib/libfoo.so on the host machine.The /usr/local location on the host machine isnot 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 CMakedistribution to execute provided tests and reportresults. The test build-target is provided to runall available tests, but the ctest(1) toolallows granular control over which tests to run, how torun them, and how to report results. Executingctest(1) in the build directory is equivalentto running the test target:

$ ctest

A regular expression can be passed to run only testswhich match the expression. To run only tests withQt in their name:

$ ctest -R Qt

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

$ ctest -E Qt

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

$ ctest -R Qt -j8

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

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

User Interaction Guide — CMake 4.0.0-rc5 Documentation (2025)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Van Hayes

Last Updated:

Views: 6326

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.