Diff & Patch for Win32

When you have modified some the source code of some project you downloaded, but do not want to commit your changes to the repository or don’t have write access to the repository, the universal language for transmitting these changes to other people is a patch in the unified diff format. This is much better than just zipping the source tree because with a patch, other people can apply your changes to their own source file tree without destroying their own changes to the sources.

For example, many of the precompiled binaries I store in my externals repository include a patch file containing the changes I’ve done (mostly just adding new project files matching my preferences).

The archive attached to this article contains the diff.exe and patch.exe from the gnuwin32 project, tweaked a little so that you don’t require administrator privileges to run patch.exe.

How to Create a Patch

My preferred way of packaging patches is to put a directory containing the unchanged files in parallel to the one containing the changed files like this:

  • Directory Icon SomeLibrary-1.2.3-original
  • Directory Icon SomeLibrary-1.2.3

Another thing you can see here is my naming scheme: I always add the version number of the library to the directory name. This makes it unambiguously clear which version of the library the patch is for.

I name the directory containing original (unmodified) state of the library like my working directory, but with -original appended to it. This name is completely ignored when you apply the patch, but anyone reading the patch in an editor will immediately get the right idea which side is which!

Finally, as a matter of common courtesy, make sure your patch is clean and doesn’t contain pointless artifacts such as build logs, temporary files or other random stuff.

To generate a patch, open a command prompt and navigate to the directory containing the two directories you wish to compare and enter:

  diff -r -u -N -w SomeLibrary-1.2.3-original SomeLibrary-1.2.3 > SomeLibrary-1.2.3-changes.patch

Applying Patches

To apply a patch, read the patch to find out what file structure it expects. The patch created before would require you to place an unmodified copy of the code in a directory called SomeLibrary-1.2.3.

Then open a command prompt and navigate to the right place for the patch (again, for the example patch above, that would be one directory above SomeLibrary-1.2.3). Then apply the patch by piping it to patch.exe:

  patch -p0 < SomeLibrary-1.2.3-changes.patch

The -p0 indicates the number of directory levels you want to strip from the patch. With -p0, no directories will be stripped, but if the patch contains a leading slash (which would turn this in to an absolute path starting at the root directory), that will be removed.


gnuwin32-diff-patch.7z (637 KiB)

Leave a Reply

Your email address will not be published. Required fields are marked *

Please copy the string k8XqKY to the field below: