I am a researcher working at the intersection of computer vision, robotics, agricultural automation, and plant phenotyping.

© 2018 - 2024. All rights reserved.

Last updated: January 27, 2024.

CMake: How to specify the compiler in CMakeLists.txt.

Setting the compiler for a CMake project is a couple lines in the CMakeLists.txt file, and they have to go in a very specific place – before the project command.

CMake-ians will likely object to this method, since there are other command line methods to set the compiler. When I am debugging something, and particularly when that something depends on a specific compiler, I don’t want to have to remember all the details – I want the details baked into the project.

Troubleshooting with cmake: delete everything in the build directory and try running CMake configuration and generation again.

More details, GitLab about methods for setting the compiler.

Share or discuss.

Share on Twitter . Share on Facebook . Share on LinkedIn .

Related Posts

C-plus-plus, my favorite print debugging method in c++. 03 jul 2023, cmake: conditional and logical expression syntax. 06 dec 2022, cmake: how to force reconfiguration. 29 nov 2022, mixing c and c++ in one file. 27 nov 2022, cmake: create a list and iterate over it to set source properties. 01 nov 2022.

© Amy Tabb 2018 - 2024. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Configure and build with CMake Presets in Visual Studio

  • 13 contributors

CMake supports two files that allow users to specify common configure, build, and test options and share them with others: CMakePresets.json and CMakeUserPresets.json . Use these files to drive CMake in Visual Studio and Visual Studio Code, in a continuous integration (CI) pipeline, and from the command line.

CMakePresets.json is for saving project-wide builds. CMakeUserPresets.json is for developers to save their own local builds. Both files are supported in Visual Studio 2019 version 16.10 or later.

This article contains information about CMakePresets.json integration with Visual Studio. Here are helpful links:

  • For more information about the format of CMakePresets.json , see the official CMake documentation .
  • For more information about the Microsoft vendor maps and macro expansion, see CMakePresets.json and CMakeUserPresets.json Microsoft vendor maps .
  • For more information about how to use CMakePresets.json in Visual Studio Code, see Configure and build with CMake Presets .

We recommend CMakePresets.json as an alternative to CMakeSettings.json . Visual Studio never reads from both CMakePresets.json and CMakeSettings.json at the same time. To enable or disable CMakePresets.json integration in Visual Studio, see Enable CMakePresets.json in Visual Studio 2019 .

Supported CMake and CMakePresets.json versions

The supported CMakePresets.json and CMakeUserPresets.json schema versions depend on your version of Visual Studio:

  • Visual Studio 2019 version 16.10 and later support schema versions 2 and 3.
  • Visual Studio 2022 version 17.4 preview 1 adds support for schema version 4.
  • Visual Studio 2022 version 17.5 preview 1 adds support for schema version 5.

You can update the version by changing the "version" field in the root object. For an example and more information, see CMakePresets.json format .

CMake version 3.20 or later is required when you're invoking CMake with CMakePresets.json from the command line. However, Visual Studio reads and evaluates CMakePresets.json and CMakeUserPresets.json itself and doesn't invoke CMake directly with the --preset option. So, CMake version 3.20 or later isn't strictly required when you're building with CMakePresets.json inside Visual Studio.

We recommend using at least CMake version 3.14 or later.

Enable CMakePresets.json integration in Visual Studio

CMakePresets.json integration isn't enabled by default in Visual Studio. You can enable it in Tools > Options > CMake > General :

Screenshot showing 'Always use CMakePresets.json' selected.

This screen is reached from the Visual Studio 2022 menu: Tools > Options > CMake > General. The option is under the CMake configure file section.

Close and reopen the folder in Visual Studio to activate the integration.

In some older versions of Visual Studio, Tools > Options > CMake > General only has a single option to enable CMakePresets.json integration:

Screenshot of an older version of Visual Studio. There is a checkbox labeled 'Use C Make Presets .json to drive CMake configure, build, and test.'

The following table indicates when CMakePresets.json is used instead of CMakeSettings.json to drive CMake configuration and build in Visual Studio 2022 and Visual Studio 2019 version 16.10 and later. If no configuration file is present, default Configure Presets are used.

In the table, " Tools > Options enabled" means Use CMakePresets.json to drive CMake configure, build, and test is selected in Tools > Options > CMake > General .

Modify automatic configuration and cache notifications

By default, Visual Studio automatically invokes configure each time the active Target System or Configure Preset changes. You can modify this behavior by selecting Never run configure step automatically in Tools > Options > CMake > General . You can also disable all CMake cache notifications (gold bars) by clearing Show CMake cache notifications .

Default Configure Presets

If no CMakePresets.json or CMakeUserPresets.json file exists, or if CMakePresets.json or CMakeUserPresets.json is invalid, Visual Studio falls back on the following default Configure Presets:

Windows example

Linux example.

If you try to open or modify a CMakePresets.json file that doesn't exist, Visual Studio automatically creates a CMakePresets.json file with the default Configure Presets at the root of your project.

Configure and build

On the Visual Studio toolbar, there are dropdowns for the Target Systems, Configure Presets, and Build Presets when CMakePresets.json integration is enabled:

Screenshot showing the dropdowns for target system set to Local Machine, configuration set to windows-arm64, and build preset set to default.

Select a Target System

The dropdown list on the left indicates the active Target System . It's the system on which CMake is invoked to configure and build the project. This dropdown list includes your local machine, all SSH connections in Connection Manager by host name, and all Windows Subsystem for Linux (WSL) installations that Visual Studio can find:

Screenshot of the Target System dropdown list

The dropdown list contains several entries including Local Machine, an ip address 192.168.0.5, WSL: ubuntu2004, WSL: debian, and Manage Connections.

In the preceding example:

  • 192.168.0.5 is a remote Linux system that was added to Connection Manager.
  • ubuntu2004 and debian are WSL installations.

Select Manage Connections to open Connection Manager.

Select a Configure Preset

The dropdown list in the middle indicates the active Configure Preset . It's the configurePreset value that's used when CMake is invoked to generate the project build system. This dropdown list includes the union of non-hidden Configure Presets defined in CMakePresets.json and CMakeUserPresets.json .

Visual Studio uses the value of hostOS in the Microsoft Visual Studio Settings vendor map to hide Configure Presets that don't apply to the active Target System. For more information, see the entry for hostOS in the table under Visual Studio Settings vendor map .

Select Manage Configurations to open the CMakePresets.json file located at the root of the project. CMakePresets.json is created if it doesn't already exist.

Select a Build Preset

The dropdown list on the right indicates the active Build Preset . It's the buildPreset value that's used when CMake is invoked to build the project. This dropdown list includes the union of non-hidden Build Presets defined in CMakePresets.json and CMakeUserPresets.json .

All Build Presets are required to specify an associated configurePreset value. Visual Studio hides Build Presets that don't apply to the active Configure Preset. For more information, see the list of Build Presets .

If there are no Build Presets associated with the active Configure Preset, Visual Studio lists the default Build Preset. The default Build Preset is equivalent to passing cmake --build with no other arguments from the command line.

Visual Studio automatically tries to configure the project when it detects that the CMake cache is out of date. To manually invoke the configuration, select Project > Configure <project-name> from the main menu. It's the same as running cmake --preset <configurePreset> from the command line, where <configurePreset> is the name of the active Configure Preset.

To disable automatic cache generation, see Automatic configuration and cache notifications .

To build the entire project, select Build > Build All from the main menu. It's the same as running cmake --build --preset <buildPreset> from the command line, where <buildPreset> is the name of the active Build Preset.

To build a single target, switch to CMake Targets View in Solution Explorer. Then right-click any target and select Build from the shortcut menu.

Visual Studio 2019 doesn't support the buildPresets.targets option to build a subset of targets specified in CMakePresets.json .

CMakePresets.json supports two menu options in Visual Studio 2019:

  • Test > Run CTests for <project-name> invokes CTest and runs all tests associated with the active Configure Preset and Build Preset, with no other arguments passed to CTest.
  • Test > Run Test Preset for <configurePreset> expands to show all Test Presets associated with the active Configure Preset. Selecting a single Test Preset is the same as running ctest --preset <testPreset> from the command line, where <testPreset> is the name of the selected Test Preset. This option is unavailable if no Test Presets are defined for the active Configure Preset.

In Visual Studio 2019, Test Explorer isn't integrated with CMakePresets.json .

Add new presets

In Visual Studio 2019, all commands and preset templates modify CMakePresets.json . You can add new user-level presets by directly editing CMakeUserPresets.json .

Use a forward slash ( / ) for paths in CMakePresets.json and CMakeUserPresets.json .

Add new Configure Presets

To add a new Configure Preset to CMakePresets.json , from Solution Explorer , right-click CMakePresets.json from Folder View and select Add Configuration from the shortcut menu. The dialog to select a Configure Preset template appears:

Screenshot of the Add Configure Preset to the JSON file dialog. It contains entries such as Linux Debug, macOS Debug, x64 Debug, and so on.

Select the Windows x64 Debug template to configure on Windows systems. Select the Linux Debug template to configure on WSL and remote Linux systems. For more information about editing CMakePresets.json , see Edit presets .

The selected template is added to CMakePresets.json if it exists. Otherwise, the template is copied into a new CMakePresets.json file.

Add new Build Presets and Test Presets

Visual Studio 2019 doesn't offer templates for new Build Presets and Test Presets. You can add Build Presets and Test Presets by directly editing CMakePresets.json . For more information, see the list of Build Presets , the list of Test Presets , or an example CMakePresets.json file .

Edit presets

The official CMake documentation is the best resource for editing Configure Presets, Build Presets, and Test Presets. The following information is a subset of the CMake documentation that's especially relevant to Visual Studio developers.

Select your compilers

