This article introduces higher-level view of the C/C++ debugger feature of Visual Studio Code by using gdb. You can step through your code and look at the values store in variables, you can set watched on variables to see when values change, you can examine the execution path of your code, etc
Environment Specification
I am using Ubuntu 16.04 LTS with standard build tools for C/C++.
$ sudo apt-get install build-essential
you may download Visual Studio Code here
If you use Windows then you may install MinGW
Implementation
First open your Visual Studio Code and install C/C++ extension by clicking Extensions button (shortcut Ctrl+Shift+X) as shown as below:
Don't forget to restart your Visual Studio Code.
Next, open folder of your C/C++ code (shortcut Ctrl+K Ctrl+O).
Create simple C++ code. In this article, I wrote simple code to sum of 2 numbers.
Next, Add Configuration from menu Debug or simply press F5 and it will add configuration automatically.
Select C++ (GDB/LLDB)
Then select g++ build and debug active file
It will create launch.json file (Please take attention to the bold letter)
{
// 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": "g++ build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
Then press F5, You will be asked to create tasks.json (Please take attention to the bold letter)
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/a.out"
],
"group": {
"kind": "build",
"isDefault": true
},
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
]
}
]
}
Then you can set break point as picture below and press F5 to start with debugging. It will stop in break point and you can do Step Over, Step Into, Step Out, Watch Variable
Hopefully this article will help you. Thank you