Vscode-cpptools: How to: Use VS Code with Visual C++ Build Tools

Created on 15 Apr 2018  Â·  41Comments  Â·  Source: microsoft/vscode-cpptools

Hi,

After reading documentation:

It is evident that documentation for VC++ Build Tools is missing for VS Code. There are samples for GDB, MAC, Linux but not Visual C++ Build Tools for Windows using Visual Studio Code.

Essentually I found a question which matches my description but in the end there is no answer:

https://stackoverflow.com/questions/44759914/how-to-setup-vscode-to-use-visual-c-build-tools-for-windows

My c_cpp_properties.json looks like this:

`{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}",
                "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/*",
                "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.13.26128/include",
                "C:/Program Files (x86)/Windows Kits/10/Include/10.0.10240.0/ucrt"

            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "intelliSenseMode": "msvc-x64",
            "browse": {
                "path": [
                    "${workspaceFolder}",
                    "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/",
                    "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/MSBuild/15.0/Bin"
                ],
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": ""
            },
            "cStandard": "c11",
            "cppStandard": "c++17"
        }
    ],
    "version": 3
}`

Additionally:
This is somewhat unrealistic that include folder is inside version 4.13.26128, which would mean in case of change in version number would leave the code pretty much useless.

OS : Latest Windows 10 and latest Visual Studio Code with up to date extension ms-vscode.cpptools 0.16.1.

Thank you in advance.

* VS Code version and if you are using the Insiders build
* C/C++ extension version
* Other extensions you installed and if the issue persists after disabling them
* step-by-step instructions to reproduce the issue
* A small code sample, zipped up project, or open source repo we can use to verify the bug
* Relevant settings from your settings.json, c_cpp_properties.json, and/or launch.json files
* Any log messages present in the Output window (use "C_Cpp.loggingLevel": "Information" in settings.json)
Feature Request docs help wanted

Most helpful comment

It shouldn't be this complicated to use VC++ in VS Code. It should be built in or at least supported by the official C++ extension.

All 41 comments

We have code that automatically populates the includePath/browse.path with the Visual Studio VC tools, but it sounds like this may not be working with the BuildTools?