You can set C and C++ compilers by using cacheVariables.CMAKE_C_COMPILER and cacheVariables.CMAKE_CXX_COMPILER in a Configure Preset. It's equivalent to passing -D CMAKE_C_COMPILER=<value> and -D CMAKE_CXX_COMPILER=<value> to CMake from the command line. For more information, see CMAKE_<LANG>_COMPILER .

Use the following examples to build with cl.exe and clang-cl.exe from Visual Studio. The C++ Clang tools for Windows components must be installed for you to build with clang-cl .

Build with cl.exe :

Build with clang :

If you use either Visual Studio 16 2019 or Visual Studio 17 2022 as your generator, you can use the toolset Configure Preset to specify the ClangCL toolset:

For more information on generators that support the toolset specification, see CMAKE_GENERATOR_TOOLSET in the CMake documentation.

In Visual Studio 2019, you must explicitly specify a Clang IntelliSense mode when you're building with clang or clang-cl .

To reproduce these builds outside Visual Studio, see Run CMake from the command line or a CI pipeline .

To build on Linux or without the Visual C++ toolset, specify the name of a compiler on your PATH instance, or an environment variable that evaluates to the full path of a compiler. Full paths are discouraged so that the file can remain shareable. A preset that builds with GCC version 8 might look like this:

You can also set compilers with a CMake toolchain file. Toolchain files can be set with cacheVariables.CMAKE_TOOLCHAIN_FILE , which is equivalent to passing -D CMAKE_TOOLCHAIN_FILE=<value> to CMake from the command line. A CMake toolchain file is most often used for cross-compilation. For more information about authoring CMake toolchain files, see CMake toolchains .

Select your generator

The Windows and Linux Configure Preset templates both specify Ninja as the default generator. Other common generators are the Visual Studio Generators on Windows and Unix Makefiles on Linux and macOS. You can specify a new generator with the generator option in a Configure Preset. It's equivalent to passing -G to CMake from the command line.

Set architecture.strategy and toolset.strategy to set when you're building with a Visual Studio Generator. For more information, see CMake generators .

Select your configuration type

You can set the configuration type ( Debug or Release ) for single configuration generators by using cacheVariables.CMAKE_BUILD_TYPE . It's equivalent to passing -D CMAKE_BUILD_TYPE=<value> to CMake from the command line. For more information, see CMAKE_BUILD_TYPE .

Select your target and host architecture when building with the Visual C++ toolset

You can set the target architecture (x64, Win32, ARM64, or ARM) by using architecture.value . It's equivalent to passing -A to CMake from the command line. For more information, see Platform Selection .

Currently, Visual Studio Generators expect the Win32 syntax and command-line generators (like Ninja) expect the x86 syntax when you're building for x86.

You can set the host architecture (x64 or x86) and toolset by using toolset.value . It's equivalent to passing -T to CMake from the command line. For more information, see Toolset Selection .

The architecture.strategy and toolset.strategy values tell CMake how to handle the architecture and toolset fields. set means CMake sets the respective value, and external means CMake won't set the respective value.

We recommend using set with IDE generators like the Visual Studio Generator. Use external with command-line generators like Ninja. These values allow vendors like Visual Studio to supply the required environment before CMake is invoked. For more information about the architecture and toolset fields, see the list of Configure Presets .

If you don't want to source an environment, you can set architecture.strategy to external and architecture.value to unspecified . You might find it useful not to source an environment for any one of these reasons:

  • You use a toolset other than MSVC.
  • You use a custom toolchain, such as in embedded scenarios.
  • You don't need a specific environment to build.

For a full list of IDE generators that support the architecture field, see CMAKE_GENERATOR_PLATFORM . For a full list of IDE generators that support the toolset field, see CMAKE_GENERATOR_TOOLSET .

Use the following examples to target ARM64 with the Ninja generator, or to target Win32 (x86) with the Visual Studio 16 2019 generator:

Set and reference environment variables

You can set environment variables by using the environment map. Environment variables are inherited through the inherits field, but you can override them as you like.

A preset's environment is the union of its own environment and the environment from all its parents. If multiple inherits presets provide conflicting values for the same variable, the earlier preset in the inherits list is preferred. You can unset a variable inherited from another preset by setting it to null .

Environment variables set in a Configure Preset also automatically flow through to associated Build Presets and Test Presets, unless inheritConfigureEnvironment is set to false . For more information, see the list of Configure Presets .

You can reference environment variables by using the $env{<variable-name>} and $penv{<variable-name>} syntax. For more information, see Macro Expansion .

Configure IntelliSense for a cross-compiler

By default, Visual Studio uses the IntelliSense mode that matches your specified toolset and target architecture. If you're cross-compiling, you might need to manually specify the correct IntelliSense mode by using the intelliSenseMode option in the Visual Studio Settings vendor map. For more information, see the entry for intelliSenseMode in the table under Visual Studio Settings vendor map .

Configure and build on a remote system or the Windows Subsystem for Linux

With CMakePresets.json support in Visual Studio, you can easily configure and build your project on Windows, WSL, and remote systems. The steps to configure and build your project on Windows, a remote system, or WSL are the same. However, a few behaviors are specific to remote development.

