在 VS Code 中配置 tasks.json 文件以在 Mac 上使用特定版本的 C++ 编译 C++

Configurate tasks.json file in VS Code to compile C++ with specific version of C++ on Mac

我正在尝试使用 VS Code 编译一些 C++ 代码,但在使用不同的 C++ 版本时遇到了一些问题。我想用一个选项 -std=c++17 来编译它,因为我需要测试的一些东西只能在 C++17 中工作(默认情况下,Clang 使用 C++14)。 因此,我尝试编辑我的 tasks.json 文件以手动添加使用 C++17 的选项。但是,即使这样做之后似乎也没有任何效果。

最初,我只为 g++ build active file 编辑了 options 部分,但是,由于它似乎不起作用,我将该选项添加到所有任务.不幸的是,这也没有帮助。你能告诉我我到底在哪里犯了错误吗? 您可以在下面找到 tasks 部分 tasks,json 文件。

"tasks": [
        {
            "type": "shell",
            "label": "clang build active file",
            "command": "/usr/bin/clang",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-std=c++17"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
        {
            "type": "shell",
            "label": "clang build active file",
            "command": "/usr/bin/clang",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-std=c++17"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build"
        },
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-std=c++17"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build"
        }
    ]

好吧,答案很简单,我实际上是在做正确的事情,但在错误的地方。

首先,可以手动将 -std=c++17 添加到您的任何任务中,或者只创建一个具有特定名称的单独任务。例如(取自 VS Code 网站),

        {
            "type": "shell",
            "label": "clang++ build active file",
            "command": "/usr/bin/clang++",
            "args": [
                "-std=c++17",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${workspaceFolder}",
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }

这是一个名为 clang++ build active file 并使用 std=c++17 作为 C++ 版本的任务。然后,您不必按 运行 code 按钮,而是必须使用 Terminal->运行 build task 选项。

我最初虽然有一种方法可以覆盖 运行 代码 按钮行为以使用不同的 C++ 版本,但我想这是唯一的方法是通过添加一个 new/editing 一个旧任务。