Search code examples
cvisual-studio-codegdb

Use gdb in vscode with -lm flag


As of https://code.visualstudio.com/docs/cpp/launch-json-reference, I can only attach to an already existing binary with vscode (in the example being a.out), but I would like to have it in a way so that I can debug without having to compile manually first (with the -lm flag). How would I go about that?


Solution

  • Figured it out. Instead of only using a launch.json, I also used a task.json as follows in order to build the c file first:

    {
        "version": "2.0.0",
        "tasks": [
            {
              "label": "build C file",
              "type": "shell",
              "command": "gcc -g -o ${workspaceFolder}/sum/main ${file} -lm",
              "problemMatcher": [],
              "group": {
                "kind": "build",
                "isDefault": true
              }
            }
          ]
    }
    

    In the launch.json, I use the task as a preLaunchTask:

    {
      "version": "0.2.0",
      "configurations": [
        {
          "name": "C Debug",
          "type": "cppdbg",
          "request": "launch",
          "program": "${workspaceFolder}/sum/main", // Dummy value
          "args": [],
          "stopAtEntry": true,
          "cwd": "${workspaceFolder}",
          "environment": [],
          "externalConsole": true,
          "MIMode": "gdb",
          "miDebuggerPath": "/usr/bin/gdb",
          "preLaunchTask": "build C file",
        }
      ],
    }
    

    More info on tasks here: https://code.visualstudio.com/docs/editor/tasks