how to configure cpp dev env in mac os catalina?

主要参考 Using Clang in Visual Studio Code 以及 在macOS下使用Visual Studio Code进行C/C++开发

官方推荐的插件只有一个,第二个教程推荐了另一个插件,需要在 config 里额外设置两个地方:

1
2
3
4
{
"C_Cpp.autocomplete": "Disabled",
"clang.cxxflags": ["-std=c++11"]
}

configure compiler path

这一步主要针对于 .vscode/c_cpp_properties.json 进行修改,如何修改参考 official doc 即可

task 配置

官网的 task 配置局限性很大,都是针对一些较为 trivial 的情况,比如直接显式指定了文件名是什么。task 的设置均在 .vscode/tasks.json 中,想要运行 cmd + p 然后 task 就可以自动显示在 tasks.json 中配置的task, 不同 task 由设置的 label 来区分。官方的 task 其实非常 trivial 👇, group 重的 isDefault 指定了 shortcut cmd + shift + b 的行为,自动执行这个 task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"label": "server",
"type": "shell",
"command": "clang++",
"args": [
"-std=c++17",
"-stdlib=libc++",
"code/server.c",
"-o",
"code/server.out",
"--debug"
],
"group": {
"kind": "build",
"isDefault": true
}
},

在我摸爬滚打 debug 的时候自动生成了一个新的 task, 这个 task 更加具有普试性, 这个 task 中利用 ${fileDirname}/${fileBasenameNoExtension} 我们就可以利用这个 task 编译任意文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"type": "shell",
"label": "clang build active file",
"command": "clang",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/usr/bin"
},
"group": {
"kind": "build",
"isDefault": true
}
}

debug 配置

debug 需要配置 launch.json,自动配置的长下面这样, 值得一提的是 preLaunchTask, 这里也是根据 task label 来识别不同的 task, 在 debug 前运行 clang build active file, 可以先编译,再 debug

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"name": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb",
"logging": {
"trace": true,
"traceResponse": true,
"engineLogging": true
},
"preLaunchTask": "clang build active file"
}

然而恶心的事总是会发生,, 升级 catalina 之后,上述默认配置不能在断点处停止, 根据这个 issue 里所描述的,我采用了 CodeLLDB 这个插件,然后将 launch.json 修改如下

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"name": "clang build and debug active file",
"type": "lldb",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
// "stopOnEntry": true,
"cwd": "${workspaceFolder}",
// "expressions": "python"
// "environment": [],
// "externalConsole": false,
"preLaunchTask": "clang build active file",
},

遗憾的是,这时候还是出现了问题 Could not initialize Python interpreter - only native expressions will be available., 这个问题官方有过建议将 expression 设置为 native 即可,见 official trouble shooting

通过 issue 以及我的 conda 常年在 vscode 里初始化有问题,我决定彻底解决一下这个问题,于是 issue 很好的解决了我的问题,还是 $PATH 出了问题,一个简单的 workaround 可以暂时解决,同时上面的问题也消失了