Svilen
Svilen

Reputation: 815

How run build task automatically before debugging in Visual Studio Code?

In VS Code I have to run the build task first and then start debugging, while in CLion I just click debug, then it builds automatically if necessary and starts debugging. Is there a way to automate this in VS Code as well?

Upvotes: 63

Views: 46413

Answers (5)

chaosink
chaosink

Reputation: 1483

Simply add "cmake.buildBeforeRun": true in settings.json if you are using CMake.

{
    "cmake.buildBeforeRun": true,
}

Upvotes: 1

Olivier MATROT
Olivier MATROT

Reputation: 35

To complete the accepted answer, following is the .json files for a c# ASP.NET 8 MVC project:

Tasks.json (replace SCTM.Web with whatever project directory and project name)

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": ["build", "${workspaceFolder}/SCTM.Web/SCTM.Web.csproj"],
            "problemMatcher": "$msCompile"
        }
    ]
}

launch.json (again adapt the project files)

{
    // 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": [
        {
            "name": "Janus 7 lieues",
            "type": "coreclr",
            "request": "launch",
            "program": "${workspaceFolder}/SCTM.Web/bin/Debug/net8.0/SCTM.Web.dll",
            "cwd": "${workspaceFolder}/SCTM.Web",
            "launchSettingsFilePath": "${workspaceFolder}/SCTM.Web/Properties/launchSettings.json",
            "launchSettingsProfile": "SCTM.Web",
            "serverReadyAction": {
                "action": "openExternally",
                "pattern": "\\bNow listening on:\\s+http?://\\S",
                "uriFormat": "http://7lieues.talentmanager.com:5001"
            },
            "preLaunchTask": "build"
        }
    ],
}

Upvotes: 1

Enthus3d
Enthus3d

Reputation: 2165

Prerequisite Config


First, if you do not yet have VSCode set up for debugging, follow this link for C++ setup on Windows with VSCode. If you have a different OS or language, you can also find it on the left sidebar of this page.

Adding a build task to the Launch.Json


To run a build task automatically before debugging, you will need to link a build task to your debug config. I'll try to illustrate the process below.

debug configs

First to access your build configs, go to the Debug bar on the side (1), and press the gear icon to access your launch.json config file (2). You will need to add a pre-launch task under your configurations in that launch.json file, and link it to your build task (3).

The string, "buildTaskLinkHere!" here represents the label of that task.

Defining the Build Task in Tasks.Json


tasks.json file

Then, you will need to set up your build task, by running it with ctrl-shift-b.

If it already exists (as implied in your post), you can find it in your .vs-code folder in the tasks.json file. If you open that task.json file, you will find the build task in the list.

All you need to do now is to take the 'label' of that task and place it in your launch.json in that pre-launch config, replacing that "buildTaskLinkHere!" label mentioned in the step before.

Good luck!

Appendix


Appendix added with examples for clean build and running configs in parallel following a shared pre-launch build.

Q: What to do if the build task fails, but the launch process starts with the old binary?

A: Potential solution given by @JoKing: add a new task that deletes the binary and execute this task before each build by requiring it in the build task with the "dependsOn" option. An example is given below for how it might look in the tasks.json file, source

{
   "tasks": [
    {
      "taskName": "build",
      "command": "tsc",
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "dependsOn": [
        "build client",
        "build server"
      ]
    },
    {
      "taskName": "build client",
      "command": "tsc",
      "args": [
        "-w",
        "-p",
        "${workspaceRoot}/src/typescript/client"
      ]
    },
    {
      "taskName": "build server",
      "command": "tsc",
      "args": [
        "-w",
        "-p",
        "${workspaceRoot}/src/typescript/server"
      ]
    }
  ]
}

Q: I have multiple configurations, but want to run build task to run once before all the configurations, is it possible?

A: I have not personally set this up before, but compound launch configurations may be what you are looking for. The example from that page has two configurations, 'Server' and 'Client', which can be launched in parallel while following the prelaunchTask ('defaultBuildTask').

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Server",
      "program": "${workspaceFolder}/server.js"
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Client",
      "program": "${workspaceFolder}/client.js"
    }
  ],
  "compounds": [
    {
      "name": "Server/Client",
      "configurations": ["Server", "Client"],
      "preLaunchTask": "${defaultBuildTask}"
    }
  ]
}

Upvotes: 81

Charles Savoie
Charles Savoie

Reputation: 356

Another way is to define a keyboard shortcut that executes your usual build command, followed by the debugging command. Adding the following to my keybindings.json file worked for me. (The file may be opened via Ctrl+Shift+P and selecting Preferences: Open Keyboard Shortcuts (JSON).)

    {
        "command": "runCommands",
        "key": "f5",
        "args": {
            "commands": [
                "cmake.build",
                "workbench.action.debug.start",
            ]
        },
        "when": "!inDebugMode && cmake:enableFullFeatureSet && debuggersAvailable && !cmake:hideBuildCommand && debugState == 'inactive'"
    }

The above is specific to the CMake VSCode extension, but you can easily find your usual build and debug commands (and "when" conditions) associated to your keyboard shortcuts using File/Preferences/Keyboard Shortcuts (Ctrl+K, Ctrl-S), selecting the Record Keys (Ctrl-K) option and pressing the key, then hovering over the description:

Screenshot of VSCode Keyboard Shortcuts editor

Upvotes: 0

VMMF
VMMF

Reputation: 954

It took me some time to understand the accepted answer. It was not clear to me from that explanation the exact way that would make my program build and debug with 1 click. Also I'm using Mingw-w64 in Windows. Following the instructions on this link and based on the accepted answer I created the following files:

launch.json:

{
    // 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": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "build"
        }
    ]
}

tasks.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "build",
            "command": "C:\\msys64\\mingw64\\bin\\g++.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build",
            "detail": "compiler: C:\\msys64\\mingw64\\bin\\g++.exe"
        }
    ]
}

The key aspect is to rename the default "label": "C/C++: g++.exe build active file" in tasks.json, for something else, for instance I used the word "build" and later reference that same word (not the path or link to tasks.json) in "preLaunchTask": "build" inside launch.json.

Notice the renaming is not strictly necessary. You can also say "preLaunchTask": "C/C++: g++.exe build active file" inside launch.json and it will also work.

Upvotes: 12

Related Questions