Next: Appending More Text to Variables , Previous: How Variables Get Their Values , Up: How to Use Variables [ Contents ][ Index ]

6.5 Setting Variables
To set a variable from the makefile, write a line starting with the variable name followed by one of the assignment operators ‘ = ’, ‘ := ’, ‘ ::= ’, or ‘ :::= ’. Whatever follows the operator and any initial whitespace on the line becomes the value. For example,
defines a variable named objects to contain the value ‘ main.o foo.o bar.o utils.o ’. 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. Variables defined with ‘ :::= ’ are immediately expanded variables. The different assignment operators are described in 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 ):
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:
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:
As with the shell function, the exit status of the just-invoked shell script is stored in the .SHELLSTATUS variable.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?
Can anybody give a clear explanation of how variable assignment really works in Makefiles.
What is the difference between :
I have read the section in GNU Make's manual, but it still doesn't make sense to me.

6 Answers 6
Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared
Immediate Set
Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.
Lazy Set If Absent
Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to
See the documentation for more details.
Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

- 30 Does A += B expand B? That is if if I do A += B, and then B += C, would A evaluate to concatenation of ${B} and ${C}? – Anton Daneyko Feb 1, 2013 at 12:46
- 24 As the linked section of the manual says. += operates according to whatever simple or recursive semantics the original assignment had. So yes, it will expand the RHS but whether it does that immediately or in a deferred manner depends on the type of the variable on the LHS. – Etan Reisner Mar 3, 2013 at 21:02
- 7 What do you mean when you say variable value is expanded? – Sashko Lykhenko Feb 20, 2015 at 21:45
- 4 @СашкоЛихенко have a look here to get meaning of expansion gnu.org/software/make/manual/make.html#Flavors – Umair R Feb 25, 2015 at 9:12
- 7 is "set if absent" lazy or immediate? can i "lazy set if absent" and "immediate set if abset"? – Woodrow Barlow Apr 1, 2016 at 14:55
Using = causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:
Using := is similar to using = . However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:
Using ?= assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value ( VAR= ), it is still considered set I think . Otherwise, functions exactly like = .
Using += is like using = , but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with := , it is expanded I think . The resulting value is expanded when it is used I think . For example:
If something like HELLO_WORLD = $(HELLO_WORLD) world! were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B) were used, the result would not be the exact same as using += because B is expanded with := whereas += would not cause B to be expanded.

