c++cmakeprecompiled-headers

Can .gch files generated from CMake's target_precompile_headers be shared across targets?


My initial attempt at incorporating precompiled header files in my project resulted in very large (~200MB) and nearly identical .gch files for each target directory. I tried the following approach, which I was hoping would produce a single .gch file generated and shared among targets. However, CMake still generated separate .gch files for each target.

add_library(pch INTERFACE)
target_precompile_headers(pch INTERFACE project.hpp)

add_executable(target1 src1.cpp)
target_link_libraries(target1 PRIVATE pch)

add_executable(target2 src2.cpp)
target_link_libraries(target2 PRIVATE pch)

Is it possible to share a CMake generated .gch file across multiple targets?


Solution

  • You need to use target_precompile_headers per each target you want PCHs for. With one producer you use like you did and then the consumers should look like this:

    target_precompile_headers(target1 REUSE_FROM pch)
    

    And you do not need to link against your pch "library".

    Docs actually have the section for it.