GNU make - 6. How to Use Variables

Go to the first, previous, next, last section, table of contents.

# 6. How to Use Variables

A variable is a name defined in a makefile to represent a string of text, called the variable's value. These values are substituted by explicit request into targets, dependencies, commands, and other parts of the makefile. (In some other versions of `make`, variables are called macros.)

Variables and functions in all parts of a makefile are expanded when read, except for the shell commands in rules, the right-hand sides of variable definitions using ``='`, and the bodies of variable definitions using the `define` directive.

Variables can represent lists of file names, options to pass to compilers, programs to run, directories to look in for source files, directories to write output in, or anything else you can imagine.

A variable name may be any sequence of characters not containing ``:'`, ``#'`, ``='`, or leading or trailing whitespace. However, variable names containing characters other than letters, numbers, and underscores should be avoided, as they may be given special meanings in the future, and with some shells they cannot be passed through the environment to a sub-`make` (see section 5.6.2 Communicating Variables to a Sub-`make`).

Variable names are case-sensitive. The names ``foo'`, ``FOO'`, and ``Foo'` all refer to different variables.

It is traditional to use upper case letters in variable names, but we recommend using lower case letters for variable names that serve internal purposes in the makefile, and reserving upper case for parameters that control implicit rules or for parameters that the user should override with command options (see section 9.5 Overriding Variables).

A few variables have names that are a single punctuation character or just a few characters. These are the automatic variables, and they have particular specialized uses. See section 10.5.3 Automatic Variables.

## 6.1 Basics of Variable References

To substitute a variable's value, write a dollar sign followed by the name of the variable in parentheses or braces: either ``$(foo)'` or ``${foo}'` is a valid reference to the variable `foo`. This special significance of ``$'` is why you must write ``$$'` to have the effect of a single dollar sign in a file name or command.

Variable references can be used in any context: targets, dependencies, commands, most directives, and new variable values. Here is an example of a common case, where a variable holds the names of all the object files in a program:

    objects = program.o foo.o utils.o
    program : $(objects)
            cc -o program $(objects)

    $(objects) : defs.h

Variable references work by strict textual substitution. Thus, the rule

    foo = c
    prog.o : prog.$(foo)
            $(foo)$(foo) -$(foo) prog.$(foo)

could be used to compile a C program ``prog.c'`. Since spaces before the variable value are ignored in variable assignments, the value of `foo` is precisely ``c'`. (Don't actually write your makefiles this way!)

A dollar sign followed by a character other than a dollar sign, open-parenthesis or open-brace treats that single character as the variable name. Thus, you could reference the variable `x` with ``$x'`. However, this practice is strongly discouraged, except in the case of the automatic variables (see section 10.5.3 Automatic Variables).

## 6.2 The Two Flavors of Variables

There are two ways that a variable in GNU `make` can have a value; we call them the two flavors of variables. The two flavors are distinguished in how they are defined and in what they do when expanded.

The first flavor of variable is a recursively expanded variable. Variables of this sort are defined by lines using ``='` (see section 6.5 Setting Variables) or by the `define` directive (see section 6.8 Defining Variables Verbatim). The value you specify is installed verbatim; if it contains references to other variables, these references are expanded whenever this variable is substituted (in the course of expanding some other string). When this happens, it is called recursive expansion.

For example,

    foo = $(bar)
    bar = $(ugh)
    ugh = Huh?

    all:;echo $(foo)

will echo ``Huh?'`: ``$(foo)'` expands to ``$(bar)'` which expands to ``$(ugh)'` which finally expands to ``Huh?'`.

This flavor of variable is the only sort supported by other versions of `make`. It has its advantages and its disadvantages. An advantage (most would say) is that:

    CFLAGS = $(include_dirs) -O
    include_dirs = -Ifoo -Ibar

will do what was intended: when ``CFLAGS'` is expanded in a command, it will expand to ``-Ifoo -Ibar -O'`. A major disadvantage is that you cannot append something on the end of a variable, as in

    CFLAGS = $(CFLAGS) -O

because it will cause an infinite loop in the variable expansion. (Actually `make` detects the infinite loop and reports an error.)

