Function “patsubst” in Makefile

In fact all is explained in the doc:

Finds whitespace-separated words in TEXT …

means that one or more spaces have to separate the words.

… that match PATTERN …

means that it select only words that match a pattern (which can include some spaces).

… and replaces them with REPLACEMENT.

means that the selected patterns will be replace by a replacement.


A picture is worth a thousand words.

For PATTERN = X:

           +----  SEPARATORS  ----+
           |                      |
   +-------+-------+     +--------+------+
   |               |     |               | 
X  space space space  X  space space space  x
|                     |                     |
+---------------------+---------------------+
                      |
                   PATTERNS

For PATTERN = X%:

                 +----  SEPARATORS  ---+
                 |                     |
               +-+-+                 +-+-+
               |   |                 |   | 
X  space space space  X  space space space  x
|            |        |            |        |
+------+-----+        +------+-----+        |
       |                     |              |
       +---  PATTERNS  ------+--------------+

Interesting thing:

When you use the % character in your pattern, you can re-use it in the replacement, like this:

$(patsubst x%,y%,xa xb xc)
# Will be "ya yb yc"

But when you have space character in the % variable, make will strip them in the replacement.

$(patsubst x%,y%,xa   xb   xc)
# Will also be "ya yb yc"

EDIT: After reading the source code, the interesting things are:

  • function.c +146: The function patsubst_expand_pat
  • misc.c +337: The function find_next_token
  • misc.c +325: The function next_token

So here is the behavior:

  1. If no % in the pattern, this is a simple substitution (which keep the spaces).
  2. Else it split the text by words and get rid of all spaces (using the isblank function).
  3. Finally, it does the replacement

Leave a Comment

tech