1

I have a project for which I want to apply a patch to a git repo before building the code, then unapply that patch after creating the executable. The reason being that I want the patch applied to the build but I want the repository that is patched to stay clean on its master branch. I noticed add_custom_command seemed to have this capability, with PRE_BUILD and POST_BUILD specifiers. I tried something like this:

add_executable(foo ...)

# foo requires a patch to some library
target_link_libraries(foo ...)

add_custom_command(TARGET foo PRE_BUILD COMMAND git apply somepatch.patch)
add_custom_command(TARGET foo POST_BUILD COMMAND git apply --reverse somepatch.patch)

However, if one looks closer at the documentation of add_custom_command they mention this in the section about the PRE_BUILD specifer:

On Visual Studio Generators, run before any other rules are executed within the target. On other generators, run just before PRE_LINK commands.

And indeed this is what happens. The patch is only getting applied after the compilation phase, and before the linking phase. So the code is being compiled before the patch is applied. How can I ensure the patch is performed before compiling the code?

torek
  • 448,244
  • 59
  • 642
  • 775
Jeff L
  • 491
  • 5
  • 14
  • "I want to apply a patch to a git repo before building the code, then unapply that patch after creating the executable." - While this intention could fit for **linear** process (e.g. implemented by a shell script with several commands executed in a sequence), it hardly fits for **dependency-driven** building process. Even if patching and un-patching source results in the same file, its **timestamp** will be updated. A changed timestamp of a source file is interpreted by a build system as **outdating** of the target file, so the target file will be recompiled on the next build. – Tsyvarev Mar 04 '22 at 18:39
  • `add_custom_command(... DEPENDS ${file_to_patch} ... )` to apply patch and generate timestamp then `add_custom_target(${unique_patch_name}_apply DEPENDS ${generated_timestamp} ...)` then `add_dependencies(${my_target} ${unique_patch_name}_apply)`. Same for reverse. – Osyotr Mar 05 '22 at 00:09

0 Answers0