Configuring task.json and launch.json for C in vs code - visual-studio-code

I am a complete beginner with C and to VSCode. I am trying to configure the task and launch jsons but have no idea where to begin. I have tried googling the answers but I keep getting the same errors. I want to be able to step through the code line by line so I can see what it is doing.
I haven't changed the tasks.json from the original that VSCode sets. The launch.json I have changed by putting in the debugger path and the path of the executable. I have included the task.json, launch.json and the error that keeps popping up. Any help is appreciated.
tasks.json
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc build active file",
"command": "/usr/bin/gcc",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
launch.json
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/scheduler.c",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
]
}
]
}

I've recently had the same issues. Here is the procedure that I follow, that seem to work:
Download and install msys2 (1)
Download MSYS2 from https://www.msys2.org/
Install folder is typically C:\msys64
Go to C:\msys64 and open mingw64.ini
Change ‘#MSYS2_PATH_TYPE=inherit’ to ‘MSYS2_PATH_TYPE=inherit’ i.e. enable PATH variable.
Add PATH environment variables (2)
Type “environment” in Windows search field, and select “Edit environment variables …”
Add path to gcc.exe and g++.exe:
— Add: “C:\msys64\mingw64\bin” to PATH variable.
Add path to VS Code to PATH variable as well:
— This is usually the folder:
C:\Users\<username>\AppData\Local\Programs\Microsoft VS Code\
Run “msys2 mingw64” and test access to compilers and debugger (3)
In Windows Search field, type “msys2” and select “msys2 mingw64” and run the following:
To install gcc, the Gnu C compiler: pacman -S mingw-w64-ucrt-x86_64-gcc
To install gdb, the Gnu GDB debugger:
pacman -S --needed base-devel mingw-w64-x86_64-toolchain
To test that you can run compilers and debugger, run:
gcc --version
g++ --version
gdb --version
Start development in VSC (4)
Open “msys mingw64” terminal and run:
cd <common projects folder>
mkdir <projname>
cd <projname>
Above changes current directory to a projects folder. I use C:\Users<username>\src\projects, i.e. this is my but you may want to use something else.
In the folder you can make a subfolder per C coding project you want to run. This is what “mkdir ” does.
You will need a little Unix Bash shell command skills here, here is an ultrashort summary:
cd – change directory to
mkdir – makes a new directory called
in the current folder.
cd .. – change directory one up.
_ cd ~ – changes directory to your home folder, I have C:\Users<username> where is my … username.
pwd – shows current directory.
Now, if you did above you are currently in the specific projects folder (you can verify this with pwd), and you should start VSC from there by typing:
code .
And accept Workspace trust.
Create a C source file (5)
Open folder view, click on + icon, and select ‘new file’, type “hello.c”, go into the file and add the contents:
include
int main() {
printf("Hello World\n");
return 0;
}
Configure VSC for building – tasks.json (6)
Press “ctrl+shift+B” to build target (or menu: -> Terminal -> Run Build Task… or press green play icon)
Select “C/C++: gcc.exe build and debug active file”
Now it tries to build, using an autogenerated tasks.json file, located in project-folder, in subfolder .vscode:
.vscode/tasks.json
An example of a tasks.json file is shown below:
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc.exe build active file",
"command": "C:\apps\msys64\mingw64\bin\gcc.exe",
"args": [
"-fdiagnostics-color=always",
"-Wall",
"-g",
"${file}",
"-o",
"${fileDirname}\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
The important section is:
"command": "C:\msys64\mingw64\bin\gcc.exe",
"args": [
"-fdiagnostics-color=always",
"-Wall",
"-g",
"${workspaceFolder}/*.c", OR TODO "${file}"
"-o",
"${fileDirname}\${fileBasenameNoExtension}.exe"
],
“command” is the Gnu C compiler, gcc.exe and the full path to it.
“args” are arguments for the compiler:
-Wall means warn about everyting.
-g means compiler must prepare for debugging.
“${file}” is current file.
-o is output file which is specified in the next line with .exe extension.
Sometimes we have to build multi-file projects and it will break the default build-functionality in tasks.json in VSC. In some cases this can be solved by changing:
${file},
to
"${workspaceFolder}/*.c",
Configure VSC for Debugging – launch.json (7)
Go to source file hello.c, and set a break point,
Click left to the line numbers to set red circle.
Select play/bug icon
Select “Debug C/C++ File”
Choose “C/C++ gcc build and debug active file” from list of automatically detected compilers.
This will autogenerate a file, launch.json in the projects folder, in subfolder .vscode:
.vscode/launch.json
An example of a launch.json file is shown below:
{
"configurations": [
{
"name": "C/C++: gcc.exe build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
]
}
],
"preLaunchTask": "C/C++: gcc.exe build active file"
}
The most important parts are:
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
and
"miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
The “program” is the program generated when building the project. I.e. the output from running the task as specified in Tasks.json.
The miDebuggerPath is the path to gdb, the GNU gdb debugger.
If these does not match with your Tasks.json settings and your installation chances are slim to make it work.
Test it by pressing the Play/Bug icon button and notice if there are errors. If not you should be able to step through the code and watch variables etc.
Configure VSC for intellisense (8)
Install extension: “C/C++ extension for VS Code” by Microsoft.
Now this extension will assist when you type code. By example you can type for to get the basics of a for-loop. Similar for if, while etc. Cool!
Save work when creating new projects (9)
Instead of having to create the tasks.json and launch.json files for each project, I copy them to a templates folder, say:
C:\Users\username\src\templates\.vscode\
Copy the newly created tasks.json and launch.json files to the .vscode subfolder.
Now, say you want to create a new project, e.g. hello2, and you create a folder for it:
C:\Users\<username>\src\projects\hello2\
Go to the templates folder by
cd C:\Users<username>\src\templates
and copy the .json files to the new project by:
cp -Rp .vscode/ ../hello2/
And now the new project has the .json files.
Optional (10)
Later you may want to update msys2. To do this, open “msys2 mingw64” and type
pacman -Suy
Done (11)
Finally done … Not the easiest thing to get going, but I still think it is worth it.

