闲来无事,想在mac中写写C/C++程序,打开应用商店,准备下个xcode玩玩,结果小30G的空间占用直接劝退。因为一直使用vscode开发,便萌生了使用插件来运行C/C++程序的想法,也就有了这篇文章。
因为使用场景的不同,为大家提供了不使用调试功能和使用调试功能两种方案。如果你只是简单的跑跑C/C++程序,可以考虑第一种方案。
使用调试功能
程序运行
1、打开vscode,点击扩展,输入C++,选择插件 C/C++安装。
2、新建文件夹cTest,文件夹下添加文件a.c
(1)a.c中输入以下代码并保存
#include <stdio.h>
int main (){
for (int i = 0; i < 10; i++)
{
if (i == 8) {
printf("Hello World!");
}
}
return 0;
}
(2)检查你的mac中是否安装了clang
clang --version
已安装,返回信息如下
(3)点击 cmd + p
,输入>Configure Default Build Task
。或 cmd+⇧+p
,输入Configure Default Build Task
(4)选择C/C++ clang++ build active file进入tasks.json文件。图中是汉化后显示
(5)覆盖tasks.json文件并保存
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "clang++ build active file",
"command": "/usr/bin/clang++",
"args": [
"-std=c++17",
"-stdlib=libc++",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
},
{
"type": "cppbuild",
"label": "C/C++: clang 生成活动文件",
"command": "/usr/bin/clang",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "编译器: /usr/bin/clang"
}
]
}
3、运行程序
(1)回到a.c窗口,点击⇧⌘B
运行程序
(2)查看目录结构,发现多了一个a文件和一个a.DYSM文件夹
a文件:编译后的可执行文件
a.DYSM文件夹:调试文件
(3)命令行进入cTest路径下,输入./a
运行程序