m4 Is Greedy

The m4 program is greedy. That is, if a macro is already defined, its value will replace its name in the second declaration. Consider this input file:

define(A,B)
define(A,C)
A B

Here, the first line assigns the value B to the macro named A. The second line notices that A is a defined macro, so m4 replaces that A with B and then defines B as having the value C. The output of this file, after processing with m4, will be:

C C

To prevent this kind of greedy behavior (and to prevent the confusion it can create), you can quote an item to prevent m4 from interpreting it. You quote with m4 by surrounding each item with left and right single quotes:

define(A,B)
define(`A',C)
A B

Here, the first line defines A as B like before. But the second line no longer sees A as a macro. Instead, the single quotes allow A to be redefined as C. So, the output is now:

C B

Although it is not strictly necessary, we recommend that all macro and value pairs be quoted. The preceding line should generally be expressed like this:

define(`A',`B')
define(`A',`C')
A B

This is the form we use when illustrating m4 throughout this book, including in the previous two chapters.

Get sendmail, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.