CMake projects in Visual Studio

CMake is a cantankerous-platform, open-source tool for defining build processes that run on multiple platforms. This article assumes you're familiar with CMake. For more than information about CMake, see the CMake documentation. The CMake tutorial is a good starting point to learn more.

Note

CMake has become more and more integrated with Visual Studio over the by few releases. To see the documentation for your preferred version of Visual Studio, use the Version selector control. Information technology's plant at the meridian of the table of contents on this folio.

Visual Studio's native support for CMake enables you to edit, build, and debug CMake projects on Windows, the Windows Subsystem for Linux (WSL), and remote systems from the same instance of Visual Studio. CMake projection files (such as CMakeLists.txt ) are consumed directly by Visual Studio for the purposes of IntelliSense and browsing. cmake.exe is invoked straight by Visual Studio for CMake configuration and build.

Installation

C++ CMake tools for Windows is installed every bit part of the Desktop development with C++ and Linux Development with C++ workloads. Both C++ CMake tools for Windows and Linux Development with C++ are required for cross-platform CMake development.

Screenshot of the Desktop development with C plus plus dropdown selected and the C plus plus C Make tools for Windows option called out.

For more information, see Install the C++ Linux workload in Visual Studio.

IDE integration

When you open a folder containing a CMakeLists.txt file, the following things happen.

A screenshot of the Start Window in Visual Studio.

  • Visual Studio adds CMake items to the Project menu, with commands for viewing and editing CMake scripts.

  • The Solution Explorer displays the folder structure and files.

  • Visual Studio runs CMake and generates the CMake cache file ( CMakeCache.txt ) for the default configuration. The CMake command line is displayed in the Output Window, along with other output from CMake.

  • In the background, Visual Studio starts to index the source files to enable IntelliSense, browsing information, refactoring, and so on. Equally you work, Visual Studio monitors changes in the editor and too on disk to keep its index in sync with the sources.

Note

Starting in Visual Studio 2022 version 17.1 Preview 2, if your folder doesn't contain a root CMakeLists.txt you'll be prompted whether you'd similar to enable CMake integration or not. For more than information, see CMake partial activation.

Once CMake enshroud generation has succeeded, you tin can also view your projects organized logically by targets. Choose the Select View button on the Solution Explorer toolbar. From the listing in Solution Explorer - Views, select CMake Targets View and printing Enter to open the targets view:

Screenshot of the Solution Explorer Views window with the C Make Targets View highlighted.

Cull the Show All Files button at the top of Solution Explorer to see all the CMake-generated output in the out/build/<config> folders.

Apply the CMakeLists.txt file in each projection folder just as you would in whatever CMake project. You can specify source files, find libraries, set compiler and linker options, and specify other build system-related information. For more data on CMake language services provided by Visual Studio, come across Editing CMakeLists.txt files.

Visual Studio uses a CMake configuration file to drive CMake enshroud generation and build. For more than data, see Configuring CMake projects and Edifice CMake projects.

To pass arguments to an executable at debug time, y'all tin can utilize another file called launch.vs.json . For more information on debugging cross-platform CMake projects in Visual Studio, see Debugging CMake projects.

Near Visual Studio and C++ language features are supported by CMake projects in Visual Studio. Examples include:

  • Edit and Continue for CMake projects

  • Incredibuild integration for CMake projects

  • AddressSanitizer support for CMake projects

  • Clang/LLVM support

Notation

For other kinds of Open up Binder projects, an additional JSON file CppProperties.json is used. This file is non relevant for CMake projects.

Configuring CMake projects

The CMake configure step generates the projection build system. It's equivalent to invoking cmake.exe from the command line. For more information on the CMake configure step, see the CMake documentation.

Visual Studio uses a CMake configuration file to drive CMake generation and build. CMakePresets.json is supported by Visual Studio 2019 version xvi.ten or after and is the recommended CMake configuration file. CMakePresets.json is supported direct past CMake and tin can be used to drive CMake generation and build from Visual Studio, from VS Code, in a Continuous Integration pipeline, and from the control line on Windows, Linux, and Mac. For more than information on CMakePresets.json , see Configure and build with CMake Presets. CMakeSettings.json is available for customers using an earlier version of Visual Studio. For more than information on CMakeSettings.json , see Customize CMake build settings.

