So compiling C on VS Code on Windows is an absolute nightmare.
The only way I am able to "force" VSCode to compile and debug my C/C++ programs is by either:
%comspec% /k "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\VsDevCmd.bat"
.bat
file set up, as this similar StackOverflow question suggests.While these approaches work, they feel like workarounds and are not ideal. What I want is to make cl.exe
work "natively" within VSCode without needing to rely on the Developer Command Prompt or any scripts.
Is there a way to set up VSCode so that cl.exe
can be used for compiling and debugging C/C++ code without these manual steps every time? I'm looking for a more permanent solution to set up the environment correctly for cl.exe
on Windows.
As I was writing this question I finally found the solution, so I decided to share it here. I tried to make it beginner friendly (win10 - x64).
Steps (for x64):
Locate and copy x64 cl.exe
's location, usually at:
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\[version]\bin\Hostx64\x64
Press Win+R to open Run dialog and type sysdm.cpl
to get System Properties
Go to Advanced
Tab
Click on Environment Variables
In System variables
section locate Path
variable and double click it
On the new window that pops up click New
and add cl.exe
's location
Click OK
Now we still have to add the VARS
that are setup when you run Developer Command Prompt for VS YYYY
:
Open x64 Native Tools Command Prompt for VS YYYY
. It has to be x64
or else you'll get a library machine type 'x86' conflicts with target machine type 'x64'
error when compiling.
cd
to your preferred directory as we are going to create a file
Run set > envvars.txt
On this new file envvars.txt
find these 3 lines:
a) INCLUDE=C:\...
b) LIB=C:\...
c) and LIBPATH=C:\...
and delete everything else.
Now there are 2 ways to add these VARS
to the System variables
manually or through a one-time *.bat
file. I chose the *.bat
file way:
We are going to turn envvars.txt
into this *.bat
file by:
a) Preceding each of the vars by setx
(permanently setting environment variables)
b) Replacing the =
with a space
c) involving the paths with quotation marks ""
d) adding /M
after the paths on each line (ensures that the variables are set for the system and not just the current user)
We should have something like:
setx INCLUDE "C:\Program Files\..." /M
setx LIB "C:\Program Files\..." /M
setx LIBPATH "C:\Program Files\..." /M
Rename envvars.txt
to envvars.bat
Execute as Administrator
Restart computer
Done.
After restart you should be able to launch VS Code however and just compile and debug. (ASSUMING YOUR TASKS.JSON
AND LAUNCH.JSON
are setup properly)