Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define the task.json to compile C/C++ code in vscode by using the cl.exe on windows?

I have installed the Microsoft Visual C++ Build Tools 2015 on my 64bit win10 , and can use the cl.exe to compile and link the C/C++ program in a plain Command Prompt window by the following steps (some instructions from Setting the Path and Environment Variables for Command-Line Builds):

 1. cd "\Program Files (x86)\Microsoft Visual Studio 14.0\VC"
 2. vcvarsall amd64
 3. cl helloworld.c

The helloworld.c is just a simple C source file to print "Hello world!". I aslo try to congfigure the task.json to directly compile and link C/C++ programs in the vs code. Here is my task.json:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "vcvarsall amd64 && cl",
    "isShellCommand": true,
    "args": ["${file}"],
    "showOutput": "always"
}

And the path of vsvarsall and cl have been added in the PATH. But it still doesn't work (the output is put at the end of the post). So my question is that: how can I to define the task.json which can first run the vcvarsall amd64 to set system variables and then execute the cl command to compile and link programs.

enter image description here

like image 693
Yulong Ao Avatar asked Oct 30 '22 20:10

Yulong Ao


1 Answers

As Rudolfs Bundulis said, make a batch file and just call it, inside it do everything you need to do.

tasks.json:

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

And in your project have the build.bat goodness.

build.bat:

@echo off
call "E:\programs\VS2015\VC\vcvarsall.bat" x64      <----- update your path to vcvarsall.bat

..
cl %YourCompilerFlags% main.cpp %YourLinkerFlags%
..

I would mention that you'd like to have another visual studio code bootstraper batch that would set the vcvars environment and then starts up the editor so you don't set the vcvars for every build. Like so:

@echo off
call "E:\programs\VS2015\VC\vcvarsall.bat" x64      <----- update your path to vcvarsall.bat

code

This way you can omit setting the vcvarsall.bat every time you compile the code. Minimal rebuild flag will also help you a lot so you only compile changed files.

like image 133
androidu Avatar answered Nov 15 '22 07:11

androidu