Use git apply
from CMake to patch source/headers/etc. under the build directory, even with untracked files.
This works on Linux, MacOS, Windows, etc. assuming Git is installed. We have tested this approach with GCC, Clang, oneAPI, MSVC, MinGW, MSYS2, etc.
This is a canonical CMake approach using add_custom_command() that is only triggered if the input file changes. It can also be used for FetchContent patching etc.
As per add_custom_command() docs, the add_custom_command() must be in the same directory as the consuming target. Otherwise, add_custom_command() is not triggered and the file isn't patch. If targets from multiple directories consume the patched file, ensure one of the targets is in the same directory as add_custom_command(), then use add_dependencies() from the other targets to the target in the patch directory.
We show a non-basic case where we have a header file to patch, showing how to prepend include directories. Compilers prioritize include directories left-to-right.
git apply
avoids numerous pitfalls experienced with GNU Patch.
More advanced projects such as those using FetchContent may need additional techniques. This example CMakeLists.txt shows that we had to rename some files to avoid collisions.