本次配置环境主要涉及三个文件,它们分别是launch.josntask.jsonc_cpp_properties.json。其中,launch.json主要用于debugger设置,task_json主要用于编译build设置,而c_cpp_properties.json主要涉及编译路径设置和IntelliSense设置。

第一步:安装插件和检查设置

安装如下插件:

  • C/C++
  • C++Intellisense
  • CodeLLDB(Mac M1必须)

查看你的Mac中Clang是否安装,使用如下的命令:

1
$ clang --version

如果Clang没有安装,那么使用如下的命令进行安装:

1
$ xcode-select --install

第二步:配置launch.json和task.json

首先,我们先新建一个hello.cpp文件作为测试文件。文件内容如下:

1
2
3
4
5
6
7
8
9
#include <iostream>

using namespace std;

int main()
{
cout<<"hello world"<<endl;
return 0;
}

然后我们按下Fn+F5运行该文件。如果你之前没有配置过,那么vscode会让你进行配置。选择C++ (GDB/LLDB)进行配置。

接下来,选择clang++

然后,在.vscode文件中会自动生成launch.jsontask.json

但是这时可以发现虽然生成编译后的文件,但是无法自动在终端中运行。同时在调试控制台出现如下的错误的信息。

1
ERROR: Unable to start debugging. Unexpected LLDB output from command "-exec-run". process exited with status -1 (attach failed ((os/kern) invalid argument))

另外,在目录中出现了dSYM为结尾的文件夹。该文件夹包含了编译调试信息,显得很烦,我并不希望它生成。

面对如上的情况,所以我们需要对配置文件进行一些修改。

修改:task.json

注释-g命令,不再生成编译调试信息。
添加-std=c++11,以便以c++11的标准进行编译。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: clang++ 生成活动文件",
"command": "/usr/bin/clang++",
"args": [
"-fdiagnostics-color=always",
"-std=c++11", // 修改编译标准
// "-g", 会生成dsYm文件
"${file}",
"-o",
"${fileDirname}/binary/${fileBasenameNoExtension}.out"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}

修改:launch.json

type属性修改为lldb

stopAtEntry属性修改为true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "clang++ - 生成和调试活动文件",
"type": "lldb", // 进行修改
"request": "launch",
"program": "${fileDirname}/binary/${fileBasenameNoExtension}.out",
"args": [],
"stopAtEntry": true, //改为true
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb",
"preLaunchTask": "C/C++: clang++ 生成活动文件"
}
]
}

修改完毕再次运行,可以看到在终端成功运行。

第三步(选做):配置c_cpp_properties.json

在默认的设置中,编译版本使用的是c++98。但是当我们想使用类似auto等c++11高版本特性时,在vscode中会出现红色波浪线。所以我们需要进行一些修改。

在vscode配置终端中(⇧⌘P),使用运行命令C/C++: 编辑配置(JSON), 会自动生成c_cpp_properties.json

修改:c_cpp_properties.json

修改cppStandard属性为c++11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${default}"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++11", // 修改为c++11
"intelliSenseMode": "macos-clang-arm64"
}
],
"version": 4
}

修改完成后,就不会出现红色波浪了。

至此,所有配置完成。

参考