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, prerequisites, recipes, 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 in recipes, 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 whitespace. However, variable names containing characters other than letters, numbers, and underscores should be considered carefully, as in some shells they cannot be passed through the environment to a sub-make (see Communicating Variables to a Sub-make). Variable names beginning with ‘.’ and an uppercase letter may be given special meaning in future versions of 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 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 Automatic Variables.
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 recipe.
Variable references can be used in any context: targets, prerequisites, recipes, 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 can lead to confusion (e.g., $foo
refers to the variable f
followed by the string oo
) so we recommend using parentheses or braces around all variables, even single-letter variables, unless omitting them gives significant readability improvements.
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.
2.1 Recursively Expanded Variable Assignment
The first flavor of variable is a recursively expanded variable. Variables of this sort are defined by lines using =
(see Setting Variables) or by the define
directive (see Defining Multi-Line Variables). 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 most other versions of make
. It has its advantages and its disadvantages. An advantage is that:
CFLAGS = $(include_dirs) -O
include_dirs = -Ifoo -Ibar
will do what was intended: when CFLAGS
is expanded in a recipe, 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 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.
2.2 Simply Expanded Variable Assignment
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 :=
or ::=
(see Setting Variables). Both forms are equivalent in GNU make
; however only the ::=
form is described by the POSIX standard.
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
Here is a somewhat more complicated example, illustrating the use of :=
in conjunction with the shell
function. (See 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 Communicating Variables to a Sub-make, for information about MAKELEVEL.)
ifeq (0,${MAKELEVEL})
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’ recipe then looks like this:
${subdirs}:
${MAKE} -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 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!)
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 ‘:=’ or ‘::=’ are simply expanded variables; these definitions can contain variable references which will be expanded before the definition is made. See 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 memory on the computer. You can split the value of a variable into multiple physical lines for readability (see Splitting Long Lines).
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 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 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 The origin Function):
FOO ?= bar
and
ifeq ($(origin FOO), undefined)
FOO = bar
endif
The shell assignment operator ‘!=’ can be used to execute a shell script and set a variable to its output. This operator first evaluates the right-hand side, then passes that result to the shell for execution. If the result of the execution ends in a newline, that one newline is removed; all other newlines are replaced by spaces. The resulting string is then placed into the named recursively-expanded variable. For example:
hash != printf '\043'
file_list != find . -name '*.c'
If the result of the execution could produce a $, and you don’t intend what follows that to be interpreted as a make variable or function reference, then you must replace every $ with $$ as part of the execution. Alternatively, you can set a simply expanded variable to the result of running a program using the shell function call. See The shell Function. For example:
hash := $(shell printf '\043')
var := $(shell find . -name "*.c")
As with the shell function, the exit status of the just-invoked shell script is stored in the .SHELLSTATUS variable.
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, if it has a value already). 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 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 ‘:=’ or ‘::=’, 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 Setting Variables, for a full explanation of ‘:=’ or ‘::=’). In fact,