How to shared terminal state and variables between dependent vscode tasks - vscode-tasks

I am using VS Code tasks to run a python script, and I need to first activate a specific Conda environment. So I can reuse the conda activate function in multiple tasks, I would like to activate a specific conda environment in one task and then run scripts in other tasks with the "conda activate" task as a dependency.
However, the following example doesn't appear to work as I expected. When I activate a conda environment in the dependent task, the main task can't "see" the activated environment. I set "panel"="shared", but that doesn't seem to make a difference in my case.
For example
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "activate_myEnv",
"type": "shell",
"command": "eval \"$(conda shell.bash hook)\" && conda activate myEnv && which python",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
}
},
{
"label": "which_python",
"dependsOn": ["activate_myEnv"],
"type": "shell",
"command": "which python",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
}
},
}
When I run the which_python task, the ouptut is:
> Executing task: eval "$(conda shell.bash hook)" && conda activate myEnv && which python <
/home/blaylock/anaconda3/envs/myEnv/bin/python #<-- myEnv is successfully activated
Terminal will be reused by tasks, press any key to close it.
> Executing task: which python <
/home/blaylock/anaconda3/envs/base/bin/python #<-- But the second task reverts to the base conda environment.
Terminal will be reused by tasks, press any key to close it.
Maybe I misunderstood what "panel"="shared" (which is the default) does, but I expected my second task to recognize that I have changed conda environments.
Edit
In this a more simplistic example, I have set variable a in one task, and try to print it in a subsequent task, but the value isn't known...
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "set_var_a",
"type": "shell",
"command": "a=5 && echo a=$a",
},
{
"label": "echo_a",
"dependsOn": ["set_var_a"],
"type": "shell",
"command": "echo a=$a",
}
}
The oupt of running the echo_a task
> Executing task: a=5 && echo a=$a <
a=5
Terminal will be reused by tasks, press any key to close it.
> Executing task: echo a=$a <
a=
Terminal will be reused by tasks, press any key to close it.
Again, I would have expected the second task to recognize variables set in the dependent task.

Related

How to override "Save Before Run" for a particular task

I have the following as a part of tasks.json to check the syntax of Ada code. It references a bash script, check.sh.
{
"label": "Check Ada",
"type": "shell",
"command": "${workspaceFolder}/.vscode/check.sh",
"args": [
"${file}"
],
"problemMatcher": [
"$ada"
],
"group": "build",
"presentation": {
"echo": true,
"reveal": "always",
"revealProblems": "onProblem",
"focus": true,
"panel": "dedicated",
"showReuseMessage": true,
"clear": true
}
}
Not necessary to know, but check.sh merely calls an Ada tool, gnatmake, like this:
fileName=$1
echo "Checking $fileName"
gnatmake -q -c -gnatc -u -P"/Users/me/bla/bla/bla/build.gpr" "$fileName"
if [[ $? == 0 ]]
then
echo "Checks OK."
else
echo "Checks bad."
fi
In Settings, I have
Task: Save Before Run
Save all dirty editors before running a task. -> Always
I prefer this Setting when doing other tasks such as building or build-and-run. However, when merely doing a syntax check as above, I do not want to save first, in case I have a lot of new errors and want to revert to the previous state.
Is there a way of overriding the Save Before Run in Settings for only the a particular task, such as the Check Ada task here?
I barely know what I am doing so it would be helpful if you address me as a fairly smart fifth-grader.

cpp files not running in vs code [duplicate]