- 7 a consequence of that is therefore VARIABLE = literal and VARIABLE := literal are always equivalent. Did I get that right? – aiao May 3, 2014 at 21:43
- 4 @aiao, yes as literals are invariant to their uses – Sebastian May 15, 2014 at 18:01
- A subtle difference is:- ?: can improve performance in recursive called makefiles. For e.g if $? = $(shell some_command_that_runs_long_time). In recursive calls this will be evaluated only once. causing gains in build performance. := will be slower since the command is needlessly running multiple times – KeshV Sep 17, 2017 at 2:33
I suggest you do some experiments using "make". Here is a simple demo, showing the difference between = and := .
make test prints:
Check more elaborate explanation here
- 5 It would be better to use a @ in front each recipe to avoid this confusing repetition of results. – Alexandro de Oliveira Jun 21, 2017 at 22:41
- 4 Make does not support /* ... */ block comment – yoonghm Aug 12, 2019 at 4:13
When you use VARIABLE = value , if value is actually a reference to another variable, then the value is only determined when VARIABLE is used. This is best illustrated with an example:
When you use VARIABLE := value , you get the value of value as it is now . For example:
Using VARIABLE ?= val means that you only set the value of VARIABLE if VARIABLE is not set already. If it's not set already, the setting of the value is deferred until VARIABLE is used (as in example 1).
VARIABLE += value just appends value to VARIABLE . The actual value of value is determined as it was when it was initially set, using either = or := .
- Actually, in your first example, VARIABLE is $(VAL) and VAL is bar. VARIABLE expanded when it is used. – strager Jan 15, 2009 at 23:27
- 1 Yes, the comments are explaining what would happen when they are used. – mipadi Jan 15, 2009 at 23:28
- Ah; I guess you corrected it, or I misread "evaluate" as "be." – strager Jan 15, 2009 at 23:35
In the above answers, it is important to understand what is meant by "values are expanded at declaration/use time". Giving a value like *.c does not entail any expansion. It is only when this string is used by a command that it will maybe trigger some globbing. Similarly, a value like $(wildcard *.c) or $(shell ls *.c) does not entail any expansion and is completely evaluated at definition time even if we used := in the variable definition.
Try the following Makefile in directory where you have some C files:
Running make will trigger a rule that creates an extra (empty) C file, called foo.c but none of the 6 variables has foo.c in its value.
- This is a great call and has plenty of examples for expansion at declaration time, it'd be useful to extend the answer with an example and some words for expansion at use time – Robert Monfera Aug 5, 2019 at 6:44
The most upvoted answer can be improved.
Let me refer to GNU Make manual "Setting variables" and "Flavors" , and add some comments.
Recursively expanded 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 .
The catch : foo will be expanded to the value of $(bar) each time foo is evaluated, possibly resulting in different values. Surely you cannot call it "lazy"! This can surprise you if executed on midnight:
Simply expanded variable
Variables defined with ‘:=’ or ‘::=’ are simply expanded variables.
Simply expanded variables are defined by lines using ‘:=’ or ‘::=’ [...]. Both forms are equivalent in GNU make; however only the ‘::=’ form is described by the POSIX standard [...] 2012.
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.
Not much to add. It's evaluated immediately, including recursive expansion of, well, recursively expanded variables.
The catch : If VARIABLE refers to ANOTHER_VARIABLE :
and ANOTHER_VARIABLE is not defined before this assignment, ANOTHER_VARIABLE will expand to an empty value.
Assign if not set
is equivalent to
where $(origin FOO) equals to undefined only if the variable was not set at all.
The catch : if FOO was set to an empty string, either in makefiles, shell environment, or command line overrides, it will not be assigned bar .
Appending :
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.
So, this will print foo bar :
but this will print foo :
The catch is that += behaves differently depending on what type of variable VAR was assigned before.
Multiline values
The syntax to assign multiline value to a variable is:
Assignment operator can be omitted, then it creates a recursively-expanded variable.
The last newline before endef is removed.
Bonus: the shell assignment operator ‘!=’
is the same as
Don't use it. $(shell) call is more readable, and the usage of both in a makefiles is highly discouraged. At least, $(shell) follows Joel's advice and makes wrong code look obviously wrong .
- Are ?= and = equivalent when defining macros that are intended to be overridden by environment variables, like CFLAGS / CPPFLAGS / LDFLAGS ? – shadowtalker Aug 17, 2021 at 13:55
- 1 @shadowtalker, no. Make variables default to environment variables, but = overrides any existing value. Also note that command-line override variables (that go after make on command line) override every single assignment in Makefile , except for overrides . – Victor Sergienko Aug 17, 2021 at 18:26
- Does this sound correct? = and := override environment variables, environment variables override =? , command-line "override variables" override both, and the override directive overrides all of the above. This interaction with environment variables and command-line override might be a very helpful clarification in your already-very-thorough answer. – shadowtalker Aug 17, 2021 at 18:35
- 1 This is accurate. Thank you. I thought that this is a bit outside of the scope of the question. On the other hand, there is no question "How do Makefile variables get their values?". Maybe it's worth asking the question. – Victor Sergienko Aug 17, 2021 at 18:54
- I took your suggestion: stackoverflow.com/a/68825174/2954547 – shadowtalker Aug 17, 2021 at 23:51
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged makefile gnu-make or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Why is this sentence from The Great Gatsby grammatical?
- Are there tables of wastage rates for different fruit and veg?
- Does Counterspell prevent from any further spells being cast on a given turn?
- My code is GPL licensed, can I issue a license to have my code be distributed in a specific MIT licensed project?
- Butterfly Theorem
- How to handle a hobby that makes income in US
- How to follow the signal when reading the schematic?
- How to match a specific column position till the end of line?
- Has 90% of ice around Antarctica disappeared in less than a decade?
- Bulk update symbol size units from mm to map units in rule-based symbology
- Is there a proper earth ground point in this switch box?
- Is it possible to rotate a window 90 degrees if it has the same length and width?
- Is a PhD visitor considered as a visiting scholar?
- Theoretically Correct vs Practical Notation
- Where does this (supposedly) Gibson quote come from?
- How can this new ban on drag possibly be considered constitutional?
- Acidity of alcohols and basicity of amines
- What is the purpose of this D-shaped ring at the base of the tongue on my hiking boots?
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Mutually exclusive execution using std::atomic?
- If a law is new but its interpretation is vague, can the courts directly ask the drafters the intent and official interpretation of their law?
- Do I need a thermal expansion tank if I already have a pressure tank?
- Is it suspicious or odd to stand by the gate of a GA airport watching the planes?
- Why do academics stay as adjuncts for years rather than move around?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Next: Conditionals , Previous: Recipes , Up: Top [ Contents ][ Index ]
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, 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 .
Next: Flavors , Previous: Using Variables , Up: Using Variables [ Contents ][ Index ]
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 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:
Variable references work by strict textual substitution. Thus, the rule
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. One place where readability is often improved is automatic variables (see Automatic Variables ).
Next: Advanced , Previous: Reference , Up: Using Variables [ Contents ][ Index ]
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 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,
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 (most would say) is that:
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
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.
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 (support for ‘ ::= ’ was added to the POSIX standard in 2012, so older versions of make won’t accept this form either).
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,
is equivalent to
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 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 .)
An advantage of this use of ‘ := ’ is that a typical ‘descend into a directory’ recipe then looks like this:
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:
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:
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:
is exactly equivalent to this (see The origin Function ):
Note that a variable set to an empty value is still defined, so ‘ ?= ’ will not set that variable.
Next: Values , Previous: Flavors , Up: Using Variables [ Contents ][ Index ]
6.3 Advanced Features for Reference to Variables
This section describes some advanced features you can use to reference variables in more flexible ways.
Next: Computed Names , Previous: Advanced , Up: Advanced [ Contents ][ Index ]
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:
sets ‘ bar ’ to ‘ a.c b.c l.a c.c ’. See Setting Variables .
A substitution reference is shorthand for the patsubst expansion function (see Functions for String Substitution and Analysis ): ‘ $( var : a = b ) ’ is equivalent to ‘ $(patsubst % a ,% b , var ) ’. 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 Functions for String Substitution and Analysis , for a description of the patsubst function.
sets ‘ bar ’ to ‘ a.c b.c l.a c.c ’.
Previous: Substitution Refs , Up: Advanced [ Contents ][ Index ]
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,
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:
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 re-expanded in the usual fashion. For example:
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 Functions for Transforming Text ), just like any other reference. For example, using the subst function (see Functions for String Substitution and Analysis ):
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,
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:
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,
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:
This example defines the variables ‘ dir ’, ‘ foo_sources ’, and ‘ foo_print ’.
Note that nested variable references are quite different from recursively expanded variables (see The Two Flavors of Variables ), though both are used together in complex ways when doing makefile programming.
Next: Setting , Previous: Advanced , Up: Using Variables [ Contents ][ Index ]
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 Overriding Variables .
- You can specify a value in the makefile, either with an assignment (see Setting Variables ) or with a verbatim definition (see Defining Multi-Line Variables ).
- Variables in the environment become make variables. See Variables from the Environment .
- Several automatic variables are given new values for each rule. Each of these has a single conventional use. See Automatic Variables .
- Several variables have constant initial values. See Variables Used by Implicit Rules .
Next: Appending , Previous: Values , Up: Using Variables [ Contents ][ Index ]
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,
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 ):
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:
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:
As with the shell function, the exit status of the just-invoked shell script is stored in the .SHELLSTATUS variable.
Next: Override Directive , Previous: Setting , Up: Using Variables [ Contents ][ Index ]
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:
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:
sets objects to ‘ main.o foo.o bar.o utils.o another.o ’.
Using ‘ += ’ is similar to:
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,
is exactly equivalent to:
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 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.
is roughly equivalent to:
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:
The first line defines the CFLAGS variable with a reference to another variable, includes . ( CFLAGS is used by the rules for C compilation; see Catalogue of Built-In 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:
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.
Next: Multi-Line , Previous: Appending , Up: Using Variables [ Contents ][ Index ]
6.7 The override Directive
If a variable has been set with a command argument (see 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:
To append more text to a variable defined on the command line, use:
See Appending More Text to Variables .
Variable assignments marked with the override flag have a higher priority than all other assignments, except another override . Subsequent assignments or appends to this variable which are not marked override will be ignored.
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:
You can also use override directives with define directives. This is done as you might expect:
See Defining Multi-Line Variables .
Next: Undefine Directive , Previous: Override Directive , Up: Using Variables [ Contents ][ Index ]
6.8 Defining Multi-Line Variables
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 both canned sequences of commands (see Defining Canned Recipes ), and also sections of makefile syntax to use with eval (see Eval Function ).
The define directive is followed on the same line by the name of the variable being defined and an (optional) assignment operator, 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 any other variable definition. 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.
The final newline before the endef is not included in the value; if you want your value to contain a trailing newline you must include a blank line. For example in order to define a variable that contains a newline character you must use two empty lines, not one:
You may omit the variable assignment operator if you prefer. If omitted, make assumes it to be ‘ = ’ and creates a recursively-expanded variable (see The Two Flavors of Variables ). When using a ‘ += ’ operator, the value is appended to the previous value as with any other append operation: with a single space separating the old and new values.
You may nest define directives: make will keep track of nested directives and report an error if they are not all properly closed with endef . Note that lines beginning with the recipe prefix character are considered part of a recipe, so any define or endef strings appearing on such a line will not be considered make directives.
When used in a recipe, the previous example is functionally equivalent to this:
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 sub-shell for each line. See Recipe 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 :
See The override Directive .
Next: Environment , Previous: Multi-Line , Up: Using Variables [ Contents ][ Index ]
6.9 Undefining Variables
If you want to clear a variable, setting its value to empty is usually sufficient. Expanding such a variable will yield the same result (empty string) regardless of whether it was set or not. However, if you are using the flavor (see Flavor Function ) and origin (see Origin Function ) functions, there is a difference between a variable that was never set and a variable with an empty value. In such situations you may want to use the undefine directive to make a variable appear as if it was never set. For example:
This example will print “undefined” for both variables.
If you want to undefine a command-line variable definition, you can use the override directive together with undefine , similar to how this is done for variable definitions:
Next: Target-specific , Previous: Undefine Directive , Up: Using Variables [ Contents ][ Index ]
6.10 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. However, 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 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. (Note this is not totally reliable; some makefiles set CFLAGS explicitly and therefore are not affected by the value in the environment.)
When make runs a recipe, variables defined in the makefile are placed into the environment of each shell. This allows you to pass values to sub- make invocations (see 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 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 handles the SHELL environment variable in a special way; see Choosing the Shell .
Next: Pattern-specific , Previous: Environment , Up: Using Variables [ Contents ][ Index ]
6.11 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 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 recipe (and in other target-specific assignments).
Set a target-specific variable value like this:
Target-specific variable assignments can be prefixed with any or all of the special keywords export , override , or private ; these apply their normal behavior to this instance of the variable only.
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 (‘ = ’), simple (‘ := ’ or ‘ ::= ’), 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. simple).
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 prerequisites of this target, and all their prerequisites, etc. (unless those prerequisites override that variable with their own target-specific variable value). So, for example, a statement like this:
will set CFLAGS to ‘ -g ’ in the recipe for prog , but it will also set CFLAGS to ‘ -g ’ in the recipes that create prog.o , foo.o , and bar.o , and any recipes which create their prerequisites.
Be aware that a given prerequisite will only be built once per invocation of make, at most. If the same file is a prerequisite of multiple targets, and each of those targets has a different value for the same target-specific variable, then the first target to be built will cause that prerequisite to be built and the prerequisite will inherit the target-specific value from the first target. It will ignore the target-specific values from any other targets.
Next: Suppressing Inheritance , Previous: Target-specific , Up: Using Variables [ Contents ][ Index ]
6.12 Pattern-specific Variable Values
In addition to target-specific variable values (see Target-specific Variable Values ), GNU make supports pattern-specific variable values. In this form, the variable is defined for any target that matches the pattern specified.
Set a pattern-specific variable value like this:
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:
will assign CFLAGS the value of ‘ -O ’ for all targets matching the pattern %.o .
If a target matches more than one pattern, the matching pattern-specific variables with longer stems are interpreted first. This results in more specific variables taking precedence over the more generic ones, for example:
In this example the first definition of the CFLAGS variable will be used to update lib/bar.o even though the second one also applies to this target. Pattern-specific variables which result in the same stem length are considered in the order in which they were defined in the makefile.
Pattern-specific variables are searched after any target-specific variables defined explicitly for that target, and before target-specific variables defined for the parent target.
Next: Special Variables , Previous: Pattern-specific , Up: Using Variables [ Contents ][ Index ]
6.13 Suppressing Inheritance
As described in previous sections, make variables are inherited by prerequisites. This capability allows you to modify the behavior of a prerequisite based on which targets caused it to be rebuilt. For example, you might set a target-specific variable on a debug target, then running ‘ make debug ’ will cause that variable to be inherited by all prerequisites of debug , while just running ‘ make all ’ (for example) would not have that assignment.
Sometimes, however, you may not want a variable to be inherited. For these situations, make provides the private modifier. Although this modifier can be used with any variable assignment, it makes the most sense with target- and pattern-specific variables. Any variable marked private will be visible to its local target but will not be inherited by prerequisites of that target. A global variable marked private will be visible in the global scope but will not be inherited by any target, and hence will not be visible in any recipe.
As an example, consider this makefile:
Due to the private modifier, a.o and b.o will not inherit the EXTRA_CFLAGS variable assignment from the prog target.
Previous: Suppressing Inheritance , Up: Using Variables [ Contents ][ Index ]

6.14 Other Special Variables
GNU make supports some variables that have special properties.
Contains the name of each makefile that is parsed by make , in the order in which it was parsed. The name is appended just before make begins to parse the makefile. Thus, if the first thing a makefile does is examine the last word in this variable, it will be the name of the current makefile. Once the current makefile has used include , however, the last word will be the just-included makefile.
If a makefile named Makefile has this content:
then you would expect to see this output:
Sets the default goal to be used if no targets were specified on the command line (see Arguments to Specify the Goals ). The .DEFAULT_GOAL variable allows you to discover the current default goal, restart the default goal selection algorithm by clearing its value, or to explicitly set the default goal. The following example illustrates these cases:
This makefile prints:
Note that assigning more than one target name to .DEFAULT_GOAL is invalid and will result in an error.
This variable is set only if this instance of make has restarted (see How Makefiles Are Remade ): it will contain the number of times this instance has restarted. Note this is not the same as recursion (counted by the MAKELEVEL variable). You should not set, modify, or export this variable.
When make starts it will check whether stdout and stderr will show their output on a terminal. If so, it will set MAKE_TERMOUT and MAKE_TERMERR , respectively, to the name of the terminal device (or true if this cannot be determined). If set these variables will be marked for export. These variables will not be changed by make and they will not be modified if already set.
These values can be used (particularly in combination with output synchronization (see Output During Parallel Execution ) to determine whether make itself is writing to a terminal; they can be tested to decide whether to force recipe commands to generate colorized output for example.
If you invoke a sub- make and redirect its stdout or stderr it is your responsibility to reset or unexport these variables as well, if your makefiles rely on them.
The first character of the value of this variable is used as the character make assumes is introducing a recipe line. If the variable is empty (as it is by default) that character is the standard tab character. For example, this is a valid makefile:
The value of .RECIPEPREFIX can be changed multiple times; once set it stays in effect for all rules parsed until it is modified.
Expands to a list of the names of all global variables defined so far. This includes variables which have empty values, as well as built-in variables (see Variables Used by Implicit Rules ), but does not include any variables which are only defined in a target-specific context. Note that any value you assign to this variable will be ignored; it will always return its special value.
Expands to a list of special features supported by this version of make . Possible values include, but are not limited to:
Supports ar (archive) files using special file name syntax. See Using make to Update Archive Files .
Supports the -L ( --check-symlink-times ) flag. See Summary of Options .
Supports “else if” non-nested conditionals. See Syntax of Conditionals .
Supports “job server” enhanced parallel builds. See Parallel Execution .
Supports the .ONESHELL special target. See Using One Shell .
Supports order-only prerequisites. See Types of Prerequisites .
Supports secondary expansion of prerequisite lists.
Uses the “shortest stem” method of choosing which pattern, of multiple applicable options, will be used. See How Patterns Match .
Supports target-specific and pattern-specific variable assignments. See Target-specific Variable Values .
Supports the undefine directive. See Undefine Directive .
Has GNU Guile available as an embedded extension language. See GNU Guile Integration .
Supports dynamically loadable objects for creating custom extensions. See Loading Dynamic Objects .
Expands to a list of directories that make searches for included makefiles (see Including Other Makefiles ).
Each word in this variable is a new prerequisite which is added to targets for which it is set. These prerequisites differ from normal prerequisites in that they do not appear in any of the automatic variables (see Automatic Variables ). This allows prerequisites to be defined which do not impact the recipe.
Consider a rule to link a program:
Now suppose you want to enhance this makefile to ensure that updates to the compiler cause the program to be re-linked. You can add the compiler as a prerequisite, but you must ensure that it’s not passed as an argument to link command. You’ll need something like this:
Then consider having multiple extra prerequisites: they would all have to be filtered out. Using .EXTRA_PREREQS and target-specific variables provides a simpler solution:
This feature can also be useful if you want to add prerequisites to a makefile you cannot easily modify: you can create a new file such as extra.mk :
then invoke make -f extra.mk -f Makefile .
Setting .EXTRA_PREREQS globally will cause those prerequisites to be added to all targets (which did not themselves override it with a target-specific value). Note make is smart enough not to add a prerequisite listed in .EXTRA_PREREQS as a prerequisite to itself.
Managing Projects with GNU Make, 3rd Edition by Robert Mecklenburg
Get full access to Managing Projects with GNU Make, 3rd Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.
There are also live events, courses curated by job role, and more.
Chapter 3. Variables and Macros
We’ve been looking at makefile variables for a while now and we’ve seen many examples of how they’re used in both the built-in and user-defined rules. But the examples we’ve seen have only scratched the surface. Variables and macros get much more complicated and give GNU make much of its incredible power.
Before we go any further, it is important to understand that make is sort of two languages in one. The first language describes dependency graphs consisting of targets and prerequisites. (This language was covered in Chapter 2 .) The second language is a macro language for performing textual substitution. Other macro languages you may be familiar with are the C preprocessor, m4 , TEX, and macro assemblers. Like these other macro languages, make allows you to define a shorthand term for a longer sequence of characters and use the shorthand in your program. The macro processor will recognize your shorthand terms and replace them with their expanded form. Although it is easy to think of makefile variables as traditional programming language variables, there is a distinction between a macro “variable” and a “traditional” variable. A macro variable is expanded “in place” to yield a text string that may then be expanded further. This distinction will become more clear as we proceed.
A variable name can contain almost any characters including most punctuation. Even spaces are allowed, but if you value your sanity you should avoid them. The only characters actually disallowed in a variable name are :, #, and =.
Variables are case-sensitive, so cc and CC refer to different variables. To get the value of a variable, enclose the variable name in $( ) . As a special case, single-letter variable names can omit the parentheses and simply use $ letter . This is why the automatic variables can be written without the parentheses. As a general rule you should use the parenthetical form and avoid single letter variable names.
Variables can also be expanded using curly braces as in ${CC} and you will often see this form, particularly in older makefile s. There is seldom an advantage to using one over the other, so just pick one and stick with it. Some people use curly braces for variable reference and parentheses for function call, similar to the way the shell uses them. Most modern makefile s use parentheses and that’s what we’ll use throughout this book.
Variables representing constants a user might want to customize on the command line or in the environment are written in all uppercase, by convention. Words are separated by underscores. Variables that appear only in the makefile are all lowercase with words separated by underscores. Finally, in this book, user-defined functions in variables and macros use lowercase words separated by dashes. Other naming conventions will be explained where they occur. (The following example uses features we haven’t discussed yet. I’m using them to illustrate the variable naming conventions, don’t be too concerned about the righthand side for now.)
The value of a variable consists of all the words to the right of the assignment symbol with leading space trimmed. Trailing spaces are not trimmed. This can occasionally cause trouble, for instance, if the trailing whitespace is included in the variable and subsequently used in a command script:
The variable assignment contains a trailing space that is made more apparent by the comment (but a trailing space can also be present without a trailing comment). When this makefile is run, we get:
Oops, the grep search string also included the trailing space and failed to find the file in ls ’s output. We’ll discuss whitespace issues in more detail later. For now, let’s look more closely at variables.
What Variables Are Used For
In general it is a good idea to use variables to represent external programs. This allows users of the makefile to more easily adapt the makefile to their specific environment. For instance, there are often several versions of awk on a system: awk , nawk , gawk . By creating a variable, AWK , to hold the name of the awk program you make it easier for other users of your makefile . Also, if security is an issue in your environment, a good practice is to access external programs with absolute paths to avoid problems with user’s paths. Absolute paths also reduce the likelihood of issues if trojan horse versions of system programs have been installed somewhere in a user’s path. Of course, absolute paths also make makefile s less portable to other systems. Your own requirements should guide your choice.
Though your first use of variables should be to hold simple constants, they can also store user-defined command sequences such as: [ 4 ]
for reporting on free disk space. Variables are used for both these purposes and more, as we will see.
Variable Types
There are two types of variables in make : simply expanded variables and recursively expanded variables. A simply expanded variable (or a simple variable) is defined using the := assignment operator:
It is called “simply expanded” because its righthand side is expanded immediately upon reading the line from the makefile . Any make variable references in the right-hand side are expanded and the resulting text saved as the value of the variable. This behavior is identical to most programming and scripting languages. For instance, the normal expansion of this variable would yield:
However, if CC above had not yet been set, then the value of the above assignment would be:
$(CC) is expanded to its value (which contains no characters), and collapses to nothing. It is not an error for a variable to have no definition. In fact, this is extremely useful. Most of the implicit commands include undefined variables that serve as place holders for user customizations. If the user does not customize a variable it collapses to nothing. Now notice the leading space. The righthand side is first parsed by make to yield the string $(CC) -M . When the variable reference is collapsed to nothing, make does not rescan the value and trim blanks. The blanks are left intact.
The second type of variable is called a recursively expanded variable. A recursively expanded variable (or a recursive variable) is defined using the = assignment operator:
It is called “recursively expanded” because its righthand side is simply slurped up by make and stored as the value of the variable without evaluating or expanding it in any way. Instead, the expansion is performed when the variable is used . A better term for this variable might be lazily expanded variable, since the evaluation is deferred until it is actually used. One surprising effect of this style of expansion is that assignments can be performed “out of order”:
Here the value of MAKE_DEPEND within a command script is gcc -M even though CC was undefined when MAKE_DEPEND was assigned.
In fact, recursive variables aren’t really just a lazy assignment (at least not a normal lazy assignment). Each time the recursive variable is used, its righthand side is reevaluated. For variables that are defined in terms of simple constants such as MAKE_ DEPEND above, this distinction is pointless since all the variables on the righthand side are also simple constants. But imagine if a variable in the righthand side represented the execution of a program, say date . Each time the recursive variable was expanded the date program would be executed and each variable expansion would have a different value (assuming they were executed at least one second apart). At times this is very useful. At other times it is very annoying!
Other Types of Assignment
From previous examples we’ve seen two types of assignment: = for creating recursive variables and := for creating simple variables. There are two other assignment operators provided by make .
The ?= operator is called the conditional variable assignment operator . That’s quite a mouth-full so we’ll just call it conditional assignment. This operator will perform the requested variable assignment only if the variable does not yet have a value.
Here we set the output directory variable, OUTPUT_DIR , only if it hasn’t been set earlier. This feature interacts nicely with environment variables. We’ll discuss this in the section Where Variables Come From later in this chapter.
The other assignment operator, += , is usually referred to as append . As its name suggests, this operator appends text to a variable. This may seem unremarkable, but it is an important feature when recursive variables are used. Specifically, values on the righthand side of the assignment are appended to the variable without changing the original values in the variable . “Big deal, isn’t that what append always does?” I hear you say. Yes, but hold on, this is a little tricky.
Appending to a simple variable is pretty obvious. The += operator might be implemented like this:
Since the value in the simple variable has already undergone expansion, make can expand $(simple) , append the text, and finish the assignment. But recursive variables pose a problem. An implementation like the following isn’t allowed.
This is an error because there’s no good way for make to handle it. If make stores the current definition of recursive plus new stuff , make can’t expand it again at runtime. Furthermore, attempting to expand a recursive variable containing a reference to itself yields an infinite loop.
So, += was implemented specifically to allow adding text to a recursive variable and does the Right Thing™. This operator is particularly useful for collecting values into a variable incrementally.
Variables are fine for storing values as a single line of text, but what if we have a multiline value such as a command script we would like to execute in several places? For instance, the following sequence of commands might be used to create a Java archive (or jar ) from Java class files:
At the beginning of long sequences such as this, I like to print a brief message. It can make reading make ’s output much easier. After the message, we collect our class files into a clean temporary directory. So we delete the temporary jar directory in case an old one is left lying about, [ 5 ] then we create a fresh temporary directory. Next we copy our prerequisite files (and all their subdirectories) into the temporary directory. Then we switch to our temporary directory and create the jar with the target filename. We add the manifest file to the jar and finally clean up. Clearly, we do not want to duplicate this sequence of commands in our makefile since that would be a maintenance problem in the future. We might consider packing all these commands into a recursive variable, but that is ugly to maintain and difficult to read when make echoes the command line (the whole sequence is echoed as one enormous line of text).
Instead, we can use a GNU make “canned sequence” as created by the define directive. The term “canned sequence” is a bit awkward, so we’ll call this a macro . A macro is just another way of defining a variable in make , and one that can contain embedded newlines! The GNU make manual seems to use the words variable and macro interchangeably. In this book, we’ll use the word macro specifically to mean variables defined using the define directive and variable only when assignment is used.
The define directive is followed by the macro name and a newline. The body of the macro includes all the text up to the endef keyword, which must appear on a line by itself. A macro created with define is expanded pretty much like any other variable, except that when it is used in the context of a command script, each line of the macro has a tab prepended to the line. An example use is:
Notice we’ve added an @ character in front of our echo command. Command lines prefixed with an @ character are not echoed by make when the command is executed. When we run make , therefore, it doesn’t print the echo command, just the output of that command. If the @ prefix is used within a macro, the prefix character applies to the individual lines on which it is used. However, if the prefix character is used on the macro reference, the entire macro body is hidden:
This displays only:
The use of @ is covered in more detail in the section Command Modifiers in Chapter 5 .
When Variables Are Expanded
In the previous sections, we began to get a taste of some of the subtleties of variable expansion. Results depend a lot on what was previously defined, and where. You could easily get results you don’t want, even if make fails to find any error. So what are the rules for expanding variables? How does this really work?
When make runs, it performs its job in two phases. In the first phase, make reads the makefile and any included makefile s. At this time, variables and rules are loaded into make ’s internal database and the dependency graph is created. In the second phase, make analyzes the dependency graph and determines the targets that need to be updated, then executes command scripts to perform the required updates.
When a recursive variable or define directive is processed by make , the lines in the variable or body of the macro are stored, including the newlines without being expanded. The very last newline of a macro definition is not stored as part of the macro. Otherwise, when the macro was expanded an extra newline would be read by make .
When a macro is expanded, the expanded text is then immediately scanned for further macro or variable references and those are expanded and so on, recursively. If the macro is expanded in the context of an action, each line of the macro is inserted with a leading tab character.
To summarize, here are the rules for when elements of a makefile are expanded:
For variable assignments, the lefthand side of the assignment is always expanded immediately when make reads the line during its first phase.
The righthand side of = and ?= are deferred until they are used in the second phase.
The righthand side of := is expanded immediately.
The righthand side of += is expanded immediately if the lefthand side was originally defined as a simple variable. Otherwise, its evaluation is deferred.
For macro definitions (those using define ), the macro variable name is immediately expanded and the body of the macro is deferred until used.
For rules, the targets and prerequisites are always immediately expanded while the commands are always deferred.
Table 3-1 summarizes what occurs when variables are expanded.
As a general rule, always define variables and macros before they are used. In particular, it is required that a variable used in a target or prerequisite be defined before its use.
An example will make all this clearer. Suppose we reimplement our free-space macro. We’ll go over the example a piece at a time, then put them all together at the end.
We define three variables to hold the names of the programs we use in our macro. To avoid code duplication we factor out the bin directory into a fourth variable. The four variable definitions are read and their righthand sides are immediately expanded because they are simple variables. Because BIN is defined before the others, its value can be plugged into their values.
Next, we define the free-space macro.
The define directive is followed by a variable name that is immediately expanded. In this case, no expansion is necessary. The body of the macro is read and stored unexpanded.
Finally, we use our macro in a rule.
When $(OUTPUT_DIR)/very_big_file is read, any variables used in the targets and prerequisites are immediately expanded. Here, $(OUTPUT_DIR) is expanded to /tmp to form the /tmp/very_big_file target. Next, the command script for this target is read. Command lines are recognized by the leading tab character and are read and stored, but not expanded.
Here is the entire example makefile . The order of elements in the file has been scrambled intentionally to illustrate make ’s evaluation algorithm.
Notice that although the order of lines in the makefile seems backward, it executes just fine. This is one of the surprising effects of recursive variables. It can be immensely useful and confusing at the same time. The reason this makefile works is that expansion of the command script and the body of the macro are deferred until they are actually used. Therefore, the relative order in which they occur is immaterial to the execution of the makefile .
In the second phase of processing, after the makefile is read, make identifies the targets, performs dependency analysis, and executes the actions for each rule. Here the only target, $(OUTPUT_DIR)/very_big_file , has no prerequisites, so make will simply execute the actions (assuming the file doesn’t exist). The command is $(free-space) . So make expands this as if the programmer had written:
Once all variables are expanded, it begins executing commands one at a time.
Let’s look at the two parts of the makefile where the order is important. As explained earlier, the target $(OUTPUT_DIR)/very_big_file is expanded immediately. If the definition of the variable OUTPUT_DIR had followed the rule, the expansion of the target would have yielded /very_big_file . Probably not what the user wanted. Similarly, if the definition of BIN had been moved after AWK , those three variables would have expanded to /printf , /df , and /awk because the use of := causes immediate evaluation of the righthand side of the assignment. However, in this case, we could avoid the problem for PRINTF , DF , and AWK by changing := to = , making them recursive variables. One last detail. Notice that changing the definitions of OUTPUT_DIR and BIN to recursive variables would not change the effect of the previous ordering problems. The important issue is that when $(OUTPUT_DIR)/very_big_file and the righthand sides of PRINTF , DF , and AWK are expanded, their expansion happens immediately, so the variables they refer to must be already defined.
Target- and Pattern-Specific Variables
Variables usually have only one value during the execution of a makefile . This is ensured by the two-phase nature of makefile processing. In phase one, the makefile is read, variables are assigned and expanded, and the dependency graph is built. In phase two, the dependency graph is analyzed and traversed. So when command scripts are being executed, all variable processing has already completed. But suppose we wanted to redefine a variable for just a single rule or pattern.
In this example, the particular file we are compiling needs an extra command-line option, -DUSE_NEW_MALLOC=1 , that should not be provided to other compiles:
Here, we’ve solved the problem by duplicating the compilation command script and adding the new required option. This approach is unsatisfactory in several respects. First, we are duplicating code. If the rule ever changes or if we choose to replace the built-in rule with a custom pattern rule, this code would need to be updated and we might forget. Second, if many files require special treatment, the task of pasting in this code will quickly become very tedious and error-prone (imagine a hundred files like this).
To address this issue and others, make provides target-specific variables . These are variable definitions attached to a target that are valid only during the processing of that target and any of its prerequisites. We can rewrite our previous example using this feature like this:
The variable CPPFLAGS is built in to the default C compilation rule and is meant to contain options for the C preprocessor. By using the += form of assignment, we append our new option to any existing value already present. Now the compile command script can be removed entirely:
While the gui.o target is being processed, the value of CPPFLAGS will contain -DUSE_ NEW_MALLOC=1 in addition to its original contents. When the gui.o target is finished, CPPFLAGS will revert to its original value. Pattern-specific variables are similar, only they are specified in a pattern rule (see Pattern Rules ).
The general syntax for target-specific variables is:
As you can see, all the various forms of assignment are valid for a target-specific variable. The variable does not need to exist before the assignment.
Furthermore, the variable assignment is not actually performed until the processing of the target begins. So the righthand side of the assignment can itself be a value set in another target-specific variable. The variable is valid during the processing of all prerequisites as well.
Where Variables Come From
So far, most variables have been defined explicitly in our own makefile s, but variables can have a more complex ancestry. For instance, we have seen that variables can be defined on the make command line. In fact, make variables can come from these sources:
Of course, variables can be defined in the makefile or a file included by the makefile (we’ll cover the include directive shortly).
Variables can be defined or redefined directly from the make command line:
A command-line argument containing an = is a variable assignment. Each variable assignment on the command line must be a single shell argument. If the value of the variable (or heaven forbid, the variable itself) contains spaces, the argument must be surrounded by quotes or the spaces must be escaped.
An assignment of a variable on the command line overrides any value from the environment and any assignment in the makefile . Command-line assignments can set either simple or recursive variables by using := or = , respectively. It is possible using the override directive to allow a makefile assignment to be used instead of a command-line assignment.
Of course, you should ignore a user’s explicit assignment request only under the most urgent circumstances (unless you just want to irritate your users).
All the variables from your environment are automatically defined as make variables when make starts. These variables have very low precedence, so assignments within the makefile or command-line arguments will override the value of an environment variable. You can cause environment variables to override makefile variables using the --environment-overrides (or -e ) command-line option.
When make is invoked recursively, some variables from the parent make are passed through the environment to the child make . By default, only those variables that originally came from the environment are exported to the child’s environment, but any variable can be exported to the environment by using the export directive:
You can cause all variables to be exported with:
Note that make will export even those variables whose names contain invalid shell variable characters. For example:
An “invalid” shell variable was created by exporting valid-variable-in-make . This variable is not accessible through normal shell syntax, only through trickery such as running grep over the environment. Nevertheless, this variable is inherited by any sub- make where it is valid and accessible. We will cover use of “recursive” make in Part II .
You can also prevent an environment variable from being exported to the subprocess:
The mp_export and mp_unexport directives work the same way the mp_sh commands mp_export and mp_unset work.
The conditional assignment operator interacts very nicely with environment variables. Suppose you have a default output directory set in your makefile , but you want users to be able to override the default easily. Conditional assignment is perfect for this situation:
Here the assignment is performed only if OUTPUT_DIR has never been set. We can get nearly the same effect more verbosely with:
The difference is that the conditional assignment operator will skip the assignment if the variable has been set in any way, even to the empty value, while the ifdef and ifndef operators test for a nonempty value. Thus, OUTPUT_DIR= is considered set by the conditional operator but not defined by ifdef .
It is important to note that excessive use of environment variables makes your makefile s much less portable, since other users are not likely to have the same set of environment variables. In fact, I rarely use this feature for precisely that reason.
Finally, make creates automatic variables immediately before executing the command script of a rule.
Traditionally, environment variables are used to help manage the differences between developer machines. For instance, it is common to create a development environment (source code, compiled output tree, and tools) based on environment variables referenced in the makefile . The makefile would refer to one environment variable for the root of each tree. If the source file tree is referenced from a variable PROJECT_SRC , binary output files from PROJECT_BIN , and libraries from PROJECT_LIB , then developers are free to place these trees wherever is appropriate.
A potential problem with this approach (and with the use of environment variables in general) occurs when these “root” variables are not set. One solution is to provide default values in the makefile using the ?= form of assignment:
By using these variables to access project components, you can create a development environment that is adaptable to varying machine layouts. (We will see more comprehensive examples of this in Part II .) Beware of overreliance on environment variables, however. Generally, a makefile should be able to run with a minimum of support from the developer’s environment so be sure to provide reasonable defaults and check for the existence of critical components.
Conditional and include Processing
Parts of a makefile can be omitted or selected while the makefile is being read using conditional processing directives. The condition that controls the selection can have several forms such as “is defined” or “is equal to.” For example:
This selects the first branch of the conditional if the variable COMSPEC is defined.
The basic syntax of the conditional directive is:
The if-condition can be one of:
The variable-name should not be surrounded by $( ) for the ifdef / ifndef test. Finally, the test can be expressed as either of:
in which single or double quotes can be used interchangeably (but the quotes you use must match).
The conditional processing directives can be used within macro definitions and command scripts as well as at the top level of makefile s:
I like to indent my conditionals, but careless indentation can lead to errors. In the preceding lines, the conditional directives are indented four spaces while the enclosed commands have a leading tab. If the enclosed commands didn’t begin with a tab, they would not be recognized as commands by make . If the conditional directives had a leading tab, they would be misidentified as commands and passed to the subshell.
The ifeq and ifneq conditionals test if their arguments are equal or not equal. Whitespace in conditional processing can be tricky to handle. For instance, when using the parenthesis form of the test, whitespace after the comma is ignored, but all other whitespace is significant:
Personally, I stick with the quoted forms of equality:
Even so, it often occurs that a variable expansion contains unexpected whitespace. This can cause problems since the comparison includes all characters. To create more robust makefile s, use the strip function:
The include Directive
We first saw the include directive in Chapter 2 , in the section Automatic Dependency Generation . Now let’s go over it in more detail.
A makefile can include other files. This is most commonly done to place common make definitions in a make header file or to include automatically generated dependency information. The include directive is used like this:
The directive can be given any number of files and shell wildcards and make variables are also allowed.
include and Dependencies
When make encounters an include directive, it expands the wildcards and variable references, then tries to read the include file. If the file exists, we continue normally. If the file does not exist, however, make reports the problem and continues reading the rest of the makefile . When all reading is complete, make looks in the rules database for any rule to update the include files. If a match is found, make follows the normal process for updating a target. If any of the include files is updated by a rule, make then clears its internal database and rereads the entire makefile . If, after completing the process of reading, updating, and rereading, there are still include directives that have failed due to missing files, make terminates with an error status.
We can see this process in action with the following two-file example. We use the warning built-in function to print a simple message from make . (This and other functions are covered in detail in Chapter 4 .) Here is the makefile :
and here is bar.mk , the source for the included file:
When run, we see:
The first line shows that make cannot find the include file, but the second line shows that make keeps reading and executing the makefile . After completing the read, make discovers a rule to create the include file, foo.mk , and it does so. Then make starts the whole process again, this time without encountering any difficulty reading the include file.
Now is a good time to mention that make will also treat the makefile itself as a possible target. After the entire makefile has been read, make will look for a rule to remake the currently executing makefile . If it finds one, make will process the rule, then check if the makefile has been updated. If so, make will clear its internal state and reread the makefile , performing the whole analysis over again. Here is a silly example of an infinite loop based on this behavior:
When make executes this makefile , it sees that the makefile is out of date (because the .PHONY target, dummy , is out of date) so it executes the touch command, which updates the timestamp of the makefile . Then make rereads the file and discovers that the makefile is out of date....Well, you get the idea.
Where does make look for included files? Clearly, if the argument to include is an absolute file reference, make reads that file. If the file reference is relative, make first looks in its current working directory. If make cannot find the file, it then proceeds to search through any directories you have specified on the command line using the --include-dir (or -I ) option. After that, make searches a compiled search path similar to: /usr/local/include , /usr/gnu/include , /usr/include . There may be slight variations of this path due to the way make was compiled.
If make cannot find the include file and it cannot create it using a rule, make exits with an error. If you want make to ignore include files it cannot load, add a leading dash to the include directive:
For compatibility with other make s, the word sinclude is an alias for -include .
It is worth noting that using an include directive before the first target in a makefile might change the default goal. That is, if the include file contains any targets at all the first of those targets will become the default goal for the makefile. This can be avoided by simply placing the desired default goal before the include (even without prerequisites or targets):
Standard make Variables
In addition to automatic variables, make maintains variables revealing bits and pieces of its own state as well as variables for customizing built-in rules:
This is the version number of GNU make . At the time of this writing, its value is 3.80 , and the value in the CVS repository is 3.81rc1 .
The previous version of make , 3.79.1, did not support the eval and value functions (among other changes) and it is still very common. So when I write makefile s that require these features, I use this variable to test the version of make I’m running. We’ll see an example of that in the section Flow Control in Chapter 4 .
This variable contains the current working directory (cwd) of the executing make process. This will be the same directory the make program was executed from (and it will be the same as the shell variable PWD ), unless the --directory ( -C ) option is used. The --directory option instructs make to change to a different directory before searching for any makefile . The complete form of the option is --directory= directory-name or -C directory-name . If --directory is used, CURDIR will contain the directory argument to --include-dir .
I typically invoke make from emacs while coding. For instance, my current project is in Java and uses a single makefile in a top-level directory (not necessarily the directory containing the code). In this case, using the --directory option allows me to invoke make from any directory in the source tree and still access the makefile . Within the makefile , all paths are relative to the makefile directory. Absolute paths are occasionally required and these are accessed using CURDIR .
This variable contains a list of each file make has read including the default makefile and makefile s specified on the command line or through include directives. Just before each file is read, the name is appended to the MAKEFILE_LIST variable. So a makefile can always determine its own name by examining the last word of the list.
The MAKECMDGOALS variable contains a list of all the targets specified on the command line for the current execution of make . It does not include command-line options or variable assignments. For instance:
The example uses the “trick” of telling make to read the makefile from the stdin with the -f- (or --file ) option. The stdin is redirected from a command-line string using bash ’s here string , “<<<”, syntax. [ 6 ] The makefile itself consists of the default goal goal , while the command script is given on the same line by separating the target from the command with a semicolon. The command script contains the single line:
MAKECMDGOALS is typically used when a target requires special handling. The primary example is the “clean” target. When invoking “clean,” make should not perform the usual dependency file generation triggered by include (discussed in the section Automatic Dependency Generation in Chapter 2 ). To prevent this use ifneq and MAKECMDGOALS :
This contains a list of the names of all the variables defined in makefile s read so far, with the exception of target-specific variables. The variable is read-only and any assignment to it is ignored.
As you’ve seen, variables are also used to customize the implicit rules built in to make . The rules for C/C++ are typical of the form these variables take for all programming languages. Figure 3-1 shows the variables controlling translation from one file type to another.

The variables have the basic form: ACTION . suffix . The ACTION is COMPILE for creating an object file, LINK for creating an executable, or the “special” operations PREPROCESS , YACC , LEX for running the C preprocessor, yacc , or lex , respectively. The suffix indicates the source file type.
The standard “path” through these variables for, say, C++, uses two rules. First, compile C++ source files to object files. Then link the object files into an executable.
The first rule uses these variable definitions:
GNU make supports either of the suffixes .C or .cc for denoting C++ source files. The CXX variable indicates the C++ compiler to use and defaults to g++ . The variables CXXFLAGS , CPPFLAGS , and TARGET_ARCH have no default value. They are intended for use by end-users to customize the build process. The three variables hold the C++ compiler flags, C preprocessor flags, and architecture-specific compilation options, respectively. The OUTPUT_OPTION contains the output file option.
The linking rule is a bit simpler:
This rule uses the C compiler to combine object files into an executable. The default for the C compiler is gcc . LDFLAGS and TARGET_ARCH have no default value. The LDFLAGS variable holds options for linking such as -L flags. The LOADLIBES and LDLIBS variables contain lists of libraries to link against. Two variables are included mostly for portability.
This was a quick tour through the make variables. There are more, but this gives you the flavor of how variables are integrated with rules. Another group of variables deals with TEX and has its own set of rules. Recursive make is another feature supported by variables. We’ll discuss this topic in Chapter 6 .
[ 4 ] The df command returns a list of each mounted filesystem and statistics on the filesystem’s capacity and usage. With an argument, it prints statistics for the specified filesystem. The first line of the output is a list of column titles. This output is read by awk which examines the second line and ignores all others. Column four of df ’s output is the remaining free space in blocks.
[ 5 ] For best effect here, the RM variable should be defined to hold rm -rf . In fact, its default value is rm -f , safer but not quite as useful. Further, MKDIR should be defined as mkdir -p , and so on.
[ 6 ] For those of you who want to run this type of example in another shell, use:
Get Managing Projects with GNU Make, 3rd 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.
Don’t leave empty-handed
Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.
It’s yours, free.

Check it out now on O’Reilly
Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.


Table of contents
What are make variables, how to use make variables, recursive and simple assignment, immediate assignment, conditional assignment, shell assignment, variables with spaces, target-specific variables, pattern-specific variables, environment variables, command-line arguments, how to append to a variable, automatic variables, implicit variables, understanding and using makefile variables.

Since its appearance in 1976, Make has been helping developers automate complex processes for compiling code, building executables, and generating documentation.
Like other programming languages, Make lets you define and use variables that facilitate reusability of values.
Have you found yourself using the same value in multiple places? This is both repetitive and prone to errors. If you’d like to change this value, you’ll have to change it everywhere. This process is tedious, but it can be solved with variables, and Make offers powerful variable manipulation techniques that can make your life easier.
In this article, you’ll learn all about make variables and how to use them.
A variable is a named construct that can hold a value that can be reused in the program. It is defined by writing a name followed by = , := , or ::= , and then a value. The name of a variable can be any sequence of characters except “:”, “#”, “=”, or white space. In addition, variable names in Make are case sensitive, like many other programming languages.
The following is an example of a variable definition:
Any white space before the variable’s value is stripped away, but white spaces at the end are preserved. Using a $ inside the value of the variable is permitted, but make will assume that a string starting with the $ sign is referring to another variable and will substitute the variable’s value:
As you’ll soon learn, make assumes that $t refers to another variable named t and substitutes it. Since t doesn’t exist, it’s empty, and therefore, foo becomes onewo . If you want to include a $ verbatim, you must escape it with another $ :
Once defined, a variable can be used in any target, prerequisite, or recipe. To substitute a variable’s value, you need to use a dollar sign ( $ ) followed by the variable’s name in parentheses or curly braces. For instance, you can refer to the foo variable using both ${foo} and $(foo) .
Here’s an example of a variable reference in a recipe:
Running make with the earlier makefile will print “Hello, World!”.
Another common example of variable usage is in compiling a C program where you can define an objects variable to hold the list of all object files:
Here, the objects variable has been used in a target, prerequisite, and recipe.
Unlike many other programming languages, using a variable that you have not set explicitly will not result in an error; rather, the variable will have an empty string as its default value. However, some special variables have built-in non-empty values, and several other variables have different default values set for each different rule (more on this later).
How to Set Variables

Setting a variable refers to defining a variable with an initial value as well as changing its value later in the program. You can either set a value explicitly in the makefile or pass it as an environment variable or a command-line argument.
Variables in the Makefile
There are four different ways you can define a variable in the Makefile:
- Recursive assignment
- Simple assignment
- Immediate assignment
- Conditional assignment
As you may remember, you can define a variable with = , := , and ::= . There’s a subtle difference in how variables are expanded based on what operator is used to define them.
- The variables defined using = are called recursively expanded variables , and
- Those defined with := and ::= are called simply expanded variables .
When a recursively expanded variable is expanded, its value is substituted verbatim. If the substituted text contains references to other variables, they are also substituted until no further variable reference is encountered. Consider the following example where foo expands to Hello $(bar) :
Since foo is a recursively expanded variable, $(bar) is also expanded, and “Hello World” is printed. This recursive expansion process is performed every time the variable is expanded, using the current values of any referenced variables:
The biggest advantage of recursively expanded variables is that they make it easy to construct new variables piecewise: you can define separate pieces of the variable and string them together. You can define more granular variables and join them together, which gives you finer control over how make is executed.
For example, consider the following snippet that is often used in compiling C programs:
Here, ALL_CFLAGS is a recursively expanded variable that expands to include the contents of CFLAGS along with the -I. option. This lets you override the CFLAGS variable if you wish to pass other options while retaining the mandatory -I. option:
A disadvantage of recursively expanded variables is that it’s not possible to append something to the end of the variable:
To overcome this issue, GNU Make supports another flavor of variable known as simply expanded variables , which are defined with := or ::= . A simply expanded variable, when defined, is scanned for further variable references, and they are substituted once and for all.
Unlike recursively expanded variables, where referenced variables are expanded to their current values, in a simply expanded variable, referenced variables are expanded to their values at the time the variable is defined:
With a simply expanded variable, the following is possible:
GNU Make supports simply and recursively expanded variables. However, other versions of make usually only support recursively expanded variables. The support for simply expanded variables was added to the Portable Operating System Interface (POSIX) standard in 2012 with only the ::= operator.
A variable defined with :::= is called an immediately expanded variable . Like a simply expanded variable, its value is expanded immediately when it’s defined. But like a recursively expanded variable, it will be re-expanded every time it’s used. After the value is immediately expanded, it will automatically be quoted, and all instances of $ in the value after expansion will be converted into $$ .
In the following code, the immediately expanded variable foo behaves similarly to a simply expanded variable:
However, if there are references to other variables, things get interesting:
Here, OUT will have the value one$$two . This is because $(var) is immediately expanded to one$two , which is quoted to get one$$two . But OUT is a recursive variable, so when it’s used, $two will be expanded:
The :::= operator is supported in POSIX Make, but GNU Make includes this operator from version 4.4 onward.
The conditional assignment operator ?= can be used to set a variable only if it hasn’t already been defined:
An equivalent way of defining variables conditionally is to use the origin function :
These four types of assignments can be used in some specific situations:
You may sometimes need to run a shell command and assign its output to a variable. You can do that with the shell function:
A shorthand for this is the shell assignment operator != . With this operator, the right-hand side must be the shell command whose result will be assigned to the left-hand side:
Trailing spaces at the end of a variable definition are preserved in the variable value, but spaces at the beginning are stripped away:
It’s possible to preserve spaces at the beginning by using a second variable to store the space character:
It’s possible to limit the scope of a variable to specific targets only. The syntax for this is as follows:
Here’s an example:
Here, the variable foo will have different values based on which target make is currently evaluating:

Pattern-specific variables make it possible to limit the scope of a variable to targets that match a particular pattern . The syntax is similar to target-specific variables:
For example, the following line sets the variable foo to World for any target that ends in .c :
Pattern-specific variables are commonly used when you want to set the variable for multiple targets that share a common pattern , such as setting the same compiler options for all C files.
The real power of make variables starts to show when you pair them with environment variables . When make is run in a shell, any environment variable present in the shell is transformed into a make variable with the same name and value. This means you don’t have to set them in the makefile explicitly:
When you run the earlier makefile , it should print your username since the USER environment variable is present in the shell.
This feature is most commonly used with flags . For example, if you set the CFLAGS environment variable with your preferred C compiler options, they will be used by most makefiles to compile C code since, conventionally, the CFLAGS variable is only used for this purpose. However, this is only sometimes guaranteed, as you’ll see next.
If there’s an explicit assignment in the makefile to a variable, it overrides any environment variable with the same name:
The earlier makefile will always print Bob since the assignment overrides the $USER environment variable. You can pass the -e flag to make so environment variables override assignments instead, but this is not recommended, as it can lead to unexpected results.
You can pass variable values to the make command as command-line variables. Unlike environment variables, command-line arguments will always override assignments in the makefile unless the override directive is used:
You can simply run make , and the default values will be used:
You can pass a new value for BAR by passing it as a command-line argument:
However, since the override directive is used with FOO , it cannot be changed via command-line arguments:
This feature is handy since it lets you change a variable’s value without editing the makefile . This is most commonly used to pass configuration options that may vary from system to system or used to customize the software. As a practical example, Vim uses command-line arguments to override configuration options , like the runtime directory and location of the default configuration.

You can use the previous value of a simply expanded variable to add more text to it:
As mentioned before, this syntax will produce an infinite recursion error with a recursively expanded variable. In this case, you can use the += operator, which appends text to a variable, and it can be used for both recursively expanded and simply expanded variables:
However, there’s a subtle difference in the way it works for the two different flavors of variables, which you can read about in the docs .
How To Use Special Variables
In Make, any variable that is not defined is assigned an empty string as the default value. There are, however, a few special variables that are exceptions:
Automatic variables are special variables whose value is set up automatically per rule based on the target and prerequisites of that particular rule. The following are several commonly used automatic variables:
- [email protected] is the file name of the target of the rule.
- $< is the name of the first prerequisite.
- $? is the name of all the prerequisites that are newer than the target, with spaces between them. If the target does not exist, all prerequisites will be included.
- $^ is the name of all the prerequisites, with spaces between them.
Here’s an example that shows automatic variables in action:
Running make with the earlier makefile prints the following:
If you run touch one to modify one and run make again, you’ll get a different output:
Since one is newer than the target hello , $? contains only one .
There exist variants of these automatic variables that can extract the directory and file-within-directory name from the matched expression. You can find a list of all automatic variables in the official docs .
Automatic variables are often used where the target and prerequisite names dictate how the recipe executes . A very common practical example is the following rule that compiles a C file of the form x.c into x.o :
Make ships with certain predefined rules for some commonly performed operations. These rules include the following:
- Compiling x.c to x.o with a rule of the form $(CC) -c $(CPPFLAGS) $(CFLAGS) $^ -o [email protected]
- Compiling x.cc or x.cpp with a rule of the form $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $^ -o [email protected]
- Linking a static object file x.o to create x with a rule of the form $(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)
- And many more
These implicit rules make use of certain predefined variables known as implicit variables. Some of these are as follows:
- CC is a program for compiling C programs. The default is cc .
- CXX is a program for compiling C++ programs. The default is g++ .
- CPP is a program for running the C preprocessor. The default is $(CC) -E .
- LEX is a program to compile Lex grammars into source code. The default is lex .
- YACC is a program to compile Yacc grammars into source code. The default is yacc .
You can find the full list of implicit variables in GNU Make’s docs .
Just like standard variables, you can explicitly define an implicit variable:
Or you can define them with command line arguments:
Flags are special variables commonly used to pass options to various command-line tools, like compilers or preprocessors. Compilers and preprocessors are implicitly defined variables for some commonly used tools, including the following:
- CFLAGS is passed to CC for compiling C.
- CPPFLAGS is passed to CPP for preprocessing C programs.
- CXXFLAGS is passed to CXX for compiling C++.
Learn more about Makefile flags .
Variables in Make are similar to variables in other programming languages. However, certain features and quirks make them powerful and convenient to use, albeit slightly difficult to wrap your head around. This article gave you an overview of the different types of variables in Make and how you can use them.
Earthly makes CI/CD super simple Fast, repeatable CI/CD with an instantly familiar syntax – like Dockerfile and Makefile had a baby.
Go to our homepage to learn more
Aniket is a student doing a Master’s in Mathematics and has a passion for computers and software.
Get notified about new articles!
We won't send you spam. Unsubscribe at any time.

5 minute read

9 minute read
Docker is among the more popular platforms for developing and deploying containerized applications. Containers are isolated environments that hold an applic...
Instantly share code, notes, and snippets.
rueycheng / GNU-Make.md
Gnu make cheatsheet.
Based on https://www.gnu.org/software/make/manual/html_node/Quick-Reference.html
Built-in Functions
Automatic variables, special variables.
Stack Exchange Network
Stack Exchange network consists of 181 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Variables in GNU Make recipes, is that possible?
Is it possible to have variables in GNU Make recipes?
Something like this doesn't work:
Is there some way to make that work at all?
As you can see what I want is to extract the revision that a file was changed and then use that later in the full recipe. Unfortunately I can't use svn:keywords as I need the revision number outside of the document in question.
5 Answers 5
This doesn't work because the make tool starts a new shell process for each recipe line. And shell variables – even 'exported' environment variables – cannot possibly propagate "upwards"; they're gone as soon as the shell process exits.
The traditional method is to join the recipe lines using \ in the Makefile:
(Note that the commands must be separated using ; or && , because the backslashes are also passed to the shell which does the same line-joining.)
See also info make "Splitting Lines" and info make "Splitting Recipe Lines" in the GNU Make manual.
The other method is to tell make to always use one shell process for the entire recipe, using the .ONESHELL directive:
See info make "One Shell" .
(Note that while .ONESHELL is recommended by POSIX, not all make versions support it ; e.g. BSD make only has a command-line flag for it. This shouldn't be a problem though.)
Thanks to https://stackoverflow.com/questions/6519234/cant-assign-variable-inside-recipe
This is the solution to change a variable in a recipe:
recipe: $(eval variablename=whatever)
taking what @user3645902 mentioned, here is the solution to the main question:

- I believe that this creates a race condition. Two recipes executing in parallel could stomp on each others' variables. – Forrest Voight Jan 24, 2021 at 20:09
According to Gnu Make 6.5 Setting Variables :
The shell assignment operator != can be used to execute a program 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.
So you could try the following (not tested):

- 2 This would work at the top level of a makefile, but not in the middle of a recipe (where shell syntax is used, not Make syntax). It'd be REV != svn info ... too. – user1686 Jul 31, 2014 at 8:01
- 1 Nope, as you see I need it as part of the recipe since the value will be different for different files. – Magnus Aug 1, 2014 at 10:56
this way of setting undef Makefile function parameter in this case $(1) argument works:
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged make or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
Hot Network Questions
- Linear Algebra - Linear transformation question
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- Largest Binary Area
- The difference between the phonemes /p/ and /b/ in Japanese
- A-Z related to countries
- Mutually exclusive execution using std::atomic?
- Is it possible to create a concave light?
- Identify those arcade games from a 1983 Brazilian music video
- How do you get out of a corner when plotting yourself into a corner
- Did this satellite streak past the Hubble Space Telescope so close that it was out of focus? If so, how close was it?
- Butterfly Theorem
- Surly Straggler vs. other types of steel frames
- ncdu: What's going on with this second size column?
- Trying to understand how to get this basic Fourier Series
- Using Kolmogorov complexity to measure difficulty of problems?
- How does fire heat air?
- How to tell which packages are held back due to phased updates
- Recovering from a blunder I made while emailing a professor
- How to match a specific column position till the end of line?
- If a law is new but its interpretation is vague, can the courts directly ask the drafters the intent and official interpretation of their law?
- Can Martian regolith be easily melted with microwaves?
- Describing the homotopy explicitly.
- Tips for golfing in SVG
- How do I align things in the following tabular environment?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Deferred Simple Variable Expansion
Most users of GNU make are familiar with its two types of variables: recursive variables, where the value is expanded every time the variable is referenced, and simple variables, where the value is expanded only once: when the variable is assigned. But what if you wanted a variable that was expanded only once, but not until the first time it was used? Such a thing is possible in GNU make… with a bit of trickery. Let’s suppose that we have a command that generates output that we will need to store in a variable in our makefile. One way to obtain that output is using a recursive variable assignment:
This has the pleasant feature that some-command is not actually invoked until the variable reference $(OUTPUT) is expanded somewhere in the makefile. If $(OUTPUT) is never expanded, then some-command is never invoked. If the variable is expanded only one time (maybe you only need that variable in the recipe of one target) then some-command is expanded once. If these are true in your makefile, you’re done!
However, if $(OUTPUT) is expanded more than once, then some-command is re-run every time $(OUTPUT) is expanded. That’s most likely not what you want.
We know how we can avoid re-running the command multiple times: use a simple variable assignment instead:
This ensures that some-command is run only one time, which is probably better overall for us, but the downside is that it will be run every time we invoke make , even if we end up not actually needing this output (because we don’t happen to be invoking any recipes that rely on it, for example).
If running the command every time is not a burden, because the command is pretty fast and/or you expand $(OUTPUT) in enough parts of your makefile that it’s rare that you don’t need it at all, then you’re done!
However, let’s further suppose that this command is kind of slow and that its output is only needed for a subset of the targets in your makefile: enough that you don’t want to run it multiple times but not enough that you’re willing to eat the cost of running it every time you invoke make . How can we defer the invocation of some-command until the first time it’s used, while also ensuring that it’s only ever run once?
We can do this (at least if you have GNU make 3.80 or above), with a bit of eval magic:
Whoa! What is going on here?
Let’s break it down.
First, we can see that we’re using a recursive variable assignment, so we know that the right-hand side of the assignment will not be evaluated when this assignment is made. Thus after make parses this line, the value of the variable OUTPUT will be the string $(eval OUTPUT := $$(shell some-comand))$(OUTPUT) . That’s good, because it means that we haven’t invoked the shell function or some-command yet. That fulfils the first part of our requirement: the command is not invoked every time we parse this makefile.
Next, suppose that we are going to expand $(OUTPUT) for the first time. Because the variable is recursive, make will expand its contents. As always, make will expand things from left to right, one expression at a time. So, it will first see this:
The eval function first will expand its argument, which yields this:
(remember that $$ expands to $ ). Then this string will be evaluated as a makefile construct. This is a simple variable assignment, which means that the right-hand side of the assignment is expanded immediately. This causes some-comand to be invoked and the output is assigned to the variable OUTPUT which is now converted into a simple variable because of the := assignment style.
You may worry about reassigning a variable while expanding it, but you don’t need to: make is working on a copy of the contents of that variable while it’s being expanded, so there’s no danger of stomping on the active value.
Wow, that’s cool! But there’s one problem here: the eval function expands to the empty string. That means the first time we expand $(OUTPUT) , we’ll get the empty string. The second and subsequent times, since we have now redefined its value, we’ll get the right output. How can we fix this? That’s where the rest of the original recursively assigned value comes in. Remember we’ve finished the eval expression, so what’s left?
This expands the variable OUTPUT and since this variable now a simple variable assignment we won’t get an error about recursive variables referencing itself; instead we’ll get the new value.
Here’s something to consider: why do we need to escape the shell function invocation? Suppose instead we wrote this:
Here, some-command would be invoked when eval expanded the argument, before it started evaluating the results. Why does this matter? In most cases it won’t… but sometimes it will. Consider if some-command generated the output “ foobar “; then eval will be expanding the makefile construct:
Here it clearly doesn’t matter: you get a value of foobar . But, suppose that some-comand instead generated the output “ foo$bar “? Now, eval wil be expanding the makefile construct:
and it will treat $b as a reference to the makefile variable b which is most likely not set, and the avlue of OUTPUT will, confusingly, be fooar instead of foo$bar . By escaping the shell function we avoid the re-expansion of its output because the function itself is not expanded until eval is evaluting the results.
One last item on this subject to consider: what about target-specific variables? If you wanted to use this construct with target-specific variables you might try to use:
However, this won’t work. Why not? Because inside the eval you’re setting the global variable OUTPUT , not the target-specific variable OUTPUT . However this is easily solved; simply modify your eval argument to make this a target-specific assignment:
I should mention that I tried this trick with pattern-specific variable assignments but couldn’t get it to work for various reasons. This may be a bug in GNU make.

IMAGES
VIDEO
COMMENTS
Variables defined with ' :::= ' are immediately expanded variables. The different assignment operators are described in See The Two Flavors of Variables. The
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
Lazy Set · Immediate Set · Lazy Set If Absent · Append · Recursively expanded variables · Simply expanded variable · Assign if not set · Appending.
A substitution reference substitutes the value of a variable with alterations that you specify. It has the form ' $( var : a = b ) ' (or ' ${ var :
Make is a de-facto tool for building and running software projects. In this article, we'll learn about the conditional variable assignment
Variables in a makefile work much the same as variables in a shell script. They are words to which a string of characters can be assigned. Once a string has
From previous examples we've seen two types of assignment: = for creating recursive variables and := for creating simple variables. There are two other
The :::= operator is supported in POSIX Make, but GNU Make includes this operator from version 4.4 onward. Conditional Assignment. The
private variable-assignment, Do not allow this variable assignment to be inherited by prerequisites. ; vpath pattern path, Specify a search path for files
The shell assignment operator != can be used to execute a program and set a variable to its output. This operator first evaluates the right-hand side, then
First, we can see that we're using a recursive variable assignment, so we know that the right-hand side of the assignment will not be evaluated