in vscode's launch.json how can I reference the name of the current build preset
- User
in vscode's launch.json how can I reference the name of the current build preset
- Assistant
In Visual Studio Code's
launch.json, you typically define configurations for launching your application. If you are using CMake Tools extension for configuring build systems, you might find yourself needing to reference build presets.As of my last update,
launch.jsonitself does not natively support dynamic references to CMake build presets directly. However, you can work around this limitation by using tasks and environment variables.Steps to Reference CMake Build Presets in
launch.json-
Define CMake Build Preset in
CMakePresets.json: This file should be at the root of your project. Define your build configurations here. -
Create a Task in
tasks.json: You need to create a task that can set an environment variable with the value of the current build preset. Here’s a simplified example of what that might look like:// .vscode/tasks.json { "version": "2.0.0", "tasks": [ { "label": "setCurrentBuildPreset", "type": "shell", "command": "echo", "args": ["${command:cmake.getPresetName}"], "problemMatcher": [], "options": { "env": { "CMAKE_BUILD_PRESET": "${command:cmake.getPresetName}" } } } ] } -
Use the Preset in
launch.json: Once you have the environment variable set, you can reference it in yourlaunch.json.// .vscode/launch.json { "version": "0.2.0", "configurations": [ { "name": "Launch Program", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build/${env:CMAKE_BUILD_PRESET}/myProgram", "args": [], "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "setCurrentBuildPreset" } ] }
Key Points
- CMakePresets.json: Manage and define your build presets here.
- tasks.json: Create a task that outputs the current build preset name into an environment variable.
- launch.json: Access this environment variable to use the current preset in configuration paths.
This method relies on the tasks system to set and use environment variables, which can then be accessed in your
launch.jsonconfiguration. If the CMake Tools API or Visual Studio Code add direct support for presets in the future, it's worth checking for more streamlined solutions. -