Related

How should tasks.json be configured for building a dotnet core solution for debugging in VSCode when the entry project references a class library

I'm having some trouble building dotnet core solutions in VSCode for debugging when the entry project has a reference to another internal class library. I have the "C# for Visual Studio Code (powered by OmniSharp)" extension installed. I am running on Ubuntu 22.04 with the dotnet 6.0.403 sdk.
While I can write, build, and run programs referencing class libraries from the command line without issue, they fail to build when launched from VS Code's "Run and Debug" section.
I've attempted to work through a basic demo solution starting from scratch:
mkdir DebugCode && cd DebugCode
dotnet new sln
dotnet new console -o DebugCode.Console
dotnet new classlib -o DebugCode.Core
dotnet sln add DebugCode.Console/Debug.Console.csproj
dotnet sln add DebugCode.Core/DebugCode.Core.csproj
I put a simple SockDrawer.cs class in the DebugCode.Core project with the following code:
namespace DebugCode.Core;
public class SockDrawer
{
private IList<string> Socks { get; set; } = new List<string>();
public SockDrawer()
{
FillDrawer();
}
public void FillDrawer()
{
Socks.Add("Godzilla socks");
Socks.Add("Sasquatch socks");
Socks.Add("Blue Lightning socks");
Socks.Add("boring work socks");
}
public void ListSocks()
{
foreach(var socks in Socks)
{
Console.Write($"{socks}, ");
}
Console.Write(Environment.NewLine);
}
}
And then I reference that in Program.cs of the DebugCode.Console project.
using DebugCode.Core;
var sockdrawer = new SockDrawer();
sockdrawer.ListSocks();
I can build and execute the program from the root DebugCode directory with no issue
dotnet run --project DebugCode.Console
The trouble starts when I try to launch the build for debugging. The build fails when launching and building from the "Run and Debug" section. Using the default extension generated launch.json and tasks.json files with the content:
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/DebugCode.Console/bin/Debug/net6.0/DebugCode.Console.dll",
"args": [],
"cwd": "${workspaceFolder}/DebugCode.Console",
"console": "integratedTerminal", // I did manually update this line
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/DebugCode.Console/DebugCode.Console.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/DebugCode.Console/DebugCode.Console.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/DebugCode.Console/DebugCode.Console.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
I get a file not found error referencing the dependent class library:
Executing task: dotnet build [redacted]/DebugCode/DebugCode.Console/DebugCode.Console.csproj /property:GenerateFullPaths=true /consoleloggerparameters:NoSummary
MSBuild version 17.3.2+561848881 for .NET
Determining projects to restore...
Restored [redacted]/DebugCode/DebugCode.Console/DebugCode.Console.csproj (in 62 ms).
1 of 2 projects are up-to-date for restore.
DebugCode.Core -> [redacted]/DebugCode/DebugCode.Core/bin/Debug/net6.0/DebugCode.Core.dll
CSC : error CS0006: Metadata file '[redacted]/DebugCode/DebugCode.Core/obj/Debug/net6.0/ref/DebugCode.Core.dll' could not be found [[redacted]/DebugCode/DebugCode.Console/DebugCode.Console.csproj]
* The terminal process "dotnet 'build', '[redacted]/DebugCode/DebugCode.Console/DebugCode.Console.csproj', '/property:GenerateFullPaths=true', '/consoleloggerparameters:NoSummary'" terminated with exit code: 1.
* Terminal will be reused by tasks, press any key to close it.
Based on this error, I've tried updating the build task to build the entire solution instead of just the console project.
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/DebugCode.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
In this case, the build succeeds but debugging fails due to a missing DebugCode.Console.deps.json file:
[redacted].vscode/extensions/ms-dotnettools.csharp-1.25.2-linux-x64/.debugger/vsdbg --interpreter=vscode --connection=/tmp/CoreFxPipe_vsdbg-ui-e0801ed66b6a4fb8aa6f0c54a5fc2cc3
Cannot use file stream for [[redacted]/DebugCode/DebugCode.Console/bin/Debug/net6.0/DebugCode.Console.deps.json]: No such file or directory
A fatal error was encountered. The library 'libhostpolicy.so' required to execute the application was not found in '[redacted]/DebugCode.Console/bin/Debug/net6.0/'.
Failed to run as a self-contained app.
- The application was run as a self-contained app because '[redacted]/DebugCode/DebugCode.Console/bin/Debug/net6.0/DebugCode.Console.runtimeconfig.json' was not found.
- If this should be a framework-dependent app, add the '[redacted]/DebugCode/DebugCode.Console/bin/Debug/net6.0/DebugCode.Console.runtimeconfig.json' file and specify the appropriate framework.
Interestingly, if I build the solution myself manually using the dotnet build DebugCode.sln command from my DebugCode directory, the above referenced DebugCode.Console.deps.json file is generated. Then, when I comment out the "preLaunchTask": "build" line of launch.json, the debugger successfully launches from the "Run and Debug" section. I figure I must have something wrong in the 'build' task in tasks.json, but I'm failing to recognize the difference between the dotnet build command I'm using manually and what tasks.json needs.
I got the preLaunchTask to build and launch the solution successfully in the debugger by removing ${workspaceFolder} from the path to the solution file.
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"DebugCode.sln", // removed ${workspaceFolder}/
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
I don't exactly understand why that works, but at least I'm building and debugging.

