Debugging C/C++ Language Not Hitting Breakpoints - c++

I have the following file overflow.c that I'm trying to debug through breakpoints in Visual Studio Code macOS:
#include <stdio.h>
int main(void) {
int n = 1;
for (int i = 0; i < 64; i++)
{
printf("%i\n", n);
n = n * 2;
}
return 0;
}
I've built it by typing make overflow in the terminal, which returns
cc overflow.o -o overflow
And I can do ./overflow in the terminal to run it, which works. I have the C/C++ extension by Microsoft installed. My launch.json looks like the following:
{
"version": "0.2.0",
"configurations": [
{
"name": "C Run",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/overflow",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb"
}
]
}
When I debug using the "C Run" configuration, it runs my entire code without hitting any of my breakpoints (found here)
The "C Attach" is for attaching to an already-running app, which isn't applicable here. I've added the following to my PATH:
PATH="/Applications/Xcode.app/Contents/Developer/usr/bin:${PATH}"
My debug console after debugging "C Run" config loads bunch of symbols, returns output from my print statements, and ends with
The program '/Users/ahlam/Downloads/workspace/overflow' has exited with code 0 (0x00000000).
EDIT: I've also tried it with C++ and it has the same behavior. Made a hello.cpp, built using g++ hello.cpp and debugging just ran the entire code without hitting any breakpoints.
Any help is appreciated.

You need to generate source-level debug information, which you can do by using the -g flag in clang:
clang -g overflow.c -o overflow
Do that instead of make overflow. You'll see a folder called overflow.dSYM in your directory. Debugging should now work.

Related

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.

Debugging a c++ code with Visual Studio Code Ubuntu

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.

How to read input when debugging in C++ in Visual Studio Code?

I'm using VSCode for debugging my CPP program in MacOSX.
I've 2 programs.
Program1
int main(){
string a;
a = "a";
a += 'b';
cout<<a<<endl;
return 0;
}
Program2
int main(){
string a;
cin>>a;
a += 'b'
cout<<a;
return 0;
}
In program1 I'm directly assigning the string a and when I debug the program in VSCode by first compiling it in terminal using :
g++ -g filename.cpp
and then selecting the Starting Debugging option in the Debugging menu. I'm able to see the state of the string a variable by moving forward in breakpoints.
The VARIABLES section shows the state of different variables and the CALL STACK show the stack frame.
But, for program2, when I go past the breakpoint of the cin>>a;, the contents of VARIABLES and of CALL STACK get cleared up.
Here are the contents of the launch.json file:
{
"version": "0.2.0",
"configurations": [
{
"name": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb"
}
]
}
How can I get user-input and move forward to debug my code?
As stated in Here
if you enable "externalConsole":true in the launch.json then you will get a pop up console window that you can type in.
To debug with inputs, you can edit the arg section as shown below:
"program": "${workspaceFolder}/main",
"args": ["<", "input_file.in"]
The example above should be the same as: ./main < input_file.in
I hope this helps anyone who comes around here:
by (1) setting "externalConsole" to true and (2) checking (enabling) "Run In Terminal" in Code-Runner Extension configuration, you can plug-in your input to your code by typing the input on the external console, that would pop up when you run your code.
Install extension CodeLLDB
Add new configuration CodeLLDB: Launch
Set program property as "program": "${workspaceFolder}/${fileBasenameNoExtension}"
(optional) Rebuild code
Chose created Launch config in VS Debug tab. And start it!
Profit!
Video manual
simply:-
step1. click on small gear-icon of debugger window.
step2. make "true" to this ["externalConsole": false,] in launch.json file.
step3. and just restart your debugger.
I also encountered the same problem, my solution was to replace cygwin's gdb and g ++ with mingw64's.
In my case this was a two-step process.
Enable externalConsole: true, as described in other responses.
Let VS code control the terminal.
If the code you are debugging requires user input, set external Console to true. after entering input, avoid clicking "x" to close the external Console. Instead, click "-" to minimise the window. Then keep hitting f10 or f11 to continue debugging.

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.

