You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac M2设备上如何升级C++版本至C++17/20?

解决Mac M2下Clang编译C版本锁定为C98的问题

一、直接在编译命令中指定C++标准

Clang默认会使用旧版C++标准,编译时必须显式指定参数:

  • 编译C++17:clang++ -std=c++17 your_code.cpp -o output
  • 编译C++20:clang++ -std=c++20 your_code.cpp -o output
    如果需要使用GNU扩展特性(部分非标准但常用的语法),可替换为-std=gnu++17或-std=gnu++20

二、配置VSCode的tasks.json(编译任务)

若使用VSCode的编译功能,需修改tasks.json文件确保编译参数包含标准指定:

  1. 打开VSCode,按Cmd+Shift+B,选择「创建tasks.json文件」,再选「clang++ 生成活动文件」
  2. 修改tasks中的args部分,添加-std=c++17(或c++20):
{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang++ 生成活动文件",
            "command": "/usr/bin/clang++",
            "args": [
                "-std=c++17", // 指定目标C++版本
                "-fcolor-diagnostics",
                "-fansi-escape-codes",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "编译器: /usr/bin/clang++"
        }
    ]
}

三、配置VSCode的c_cpp_properties.json(智能提示)

这一步用于让VSCode代码提示匹配目标标准,避免编辑器误报:

  1. 按Cmd+Shift+P,输入「Edit Configurations (JSON)」打开c_cpp_properties.json
  2. 修改cppStandard字段为c++17或c++20,同时确保compilerPath指向正确的Clang路径(Mac M2下通常为/usr/bin/clang++):
{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "macFrameworkPath": [
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/clang++",
            "cStandard": "c17",
            "cppStandard": "c++17", // 设置对应C++标准
            "intelliSenseMode": "macos-clang-arm64"
        }
    ],
    "version": 4
}

四、设置全局默认编译参数(可选)

若想让终端中Clang默认使用新标准,可配置环境变量:

  1. 打开终端,编辑~/.zshrc文件:open ~/.zshrc
  2. 添加一行:export CXXFLAGS="-std=c++17"(或c++20)
  3. 保存后执行source ~/.zshrc生效,之后终端编译默认会携带该参数

内容的提问来源于stack exchange,提问作者Marcus Hauen-Limkilde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:08:15