Applying `set_property` on source file generated for CMake precompiled headers without hardcoding PCH path

379 views Asked by At

I am using CMake's target_precompile_headers to generate a precompiled header from a PCH.hpp file in a project I'm contributing to.

I need to ensure that the resultant generated source file has the exact same compilation and warning flags as the other source files in my project, to avoid -Winvalid-pch issues.

At the moment, I am doing this:

target_precompile_headers(sfml-system PRIVATE "${CMAKE_SOURCE_DIR}/src/SFML/PCH.hpp")

set_property(SOURCE "${CMAKE_BINARY_DIR}/src/SFML/System/CMakeFiles/sfml-system.dir/cmake_pch.hxx.cxx" 
             APPEND_STRING PROPERTY COMPILE_FLAGS " ${WARNINGS}")

However, having to hardcode the path to the generated cmake_pch.hxx.cxx file seems brittle, potentially non-portable, and a maintenance burden.

Is there any way I can retrieve the path to the cmake_pch.hxx.cxx file without hardcoding it?

1

There are 1 answers

2
Alex Reinking On

As far as I can tell, the flags associated with the target argument to sfml-system are already applied to the PCH. Here's my reproducer:

cmake_minimum_required(VERSION 3.22)
project(test)

add_executable(test main.cpp)
target_precompile_headers(test PRIVATE "PCH.hpp")

# This is just to probe CMake's behavior. Don't actually
# add defines this way!!
target_compile_options(test PRIVATE "-DVIA_TCO")

Then I create empty main.cpp and PCH.hpp files and do a dry-run of the build:

$ cmake -G Ninja -S . -B build -DCMAKE_CXX_FLAGS="-DVIA_FLAGS"
[1/3] /usr/bin/c++   -DVIA_FLAGS -DVIA_TCO -Winvalid-pch -x c++-header -include /home/alex/test/build/CMakeFiles/test.dir/cmake_pch.hxx -MD -MT CMakeFiles/test.dir/cmake_pch.hxx.gch -MF CMakeFiles/test.dir/cmake_pch.hxx.gch.d -o CMakeFiles/test.dir/cmake_pch.hxx.gch -c /home/alex/test/build/CMakeFiles/test.dir/cmake_pch.hxx.cxx
[2/3] /usr/bin/c++   -DVIA_FLAGS -DVIA_TCO -Winvalid-pch -include /home/alex/test/build/CMakeFiles/test.dir/cmake_pch.hxx -MD -MT CMakeFiles/test.dir/main.cpp.o -MF CMakeFiles/test.dir/main.cpp.o.d -o CMakeFiles/test.dir/main.cpp.o -c /home/alex/test/main.cpp
[3/3] : && /usr/bin/c++ -DVIA_FLAGS  CMakeFiles/test.dir/main.cpp.o -o test   && :

As you can see, both the flags from target_compile_options and CMAKE_CXX_FLAGS (at the command line) applied to the PCH.

So to this point:

I need to ensure that the resultant generated source file has the exact same compilation and warning flags as the other source files in my project, to avoid -Winvalid-pch issues.

Any halfway reasonable way of adding flags should work automatically.