${sourceDir} behavior in remote copy scenarios

In local scenarios (including WSL1), ${sourceDir} evaluates to the path to the project source directory that's open in Visual Studio. In remote copy scenarios, ${sourceDir} evaluates to the path to the project source directory on the Target System and not the project source directory on the local machine.

The value of sourceDir in the Visual Studio Remote Settings vendor map determines the project source directory on the Target System (defaults to $env{HOME}/.vs/$ms{projectDirName} ). For more information, see the entry for sourceDir in the table under Visual Studio Settings vendor map .

Local folder for remote output

Remote copy scenarios require a local directory to copy some remote files like CMake File API response files or build files if copyBuildOutput in the Visual Studio Remote Settings vendor map is set to true . These files are automatically copied to <local-source-directory>/out/<remote-connection-ID>/build/${presetName} .

Invoking the same Configure Preset on Windows and WSL1

You'll see an error if you try to use the same Configure Preset on Windows and WSL1. Windows and WSL1 both use the Windows file system, so CMake will try to use the same output directory ( binaryDir ) for both the Windows and WSL1 build trees.

If you want to use the same Configure Preset with both Windows and the WSL1 toolset, create a second Configure Preset that inherits from the original preset and specifies a new binaryDir value. In the following example, windows-preset can be used on Windows and base-preset can be used on WSL1:

In Visual Studio 2019, only the WSL1 toolset is supported. You'll see this behavior any time you invoke configure on both Windows and WSL.

Enable vcpkg integration

Vcpkg helps you manage C and C++ libraries on Windows, Linux, and macOS. A vcpkg toolchain file ( vcpkg.cmake ) must be passed to CMake to enable vcpkg integration. For more information, see the vcpkg documentation .

Visual Studio no longer passes your vcpkg toolchain file to CMake automatically when CMakePresets.json integration is enabled. This change eliminates Visual Studio-specific behavior and ensures that you can reproduce your build from the command line.

Instead, set the path to vcpkg.cmake by using the VCPKG_ROOT environment variable in CMakePresets.json :

VCPKG_ROOT should be set to the root of your vcpkg installation. For more information, see vcpkg environment variables .

If you're already using a CMake toolchain file and want to enable vcpkg integration, see Using multiple toolchain files . Follow those instructions to use an external toolchain file with a project by using vcpkg.

Variable substitution in launch.vs.json and tasks.vs.json

CMakePresets.json supports variable substitution in launch.vs.json and tasks.vs.json . Here are some considerations:

Environment variables set in the active Configure Preset automatically flow through to launch.vs.json and tasks.vs.json configurations. You can unset individual environment variables in launch.vs.json and tasks.vs.json by setting them to null . The following example sets the variable DEBUG_LOGGING_LEVEL to null in launch.vs.json : "env": { "DEBUG_LOGGING_LEVEL": null } .

Key values set in the active Configure Preset are available for consumption in launch.vs.json and tasks.vs.json with the syntax ${cmake.<KEY-NAME>} . For example, use ${cmake.binaryDir} to reference the output directory of the active Configure Preset.

Individual environment variables set in the environment map of the active Configure Preset are available for consumption in launch.vs.json and tasks.vs.json through the syntax ${env.<VARIABLE-NAME>} .

Update your launch.vs.json and task.vs.json files to reference CMakePresets.json syntax instead of CMakeSettings.json syntax. Macros that reference the old CMakeSettings.json syntax when CMakePresets.json is the active configuration file are slated for deprecation in a future release. For example, reference the output directory of the active Configure Preset with ${cmake.binaryDir} instead of ${cmake.buildRoot} , because CMakePresets.json uses the binaryDir syntax.

Troubleshoot

If things aren't working as expected, you can try a few troubleshooting steps.

If either CMakePresets.json or CMakeUserPresets.json is invalid, Visual Studio will fall back on its default behavior and show only the default Configure Presets. Visual Studio IntelliSense can help you catch many of these JSON errors, but it won't know if you're referencing a preset with inherits or configurePreset by the wrong name.

To check if your preset files are valid, run cmake --list-presets from the command line at the root of your project directory. (CMake 3.20 or later is required.) If either file is invalid, you'll see the following error:

Other troubleshooting steps include:

  • Delete the cache and reconfigure the project ( CMake: Delete Cache and Project > Configure <project-name> ).
  • Close and reopen the folder in Visual Studio ( File > Close Folder ).
  • Delete the .vs folder at the root your project.

If you've identified a problem, the best way to report it is by selecting the Send Feedback button in the upper-right corner of Visual Studio.

Enable logging for remote connections

You can enable logging for remote connections if you're having trouble connecting or copying files to a remote system. For more information, see Logging for remote connections .

Enable AddressSanitizer for Windows and Linux

Visual Studio supports AddressSanitizer (ASAN), a C and C++ runtime memory error detector, for both Windows and Linux development. The addressSanitizerEnabled option in CMakeSettings.json enables AddressSanitizer. CMakePresets.json doesn't support this behavior.

