简体   繁体   中英

Compiling C/C++ in VS Code

I'm trying to compile C/C++ code in VS Code using cl (installed via visual studio 2019). I've set up the json files like the MS website suggests,

https://code.visualstudio.com/docs/cpp/config-msvc ,

but I still get the error:

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.

Here are my json files:

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

}

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

}

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.

Your "msvc build" task only specifies "cl.exe" for its command, with no leading path. The problem is that cl.exe isn't on your PATH, or anywhere that VS Code can see when it goes to run your build task.

One solution to this is to open VS Code using the "Developer Command Prompt" for whatever Visual Studio version you have. This version of the command prompt defines the location of the Visual Studio build tools so that any program or command that is run from that cmd prompt will be able to find the programs like "cl.exe".

There is another solution that I prefer to use, which is to write a batch script for your build task.

Put this script in the root of your VSCode workspace and call it build.bat :

:: set the path to your visual studio vcvars script, it is different for every version of Visual Studio.
set VS2017TOOLS="C:\Program Files(x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"

:: make sure we found them
if not exist %VS2017TOOLS% (
    echo VS 2017 Build Tools are missing!
    exit
)

:: call that script, which essentially sets up the VS Developer Command Prompt
call %VS2017TOOLS%

:: run the compiler with your arguments
cl.exe /EHsc /Zi /Fe: helloworld.exe test.c

exit

Then your task has to be changed to run the batch script:

{
    "label": "msvc build",
    "type": "shell",
    "command": "${workspaceFolder}/build.bat",
    "group":  {
        "kind": "build",
        "isDefault": true
    },
    "presentation": {
        "reveal":"always"
    },
    "problemMatcher": "$msCompile"
}

The advantage to using the batch script this way is that you do not need to run VS Code from the Developer Command Prompt, and the $msCompile problem matcher will still be able to display errors and warnings inside VS Code.

Another note is that the batch script in this answer is specific to just your project. You can continue to update that script to build your project as it gets larger, or you could take advantage of a tool like CMake to handle the generation of the actual build scripts from a configuration file.

Then your build.bat may look more like this:

:: set the path to your visual studio vcvars script, it is different for every version of Visual Studio.
set VS2017TOOLS="C:\Program Files(x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"

:: make sure we found them
if not exist %VS2017TOOLS% (
    echo VS 2017 Build Tools are missing!
    exit
)

:: call that script, which essentially sets up the VS Developer Command Prompt
call %VS2017TOOLS%

:: Set some variables for the source directory and the build directory
set SrcDir=%CD%
set BuildDir=%CD%\build

:: Make the build directory if it doesn't exist
if not exist "%BuildDir%" mkdir "%BuildDir%"

:: Make sure you configure with CMake from the build directory
cd "%BuildDir%"

:: Call CMake to configure the build (generates the build scripts)
cmake %SrcDir%^
 -D CMAKE_C_COMPILER=cl.exe^
 -D CMAKE_CXX_COMPILER=cl.exe^

:: Call CMake again to build the project
cmake --build %BuildDir%

exit

I have struggled in the same problem as following the instructions in Configure VS Code for Microsoft C++ . Thankfully I found this question and @Romen's great answer.

However, here are some itchy points in his solution:

  1. He hard-coded the executable name and the file name so that you have to change it every time you make a new project.
  2. He put the .bat in the folder of the compiled file but not the .vscode folder so that we couldn't copy one folder directly while making new projects.

For this two flecks, I modified his codes a little bit so that it's more convenient to make new projects debugging with Microsoft C++.

  1. In the build.bat file, change the command

    cl.exe /EHsc /Zi /Fe: helloworld.exe helloworld.cpp

    to

    cl.exe /EHsc /Zi /Fe: %1.exe %1.cpp

  2. Move the build.bat to .vscode folder and change "command": "build.bat" to "command": ".\\.vscode\\build.bat ${fileBasenameNoExtension}" .

This is trivial, but I hope it could help some newbies like me and inspire better solutions for more complicated cases :)

For anyone comming here thinking the best solution would be to set the path environment variables, so cl.exe could be run in any command prompt, or power shell terminal, this is not recommended, as per documentation:

The MSVC command-line tools use the PATH, TMP, INCLUDE, LIB, and LIBPATH environment variables, and also use other environment variables specific to your installed tools, platforms, and SDKs. Even a simple Visual Studio installation may set twenty or more environment variables. Because the values of these environment variables are specific to your installation and your choice of build configuration, and can be changed by product updates or upgrades, we strongly recommend that you use a developer command prompt shortcut or one of the customized command files to set them, instead of setting them in the Windows environment yourself.

https://docs.microsoft.com/en-us/cpp/build/setting-the-path-and-environment-variables-for-command-line-builds?view=vs-2019

What worked for me:

Following this guide , I made this change in task.json :

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "cl.exe build active file",
            "command": "build.bat", //calling build.bat instead
            "args": [
                "/Zi",
                "/EHsc",
                "/Fe:",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "${file}"
            ],
            "problemMatcher": [
                "$msCompile"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Then my build.bat ( sDevCmd.bat is called when the developer terminal is opened):

call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\VsDevCmd.bat"
echo Building...
cl.exe %*

Then Ctrl + Shift + B .

Default terminal of VSCode does not have cl.exe PATH , you need to use Developer Command Prompt :

  1. Open Developer Command Prompt

https://code.visualstudio.com/docs/cpp/config-msvc :

To open the Developer Command Prompt for VS, start typing 'developer' in the Windows Start menu, and you should see it appear in the list of suggestions. The exact name depends on which version of Visual Studio or the Visual Studio Build Tools you have installed. Click on the item to open the prompt.

  1. Go to project parent folder Lets say it is D:\workspace and project name is myproject

在此处输入图像描述

  1. Ctrl+Shift+B to build

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM