Cmake visual studio code windows

In this article, you’ll learn how to create a CMake hello world project from scratch using the CMake Tools extension in VS Code.

If you have an existing CMake project that already has a CMakeLists.txt file in the root directory but no CMake presets, you can skip to Create a CMakePresets.json file to configure your project with CMake presets.

Otherwise, create a folder for a new project. From the Terminal window, create an empty folder called HelloWorld, navigate into it, and open VS Code in that folder by entering the following commands:

mkdir helloworld
cd helloworld
code .

The code . command opens VS Code in the current working folder, which becomes your «workspace».

Create a CMakeLists.txt file

The CMake Tools extension can create the files for a basic CMake project for you.

  1. Open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and run the CMake: Quick Start command:

    Create CMake quickstart

  2. Enter a project name, and select C++ as the project language.

    This information will be written to CMakeLists.txt and a few initial source files.

    Note: If you had other source code files in this folder that you wanted to add as targets to the CmakeLists.txt, an option to add these would now be given. But for this tutorial, we will stick with just the hello world file.

  3. Select CTest as an additional option to add support for testing. You can also select CPack for CPack support.

    Additional Options

  4. Next, select Executable as the project type to create a basic source file (main.cpp) that includes a basic main() function.

    Choose project type

    Note: If you had wanted to create a basic source and header file, you would have selected Library instead. But for this tutorial, Executable will do. If you are prompted to configure IntelliSense for the folder, select Allow.

This successfully creates the CMakeLists.txt file, which tells the CMake tools how to build your project.

Project contents

Create a CMakePresets.json file

Next, continue with the CMake Quick Start to create a CMakePresets.json file.

  1. Select Add a New Preset and Create from Compilers.

    The extension automatically scans for kits on your computer and creates a list of compilers found on your system.

  2. Select the compiler you want to use.

    For example, depending on the compilers you have installed, you might see something like this:

    Add a new preset

  3. Enter a name for this new preset.

    The name for the preset will be written to CMakePresets.json.

After completing these steps, you should now have a complete hello world CMake project that contains the following files: main.cpp, CMakeLists.txt, and CMakePresets.json.

Add a new preset

5/29/2024

CMake Tools

Enhancing CMake development in VS Code.

CMake Tools Banner

Introduction

CMake Tools provides the native developer a full-featured, convenient, and powerful workflow for CMake-based projects in Visual Studio Code. It simplifies advanced configurations with support for CMake presets and enhances the development experience by supporting rich IntelliSense features, a built-in debugger for CMake scripts, and configurable CMake tasks. Its customizable interface allows for efficient tailored control of projects, while CTest integration ensures straightforward test execution and monitoring.

Features

 

 

 

 

Setup and Installation

Ensure CMake is available on your system. A couple of options are:

  • Download CMake.
  • Utilize the CMake that is bundled with a Visual Studio installation.

Install the CMake Tools extension from the Extensions pane within VS Code or from the VS Code Marketplace.

Ensure that either you’ve added your CMake executable to your PATH, or you’ve adjusted the cmake.cmakePath setting to point to your CMake executable.

Resources

  • Docs for comprehensive documentation.
  • Quick Start to get up and running fast.
  • Github for source code, issues, and contributing.

Contributing

We encourage an open and collaborative development environment and welcome all contributions. Whether you’re fixing bugs, proposing new features, or improving our documentation — we invite you to join the CMake Tools community. Please review our contribution guidelines and adhere to our code of conduct.

You can file issues with us using one of our templates:

Bug Report: If you see an error message or encounter an issue while using the CMake Tools extension.

Feature Request: If you have a suggestion or need a feature that would enhance development.

Documentation Request: Requesting changes or additions to the CMake Tools documentation.

Microsoft Open Source Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Data/Telemetry

This extension collects usage data and sends it to Microsoft to help improve our products and services. Collection of telemetry is controlled via the same setting provided by Visual Studio Code: "telemetry.enableTelemetry". Read our privacy statement to learn more.

Credits

This project was started by @vector-of-bool and is now currently maintained by Microsoft.

Contributors

Contributors

Overview

This is a practical guide for using CMake and C++ in VSCode. I find this a nice way to easily develop C++ applications without the use of a more heavyweight IDE like CLion or Full Fat VS.

VSCode Setup

First step is to download the relevant extensions that provide useful functionality. So you will need the following extensions:

  • C/C++
  • C/C++ Extensions
  • CMake
  • CMake Tools

Next is to either open an existing project (obviously this must use CMake) or create a new one. If you have a project you can skip the next section otherwise I will run through creating a small project.

Project Creation

For the purposes of this tutorial I will create a new small CMake project with a simple executable. First in a blank directory create a top level CMakeLists.txt file with the following contents:

cmake_minimum_required(VERSION 3.22)

# Project settings
project(
        cr_cpp_cmake_vscode
        VERSION 1.0.0
        DESCRIPTION ""
        LANGUAGES CXX C
)

add_subdirectory(app)

Now create a new directory called app and add a cpp file called main.cpp and another CMakeLists.txt file, with the following content:

app/main.cpp
#include <iostream>

int main()
{
    std::cout << "Hello, world!" << std::endl;
    return 0;
}
app/CMakeLists.txt
add_executable(cr_app main.cpp)

Configure CMake and Build

Now we have a project we can set it up. You can do all this using regular CMake commands, but I will show you which commands you can use within VSCode to make this easier. First open the command palette with Ctrl + Shift + P, and find the CMake: Configure option. Run this and it should ask you what toolchain you would like to use.

pick one of the ones available and it will run the initial setup to setup those toolchains. The CMakesidebar should now be visible for you to see what has been setup. This will automatically setup a Debug “variant”. You can then simply hit F7 to build (or select the CMake: Build command from the command palette).

You should find your executable built in the build directory which you can now run!

Building in Release

At some point you will want to switch to a release build. To do this you can in one of 2 ways. Either select CMake: Select Variant from the command palette and choose “Release” OR in the CMake sidebar under “Configure” hit the pencil icon next to the current variant to pick the one you want:

Debugging

Debugging is an integral part of developing any C++ code, so how do we do it in this environment. Some default level of debugging is already setup behind the scenes with the steps above. To debug the app, you simply need to hit the debug icon in the section in the CMake sidebar:

This is fine for simple cases but what if say we want to pass command line arguments to the program. This requires a bit more setup.

First click on the Run and Debug sidebar panel, and select the create a launch.json file link

It will ask you to select a debugger, I picked windows

this will create an empty launch.json file. Click the Add Configuration button at the bottom and select C\C++: (Windows) Launch. This will add the relevant configuration, which you can change to suit your needs, for example I changed mine to this, notice the args entry which provides the program arguments

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug cr_app",
            "type": "cppvsdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/app/Debug/cr_app.exe",
            "args": ["friend"],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": []
        }
    ]
}

after altering my main.cpp to this

#include <iostream>

int main(int argc, char *argv[])
{
    std::cout << "Hello, " << argv[1] << std::endl;
    return 0;
}

to debug you can then hit F5 or run it from the sidebar

and in the debug console you will see the output

That’s All Folks

There are a lot of other commands you can use to setup and customise C++ building and debugging in VSCode, but these are the basics to get you started. Its pretty easy and with handy keyboard shortcuts for most things, its quite a pleasant experience!


I. C++ project with VSCode

  There are multiple ways of creating C++ project. You could choose to go with heavy lifting IDE(Microsoft Visual Studio, Eclipse, Code::Blocks, CLion,…), or go with plain notepad++, compiler, and a console.
  But all of these IDE required you to install additional software on your PC, and the text editor, compiler combo make it hard when it come to debug your program.
Then you may want to start with VsCode, a perfect fit between two options above, simple but has enough extension for your needs, and you can use it for different programming languages.

Let’s start

1. Target system

As mention above, vscode is a code editor with a lot of powerful extensions. But at the core, it’s still a text editor, and to build your C/C++ program, you still need to provide the compiler.
The compiler, where and how to install it.

  1. Windows
    • You can get MS visual studio code compiler cl here, it’s come with IDE though. I think we could install the compiler only, but you have to look around for that option.
    • Or you can get MingGW-g++, it’s come along with cgwin(bash like console on window). It’s pretty old but work perfect when you want a linux like environment on window
  2. Linux or Windows Linux Subsystem
    • On a linux machine or WSL, it should come with pre-install gnu-g++, you could test with type g++ --version to check. If it’s not installed, then sudo apt install g++ should do the job

2. VsCode extensions

There is a lot of extensions, which support C/C++ development on vscode. But to keep it simple, we usually go with one below.

Ctrl + Shift + X, search for «C++» and you get everything