Instead, enable and disable AddressSanitizer by setting the required compiler and linker flags yourself. Setting them removes Visual Studio-specific behavior and ensures that the same CMakePresets.json file can reproduce your build from the command line.

You can add the following sample to CMakeLists.txt to enable or disable AddressSanitizer for a target:

The <additional-options> part lists other compilation flags, like "-fno-omit-frame-pointer" . For more information about AddressSanitizer for Linux, see Using AddressSanitizer . For more information about using AddressSanitizer with MSVC, see Use AddressSanitizer from a developer command prompt .

Pass runtime flags to AddressSanitizer by using the ASAN_OPTIONS field in launch.vs.json . ASAN_OPTIONS defaults to detect_leaks=0 when no other runtime options are specified because LeakSanitizer isn't supported in Visual Studio.

Run CMake from the command line or a CI pipeline

You can use the same CMakePresets.json and CMakeUserPresets.json files to invoke CMake in Visual Studio and from the command line. The CMake and CTest documentation are the best resources for invoking CMake and CTest with --preset . CMake version 3.20 or later is required.

Sourcing the environment when building with command-line generators on Windows

It's up to the user to configure the environment before CMake is invoked in building with a command-line generator. If you're building with Ninja and the Visual C++ toolset on Windows, set the environment before CMake is called to generate the build system. You can do it by calling vcvarsall.bat with the architecture argument. The architecture argument specifies the host and target architecture to use. For more information, see vcvarsall syntax . If you build on Linux or on Windows with a Visual Studio Generator, you don't need to take this step.

It's the same step that Visual Studio takes for you when the IDE invokes CMake. Visual Studio parses the active Configure Preset for the host and target architecture specified by toolset and architecture . Visual Studio then sources the specified environment from vcvarsall.bat . When you build from the Windows command line with Ninja, you'll need to take this step yourself.

vcvarsall.bat is installed with the Build Tools for Visual Studio. By default, vcvarsall.bat is installed in C:\Program Files (x86)\Microsoft Visual Studio\2019\<edition>\VC\Auxiliary\Build . You can add vcvarsall.bat to PATH if you use the command-line workflow often.

Example command-line workflow

You can use the following commands to configure and build a CMake project that uses Ninja to target ARM64 with x64 build tools. CMake version 3.20 or later is required. Run these commands from the directory where your CMakePresets.json file is located:

Example CMakePresets.json file

The CMakePresets.json file in box2d-lite contains examples of Configure Presets, Build Presets, and Test Presets. For more information about this example, see the presentation An Introduction to CMakePresets.json . You can see another example in the DirectXTK project, which shows many build targets in its configurePresets section.

Learn more about configuring and debugging CMake projects in Visual Studio:

CMake Projects in Visual Studio Customize CMake build settings Configure CMake debugging sessions CMake predefined configuration reference

Submit and view feedback for

Additional resources

The Eclectic Coder

Sean bone's portfolio.

  • Build systems
  • Software Development

Using CMake to set preprocessor directives

Preprocessor flags.

C++ preprocessor directives are useful for many things. One use is to set flags from the command line in order to compile the program in different ways. For instance, we could have a DEBUG flag which, if set, gives us some extra feedback useful for debugging:

These options could be set from the command line when compiling the program, by prefixing their name with -D :

This is the equivalent of setting #define DEBUG at the beginning of main.cpp . You can also give it a value:

Is equivalent to writing #define DEBUG 1 in main.cpp .

Setting flags with CMake

If you use CMake however, you’re not writing the compilation command yourself. So, how can we achieve the same effect?

First, we will use CMake’s option() function to add a command-line option when running the cmake command:

Now we can set this option to ON when running CMake:

Then, we’ll use CMake’s add_definitions() function to set the corresponding preprocessor flag in our C++ program:

That’s all there is to it. Below you can find a sample CMake file with this functionality built into it:

' src=

set compiler define cmake

Visual Studio Code CMake Tools Extension 1.17 Update: CMake Presets v6, Overriding Cache Variables, and Side Bar Updates

set compiler define cmake

Sinem Akinci

February 13th, 2024 0 0

