1

I would like to know if anyone here has managed to use CMake to build a precompiled header in a single location within a project and then use it from that location to build the other libraries and executables of the project. The only way I have managed to do this is to copy the pch file manually in each library/executable folder but I want to avoid having to do this because it takes a lot of space and time.

Say I have this project structure

root
| include
  - precompiled.h
  - common_project_header_files
| src
  | precompiled
    - precompiled.cc
  | lib1
    - source/header files for lib1
  | lib2
    - source/header files for lib2
| lib

I would like to first build precompiled.pch using precompiled.h and precompiled.cc (which only includes precompiled.h) in a location visible to the libraries' files and then use it from there to build lib1 and lib2.

Can this be done using CMake?

tatones
  • 81
  • 4

1 Answers1

0

I had the same problem and found a working solution (albeit not perfect, see below). Say that precompiled is the target of the build command that creates your precompiled.pch in the build directory. Add a custom command to precompiled, like so:

add_custom_command(TARGET precompiled POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E
  copy  "${CMAKE_BINARY_DIR}/precompiled.pch"
  "${CMAKE_SOURCE_DIR}/include/precompiled.pch")

This will copy precompiled.pch into your include folder whenever it is built. However, you will still run into problems if your lib1 and lib2 targets are built before precompiled, so you have to add precompiled as a dependency of those two to enforce the right build order:

add_dependencies(lib1 precompiled)
add_dependencies(lib2 precompiled)

The reason that I said this is not perfect is that (at least for me) precompiled.pch will be rebuilt from scratch every single time lib1 or lib2 are built (I don't know why). If this is acceptable to you, this solution should work, though.

Roberto
  • 3,003
  • 1
  • 18
  • 25