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.
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.
- ‣ Makefile Examples
- ‣ Makefile Wildcards
- ‣ G++ Makefile
Learn More About Earthly
Earthly makes builds super simple. Learn More
Understanding and Using Makefile Variables
In this Series
Table of Contents
The article explains the intricacies of Makefile variables. Earthly improves on Makefile performance by introducing sophisticated caching and concurrent execution. Learn more about Earthly .
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:
- $@ 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 $@
- Compiling x.cc or x.cpp with a rule of the form $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $^ -o $@
- 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 .
Make variables are akin to variables in other languages with unique features that make them effective yet somewhat complex. Learning them can be a handy addition to your programming toolkit. If you’ve enjoyed diving into the intricacies of Makefile variables, you might want to explore Earthly for a fresh take on builds!
Bala is a technical writer who enjoys creating long-form content. Her areas of interest include math and programming. She shares her learning with the developer community by authoring tutorials, how-to guides, and more.
12 minute read
Learn how to automate the software building process using `make`, a powerful tool that saves time and resources. This article covers the basics of writing a ...
8 minute read
Learn how to use wildcards in Makefiles to create flexible and automated build processes. This tutorial provides examples and explanations of common wildcard...
Bambo's Blog
Lifelong learner, tenacious researcher, passionate developer
Special Variables in Makefile - Default Target and Automatic Variables
Tips about some special variables used in makefile: automatic variables, $@ , $< , $^ ; wildcard placeholder % in targets and dependencies and $* in recipe; and .DEFAULT_GOAL .
automatic variable A variable whose value is automatically redefined for each rule. Make’s automatic variables include $@ , which holds the rule’s target, $^ , which holds its dependencies, and, $< , which holds the first of its dependencies, and $* , which holds the stem with witch the pattern was matched. Automatic variables are typically used in pattern rules.
The first three are not hard to understand but not easy to remember clearly. The last one needs to be elaborated with the wildcard placeholder % . The wildcard placeholder % takes part in the composition of a pattern. Its function is like (.+) in regular expression. If Make finds a dependency matching the pattern, then the “group” caught in the pattern is substituted into the target. For example,
might be expanded to be
if there is an file called CLBase.cpp under the current path. While % could only be used in the targets and depedencies, to access the match in the recipe, use $* instead. For example,
The .DEFAULT_GOAL works like an environment variable to specify which is the default target that Make would build when target is absent from the command line. .DEFAULT_GOAL would be set to the first valid target (pseudo-target is not in the consideration) appears after it. So usually, the first target in a makefile would be the default target, but it can be customized explicitly:
Two more special variables in Makefile I learned recently: $(MAKECMDGOALS) and $(MAKECMDLINE) . They enable the Makefile to refer to the command line and do things special, for example:
- Automation and Make: Running Make - Where there is list of key points make things clear.
- Makefile - Get arguments passed to make - Thanks Alex Cohn for the answer on make command line.
Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
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:
- 1 I believe that this creates a race condition. Two recipes executing in parallel could stomp on each others' variables. – Forrest Voight Commented 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):
- 3 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. – grawity_u1686 Commented 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 Commented Aug 1, 2014 at 10:56
this way of setting undef Makefile function parameter in this case $(1) argument works:
You must log in to answer this question.
Not the answer you're looking for browse other questions tagged make ..
- The Overflow Blog
- CEO Update: Building trust in AI is key to a thriving knowledge ecosystem
- How to improve the developer experience in today’s ecommerce world
- Featured on Meta
- Preventing unauthorized automated access to the network
- Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
Hot Network Questions
- Why do Chief Justice Roberts, and Judge Posner, knowingly not read fine print?
- Polars - How to run computations on other rows efficiently
- Gibbs measure as stationary distribution of SDEs
- Is using online interaction platforms like Wooclap effective in a university math classroom?
- How can I encourage my toddler to try new foods?
- How do North Korean troops in Ukraine threaten South Korea?
- Leaving e-bike out in the rain WITHOUT battery
- Linux and sanctions
- Paired t test and CLT: What is supposed to be normally distributed?
- What to do if a work is too extensive to be properly presented in a single paper?
- Best statistical analysis with (very) limited samples : MLR vs GLM vs GAM vs something else?
- How best would airmobile/air assault tactics be employed in a medieval setting?
- How to create a cicular hole pattern with geometry nodes (flange hole pattern)?
- An empty program that does nothing in C++ needs a heap of 204KB but not in C
- Tcolorbox, "breakable" unrecognized
- A strange way to end a chess tournament
- Why are there no clear experiments describing the exact boundary between classical and quantum sizes?
- How important is it to avoid a duplicate name?
- Why do key signatures switch from flats to sharps at a certain mode brightness?
- How to deal with "cans of worms" of references in publications
- When making a batch cocktail how do I preserve the carbonation
- 怎么理解 troll factories
- Why is the First Law of Motion a physical law?
- Why are the ISS Cupola window's primary pressure panes vented to space?
Previous: Immediately Expanded Variable Assignment , Up: The Two Flavors of Variables [ Contents ][ Index ]
6.2.4 Conditional Variable Assignment
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.
IMAGES
VIDEO
COMMENTS
64. Variables specified on make command line override the values assigned in makefile: TMPDIR := "/tmp". test: @echo $(TMPDIR) And then: make TMPDIR=whatever. whatever. It is generally considered a bad practice for makefiles to depend on environment variables because that may lead to non-reproducible builds.
However, an explicit assignment in the makefile, or with a command argument, overrides the environment. ... GNU make supports some variables that have special properties. MAKEFILE_LIST. ... The .DEFAULT_GOAL variable allows you to discover the current default goal, restart the default goal selection algorithm by clearing its value, or to ...
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 ...
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, objects = main.o foo.o bar.o utils.o. defines a variable named ...
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, commands, and other parts of the makefile. (In some other versions of make, variables are called macros.) Variables and functions in all parts ...
Appendix A Quick Reference. This appendix summarizes the directives, text manipulation functions, and special variables which GNU make understands. See Special Built-in Target Names, Catalogue of Built-In Rules, and Summary of Options, for other summaries.. Here is a summary of the directives GNU make recognizes: . define variable define variable = define variable:=
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.
You can use the MAKEFLAGS variable to disable the built-in implicit rules and the built-in variable settings. This way: MAKEFLAGS += -rR. This will clean a lot of default settings (you can check it by using make -p). But the default variables (like CC) will still have a default value. answered Mar 22, 2017 at 17:39.
On the other hand, in the second scenario, we didn't pass the value of the USER variable, so we got the default login name in the greeting ... Conclusion. In this tutorial, we took a step-by-step approach to learn about the conditional variable assignment in a Makefile. We first understood the basics of using variables in a Makefile, followed ...
The .DEFAULT_GOAL works like an environment variable to specify which is the default target that Make would build when target is absent from the command line. .DEFAULT_GOAL would be set to the first valid target (pseudo-target is not in the consideration) appears after it. So usually, the first target in a makefile would be the default target, but it can be customized explicitly:
I have a Makefile that has a variable that needs to have a default value in case when variable is unset or if set but has null value. How can I achieve this? I need this, as I invoke make inside a shell script and the value required by the makefile can be passed from the shell as $1. And to pass this to makefile I have to set it inside bash-script.
Assuming make is GNU Make, all the environment variable settings inherited by make are automatically registered as make variable settings. See 6.10 Variables from the Environment. So you can just write, e.g. Makefile (1) ifdef myvar MYVAR := $(myvar) else MYVAR := default endif .PHONY: all all: echo $(MYVAR) Which runs like:
If a variable has been set with a command argument (see section Overriding Variables), then ordinary assignments in the makefile are ignored. If you want to set the variable in the makefile even though it was set with a command argument, you can use an override directive, which is a line that looks like this: override variable = value. or
1. 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.
Conditional Assignment (GNU make) Previous: Immediately Expanded Variable Assignment , Up: The Two Flavors of Variables [ Contents ][ Index ] 6.2.4 Conditional Variable Assignment
The default behavior of make is to run the first target in the Makefile if you don't specify a target as a command-line argument. If you like to override this behavior, there is the .DEFAULT_GOAL special variable. There is a convention to have a target named all which builds everything, but this is just human convention, not a special case or a ...
GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target. Ref: The Gnu Make manual - Special Variables