When yous make significant changes to your CMake configuration file or a CMakeLists.txt file, Visual Studio volition automatically run the CMake configure step. You lot tin can invoke the configure footstep manually: Select Projection > Configure Cache from the toolbar. Y'all can besides change your configuration preferences in Tools > Options > CMake > General.

CMake configuration options.

If the configure step finishes without errors, then the information that's available drives C++ IntelliSense and language services. It'south also used in build and debug operations.

Y'all tin can also open an existing CMake cache in Visual Studio. For more data, see Open an existing enshroud.

Customize configuration feedback and notifications

Past default, well-nigh configuration messages are suppressed unless at that place's an error. To see all messages, select Tools > Options > CMake > Enable verbose CMake diagnostic output.

You can as well disable all CMake enshroud notifications (gilded bars) past deselecting Show CMake cache notification.

Troubleshooting CMake cache errors

If you need more information about the state of the CMake cache to diagnose a problem, open up the Project main menu or the CMakeLists.txt context menu in Solution Explorer to run one of these commands:

  • View CMakeCache.txt opens the CMakeCache.txt file from the build directory in the editor. Whatever edits you lot make hither to CMakeCache.txt are wiped out if you lot make clean the cache. To make changes that persist after yous make clean the enshroud, meet Customize CMake settings or Configure and build with CMake Presets.

  • Delete Cache and Reconfigure deletes the build directory and reconfigures from a clean cache.

  • Configure Enshroud forces the generate step to run even if Visual Studio considers the environment upwardly to date.

Edifice CMake projects

The CMake build step builds an already generated projection binary tree. It's equivalent to invoking cmake --build from the command line. For more information on the CMake build pace, run across the CMake documentation.

To build a CMake projection, you have these choices:

  1. In the toolbar, find the Startup Item dropdown. Select the preferred target and printing F5, or choose the Run button on the toolbar. The project automatically builds first, just similar a Visual Studio solution.

  2. Right-click on CMake target with CMake Targets View active in the Solution Explorer and select Build from the context menu.

  3. From the principal menu, select Build > Build All. Make sure that a CMake target is already selected in the Startup Item dropdown in the toolbar.

Equally you would expect, build results are shown in the Output Window and Error Listing.

CMake build errors.

Edit build settings

Visual Studio uses a CMake configuration file to drive CMake builds. CMake configuration files encapsulate build options like native build tool switches and environment variables. If CMakePresets.json is your active configuration file, see Configure and build with CMake Presets. If CMakeSettings.json is your active configuration file, see Customize CMake build settings. CMakePresets.json is available in Visual Studio 2019 version 16.10 or later and is the recommended CMake configuration file.

Debugging CMake projects

All executable CMake targets are shown in the Startup Particular dropdown in the toolbar. To outset debugging, select ane and press the Debug > Commencement Debugging push in the toolbar. In a CMake project, the "Current document" option is only valid for .cpp files.

A screenshot of the Startup Item dropdown in a CMake project.

The Debug or F5 commands first build the projection if changes accept been made since the previous build. Changes to the CMake configuration file ( CMakePresets.json or CMakeSettings.json ) or a CMakeLists.txt causes the CMake enshroud to be regenerated.

Yous can customize a CMake debugging session by setting properties in the launch.vs.json file. To customize debug settings for a specific target, select the target in the Startup Item dropdown and press Debug > Debug and Launch Settings for <active-target>. For more information on CMake debugging sessions, see Configure CMake debugging sessions.

Just My Code for CMake projects

When y'all build for Windows using the MSVC compiler, CMake projects have support for But My Code debugging. To alter the Just My Code setting, go to Tools > Options > Debugging > General.

Edit and Continue for CMake projects