I also hit the problem with the changing versions breaking my includePaths after a compiler update...making this better is on our TODO list (not sure if there's an issue tracking it already).

We have code that automatically populates the includePath/browse.path with the Visual Studio VC tools, but it sounds like this may not be working with the BuildTools?

Yes its not working with Visual C++ Build Tools . Looks like _not_ many people are trying it. Else this would have been requested by many people.

Maybe the team behind Visual C/C++ Build Tools can help in this case. I am unaware of their contact. :/ Copying @AndrewPardoe

deycrypt, I'm understanding that IntelliSense is working just fine with the build tools, you would just like a tutorial on how to setup actually BUILDING with them. This is a good point, I'll see what we can do, asap.

The quickest, simplest case for a one file program is to create a tasks.json that looks like this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "compile",
"type": "shell",
"command": "cl",
"args": [
"TestFile.cpp"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

(Of course you'd need to change the file from TestFile.cpp to whatever other file you have)

Then open Developer Command Prompt for VS 2017 and run code.exe from that command-shell. Then press Ctrl-Shift-B. The file should be compiled successfully. There is obviously much more that could be done here, but in case this is helpful, I wanted to get it out there sooner rather than later.

@greazer Hi, I probably could figure the build part. Its not the build.
Its the locating the Visual C++ Build tools compiler. The inclusion of header files etc. That needs cleaning up / documentation. Precisely its the c_cpp_properties.json file for C++ build tools. (Again not G++ and not the MSVC from Microsoft Visual Studio)

While I understand that the plugin to autoexplore the install for C++ Build Tools would be a stretch but once pointed to the directory it should be able to pickup rest of the # include folders (like it does for G++ on MAC).

I've been looking everywhere for any bits of documentation for using BuildTools with VS Code. I was able to compile it fine using _cl.exe_ but the problem was with VS Code not detecting include paths (or maybe I was not giving all of 'em).

Following are the contents of my _c_cpp_properties.json_

{
    "configurations": [
        {
            "name": "Win32",
            "browse": {
                "path": [
                    "${workspaceFolder}",
                ],
                "limitSymbolsToIncludedHeaders": true
            },
            "includePath": [
                "${workspaceFolder}",
                "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.14.26428\\include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "msvc-x64"
        }
    ],
    "version": 4
}

After this, the #include <iostream> header keeps saying

_cannot open source file "corecrt.h" (dependency of "iostream")_

I tried looking for this file but couldn't find it. Some documentation on include paths would really help :smile:

@kartikgola, corecrt.h is part of the Windows SDK. If you install that, you can add those paths to your includePath.

E.g:

C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\ucrt
C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um
C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\shared
C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\winrt

@greazer I tried that example config file on a hello world app and building generated: fatal error C1034: iostream: no include path set

This is with the current version of VS Code, Build tools for VS2017 installed (and actually working as a dep in other tools such as node gyp). Since it's been a few months, are there any guides for using VS Code with VS build tools you could direct me to by any chance?

@deycrypt sorry, yes I was misunderstanding.
@AlchemistCamp, The compiler cannot find your system headers. You need to set your include path environment variable prior to doing a build. This was the reason I stated:
"Then open Developer Command Prompt for VS 2017 and run code.exe from that command-shell."
The developer command prompt sets the appropriate build environment variables. There are other ways to get your environment variables set, but this is simple and effective.

@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64     
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% helloworld.cpp /link %linkerflags%

An alternative way, save these code as build.bat then call it in task.json.

{  
   // See https://go.microsoft.com/fwlink/?LinkId=733558
   // for the documentation about the tasks.json format
   "version": "0.1.0",
   "windows": {
      "command": "build.bat",
      "isShellCommand": true,
      "showOutput": "always"
   }

Not graceful, but work.

So far i've got this working (with debugging too)

The compile task in side the tasks.json launches a cmd.exe process and runs vcvarsall.bat before running the cl.exe command.

// tasks.json
{
    "version": "2.0.0",
    "echoCommand": true,
    "tasks": [
        {
            "label": "compile",
            "command": "cmd",
            "type": "process",
            "args": [
                "/C %vcvarsall% && cl /Od /Zi /EHsc /Fd:%outpath%/vc141.pdb /Fo:%outpath%/%TargetName%.obj ./main.cpp /link /OUT:%outpath%/%TargetName%.%TargetExt% /PDB:%outpath%/%TargetName%.pdb",
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
        }
    ],
    "options": {
        "env": {
            "outpath": "out", // must exist before running
            "TargetName": "hello",
            "TargetExt": "exe",
            "vcvarsall": "\"C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Auxiliary\\Build\\vcvarsall.bat\" x64",
        }
    }
}

The (Windows) Launch configuration runs the compile task before launching the program.

`JSON // launch.json { "version": "0.2.0", "configurations": [ { "name": "(Windows) Launch", "type": "cppvsdbg", "request": "launch", "program": "out/hello.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": true, "preLaunchTask": "compile" } ] }

Placing a debug breakpoint and pressing F5 is working for me so far.

It shouldn't be this complicated to use VC++ in VS Code. It should be built in or at least supported by the official C++ extension.

not sure if this is still valid or will work. I am going to try it though.
https://blogs.msdn.microsoft.com/vcblog/2016/10/24/building-your-c-application-with-visual-studio-code/

I'm also surprised that configuring other compilers other than VC++ is easier in VSCode and that there is no example of setting this up in the docs.

Would have been nice if the extension could pick up settings from a VS solution or project for build and debug setup.

We have a set of new guides we're working on.

This one in particular is under review and hasn't been published, but if you would like to take a look and provide any feedback, we would certainly appreciate it.

There are other plugins for the other compilers like Clang (https://marketplace.visualstudio.com/items?itemName=mitaki28.vscode-clang )
But I think if we had a nice clean central post that says Here’s how you set up our plugin for
VC++, GCC, Clang, and maybe others with a settings section for each it would help clear this up a bit. We are spoiled for choice which is nice, but it has it’s complications.

@bobbrow that looks good. Answered a few of the things I felt I was stuck on.

By the way, would it be possible to set up a workflow where VSCode calls msbuild to build a solution/project and still be able to debug from VSCode?

I will have to try that. I already have .bat files to run my VS build from any command line. (loading vcvarsall.bat as you do here.)

In that scenario - the missing piece for me has been setting up the debugger. I presume it will work even if I use msbuild to compile by application?

@bobbrow Thanks for the guide you posted. The problem for me is that your guide focuses on invoking the compiler (cl.exe) directly. I would like the VS Code task to call msbuild to build a predefined Visual Studio project. Please will you consider including that application in your guide?

@thomthom, @DavidA2014 that is good feedback. We can look at adding a guide for that.

The only thing that should really change would be the section on generating the tasks.json. There is a template for MSBuild which I've copied below (and added switches for config/platform). I need to look at the $msCompile problem matcher because it doesn't seem to be matching errors, but this task will build a SLN in the workspace folder out of the box.

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "msbuild",
            "args": [
                // Ask msbuild to generate full paths for file names.
                "/property:GenerateFullPaths=true",
                "/property:Configuration=Debug",
                "/property:Platform=x64",
                "/t:build"
            ],
            "group": "build",
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "reveal": "silent"
            },
            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "problemMatcher": "$msCompile"
        }
    ]
}

That's great. I always have a Visual Studio solution for my Windows projects. But some times VSCode is just that much snappier to do some quick work in - being able to build and debug would be a nice workflow addition.

Hello.

As an original poster of this thread. I felt obliged to comment. I have given up on having an idea that a lightweight solution. Which is VS Code (which has an integrated debugger) will work with Visual Studio Build Tools on Windows environment.

Basically this would have been an epic solution for standard 300-400 line C programs. Proof of concepts etc, who don't need project management. But of-course it is too much to expect.

Even now as Build Tools for Visual Studio 2019 RC is making its release. The version /2019 gets appended and in the end it renders my code useless. Unless I manually go and tweak each one of my programs.

image

Here is what is expected from VS Code in Windows: An automated scan for standard directories as soon as VS Code is fired / or C environment is setup for the first time. All compiler and build directories created on its own. Build standard templates based on its finding, both for C and C++ projects. If this was in C I would have written a code for a directory traversal. Too bad I don't know any electron or JS programming. So I am sorry I cannot contribute.

Thank you folks for all your efforts.

@deycrypt, maybe you can help me understand better what you would like to see that is not present in the extension today. The C++ extension is capable of detecting the Visual Studio Build tools and using them to configure your c_cpp_properties.json automatically. Since your original post, the extension has added a "compilerPath" property to our config schema which removes the need to manually paste in system include paths. When opening a new folder that has not been configured we will scan for installed compilers and auto-populate this if it finds a Visual Studio installation. If this isn't working for you, we'd like to know about it.

We have also released a command that will build and debug the active code file which should enable the "proof of concept" scenario you mentioned (single code file with int main and other experimental code). At the current time, it just requires that you launch VS Code from the "Developer Command Prompt" so that the build environment is properly configured before attempting to compile.

Something you can do to make the 'start code from a VS Command prompt' a bit easier, is go in to
C:Program Files (x86)Microsoft Visual Studio2017ProfessionalCommon7Tools
make a copy of the vsDevCmd.bat file and call it something like VsDevCmdCode.bat.
Open that new file and go to the end of the file. Add "call code" (without quotes) just before the
exit /B 0 line.
Save this file in C:Program Files (x86)Microsoft Visual Studio2017ProfessionalCommon7Tools
Drag the Visual Studio Command Prompt from your Start menu to your Desktop to create a shortcut to it, then open it's Properties.
In the Target line, change the target to
%comspec% /k "C:Program Files (x86)Microsoft Visual Studio2017ProfessionalCommon7ToolsVsDevCmdCode.bat"
Save that.

Now when you want to start VS Code for C++, just use that shortcut. It will load all of the VS environment variables up, and start code from within that environment. When I created a simple C++ file to test it, it worked fine. The build system did ask me if I wanted to use cl or clang because I have both installed, but it worked just fine.

maybe easy-cpp-projects can help you.
or you can install it‘s’ plugin(Easy C++ projects) in vscode.
reference:https://dev.to/acharluk/developing-c-with-visual-studio-code-4pb9

I found this article which is very helpful.
https://code.visualstudio.com/docs/cpp/config-msvc

@bobbrow Hi Bob, a couple of questions related to using msbuild with VS Code:

  1. The document link in https://github.com/microsoft/vscode-cpptools/issues/1839#issuecomment-475350756 is now broken. Has that document been published?

  2. In your comment https://github.com/microsoft/vscode-cpptools/issues/1839#issuecomment-476742549 you mention:

the $msCompile problem matcher because it doesn't seem to be matching errors

Is there any progress on fixing that?

  1. Is there any chance of a guide for how to use VS Code with a Visual Studio solution?

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

VS Code itself ships the $msCompile problem matcher, so you could look if they have a bug already or file a new one.

@DavidA2014
We don't have a guide for using VS Code with a Visual Studio solution. Our extension does not parse those project files. Our strategy is to provide language services in this extension and let other extensions manage build systems (e.g. CMake, Arduino). Creating an extension that can understand sln/vcxproj would fall under that umbrella, but we haven't started that work yet.

I ran into the same thing, but I was missing the first step from:
https://code.visualstudio.com/docs/cpp/config-msvc

i.e. "start VS Code from the Developer Command Prompt"

this one fixed it for me. It initializes all the needed env variables for you.

Thanks

I already try all solutions but C++ Extension cannot detect installed VS Build tools
image
But CMake Tools does it.
image

Any ideas?

@Gargony Yeah, we haven't added code to detect cl.exe from the build tools. You can try just using "cl.exe" or finding the path to the cl.exe in the build tools. And you can use C/C++: Log Diagnostics after opening a .cpp file to verify if the correct includePaths got used.

@sean-mcmanus there shouldn't be anything special about the Build Tools SKU since it registers itself the same way as VS 2017/2019. We'll need to investigate. It seems that there is also a problem with us not reporting all VS installations either. Can you move this to a new issue?

@sean-mcmanus Thanks for quick reply.
But my problem is a more deep. )))
Our cmake uses clang 7.0.0 cl.exe (clang-cl.exe) and I set option:
_"configurationProvider": "vector-of-bool.cmake-tools"._
All works correct and build fine. But intellicense works wrong because "cmake--tools" provide options uncompataible with cpptools, "compilerPath": "C:/Program Files (x86)/LLVM/msbuild-bin/cl.exe". So cpptools cannot find standart *.h(s) (std) (e.g. <vector>, <list>,...).
Manual setting "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe"
and/or
"includePath":[
"C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/include"
]
not helps because (I suppose) _"configurationProvider": "vector-of-bool.cmake-tools"._ override my changes.
Currently I use without _"configurationProvider": "vector-of-bool.cmake-tools"_, with manual settings

Btw: you are make a cool extension, thank you )))

@Gargony Our support for clang-cl.exe has some known deficiencies. I moved your details to a new issue, but how are you using the build tools and clang-cl.exe? Do the build tools just supply the headers for clang-cl.exe and you don't use cl.exe?

@sean-mcmanus
For support ABI-compatible (as in https://clang.llvm.org/docs/MSVCCompatibility.html)
Brfore run VSCode I execute:
call "%ProgramFiles(x86)%Microsoft Visual Studio2017BuildToolsVCAuxiliaryBuildvcvarsall.bat" x86
set "PATH=%ProgramFiles(x86)%LLVMmsbuild-bin;%PATH%"
set "INCLUDE=%ProgramFiles(x86)%LLVMlibclang7.0.0include;%INCLUDE%

And clang can find rc.exe, link.exe, and so on.

Is it possible to use VS Code + Microsoft Visual C++ Build Tools (and Windows 10 win32 SDK), to compile Visual Studio win32 projects?

Strange that I can't find any webpages with a tutorial how to do this... But it seems possible?

Since I mainly use VS Code to write C++, I've found it most convenient to have my shortcut for launching VS Code always run vcvarsall.bat first. That way, I don't need to configure anything per-project for the C++ extension to work.

If anyone else wants to do that, create a batch file as follows, and set VCVARSALL to point to vcvarsall.bat:

"%VCVARSALL%" x64 && start Code

This issue is labeled closed but I don't see any workable resolutions in it.

I have VSCode installed and Visual Studio 2019, and following the tutorial at https://code.visualstudio.com/docs/cpp/config-msvc does not work for me.

I tried kaiskye's suggestion using the vcvarsall.bat file and then code, also the article instruction of running code from the developer command prompt and same result - as the screenshot shows,still can't find the #includes, even though the vars screen below shows all variables set correctly. Also, no build tasks found under c++ or cl.exe so I can't complete the tutorial.

vscode-cpp-ext-not-finding-build-task

Hi Ionmiller. Your issue appears to be with how the extension is configured. Could you open a new issue? It should prompt you to provide details about your configuration. The following:

  • contents of c_cpp_properties.json
  • Output of C/C++: Log Diagnostics for the file
  • Debug C/C++ Log channel output leading up to the issue ("C_Cpp.loggingLevel": "Debug")

.. would give us the information we would need to understand what is going on.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ecbrodie picture ecbrodie  Â·  3Comments

vicatcu picture vicatcu  Â·  3Comments

narutse picture narutse  Â·  3Comments

wdc596933938 picture wdc596933938  Â·  3Comments

arl picture arl  Â·  3Comments