Add ability to share precompiled headers between subdirectories
I successfully enabled precompiled headers for my application using
add_executable(
${CMAKE_PROJECT_NAME}
main.cpp
)
target_precompile_headers(
${CMAKE_PROJECT_NAME}
PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:<array$<ANGLE-R>>"
"$<$<COMPILE_LANGUAGE:CXX>:<cstddef$<ANGLE-R>>"
"$<$<COMPILE_LANGUAGE:CXX>:<cstdint$<ANGLE-R>>"
"$<$<COMPILE_LANGUAGE:CXX>:<cmath$<ANGLE-R>>"
"$<$<COMPILE_LANGUAGE:CXX>:<string$<ANGLE-R>>"
"$<$<COMPILE_LANGUAGE:CXX>:<vector$<ANGLE-R>>"
"$<$<COMPILE_LANGUAGE:CXX>:<boost/asio.hpp$<ANGLE-R>>"
)
But most of my application source code is organized in separate CMake library targets which are included via add_subdirectory
and linked via target_link_libraries
:
add_subdirectory(myLib)
target_link_libraries(
${CMAKE_PROJECT_NAME}
PRIVATE
myLib
)
These libraries are shared between multiple projects and don't know anything about precompiled headers. My idea is to "inject" the precompiled headers from the executable (above) into the build of those libraries (which requires that the whole project shares the same preprocessor definitions):
get_target_property(
APPLICATION_LINK_LIBRARIES
${CMAKE_PROJECT_NAME}
LINK_LIBRARIES
)
foreach(lib ${APPLICATION_LINK_LIBRARIES})
if(TARGET ${lib})
target_precompile_headers(
${lib}
REUSE_FROM
${CMAKE_PROJECT_NAME}
)
endif()
endforeach()
Unfortunately the code above fails with:
CMake Error at CMakeLists.txt:543 (target_precompile_headers): PRECOMPILE_HEADERS_REUSE_FROM set with non existing target
It looks like the executable target (from the top level CMakeLists.txt
) is not visible within the CMakeLists.txt
included via add_subdirectory
.
I considered creating precompiled headers individually for each library target, but as there are many libraries which only a few source files per lib, there would be no performance benefit in this case.