When you lot build for Windows with the MSVC compiler, CMake projects take support for Edit and Continue. Add the following code to your CMakeLists.txt file to enable Edit and Continue.

                if(MSVC)   target_compile_options(<target> PUBLIC "/ZI")   target_link_options(<target> PUBLIC "/INCREMENTAL") endif()                              

Attach to a CMake project running on Linux

Visual Studio allows you to debug a process running on a remote Linux system or WSL and debug it with the GDB debugger. To become started, select Debug > Attach to Process..., set the Connection type to SSH, and select your Connectedness target from the list of connections in the Connexion Manager. Select a process from the list of available processes and press Attach. GDB must be installed on your Linux machine. For more information on SSH connections, meet the Connexion Manager

A screenshot of the Attach to Process menu.

CMake partial activation

In Visual Studio 2022 version 17.1 and later, CMake functionality won't be enabled automatically if your root binder doesn't comprise a CMakeLists.txt file. Instead, a dialog will prompt you on whether y'all'd like to enable CMake functionality for your project. If yous reject, CMake cache generation won't start and CMake configurations (from CMakeSettings.json or CMakePresets.json) won't announced in the configuration dropdown. If you have, yous'll be taken to a workspace-level configuration file, CMakeWorkspaceSettings.json (stored in the .vs directory), to specify the folders y'all'd like to enable CMake for. (These folders comprise your root CMakeLists.txt files).

The accustomed properties are:

Property Description
enableCMake Enable Visual Studio's integration for this workspace.
sourceDirectory A string or array of strings specifying the directory or directories with CMakeLists.txt. Macros (such equally ${workspaceRoot}) are allowed. Relative paths are based on the workspace root. Directories outside of the current workspace will exist ignored.

Y'all can achieve CMakeWorkspaceSettings.json through the Project > CMake Workspace Settings carte command at whatsoever time, fifty-fifty if CMake functionality is currently disabled.

Open an existing cache

When you open an existing CMake cache file ( CMakeCache.txt ), Visual Studio doesn't try to manage your cache and build tree for yous. Your custom or preferred tools have complete control over how CMake configures your project.

Y'all can add an existing CMake cache to an open project. It'southward done the aforementioned manner y'all'd add a new configuration. For more information, encounter our web log post on opening an existing cache in Visual Studio.

Notation

The default existing enshroud experience relies on cmake-server, which was removed from CMake in version iii.twenty. To continue using existing enshroud functionality in Visual Studio 2019 version 16.10 and later, have one of these steps:

  • Manually install CMake version 3.19 or lower. Then, set the cmakeExecutable holding in your existing cache configuration to employ that version of CMake.
  • In your existing enshroud configuration, prepare the cacheGenerationCommand holding to let Visual Studio request the necessary CMake file-based API files. For more information on that holding, see CMakeSettings.json reference.
  • Use a query file to asking the CMake file-based API files when generating your cache before information technology'southward opened in Visual Studio. For query file instructions, run into the next section, Advanced CMake cache troubleshooting.

Avant-garde CMake enshroud troubleshooting

Visual Studio uses the CMake file-based API (in versions 3.14 and later) to populate the editor with information specific to your project structure. For more than data, run into the C++ team weblog post on multi-root workspaces and file-based API.

Before generating the CMake cache, your custom or preferred tools may need to create a query file named .cmake/api/v1/query/client-MicrosoftVS/query.json in your build output folder (the folder that contains CMakeCache.txt ). The query file should incorporate this content:

                {"requests":[{"kind":"cache","version":2},{"kind":"cmakeFiles","version":one},{"kind":"codemodel","version":two}]}                              

When your custom or preferred tools generate your cache, CMake places files under .cmake/api/v1/response that Visual Studio uses to populate the editor with information specific to your project structure.

Editing CMakeLists.txt files

To edit a CMakeLists.txt file, right-click on the file in Solution Explorer and choose Open. If y'all make changes to the file, a yellow condition bar appears and informs you that IntelliSense will update. It gives you a chance to cancel the update operation. For information about CMakeLists.txt , see the CMake documentation.

CMakeLists.txt file editing.

As soon as you save the file, the configuration step automatically runs again and displays information in the Output window. Errors and warnings are shown in the Error List or Output window. Double-click on an fault in the Error List to navigate to the offending line in CMakeLists.txt .

