您可以在 VS Code 中使用 custom task configuration 执行相同的操作来编译您的 .c 文件。
假设我们有这个带有 math.h 的 test.c 文件。
#include <math.h>
#include <stdio.h>
#define PI 3.14159265 //defines the value of PI
/* Calculate the volume of a sphere from a given radius */
double volumeFromRadius(double radius) {
return (4.0/3.0) * PI * pow(radius,3.0f);
}
int main(void) {
double radius = 5.1;
printf("The volume for radius=%.2f is %.2f", radius, volumeFromRadius(radius));
}
第 1 步:创建 tasks.json 文件
这是用于编译/构建您的代码。
要自动创建:
- 打开 .c 文件
- 打开命令面板
- 选择 C/C++: Build and Debug Active File(由 C/C++ 扩展添加)
- 选择你的编译器(例如我的是
gcc-7)
这将自动创建一个 tasks.json 文件并尝试编译您的 .c 文件,我们预计该文件会失败,因为它缺少 -lm 标志。因此,编辑 tasks.json 文件的内容:
{
"version": "2.0.0",
"tasks": [
{
"label": "Compile test.c",
"type": "shell",
"command": "/usr/bin/gcc-7",
"args": [
"-g",
"-o",
"${workspaceFolder}/Q/test.out",
"${workspaceFolder}/Q/test.c",
"-lm"
]
}
]
}
在这里,我将-lm 标志添加到gcc 参数并将label 编辑为“编译test.c”。适当修改 .c 和 .out 文件的路径以匹配您的环境。
有关架构的更多信息:https://code.visualstudio.com/docs/editor/tasks#_custom-tasks。
第 2 步:创建一个 launch.json 文件
这是用于运行您的代码。
要自动创建:
- 打开命令面板
- 选择调试:打开launch.json
- 选择C++ (GDB/LLDB)
然后对其进行编辑以运行预期的 .out 文件。
{
"version": "0.2.0",
"configurations": [
{
"name": "Run test.c",
"preLaunchTask": "Compile test.c",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/Q/test.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/Q",
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
]
}
注意preLaunchTask 应该在tasks.json 中指定相同的任务标签。同样,适当地修改路径以匹配您的环境,尤其是 .out 文件的路径和文件名。
第 3 步:编译并运行它
现在,我不使用(或不喜欢)Code Runner。
我使用 VS Code 的内置调试器配置。
单击左侧的调试器,然后从下拉列表中选择“Run test.c”。
这应该编译您的 .c 文件,运行它,并将任何输出打印到终端面板。
默认情况下,焦点转到运行输出。但如果您还想查看编译/构建日志,您可以从下拉列表中选择任务。