Another disadvantage is that any functions (see section 8. Functions for Transforming Text) referenced in the definition will be executed every time the variable is expanded. This makes `make` run slower; worse, it causes the `wildcard` and `shell` functions to give unpredictable results because you cannot easily control when they are called, or even how many times.

To avoid all the problems and inconveniences of recursively expanded variables, there is another flavor: simply expanded variables.

Simply expanded variables are defined by lines using ``:='` (see section 6.5 Setting Variables). The value of a simply expanded variable is scanned once and for all, expanding any references to other variables and functions, when the variable is defined. The actual value of the simply expanded variable is the result of expanding the text that you write. It does not contain any references to other variables; it contains their values as of the time this variable was defined. Therefore,

    x := foo
    y := $(x) bar
    x := later

is equivalent to

    y := foo bar
    x := later

When a simply expanded variable is referenced, its value is substituted verbatim.

Here is a somewhat more complicated example, illustrating the use of ``:='` in conjunction with the `shell` function. (See section 8.6 The `shell` Function.) This example also shows use of the variable `MAKELEVEL`, which is changed when it is passed down from level to level. (See section 5.6.2 Communicating Variables to a Sub-`make`, for information about `MAKELEVEL`.)

    ifeq (0,${MAKELEVEL})
    cur-dir   := $(shell pwd)
    whoami    := $(shell whoami)
    host-type := $(shell arch)
    MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
    endif

An advantage of this use of ``:='` is that a typical `descend into a directory' command then looks like this:

    ${subdirs}:
          ${MAKE} cur-dir=${cur-dir}/$@ -C $@ all

Simply expanded variables generally make complicated makefile programming more predictable because they work like variables in most programming languages. They allow you to redefine a variable using its own value (or its value processed in some way by one of the expansion functions) and to use the expansion functions much more efficiently (see section 8. Functions for Transforming Text).

You can also use them to introduce controlled leading whitespace into variable values. Leading whitespace characters are discarded from your input before substitution of variable references and function calls; this means you can include leading spaces in a variable value by protecting them with variable references, like this:

    nullstring :=
    space := $(nullstring) # end of the line

Here the value of the variable `space` is precisely one space. The comment ``# end of the line'` is included here just for clarity. Since trailing space characters are not stripped from variable values, just a space at the end of the line would have the same effect (but be rather hard to read). If you put whitespace at the end of a variable value, it is a good idea to put a comment like that at the end of the line to make your intent clear. Conversely, if you do not want any whitespace characters at the end of your variable value, you must remember not to put a random comment on the end of the line after some whitespace, such as this:

    dir := /foo/bar    # directory to put the frobs in

Here the value of the variable `dir` is ``/foo/bar '` (with four trailing spaces), which was probably not the intention. (Imagine something like ``$(dir)/file'` with this definition!)

There is another assignment operator for variables, ``?='`. This is called a conditional variable assignment operator, because it only has an effect if the variable is not yet defined. This statement:

    FOO ?= bar

is exactly equivalent to this (see section 8.5 The `origin` Function):

    ifeq ($(origin FOO), undefined)
      FOO = bar
    endif

Note that a variable set to an empty value is still defined, so ``?='` will not set that variable.

## 6.3 Advanced Features for Reference to Variables

This section describes some advanced features you can use to reference variables in more flexible ways.

### 6.3.1 Substitution References

A substitution reference substitutes the value of a variable with alterations that you specify. It has the form ``$(var:a=b)'` (or ``${var:a=b}'`) and its meaning is to take the value of the variable var, replace every a at the end of a word with b in that value, and substitute the resulting string.

When we say "at the end of a word", we mean that a must appear either followed by whitespace or at the end of the value in order to be replaced; other occurrences of a in the value are unaltered. For example:

    foo := a.o b.o c.o
    bar := $(foo:.o=.c)

sets ``bar'` to ``a.c b.c c.c'`. See section 6.5 Setting Variables.

A substitution reference is actually an abbreviation for use of the `patsubst` expansion function (see section 8.2 Functions for String Substitution and Analysis). We provide substitution references as well as `patsubst` for compatibility with other implementations of `make`.

Another type of substitution reference lets you use the full power of the `patsubst` function. It has the same form ``$(var:a=b)'` described above, except that now a must contain a single ``%'` character. This case is equivalent to ``$(patsubst a,b,$(var))'`. See section 8.2 Functions for String Substitution and Analysis, for a description of the `patsubst` function.

    For example:

    foo := a.o b.o c.o
    bar := $(foo:%.o=%.c)

sets ``bar'` to ``a.c b.c c.c'`.

### 6.3.2 Computed Variable Names

Computed variable names are a complicated concept needed only for sophisticated makefile programming. For most purposes you need not consider them, except to know that making a variable with a dollar sign in its name might have strange results. However, if you are the type that wants to understand everything, or you are actually interested in what they do, read on.

Variables may be referenced inside the name of a variable. This is called a computed variable name or a nested variable reference. For example,

    x = y
    y = z
    a := $($(x))

defines `a` as ``z'`: the ``$(x)'` inside ``$($(x))'` expands to ``y'`, so ``$($(x))'` expands to ``$(y)'` which in turn expands to ``z'`. Here the name of the variable to reference is not stated explicitly; it is computed by expansion of ``$(x)'`. The reference ``$(x)'` here is nested within the outer variable reference.

The previous example shows two levels of nesting, but any number of levels is possible. For example, here are three levels:

    x = y
    y = z
    z = u
    a := $($($(x)))

Here the innermost ``$(x)'` expands to ``y'`, so ``$($(x))'` expands to ``$(y)'` which in turn expands to ``z'`; now we have ``$(z)'`, which becomes ``u'`.

References to recursively-expanded variables within a variable name are reexpanded in the usual fashion. For example:

    x = $(y)
    y = z
    z = Hello
    a := $($(x))

defines `a` as ``Hello'`: ``$($(x))'` becomes ``$($(y))'` which becomes ``$(z)'` which becomes ``Hello'`.

Nested variable references can also contain modified references and function invocations (see section 8. Functions for Transforming Text), just like any other reference. For example, using the `subst` function (see section 8.2 Functions for String Substitution and Analysis):

    x = variable1
    variable2 := Hello
    y = $(subst 1,2,$(x))
    z = y
    a := $($($(z)))

eventually defines `a` as ``Hello'`. It is doubtful that anyone would ever want to write a nested reference as convoluted as this one, but it works: ``$($($(z)))'` expands to ``$($(y))'` which becomes ``$($(subst 1,2,$(x)))'`. This gets the value ``variable1'` from `x` and changes it by substitution to ``variable2'`, so that the entire string becomes ``$(variable2)'`, a simple variable reference whose value is ``Hello'`.

A computed variable name need not consist entirely of a single variable reference. It can contain several variable references, as well as some invariant text. For example,

    a_dirs := dira dirb
    1_dirs := dir1 dir2

    a_files := filea fileb
    1_files := file1 file2

    ifeq "$(use_a)" "yes"
    a1 := a
    else
    a1 := 1
    endif

    ifeq "$(use_dirs)" "yes"
    df := dirs
    else
    df := files
    endif

    dirs := $($(a1)_$(df))

will give `dirs` the same value as `a_dirs`, `1_dirs`, `a_files` or `1_files` depending on the settings of `use_a` and `use_dirs`.

Computed variable names can also be used in substitution references:

    a_objects := a.o b.o c.o
    1_objects := 1.o 2.o 3.o

    sources := $($(a1)_objects:.o=.c)

defines `sources` as either ``a.c b.c c.c'` or ``1.c 2.c 3.c'`, depending on the value of `a1`.

The only restriction on this sort of use of nested variable references is that they cannot specify part of the name of a function to be called. This is because the test for a recognized function name is done before the expansion of nested references. For example,

    ifdef do_sort
    func := sort
    else
    func := strip
    endif

    bar := a d b g q c

    foo := $($(func) $(bar))

attempts to give ``foo'` the value of the variable ``sort a d b g q c'` or ``strip a d b g q c'`, rather than giving ``a d b g q c'` as the argument to either the `sort` or the `strip` function. This restriction could be removed in the future if that change is shown to be a good idea.