How to set up tasks.json file in VSCODE to compile Fortran programs?

I want to set up VScode (OS: Windows 10) to create and then compile programs written in Fortran 90/95. I can do this by typing in the terminal : gfortran -o Example_exe Example.f90 and then ./Example_exe. I don't want to have to write these lines every time, so I tried to set up my tasks.json file to automate a build routine using gfortran as compiler.
I found this tutorial : https://titanwolf.org/Network/Articles/Article?AID=360e0bde-0507-4de4-960c-2eae8fa8c782#gsc.tab=0 but the tasks.json file given is unclear.
Can I have a tasks.json file setup to automate my build routine please ?
I have installed the following extensions : Modern Fortran, Fortran IntelliSense, Code Runner, Fortran Breakpoint Support
Yes you can. Assuming that you want to execute in debug mode, you should create a tasks.json and a launcher.json and place them in .vscode/ at the root of your workspace.
Assuming the following file structure and a debugging mode with GDB for the execution:
root/
.vscode/
code/
Example_exe
This is what your tasks.json should look like:
{
"version": "2.0.0",
"tasks": [
{
"label": "compile",
"type": "shell",
"command": "gfortran -o Example_exe Example.f90 -g",
"options": {
"cwd": "code/"
}
}
]
}
And then, the launch.json, which will identify tasks.json as a "preLaunchTask".
{
"version": "0.2.0",
"configurations":[
{
"name": "Run my example",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}\\code\\example_exe.exe",
"args": ["],
"stopAtEntry": false,
"cwd": "${workspaceFolder}\\code",
"miDebuggerPath": "gdb.exe",
"preLaunchTask": "compile",
}
]
}
Launch the debugger by pressing F5 (or in the Run menu).
If you don't want to run in debug mode, have a look at this issue.
Sources:
How to build and run C++ code in Visual Studio Code?
awesome tutorial (for ubuntu, working for me with VSCode-gfortran-Win10)
https://www.youtube.com/watch?v=Rj-kYb9nZ3g&ab_channel=LukasLamm.

Starlark debugger for Bazel in Visual Studio Code

