VS Code | Build, Run and Debug in C++ - GeeksforGeeks (2024)

Last Updated : 12 Sep, 2023

Improve

In this article, we will discuss the VS Code setup required for break-point debugging. Firstly create a file launch.json that configures the VS Code to launch the GDB debugger at the beginning of the debugging process. Then create a file tasks.json that tells VS Code how to build (compile) the program. Finally, make some changes to the console settings and implements the build and debugging.

Program:
Let below be the code for the demonstrate purposes:

C++

// C++ program to find the value of

// the pow(a, b) iteratively

#include <bits/stdc++.h>

using namespace std;

// Driver Code

int main()

{

int a, b, pow = 1;

// Input two numbers

cin >> a >> b;

// Iterate till b from 1

for (int i = 1; i <= b; i++) {

pow = pow * a;

}

// Print the value

cout << pow;

}

Launch.json

This file pertains to information like the name of the debugger, path to the debugger, current CPP file’s directory, and console regarding data. Below is the code in the file 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": "g++.exe - Build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname} \\${fileBasenameNoExtension}.exe", // There I have got error Property keys must be doublequotedjsonc "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": true, "MIMode": "gdb", "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++.exe build active file" } ]}

Important terms in launch.json: You can either use entirely code given above or otherwise you may use the code generated in your machine automatically. In both cases, you have to take some precautions. Firstly, make sure that the attribute “externalConsole” is marked as true (we will understand its significance later in this topic). Then check whether the property “miDebuggerPath” points to the gdb debugger correctly. Let us discuss these attributes in detail:

  1. name and type: These are quite self-explanatory, these refer to the name and type of launch.json.
  2. request: states the type of JSON file.
  3. program: stores the detailed address of the program for which launch.json file.
  4. cwd: denotes current working directory. Note that all the addresses in launch.json file are in general form, they are not specific to any file.
  5. externalConsole: as there is no way to handle input/output in VS Code’s integrated terminal, use an external console for this. So set it to true.
  6. miDebuggerPath: points to the location of debugger, this will vary from user to user.
  7. preLaunchTask: this contains the name of tasks.json file.

Note: If you are not able to find any of the executable listed above (such as gdb.exe or g++.exe), you may have to install them manually. You can use MinGW Install Manager to install the required components.

Steps:

  • Go to the Run tab on the left of the screen and click on Run and Debug.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (1)

  • You will be asked to choose the debugger, choose C++(GDB/LLDB). Note this option will appear only if you have MinGW installed and configured in your PC.(Refer to this article to install and configure MinGW).

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (2)

  • Then choose “g++.exe – Build and debug active file”. It refers to g++ GNU C++ compiler.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (3)

  • After this a Launch.json file will appear, you may either use it or the one I provided above. Again make sure the externalConsole is marked true and miDebuggerPath is set correctly.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (4)

  • After this click the play button on the top left of the screen and move on to the tasks.json file.

Tasks.json:

This file contains information like the commands used for compilation, the compiler’s address, the same label as in launch.json, and some other information. Below is the code in the file task.json:

{ "version": "2.0.0", "tasks": [ { "type": "shell", "label": "C/C++: g++.exe build active file", "command": "C:\\MinGW\\bin\\g++.exe", "args": [ "-std=c++11", "-O2", "-Wall", "-g", "${file}", "-o", "${fileDirname} \\ ${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": [ "$gcc" ], "group": { "isDefault": true, "kind": "build" } } ]}

Important terms in task.json: The above mentioned tasks.json file can be used entirely without caution. However, the only thing to take care of is that the label of tasks.json should match with preLaunchTask of Launch.json. Let’s discuss some terms in more detail:

  • label: this is unique to a tasks.json file and is used by launch.json to call tasks.json before its execution.
  • command: this points to the g++ compiler application, as it will be used in compilation
  • args: these arguments along with command when concatenated look like that is exactly the command we use for the compilation of CPP file and creation of the executable file as:

g++ -std=c++11 -O2 -Wall ${file} -o ${fileDirname}\\${fileBasenameNoExtension}.exe

Steps:

  • From the last step of launch.json we had clicked on the play button on the top left, now a dialogue box appears, which says that there is no tasks.json file in the current directory. Therefore, we need to create one, so Click on the Configure Task.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (5)

  • Then click on Create tasks.json file from a template.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (6)

  • Then Click on Others.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (7)

  • Paste the code provided above in the newly created tasks.json file. Make sure to delete the existing code before doing so.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (8)

Console Adjustments

Steps:

  • One point that is already covered is that externalConsole in launch.json has to be true.
  • Now, include conio.h header file in our program and call get-character method at last of our main() function. This will stop the command prompt from disappearing immediately after the execution completes so that we get time to examine the output until we press any character. Now the code becomes:

C++

// C++ program to find the value of

// the pow(a, b) iteratively

#include <bits/stdc++.h>

#include <conio.h>

using namespace std;

// Driver Code

int main()

{

int a, b, pow = 1;

// Input two numbers

cin >> a >> b;

// Iterate till b from 1

for (int i = 1; i <= b; i++) {

pow = pow * a;

}

// Print the value

cout << pow;

_getch();

}

  • Put a red break-point at some line of code that we want to examine/debug.
  • Then we click on the play button on the top left of the screen to start the build.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (9)

Break-point Debugging:

Steps:

  • In the appeared command prompt, we enter the required input and press enter.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (10)

  • We notice that the execution begins and it pauses at the mentioned break-point.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (11)

  • Now there are some options, we can either continue, step over, step into, step out-of, or restart the execution. You can do whatever you like to debug your code.
  • Also, notice the value of all variables at that time of execution on the left of the screen.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (12)

  • Debug as you want and as much as you want, then after the entire execution is over, go to the command prompt and notice the output there.

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (13)

  • After you have finished examining the output, press any key to close the command prompt.


sarvjot

Improve

Next Article

VS Code | Compile and Run in C++

Please Login to comment...

VS Code | Build, Run and Debug in C++ - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5535

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.