Patching Source Code

This document describes how to create and apply a patch to source code. A patch is a text file that contains the information needed to change a set of source files from one version to another. A patch is created by using the diff command to compare two directories: one directory contains the original version of the source code, and the other directory contains the new version of the source code. The output of the diff command is captured in a text file, which is the “patch”.

A patch allows a new version of source code to be recreated from the original source code by applying the patch to a copy of the original source code.

Creating a Patch

To create a patch, you need two copies of the source code.

In the directory containing the new, modified version of the source code, remove any files that are not part of the source code (for example, object files that were left in the directory when the source code was compiled).

Create the patch using the diff command with the –urNb options. Redirect the output from the diff command to a file that will contain the patch. To simplify using the patch later, it is best if the directory with the original source code and the directory with the new source code are subdirectories of the same directory. Also, be sure to list the directories on the command line with the original directory first and the new directory second.

$ cd parentDirectory

$ diff –urNb originalSourceDirectory newSourceDirectory >patchFile

Applying a Patch

Use the following commands to apply the patch.

$ cd sourceDirectory/..

$ patch –spx <patchFile

In the options to the patch command, replace x with the number of nodes to strip from the file names inside the patch so they line up with the directory where you are applying the patch from. The easiest way to determine this is to open the patch file in an editor and look at the file names. It is usually a simple matter to determine how many nodes to strip so that the file names in the patch will be relative to the current directory.

For example, in the example of creating a patch above, the patch was made from the directory one level above the source directories. The commands to apply the patch above are executed from the directory containing the source code, which is one level lower. Thus, in this example, x should be replaced with 1.

It is possible that there will be conflicts with other changes when the patch is applied if other changes have been made to the new source code. To find the parts of the patch that did not apply correctly, use the following commands.

$ cd sourceDirectory

$ find . –name “*.rej” –print