3. Let’s build and debug it

Alright, after you get all the extensions and compiler in place, let’s create a simple C++ program and try to build it.

  • Create a folder for your project, open vscode then [Ctrl + k + o] to open your project folder.
  • Create a main.cpp and input your sample code.
#include <iostream>

int main(int argc, const char* argv[])
{
    std::cout << "ayy" << std::endl;
}
  • [Ctrl + Shift + p]: type in “C/C++: edit configurations”.
    You can choose UI option to show the UI for setting, go through it and change the setting your self, after you finished just [Ctrl + s] the configuration shall be save and store to ./.vscode/c_cpp_properties.json in your project folder
    If you chose the JSON, the c_cpp_properties.json shall be open right away for you with default a default config for the available compiler in your environment. Below is sample configurations, 1st for mingw64 g++ compiler and 2nd is for msvc compiler.
{
    "configurations": [
        {
            "name": "Win32_mingw64",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "10.0.18362.0",
            "compilerPath": "C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin/g++.exe",
            "intelliSenseMode": "windows-gcc-x64",
            "cStandard": "c17",
            "cppStandard": "c++17"
        },
        {
            "name": "Win32_cl",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "10.0.18362.0",
            "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.27.29110/bin/Hostx64/x64/cl.exe",
            "intelliSenseMode": "windows-msvc-x64",
            "cStandard": "c17",
            "cppStandard": "c++17"
        }
    ],
    "version": 4
}

[Ctrl + Shift + p]: “Select configuration” then you can create multiple configuration and switch between them.

[Ctrl + Shift + p]: “Build and Debug Active File”, you can build and debug a simple Cpp program, remember to open your main.cpp first as active file. Red one is default, green is Tasks option, which is created after 1st execute.

Build and Debug Active File

Build and Debug Active File

Select your target compiler, then your Cpp file will be build and executed. If you want to stop the program, place debug point on the line count ruler in the editor or else it will run to the end right away.

NOTE: To able to use the msvc compiler, vscode has to be lunched from “Developer Command Prompt for VS”. i.e. Start > Developer Command Prompt for VS > cd to project folder > code . to open vscode

After execute, your vscode shall spawn a new tasks.json file in .vscode folder of project. Below is sample tasks.json file, which is generated when you run with 2 different compiler (msvc and gnu-g++).

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "mvsc_preruntask",             // Default value is "C/C++: cl.exe build active file", you could change it
            "command": "cl.exe",                    // call the compiler to compile the program
            "args": [                               // input args for the compiler
                "/Zi",
                "/EHsc",
                "/nologo",
                "/Fe:",
                "${fileDirname}\\app.exe",          // "${fileDirname}\\${fileBasenameNoExtension}.exe", output to app.exe file
                "${fileDirname}\\*.cpp"             // "${file}" , change to target build all *.cpp file in current folder
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$msCompile"
            ],
            "group": "build",
            "detail": "Task generated by Debugger.",
            "promptOnClose": true
        },
        {
            "type": "cppbuild",
            "label": "g++_preruntask",              // "C/C++: g++.exe build active file"
            "command": "C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin/g++.exe",
            "args": [
                "-g",
                "${fileDirname}\\*.cpp",            // "${file}"
                "-o",
                "${fileDirname}\\app.exe"           // "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build",
            "detail": "Task generated by Debugger.",
            "promptOnClose": true
        }
    ],
    "version": "2.0.0"
}

More on tasks.json setup here!
Basically you can change the tasks to call to external script command to build your project (i.e. make,..). But for now it’s a simple project so let’s just change some of its default value (label, compiler args) so we can refer to it in lunch debug.
[Ctrl + Shift + D] to lunch debug operations, we will refer to those build tasks before proceed with the debugger.

Lunch file for debug

Lunch Debug

Select the target environment, a lunch.json file will be created in .vscode folder. Change some default value, so lunch operation shall prefer to your preLunchTask. After updates, in debug shall show you the available options.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "preLaunchTask": "mvsc_preruntask",     // label of target task in your tasks.json
            "name": "(Windows) Launch",
            "type": "cppvsdbg",
            "request": "launch",
            "program": "${workspaceFolder}/app.exe", // application name you want to debug
            "args": [],                              // input args for the debug program, in this case is "app.exe"
            "stopAtEntry": true,                     // debug stop at entry of main
            "cwd": "${fileDirname}",
            "environment": [],
            "console": "integratedTerminal"
        },
        {
            "preLaunchTask": "g++_preruntask",
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/app.exe",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin/gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        },
    ]
}