CMakeLists.txt file errors.

Language services for CMake

Language services for CMake are available in Visual Studio 2019 version xvi.5 or after. Information technology supports code navigation features like Go To Definition, Peek Definition, and Detect All References for CMake variables, functions, and targets in CMake script files. For more information, see Lawmaking Navigation for CMake Scripts.

Find All References on a CMake variable, target, or function.

CMake projection manipulation

CMake projection manipulation is available in Visual Studio 2019 version 16.5 or later. Project manipulation enables you to add, remove, and rename source files and targets in your CMake project without manually editing your CMake scripts. When you add or remove files from the Solution Explorer, Visual Studio automatically edits your CMake project. There could be more than than one place where information technology makes sense to add or remove a reference to a CMake script. If so, Visual Studio asks yous where you want to make the change and displays a preview of the proposed changes. For step-by-stride instructions, see Add, Remove, and Rename Files and Targets in CMake Projects.

Resolving ambiguity with CMake project manipulation.

IntelliSense for CMake projects

By default, Visual Studio uses the IntelliSense mode that matches the compiler and target architecture specified by the active CMake configuration.

If CMakePresets.json is your active CMake configuration file, then you lot tin can specify IntelliSense options using intelliSenseMode and intelliSenseOptions in the Visual Studio Settings vendor map. For more information, encounter the Visual Studio Settings vendor map reference.

If CMakeSettings.json is your agile CMake configuration file, and so you can specify IntelliSense options using intelliSenseMode in CMakeSettings.json . For more information, see the CMakeSettings.json reference.

Configure IntelliSense with CMake toolchain files

In Visual Studio 2019 version xvi.9 and after, Visual Studio automatically configures IntelliSense in CMake projects based on CMake variables when you use a CMake toolchain file. For more information, encounter Configure IntelliSense with CMake Toolchain Files.

Vcpkg integration

CMake projects opened in Visual Studio integrate with vcpkg, a cross-platform C/C++ dependency manager. Earlier using vcpkg with Visual Studio, yous must run vcpkg integrate install. For instructions and more information on vcpkg, encounter the vcpkg documentation.

If CMakeSettings.json is your agile configuration file, Visual Studio automatically passes the vcpkg toolchain file (vcpkg.cmake) to CMake. This behavior is disabled automatically when yous specify any other toolchain in your CMake Settings configuration.

If CMakePresets.json is your active configuration file, you'll need to prepare the path to vcpkg.cmake in CMakePresets.json . We recommend using the VCPKG_ROOT environment variable instead of an accented path to go along the file shareable. For more than information, see Enable vcpkg integration with CMake Presets. CMakePresets.json is bachelor in Visual Studio 2019 version 16.10 or later and is the recommended CMake configuration file.

Run CMake from the control line

If CMakePresets.json is your active CMake configuration file, then you can hands reproduce your local builds outside of Visual Studio. For more than data, see Run CMake from the command line or a CI pipeline. CMakePresets.json is supported in Visual Studio 2019 version 16.10 or afterwards and is the recommended CMake configuration file.

If CMakeSettings.json is your active CMake configuration file, so you'll need to manually laissez passer the arguments that are encoded in your CMakeSettings.json file to CMake. If you have installed CMake from the Visual Studio Installer, you can run it from the command line by following these steps:

  1. Run the appropriate vsdevcmd.bat file (x86/x64). For more information, see Building on the command line .

  2. Switch to your output folder.

  3. Run CMake to build or configure your app.

Visual Studio 2017 has rich support for CMake, including cantankerous-platform CMake projects. The Visual C++ Tools for CMake component uses the Open Folder feature to enable the IDE to consume CMake project files (such equally CMakeLists.txt ) directly for the purposes of IntelliSense and browsing. Both Ninja and Visual Studio generators are supported. If yous use a Visual Studio generator, information technology generates a temporary projection file and passes it to MSBuild. However, the project is never loaded for IntelliSense or browsing purposes. You as well can import an existing CMake cache.

