How to set up and debug a C language environment in Visual Studio Code?
To set up and debug a C language environment in VSCode, you can follow these steps:
- To install VSCode: First, make sure you have installed VSCode on your computer. You can download and install it from the official VSCode website (https://code.visualstudio.com/).
- Install the C/C++ extension: In VSCode, click on the extensions icon on the left (four square icon), search for and install the “C/C++” extension.
- Configure the compiler: In VSCode, click on “File” -> “Preferences” -> “Settings” to open the user settings. In the search box, type “c_cpp_properties”, click on the “Edit in settings.json” link, and add the following content to the settings.json file.
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"compilerPath": "C:/MinGW/bin/gcc.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "gcc-x64"
}
],
"version": 4
}
Please note that the “compilerPath” in the above configuration needs to be modified according to the installation path of your compiler.
- To create a C file, in VSCode, click on “File” -> “New File”, and save the file with a “.c” extension, such as “hello.c”.
- Write C code: In the newly created C file, write your C code, for example:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
- Compile and run: Press Ctrl+` (or click on “View” -> “Terminal”) to open the terminal. Enter the following command to compile C code in the terminal.
gcc hello.c -o hello
Next, execute the compiled executable file with the following command:
./hello
You will see the program output result as “Hello, World!” in the terminal.
- Debugging C code: Click on the debugging icon (bug icon) on the left side of VSCode, then click on the “Create a debug configuration” button. Select “C++ (GDB/LLDB)” and VSCode will automatically create a “launch.json” file. Add the following configuration to the “launch.json” file:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/hello",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:/MinGW/bin/gdb.exe",
"preLaunchTask": "build"
}
]
}
Ensure that “miDebuggerPath” matches your GDB debugger path.
- Debugging: Clicking the “Start debugging” button or pressing F5 will launch the debugger in VSCode and run your C code. You can set breakpoints, step through your code, and more.
Here are the steps to configure and debug the C language environment in VSCode. Hope it helps you!