如何在MacBook上配置C++的编译运行环境

这里省略了安装Visual Studio Code的过程。具体安装过程可以参考互联网上的教程。

安装 Xcode Command Line Tools

确保已安装编译器工具链:

1
2
xcode-select --install  # 安装 Clang/LLVM
clang++ --version # 验证安装clang++

配置 VS Code 插件

安装以下核心扩展:

  • C/C++(Microsoft 官方扩展,语法支持与调试)
  • CodeLLDB(调试器,解决 macOS 系统兼容性问题)1410
  • Code Runner

安装后如何配置C++运行环境

  1. 创建一个目录用于存放代码文件,如 cpp_practice

  2. 在cpp_practice下创建 .vscode 文件夹

  3. .vscode 分别创建3个子文件,如下:

    1
    2
    3
    4
    .vscode
    ├── c_cpp_properties.json
    ├── launch.json
    └── tasks.json
  4. c_cpp_properties.json 文件内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    {
    "configurations": [
    {
    "name": "Mac",
    "includePath": ["${workspaceFolder}/**"],
    "defines": [],
    "macFrameworkPath": [
    "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
    ],
    "compilerPath": "/usr/bin/clang++", // 或 GNU GCC 路径(如 /opt/homebrew/bin/g++-13)
    "cStandard": "c17",
    "cppStandard": "c++17", // 支持 C++17/20
    "intelliSenseMode": "macos-clang-arm64"
    }
    ],
    "version": 4
    }
  5. launch.json 文件内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    {
    "version": "0.2.0",
    "configurations": [
    {
    "name": "调试C++",
    "type": "lldb",
    "request": "launch",
    "program": "${fileDirname}/bin/${fileBasenameNoExtension}",
    "args": [],
    "cwd": "${fileDirname}",
    "preLaunchTask": "Build with Clang" // 需与 tasks.json 的 label 一致
    }
    ]
    }
  6. tasks.json 文件内容如下:

    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
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    {
    "version": "2.0.0",
    "tasks": [
    {
    "label": "Build with Clang",
    "type": "shell",
    "command": "clang++",
    "args": [
    "-std=c++17",
    "-g",
    "${file}",
    "-o",
    "${fileDirname}/bin/${fileBasenameNoExtension}",
    "-Wall"
    ],
    "group": "build",
    "problemMatcher": [
    "$gcc"
    ]
    },
    {
    "type": "cppbuild",
    "label": "C/C++: clang++ 生成活动文件",
    "command": "/usr/bin/clang++",
    "args": [
    "-fcolor-diagnostics",
    "-fansi-escape-codes",
    "-g",
    "${file}",
    "-o",
    "${fileDirname}/bin/${fileBasenameNoExtension}"
    ],
    "options": {
    "cwd": "${fileDirname}"
    },
    "problemMatcher": [
    "$gcc"
    ],
    "group": {
    "kind": "build",
    "isDefault": true
    },
    "detail": "调试器生成的任务。"
    }
    ]
    }
文章目录
  1. 1. 安装 Xcode Command Line Tools
  2. 2. 配置 VS Code 插件
  3. 3. 安装后如何配置C++运行环境