Debug a C Child Process Using VS Code - c

I am using VScode with the following version details:
Version: 1.73.0 (user setup)
Commit: 8fa188b2b301d36553cbc9ce1b0a146ccb93351f
Date: 2022-11-01T15:34:06.111Z
Electron: 19.0.17
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Windows_NT x64 10.0.22000
Sandboxed: No
I am unable to debug a child process when I use fork().
I tried looking for a way to do so, and heard about this extension for Visual Studio: https://marketplace.visualstudio.com/items?itemName=vsdbgplat.MicrosoftChildProcessDebuggingPowerTool2022&ssr=false#overview
I tried checking in the extensions section of VSCode but didn't find it. So, I decided to manually install is by downloading the vsix file. When I tried installing it by using the "Install from VSIX" option in the extension manager, I get this error:
extension/package.json not found inside zip.
I did some more Googling and saw something about Visual Studio being different from Visual Studio Code, and that might be the cause of the error in installation.
So, is there any way/alternative around this? How do I debug a child process in Visual Studio Code?

This is something outside of the main guides from VS Code, although they vaguely mentioned about supporting this.
You can refer to the GDB's fork debug page for more info, here is what you can add into your .vscode/launch.json:
{
"configurations": [
{
// ...
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
// https://sourceware.org/gdb/onlinedocs/gdb/Forks.html
"description": "Fork follows Child process",
"text": "set follow-fork-mode child",
"ignoreFailures": true
},
{
// https://sourceware.org/gdb/onlinedocs/gdb/Forks.html
"description": "Fork will keep the other process attached to debugger",
"text": "set detach-on-fork off",
"ignoreFailures": true
}
]
}
]
}
If you're using LLDB or codeLLDB, here is the LLDB command that mirrors the above except the detach feature:
{
"configurations": [
{
// ...
"initCommands": [
"settings set target.process.follow-fork-mode child"
]
}
]
}
Edit
I haven't used MSVC personally, but if you're using MSVC debugger, you can try to use .childdbg 1 as a startup command, here is the reference page from Microsoft.

Related

VS Code debugging issue when reading data from a file in C

I'm trying to debug my code in VS Code. When I "Run" the code (the button on the top right corner or Ctrl+Alt+N) it works perfectly. But when I try debug, the code goes to the flow==NULL option.
Here is my reading function from code:
AVLTree readData(char* file_name){
AVLTree myTree;
myTree = CreateTree();
/* Opening file stream for reading data from the file */
FILE* flow;
flow = fopen(file_name,"r");
if(flow==NULL){
printf("\nflow == NULL option\n");
printf("File Error"); exit(1);
}
else{
printf("File opened successfully\n");
}
Also here is my 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": "gcc.exe - Etkin dosyayı derle ve dosyada hata ayıkla",
"type": "cppdbg",
"request": "launch",
// "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"program": "${fileDirname}\\indexingphotos.exe",
"args": [],
"stopAtEntry": false,
"cwd": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "gdb için düzgün yazdırmayı etkinleştir",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: gcc.exe etkin dosyayı derle"
}
]
}
What should I do?
Also, I'm a computer engineering student and I worked with Dev C++ until now. I'm trying to switch to VS CODE, but it seems too confusing than Dev C++. How can I learn to use VS Code (or another modern IDE) any suggestions?
There is one thing you can try: change the value of "cwd"(current working directory) in "launch.json" to the folder where you have your file to read. For example, if you have your file to read in the path "C:\Users\username\Documents\file.txt", just put the "cwd": "C:\Users\username\Documents", then compile and run it again.
The "launch.json" file controls the arguments for your C++ debugger and you can find a full list of such arguments including "cwd" in the reference of VS code here. One possible reason why you cannot read the file is that your program cannot find the file because your file is not in the search path of your program.
I had the same issue just now and tried to solve it by setting the current working directory although I'm not sure if that's the best way to do it. A better way is probably to run debugger with argument to add new directory to the search path(like what you can do in "task.json" using -I argument). I was not able to find an argument for gdb. But one thing is for sure: you have to let the program or debugger find the file in some way.
In my case, replacing ${fileDirname} with ${workspaceFolder} resolved the issue

VSCode C trouble: Debug and Build C on Windows

