Using clang on Windows

Update 1: Visual Studio 2017 works. Thanks to STL.


Disclaimer: This isn't about clang/C2, clang/C2 is Microsoft own fork of clang to work with their backend. This is using clang + llvm.

tl;dr: All the source is in this repository: https://github.com/Leandros/ClangOnWindows


Recently Chrome decided to switch their Windows builds to use clang, exclusively. That got me intrigued to try it again, since my former experience of trying to use clang on Windows was rather mixed. However if it's good enough for Chrome, it surely must've improved!

Unfortunately, getting clang to compile MSVC based projects isn't as easy as just dropping in clang and changing a few flags. Let's get started.

Requirements

You'll need:

Building

Since I want to keep this build-system independent, I've setup a .bat script with all the required steps to compile a simple example. You can grab it here: github.com/Leandros/ClangOnWindows.

Open the build.bat and let's walk through it:

  • Set LLVMPath, VSPath and WinSDKPath to the installation paths of LLVM, VS 2017 and the current Windows Kit.
  • OUTPUT defines the name of the final .exe.
  • CFLAGS contains all your usual clang compiler flags, for our example I've kept them simple.
  • CPPFLAGS defines the include directories of the Universal CRT, C++ Standard Library and Windows SDK.
  • LDLIBS defines the library import paths for the Universal CRT, C++ Standard Library and Windows SDK.
  • MSEXT are the required flags to make clang act more like CL. Not required anymore, Visual Studio 2017 will work without.

The rest of the file is dedicated to compiling all .cc files in the current directory and linking them into an executable.

This example makes use of lld, LLVMs linker. It has a caveat, it's not yet able to fully emit PDBs, you might want to consider to keep using LINK.EXE until lld is fully ready. You can use your normal linking process, the output of clang is fully compatible.

Questions? @ArvidGerstmann on Twitter.