You can also use computed variable names in the left-hand side of a variable assignment, or in a `define` directive, as in:

    dir = foo
    $(dir)_sources := $(wildcard $(dir)/*.c)
    define $(dir)_print
    lpr $($(dir)_sources)
    endef

This example defines the variables ``dir'`, ``foo_sources'`, and ``foo_print'`.

Note that nested variable references are quite different from recursively expanded variables (see section 6.2 The Two Flavors of Variables), though both are used together in complex ways when doing makefile programming.

## 6.4 How Variables Get Their Values

Variables can get values in several different ways:

- You can specify an overriding value when you run `make`. See section 9.5 Overriding Variables.
- You can specify a value in the makefile, either with an assignment (see section 6.5 Setting Variables) or with a verbatim definition (see section 6.8 Defining Variables Verbatim).
- Variables in the environment become `make` variables. See section 6.9 Variables from the Environment.
- Several automatic variables are given new values for each rule. Each of these has a single conventional use. See section 10.5.3 Automatic Variables.
- Several variables have constant initial values. See section 10.3 Variables Used by Implicit Rules.

## 6.5 Setting Variables

To set a variable from the makefile, write a line starting with the variable name followed by ``='` or ``:='`. Whatever follows the ``='` or ``:='` on the line becomes the value. For example,

    objects = main.o foo.o bar.o utils.o

defines a variable named `objects`. Whitespace around the variable name and immediately after the ``='` is ignored.

Variables defined with ``='` are recursively expanded variables. Variables defined with ``:='` are simply expanded variables; these definitions can contain variable references which will be expanded before the definition is made. See section 6.2 The Two Flavors of Variables.

The variable name may contain function and variable references, which are expanded when the line is read to find the actual variable name to use.

There is no limit on the length of the value of a variable except the amount of swapping space on the computer. When a variable definition is long, it is a good idea to break it into several lines by inserting backslash-newline at convenient places in the definition. This will not affect the functioning of `make`, but it will make the makefile easier to read.

Most variable names are considered to have the empty string as a value if you have never set them. Several variables have built-in initial values that are not empty, but you can set them in the usual ways (see section 10.3 Variables Used by Implicit Rules). Several special variables are set automatically to a new value for each rule; these are called the automatic variables (see section 10.5.3 Automatic Variables).

If you'd like a variable to be set to a value only if it's not already set, then you can use the shorthand operator ``?='` instead of ``='`. These two settings of the variable ``FOO'` are identical (see section 8.5 The `origin` Function):

    FOO ?= bar

and

    ifeq ($(origin FOO), undefined)
    FOO = bar
    endif

## 6.6 Appending More Text to Variables

Often it is useful to add more text to the value of a variable already defined. You do this with a line containing ``+='`, like this:

    objects += another.o

This takes the value of the variable `objects`, and adds the text ``another.o'` to it (preceded by a single space). Thus:

    objects = main.o foo.o bar.o utils.o
    objects += another.o

sets `objects` to ``main.o foo.o bar.o utils.o another.o'`.

Using ``+='` is similar to:

    objects = main.o foo.o bar.o utils.o
    objects := $(objects) another.o

but differs in ways that become important when you use more complex values.

When the variable in question has not been defined before, ``+='` acts just like normal ``='`: it defines a recursively-expanded variable. However, when there is a previous definition, exactly what ``+='` does depends on what flavor of variable you defined originally. See section 6.2 The Two Flavors of Variables, for an explanation of the two flavors of variables.

When you add to a variable's value with ``+='`, `make` acts essentially as if you had included the extra text in the initial definition of the variable. If you defined it first with ``:='`, making it a simply-expanded variable, ``+='` adds to that simply-expanded definition, and expands the new text before appending it to the old value just as ``:='` does (see section 6.5 Setting Variables, for a full explanation of ``:='`). In fact,

    variable := value
    variable += more

is exactly equivalent to:

    variable := value
    variable := $(variable) more

On the other hand, when you use ``+='` with a variable that you defined first to be recursively-expanded using plain ``='`, `make` does something a bit different. Recall that when you define a recursively-expanded variable, `make` does not expand the value you set for variable and function references immediately. Instead it stores the text verbatim, and saves these variable and function references to be expanded later, when you refer to the new variable (see section 6.2 The Two Flavors of Variables). When you use ``+='` on a recursively-expanded variable, it is this unexpanded text to which `make` appends the new text you specify.

    variable = value
    variable += more

is roughly equivalent to:

    temp = value
    variable = $(temp) more

except that of course it never defines a variable called `temp`. The importance of this comes when the variable's old value contains variable references. Take this common example:

    CFLAGS = $(includes) -O
    ...
    CFLAGS += -pg # enable profiling

The first line defines the `CFLAGS` variable with a reference to another variable, `includes`. (`CFLAGS` is used by the rules for C compilation; see section 10.2 Catalogue of Implicit Rules.) Using ``='` for the definition makes `CFLAGS` a recursively-expanded variable, meaning ``$(includes) -O'` is not expanded when `make` processes the definition of `CFLAGS`. Thus, `includes` need not be defined yet for its value to take effect. It only has to be defined before any reference to `CFLAGS`. If we tried to append to the value of `CFLAGS` without using ``+='`, we might do it like this:

    CFLAGS := $(CFLAGS) -pg # enable profiling

This is pretty close, but not quite what we want. Using ``:='` redefines `CFLAGS` as a simply-expanded variable; this means `make` expands the text ``$(CFLAGS) -pg'` before setting the variable. If `includes` is not yet defined, we get `` -O -pg'`, and a later definition of `includes` will have no effect. Conversely, by using ``+='` we set `CFLAGS` to the unexpanded value ``$(includes) -O -pg'`. Thus we preserve the reference to `includes`, so if that variable gets defined at any later point, a reference like ``$(CFLAGS)'` still uses its value.

## 6.7 The `override` Directive

If a variable has been set with a command argument (see section 9.5 Overriding Variables), then ordinary assignments in the makefile are ignored. If you want to set the variable in the makefile even though it was set with a command argument, you can use an `override` directive, which is a line that looks like this:

    override variable = value

or

    override variable := value

To append more text to a variable defined on the command line, use:

    override variable += more text

See section 6.6 Appending More Text to Variables.

The `override` directive was not invented for escalation in the war between makefiles and command arguments. It was invented so you can alter and add to values that the user specifies with command arguments.

For example, suppose you always want the ``-g'` switch when you run the C compiler, but you would like to allow the user to specify the other switches with a command argument just as usual. You could use this `override` directive:

    override CFLAGS += -g

You can also use `override` directives with `define` directives. This is done as you might expect:

    override define foo
    bar
    endef

See the next section for information about `define`.

## 6.8 Defining Variables Verbatim

Another way to set the value of a variable is to use the `define` directive. This directive has an unusual syntax which allows newline characters to be included in the value, which is convenient for defining canned sequences of commands (see section 5.7 Defining Canned Command Sequences).

The `define` directive is followed on the same line by the name of the variable and nothing more. The value to give the variable appears on the following lines. The end of the value is marked by a line containing just the word `endef`. Aside from this difference in syntax, `define` works just like ``='`: it creates a recursively-expanded variable (see section 6.2 The Two Flavors of Variables). The variable name may contain function and variable references, which are expanded when the directive is read to find the actual variable name to use.

    define two-lines
    echo foo
    echo $(bar)
    endef

The value in an ordinary assignment cannot contain a newline; but the newlines that separate the lines of the value in a `define` become part of the variable's value (except for the final newline which precedes the `endef` and is not considered part of the value).

The previous example is functionally equivalent to this:

    two-lines = echo foo; echo $(bar)

since two commands separated by semicolon behave much like two separate shell commands. However, note that using two separate lines means `make` will invoke the shell twice, running an independent subshell for each line. See section 5.2 Command Execution.

If you want variable definitions made with `define` to take precedence over command-line variable definitions, you can use the `override` directive together with `define`:

    override define two-lines
    foo
    $(bar)
    endef

See section 6.7 The `override` Directive.

## 6.9 Variables from the Environment

Variables in `make` can come from the environment in which `make` is run. Every environment variable that `make` sees when it starts up is transformed into a `make` variable with the same name and value. But an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ``-e'` flag is specified, then values from the environment override assignments in the makefile. See section 9.7 Summary of Options. But this is not recommended practice.)

Thus, by setting the variable `CFLAGS` in your environment, you can cause all C compilations in most makefiles to use the compiler switches you prefer. This is safe for variables with standard or conventional meanings because you know that no makefile will use them for other things. (But this is not totally reliable; some makefiles set `CFLAGS` explicitly and therefore are not affected by the value in the environment.)

When `make` is invoked recursively, variables defined in the outer invocation can be passed to inner invocations through the environment (see section 5.6 Recursive Use of `make`). By default, only variables that came from the environment or the command line are passed to recursive invocations. You can use the `export` directive to pass other variables. See section 5.6.2 Communicating Variables to a Sub-`make`, for full details.

Other use of variables from the environment is not recommended. It is not wise for makefiles to depend for their functioning on environment variables set up outside their control, since this would cause different users to get different results from the same makefile. This is against the whole purpose of most makefiles.

Such problems would be especially likely with the variable `SHELL`, which is normally present in the environment to specify the user's choice of interactive shell. It would be very undesirable for this choice to affect `make`. So `make` ignores the environment value of `SHELL` (except on MS-DOS and MS-Windows, where `SHELL` is usually not set. See section 5.2 Command Execution.)

## 6.10 Target-specific Variable Values

Variable values in `make` are usually global; that is, they are the same regardless of where they are evaluated (unless they're reset, of course). One exception to that is automatic variables (see section 10.5.3 Automatic Variables).

The other exception is target-specific variable values. This feature allows you to define different values for the same variable, based on the target that `make` is currently building. As with automatic variables, these values are only available within the context of a target's command script (and in other target-specific assignments).

Set a target-specific variable value like this:

    target ... : variable-assignment

or like this:

    target ... : override variable-assignment

Multiple target values create a target-specific variable value for each member of the target list individually.

The variable-assignment can be any valid form of assignment; recursive (``='`), static (``:='`), appending (``+='`), or conditional (``?='`). All variables that appear within the variable-assignment are evaluated within the context of the target: thus, any previously-defined target-specific variable values will be in effect. Note that this variable is actually distinct from any "global" value: the two variables do not have to have the same flavor (recursive vs. static).

Target-specific variables have the same priority as any other makefile variable. Variables provided on the command-line (and in the environment if the ``-e'` option is in force) will take precedence. Specifying the `override` directive will allow the target-specific variable value to be preferred.

There is one more special feature of target-specific variables: when you define a target-specific variable, that variable value is also in effect for all dependencies of this target (unless those dependencies override it with their own target-specific variable value). So, for example, a statement like this:

    prog : CFLAGS = -g
    prog : prog.o foo.o bar.o

will set `CFLAGS` to ``-g'` in the command script for ``prog'`, but it will also set `CFLAGS` to ``-g'` in the command scripts that create ``prog.o'`, ``foo.o'`, and ``bar.o'`, and any command scripts which create their dependencies.

## 6.11 Pattern-specific Variable Values

In addition to target-specific variable values (see section 6.10 Target-specific Variable Values), GNU `make` supports pattern-specific variable values. In this form, a variable is defined for any target that matches the pattern specified. Variables defined in this way are searched after any target-specific variables defined explicitly for that target, and before target-specific variables defined for the parent target.

Set a pattern-specific variable value like this:

    pattern ... : variable-assignment

or like this:

    pattern ... : override variable-assignment

where pattern is a %-pattern. As with target-specific variable values, multiple pattern values create a pattern-specific variable value for each pattern individually. The variable-assignment can be any valid form of assignment. Any command-line variable setting will take precedence, unless `override` is specified.

For example:

    %.o : CFLAGS = -O

will assign `CFLAGS` the value of ``-O'` for all targets matching the pattern `%.o`.

Go to the first, previous, next, last section, table of contents.