首页 > 解决方案 > 我在使用 MinGW 和 VS Code 时出现构建错误“g++ notrecognized as a cmdlet ...”

问题描述

我正在尝试在 VS Code 2019 中设置构建并运行 c++ 文件。编辑 tasks.json 文件后出现构建错误。环境变量应设置为 g++。到目前为止,我一直在关注本教程

我尝试按照 GitHub 上的问题线程中的建议将“命令”更改为“C:\MinGW\bin\g++.exe”。但是,由于我的 c++ 文件不在此文件路径中,因此在我构建代码时程序无法找到它。这就是 tasks.json 文件的“命令”部分的样子:

"label": "build calculator adventure",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "-o",
                "Calculator-Adventure",
                "Calculator Adventure.cpp"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }

"Calculator-Adventure"部分是我的文件名。预期的输出是代码为我的代码构建和创建 .exe 文件,如教程中所述和 VS Code Docs 中所述。

但是,它当前将以下内容输出到终端:

> Executing task: ‪‪g++ -g Calculator Adventure.cpp -o Calculator-Adventure <

g++ : The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

The terminal process terminated with exit code: 1"

标签: c++buildvisual-studio-codemingwmingw-w64

解决方案


好的,我终于想通了。对我有用的是将 git bash shell (C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Git) 的文件路径添加到控制面板中的系统环境变量中(如何在此处执行此操作)。确保将 MinGW bin 文件夹的文件路径也添加到环境变量中(32 位安装程序:C:\MinGW\bin)(64 位安装程序:C:/mingw-w64/x86_64-8.1.0-win32- seh-rt_v6-rev0/mingw64/bin) 然后,重新启动 VS Code 并再次构建 (Ctrl+Shift+B)。

这是 .json 文件的最终代码:

c_cpp_properties.json:

    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "10.0.17763.0",
            "compilerPath": "C:/mingw-w64/x86_64-8.1.0-win32-seh-rt_v6-rev0/mingw64/bin/g++.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "gcc-x64",
            "browse": {
                "path": [
                    "${workspaceFolder}"
                ],
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": ""
            }
        }
    ],
    "version": 4
}

任务.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build calculator adventure",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "-o",
                "Calculator-Adventure",
                "Calculator Adventure.cpp"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

有关更多信息,请查看此页面。这是在 VS Code 中使用 C++ 的 MinGW 编译器的非常详细的分步指南(请仔细阅读)。如果您有任何其他问题,请查看本教程(问题中链接的相同教程)。希望这可以帮助!

注意:在我链接的文档页面中,他们使用 64 位版本的 MinGW。不过,它应该仍然适用于 32 位版本。感谢 @drescherjm 发布 VS Code 文档!


推荐阅读