Installation

Visual C++ Tools for CMake is installed as part of the Desktop evolution with C++ and Linux Evolution with C++ workloads.

Screenshot of the Individual components tab with the Visual C plus plus tools for C make option called out.

For more than information, see Install the C++ Linux workload in Visual Studio.

IDE integration

When you cull File > Open up > Folder to open a folder containing a CMakeLists.txt file, the following things happen:

  • Visual Studio adds a CMake menu particular to the primary carte du jour, with commands for viewing and editing CMake scripts.

  • Solution Explorer displays the binder structure and files.

  • Visual Studio runs CMake and optionally generates the CMake cache for the default configuration, which is x86 Debug. The CMake control line is displayed in the Output Window, along with other output from CMake.

  • In the background, Visual Studio starts to alphabetize the source files to enable IntelliSense, browsing information, refactoring, and then on. As y'all work, Visual Studio monitors changes in the editor and likewise on disk to keep its index in sync with the sources.

Y'all can open folders containing whatever number of CMake projects. Visual Studio detects and configures all the "root" CMakeLists.txt files in your workspace. CMake operations (configure, build, debug), C++ IntelliSense, and browsing are available to all CMake projects in your workspace.

CMake project with multiple roots.

Y'all tin also view your projects organized logically by targets. Cull Targets view from the dropdown in the Solution Explorer toolbar:

CMake targets view button.

Visual Studio uses a file called CMakeSettings.json to shop surround variables or command-line options for CMake. CMakeSettings.json likewise enables you lot to define and store multiple CMake build configurations. You can conveniently switch between them in the IDE.

Otherwise, use the CMakeLists.txt only every bit you would in any CMake project to specify source files, find libraries, set compiler and linker options, and specify other build system-related information.

If you need to pass arguments to an executable at debug time, you can use some other file called launch.vs.json . In some scenarios, Visual Studio automatically generates these files. You can edit them manually, or fifty-fifty create the file yourself.

Notation

For other kinds of Open Folder projects, two additional JSON files are used: CppProperties.json and tasks.vs.json . Neither of these are relevant for CMake projects.

Import an existing enshroud

When you import an existing CMakeCache.txt file, Visual Studio automatically extracts customized variables and creates a pre-populated CMakeSettings.json file based on them. The original cache isn't modified in any mode. It can still be used from the command line, or with any tool or IDE used to generate it. The new CMakeSettings.json file is placed alongside the project's root CMakeLists.txt . Visual Studio generates a new cache based the settings file. You lot tin can override automatic cache generation in the Tools > Options > CMake > General dialog.

Non everything in the cache is imported. Properties such as the generator and the location of the compilers are replaced with defaults that are known to work well with the IDE.

To import an existing cache

  1. From the principal menu, choose File > Open > CMake:

    Open CMake.

    This command brings up the Import CMake from Cache wizard.

  2. Navigate to the CMakeCache.txt file that you want to import, and and then choose OK. The Import CMake Project from Enshroud wizard appears:

    Import a CMake cache.

    When the wizard completes, you can come across the new CMakeCache.txt file in Solution Explorer next to the root CMakeLists.txt file in your project.

Building CMake projects

To build a CMake project, you accept these choices:

  1. In the Full general toolbar, observe the Configurations dropdown. It's probably showing "Linux-Debug" or "x64-Debug" by default. Select the preferred configuration and press F5, or cull the Run (light-green triangle) push on the toolbar. The project automatically builds showtime, just similar a Visual Studio solution.

  2. Right-click on CMakeLists.txt in Solution Explorer and select Build from the context menu. If y'all accept multiple targets in your folder construction, you can choose to build all or simply 1 specific target.

  3. From the primary menu, select Build > Build Solution (F7 or Ctrl+Shift+B). Make sure that a CMake target is already selected in the Startup Item dropdown in the Full general toolbar.

CMake build menu command.

You lot tin can customize build configurations, environs variables, control-line arguments, and other settings in the CMakeSettings.json file. It lets you make changes without modifying the CMakeLists.txt file. For more than information, see Customize CMake settings.