The February release of the CMake Tools extension in VS Code is now available. With this release, we have three major new updates to the extension, including some of our highly upvoted requests:

  • There is now support for CMake Presets v6, which includes the new workflow presets and package presets . ( Issue #2871 )
  • You can now pin common CMake Tools commands in the CMake side bar.
  • You can now override/add to cache variables and other settings when using CMake Presets ( Issue #1836 )

To view the full list of updates with this release, please look at our CHANGELOG . This release features 2 contributions from our open-source community, and we greatly thank you for your support!

CMake Presets v6 Support

Kitware has added two new CMake Presets in version 6: workflow and package presets. Workflow presets allow you to define a string of CMake presets that you want to execute (e.g.  a configure action followed by a build action). Package presets are presets that invoke CPack to package your software based on a variety of specifications. You can learn more about these presets from Kitware’s CMake Presets documentation. There is now added support to include these new preset types in your CMake presets file and invoke them through the extension.

With this added capability, you can select and run these presets by default from the CMake Side bar as you would any other preset.

The Cmake Sidebar in VS Code with Package and Workflow nodes highlighted and their relevant presets

Additionally, you can toggle the presets visibility across the side bar and status bar via the CMake Status Bar Visibility options through “ workflow ” , “ workflowPreset ” , and “ packagePreset ” settings. To learn more about the supported visibility options, please see our documentation .

While CMake Presets v7 and v8 do not have official support yet in the product, expansion of $penv{} in #include was added in the previous 1.16 release of the extension. We will be working to add the full support for v7 and v8 in upcoming releases.

Override/add to cache variables when using CMake Presets

One of our most highly-upvoted tickets was to add adjustments to CMake Presets by overriding/adding to cache variables. There are now new settings.json fields that modify configuration, build, and testing to override CMake Presets environments and arguments if you require this workflow. Specifically, these fields include:

Overrides any CMake command:

  • cmake.environment

Overrides configure CMake commands

  • cmake.configureArgs

Overrides build CMake commands

  • cmake.buildArgs
  • cmake.buildEnvironment
  • cmake.buildToolsArgs

Overrides test CMake commands

  • cmake.ctestArgs
  • cmake.testEnvironment

If there are settings set in any of the above fields, the affected CMake presets will display in the UI whether override settings have been applied for ease of tracking.

An example of cmake.configureArgs override showing in the UI that override settings are applied.

Additionally, a setting icon will appear that, when clicked, will open to the possible settings that may be affecting the configuration.

A Settings gear that allows you to view the settings overriding your Configure Preset.

Pin common CMake commands to side bar

If you commonly perform any type of CMake command, you can now pin these commands to the CMake side bar so that they’re easily accessible. To add a new CMake command to the side bar, navigate to the Pinned CMake Commands section and select the plus sign to search for a new CMake command to add.

An empty pinned commands pane in the CMake side bar with the option to add a new commands

To run any given command, just hover over the command and select the corresponding play button. You can also remove any command from the list by hovering over it, right-clicking, and selecting Unpin Command .

What’s next?

We have a lot of exciting new things planned for the 1.18 release including adding the first layers of CMake language services to the extension , adding tasks to the CMake side bar , and having an option for CMake to be automatically installed when missing via package manager . You can view these plans any time via our new GitHub project view .

Let our team know what else you would like to see from us by  adding an issue to our repo  or upvoting any existing issues with a thumbs up.

What do you think?

Download the  CMake Tools extension  for Visual Studio Code and let us know what you think. We would love to see what you contribute to our  repo  and we are active on reviews and collaboration. Comment below or reach us via email at  [email protected]  or via Twitter at  @VisualC .

set compiler define cmake

Sinem Akinci Program Manager II, Visual C++ Team

' data-src=

Leave a comment Cancel reply

Log in to join the discussion.

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

cmake tutorials problems

I have been having problems with going through cmake tutorials as I always get failures when invoking

Cmake build

Cmake –system-information

– Building for: Visual Studio 17 2022

CMake Error at CMakeLists.txt:6 (project):

No CMAKE_C_COMPILER could be found.

No CMAKE_CXX_COMPILER could be found.

Error: --system-information failed on internal CMake!

I am invoking the commands through a bash shell within Visual Code running on Windows 11. I have tried setting the ENV variables shown and CC , CXX.

To add to the consternation is if I run CMake Tools extension by using Quick Start everything works with the compiler referenced in the CMakeCache.txt in build.

This is kind of hard to debug since both methods are opaque to me at this point. It would be nice if you could set a cmake debug flag and it would just print.

I suspect there is something between the bash environment and the set of actions used by CMake: Quick tools in Visual Code.

I would like to continue with the tutorials but they all fail in a similar way. Getting in the way of Vulkan programming.

Which CMake version do you use?

Try to install current Version from cmake.org or:

You may also try the WindowsToolchain examples. use example/CMakePresets.json with

I actually tried that and fixed the paths within Visual Studio x64 environment. Didn’t help.

There is just something in the Cmake Tools vs cmake cli. I think that cmake cli is looking to qualify a compiler and it is failing. I am trying to use the x64 cl compiler installed with Visual Studio Community.

I am also trying to figure out how to debug/watch the cmake cli process but I have not yet figured out a logging mechanism Thanks, Frank

I am trying to use --preset but am unsure how to use it. I found a json file at C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMakeSettingsTemplates\CMakePresets.Windows.json

and the contents seem to indicate what I want. I have made some progress however it counter-intutive that I need this file in the project root directory.

CMake Tools in Visual Code sets it up correctly by referring to kits and setting to amd64 in my case. Works but not helpful when trying to work through a command line tutorial Thanks, Frank

Which tutorial do you mean?

cmake.org tutorial or vscode-cmake-tools tutorial ?

why not simple use cmake-gui?

Bildschirmfoto 2024-02-15 um 09.22.26

cmake.org tutorial and a few others.

Visual Code and its plugins are out of my scope.

Why not simply work with cmake-gui or cmake on bash ?

Well for education purposes of learning how it works.

:roll_eyes:

I’m working now on a different problem where the linker is not picking up system32 libraries in the x64-debug preset. More later

Good idea ! Install WSL2 and ubuntu 22.04 , it’s so esay on Linux ;-))

