最近入手了macbook pro 2020 13.3寸, 立刻想着在mac配置上vscode的C++安装环境, 但经历了不少挫折. 一开始是想参照知乎@谭九鼎的windows10下相关配置链接来设置, 但发现不少bug, 如Mac配置gdb似乎很麻烦, 得改为自带的lldb. 改好之后调试居然无法显示终端, 而且无法进行输入交互!! 最后还是在vscode的官方文档中抄了设置并参考了很多CSDN的文章才慢慢设置好. 下面分享一下安装的插件和相关配置文件, 留作备份.
在工作目录中新建.vscode
文件夹, 然后进入该文件夹分别新建如下名称文件:
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "clang++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true, // 调用Mac自带终端
"MIMode": "lldb",
"preLaunchTask": "clang++ build active file"
}
]
}
2.tasks.json
{
"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": "/usr/bin"
},
"problemMatcher": "$gcc",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "new" // 可选为shared, 但编译会提示终端被任务重用, 建议设置为new
},
}
]
}
settings.json
{
"files.defaultLanguage": "c++", // 输入分号(C/C++的语句结束标识)后自动格式化当前这一行的代码
"editor.suggest.snippetsPreventQuickSuggestions": false, // clangd的snippets有很多的跳转点,不用这个就必须手动触发Intellisense了
"editor.acceptSuggestionOnEnter": "on", // on: 回车自动补全 off: tab自动补全
// "editor.snippetSuggestions": "top", // (可选)snippets显示在补全列表顶端,默认是inline
"code-runner.runInTerminal": true, // 设置成false会在“输出”中输出,无法输入
"code-runner.executorMap": {
"c": "cd $dir && gcc $fileName -o $fileNameWithoutExt.out -Wall -O2 -std=c11 && ./$fileNameWithoutExt.out",
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt.out -Wall -O2 -std=c++17 && ./$fileNameWithoutExt.out"
},
"code-runner.saveFileBeforeRun": true, // run code前保存
"code-runner.preserveFocus": false, // 若为false,run code后光标会聚焦到终端上。如果需要频繁输入数据可设为false
"code-runner.clearPreviousOutput": false, // 每次run code前清空属于code runner的终端消息,默认false
"code-runner.ignoreSelection": true, // 默认为false,效果是鼠标选中一块代码后可以单独执行,但C是编译型语言,不适合这样用
"C_Cpp.clang_format_sortIncludes": true,
"editor.formatOnType": true, // 格式化时调整include的顺序(按字母排序)
}
c_cpp_properties.json
shift+command+p
, 选择C/C++: Edit Configurations (UI)
, 按下图设置并保存自动生成c_cpp_properties.json
.{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**"
],
"macFrameworkPath": [
"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
], // 建议先安装xcode, 该项可以自动生成
"compilerPath": "/usr/bin/clang",
"intelliSenseMode": "clang-x64",
"cStandard": "c11",
"cppStandard": "c++17"
}
],
"version": 4
}
ok, 配置完成, 现在你可以逐步调试程序, 并显示调试终端了, 此外可以在调试中可以通过cin
交互输入.