VSCode: Debugger for C++ does not launch nor attach properly

I am using:
Ubuntu 16.04 (I know it is not supported officially)
Latest VSCode version
Latest "C/C++ for VSCode" version
My project is a C++ project and the structure looks like this:
/home/lvier/mainProject/fooProject (source code)
/home/lvier/mainProject/build/fooProject (binaries)
I am working in the sub-project "/home/lvier/mainProject/fooProject" and in "/home/lvier/mainProject/build/fooProject" there are many sub programs (lets say "foo", "foo_sub1", "foo_sub2" ...).
My goal:
I want to start the program "foo" (which starts all other foo_sub-programs) and then, I want to debug a certain sub program (let's say "foo_sub1") by attaching to it. I am also fine with starting and debugging in the same time as long as I can debug the sub-program "foo_sub1". The main project itself does not contain any executables.
Some months ago, debugging was working with "attach". For me it is not working anymore (because of VSCode updates and/or C/C++ extension updates). Here are my problems:
Assume that "foo" is running.
When using the "C++ Attach"-config and setting "request": "attach" (which is getting highlighted as "not an accepted value"), it will ask for the property "processId" if it is not set. If I set "processId", the error "Attach not supported" pops up.
If I use the "C++ Attach"-config with "request": "launch" (in the beginning this was autogenerated by the C/C++-extension), then the program finds the process id, tries to attach but then aborts with the message "Unable to start debugging. Commands are only accepted when the process is stopped." - what a surprise.
Assume that "foo" is not running yet.
When using the "C++ Launch"-config, the program starts but no UI elements appear. Instead, it starts with a new terminal popping up which says "warning gdb failed to set controlling terminal operation not permitted" for a brief moment and in the internal console of VSCode, it states that it stops at a certain line of code (a breakpoint not defined by me) and prints
"Stopped due to shared library event (no libraries added or removed)
Loaded '/lib64/ld-linux-x86-64.so.2'. Symbols loaded.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1"."
From there I can't continue further and I have to manually terminate the program.
When I use GDB without VSCode, i.e. just by native terminal, my program is starting properly but with VSCode, there seem to be some issues currently.
This is my current, autogenerated config where I only edited the "cwd" and "program" paths (assume that the environment variable "${env.build_foo}" is set to "/home/lvier/mainProject/build/fooProject"):
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch",
"type": "cppdbg",
"request": "launch",
"targetArchitecture": "x64",
"program": "${env.build_foo}/foo",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"linux": {
"MIMode": "gdb"
},
"osx": {
"MIMode": "lldb"
},
"windows": {
"MIMode": "gdb"
}
},
{
"name": "C++ Attach",
"type": "cppdbg",
"targetArchitecture": "x64",
"request": "launch", // <-- "attach" is not allowed (anymore)! :(
"program": "${env.build_foo}/foo_sub1",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"processId": "${command.pickProcess}",
"externalConsole": false,
"linux": {
"MIMode": "gdb"
},
"osx": {
"MIMode": "lldb"
},
"windows": {
"MIMode": "gdb"
}
}
]
}
So far I am really frustrated and still don't want to give up on VSCode (I don't want to switch to another IDE yet). I have searched a lot for other issues and also tried to set some other config-properties but none of it helped.
Does anyone else also have such issues with the debugger or is this a general problem with the extension (... and Ubuntu 16.04)?
I am happy for any help or convenient workaround. Thanks in advance!
Note:
I have also created a thread on the related github page (see https://github.com/Microsoft/vscppsamples/issues/115)
Update 07/26/2016:
It seems like there is a bug with the C/C++ extension (see comments in the github link above). It is still being investigated though.
Here solution:
...Debugging works for me now after I removed the GCC -s flag (strip symbol table and relocation information) from the linker settings...
Got it from last answer of the next link (thanks HorstBaerbel):
https://github.com/Microsoft/vscode-cpptools/issues/115#issuecomment-299334301