Now open your main.cpp, press F5.

debug

Tadaa, you ready to go, let’s write your program and debug it

More on lunch.json setting here!

II. (Too bland?) Let’s add CMake flavor

  So in first section, we able to setup a simple project to build and debug your cpp file. If you want to extend the project, adding new file, using external library, you need to update the tasks.json so it will call to your build script or external build system to handle larger project.
But today we shall using CMake(build system generator). It basically generate build directory base our selected build tool and help us to move our project between platform and compiler easily.

Build system: Build automation involves scripting or automating the process of compiling computer source code into binary code. Ex: make, GNU make, nmake, bitbake, ninja

Build system generator: Generator tools do not build directly, but rather generate files to be used by a native build tool. Ex: CMake

Let’s get the CMake extension, install RemoteSSH/WSL if you want develop on remote machine(Linux) from your windows base environment.

additional extension

CMake, RemoteSSH/WSL

CMake project setup is pretty much the same for both windows and linux, so for the following section, we shall use vscode to setup a project on remote linux.

Let’s switch development environment to Linux from your windows machine

Click here.

select remote icon

Select your target, could be either WSL on your windows or a remote linux machine with SSH

select option

After that, vscode shall connect to your remote machine. Go to extension tab, it will show available extension that you can install on remote machine (it’s the the same as previous section).
[Ctrl + Shift + P]: “cmake”, it will show you available operation with cmake extension. Click on configure, select the compiler and enter your project name.

cmake configuration

CMake extension request you to create a CMakeLists.txt for your project, and it should be like this.

cmake_minimum_required(VERSION 3.0.0)
project(sample VERSION 0.1.0)

include(CTest)
enable_testing()

add_executable(sample main.cpp)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

In the status bar, you should able to see 3 action: Build, Debug, Lunch. Click on build or F7 and cmake shall create build directory and build your project in it. Let’s update the directory: add src and include folder and provide additional code there. Then update your CMakeLists.txt as following (for more about CMake, please check CMake Documentation)

cmake_minimum_required(VERSION 3.0.0)
project(sample VERSION 0.1.0)

include(CTest)
enable_testing()

set (SRC_FILES main.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/sample_src.cpp) # your source files


add_executable(sample ${SRC_FILES}) # build executable "sample"


target_include_directories(sample PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) # include directory for header files


set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

Almost done, let’s update some setting of cmake, so we can push input args to our programs as previous debug session. Create a file settings.json in .vscode folder and input below content.

{
    "cmake.debugConfig":
    {
        "stopAtEntry": true,        # debug stop at entry of main
        "args": ["a", "b", "c"],    # we push 3 input args here
        "MIMode": "gdb",
        "externalConsole": false,
    }
}

OK, now Ctrl + F5, it shall build your project and lunch debug mode.

project with cmake

End result

Nice, now you can update your project, create additional modules, add external libraries, etc. Of course, you have to update the CMakeLists.txt correspondingly with the changes of project. We will have a CMake topic in the near future.
Another thing, VSCode remote extension is pretty convenience when you want to create/build your project in remote machine(raspberry, beaglebone,…). You can just setup a raspberry with ssh enable and it’s good to go. No need for additional keyboard, mouse, monitor or using ssh with CLI.

Remote and debug?

When your program required su to run then normal debug will not work. Here is a workaround.
cd /usr/bin
sudo mv gdb gdb_origin
sudo vim gdb
Input:

#!/bin/sh

sudo gdb_origin $@

sudo chmod 0755 gdb
Now you are able to debug your program as su.

Время на прочтение6 мин

Количество просмотров16K

В CMake 3.19 и 3.20 был зарелижен CMakePresets.json, который позволяет пользователям указывать общие параметры настройки, сборки и тестирования и делиться ими с другими пользователями. Мы добавили поддержку CMakePresets.json в Visual Studio и создали расширение CMake Tools для Visual Studio Code. Теперь вы можете вызывать CMake с CMakePresets.json в Visual Studio, в Visual Studio Code, в конвейере непрерывной интеграции и из терминалов в Windows, Linux и macOS.

Интеграция CMake Presets теперь доступна в Visual Studio 2019 16.10 Preview 2 и CMake Tools 1.7.