I'm trying to setup VSCode to build and debug C on Windows.
I have installed MinGW.
I'm trying to generate an .exe file for the following code:
#define USE_PTS true
#include "Cartography.h"
static Cartography cartography ;
static int nCartography = 0;
int main(void)
{
nCartography = loadCartography("map (1).txt", &cartography);
showCartography(cartography, nCartography);
interpreter(cartography, nCartography);
return 0;
}
I have two other files Cartography.hand Cartography.c.
If I run the following command using the powershell terminal, it generates an .exe file perfectly:
gcc -std=c11 -o Main Cartography.c Main.c -lm
But if I try to build it using VSCode (using Ctrl + Shift + B) it doesn't recognize the other files:
> Executing task in folder Projeto2LAP: gcc -std=c11 -o Main Cartography.c Main.c -lm <
gcc.exe: error: Cartography.c: No such file or directory
gcc.exe: error: Main.c: No such file or directory
The terminal process terminated with exit code: 1
Terminal will be reused by tasks, press any key to close it.
Here is my tasks.json file:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: gcc.exe build active file",
"command": "gcc -std=c11 -o Main Cartography.c Main.c -lm",
"options": {
"cwd": "C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
The other issue I have is when I'm trying to use the built in VSCode debugger.
I generate the .exe file using the command I mentioned, so an .exe file is present in the current folder.
(I should also mention that the folder I'm working on only contains the files and the .vscode folder, there are no subfolders or anything that could cause an error).
When I click on debug it gives me the following error message:
Error message prompt
Here is my launch.json file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/Main.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
What am I doing wrong?
Your first question:
When you use the powershell command, it gets your *.c files from your current wording directory via relative paths. This is what you attempt to do in the task command, but your CWD is set to the wrong place. In tasks.json, you need to either specify the absolute paths of your files in the gcc command or change your CWD to the directory of the *.c files. Or better, VSC lets you set "cwd": "${workspaceFolder}". This means if you change the name or do any other edits, your task will still work. (For bonus points, you could set the CWD to the enclosing folder of the currently selected file.) First question part 2: The task error probably isn't you. It appears to be a known bug. Instructions here to mitigate it.
Sorry for the late response
I don't see any reason why you would get the debugging error, so my only guess is a permissions problem. Your debugger may not be able to "see" that that directory exists. Make sure neither it nor any of its parent folders have unduly tights restrictions.
Rather than pass one long string to launch GCC in tasks.json, consider using the "args" list variable, placing each arg in a separate element of the list.
Assuming your source files are located within the same directory that was opened in VSCode, the previously-mentioned "${workspaceFolder}" macro will construct the correct paths.
Otherwise, provide absolute paths to your source files as earlier suggested.
Example:
{
"label": "GCC Build Debug (64-bit)",
"type": "shell",
"command": "C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\bin\\gcc",
"args": [
"--std=c11",
"-g",
"-lm",
"-o",
"${workspaceFolder}/Main"
"${workspaceFolder}/Main.c",
"${workspaceFolder}/Cartography.c"
],
"problemMatcher": [
"$msCompile"
]
},

Visual Studio Code Task to Compile and Run .c Files

How can I create a task in Visual Studio Code (the most recent version) to compile and run .c files.
I found this online:
"version": "2.0.0",
"tasks": [
{
"label": "compile and run C",
"type": "shell",
"command": "(gcc -g ${file} -o ${fileBasenameNoExtension}) -and (./${fileBasenameNoExtension})",
"presentation": {
"reveal": "always",
"panel": "shared"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
I managed to tweak it but it still wont compile and run at the same time, instead I get this:
> Executing task: (gcc -g d:\ISEP\ARQCP\partilha\arqcp19202deg01\pl0_7.c -o pl0_7) -and (./pl0_7) <
False
Terminal will be reused by tasks, press any key to close it.
Is there any way to compile and run my code with a simple shortcut (currently i press CTRL+SHIFT+B to "compile and run")?
So I kept looking for a way to do it and I found this simple extension: Code Runner.
Basically it just adds a Run Code button for most of the coding languages and it makes it so much easier.

Live variable view using OpenOCD and VSCode

I really like using VScode + cortex debug extension + openOCD over Keil or Eclipse in embedded projects. Although i wasn't able to figure out how to set up live variable view, which you can set up with eclipse + openOCD.
1. Is it possible to have real time view of global variables over SWD using openOCD and cortex debug on VScode?
I can only see variable values when i pause the program, when the program is debugged i see:
When running:
counter: not available
When paused:
counter: 550
Cortex debug config:
{
"version": "0.2.0",
"configurations": [
{
"name": "Cortex Debug",
"cwd": "${workspaceRoot}",
"executable": "D:\\Code\\embedded\\STM32F1\\build\\STM32F1.elf",
"device": "STM32F103C8",
"request": "launch",
"type": "cortex-debug",
"servertype": "openocd",
"svdFile": "D:\\Code\\embedded\\STM32F1\\STM32F103.svd",
"configFiles": [
"D:\\apps\\openOCD\\OpenOCD-20190426-0.10.0\\share\\openocd\\scripts\\board\\stm32f103c8_blue_pill.cfg"
]
}
]
}
You can have live variable view with ST-Link GDB server, not OCD. Tested it on STM32CubeIDE. Will update when test on VSCODE.

Auto run executable after save in Visual Studio Code

I want to use visual studio code for C programming and I want to automate the procedure of saving -> compiling -> running. At the moment I have MinGW installed and using the C/C++ extension I achieved the saving and compiling using Ctrl+S (I changed the shortcut of compiling) but in order to execute I need to go to the cmd prompt and execute the program.
Is there any way I can, using one button, achieve this?
The closest I came to the aswer is to define my shortcuts
[
{
"key": "ctrl+s",
"command": "workbench.action.tasks.build"
},
{
"key": "ctrl+d",
"command": "workbench.action.tasks.test"
}
]
Then in tasks.json
{
"version": "0.1.0",
"command": "cmd",
"isShellCommand": true,
"args": ["/C"],
"showOutput": "silent",
"tasks": [
{
"taskName": "saveNcompile",
"suppressTaskName": true,
"isBuildCommand": true,
"args": ["gcc main.c -o main.exe"]
}, {
"taskName": "execute",
"suppressTaskName": true,
"isTestCommand": true,
"args": ["main.exe"]
}
]
}
And now using ctrl+s save and compile and ctrl+d execute.

Resources