I have seen a few (old) posts on the 'net about hacking together some support for pre-compiled headers in CMake. They all seem a bit all-over the place and everyone has their own way of doing it. What is the best way of doing it currently?


There is a third party CMake module named 'Cotire' which automates the use of precompiled headers for CMake based build systems and also supports unity builds.


CMake has just gained support for PCHs (pre-compiled headers), it should be available in the upcoming 3.16 release, due 2019-10-01:

https://gitlab.kitware.com/cmake/cmake/merge_requests/3553

  target_precompile_headers(<target>
    <INTERFACE|PUBLIC|PRIVATE> [header1...]
    [<INTERFACE|PUBLIC|PRIVATE> [header2...] ...])

There is ongoing discussion on supporting sharing PCHs between targets: https://gitlab.kitware.com/cmake/cmake/issues/19659

There is some additional context (motivation, numbers) available at https://blog.qt.io/blog/2019/08/01/precompiled-headers-and-unity-jumbo-builds-in-upcoming-cmake/