In project README
CMake does not allow to insert source file to existing target once it has been defined.
But source can be insert before add_executable/library.
Even if it was possible, we could not ensure precompiled header is built first in main target, but adding it as subtarget we can.
It's possible with OBJECT_DEPENDS property on source files.
We cannot prevent header.pch, which is output of CPCH/CXXPCH compiler from being linked when it is in part of main target, but if we put it into OBJECT library, then by definition we skip linking process. Also we take the result object to be a recompiled header for main target.
Output can be changed witho dummy .o file without code.
project(pchtest CXX)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
add_executable(${PROJECT_NAME} "main.cpp" "pch.cpp" "pch.h" "pch_dummy.cpp")
add_compile_options(${PROJECT_NAME} PUBLIC -Wall -Werror -Winvalid-pch)
set_source_files_properties(pch.cpp PROPERTIES COMPILE_OPTIONS "-x;c++-header" OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/pchtest.dir/pch_dummy.cpp.o)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/pch.h.gch
COMMAND ${CMAKE_COMMAND} -E rename ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/pchtest.dir/pch.cpp.o ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/pch.h.gch
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/pchtest.dir/pch_dummy.cpp.o ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/pchtest.dir/pch.cpp.o
COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/pch.h.gch
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/pchtest.dir/pch.cpp.o
COMMENT "Copy PCH"
)
set_source_files_properties(main.cpp PROPERTIES OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/pch.h.gch COMPILE_OPTIONS "-include;${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/pch.h")
Full example here.
Works with CMake 3.14.3, gcc 8.3.1 and Makefile generator. Ninja generator doesn't works but it seems a CMake bug. I opened an issue here.
In project README
But source can be insert before
add_executable/library.It's possible with
OBJECT_DEPENDSproperty on source files.Output can be changed witho dummy .o file without code.
Full example here.
Works with CMake 3.14.3, gcc 8.3.1 and Makefile generator. Ninja generator doesn't works but it seems a CMake bug. I opened an issue here.