# Example: GNU Patch from CMake

**URL:** https://discourse.cmake.org/t/example-gnu-patch-from-cmake/4492
**Category:** Code
**Created:** [November 16, 2021, 5:04pm UTC](https://discourse.cmake.org/t/example-gnu-patch-from-cmake/4492 "2021-11-16T17:04:10Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![scivision](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/s/a87d85/32.png) [@scivision](https://discourse.cmake.org/u/scivision)
#### Post date: [November 16, 2021, 5:04pm UTC](https://discourse.cmake.org/t/example-gnu-patch-from-cmake/4492/1 "2021-11-16T17:04:10Z")

</div>

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.

> **[GitHub - scivision/cmake-patch-file: Use GNU Patch from CMake to patch...](https://github.com/scivision/cmake-patch-file)**
>
> Use GNU Patch from CMake to patch source/headers/etc. - GitHub - scivision/cmake-patch-file: Use GNU Patch from CMake to patch source/headers/etc.

---

<div class="post-metadata">

### Author: ![bertulli](https://discourse.cmake.org/user_avatar/discourse.cmake.org/bertulli/32/4630_2.png) [@bertulli](https://discourse.cmake.org/u/bertulli)
#### Post date: [August 1, 2025, 3:09pm UTC](https://discourse.cmake.org/t/example-gnu-patch-from-cmake/4492/2 "2025-08-01T15:09:27Z")

</div>

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
