How to use the debugger in visual studio code? - c++

I am using Visual Studio Code for C++ coding on Ubuntu 18.04.
I found that for the debugging, I should always build an a.out file and then use the debugger. If I run the code directly by ctrl+alt+n then the code runs completely but it won't give me an a.out file.
Is there any way that I can automate this process?
I have also noticed that there is no build option available.
Here is the launch.json file:
{
// 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}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}

You could create custom build+launch task for running your C++ code through a debugger.
Let's say we have this sample code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
vector<int> numbers{ 10, 20, 30 };
for (int n : numbers)
{
cout << n << endl;
}
}
First, make sure to have Microsoft's C++ extension installed.
Next, create a custom build task.
This tells VS Code how to compile your code.
Open the Command Palette
Select Tasks: Configure Task
Select C/C++: g++: build active file
You can other compilers that are available on your system
That would create or open an existing .vscode/tasks.json file
Configure it
{
"type": "shell",
"label": "build-my-app",
"command": "/usr/bin/g++",
"args": [
"-g",
"-std=c++11",
"${workspaceFolder}/path/to/test.cpp",
"-o",
"${workspaceFolder}/path/to/test.out"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
Set label to uniquely name your custom task
Set the compile flags like -g, -std=xxx, -l<lib>, -I<header>
Set the output filename instead of a.out
Next, create a custom launch task.
This tells VS Code how to run your code through the debugger.
Open the Command Palette
Select Debug: Open launch.json
That would create or open an existing .vscode/launch.json file
Configure it
{
"name": "run-my-app",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/path/to/test.out",
"preLaunchTask": "build-my-app",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb"
}
Set name to uniquely name your launch task
Set preLaunchTask to the build task label you created earlier
Set program to the output filename you set in the build task
Finally, whenever you want to run your app, just open the Debug/Run panel and select your launch task from the dropdown (find the name you set in launch.json). Set your breakpoints then click the Play button.
You'll get the debugger controls for stepping through your code, the variables and call stack information, and the console output in the Debug Console.

Maybe you should try to compile using the the flag -g
Something like
g++ -g file.cpp
This command should generate an excutable and a directory that contains information that the debugger can read.
I am no sure if this is appropiate for VS debugger since I use gdb (gnu debugger) but maybe will work

Related

Use integrated terminal for debugging C++

I would like to use the integrated terminal for debugging C++ files in VSCode on my Mac. I have the C/C++ extension added and enabled globally.
Here is the launch.json that I am using:
{
// 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": "clang++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb",
"preLaunchTask": "clang++ build active file"
}
]
}
I have tried adding "console": "integratedTerminal" to this with no change. When debugging a program, the terminal output says:
> Executing task: /usr/bin/clang++ -fdiagnostics-color=always -std=c++17 -g /Users/kris/learncpp/chapter_03/debugTest4.cpp -o /Users/kris/learncpp/chapter_03/debugTest4 <
Terminal will be reused by tasks, press any key to close it.
Hitting any key here closes the terminal and drops me into a bash shell. Is there another setting I am missing somewhere?

Error message when running C++ programs in Visual Studio Code with "Run Without Debugging" option

I'm using Visual Studio Code to learn C++, and have a program with the following code:
#include <cstdio>
class ClockOfTheLongNow {
private:
int year;
public:
void add_year(){
year++;
}
bool set_year(int new_year){
if (new_year < 2019) return false;
year = new_year;
return true;
}
int get_year(){
return year;
}
};
int main(){
ClockOfTheLongNow clock;
if(!clock.set_year(2019)){
clock.set_year(2019);
}
clock.add_year();
printf("year: %d", clock.get_year());
}
I go up to the bar at the top and press Run > Run Without Debugging:
Option being selected
When I do that, I get the following error message: launch: program 'enter program name, for example C:\Users\drago\Desktop\cpp\a.exe' does not exist
When I open launch.json, it looks like this:
{
// 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": "enter program name, for example ${workspaceFolder}/a.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/path/to/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
The error message makes me think the IDE isn't automatically using the path of the file. For a similar problem in C someone answered that the .json file should be edited, but it would be a pain to have to do that every time. Is there a way to make VS Code do it automatically?
I was able to work around it by installing the Code Runner extension, which allows me to run the code successfully with the arrow button in the upper-right hand corner of the screen, but I also want to be able to do it with the Visual Studio Code's builtin Run options.
I have MinGW installed and added to my PATH environment variable in Windows.
You may be experiencing this issue because you have defined the executable in file launch.json as follows:
"program": "enter program name, for example ${workspaceFolder}/a.exe"
Update the program field in the launch.json file as follows:
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe"
In this case, you also need to update the args field in the tasks.json file as follows. In this way, when the C++ source code is compiled, the g++ command line tool will use the -o flag to generate the executable in the filename.
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
]

Program Output No Longer Appears In Integrated Terminal