i am new to Visual studio Code. I followed this tutorial to set up a Bazel build configuration in Visual studio code (I use Windows 10).
I created a simple task.json
{
"version": "2.0.0",
"tasks": [
{
"label": "Build Example (Debug)",
"type": "shell",
"command": "bazel build //main:hello-world -c dbg",
"windows": {
"command": "bazel build //main:hello-world --experimental_enable_runfiles -c dbg"
},
"osx": {
"command": "bazel build //main:hello-world -c dbg --spawn_strategy=standalone",
},
"group": {
"kind": "build",
"isDefault": true
},
}
]
}
and launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Example",
"type": "cppvsdbg",
"request": "launch",
"args": [],
"stopAtEntry": false,
"preLaunchTask": "Build Example (Debug)",
"cwd": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin/example.exe.runfiles/__main__/",
"program": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin/main/hello-world.exe",
"externalConsole": false,
"windows": {
"type": "cppdbg",
"type": "cppvsdbg",
"cwd": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin",
"program": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin/main/hello-world.exe",
},
},
}
]
}
In this way with run-> start debugging, I am able to debug and stop to breakpoins within the .cpp code of my project.
However, I read here, that is also possible to use the Starlark debugger to debug the .bzl files and Starlark rules.
According to the instructions in the same page I should be able to do this "by right-clicking a build target in the Bazel Build Targets view and selecting "Build Target with Starlark Debugger"". Unfortunately i can't see this option in my Bazel Build Targets view windows:
The Bazel Build Targets view is empty. and if i right click i can't see the "Build Target with Starlark Debugger" option. According to this link i should be able to see my targets listed below Bazel Build Targets view. I guess i am missing something in the configuration of the project or maybe some starlack extension?
Thanks for any help.
Bazel build targets does not work for me on windows either. When I run it, the extension outputs some error about bazel query. I haven't been on windows recently enough to remember the exact message, but I believe it is something along the lines of what is documented in this open issue.
Looks like there is a pull request open to solve it but no one has reviewed it yet. Best bet might be to weigh in over on either one of those after checking your extension output error log to see if it matches what is documented in there. Alternatively, you can check out the Clion with Bazel plugin, I have not tried that on windows yet though.

vscode debug setting in launch.json with custom executable inside pipenv

Hello I'm working with pipenv which have a differetn path for every developer, but I want to have the same launch setting for all. The problem is that the program is not the python is a custom executable with is under the virtual environment bin folder.
Here is my current launch.json
{
"name": "Python: TEST",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"console": "integratedTerminal",
"program": "${env:HOME}/.local/share/virtualenvs/venv-PbRe8Lzd/bin/<program>",
"args": [
...
],
"cwd": "${workspaceRoot}",
}
And for me works OK becaouse my is under "venv-PbRe8Lzd/bin/" but for the other developers that have different venv folder no. Any Idea on how to do this generic for all?
I think better not to sync .vscode folder at all. But anyway it's possible to put interpreter path into another file ".vscode/settings.json".
Delete "program" from launch.json.
Install the Python extension for Visual Studio Code https://github.com/Microsoft/vscode-python (probably it's already installed)
Press Ctrl+Shift+P
Search "Python: Select Interpreter"
Select pipenv interpreter path
or
Create/modify file ".vscode/settings.json"
{
"python.pythonPath": "${env:HOME}/.local/share/virtualenvs/venv-PbRe8Lzd/bin/python"
}

Debugging Perl with Visual Studio Code

I have just started with Perl today and installed ActivePerl 5.24.1 and everything went well. I was able to create my test program testPerl.pl with simple a print command and run it through console.
Now I wanted to use Visual Studio Code to run my Perl script, and so I opened the project folder [testPerl.pl location] with Visual Studio Code and tried to debug the code. I have installed the Perl-Debug extension in the editor and when I hit F5, Visual Studio Code asked me to Select Environment and I chose the Perl Debug option, which actually created the launch.json file for me with the below contents.
{
"version": "0.0.2",
"configurations": [
{
"type": "perl",
"request": "launch",
"exec": "perl",
"name": "Perl-Debug",
"root": "${workspaceRoot}/",
"program": "${workspaceRoot}/${command.AskForProgramName}",
"inc": [],
"stopOnEntry": true
}
]
}
I have kept default values as it, and when I hit F5 again, it asked me for a command with default value test.pl. It is because of ${command.AskForProgramName}, I assume. I entered my file name testPerl.pl in the command, but then nothing happens. It starts and ends without any print in console.
How can I actually configure this launch.json file or is there another way I need to do this?
I tried with a newer version of the plugin: Perl Debug version 0.2.0.
This works out of the box. The proposed configuration looks as follows:
{
// 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": [
{
"type": "perl",
"request": "launch",
"name": "Perl-Debug local",
"program": "${workspaceFolder}/${relativeFile}",
"exec": "perl",
"execArgs": [],
"root": "${workspaceRoot}/",
"inc": [],
"args": [],
"env": {},
"stopOnEntry": true
},
{
"type": "perl",
"request": "launch",
"name": "Perl-Debug remote",
"program": "${workspaceFolder}/${relativeFile}",
"root": "${workspaceRoot}/",
"stopOnEntry": true,
"port": 5000
}
]
}
Do note I tried this out on a Mac, with Visual Studio Code version 1.24.0.
I ran Visual Studio Code on a Mac and changed
"program": "${workspaceRoot}/${command.AskForProgramName}"
to
"program": "${file}"
to get the current file to debug.