环境

安装 C++ entendsion

image.png

安装 clang

检查系统是否安装了 clang

  1. clang --version

如果没有安装,则执行

  1. xcode-select --install

编写程序

  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5. int main() {
  6. vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
  7. for(const string& word : msg) {
  8. cout << word << " ";
  9. }
  10. cout << endl;
  11. }

VS Code 配置文件

  • tasks.json (compiler build settings)
  • launch.json (debugger settings)
  • c_cpp_properties.json (compiler path and IntelliSense settings)

    编译运行

    设置编译

    选择 Terminal > Configure Default Build Task.
    image.png
    .vscode 下会创建一个 tasks.json 文件,如下:
    1. {
    2. "version": "2.0.0",
    3. "tasks": [
    4. {
    5. "type": "shell",
    6. "label": "C/C++: clang++ build active file",
    7. "command": "/usr/bin/clang++",
    8. "args": [
    9. "-std=c++17",
    10. "-stdlib=libc++",
    11. "-g",
    12. "${file}",
    13. "-o",
    14. "${fileDirname}/${fileBasenameNoExtension}"
    15. ],
    16. "options": {
    17. "cwd": "${workspaceFolder}"
    18. },
    19. "problemMatcher": [
    20. "$gcc"
    21. ],
    22. "group": {
    23. "kind": "build",
    24. "isDefault": true
    25. }
    26. }
    27. ]
    28. }

    运行

    选择 Terminal-> Run Build Task.

    Debug

    选择 Run > Add Configuration… 选择 C++ (GDB/LLDB)
    image.png
    .vscode 下会创建一个 launch.json 文件,如下:
    1. {
    2. // Use IntelliSense to learn about possible attributes.
    3. // Hover to view descriptions of existing attributes.
    4. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    5. "version": "0.2.0",
    6. "configurations": [
    7. {
    8. "name": "Launch (lldb)",
    9. "type": "cppdbg",
    10. "request": "launch",
    11. "program": "${fileDirname}/${fileBasenameNoExtension}",
    12. "args": [],
    13. "stopAtEntry": true,
    14. "cwd": "${workspaceFolder}",
    15. "environment": [],
    16. "externalConsole": false,
    17. "MIMode": "lldb"
    18. }
    19. ]
    20. }
    Run > Start Debugging 开始 debug

    C/C++ 配置

    选择 View-> Command Palette…C/C++: Edit Configurations (UI) 如下:
    image.png
    .vscode 下会创建一个 c_cpp_properties.json 文件,可以根据需要修改配置。

    常用插件

    Clang-Format

    可以用快捷键很方便的格式化C++代码。

    TabNine

    基于AI的自动代码补全,亲测好用,没有语言限制,看官网介绍就知道了(有点占内存)。
    官网:https://www.tabnine.com

    参考

  1. C/C++ for VS Code
  2. Using Clang in VS Code
  3. Debugging with LLDB-MI on MacOS