I am trying to configure VSCode for debugging my code. My project is configured by CMake. I use the CMake Tools extensions. Configuring and building as well as quick debugging works so far.
But since I want to configure the launch specifications I let VSCode generate the launch.json file according to:
"Visual Studio Code generates a launch.json with almost all of the required information." https://code.visualstudio.com/docs/cpp/launch-json-reference
I do this by having my main.cpp tab open and then clicking on "create a launch.json file". (See picture.)
I am working in a Ubuntu 18.04 environment. Which is why I select C++ (GDB/LLDB) from the command pop up.
Then a launch.json is created and opened. But it looks extremely empty. See here:
{
// 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": []
}
I expected something more like the example from the VS json reference page:
{
"name": "C++ Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/a.out",
"args": ["arg1", "arg2"],
"environment": [{ "name": "config", "value": "Debug" }],
"cwd": "${workspaceFolder}"
}
Am I missing something? Since I have only a very brief idea of my possibilities with the launch.json and what is required to fill in to make it work correctly, I hoped that VS Code would help me out here.
In Visual Studio IDE, there seems to be an ability to use tracepoints as opposed to breakpoints while debugging. This allows one to debug code without having too many printfs clutter the code. An example of this feature on Visual Studio IDE is provided in this video (time stamp 11 Mins, 14 Seconds). Essentially, instead of writing inside of the code itself printfs to the screen or else fprintfs to a file that then has to be examined later on, when a breakpoint is hit, can some logging information be printed/logged out visually into a debug console/output window?
Is a similar functionality available in VSCode for C++ specifically? At present, when I edit a breakpoint in VSCode, it only allows setting of a conditional breakpoint. The video does not talk about debugging C++ code but is focused on C# and the presenter does state that many of the features overlap with C++.
At present, I compile and build my code for debugging via the following task:
{
"label": "winbuilddebug",
"type": "process",
"command": "msbuild",
"args": [
".vscode/windows.vcxproj",
"/property:GenerateFullPaths=true",
"/property:Configuration=Debug",
"/property:Platform=x64",
"/t:build",
"/consoleloggerparameters:NoSummary"
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": {
"base": "$msCompile",
"fileLocation": "absolute"
}
}
Then, I set up breakpoints and then hit F5 to start debugging. I do not use any other extension specifically for debugging/running, etc.
What I'm trying to do seems simple enough, but it's been crazy hard to actually get there. I have a Django application that runs in a docker-compose environment, and I want to run and debug the unit tests with breakpoints in Vscode.
Since this is a big project with a team that doesn't necessarily use vscode, I can't add libraries willy-nilly (like ptvsd, for example). I'm hoping there's a magic configuration for tasks.json and launch.json that will makes things work.
I have a container for a postgres database, one for django, and one for redis, all defined in docker-compose.yml. There's a command that I can run in the terminal that will run the tests, it's:
docker-compose run --rm app python manage.py test
where app is the django app container. I'd love to be able to run this command in such a way that it can hit breakpoints in vscode.
My incomplete stab at the launch.json file looks like this:
{
"configurations": [{
"name": "Docker: Python - Django",
"type": "docker",
"request": "launch",
"preLaunchTask": "compose-for-debug",
"python": {
"pathMappings": [{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}],
"projectType": "django"
}
}]
}
And my tasks.json:
{
"version": "2.0.0",
"tasks": [{
"type": "docker-build",
"label": "docker-build",
"platform": "python",
"dockerBuild": {
"tag": "dockerdebugging:latest",
"dockerfile": "${workspaceFolder}/Dockerfile",
"context": "${workspaceFolder}",
"pull": true
}
},
{
"type": "docker-run",
"label": "docker-run: debug",
"dependsOn": [
"docker-build"
],
"python": {
"args": [
"test",
"--nothreading",
"--noreload"
],
"file": "manage.py"
}
}
]
}
I think I need to convert the build task to a docker compose task somehow, but I just can't figure out how its done. It may also make sense to run the containers in the terminal, and somehow make vscode attach to them with breakpoints enabled.
Even some help with how to approach this would be great. I know it's a tricky one.
This question became somewhat popular, but a direct answer never came. If you've landed here looking for a way to hit breakpoints inside vscode using docker, my suggestion is to use the Remote Container extension.
When the container is up, right click it and open a vscode window inside of the container itself. Then everything will just work.
I've searched for an answer to this question, but couldn't seem to find one. I know that we can use task.json files to automate the build process. But I want to use Visual Studio Code to implement algorithms in C++ for competitive programming. I want to be able to compile a program, and run it all in one go, if there aren't any errors. If there are errors, I would like them to be displayed.
Also, visual studio code comes with an integrated terminal, so it would be nice if the program output could be redirected there.
Also, how can we map a keyboard shortcut to run this task.
I'm using Visual Studio Code 2019 on Windows 10 with the MinGW G++ compiler.
EDIT
I've tried Escape0707's answer below, and I tried executing 'Run Code' with the default key binding of Ctrl + Alt + N but I'm getting this error.
Updated method which combines make and vscode-cpptools debug:
If you don't care about VSCode integrated debugging tools, which will give you the ability to set breakpoints, change variable value during runtime, inspect variable value, and etc, and you want a somewhat easier, simpler, faster, transparent way to invoke the good old command line tools, skip this section and checkout Code Runner below.
The default configurations come with VSCode C++ extension are kind of slow for low-end machines. The worst part is that they will always rebuild your executable, and don't support 'Start Without Debugging'. Below is a workaround for Linux (and of course remote-WSL).
To address the first issue, you setup make (for simple one source file compiling you only need to install make) to build your source codes, and setup the build task in tasks.json. To address the second issue, you create another task just to run the built executable after the first task finished:
Use Intellisense to learn about each properties in configs.
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"presentation": {
"clear": true,
"focus": true,
"panel": "shared"
},
"tasks": [
{
"label": "make active file",
"type": "shell",
"command": "make",
"args": ["${fileBasenameNoExtension}.out"],
"problemMatcher": "$gcc",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "run active file executable without debuging",
"type": "shell",
"command": "${fileDirname}/${fileBasenameNoExtension}.out",
"presentation": {
"clear": false
}
},
{
"label": "make and run active file without debuging",
"group": {
"kind": "test",
"isDefault": true
},
"dependsOn": [
"make active file",
"run active file executable without debuging"
],
"dependsOrder": "sequence"
}
]
}
To enable debugging using VSCode in this way, first make sure you added -g compile flag to CXXFLAGS in Makefile.
For quick information about how to write a Makefile, see this, or this, or this. Or check this last part of this answer.
Then, create the following launch.json:
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": "make and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.out",
"cwd": "${workspaceFolder}",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}
Now you can use command palette to try Task: Run Build Task, Task: Run Test Task, Debug: Start Debugging.
Original answer
Please consider Code Runner, as it seems faster (for me) than VSCode's built-in debug procedure for practicing with many small C++ code files. I'll describe how I use that extension to satisfy a similar requirement.
Make sure you've configured your PATH to include clang++ so you can invoke it from the integrated terminal.
You can also use g++ by substitute clang++ below with g++. I prefer clang++ as it provides stricter checks for C++ beginners like me.
Install the extension.
In your VSCode's settings.json, consider adding the following entries:
"code-runner.clearPreviousOutput": true,
"code-runner.preserveFocus": false,
"code-runner.runInTerminal": true,
"code-runner.saveFileBeforeRun": true
And add the last customization code-runner.executorMap to user/workspace setting that describes which command you would like the extension to send to the terminal when current filename's extension meets the specified ones. For example:
"code-runner.executorMap": {
"cpp": "\b\b\b\b\b\b\b\b\b\bclang++ -std=c++17 $fileName -o a.out && ./a.out"
},
The above setting tells the extension, "When see a .cpp file, send 10 Backspace to terminal (to delete any mistyped characters) and call clang++ -std=c++17 *filename* -o a.out && ./a.out.
I use this command on my Linux machine, for Windows, try change the filename extension of the output file to .exe and invoke it with .\a.exe or simply a.exe.
Finally, map the Run Code command to your preferred keybinding in VSCode's Keyboard Shortcuts settings. Mine is to bind it to F5 which is originally bound to Debug: Continue.
Happy coding!
Update about make
Read on to learn how to avoid redundant compiling process and speed up case test by utilizing GNU make. I'll do this on Linux and only for C++, since I have not used make on Windows or OS X and C++ is the best for ACM.
Make sure make is installed and in your PATH
Create a file named Makefile (or makefile) under the same directory you invoke make. (Or in another directory and make -f /path/to/Makefile).
Redefine compiler options to whatever you like in the Makefile, e.g.:
CXX = clang++
CXXFLAGS = -std=c++17 -g -Weverything -Werror
Create auto-target rule for *.out in the Makefile, i.e.:
%.out: %.cpp
$(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $#
Attention: must use Tab to indent the second line, not Spaces.
Change code-runner.executorMap to :
"code-runner.executorMap": {
"cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
(Optional) To ignore *.out for git:
echo "*.out" >> .gitignore
(Optional) To remove *.out in current directory:
rm *.out
Now the Run Code command will invoke make and make will only regenerate .out file when the corresponding .cpp file is newer than the .out file, thus allows us to skip compilation and proceed with testing even smoother.
The CXXFLAGS is for C++ compiler options, CFLAGS is for C compiler options. You can find other language compiler options and their variable name using make -p, Google and GNU make manual#Automatic-Variables.
To Build/run C++ projects in VS code , you manually need to configure tasks.json file which is in .vscode folder in workspace folder . To open tasks.json , press ctrl + shift + P , and type Configure tasks , and press enter, it will take you to tasks.json
Here i am providing my tasks.json file with some comments to make the file more understandable , It can be used as a reference for configuring tasks.json , i hope it will be useful
After configuring tasks.json , to compile and run your c++ file , press ctrl+shift+B , this is shortcut for running build tools in vscode . Your C++ program will now run on vscode integrated terminal only .
If this presents some issues , then change default terminal to cmd(by default it is powershell in windows) and make sure there aren't any spaces in path to your file .
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build & run", //It's name of the task , you can have several tasks
"type": "shell", //type can be either 'shell' or 'process' , more details will be given below
"command": "g++",
"args": [
"-g", //gnu debugging flag , only necessary if you want to perform debugging on file
"${file}", //${file} gives full path of the file
"-o",
"${workspaceFolder}\\${fileBasenameNoExtension}", //output file name
"&&", //to join building and running of the file
"${workspaceFolder}\\${fileBasenameNoExtension}"
],
"group": {
"kind": "build", //defines to which group the task belongs
"isDefault": true
},
"presentation": {
"echo": false,
"reveal": "always",
"focus": true,
"panel": "shared",
"clear": false,
"showReuseMessage": false
},
"problemMatcher": "$gcc"
},
]
}
All the properties in the presentation of tasks.json are just used to customize build tasks as per your needs , feel free to change them to what you like best . You can read about presentation properties (and other things) on vscode tasks documentations
I am debugging my CPP code with VSCode. I need to use a preLaunchTask to set my environment before my code run. So my code should run after preLaunchTask right in the same terminal. But it start in two different terminal now. How can I do with this?
And btw how can I start the process in the same terminal next time? Some process will start another terminal next time, I am confuse.
My preLaunchTask:
{
"label": "source_setup",
"type": "shell",
"command": "source ./devel/setup.zsh && export ROS_MASTER_URI=http://localhost:11311/ "
},
As stated by #isidorn in this vscode GitHub issue this feature is currently not yet supported. In the meantime, people can achieve the desired behaviour by adding the following code to their .bashrc
# Source ros setup.bash if present
if [ -f '../devel/setup.bash' ]; then . "../devel/setup.bash";fi
If you don't want to manually switch to the terminal once the task has ran, here is a good workaround:
add this line to your launch.json config:
"internalConsoleOptions": "openOnSessionStart"
This will switch to the terminal view once the task script has finished running.
I think you could just use envFile property.
In my case launch for debugging looks like this (this one is used by python, but it also needs sourcing ./devel/setup.bash before running):
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current ROS File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/devel/setup.bash"
}
]
}