Creating and Using Macros

Macros (often called variables) are like variables in a programming language. In make, they are most similar to variables in the shell language, having string values that can be assigned, referenced, and compared.

Defining macros

GNU make provides multiple ways to define macros. The different mechanisms affect how make treats the value being assigned. This in turn affects how the value is treated when the macro’s value is retrieved, or referenced. GNU make defines two types of variables, called recursively expanded variables and simply expanded variables, respectively. The various macro assignment forms are as follows:

name = value

Create a recursively expanded variable. The value of name is the verbatim text on the right side of the =. If this value contains any references to other variable values, those values are retrieved and expanded when the original variable is referenced. For example:

    bar = v1
    foo = $(bar)            Value of bar retrieved when foo's value is referenced
    ...
    x = $(foo)              x is assigned 'v1'
    bar = v2
    y = $(foo)y is assigned 'v2'
name := value

Create a simply expanded variable. The value is expanded completely, immediately at the time of the assignment. Any variable references in value are expanded then and there. For example:

    bar = v1
    foo := $(bar)           foo is assigned 'v1'
    x = $(foo)              x is assigned 'v1'
    bar = v2
    y = $(foo)y is still assigned 'v1'

A significant advantage of simply expanded variables is that they work like variables in most programming languages, ...

Get Unix in a Nutshell, 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.