Notes on Building C Code in Windows

2014-10-08 16:14

Just for fun I wanted to make some notes about how to compile a simple C program in Windows from the command line with the minimal of extras to install. If you go looking on the web almost all answers to the question "how do I compile a C program on windows?" is either to download and install Visual Studio Express for Windows (the free version of Visual Studio), to use MinGW or to get Cygwin.

A better basic answer in my humble opinion is that you can use the Microsoft Windows SDK to get a usable C/C++ compiler on your system.

Ok, so, how do you go about to compile a C-program from command line on Windows once you got the SDK installed?

First we have to locate the compiler. If installed by the SDK it can be found at C:\Program Files\Microsoft SDKs\Windows\< version >\bin\cl.exe but if you have Visual Studio installed it can be found at C:\Program Files (x86)\Microsoft Visual Studio < version >\VC\bin\cl.exe.

Of course, being windows, as I run through these examples the installation of the SDK fails so I resort to the fallback of using Visual Studio thus failing to prove my point of not need to install Visual Studio entirely.

So my initial assertion about there being a better basic answer to this is false.


Compile and link

Using the this simple test program (saved as main.c):

#include <stdio.h>

int main(int argc, char* argv[]) {
  printf("hello world!\n");
  return 0;

With Visual Studio installed just run a Developer Command Prompt (found under Tools section of Visual Studio program group), change dir to your project directory and run:

cl main.c

This should compile and link the code to give you a main.exe executable.

Just out of curiosity I wrote a bat file to accomplish the same thing my system (still using Visual Studio) without using the developer command prompt:

set compiler=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\cl.exe
set include=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include
set lib=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\LIB;C:\Program Files (x86)\Windows Kits\8.1\lib\winv6.3\um\x86

"%compiler%" /I"%include%" main.c /link "%lib%"*

The magic of the develop command prompt is it runs the vcvarsall.bat to setup paths correctly. Have a look at it if you want to understand how it works. On my system it can be found in C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat.


The easiest way to compile a C-program in Windows is without doubt to install Visual Studio.

The second viable option, with a smaller footprint and very well suited for those coming from a UNIX world, is to use MinGW or Cygwin.