LOL you are probably right about OS. My experience with Linux is about 6 years setting up marketing servers and fortifying them. And Raspberry Pi.

I got everything going well now. I ran the exercises in a X64 Dev prompt on windows and they worked. Then I got rid of a hacked path in a .bashrc that gets invoked in the shell env with VScode.

Learn though mistakes. Now onward. Thanks for your help

Thanks for the git. I will explore it. You are a mensch ! Frank

IMAGES

  1. c++

    set compiler define cmake

  2. 3: CMake-Set compile options

    set compiler define cmake

  3. c++

    set compiler define cmake

  4. Como realizar o set do CMAKE_CXX_COMPILER?

    set compiler define cmake

  5. Cmake set compiler

    set compiler define cmake

  6. CMAKE: Tutorial for a quick implementation with examples

    set compiler define cmake

VIDEO

  1. Software Development with C++: Recursive CMake

  2. 0x07 C

  3. How to use INCLUDE in CMake (simple)

  4. Describe language processors or translators and their use . Define compiler?

  5. How Can I Get Started with CMake? A Beginner’s Guide

  6. Does CMake Only Work for C++? And Other Questions

COMMENTS

  1. Define a preprocessor macro through CMake

    6 Answers Sorted by: 530 For a long time, CMake had the add_definitions command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options). An example using the new add_compile_definitions:

  2. add_compile_definitions

    Adds preprocessor definitions to the compiler command line. The preprocessor definitions are added to the COMPILE_DEFINITIONS directory property for the current CMakeLists file. They are also added to the COMPILE_DEFINITIONS target property for each target in the current CMakeLists file. Definitions are specified using the syntax VAR or VAR=value .

  3. add_definitions

    Adds definitions to the compiler command line for targets in the current directory, whether added before or after this command is invoked, and for the ones in sub-directories added after. This command can be used to add any flags, but it is intended to add preprocessor definitions. Note This command has been superseded by alternatives:

  4. target_compile_definitions

    Specifies compile definitions to use when compiling a given <target>. The named <target> must have been created by a command such as add_executable () or add_library () and must not be an ALIAS target. The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments.

  5. CMake: How to specify the compiler in CMakeLists.txt

    Setting the compiler for a CMake project is a couple lines in the CMakeLists.txt file, and they have to go in a very specific place - before the project command. set(CMAKE_C_COMPILER "gcc-4.2") set(CMAKE_CXX_COMPILER "/usr/bin/g++-4.2") project("YourProjectName")

  6. Configure and build with CMake Presets

    Visual Studio 2022 version 17.5 preview 1 adds support for schema version 5. You can update the version by changing the "version" field in the root object. For an example and more information, see CMakePresets.json format. CMake version 3.20 or later is required when you're invoking CMake with CMakePresets.json from the command line.

  7. Using CMake to set preprocessor directives

    Now we can set this option to ON when running CMake: cmake -DUSE_DEBUG=ON .. Then, we'll use CMake's add_definitions () function to set the corresponding preprocessor flag in our C++ program: if (USE_DEBUG) add_definitions (-DDEBUG) endif () That's all there is to it. Below you can find a sample CMake file with this functionality built into it:

  8. How do I set define based on current build type?

    How do I set define based on current build type? Code Jack (Jack) November 17, 2022, 12:52pm 1 I want to ensure that a particular compiler definition is set/not set based on the build type. I thought that this would work but it's not:

  9. COMPILE_DEFINITIONS

    The COMPILE_DEFINITIONS property may be set to a semicolon-separated list of preprocessor definitions using the syntax VAR or VAR=value . Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values).

  10. `GenerateExportHeader` and multi-compiler support

    I have just started looking into GenerateExportHeader, but what I've noticed is that it does only generates the define for the specific compiler I am using, e.g. it does not have branching for __GNUC__, _MSC_VER. But then this is rather confusing, what is the purpose of this module? Particularly I am looking at the DEPRECATED macro, which would not be usable in the exported header. EXPORT ...

  11. CMake target_include_directories doesn't export to compile_commands

    I am trying to use CMake to build a CUDA project. However, when I use add_library followed by target_include_directories, the relevant commands are not updated in the compile_commands.json file. The structure of the project is shown here. There are three CMakeLists.txt; one in Euler_CUDA, one in src and one in solver. In sequence, the CMakeLists are the following: cmake_minimum_required ...

  12. Visual Studio Code CMake Tools Extension 1.17 Update: CMake Presets v6

    Workflow presets allow you to define a string of CMake presets that you want to execute (e.g. a configure action followed by a build action). ... If there are settings set in any of the above fields, the affected CMake presets will display in the UI whether override settings have been applied for ease of tracking. ... The MSVC compiler adds ...

  13. c

    If you want to change a compiler, set CMAKE_C_COMPILER in the CMakeLists.txt or in the toolchain file. If you want to change a generator, pass appropriate -G option to cmake. (I know, that cl compiler, shipped with Visual Studio, works with other generators. But I am not sure, whether Visual Studio would work with gcc .)

  14. cmake-toolchains(7)

    Language-specific built-in variables, such as CMAKE_CXX_COMPILER , CMAKE_CXX_COMPILER_ID etc are set by invoking the project () command. If no project command is in the top-level CMakeLists file, one will be implicitly generated. By default the enabled languages are C and CXX: project (C_Only C)

  15. cmake tutorials problems

    There is just something in the Cmake Tools vs cmake cli. I think that cmake cli is looking to qualify a compiler and it is failing. I am trying to use the x64 cl compiler installed with Visual Studio Community. I am also trying to figure out how to debug/watch the cmake cli process but I have not yet figured out a logging mechanism Thanks, Frank

  16. CMake command line for C++ #define

    CMake command line for C++ #define. I need to compile different versions of a certain project by adding compiler switches. Usually I would do this by using add_definitions or something like. in the CMakeLists.txt file. In this specific project however, I am not allowed to modify any sources, including the CMakeLists.txt file.

  17. CXX_STANDARD

    See the cmake-compile-features (7) manual for information on compile features and a list of supported compilers. This property is initialized by the value of the CMAKE_CXX_STANDARD variable if it is set when a target is created.

  18. CMake

    I'm trying to set multiple compile definitions for one of the executables I'm trying to compile in CMake (in order to activate macros used for debugging). Here's what I tried:

  19. target_precompile_headers

    Arguments to target_precompile_headers may use generator expressions with the syntax $<...>.See the cmake-generator-expressions(7) manual for available expressions. The $<COMPILE_LANGUAGE:...> generator expression is particularly useful for specifying a language-specific header to precompile for only one language (e.g. CXX and not C).In this case, header file names that are not explicitly in ...

  20. cmake: how to check if preprocessor is defined

    1 CMake automatically defines several variables, which describes the system. So you may check (in if command) these variables for include OS-dependent code. See Variables That Provide Information. - Tsyvarev Jan 22, 2016 at 9:13 @usr1234567 by pre-processor I meant a variable defined by the -D option to gcc (same as #define ). - Mandeep Sandhu

  21. CMAKE_<LANG>_COMPILER

    CMAKE_<LANG>_COMPILER¶ The full path to the compiler for LANG. This is the command that will be used as the <LANG> compiler. Once set, you can not change this variable. Usage¶ This variable can be set by the user during the first time a build tree is configured. If a non-full path value is supplied then CMake will resolve the full path of the ...

  22. How to set compiler options with CMake in Visual Studio 2017

    Visual Studio 2017 comes with full CMake integration. To learn about this combination, I was starting with this basic sample: # CMakeLists.txt cmake_minimum_required (VERSION 3.8) project (foo) add_executable (foo foo.cpp) and. // foo.cpp int main () {} This properly generates build scripts, and compiles and links with no issues. That was easy.

  23. CMakeForceCompiler

    It sets CMAKE_Fortran_COMPILER to the given compiler and the cmake internal variable CMAKE_Fortran_COMPILER_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests. So a simple toolchain file could look like this:

  24. Setting CMake compilation options in VS Code

    In case you need to run this command often, you could customize your vscode settings, for a better cmake-gui integration, by using the Command Runner extension, which allows to run custom shell commands. After installation add the following to your settings.json: "command-runner.commands": { "cmake-gui": "cmake-gui $ {workspaceFolder}/build" }

  25. CheckPrototypeDefinition

    The following variables may be set before calling this function to modify the way the check is run: CMAKE_REQUIRED_FLAGS. ... The contents of CMAKE_<LANG>_FLAGS and its associated configuration-specific variable are automatically added to the compiler command before the contents of CMAKE_REQUIRED_FLAGS.

  26. CMake 3.29 Release Notes

    cmake(1)-E cat can now print the standard input by passing the -argument. Generators ¶ Visual Studio Generators now support selecting between the Intel oneAPI Fortran compiler (ifx) and the Intel classic Fortran compiler (ifort) using a fortran= field in CMAKE_GENERATOR_TOOLSET. File-Based API ¶

  27. How to correctly define CMakeLists.txt for Tesseract?

    Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

  28. CMAKE_TRY_COMPILE_PLATFORM_VARIABLES

    List of variables that the try_compile() command source file signature must propagate into the test project in order to target the same platform as the host project.. This variable should not be set by project code. It is meant to be set by CMake's platform information modules for the current toolchain, or by a toolchain file when used with CMAKE_TOOLCHAIN_FILE.