Example: GNU Patch from CMake

To patch files in one’s own project, or when using other projects via FetchContent etc., it’s possible to patch source/header/etc. using GNU Patch and add_custom_command() with the benefit of CMake canonical approach (triggers only if source changes).

I have seen requests for this but didn’t find a cross-platform solution (Linux, MacOS, Windows) so I made an example. It requires that GNU Patch “patch” is available, which is usually is. On Windows, MSYS2 or WSL are used to get patch executable.

1 Like

thanks, this really helped me! a thing though: if the file to patch is inside a git submodule, copying it in the build directory doesn’t make it build. i tested and overwriting the file in the source directory works, but runs only if it is a clean build i think, because the timestamp of the modified file will always be newer if you change it. also, i added a add_custom_target with the specified dependency to make the build system know it has to build it before the using project