安装构建工具后,Visual Studio Code MSVC cl.exe未找到。

9

安装了VS Code,安装了构建工具,并按照此处的教程进行了设置:https://code.visualstudio.com/docs/cpp/config-msvc

然而,Visual Studio Code无法找到cl.exe来编译C++。

我已将教程中的路径替换为我的硬盘上正确的路径(cl.exe在那里)。

// My Config
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "10.0.17763.0",
            "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.22.27905/bin/Hostx64/x64/cl.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "msvc-x64"
        }
    ],
    "version": 4
}

// The tutorial build-task
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "msvc build",
            "type": "shell",
            "command": "cl.exe",
            "args": [
                "/EHsc",
                "/Zi",
                "/Fe:",
                "helloworld.exe",
                "helloworld.cpp"
            ],
            "group":  {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "reveal":"always"
            },
            "problemMatcher": "$msCompile"
        }
    ]
}

运行构建任务时,出现了这个错误提示,尽管 compilerPath 是正确的(cl.exe 也在那里),helloworld.cpp 也存在。以管理员身份运行仍然没有帮助。
cl.exe : The term 'cl.exe' 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.
At line:1 char:1
+ cl.exe /EHsc /Zi /Fe: helloworld.exe helloworld.cpp
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (cl.exe:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
3个回答

11
“c_cpp_properties.json”文件仅配置C/C++扩展中的IntelliSense,因此“compilerPath”选项无法帮助构建。
确保您从开发人员命令提示符中启动VS Code。这将设置必要的环境变量,包括“cl.exe”的位置。

1
有没有办法从JSON文件中配置这个?还是每次都需要从VS Dev命令提示符中打开VS Code? - Michele Iafrancesco
1
@Michele 文档中指出,“要使用MSVC[...],必须从开发人员命令提示符中运行”,这似乎是最可靠的方法。如果你真的想尝试避免这种情况,也可以在现有的命令窗口中使用开发工具,甚至可以为调试和任务设置env变量。否则,最好将其编写为单独的问题。 - Callum Watkins
谢谢,第一个选项有效!我能够从命令提示符中调用vcvarsall.bat,然后很好地运行编译器! - Michele Iafrancesco
我之前在不通过开发者命令提示符打开的情况下就能让它工作,所以一定有办法配置 VS Code,不需要这个额外的步骤。 - undefined

2
在 Visual Studio Code 的文档中,你可以找到解决此问题的方法。在 "C++ > Microsoft C++ on Windows > Troubleshooting" 部分中,他们解释说你需要从 Developer Command Promp 中打开项目。
例如:
cd projects/yourproject
code .

我还没有找到其他的方法来完成它。

这是使用cl.exe编译器的最佳方法。请记住,它不是命令提示符(cmd),而是Visual Studio开发人员命令提示符。 - basjak

0

我的第一个答案使用了硬编码路径,但这个更好。你只需要注意路径,因为文档使用的是2019等。 VsDevCmd.bat设置了所有你需要的环境变量,并且在VSCode中很容易使用。它还会给你编译器错误,而我之前使用硬编码cl.exe路径的解决方案出现了某些问题。 在开发者命令提示符外运行VS Code


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接