c++visual-studioprecompiled-headerscl

Using precompiled headers in msvc when building from the command line with the cl compiler


Edit: I know how to use it in VS, and CMake, I am trying to find out how to do it using cl.exe on the command line and not from inside the Visual Studio IDE or using a build generator like CMake.

Original question: I am trying to use precompiled headers on windows with MSVC. mainly to bundle all Microsoft's headers in one place and precompile them for faster compile builds.

The problem is I can not figure out how to actually use pch files. I was trying following the two links from the official documentation: Create Precompiled Headers and also this: Use Precompiled Headers

I am generating the .pch file are follows:

cl /c /Ycheaders.h main.cpp

inside headers.h I do the following:

#include <windows.h>
#include <iostream>
//--- other includes that will never change ----//

And following the documentation this is how I try to use it.

cl /Yuheaders.h main.cpp

this get me the following error: fatal error C1854: cannot overwrite information formed during creation of the precompiled header in object main.obj

I assumed the documentation is wrong (because the provided command in the docs: cl /Ycheader.h main.cpp is wrong and does not work and it needs /c before it as in the comment in the example code), It did not make sense to me to compile your main.cpp so I repeated the steps above with creating the precompiled headers files with headers.cpp instead of main.cpp where headers.cpp is just an empty source file with a single include headers.h and the I get a linking error 1 unresolved external LINK error 1120 without specifying what was unresolved.

Ideally if anyone has a minimal example of how to create header files for msvc and then shows how to use them.


Solution

  • Create pch:

    cl /EHsc /c /Ycheader.h header.cpp
    

    Use pch:

    cl /EHsc /Yuheader.h /Fpheader.pch main.cpp /link header.obj