Microsoft's Visual Studio Code editor is quite nice, but it has no default support for building C++ projects.
How do I configure it to do this?
There is a much easier way to compile and run C++ code, no configuration needed:
Install the Code Runner Extension
Open your C++ code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.
Moreover you could update the config in settings.json using different C++ compilers as you want, the default config for C++ is as below:
"code-runner.executorMap": {
"cpp": "g++ $fullFileName && ./a.out"
}
The build tasks are project specific. To create a new project, open a directory in Visual Studio Code.
Following the instructions here, press Ctrl + Shift + P, type Configure Tasks, select it and press Enter.
The tasks.json file will be opened. Paste the following build script into the file, and save it:
{
"version": "0.1.0",
"command": "make",
"isShellCommand": true,
"tasks": [
{
"taskName": "Makefile",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
// Pass 'all' as the build target
"args": ["all"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Now go to menu File → Preferences → Keyboard Shortcuts, and add the following key binding for the build task:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "f8", "command": "workbench.action.tasks.build" }
]
Now when you press F8 the Makefile will be executed, and errors will be underlined in the editor.
A makefile task example for new 2.0.0 tasks.json version.
In the snippet below some comments I hope they will be useful.
{
"version": "2.0.0",
"tasks": [
{
"label": "<TASK_NAME>",
"type": "shell",
"command": "make",
// use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
"options": {
"cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
},
// start the build without prompting for task selection, use "group": "build" otherwise
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared"
},
// arg passing example: in this case is executed make QUIET=0
"args": ["QUIET=0"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["absolute"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Here is how I configured my VS for C++
Make sure to change appropriete paths to where your MinGW installed
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch (GDB)",
"type": "cppdbg",
"request": "launch",
"targetArchitecture": "x86",
"program": "${workspaceRoot}\\${fileBasename}.exe",
"miDebuggerPath":"C:\\mingw-w64\\bin\\gdb.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"externalConsole": true,
"preLaunchTask": "g++"  
}
]
}
tasks.json
{
"version": "0.1.0",
"command": "g++",
"args": ["-g","-std=c++11","${file}","-o","${workspaceRoot}\\${fileBasename}.exe"],
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceRoot}",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
"C:/mingw-w64/x86_64-w64-mingw32/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"__GNUC__=6",
"__cdecl=__attribute__((__cdecl__))"
],
"intelliSenseMode": "msvc-x64",
"browse": {
"path": [
"${workspaceRoot}",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
"C:/mingw-w64/x86_64-w64-mingw32/include"
]
},
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
],
"version": 3
}
Reference:
C/C++ for VS Code
c_cpp_properties.json template
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
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}\\build\\${fileBasenameNoExtension}", //output file name
"&&", //to join building and running of the file
"${workspaceFolder}\\build\\${fileBasenameNoExtension}"
],
"group": {
"kind": "build", //defines to which group the task belongs
"isDefault": true
},
"presentation": { //Explained in detail below
"echo": false,
"reveal": "always",
"focus": true,
"panel": "shared",
"clear": false,
"showReuseMessage": false
},
"problemMatcher": "$gcc"
},
]
}
Now , stating directly from the VS code tasks documentation
description of type property :
type: The task's type. For a custom task, this can either be shell or process. If shell is specified, the command is interpreted
as a shell command (for example: bash, cmd, or PowerShell). If
process is specified, the command is interpreted as a process to
execute.
The behavior of the terminal can be controlled using the
presentation property in tasks.json . It offers the following properties:
reveal: Controls whether the Integrated Terminal panel is brought to front. Valid values are:
- always - The panel is always brought to front. This is the default
- never - The user must explicitly bring the terminal panel to the front using the
View > Terminal command (Ctrl+`).
- silent - The terminal panel is brought to front only if the output is not scanned for errors and warnings.
focus: Controls whether the terminal is taking input focus or not. Default is false.
echo: Controls whether the executed command is echoed in the terminal. Default is true.
showReuseMessage: Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
panel: Controls whether the terminal instance is shared between task runs. Possible values are:
- shared: The terminal is shared and the output of other task runs are added to the same terminal.
- dedicated: The terminal is dedicated to a specific task. If that task is executed again, the terminal is reused. However, the
output of a different task is presented in a different terminal.
- new: Every execution of that task is using a new clean terminal.
clear: Controls whether the terminal is cleared before this task is run. Default is false.
Out of frustration at the lack of clear documentation,
I've created a Mac project on github that should just work (both building and debugging):
vscode-mac-c-example
Note that it requires XCode and the VSCode Microsoft cpptools extension.
I plan to do the same for Windows and linux (unless Microsoft write decent documentation first...).
First of all, goto extensions (Ctrl + Shift + X) and install 2 extensions:
Code Runner
C/C++
Then, then reload the VS Code and select a play button on the top of the right corner your program runs in the output terminal. You can see output by Ctrl + Alt + N.
To change other features goto user setting.
The basic problem here is that building and linking a C++ program depends heavily on the build system in use. You will need to support the following distinct tasks, using some combination of plugins and custom code:
General C++ language support for the editor. This is usually done using ms-vscode.cpptools, which most people expect to also handle a lot of other stuff, like build support. Let me save you some time: it doesn't. However, you will probably want it anyway.
Build, clean, and rebuild tasks. This is where your choice of build system becomes a huge deal. You will find plugins for things like CMake and Autoconf (god help you), but if you're using something like Meson and Ninja, you are going to have to write some helper scripts, and configure a custom "tasks.json" file to handle these. Microsoft has totally changed everything about that file over the last few versions, right down to what it is supposed to be called and the places (yes, placeS) it can go, to say nothing of completely changing the format. Worse, they've SORT OF kept backward compatibility, to be sure to use the "version" key to specify which variant you want. See details here:
https://code.visualstudio.com/docs/editor/tasks
...but note conflicts with:
https://code.visualstudio.com/docs/languages/cpp
WARNING: IN ALL OF THE ANSWERS BELOW, ANYTHING THAT BEGINS WITH A "VERSION" TAG BELOW 2.0.0 IS OBSOLETE.
Here's the closest thing I've got at the moment. Note that I kick most of the heavy lifting off to scripts, this doesn't really give me any menu entries I can live with, and there isn't any good way to select between debug and release without just making another three explicit entries in here. With all that said, here is what I can tolerate as my .vscode/tasks.json file at the moment:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build project",
"type": "shell",
"command": "buildscripts/build-debug.sh",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
// Reveal the output only if unrecognized errors occur.
"echo": true,
"focus": false,
"reveal": "always",
"panel": "shared"
},
// Use the standard MS compiler pattern to detect errors, warnings and infos
"options": {
"cwd": "${workspaceRoot}"
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
},
{
"label": "rebuild project",
"type": "shell",
"command": "buildscripts/rebuild-debug.sh",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
// Reveal the output only if unrecognized errors occur.
"echo": true,
"focus": false,
"reveal": "always",
"panel": "shared"
},
// Use the standard MS compiler pattern to detect errors, warnings and infos
"options": {
"cwd": "${workspaceRoot}"
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
},
{
"label": "clean project",
"type": "shell",
"command": "buildscripts/clean-debug.sh",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
// Reveal the output only if unrecognized errors occur.
"echo": true,
"focus": false,
"reveal": "always",
"panel": "shared"
},
// Use the standard MS compiler pattern to detect errors, warnings and infos
"options": {
"cwd": "${workspaceRoot}"
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Note that, in theory, this file is supposed to work if you put it in the workspace root, so that you aren't stuck checking files in hidden directories (.vscode) into your revision control system. I have yet to see that actually work; test it, but if it fails, put it in .vscode. Either way, the IDE will bitch if it isn't there anyway. (Yes, at the moment, this means I have been forced to check .vscode into subversion, which I'm not happy about.) Note that my build scripts (not shown) simply create (or recreate) a DEBUG directory using, in my case, meson, and build inside it (using, in my case, ninja).
Run, debug, attach, halt. These are another set of tasks, defined in "launch.json". Or at least they used to be. Microsoft has made such a hash of the documentation, I'm not even sure anymore.
Here is how I configured my VS for C++ using g++ compiler and it works great including debugging options:
tasks.json file
{
"version": "0.1.0",
"command": "g++",
"isShellCommand": true,
// compiles and links with debugger information
"args": ["-g", "-o", "hello.exe", "hello.cpp"],
// without debugger information
// "args": ["-o", "hello.exe", "hello.cpp"],
"showOutput": "always"
}
launch.json file
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch (Windows)",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/hello.exe",
"MIMode": "gdb",
"miDebuggerPath": "C:\\MinGw\\bin\\gdb.exe",
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"externalConsole": false,
"visualizerFile": "${workspaceRoot}/my.natvis"
}
]
}
I also have 'C/C++ for Visual Studio Code' extension installed in VS Code
If your project has a CMake configuration it's pretty straight forward to setup VSCode, e.g. setup tasks.json like below:
{
"version": "0.1.0",
"command": "sh",
"isShellCommand": true,
"args": ["-c"],
"showOutput": "always",
"suppressTaskName": true,
"options": {
"cwd": "${workspaceRoot}/build"
},
"tasks": [
{
"taskName": "cmake",
"args": ["cmake ."]
},
{
"taskName": "make",
"args" : ["make"],
"isBuildCommand": true,
"problemMatcher": {
"owner": "cpp",
"fileLocation": "absolute",
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
This assumes that there is a folder build in the root of the workspace with a CMake configuration.
There's also a CMake integration extension that adds a "CMake build" command to VScode.
PS! The problemMatcher is setup for clang-builds. To use GCC I believe you need to change fileLocation to relative, but I haven't tested this.
With an updated VS Code you can do it in the following manner:
Hit (Ctrl+P) and type:
ext install cpptools
Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):
Type in your code and hit save.
Hit (Ctrl+Shift+P and type, Configure task runner and then select other at the bottom of the list.
Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:
#echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% hello.cpp /link %linkerflags%
Edit the task.json file as follows and save it:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "build.bat",
"isShellCommand": true,
//"args": ["Hello World"],
"showOutput": "always"
}
Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.
For debugging the project, Hit F5 and select C++(Windows).
In launch.json file, edit the following line and save the file:
"program": "${workspaceRoot}/hello.exe",
Hit F5.
Can use Extension Code Runner to run code with play icon on top Right ans by shortcut key :Ctrl+Alt+N and to abort Ctrl+Alt+M. But by default it only shows output of program but for receiving input you need to follow some steps:
Ctrl+, and then settings menu opens and Extensions>Run Code Configuration scroll down its attributes and find Edit in settings.json click on it and add following code insite it :
{
"code-runner.runInTerminal": true
}
You can reference to this latest gist having a version 2.0.0 task for Visual Studio Code, https://gist.github.com/akanshgulati/56b4d469523ec0acd9f6f59918a9e454
You can easily compile and run each file without updating the task. It's generic and also opens the terminal for input entries.
There's now a C/C++ language extension from Microsoft. You can install it by going to the "quick open" thing (Ctrl+p) and typing:
ext install cpptools
You can read about it here:
https://blogs.msdn.microsoft.com/vcblog/2016/03/31/cc-extension-for-visual-studio-code/
It's very basic, as of May 2016.

Using the g++ compiler in VS Code [duplicate]

Microsoft's Visual Studio Code editor is quite nice, but it has no default support for building C++ projects.
How do I configure it to do this?
There is a much easier way to compile and run C++ code, no configuration needed:
Install the Code Runner Extension
Open your C++ code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.
Moreover you could update the config in settings.json using different C++ compilers as you want, the default config for C++ is as below:
"code-runner.executorMap": {
"cpp": "g++ $fullFileName && ./a.out"
}
The build tasks are project specific. To create a new project, open a directory in Visual Studio Code.
Following the instructions here, press Ctrl + Shift + P, type Configure Tasks, select it and press Enter.
The tasks.json file will be opened. Paste the following build script into the file, and save it:
{
"version": "0.1.0",
"command": "make",
"isShellCommand": true,
"tasks": [
{
"taskName": "Makefile",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
// Pass 'all' as the build target
"args": ["all"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Now go to menu File → Preferences → Keyboard Shortcuts, and add the following key binding for the build task:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "f8", "command": "workbench.action.tasks.build" }
]
Now when you press F8 the Makefile will be executed, and errors will be underlined in the editor.
A makefile task example for new 2.0.0 tasks.json version.
In the snippet below some comments I hope they will be useful.
{
"version": "2.0.0",
"tasks": [
{
"label": "<TASK_NAME>",
"type": "shell",
"command": "make",
// use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
"options": {
"cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
},
// start the build without prompting for task selection, use "group": "build" otherwise
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared"
},
// arg passing example: in this case is executed make QUIET=0
"args": ["QUIET=0"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["absolute"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Here is how I configured my VS for C++
Make sure to change appropriete paths to where your MinGW installed
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch (GDB)",
"type": "cppdbg",
"request": "launch",
"targetArchitecture": "x86",
"program": "${workspaceRoot}\\${fileBasename}.exe",
"miDebuggerPath":"C:\\mingw-w64\\bin\\gdb.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"externalConsole": true,
"preLaunchTask": "g++"  
}
]
}
tasks.json
{
"version": "0.1.0",
"command": "g++",
"args": ["-g","-std=c++11","${file}","-o","${workspaceRoot}\\${fileBasename}.exe"],
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceRoot}",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
"C:/mingw-w64/x86_64-w64-mingw32/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"__GNUC__=6",
"__cdecl=__attribute__((__cdecl__))"
],
"intelliSenseMode": "msvc-x64",
"browse": {
"path": [
"${workspaceRoot}",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
"C:/mingw-w64/x86_64-w64-mingw32/include"
]
},
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
],
"version": 3
}
Reference:
C/C++ for VS Code
c_cpp_properties.json template
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
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}\\build\\${fileBasenameNoExtension}", //output file name
"&&", //to join building and running of the file
"${workspaceFolder}\\build\\${fileBasenameNoExtension}"
],
"group": {
"kind": "build", //defines to which group the task belongs
"isDefault": true
},
"presentation": { //Explained in detail below
"echo": false,
"reveal": "always",
"focus": true,
"panel": "shared",
"clear": false,
"showReuseMessage": false
},
"problemMatcher": "$gcc"
},
]
}
Now , stating directly from the VS code tasks documentation
description of type property :
type: The task's type. For a custom task, this can either be shell or process. If shell is specified, the command is interpreted
as a shell command (for example: bash, cmd, or PowerShell). If
process is specified, the command is interpreted as a process to
execute.
The behavior of the terminal can be controlled using the
presentation property in tasks.json . It offers the following properties:
reveal: Controls whether the Integrated Terminal panel is brought to front. Valid values are:
- always - The panel is always brought to front. This is the default
- never - The user must explicitly bring the terminal panel to the front using the
View > Terminal command (Ctrl+`).
- silent - The terminal panel is brought to front only if the output is not scanned for errors and warnings.
focus: Controls whether the terminal is taking input focus or not. Default is false.
echo: Controls whether the executed command is echoed in the terminal. Default is true.
showReuseMessage: Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
panel: Controls whether the terminal instance is shared between task runs. Possible values are:
- shared: The terminal is shared and the output of other task runs are added to the same terminal.
- dedicated: The terminal is dedicated to a specific task. If that task is executed again, the terminal is reused. However, the
output of a different task is presented in a different terminal.
- new: Every execution of that task is using a new clean terminal.
clear: Controls whether the terminal is cleared before this task is run. Default is false.
Out of frustration at the lack of clear documentation,
I've created a Mac project on github that should just work (both building and debugging):
vscode-mac-c-example
Note that it requires XCode and the VSCode Microsoft cpptools extension.
I plan to do the same for Windows and linux (unless Microsoft write decent documentation first...).
First of all, goto extensions (Ctrl + Shift + X) and install 2 extensions:
Code Runner
C/C++
Then, then reload the VS Code and select a play button on the top of the right corner your program runs in the output terminal. You can see output by Ctrl + Alt + N.
To change other features goto user setting.
The basic problem here is that building and linking a C++ program depends heavily on the build system in use. You will need to support the following distinct tasks, using some combination of plugins and custom code:
General C++ language support for the editor. This is usually done using ms-vscode.cpptools, which most people expect to also handle a lot of other stuff, like build support. Let me save you some time: it doesn't. However, you will probably want it anyway.
Build, clean, and rebuild tasks. This is where your choice of build system becomes a huge deal. You will find plugins for things like CMake and Autoconf (god help you), but if you're using something like Meson and Ninja, you are going to have to write some helper scripts, and configure a custom "tasks.json" file to handle these. Microsoft has totally changed everything about that file over the last few versions, right down to what it is supposed to be called and the places (yes, placeS) it can go, to say nothing of completely changing the format. Worse, they've SORT OF kept backward compatibility, to be sure to use the "version" key to specify which variant you want. See details here:
https://code.visualstudio.com/docs/editor/tasks
...but note conflicts with:
https://code.visualstudio.com/docs/languages/cpp
WARNING: IN ALL OF THE ANSWERS BELOW, ANYTHING THAT BEGINS WITH A "VERSION" TAG BELOW 2.0.0 IS OBSOLETE.
Here's the closest thing I've got at the moment. Note that I kick most of the heavy lifting off to scripts, this doesn't really give me any menu entries I can live with, and there isn't any good way to select between debug and release without just making another three explicit entries in here. With all that said, here is what I can tolerate as my .vscode/tasks.json file at the moment:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build project",
"type": "shell",
"command": "buildscripts/build-debug.sh",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
// Reveal the output only if unrecognized errors occur.
"echo": true,
"focus": false,
"reveal": "always",
"panel": "shared"
},
// Use the standard MS compiler pattern to detect errors, warnings and infos
"options": {
"cwd": "${workspaceRoot}"
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
},
{
"label": "rebuild project",
"type": "shell",
"command": "buildscripts/rebuild-debug.sh",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
// Reveal the output only if unrecognized errors occur.
"echo": true,
"focus": false,
"reveal": "always",
"panel": "shared"
},
// Use the standard MS compiler pattern to detect errors, warnings and infos
"options": {
"cwd": "${workspaceRoot}"
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
},
{
"label": "clean project",
"type": "shell",
"command": "buildscripts/clean-debug.sh",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
// Reveal the output only if unrecognized errors occur.
"echo": true,
"focus": false,
"reveal": "always",
"panel": "shared"
},
// Use the standard MS compiler pattern to detect errors, warnings and infos
"options": {
"cwd": "${workspaceRoot}"
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Note that, in theory, this file is supposed to work if you put it in the workspace root, so that you aren't stuck checking files in hidden directories (.vscode) into your revision control system. I have yet to see that actually work; test it, but if it fails, put it in .vscode. Either way, the IDE will bitch if it isn't there anyway. (Yes, at the moment, this means I have been forced to check .vscode into subversion, which I'm not happy about.) Note that my build scripts (not shown) simply create (or recreate) a DEBUG directory using, in my case, meson, and build inside it (using, in my case, ninja).
Run, debug, attach, halt. These are another set of tasks, defined in "launch.json". Or at least they used to be. Microsoft has made such a hash of the documentation, I'm not even sure anymore.
Here is how I configured my VS for C++ using g++ compiler and it works great including debugging options:
tasks.json file
{
"version": "0.1.0",
"command": "g++",
"isShellCommand": true,
// compiles and links with debugger information
"args": ["-g", "-o", "hello.exe", "hello.cpp"],
// without debugger information
// "args": ["-o", "hello.exe", "hello.cpp"],
"showOutput": "always"
}
launch.json file
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch (Windows)",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/hello.exe",
"MIMode": "gdb",
"miDebuggerPath": "C:\\MinGw\\bin\\gdb.exe",
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"externalConsole": false,
"visualizerFile": "${workspaceRoot}/my.natvis"
}
]
}
I also have 'C/C++ for Visual Studio Code' extension installed in VS Code
If your project has a CMake configuration it's pretty straight forward to setup VSCode, e.g. setup tasks.json like below:
{
"version": "0.1.0",
"command": "sh",
"isShellCommand": true,
"args": ["-c"],
"showOutput": "always",
"suppressTaskName": true,
"options": {
"cwd": "${workspaceRoot}/build"
},
"tasks": [
{
"taskName": "cmake",
"args": ["cmake ."]
},
{
"taskName": "make",
"args" : ["make"],
"isBuildCommand": true,
"problemMatcher": {
"owner": "cpp",
"fileLocation": "absolute",
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
This assumes that there is a folder build in the root of the workspace with a CMake configuration.
There's also a CMake integration extension that adds a "CMake build" command to VScode.
PS! The problemMatcher is setup for clang-builds. To use GCC I believe you need to change fileLocation to relative, but I haven't tested this.
With an updated VS Code you can do it in the following manner:
Hit (Ctrl+P) and type:
ext install cpptools
Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):
Type in your code and hit save.
Hit (Ctrl+Shift+P and type, Configure task runner and then select other at the bottom of the list.
Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:
#echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% hello.cpp /link %linkerflags%
Edit the task.json file as follows and save it:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "build.bat",
"isShellCommand": true,
//"args": ["Hello World"],
"showOutput": "always"
}
Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.
For debugging the project, Hit F5 and select C++(Windows).
In launch.json file, edit the following line and save the file:
"program": "${workspaceRoot}/hello.exe",
Hit F5.
Can use Extension Code Runner to run code with play icon on top Right ans by shortcut key :Ctrl+Alt+N and to abort Ctrl+Alt+M. But by default it only shows output of program but for receiving input you need to follow some steps:
Ctrl+, and then settings menu opens and Extensions>Run Code Configuration scroll down its attributes and find Edit in settings.json click on it and add following code insite it :
{
"code-runner.runInTerminal": true
}
You can reference to this latest gist having a version 2.0.0 task for Visual Studio Code, https://gist.github.com/akanshgulati/56b4d469523ec0acd9f6f59918a9e454
You can easily compile and run each file without updating the task. It's generic and also opens the terminal for input entries.
There's now a C/C++ language extension from Microsoft. You can install it by going to the "quick open" thing (Ctrl+p) and typing:
ext install cpptools
You can read about it here:
https://blogs.msdn.microsoft.com/vcblog/2016/03/31/cc-extension-for-visual-studio-code/
It's very basic, as of May 2016.

VS code - Hide build/echo task for cpp

I'm using VS Code for running c++ code.
Whenever I Ctrl + Shift + B to build my .cpp file, an 'echo' tab pops up, which makes the entire bottom panel appear and then I am asked to "Terminal will be reused by tasks, press any key to close it."
I don't want the tab or the panel to pop up at all and want the entire build process to happen in silence, nothing pops up.
This is my tasks.json file
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "gcc",
"args":[
"main.cpp","-lstdc++","-o" ,"main.exe"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
This can be configured using "presentation": {...}. Following worked for me:
{
"version": "2.0.0",
"tasks": [
{
"label": "Test task",
"type": "shell",
"command": "echo Hello world",
"presentation": {
"echo": true,
"reveal": "never",
"showReuseMessage": false,
}
}
]
}
Solved by downgrading VSCode to 1.60: https://code.visualstudio.com/updates/v1_60

Is there a way to get a pickString dynamically populated in a VS Code task?

I'd like to provide a list of strings as a pickString for a task. The list of strings will be a list of folder names, which I can get from PowerShell, but I'm not sure how to display this list in a task.
How can I set up my task and input so this list can be populated?
{
"version": "2.0.0",
"tasks": [
{
"label": "Test Task",
"type": "shell",
"windows": {
"command": "echo",
"args": [
"-opt",
"${input:optionsList}"
]
}
}
],
"inputs": [
"id": "optionsList",
"type": "pickString",
"options": [<insert something here>]
]
}
I want the user to see the list of folders while the task is running.
Problem
Actually VSCode tasks doesn't have this functionality built-in. The enhancement request was closed probably because there is no plans to develop it in the near future.
Alternative Solution
You can install the augustocdias.tasks-shell-input and configure an input variable with type command calling this extension for populating the pick list.
Follow the following steps:
Install the extension with:
Search in the Extensions Sidebar (Ctrl+Shift+X) for augustocdias.tasks-shell-input and install or
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter:
ext install augustocdias.tasks-shell-input
Configure your task.json with:
A task with the command you want to execute
Add to the task args configuration entry one or more references to input variables like ${input:my_variable}.
Configure an entry in the inputs section with:
id: use the same variable name defined in task args like my_variable for ${input:my_variable}
type: command
command: shellCommand.execute
args: add an config with the properties: command, cwd, env
See the example task.json file bellow.
Example
Example task.json file using augustocdias.tasks-shell-input extension:
{
"version": "2.0.0",
"tasks": [
{
"label": "Dynamically Populated Task",
"type": "shell",
"command": "echo",
"args": [
"'${input:my_dynamic_input_variable}'"
],
"problemMatcher": []
}
],
"inputs": [
{
"id": "my_dynamic_input_variable",
"type": "command",
"command": "shellCommand.execute",
"args": {
"command": "ls -1 *.*",
"cwd": "${workspaceFolder}",
"env": {
"WORKSPACE": "${workspaceFolder[0]}",
"FILE": "${file}",
"PROJECT": "${workspaceFolderBasename}"
}
},
}
]
}
Task/Launch Input Variables shows a way to do this with a command input variable. That command can come from vscode's built-in commands or from an extension. In your case, there is no built-in command which returns a list of folders in a given workspace. But it is fairly straightforward to do it in an extension. The documentation does not give a full example of how to do this so I'll show one here. First the demo of it working to ls a chosen folder in a task:
.
Here is the entire tasks.json file:
{
"version": "2.0.0",
"tasks": [
{
"label": "List Folder Choice files",
"type": "shell",
"command": "ls", // your command here
"args": [
"${input:pickTestDemo}" // wait for the input by "id" below
],
"problemMatcher": []
}
],
"inputs": [
{
"id": "pickTestDemo",
"type": "command",
"command": "folder-operations.getFoldersInWorkspace" // returns a QuickPick element
},
]
}
You can see in the input variables that a command is called from the folder-operations extension. Since that command returns a QuickPick element that is what you'll see when you run the task.
Here is the guts of the extension:
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
/**
* #param {vscode.ExtensionContext} context
*/
function activate(context) {
let disposable = vscode.commands.registerCommand('folder-operations.getFoldersInWorkspace', async function () {
// get the workspaceFolder of the current file, check if multiple workspaceFolders
// a file must be opened
const wsFolders = await vscode.workspace.workspaceFolders;
if (!wsFolders) vscode.window.showErrorMessage('There is no workspacefolder open.')
const currentWorkSpace = await vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri);
// filter out files, keep folder names. Returns an array of string.
// no attempt made here to handle symbolic links for example - look at lstatSync if necessary
const allFilesFolders = fs.readdirSync(currentWorkSpace.uri.fsPath);
const onlyFolders = allFilesFolders.filter(f => fs.statSync(path.join(currentWorkSpace.uri.fsPath, f)).isDirectory());
// showQuickPick() takes an array of strings
return vscode.window.showQuickPick(onlyFolders);
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {}
module.exports = {
activate,
deactivate
}
Here is a link to the folder-operations demo extension so you can look at the full extension code and its package.json. Once you get your extension publishing credentials set up it is really pretty easy to publish more.
Short of installing an extension or writing your own, you should first determine your workspace folder structure.
You could have
Single-root workspace (workspace=folder)
Multi-root workspace with main folder (workspace=folder)
Multi-root workspace with no main folder (workspace=folder/../)
There are built-in vars that allow you to access, for example
folder path (=workspace if 1,2,3) ${workspaceFolder}
current file path relative to ${workspaceFolder} ${relativeFileDirname}
Say you want to run git gui for the repo of the current open file - with "cwd" : "${relativeFileDirname}" in tasks.json config, git should pick up the current repo, and you don't need to ask for the folder path.