Почему я должен использовать CMake Presets?

Поддержка configurePresets была зарелижена в CMake 3.19. Наша команда в Microsoft работала над поддержкой buildPresets и testPresets в CMake 3.20, и мы очень рады решить некоторые типичные проблемы, связанные с конфигурацией и сборкой CMake, с помощью CMake Presets (пресетов).

  • Более плавный переход между Visual Studio и Visual Studio Code. С добавлением поддержки CMakePresets.json один и тот же файл можно использовать для управления CMake как в Visual Studio, так и в Visual Studio Code. Это упрощает разработчикам в вашей команде переключение между Visual Studio и Visual Studio Code и позволяет работать в среде разработки, которая лучше всего отвечает их текущим потребностям.

  • Предустановки для отдельно взятого проекта всегда можно сохранить или достать из системы контроля версий. CMake поддерживает два файла: CMakePresets.json и CMakeUserPresets.json. CMakePresets.json предназначен для сохранения глобальных предустановок проекта, а CMakeUserPresets.json задуман для хранения собственных локальных предустановок под отдельных разработчиков. Это гарантирует, что информацию, касающуюся конкретного проекта, можно будет вносить в систему контроля версий, а новым членам группы будет проще влиться в работу. Это также упрощает для команд синхронизацию изменений в своих сборках CMake. И CMakePresets.json, и CMakeUserPresets.json поддерживаются в Visual Studio и Visual Studio Code.

  • Воспроизведение сборок в Visual Studio и Visual Studio Code из командной строки. Поскольку CMakePresets.json поддерживается самим CMake, тот же файл CMakePresets.json можно использовать для вызова CMake в Visual Studio, в Visual Studio Code, в конвейере непрерывной интеграции и из командной строки в Windows, Linux и macOS. Вызов CMake с CMakePresets.json из командной строки поддерживается с CMake версии 3.20.

  • Упростите возню с инструкциями по сборке для проектов CMake с открытым исходным кодом. Вы можете запулить любой проект, в корневом каталоге репозитория которого есть файл CMakePresets.json, собрать и протестировать его локально, используя инструкции, вложенные в пресет. Все аргументы команды, которые могут быть переданы в CMake или CTest из командной строки, можно указать в Configure, Build или Test пресетах.

Больше информации о пресетах CMake вы можете найти в моей недавней презентации в ACCU, где я демонстрирую, как использовать CMakePresets.json в Visual Studio, из командной строки и в конвейере GitHub Actions. Вы также можете ознакомиться с примером файла CMakePresets.json, зарегистрироваться в Pure Virtual C++ или почитать официальную документацию CMake. Более подробная информация об интеграции пресетов CMake в Visual Studio и VS Code приведена ниже.

Пресеты CMake в Visual Studio

Лучшим источником информации об интеграции пресетов CMake в Visual Studio является наша документация. Интеграция пресетов CMake в Visual Studio пока еще в статусе превью.

CMakePresets.json станет рекомендуемой альтернативой CMakeSettings.json. Visual Studio никогда не будет считывать данные одновременно из CMakePresets.json и CMakeSettings.json. Вы можете включить интеграцию пресетов CMake для всех проектов в Tools > Options > CMake > General. Чтобы активировать интеграцию, необходимо закрыть и снова открыть папку в Visual Studio.

Вы можете включить интеграцию пресетов CMake для одного проекта, добавив файл CMakePresets.json в корень открытой папки. Опять же, для активации интеграции вы должны закрыть и снова открыть папку. Дополнительные сведения смотрите в разделе Enable CMake Presets integration in Visual Studio 2019.

После включения интеграции пресетов CMake вы увидите три раскрывающихся списка в панели меню.

В раскрывающемся списке слева указывается активная целевая система (Target System). Это система, в которой CMake будет вызываться для настройки и сборки проекта. В этом раскрывающемся списке отображается локальный компьютер, все SSH-подключения в Connection Manager по имени узла и все инсталляции Windows Subsystem для Linux (WSL), которые сможет найти Visual Studio.

В раскрывающемся списке посередине указывается активный Configure Preset, который будет использоваться при вызове CMake для создания системы сборки проекта. В этом раскрывающемся списке приведены не скрытые Configure пересеты, определенные в файлах CMakePresets.json и CMakeUserPresets.json, которые применяются в Target System. Активный Configure Preset на изображении выше — это ninja-debug.

