PCH: Issue with regenerating pch file with Clang when changing defines in project
Attaching project below.
The issue is that when you use Clang + CMake + PCH, and you build once, and then you change the project to add a define, and build again, the build will fail because Clang says the gch file / module file is out of date.
Here is sample error message:
fatal error: PCH file '/Volumes/T3/Dev/projects/cmake/pch_rebuild_needed/build/CMakeFiles/myapp.dir/CMakeFiles/myapp.dir/cmake_pch.hxx.gch' is out of date and needs to be rebuilt:
module file out of date
note: imported by '/Volumes/T3/Dev/projects/cmake/pch_rebuild_needed/build/CMakeFiles/myapp.dir/CMakeFiles/myapp.dir/cmake_pch.hxx.gch'
1 error generated.
Note that this seems to be a bug in clang. If you try to invoke the compiler to generate a gch file with the exact same command line twice, it will create an invalid gch file, and on the third time it will even complain that the gch file can't be created.
The same does not happen with GCC / MSVC.
Tested the issue to happen with Clang 8.0.1 and AppleClang 10.0.1 (XCode 10.2). It looks like the issue is somehow connected to the fact that both the header file and the compiled artifact are in the same directory.
I think the fix / workaround would be to always remove the gch file before trying to compile it.
Inline project:
cmake_minimum_required(VERSION 3.15)
project(precompile_header_issue VERSION 0.1 LANGUAGES CXX)
add_executable(myapp main.cpp header.cpp)
target_include_directories(myapp PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_precompile_headers(myapp PRIVATE header.h)
# First build with this commented.
# Then build with this uncommented.
#target_compile_definitions(myapp PRIVATE foo)
// main.cpp
#include "header.h"
int main() {return blob();}
// header.h
#ifndef BLOB
#define BLOB
int blob();
#endif
// header.cpp
int blob() { return 2;}