官方文档:https://code.visualstudio.com/docs/cpp/config-clang-mac
$ clang --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: x86_64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
mkdir /workspace/projects
cd /workspace/projectsmkdir helloworld
cd helloworld
code .
使用 code 指令将该目录定义为一个代码项目的工作目录,在该目录下我们会创建 1 个 VS code 代码项目专有的配置目录 .vscode,包含了以下 3 个文件:
创建 C/C++ 源码文件:
#include int main()
{for (int i=0; i<3; i++){std::cout << "hello world" << std::endl;}return 0;
}
运行并查看输出:
第一次运行后会自动生成 tasks.json 文件,设置了代码编译和构建的配置参数。
{"tasks": [{"type": "cppbuild","label": "C/C++: clang++ 生成活动文件","command": "/usr/bin/clang++","args": ["-fcolor-diagnostics","-fansi-escape-codes","-g","${file}","-o","${fileDirname}/${fileBasenameNoExtension}"],"options": {"cwd": "${fileDirname}"},"problemMatcher": ["$gcc"],"group": {"kind": "build","isDefault": true},"detail": "调试器生成的任务。"}],"version": "2.0.0"
}
/usr/bin/clang++ -fcolor-diagnostics -fansi-escape-codes -g /workspace/projects/helloworld/helloworld.cpp -o /workspace/projects/helloworld/helloworld
单击行号插入 breakpoint。
进入调试界面开始调试:
在需要自定义 debug 流程的场景中,可以通过添加 launch.json 配置文件来完成。
{"configurations": [{"name": "C/C++: clang++ 生成和调试活动文件","type": "cppdbg","request": "launch","program": "${fileDirname}/${fileBasenameNoExtension}","args": [],"stopAtEntry": false,"cwd": "${fileDirname}","environment": [],"externalConsole": false,"MIMode": "lldb","preLaunchTask": "C/C++: clang++ 生成活动文件"}],"version": "2.0.0"
}
{// 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": [{"type": "lldb","request": "launch","name": "Debug","program": "${fileDirname}/${fileBasenameNoExtension}.out","args": [],"cwd": "${workspaceFolder}"}]
}
最后,针对 C/C++ 的诸多扩展内容,我们可以通过 UI 的方式来设置相关的配置,同时会自动生成 c_cpp_properties.json 文件。