В раскрывающемся списке справа указывается активный Build Preset, который будет использоваться при вызове CMake для сборки проекта. В этом раскрывающемся списке приведены не скрытые Build пресеты, определенные в файлах CMakePresets.json и CMakeUserPresets.json, которые применяются к активному Configure Preset. Активный Build Preset на изображении выше — verbose-build. Ознакомьтесь с нашей документацией по настройке и сборке в разделе CMake configuration and build.

 С помощью Visual Studio вы можете редактировать, создавать и отлаживать ваши CMake таргеты в Windows, WSL и удаленных системах из одной IDE. Visual Studio автоматически скопирует ваш исходный код в указанную целевую систему, но ваши инструменты сборки (CMake, генератор, компиляторы), rsync, zip и gdb должны быть уже установлены. Дополнительная информация в разделе Creating a Linux environment.

Дополнительную информацию о добавлении, редактировании пресетов, запуске тестов и многом другом смотрите в нашей документации в разделе CMake Presets integration in Visual Studio.

Пресеты CMake в расширении CMake Tools для Visual Studio Code

Лучшим источником информации об интеграции пресетов CMake в расширение CMake Tools является наша документация. Интеграция пресетов CMake в расширение CMake Tools пока еще в статусе превью.

CMakePresets.json станет рекомендуемой альтернативой файлам китов (kits) и вариантов (variants). CMake Tools никогда не будет считывать настройки одновременно из CMakePresets.json и китов и вариантов. Вы можете включить интеграцию пресетов CMake, изменив значение cmake.useCMakePresets в settings.json.

Параметр

Описание

Допустимые значения

Значение по умолчанию

cmake.useCMakePresets

Используйте CMakePresets.json для запуска CMake configure, build, и test

always, never, auto

auto

Значение auto расценивается как always, если в cmake.sourceDirectory активной папки есть CMakePresets.json, и расценивается как never, если в cmake.sourceDirectory активной папки нет файла CMakePresets.json. Установите значение cmake.useCMakePresest на always или never, чтобы явно включать или отключать интеграцию пресетов CMake для всех проектов CMake. Дополнительная информация в разделе Enable CMake Presets in the CMake Tools extension.

После включения интеграции пресетов CMake вы можете запускать несколько новых команд.

Используйте команды CMake: Select Configure Preset, CMake: Select Build Preset и CMake: Select Test Preset, чтобы выбрать ваши активные пресеты. Ваши активные пресеты отображаются в строке состояния.

На изображении выше [active-configure-preset] указывает активный Configure Preset, [active-build-preset] указывает активный Build Preset, а [active-test-preset] указывает активный Test Preset.

Дополнительные сведения о добавлении, редактировании пресетов, запуске CMake и многом другом смотрите в нашей документации по интеграции пречетов CMake в Visual Studio Code.

Что дальше?

Интеграция пресетов CMake в Visual Studio и Visual Studio Code пока еще в статусе превью. Мы продолжим дополнять нашу интеграцию учитывая ваши отзывы в будущих релизах Visual Studio и расширения CMake Tools для VS Code.

В Visual Studio лучший способ сообщить об ошибке или предложить функцию — это нажать кнопку Send Feedback в правом верхнем углу IDE. Дополнительная информация в разделе Visual Studio feedback options.

В VS Code лучший способ сообщить об ошибке или предложить функцию — создать (или проголосовать за) issue в GitHub репозитории расширения.

Нам интересно узнать о вашем опыте внедрения CMakePresets.json. Вы можете связаться с нами по адресу cmake@microsoft.com, чтобы оставить отзыв и поделиться своей историей. Вы также можете связаться с нами в Twitter (@VisualC).


Перевод материала подготовлен в преддверии старта курса «C++ Developer. Professional».

Всех желающих приглашаем на вебинар «Корутины — что это и зачем?». На этом открытом уроке разберем понятие сопрограмм (coroutines), их классификацию, детально рассмотрим реализацию, допущения и компромиссы, предлагаемые новым стандартом C++. Рассмотрим пользовательские типы, которые добавились для реализации сопрограмм (Promise, Awaitable.) Разберём пример реализации асинхронного сетевого взаимодействия с использованием сопрограмм.

РЕГИСТРАЦИЯ

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Все windows 7 цены
  • Bitrix otp для windows
  • Windows 7 fix for games
  • One drive windows live
  • Установить браузер google chrome для windows 10 бесплатно