Debugging a c++ code with Visual Studio Code Ubuntu - c++

Good evening to everyone, I try to debug this little program in visual studio code in ubuntu:
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::string folder = argv[1];
}
but the debug terminate with this error in the terminal:
"terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
"
and this in the debug console:
"Unable to open 'raise.c': Unable to read file (Error: File not found (/build/glibc-4WA41p/glibc-2.30/sysdeps/unix/sysv/linux/raise.c))."
So the question are:
1) Is possible to display the number of the line where the error occurs? (In this case line 6)
2) Why does this error happen, and how to avoid it?
3) For avoiding this problem I can write, for example:
string folder = "/home/lorenzo/Images";
but I don't want to do that. For "running" the program from the terminal I write ./main /home/lorenzo/Images, so I pass the folder to the program in this way. Is possible to do the same thing when debbuging, without writing the folder directly in the program, or using cin?
Thanks in advance!

If you want to debug with VS Code, there's a setup that you have to do for each project, but after the setup is complete, it's straightforward.
Install gdb if you haven't already. You then need to choose a configuration in the debug panel. Instructions can be found here. Compile your program with -g at a minimum. I prefer also adding in -O0 to minimize optimizations.
Once you get set up, you're now ready to debug with VS Code. Now, to [hopefully] answer your questions.
gdb can do this for some segmentation faults; generally you'll want to learn how to move through the code yourself.
I attempted to compile and run your program, and it worked just fine. Is the name of your executable main? I compiled on Debian using gcc 5.5. I didn't name my executable, so my invocation looked like this:
./a.out /home/sweenish/tmp. Since mine didn't fail, I can't offer much help here. But your compiler is saying that a file doesn't exist. Did you install the build-essential package?
Yes, you can automate the extra argument by adding the option to your launch.json file for the VS Code project.
Here's a short example:
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::string folder = argv[1];
std::cout << folder << '\n'; // Set a breakpoint here
}
I added an extra line of code to your example. Set a breakpoint by clicking left of the line number, a red circle will appear.
{
// 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": "g++",
"args": [
"-Wall",
"-std=c++17",
"-g",
"-O0",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/home/linuxbrew/.linuxbrew/bin"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
]
}
This is a slightly modified auto-generated task. I added -Wall, -std=c++17, and -O0. The file is tasks.json. If you don't create it before attempting to execute the debug, it will ask prompt you to generate it.
{
// 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": [
"/home/lorenzo/Images"
],
"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": "gdb"
}
]
}
This is the auto-generated launch.json. Notice that I added the path argument. The debugger will always invoke with that argument, saving you some typing.
I then hit the Play button in the debugging panel while my C++ file is active, and it will compile and start the debugger for me. From the debug console, running:
-exec print argv[1] prints the file path that I am using as an argument to the program.

Related

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 use the debugger in visual studio code?

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

VS code is ignoring the breakpoint in c++ debugging

I am debugging a c++ code in VS Code but it doesn't stop on breakpoint and visualize the variables, watch and call stack, which it was supposed to do. Instead of this, it prints this in debug console:
Breakpoint 1, 0x000000000040074a in main ()
[Inferior 1 (process 9445) exited normally]
The program '/home/hashir/x/a.out' has exited with code 0 (0x00000000)
here is 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": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "/home/hashir/x/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "/home/hashir/x/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
Compile the program using the -g tag along with g++/clang++.
This problem literally ruined my day. It turned out that all I had to do is just Terminal > Run Build Task or Ctrl+Shift + B and then start debugging.
I've figured out that if your source-code file name contains white spaces, like "Binary Search.cpp", VSCode will ignore the breakpoints regardless of "stop at entry" configuration. Removing the white spaces from my source files' names worked, although their paths contain white spaces. For example "C++ Exercises/BinarySearch.cpp" seems to be valid.
In this issue opened on GitHub, it is suggested that non-ascii characters might cause such problems.
The default launch.json file has this line:
"program": "${workspaceFolder}/a.out",
But this will run a.out to start debugging, and if you configured tasks.json file with only one cpp file, it will have lines like:
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
this will create an executable with the same name with your current file.
Either change the tasks.json to create an a.out file or change launch.json file with the no extension name of your current file.
launch.json:
"program": "${workspaceFolder}/<stripped current file name>",
OR
tasks.json:
"-o",
"${fileDirname}/a.out"
It seem something wrong with environment vars, try open vscode from "developer command prompt for VScode", then on prompt, type: code

Debugging c++ built with a makefile in Visual Studio Code

I have an existing code base that builds with a makefile and I'd like to use Visual Studio Code to run it.
I started by opening my project directory with Visual Studio Code.
Then, for building I created a task as per http://code.visualstudio.com/docs/languages/cpp :
{
"version": "0.1.0",
"command": "bash",
"isShellCommand": true,
"args":["-c", "cd build && make"]
}
which works fine. I then downloaded the C++ extension and created a launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch",
"type": "cppdbg",
"request": "launch",
"targetArchitecture": "x64",
"program": "${workspaceRoot}/build/myProgram",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"linux": {
"MIMode": "gdb"
},
"osx": {
"MIMode": "lldb"
},
"windows": {
"MIMode": "gdb"
}
},
// attach here, which I don't care about
]
}
This launch file allows me to start my program using the built-in debugger. I know that it works because I see all the symbol files getting loaded and I can pause the program.
However, VS Code doesn't "see" my source files; when I pause it says
Source /Unknown Source is not available.
I also can't set breakpoints in the source. I see that some symbols get loaded though as I can see my function names on the call stack when I pause execution.
So what did I miss? Do I absolutely have to do as they say here ( http://code.visualstudio.com/docs/languages/cpp ) and make a g++ task where I'll have to manually input all my include paths and linker inputs? The point of using a makefile in the first place was to not have to do this tedious stuff...
Thanks a lot to anyone who knows how to wrangle VS code.
You should be able to debug by just using tasks.json and launch.json.
Are you sure you have the -g option set in your makefile?
Another thing - you can have your task be executed on launch by adding
"preLaunchTask": "bash" to your your launch.json.
Hope this helps!
At windows; Mingw, gdb and -g parameter at compilation of the executable are necessary with c/c++ extension. "preLaunchTask": "bash" is not necessary in launch.json.