CMake apply patch file

Patching files with the patch program has been a common task for decades. Due to technical issues with potential patch library implementation, CMake does not include a native patch function. We use CMake to detect if “patch” is available, which it virtually always is on Unix-like systems. For Windows, we use WSL.

The example below is for patching a single file, but could be extended to a directory structure. In this example “my.c” is the source file to be patched, and “my.patch” is the “diff -u” generated patch file.