Debugging C/C++ code in Visual Studio Code (VSC)

I’ve been occupied with competitive programing a lot lately. For writing code I use Visual Studio Code because I am used to it from javascript and python world. To test code I write given input from competition task to in.txt file and then run custom task build.

Steps needed for running/debugging:

1. install C/C++ extension.

https://code.visualstudio.com/docs/languages/cpp

2. Define task to build code.

Go to Tasks > Configure tasks and choose your task to edit or create new one.

{
  "_comment": "
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
  ",
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build & run",
      "type": "shell",
      "command": "g++ program.cpp -std=c++14 -o program.out && time ./program < in.txt",
      "group": {
        "kind": "build",
        "isDefault": true
      }
    },
    {
      "label": "build & debug",
      "type": "shell",
      "command": "g++ program.cpp -std=c++14 -g -o program.out",
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

Make sure you have -g switch. This will allow you to debug code later. Now you should be able to build and run your code using: ctrl + shift + b

3. Install debugging dependencies

You need gdb and xTerm or gnome terminal. I am using deepin linux so I had to run

sudo apt-get install gdb xterm

4. Setup debugging

Go to Debug > open configurations

{
   "_comment": "
        // 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": "${workspaceFolder}/program.out",
      "args": [
        "<",
        "in.txt"
      ],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": true,
      "MIMode": "gdb",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "build & debug"
    }
  ]
}

Note the args < in.txt which will allow you to redirect input file while debugging.

Thats it!

You should be able to debug code now, by setting up breakpoints and hitting F5 or go to debug > start debugging

comments powered by Disqus