As you would wait, build results are shown in the Output Window and Mistake List.

CMake build errors.

In a folder with multiple build targets, you lot can specify which CMake target to build: Choose the Build item on the CMake menu or the CMakeLists.txt context carte to specify the target. If you enter Ctrl+Shift+B in a CMake projection, it builds the current active document.

Debugging CMake projects

To debug a CMake projection, choose the preferred configuration and press F5. Or, press the Run button in the toolbar. If the Run button says "Select Startup Item", select the dropdown arrow and choose the target that you want to run. (In a CMake project, the "Current certificate" option is simply valid for .cpp files.)

CMake run button.

The Run or F5 commands start build the projection if changes accept been fabricated since the previous build.

Yous can customize a CMake debugging session by setting properties in the launch.vs.json file. For more information, see Configure CMake debugging sessions.

Editing CMakeLists.txt files

To edit a CMakeLists.txt file, right-click on the file in Solution Explorer and choose Open. If you make changes to the file, a xanthous status bar appears and informs y'all that IntelliSense volition update. Information technology gives you a risk to cancel the update performance. For information about CMakeLists.txt , see the CMake documentation.

CMakeLists.txt file editing.

Equally soon every bit you lot save the file, the configuration footstep automatically runs again and displays data in the Output window. Errors and warnings are shown in the Error Listing or Output window. Double-click on an error in the Error List to navigate to the offending line in CMakeLists.txt .

CMakeLists.txt file errors.

CMake configure step

When significant changes are made to the CMakeSettings.json or to CMakeLists.txt files, Visual Studio automatically reruns the CMake configure pace. If the configure footstep finishes without errors, the information that's collected is bachelor in C++ IntelliSense and language services. It's also used in build and debug operations.

Multiple CMake projects may apply the aforementioned CMake configuration name (for example, x86-Debug). All of them are configured and built (in their own build root folder) when that configuration is selected. Y'all can debug the targets from all of the CMake projects that participate in that CMake configuration.

CMake Build Only menu item.

Yous tin limit builds and debug sessions to a subset of the projects in the workspace. Create a new configuration with a unique name in the CMakeSettings.json file. Then, utilize the configuration to those projects only. When that configuration is selected, IntelliSense and the build and debug commands only apply to those specified projects.

Troubleshooting CMake enshroud errors

If yous need more information almost the state of the CMake cache to diagnose a problem, open the CMake main menu or the CMakeLists.txt context carte du jour in Solution Explorer to run one of these commands:

  • View Enshroud opens the CMakeCache.txt file from the build root folder in the editor. (Any edits y'all make hither to CMakeCache.txt are wiped out if you clean the cache. To make changes that persist after the cache is cleaned, see Customize CMake settings.)

  • Open Cache Binder opens an Explorer window to the build root binder.

  • Clean Cache deletes the build root binder so that the adjacent CMake configure footstep starts from a clean cache.

  • Generate Enshroud forces the generate step to run even if Visual Studio considers the environment up to engagement.

Automated cache generation can be disabled in the Tools > Options > CMake > General dialog.

Single file compilation

To build a unmarried file in a CMake project, right-click on the file in Solution Explorer. Cull Compile from the popular-up menu. You can likewise build the currently open up file in the editor by using the main CMake menu:

CMake single file compilation.

Run CMake from the command line

If you have installed CMake from the Visual Studio Installer, you can run it from the command line by following these steps:

  1. Run the appropriate vsdevcmd.bat file (x86/x64). For more information, see Edifice on the Command Line.

  2. Switch to your output folder.

  3. Run CMake to build or configure your app.

In Visual Studio 2015, Visual Studio users tin can use a CMake generator to generate MSBuild projection files, which the IDE so consumes for IntelliSense, browsing, and compilation.

Encounter likewise

Tutorial: Create C++ cross-platform projects in Visual Studio
Configure a Linux CMake project
Connect to your remote Linux computer
Customize CMake build settings
CMakeSettings.json schema reference
Configure CMake debugging sessions
Deploy, run, and debug your Linux projection
CMake predefined configuration reference