C++ - Reuse PCH accross static libraries

Hi,
I would like to generate precompiled headers and reuse them in static libraries, to avoid having n times the same pch, generated locally.

Here the structure:

-- root_folder
     -- pch_lib
          -- build         <- I would like to reuse the pch generated here in the other static libs
          -- include
          -- source
          -- CMakeLists.txt
     -- static_lib1
          -- build
          -- include
          -- source
          -- CMakeLists.txt
     -- static_lib2
          -- build
          -- include
          -- source
          -- CMakeLists.txt

Both the static libs have the same include requirements (vector, deque… and others);

Here is my Cmake for pch_lib (very simplified and commented inline for this post)

cmake_minimum_required(VERSION 3.20)

set(APP_NAME MY_pch)
project(${APP_NAME} LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS ON)

set(HEADER_FILES_workspace ${CMAKE_SOURCE_DIR}/../)
... other variables set

set(CMAKE_EXE_LINKER_FLAGS -fuse-ld=mold)
set(CMAKE_CONFIGURATION_TYPES "Debug" "Release")
file(GLOB SOURCES DEPENDS_ON  source/*.cpp)

add_library(${APP_NAME} STATIC ${SOURCES})
set_target_properties(${APP_NAME} PROPERTIES LINKER_LANGUAGE CXX)

target_include_directories(${APP_NAME} PUBLIC ${HEADERS1} ${HEADERS2})
target_compile_options(${APP_NAME} PUBLIC -Wall -Wextra -pedantic)

target_precompile_headers(${APP_NAME} PUBLIC <vector> <iostream> and others)

Now, here is the cmake for static lib1:

cmake_minimum_required(VERSION 3.20)

set(APP_NAME static_lib1)
project(${APP_NAME} LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS ON)

set(HEADER_FILES_workspace ${CMAKE_SOURCE_DIR}/../)
.. other variable set

set(CMAKE_EXE_LINKER_FLAGS -fuse-ld=mold)
set(CMAKE_CONFIGURATION_TYPES "Debug" "Release")
file(GLOB SOURCES DEPENDS_ON  source/*.cpp)

set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)

add_library(${APP_NAME} STATIC ${SOURCES})
set_target_properties(${APP_NAME} PROPERTIES LINKER_LANGUAGE CXX)

target_precompile_headers(${APP_NAME} REUSE_FROM ? ) <-- How to handle this?

target_include_directories(${APP_NAME} PUBLIC ${HEADERS1} ${HEADERS2})
target_compile_options(${APP_NAME} PUBLIC -Wall -Wextra -pedantic)

I don’t know how to tell cmake to reuse the pch compiled by the pch_lib.
I am not even sure I did it the proper way for pch_lib (I create a static library for nothing there).

Questions:

  • Is there a better way to generate the dummy lib to create the PCH?
  • How to set the reuse_from property?

May you please help me solving this?

I guess I won’t reuse any PCH and waste some SSD space and redo the operation for each library.

It is striking me that no mechanism exists, except major manual hack ( filesystem linking, and modification of the CMake compilation output)…

I secretly hope I am wrong