安装生成工具后找不到Visual Studio代码MSVC cl.exe



设置VS代码后,安装构建工具并在此处完成教程:https://code.visualstudio.com/docs/cpp/config-msvc

Visual Studio代码找不到用于编译C++的cl.exe。

我在硬盘上用正确的路径替换了教程中的路径(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

"c_cpp_properties.json"文件仅在c/c++扩展中配置IntelliSense,因此compilerPath选项对构建没有帮助。

请确保您从开发人员命令提示符启动VS代码。这将设置必要的环境变量,包括"cl.exe"的位置。

在Visual Studio代码的文档中,您可以看到此问题的解决方案。在">C++>Windows上的Microsoft C++>故障排除";他们解释说,你需要从开发者命令Promp打开你的项目

例如:

cd projects/yourproject
code .

我还没有找到其他方法。

我的第一个答案使用了硬编码路径,但这更好。你只需要注意路径,因为文档使用2019等。VsDevCmd.bat设置了您需要的所有env变量,它在VSCode中很容易工作。它还为您提供编译器错误,而我以前使用硬编码cl.exe路径的解决方案由于某种原因没有提供这些错误。在开发者命令提示符之外运行VS代码