Previously, when I tried to debug in VSCode on Windows 10 using the C/C++ extension and MinGW32's g++ and gdb, I was able to press F5(the default "start debugging" hotkey), set up my tasks.json and launch.json, and the program's output would appear in the integrated terminal, as well as any prompts for input. This was useful especially when I needed to also provide input to the program while debugging it for schoolwork, without opening an external shell. However, this is no longer the case and I'm confused as to why, as I haven't actively changed anything to cause this to occur, and now all program output is appearing in the Debug Console, where I cannot enter input. I'd prefer to restore things to what I've described above, where all output/input occurs in the integrated terminal, but I'm unsure how I would accomplish this. I have tried to debug Python programs in VSCode as well, using the available Python extension, but the output of print statements appears in the integrated terminal, where I'd expect it to. In addition, the Code Runner extension works with my current issue, but I'd prefer to restore my working environment to its' previous state. My current version of VSCode is 1.49.2, my C/C++ extension version is 1.0.1, and my Python extension version is 2020.9.111407. I am also using g++.exe (MinGW.org GCC Build-20200227-1) 9.2.0 and GNU gdb (GDB) 7.6.1
For maximum clarity, compiling and debugging from the integrated terminal by manually typing the g++ and gdb commands works fine, but F5 no longer produces the behavior I'd expect.
I've made sure that my launch.json has "externalConsole": false set properly, my Terminal: Explorer Kind setting is set to "integrated", and Terminal > Integrated: Inherit Env is set to true. I've tried to toggle all of these options, running in Administrator mode, running in compatibility mode for Windows 8, rolling back to old versions of the extensions I'm using, and nothing has changed this behavior.
tasks.json:
{
"tasks": [
{
"type": "shell",
"label": "C/C++: g++.exe build active file",
"command": "C:\\Programming\\MinGW32\\bin\\g++.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
],
"version": "2.0.0"
}
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",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:\\Programming\\MinGW32\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++.exe build active file"
}
]
}
test.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "Hello\n";
system("pause");
return 0;
}
This is what happens when I press F5 on a python file, this is the kind of behavior I'd expect.
This is what happens when I press F5 on my cpp file, no output appears in the integrated terminal.
Instead, it appears here.
I have chosen to omit the code from my .py file in the first image due to its' simplicity
UPDATE(Sept. 28, 2020): Apparently this issue has been documented here, and the solution that worked for me was to install mingw-w64 from their sourceforge, then update my mingw path in system environment variables.
The only solution I found is to set "externalConsole": true, in launch.json, working in the external console instead.

How to solve : "launch : program "executable.out" does not exist" in VS Code when debugging with gdb

I am following that tutorial from the VScode team :
https://code.visualstudio.com/docs/cpp/config-wsl#_debug-helloworldcpp
I have run and built another c++ project.
It compiles but the project kraches at runtime, so I decide to debug it.
So i want to debug and I use gdb as proposed by this good tutorial.
When I execute the debugging with "F5", I have that launch.json file :
{
// 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": "executable.out",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
I have modified the "program" section to put the name of my executable ( executable.out) , which is located in the "workspaceFolder"
So I don't understand the error message I get when I do "F5" :
launch : program "executable.out" does not exist
Could someone explain to me how to solve that ?
I thought a lot before posting this question.
Thanks a lot in advance.
Best regards
Use absolute path in program:
"program": "${workspaceFolder}/executable.out"
I assume you are using Linux, since you are using g++ compiler.
Did you compile your cpp file to "executable.out", e.g.
g++ main.cpp -o executable.out
Your launch.json configuration look fine to me. It should work.

Visual Studio Code use input text file on debug

I am trying to follow the direction from this post
Visual Studio Code redirect input on debug
but when I add the console config to the launch.json file
"console": "integratedTerminal"
it throws a "Property console is not allowed". and when I debug the program it still waits on input and never reach break point like I would if I start in shell like
"./a.out 1 test1.txt"
"./a.out 1 <test1.txt"
Full config
{
"version": "0.2.0",
"configurations": [
{
"name": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
//"program": "${workspaceRoot}/a.out.dSYM/Contents/Resources/DWARF/a.out",
"program": "${workspaceRoot}/a.out",
"args": ["1", "<","test1.txt"],
"stopAtEntry": false,
"cwd": "${workspaceRoot}/",
"environment": [],
"externalConsole": true,
"MIMode": "lldb",
//"miDebuggerPath": "C:\\mingw\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"console": "integratedTerminal"
//"preLaunchTask": //"build test1"
}
]
}
I use GDB instead of lldb but still encountered the same issue. It waited for an input when I typed arguments in the "launch.json" file this way:
"args": ["<", "test1.txt"],
But it started working properly when I had rewritten it in the following manner:
"args": ["<", "${workspaceFolder}/test1.txt"],
I think that one should add a parent folder even though the input file is in the workspace folder or simply use the full path.
If you use the integrated console, the < doesn't get interpreted by a shell. Usually, using externalConsole: true fixes the problem since this uses a shell. But if the external console doesn't work on your system for whatever reason and you're forced to use externalConsole: false, the workaround is to let GDB create the shell: miDebuggerArgs: "'-ex' 'run < /path/to/test1.txt'"