Next: Rules , Previous: Introduction , Up: Top   [ Contents ][ Index ]

3 Writing Makefiles

The information that tells make how to recompile a system comes from reading a data base called the makefile .

Next: Makefile Names , Previous: Makefiles , Up: Makefiles   [ Contents ][ Index ]

3.1 What Makefiles Contain

Makefiles contain five kinds of things: explicit rules , implicit rules , variable definitions , directives , and comments . Rules, variables, and directives are described at length in later chapters.

  • An explicit rule says when and how to remake one or more files, called the rule’s targets . It lists the other files that the targets depend on, called the prerequisites of the target, and may also give a recipe to use to create or update the targets. See Writing Rules .
  • An implicit rule says when and how to remake a class of files based on their names. It describes how a target may depend on a file with a name similar to the target and gives a recipe to create or update such a target. See Using Implicit Rules .
  • A variable definition is a line that specifies a text string value for a variable that can be substituted into the text later. The simple makefile example shows a variable definition for objects as a list of all object files (see Variables Make Makefiles Simpler ).
  • Reading another makefile (see Including Other Makefiles ).
  • Deciding (based on the values of variables) whether to use or ignore a part of the makefile (see Conditional Parts of Makefiles ).
  • Defining a variable from a verbatim string containing multiple lines (see Defining Multi-Line Variables ).

You cannot use comments within variable references or function calls: any instance of # will be treated literally (rather than as the start of a comment) inside a variable reference or function call.

Comments within a recipe are passed to the shell, just as with any other recipe text. The shell decides how to interpret it: whether or not this is a comment is up to the shell.

Within a define directive, comments are not ignored during the definition of the variable, but rather kept intact in the value of the variable. When the variable is expanded they will either be treated as make comments or as recipe text, depending on the context in which the variable is evaluated.

Previous: Makefile Contents , Up: Makefile Contents   [ Contents ][ Index ]

3.1.1 Splitting Long Lines

Makefiles use a “line-based” syntax in which the newline character is special and marks the end of a statement. GNU make has no limit on the length of a statement line, up to the amount of memory in your computer.

However, it is difficult to read lines which are too long to display without wrapping or scrolling. So, you can format your makefiles for readability by adding newlines into the middle of a statement: you do this by escaping the internal newlines with a backslash ( \ ) character. Where we need to make a distinction we will refer to “physical lines” as a single line ending with a newline (regardless of whether it is escaped) and a “logical line” being a complete statement including all escaped newlines up to the first non-escaped newline.

The way in which backslash/newline combinations are handled depends on whether the statement is a recipe line or a non-recipe line. Handling of backslash/newline in a recipe line is discussed later (see Splitting Recipe Lines ).

Outside of recipe lines, backslash/newlines are converted into a single space character. Once that is done, all whitespace around the backslash/newline is condensed into a single space: this includes all whitespace preceding the backslash, all whitespace at the beginning of the line after the backslash/newline, and any consecutive backslash/newline combinations.

If the .POSIX special target is defined then backslash/newline handling is modified slightly to conform to POSIX.2: first, whitespace preceding a backslash is not removed and second, consecutive backslash/newlines are not condensed.

Splitting Without Adding Whitespace

If you need to split a line but do not want any whitespace added, you can utilize a subtle trick: replace your backslash/newline pairs with the three characters dollar sign/backslash/newline:

After make removes the backslash/newline and condenses the following line into a single space, this is equivalent to:

Then make will perform variable expansion. The variable reference ‘ $ ’ refers to a variable with the one-character name “ ” (space) which does not exist, and so expands to the empty string, giving a final assignment which is the equivalent of:

Next: Include , Previous: Makefile Contents , Up: Makefiles   [ Contents ][ Index ]

3.2 What Name to Give Your Makefile

By default, when make looks for the makefile, it tries the following names, in order: GNUmakefile , makefile and Makefile .

Normally you should call your makefile either makefile or Makefile . (We recommend Makefile because it appears prominently near the beginning of a directory listing, right near other important files such as README .) The first name checked, GNUmakefile , is not recommended for most makefiles. You should use this name if you have a makefile that is specific to GNU make , and will not be understood by other versions of make . Other make programs look for makefile and Makefile , but not GNUmakefile .

If make finds none of these names, it does not use any makefile. Then you must specify a goal with a command argument, and make will attempt to figure out how to remake it using only its built-in implicit rules. See Using Implicit Rules .

If you want to use a nonstandard name for your makefile, you can specify the makefile name with the ‘ -f ’ or ‘ --file ’ option. The arguments ‘ -f   name ’ or ‘ --file= name ’ tell make to read the file name as the makefile. If you use more than one ‘ -f ’ or ‘ --file ’ option, you can specify several makefiles. All the makefiles are effectively concatenated in the order specified. The default makefile names GNUmakefile , makefile and Makefile are not checked automatically if you specify ‘ -f ’ or ‘ --file ’.

Next: MAKEFILES Variable , Previous: Makefile Names , Up: Makefiles   [ Contents ][ Index ]

3.3 Including Other Makefiles

The include directive tells make to suspend reading the current makefile and read one or more other makefiles before continuing. The directive is a line in the makefile that looks like this:

filenames can contain shell file name patterns. If filenames is empty, nothing is included and no error is printed.

Extra spaces are allowed and ignored at the beginning of the line, but the first character must not be a tab (or the value of .RECIPEPREFIX )—if the line begins with a tab, it will be considered a recipe line. Whitespace is required between include and the file names, and between file names; extra whitespace is ignored there and at the end of the directive. A comment starting with ‘ # ’ is allowed at the end of the line. If the file names contain any variable or function references, they are expanded. See How to Use Variables .

For example, if you have three .mk files, a.mk , b.mk , and c.mk , and $(bar) expands to bish bash , then the following expression

is equivalent to

When make processes an include directive, it suspends reading of the containing makefile and reads from each listed file in turn. When that is finished, make resumes reading the makefile in which the directive appears.

One occasion for using include directives is when several programs, handled by individual makefiles in various directories, need to use a common set of variable definitions (see Setting Variables ) or pattern rules (see Defining and Redefining Pattern Rules ).

Another such occasion is when you want to generate prerequisites from source files automatically; the prerequisites can be put in a file that is included by the main makefile. This practice is generally cleaner than that of somehow appending the prerequisites to the end of the main makefile as has been traditionally done with other versions of make . See Automatic Prerequisites .

If the specified name does not start with a slash, and the file is not found in the current directory, several other directories are searched. First, any directories you have specified with the ‘ -I ’ or ‘ --include-dir ’ option are searched (see Summary of Options ). Then the following directories (if they exist) are searched, in this order: prefix /include (normally /usr/local/include 1 ) /usr/gnu/include , /usr/local/include , /usr/include .

If an included makefile cannot be found in any of these directories, a warning message is generated, but it is not an immediately fatal error; processing of the makefile containing the include continues. Once it has finished reading makefiles, make will try to remake any that are out of date or don’t exist. See How Makefiles Are Remade . Only after it has tried to find a way to remake a makefile and failed, will make diagnose the missing makefile as a fatal error.

If you want make to simply ignore a makefile which does not exist or cannot be remade, with no error message, use the -include directive instead of include , like this:

This acts like include in every way except that there is no error (not even a warning) if any of the filenames (or any prerequisites of any of the filenames ) do not exist or cannot be remade.

For compatibility with some other make implementations, sinclude is another name for -include .

Next: Remaking Makefiles , Previous: Include , Up: Makefiles   [ Contents ][ Index ]

3.4 The Variable MAKEFILES

If the environment variable MAKEFILES is defined, make considers its value as a list of names (separated by whitespace) of additional makefiles to be read before the others. This works much like the include directive: various directories are searched for those files (see Including Other Makefiles ). In addition, the default goal is never taken from one of these makefiles (or any makefile included by them) and it is not an error if the files listed in MAKEFILES are not found.

The main use of MAKEFILES is in communication between recursive invocations of make (see Recursive Use of make ). It usually is not desirable to set the environment variable before a top-level invocation of make , because it is usually better not to mess with a makefile from outside. However, if you are running make without a specific makefile, a makefile in MAKEFILES can do useful things to help the built-in implicit rules work better, such as defining search paths (see Directory Search ).

Some users are tempted to set MAKEFILES in the environment automatically on login, and program makefiles to expect this to be done. This is a very bad idea, because such makefiles will fail to work if run by anyone else. It is much better to write explicit include directives in the makefiles. See Including Other Makefiles .

Next: Overriding Makefiles , Previous: MAKEFILES Variable , Up: Makefiles   [ Contents ][ Index ]

3.5 How Makefiles Are Remade

Sometimes makefiles can be remade from other files, such as RCS or SCCS files. If a makefile can be remade from other files, you probably want make to get an up-to-date version of the makefile to read in.

To this end, after reading in all makefiles make will consider each as a goal target and attempt to update it. If a makefile has a rule which says how to update it (found either in that very makefile or in another one) or if an implicit rule applies to it (see Using Implicit Rules ), it will be updated if necessary. After all makefiles have been checked, if any have actually been changed, make starts with a clean slate and reads all the makefiles over again. (It will also attempt to update each of them over again, but normally this will not change them again, since they are already up to date.) Each restart will cause the special variable MAKE_RESTARTS to be updated (see Special Variables ).

If you know that one or more of your makefiles cannot be remade and you want to keep make from performing an implicit rule search on them, perhaps for efficiency reasons, you can use any normal method of preventing implicit rule look-up to do so. For example, you can write an explicit rule with the makefile as the target, and an empty recipe (see Using Empty Recipes ).

If the makefiles specify a double-colon rule to remake a file with a recipe but no prerequisites, that file will always be remade (see Double-Colon ). In the case of makefiles, a makefile that has a double-colon rule with a recipe but no prerequisites will be remade every time make is run, and then again after make starts over and reads the makefiles in again. This would cause an infinite loop: make would constantly remake the makefile, and never do anything else. So, to avoid this, make will not attempt to remake makefiles which are specified as targets of a double-colon rule with a recipe but no prerequisites.

If you do not specify any makefiles to be read with ‘ -f ’ or ‘ --file ’ options, make will try the default makefile names; see What Name to Give Your Makefile . Unlike makefiles explicitly requested with ‘ -f ’ or ‘ --file ’ options, make is not certain that these makefiles should exist. However, if a default makefile does not exist but can be created by running make rules, you probably want the rules to be run so that the makefile can be used.

Therefore, if none of the default makefiles exists, make will try to make each of them in the same order in which they are searched for (see What Name to Give Your Makefile ) until it succeeds in making one, or it runs out of names to try. Note that it is not an error if make cannot find or make any makefile; a makefile is not always necessary.

When you use the ‘ -t ’ or ‘ --touch ’ option (see Instead of Executing Recipes ), you would not want to use an out-of-date makefile to decide which targets to touch. So the ‘ -t ’ option has no effect on updating makefiles; they are really updated even if ‘ -t ’ is specified. Likewise, ‘ -q ’ (or ‘ --question ’) and ‘ -n ’ (or ‘ --just-print ’) do not prevent updating of makefiles, because an out-of-date makefile would result in the wrong output for other targets. Thus, ‘ make -f mfile -n foo ’ will update mfile , read it in, and then print the recipe to update foo and its prerequisites without running it. The recipe printed for foo will be the one specified in the updated contents of mfile .

However, on occasion you might actually wish to prevent updating of even the makefiles. You can do this by specifying the makefiles as goals in the command line as well as specifying them as makefiles. When the makefile name is specified explicitly as a goal, the options ‘ -t ’ and so on do apply to them.

Thus, ‘ make -f mfile -n mfile foo ’ would read the makefile mfile , print the recipe needed to update it without actually running it, and then print the recipe needed to update foo without running that. The recipe for foo will be the one specified by the existing contents of mfile .

Next: Reading Makefiles , Previous: Remaking Makefiles , Up: Makefiles   [ Contents ][ Index ]

3.6 Overriding Part of Another Makefile

Sometimes it is useful to have a makefile that is mostly just like another makefile. You can often use the ‘ include ’ directive to include one in the other, and add more targets or variable definitions. However, it is invalid for two makefiles to give different recipes for the same target. But there is another way.

In the containing makefile (the one that wants to include the other), you can use a match-anything pattern rule to say that to remake any target that cannot be made from the information in the containing makefile, make should look in another makefile. See Pattern Rules , for more information on pattern rules.

For example, if you have a makefile called Makefile that says how to make the target ‘ foo ’ (and other targets), you can write a makefile called GNUmakefile that contains:

If you say ‘ make foo ’, make will find GNUmakefile , read it, and see that to make foo , it needs to run the recipe ‘ frobnicate > foo ’. If you say ‘ make bar ’, make will find no way to make bar in GNUmakefile , so it will use the recipe from the pattern rule: ‘ make -f Makefile bar ’. If Makefile provides a rule for updating bar , make will apply the rule. And likewise for any other target that GNUmakefile does not say how to make.

The way this works is that the pattern rule has a pattern of just ‘ % ’, so it matches any target whatever. The rule specifies a prerequisite force , to guarantee that the recipe will be run even if the target file already exists. We give the force target an empty recipe to prevent make from searching for an implicit rule to build it—otherwise it would apply the same match-anything rule to force itself and create a prerequisite loop!

Next: Parsing Makefiles , Previous: Overriding Makefiles , Up: Makefiles   [ Contents ][ Index ]

3.7 How make Reads a Makefile

GNU make does its work in two distinct phases. During the first phase it reads all the makefiles, included makefiles, etc. and internalizes all the variables and their values and implicit and explicit rules, and builds a dependency graph of all the targets and their prerequisites. During the second phase, make uses this internalized data to determine which targets need to be updated and run the recipes necessary to update them.

It’s important to understand this two-phase approach because it has a direct impact on how variable and function expansion happens; this is often a source of some confusion when writing makefiles. Below is a summary of the different constructs that can be found in a makefile, and the phase in which expansion happens for each part of the construct.

We say that expansion is immediate if it happens during the first phase: make will expand that part of the construct as the makefile is parsed. We say that expansion is deferred if it is not immediate. Expansion of a deferred construct part is delayed until the expansion is used: either when it is referenced in an immediate context, or when it is needed during the second phase.

You may not be familiar with some of these constructs yet. You can reference this section as you become familiar with them, in later chapters.

Variable Assignment

Variable definitions are parsed as follows:

For the append operator ‘ += ’, the right-hand side is considered immediate if the variable was previously set as a simple variable (‘ := ’ or ‘ ::= ’), and deferred otherwise.

For the shell assignment operator ‘ != ’, the right-hand side is evaluated immediately and handed to the shell. The result is stored in the variable named on the left, and that variable becomes a simple variable (and will thus be re-evaluated on each reference).

Conditional Directives

Conditional directives are parsed immediately. This means, for example, that automatic variables cannot be used in conditional directives, as automatic variables are not set until the recipe for that rule is invoked. If you need to use automatic variables in a conditional directive you must move the condition into the recipe and use shell conditional syntax instead.

Rule Definition

A rule is always expanded the same way, regardless of the form:

That is, the target and prerequisite sections are expanded immediately, and the recipe used to build the target is always deferred. This is true for explicit rules, pattern rules, suffix rules, static pattern rules, and simple prerequisite definitions.

Next: Secondary Expansion , Previous: Reading Makefiles , Up: Makefiles   [ Contents ][ Index ]

3.8 How Makefiles Are Parsed

GNU make parses makefiles line-by-line. Parsing proceeds using the following steps:

  • Read in a full logical line, including backslash-escaped lines (see Splitting Long Lines ).
  • Remove comments (see What Makefiles Contain ).
  • If the line begins with the recipe prefix character and we are in a rule context, add the line to the current recipe and read the next line (see Recipe Syntax ).
  • Expand elements of the line which appear in an immediate expansion context (see How make Reads a Makefile ).
  • Scan the line for a separator character, such as ‘ : ’ or ‘ = ’, to determine whether the line is a macro assignment or a rule (see Recipe Syntax ).
  • Internalize the resulting operation and read the next line.

An important consequence of this is that a macro can expand to an entire rule, if it is one line long . This will work:

However, this will not work because make does not re-split lines after it has expanded them:

The above makefile results in the definition of a target ‘ target ’ with prerequisites ‘ echo ’ and ‘ built ’, as if the makefile contained target: echo built , rather than a rule with a recipe. Newlines still present in a line after expansion is complete are ignored as normal whitespace.

In order to properly expand a multi-line macro you must use the eval function: this causes the make parser to be run on the results of the expanded macro (see Eval Function ).

Previous: Parsing Makefiles , Up: Makefiles   [ Contents ][ Index ]

3.9 Secondary Expansion

Previously we learned that GNU make works in two distinct phases: a read-in phase and a target-update phase (see How make Reads a Makefile ). GNU make also has the ability to enable a second expansion of the prerequisites (only) for some or all targets defined in the makefile. In order for this second expansion to occur, the special target .SECONDEXPANSION must be defined before the first prerequisite list that makes use of this feature.

If that special target is defined then in between the two phases mentioned above, right at the end of the read-in phase, all the prerequisites of the targets defined after the special target are expanded a second time . In most circumstances this secondary expansion will have no effect, since all variable and function references will have been expanded during the initial parsing of the makefiles. In order to take advantage of the secondary expansion phase of the parser, then, it’s necessary to escape the variable or function reference in the makefile. In this case the first expansion merely un-escapes the reference but doesn’t expand it, and expansion is left to the secondary expansion phase. For example, consider this makefile:

After the first expansion phase the prerequisites list of the myfile target will be onefile and $(TWOVAR) ; the first (unescaped) variable reference to ONEVAR is expanded, while the second (escaped) variable reference is simply unescaped, without being recognized as a variable reference. Now during the secondary expansion the first word is expanded again but since it contains no variable or function references it remains the value onefile , while the second word is now a normal reference to the variable TWOVAR , which is expanded to the value twofile . The final result is that there are two prerequisites, onefile and twofile .

Obviously, this is not a very interesting case since the same result could more easily have been achieved simply by having both variables appear, unescaped, in the prerequisites list. One difference becomes apparent if the variables are reset; consider this example:

Here the prerequisite of onefile will be expanded immediately, and resolve to the value top , while the prerequisite of twofile will not be full expanded until the secondary expansion and yield a value of bottom .

This is marginally more exciting, but the true power of this feature only becomes apparent when you discover that secondary expansions always take place within the scope of the automatic variables for that target. This means that you can use variables such as $@ , $* , etc. during the second expansion and they will have their expected values, just as in the recipe. All you have to do is defer the expansion by escaping the $ . Also, secondary expansion occurs for both explicit and implicit (pattern) rules. Knowing this, the possible uses for this feature increase dramatically. For example:

Here, after the initial expansion the prerequisites of both the main and lib targets will be $($@_OBJS) . During the secondary expansion, the $@ variable is set to the name of the target and so the expansion for the main target will yield $(main_OBJS) , or main.o try.o test.o , while the secondary expansion for the lib target will yield $(lib_OBJS) , or lib.o api.o .

You can also mix in functions here, as long as they are properly escaped:

This version allows users to specify source files rather than object files, but gives the same resulting prerequisites list as the previous example.

Evaluation of automatic variables during the secondary expansion phase, especially of the target name variable $$@ , behaves similarly to evaluation within recipes. However, there are some subtle differences and “corner cases” which come into play for the different types of rule definitions that make understands. The subtleties of using the different automatic variables are described below.

Secondary Expansion of Explicit Rules

During the secondary expansion of explicit rules, $$@ and $$% evaluate, respectively, to the file name of the target and, when the target is an archive member, the target member name. The $$< variable evaluates to the first prerequisite in the first rule for this target. $$^ and $$+ evaluate to the list of all prerequisites of rules that have already appeared for the same target ( $$+ with repetitions and $$^ without). The following example will help illustrate these behaviors:

In the first prerequisite list, all three variables ( $$< , $$^ , and $$+ ) expand to the empty string. In the second, they will have values foo.1 , foo.1 bar.1 , and foo.1 bar.1 respectively. In the third they will have values foo.1 , foo.1 bar.1 foo.2 bar.2 , and foo.1 bar.1 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1 respectively.

Rules undergo secondary expansion in makefile order, except that the rule with the recipe is always evaluated last.

The variables $$? and $$* are not available and expand to the empty string.

Secondary Expansion of Static Pattern Rules

Rules for secondary expansion of static pattern rules are identical to those for explicit rules, above, with one exception: for static pattern rules the $$* variable is set to the pattern stem. As with explicit rules, $$? is not available and expands to the empty string.

Secondary Expansion of Implicit Rules

As make searches for an implicit rule, it substitutes the stem and then performs secondary expansion for every rule with a matching target pattern. The value of the automatic variables is derived in the same fashion as for static pattern rules. As an example:

When the implicit rule is tried for target foo , $$< expands to bar , $$^ expands to bar boo , $$+ also expands to bar boo , and $$* expands to f .

Note that the directory prefix (D), as described in Implicit Rule Search Algorithm , is appended (after expansion) to all the patterns in the prerequisites list. As an example:

The prerequisite list printed, after the secondary expansion and directory prefix reconstruction, will be /tmp/foo/foo.c /tmp/bar/foo.c foo.h . If you are not interested in this reconstruction, you can use $$* instead of % in the prerequisites list.

GNU Make compiled for MS-DOS and MS-Windows behaves as if prefix has been defined to be the root of the DJGPP tree hierarchy.

Understanding and Using Makefile Variables

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

Aniket Bhattacharyea %

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

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

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.

How to Append to a Variable

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 Priya C %

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.

makefile default assignment

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 ...

makefile default assignment

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...

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.

Variables for C/C++ compilation

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.

Cover of Software Architecture Patterns

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.

makefile default assignment

Browse Course Material

Course info.

  • Prof. Kevin Amaratunga

Departments

  • Civil and Environmental Engineering
  • Mechanical Engineering

As Taught In

  • Software Design and Engineering

Learning Resource Types

Foundations of software engineering, makefile primer, how to use make, introduction.

make is a command generator which generates a sequence of commands for execution by the UNIX® shell. These commands usually relate to the maintenance of a set of files in a software development project. We will use make to help us organize our C++ and C source code files during the compilation and linking process. In particular, make can be used to sort out the dependency relations among the various source files, object files and executables and to determine exactly how the object files and executables will be produced.

Invoking make from the Command Line

make may be invoked from the command line by typing:

make -f make filename program

Here, program is the name of the target i.e. the program to be made. makefilename is a description file which tells the make utility how to build the target program from its various components . Each of these components could be a target in itself. make would therefore have to build these targets, using information in the description file, before program can be made. program need not necessarily be the highest level target in the hierarchy, although in practice it often is.

It is not always necessary to specify the name of the description file when invoking make . For example,

make program

would cause make to look in the current directory for a default description file named makefile or Makefile , in that order.

Furthermore, it is not even necessary to specify the name of the final target. Simply typing

will build the first target found in the default description file, together with all of its components. On the other hand, it is also possible to specify multiple targets when invoking make .

make Description Files (makefiles)

Here is an example of a simple makefile:

program: main.o iodat.o            cc -o program main.o iodat.o main.o: main.c            cc -c main.c iodat.o: iodat.c            cc -c iodat.c

Each entry consists of a dependency line containing a colon, and one or more command lines each starting with a tab. Dependency lines have one or more targets to the left of the colon. To the right of the colon are the component files on which the target(s) depend.

A command line will be executed if any target listed on the dependency line does not exist, or if any of the component files are more recent than a target.

Here are some points to remember:

  • Comments start with a pound sign (#).
  • Continuation of a line is denoted by a backslash (\).
  • Lines containing equals signs (=) are macro definitions (see next section).
  • Each command line is typically executed in a separate Bourne shell i.e. _sh_ 1 .

To execute more than one command line in the same shell, type them on the same line, separated by semicolons. Use a \ to continue the line if necessary. For example,

program: main.o iodat.o           cd newdir; \           cc -o program main.o iodat.o

would change to the directory newdir before invoking cc . (Note that executing the two commands in separate shells would not produce the required effect, since the cd command is only effective within the shell from which it was invoked.)

The Bourne shell’s pattern matching characters maybe used in command lines, as well as to the right of the colon in dependency lines e.g.

program: *.c            cc -o program *.c

Macro Definitions in the Description File

Macro definitions are of the form:

name = string

Subsequent references to $( name ) or ${name} are then interpreted as string . Macros are typically grouped together at the beginning of the description file. Macros which have no string to the right of the equals sign are assigned the null string. Macros may be included within macro denitions, regardless of the order in which they are defined.

Here is an example of a macro:

_CC = /mit/gnu/arch/sun4x 57/bin/g++ program: program.C            ${CC} -o program program.C

_ Shell Environment Variables

Shell variables that were part of the environment before make was invoked are available as macros within make . Within a make description file, however, shell environment variables must be surrounded by parentheses or braces, unless they consist of a single character. For example, ${PWD} may be used in a description file to refer to the current working directory.

Command Line Macro Definitions

Macros can be defined when invoking make e.g.

make program CC=/mit/gnu/arch/sun4x_57/bin/g++

Internal Macros

make has a few predefined macros:

  • $? evaluates to the list of components that are younger than the current target. Can only be used in description file command lines.
  • $@ evaluates to the current target name. Can only be used in description file command lines.
  • $$@ also evaluates to the current target name. However, it can only be used on dependency lines.

PROGS = prog1 prog2 prog3 ${PROGS}: [email protected]            cc -o $@ $?

This will compile the three files prog1.c , prog2.c and prog3.c , unless any of them have already been compiled. During the compilation process, each of the programs becomes the current target in turn. In this particular example, the same effect would be obtained if we replaced the $? by [email protected]

Order of Priority of Macro Assignments

The following is the order of priority of macro assignments, from least to greatest:

  • Internal (default) macro definitions.
  • Shell environment variables.
  • Description file macro definitions.
  • Command line macro definitions.

Items 2. and 3. can be interchanged by specifying the -e option to make .

Macro String Substitution

String substitutions may be performed on all macros used in description file shell commands. However, substitutions occur only at the end of the macro, or immediately before white space. The following example illustrates this:

               LETTERS = abcxyz xyzabc xyz                print:                          echo $(LETTERS:xyz=def)

This description file will produce the output

               abcdef xyzabc def

Suffix Rules

The existence of naming and compiling conventions makes it possible to considerably simplify description files. For example, the C compiler requires that C source files always have a .c suffix. Such naming conventions enable make to perform many tasks based on suffix rules . make provides a set of default suffix rules. In addition, new suffix rules can be defined by the user.

For example, the description file on page 2 can be simplified to

program: main.o iodat.o             cc -o program main.o iodat.o

make will use the following default macros and suffix rules to determine how to build the components main.o and iodat.o .

CC = cc CFLAGS = -O .SUFFIXES: .o .c .c.o:          ${CC} ${CFLAGS} $<

The entries on the .SUFFIXES line represent the suffixes which make will consider significant . Thus, in building iodat.o from the above description file, make looks for a user-specified dependency line containing iodat.o as a target. Finding no such dependency, make notes that the .o suffix is significant and therefore it looks for another file in the current directory which can be used to make iodat.o. Such a file must

have the same name (apart from the suffix) as iodat.o .

have a significant suffix.

be able to be used to make iodat.o according to an existing suffix rule.

make then applies the above suffix rule which specifies how to build a .o file from a .c file. The $< macro evaluates to the component that triggered the suffix rule i.e. iodat.c .

After the components main.o and iodat.o have been updated in this way (if necessary), the target program will be built according to the directions in the description file.

Internal Macros in Suffix Rules

The following internal macros can only be used in suffix rules.

$< evaluates to the component that is being used to make the target.

$* evaluates to the filename part (without any suffix) of the component that is being used to make the target.

Note that the $? macro cannot occur in suffix rules. The $@ macro, however, can be used.

Null Suffixes

Files with null suffixes (no suffix at all) can be made using a suffix rule which has only a single suffix e.g.

.c:           ${CC} -o $@ $<

This suffix rule will be invoked to produce an executable called program from a source file program.c , if the description file contains a line of the form.

          program:

Note that in this particular situation it would be incorrect to specify that program depended on program.c , because make would then consider the command line to contain a null command and would therefore not invoke the suffix rule. This problem does not arise when building a .o file from a .c file using suffix rules. A .o file can be specified to depend on a .c file (and possibly some additional header files) because of the one-to-one relationship that exists betweeen .o and .c files.

Writing Your Own Suffix Rules

Suffix rules and the list of significant suffixes can be redefined. A line containing . SUFFIXES by itself will delete the current list of significant suffixes e.g.

.SUFFIXES: .SUFFIXES: .o .c .c.o:              ${CC} -o $@ $<

[1] Talbot, S. “Managing Projects with Make.” O’Reilly & Associates, Inc.

facebook

You are leaving MIT OpenCourseWare

makefile default assignment

Getting Started

Why do makefiles exist, what alternatives are there to make, the versions and types of make, running the examples, makefile syntax, the essence of make, more quick examples, the all target, multiple targets, automatic variables and wildcards, automatic variables, fancy rules, implicit rules, static pattern rules, static pattern rules and filter, pattern rules, double-colon rules, commands and execution, command echoing/silencing, command execution, default shell, double dollar sign.

  • Error handling with -k, -i, and -

Interrupting or killing make

Recursive use of make, export, environments, and recursive make, arguments to make, variables pt. 2, flavors and modification, command line arguments and override, list of commands and define, target-specific variables, pattern-specific variables, conditional part of makefiles, conditional if/else, check if a variable is empty, check if a variable is defined, $(makeflags), first functions, string substitution, the foreach function, the if function, the call function, the shell function, other features, include makefiles, the vpath directive, .delete_on_error, makefile cookbook.

I built this guide because I could never quite wrap my head around Makefiles. They seemed awash with hidden rules and esoteric symbols, and asking simple questions didn’t yield simple answers. To solve this, I sat down for several weekends and read everything I could about Makefiles. I've condensed the most critical knowledge into this guide. Each topic has a brief description and a self contained example that you can run yourself.

If you mostly understand Make, consider checking out the Makefile Cookbook , which has a template for medium sized projects with ample comments about what each part of the Makefile is doing.

Good luck, and I hope you are able to slay the confusing world of Makefiles!

Makefiles are used to help decide which parts of a large program need to be recompiled. In the vast majority of cases, C or C++ files are compiled. Other languages typically have their own tools that serve a similar purpose as Make. Make can also be used beyond compilation too, when you need a series of instructions to run depending on what files have changed. This tutorial will focus on the C/C++ compilation use case.

Here's an example dependency graph that you might build with Make. If any file's dependencies changes, then the file will get recompiled:

makefile default assignment

Popular C/C++ alternative build systems are SCons , CMake , Bazel , and Ninja . Some code editors like Microsoft Visual Studio have their own built in build tools. For Java, there's Ant , Maven , and Gradle . Other languages like Go, Rust, and TypeScript have their own build tools.

Interpreted languages like Python, Ruby, and raw Javascript don't require an analogue to Makefiles. The goal of Makefiles is to compile whatever files need to be compiled, based on what files have changed. But when files in interpreted languages change, nothing needs to get recompiled. When the program runs, the most recent version of the file is used.

There are a variety of implementations of Make, but most of this guide will work on whatever version you're using. However, it's specifically written for GNU Make, which is the standard implementation on Linux and MacOS. All the examples work for Make versions 3 and 4, which are nearly equivalent other than some esoteric differences.

To run these examples, you'll need a terminal and "make" installed. For each example, put the contents in a file called Makefile , and in that directory run the command make . Let's start with the simplest of Makefiles:

Note: Makefiles must be indented using TABs and not spaces or make will fail.

Here is the output of running the above example:

That's it! If you're a bit confused, here's a video that goes through these steps, along with describing the basic structure of Makefiles.

A Makefile consists of a set of rules . A rule generally looks like this:

  • The targets are file names, separated by spaces. Typically, there is only one per rule.
  • The commands are a series of steps typically used to make the target(s). These need to start with a tab character , not spaces.
  • The prerequisites are also file names, separated by spaces. These files need to exist before the commands for the target are run. These are also called dependencies

Let's start with a hello world example:

There's already a lot to take in here. Let's break it down:

  • We have one target called hello
  • This target has two commands
  • This target has no prerequisites

We'll then run make hello . As long as the hello file does not exist, the commands will run. If hello does exist, no commands will run.

It's important to realize that I'm talking about hello as both a target and a file . That's because the two are directly tied together. Typically, when a target is run (aka when the commands of a target are run), the commands will create a file with the same name as the target. In this case, the hello target does not create the hello file .

Let's create a more typical Makefile - one that compiles a single C file. But before we do, make a file called blah.c that has the following contents:

Then create the Makefile (called Makefile , as always):

This time, try simply running make . Since there's no target supplied as an argument to the make command, the first target is run. In this case, there's only one target ( blah ). The first time you run this, blah will be created. The second time, you'll see make: 'blah' is up to date . That's because the blah file already exists. But there's a problem: if we modify blah.c and then run make , nothing gets recompiled.

We solve this by adding a prerequisite:

When we run make again, the following set of steps happens:

  • The first target is selected, because the first target is the default target
  • This has a prerequisite of blah.c
  • Make decides if it should run the blah target. It will only run if blah doesn't exist, or blah.c is newer than blah

This last step is critical, and is the essence of make . What it's attempting to do is decide if the prerequisites of blah have changed since blah was last compiled. That is, if blah.c is modified, running make should recompile the file. And conversely, if blah.c has not changed, then it should not be recompiled.

To make this happen, it uses the filesystem timestamps as a proxy to determine if something has changed. This is a reasonable heuristic, because file timestamps typically will only change if the files are modified. But it's important to realize that this isn't always the case. You could, for example, modify a file, and then change the modified timestamp of that file to something old. If you did, Make would incorrectly guess that the file hadn't changed and thus could be ignored.

Whew, what a mouthful. Make sure that you understand this. It's the crux of Makefiles, and might take you a few minutes to properly understand . Play around with the above examples or watch the video above if things are still confusing.

The following Makefile ultimately runs all three targets. When you run make in the terminal, it will build a program called blah in a series of steps:

  • Make selects the target blah , because the first target is the default target
  • blah requires blah.o , so make searches for the blah.o target
  • blah.o requires blah.c , so make searches for the blah.c target
  • blah.c has no dependencies, so the echo command is run
  • The cc -c command is then run, because all of the blah.o dependencies are finished
  • The top cc command is run, because all the blah dependencies are finished
  • That's it: blah is a compiled c program

If you delete blah.c , all three targets will be rerun. If you edit it (and thus change the timestamp to newer than blah.o ), the first two targets will run. If you run touch blah.o (and thus change the timestamp to newer than blah ), then only the first target will run. If you change nothing, none of the targets will run. Try it out!

This next example doesn't do anything new, but is nontheless a good additional example. It will always run both targets, because some_file depends on other_file , which is never created.

clean is often used as a target that removes the output of other targets, but it is not a special word in Make. You can run make and make clean on this to create and delete some_file .

Note that clean is doing two new things here:

  • It's a target that is not first (the default), and not a prerequisite. That means it'll never run unless you explicitly call make clean
  • It's not intended to be a filename. If you happen to have a file named clean , this target won't run, which is not what we want. See .PHONY later in this tutorial on how to fix this

Variables can only be strings. You'll typically want to use := , but = also works. See Variables Pt 2 .

Here's an example of using variables:

Single or double quotes have no meaning to Make. They are simply characters that are assigned to the variable. Quotes are useful to shell/bash, though, and you need them in commands like printf . In this example, the two commands behave the same:

Reference variables using either ${} or $()

Making multiple targets and you want all of them to run? Make an all target. Since this is the first rule listed, it will run by default if make is called without specifying a target.

When there are multiple targets for a rule, the commands will be run for each target. $@ is an automatic variable that contains the target name.

Both * and % are called wildcards in Make, but they mean entirely different things. * searches your filesystem for matching filenames. I suggest that you always wrap it in the wildcard function, because otherwise you may fall into a common pitfall described below.

* may be used in the target, prerequisites, or in the wildcard function.

Danger: * may not be directly used in a variable definitions

Danger: When * matches no files, it is left as it is (unless run in the wildcard function)

% is really useful, but is somewhat confusing because of the variety of situations it can be used in.

  • When used in "matching" mode, it matches one or more characters in a string. This match is called the stem.
  • When used in "replacing" mode, it takes the stem that was matched and replaces that in a string.
  • % is most often used in rule definitions and in some specific functions.

See these sections on examples of it being used:

There are many automatic variables , but often only a few show up:

Make loves c compilation. And every time it expresses its love, things get confusing. Perhaps the most confusing part of Make is the magic/automatic rules that are made. Make calls these "implicit" rules. I don't personally agree with this design decision, and I don't recommend using them, but they're often used and are thus useful to know. Here's a list of implicit rules:

  • Compiling a C program: n.o is made automatically from n.c with a command of the form $(CC) -c $(CPPFLAGS) $(CFLAGS) $^ -o $@
  • Compiling a C++ program: n.o is made automatically from n.cc or n.cpp with a command of the form $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $^ -o $@
  • Linking a single object file: n is made automatically from n.o by running the command $(CC) $(LDFLAGS) $^ $(LOADLIBES) $(LDLIBS) -o $@

The important variables used by implicit rules are:

  • CC : Program for compiling C programs; default cc
  • CXX : Program for compiling C++ programs; default g++
  • CFLAGS : Extra flags to give to the C compiler
  • CXXFLAGS : Extra flags to give to the C++ compiler
  • CPPFLAGS : Extra flags to give to the C preprocessor
  • LDFLAGS : Extra flags to give to compilers when they are supposed to invoke the linker

Let's see how we can now build a C program without ever explicitly telling Make how to do the compililation:

Static pattern rules are another way to write less in a Makefile, but I'd say are more useful and a bit less "magic". Here's their syntax:

The essence is that the given target is matched by the target-pattern (via a % wildcard). Whatever was matched is called the stem . The stem is then substituted into the prereq-pattern , to generate the target's prereqs.

A typical use case is to compile .c files into .o files. Here's the manual way :

Here's the more efficient way , using a static pattern rule:

While I introduce functions later on, I'll foreshadow what you can do with them. The filter function can be used in Static pattern rules to match the correct files. In this example, I made up the .raw and .result extensions.

Pattern rules are often used but quite confusing. You can look at them as two ways:

  • A way to define your own implicit rules
  • A simpler form of static pattern rules

Let's start with an example first:

Pattern rules contain a '%' in the target. This '%' matches any nonempty string, and the other characters match themselves. ‘%’ in a prerequisite of a pattern rule stands for the same stem that was matched by the ‘%’ in the target.

Here's another example:

Double-Colon Rules are rarely used, but allow multiple rules to be defined for the same target. If these were single colons, a warning would be printed and only the second set of commands would run.

Add an @ before a command to stop it from being printed You can also run make with -s to add an @ before each line

Each command is run in a new shell (or at least the effect is as such)

The default shell is /bin/sh . You can change this by changing the variable SHELL:

If you want a string to have a dollar sign, you can use $$ . This is how to use a shell variable in bash or sh .

Note the differences between Makefile variables and Shell variables in this next example.

Error handling with -k , -i , and -

Add -k when running make to continue running even in the face of errors. Helpful if you want to see all the errors of Make at once. Add a - before a command to suppress the error Add -i to make to have this happen for every command.

Note only: If you ctrl+c make, it will delete the newer targets it just made.

To recursively call a makefile, use the special $(MAKE) instead of make because it will pass the make flags for you and won't itself be affected by them.

When Make starts, it automatically creates Make variables out of all the environment variables that are set when it's executed.

The export directive takes a variable and sets it the environment for all shell commands in all the recipes:

As such, when you run the make command inside of make, you can use the export directive to make it accessible to sub-make commands. In this example, cooly is exported such that the makefile in subdir can use it.

You need to export variables to have them run in the shell as well.

.EXPORT_ALL_VARIABLES exports all variables for you.

There's a nice list of options that can be run from make. Check out --dry-run , --touch , --old-file .

You can have multiple targets to make, i.e. make clean run test runs the clean goal, then run , and then test .

There are two flavors of variables:

  • recursive (use = ) - only looks for the variables when the command is used , not when it's defined .
  • simply expanded (use := ) - like normal imperative programming -- only those defined so far get expanded

Simply expanded (using := ) allows you to append to a variable. Recursive definitions will give an infinite loop error.

?= only sets variables if they have not yet been set

Spaces at the end of a line are not stripped, but those at the start are. To make a variable with a single space, use $(nullstring)

An undefined variable is actually an empty string!

Use += to append

String Substitution is also a really common and useful way to modify variables. Also check out Text Functions and Filename Functions .

You can override variables that come from the command line by using override . Here we ran make with make option_one=hi

The define directive is not a function, though it may look that way. I've seen it used so infrequently that I won't go into details, but it's mainly used for defining canned recipes and also pairs well with the eval function .

define / endef simply creates a variable that is set to a list of commands. Note here that it's a bit different than having a semi-colon between commands, because each is run in a separate shell, as expected.

Variables can be set for specific targets

You can set variables for specific target patterns

ifdef does not expand variable references; it just sees if something is defined at all

This example shows you how to test make flags with findstring and MAKEFLAGS . Run this example with make -i to see it print out the echo statement.

Functions are mainly just for text processing. Call functions with $(fn, arguments) or ${fn, arguments} . Make has a decent amount of builtin functions .

If you want to replace spaces or commas, use variables

Do NOT include spaces in the arguments after the first. That will be seen as part of the string.

$(patsubst pattern,replacement,text) does the following:

"Finds whitespace-separated words in text that match pattern and replaces them with replacement. Here pattern may contain a ‘%’ which acts as a wildcard, matching any number of any characters within a word. If replacement also contains a ‘%’, the ‘%’ is replaced by the text that matched the ‘%’ in pattern. Only the first ‘%’ in the pattern and replacement is treated this way; any subsequent ‘%’ is unchanged." ( GNU docs )

The substitution reference $(text:pattern=replacement) is a shorthand for this.

There's another shorthand that replaces only suffixes: $(text:suffix=replacement) . No % wildcard is used here.

Note: don't add extra spaces for this shorthand. It will be seen as a search or replacement term.

The foreach function looks like this: $(foreach var,list,text) . It converts one list of words (separated by spaces) to another. var is set to each word in list, and text is expanded for each word. This appends an exclamation after each word:

if checks if the first argument is nonempty. If so, runs the second argument, otherwise runs the third.

Make supports creating basic functions. You "define" the function just by creating a variable, but use the parameters $(0) , $(1) , etc. You then call the function with the special call builtin function. The syntax is $(call variable,param,param) . $(0) is the variable, while $(1) , $(2) , etc. are the params.

shell - This calls the shell, but it replaces newlines with spaces!

The include directive tells make to read one or more other makefiles. It's a line in the makefile that looks like this:

This is particularly useful when you use compiler flags like -M that create Makefiles based on the source. For example, if some c files includes a header, that header will be added to a Makefile that's written by gcc. I talk about this more in the Makefile Cookbook

Use vpath to specify where some set of prerequisites exist. The format is vpath <pattern> <directories, space/colon separated> <pattern> can have a % , which matches any zero or more characters. You can also do this globallyish with the variable VPATH

The backslash ("\") character gives us the ability to use multiple lines when the commands are too long

Adding .PHONY to a target will prevent Make from confusing the phony target with a file name. In this example, if the file clean is created, make clean will still be run. Technically, I should have used it in every example with all or clean , but I didn't to keep the examples clean. Additionally, "phony" targets typically have names that are rarely file names, and in practice many people skip this.

The make tool will stop running a rule (and will propogate back to prerequisites) if a command returns a nonzero exit status. DELETE_ON_ERROR will delete the target of a rule if the rule fails in this manner. This will happen for all targets, not just the one it is before like PHONY. It's a good idea to always use this, even though make does not for historical reasons.

Let's go through a really juicy Make example that works well for medium sized projects.

The neat thing about this makefile is it automatically determines dependencies for you. All you have to do is put your C/C++ files in the src/ folder.

makefile default assignment

An official website of the United States government

Here's how you know

Official websites use .gov A .gov website belongs to an official government organization in the United States.

Secure .gov websites use HTTPS A lock ( Lock Locked padlock ) or https:// means you’ve safely connected to the .gov website. Share sensitive information only on official, secure websites.

fhfa's logo

Suspended Counterparty Program

FHFA established the Suspended Counterparty Program to help address the risk to Fannie Mae, Freddie Mac, and the Federal Home Loan Banks (“the regulated entities”) presented by individuals and entities with a history of fraud or other financial misconduct. Under this program, FHFA may issue orders suspending an individual or entity from doing business with the regulated entities.

FHFA maintains a list at this page of each person that is currently suspended under the Suspended Counterparty Program.

This page was last updated on 03/26/2024

Previous: Suppressing Inheritance , Up: How to Use 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 the .EXTRA_PREREQS special target.

Supports grouped target syntax for explicit rules. See Multiple Targets in a Rule .

Has GNU Guile available as an embedded extension language. See GNU Guile Integration .

Supports “job server” enhanced parallel builds. See Parallel Execution .

Supports “job server” enhanced parallel builds using named pipes. See Integrating GNU make .

Supports dynamically loadable objects for creating custom extensions. See Loading Dynamic Objects .

Supports the .NOTINTERMEDIATE special target. See Integrating GNU make .

Supports the .ONESHELL special target. See Using One Shell .

Supports order-only prerequisites. See Types of Prerequisites .

Supports the --output-sync command line option. See Summary of Options .

Supports secondary expansion of prerequisite lists.

Supports exporting make variables to shell functions.

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 Undefining Variables .

Expands to a list of directories that make searches for included makefiles (see Including Other Makefiles ). Note that modifying this variable’s value does not change the list of directories which are searched.

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.

IMAGES

  1. How to Write a Makefile with Ease

    makefile default assignment

  2. gnu make

    makefile default assignment

  3. Makefile Variables Are Complicated

    makefile default assignment

  4. [Microchip][Mplab X IDE v5.35] В Makefile-default.mk есть некоторые

    makefile default assignment

  5. How to Create a Simple Makefile

    makefile default assignment

  6. How to Write a Makefile with Ease

    makefile default assignment

VIDEO

  1. Shared library in C

  2. Create a basic Makefile

  3. C++ Linux Tutorial

  4. Learn Makefile in 30 Seconds #shorts

  5. Case studies in Finance

  6. C++ overloading, default arguments, casting and using; pt2

COMMENTS

  1. Define a Makefile variable using a ENV variable or a default value

    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.

  2. Setting (GNU make)

    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 ...

  3. Using Variables (GNU make)

    However, an explicit assignment in the makefile, or with a command argument, overrides the environment. ... By default, only variables that came from the environment or the command line are passed to recursive invocations. ... GNU make supports some variables that have special properties. MAKEFILE_LIST. Contains the name of each makefile that ...

  4. GNU make

    By default, when make looks for the makefile, it tries the following names, in order: GNUmakefile, makefile and Makefile. Normally you should call your makefile either makefile or Makefile . (We recommend Makefile because it appears prominently near the beginning of a directory listing, right near other important files such as README .)

  5. Using Variables (GNU make)

    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 ...

  6. GNU Make

    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, ... By default, only variables that came from the environment or the command line are passed to recursive ...

  7. Makefiles (GNU make)

    3.1 What Makefiles Contain. Makefiles contain five kinds of things: explicit rules, implicit rules, variable definitions, directives, and comments.Rules, variables, and directives are described at length in later chapters. An explicit rule says when and how to remake one or more files, called the rule's targets.It lists the other files that the targets depend on, called the prerequisites of ...

  8. Understanding and Using Makefile Variables

    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.

  9. 3. Variables and Macros

    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.

  10. Makefile Primer

    Order of Priority of Macro Assignments. The following is the order of priority of macro assignments, from least to greatest: Internal (default) macro definitions. Shell environment variables. Description file macro definitions. Command line macro definitions. Items 2. and 3. can be interchanged by specifying the -e option to make. Macro String ...

  11. Quick Reference (GNU make)

    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:=

  12. Makefile Tutorial By Example

    For each example, put the contents in a file called Makefile, and in that directory run the command make. Let's start with the simplest of Makefiles: hello: echo "Hello, World". Note: Makefiles must be indented using TABs and not spaces or make will fail. Here is the output of running the above example: $ make.

  13. makefile

    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

  14. The Conditional Variable Assignment Operator in a Makefile

    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 message. Fairly straightforward, right? That's all we need to know for using the conditional operator to create an effective Makefile for our projects. 5. Conclusion

  15. GNU make

    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

  16. Goals (GNU make)

    You can manage the selection of the default goal from within your makefile using the .DEFAULT_GOAL variable (see Other Special Variables ). You can also specify a different goal or goals with command line arguments to make. Use the name of the goal as an argument. If you specify several goals, make processes each of them in turn, in the order ...

  17. Computing Makefile variable on assignment

    With GNU Make, you can use := instead of = as in. TMP:=$(shell mktemp -d /tmp/.XXXXX) Edit As pointed out by Novelocrat, the = assignment differs from := assignment in that values assigned using = will be evaluated during substitution (and thus, each time, the variable is used), whereas := assigned variables will have their values evaluated ...

  18. Makefile: Default Value of Variable that is set but has null value

    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.

  19. Suspended Counterparty Program

    FHFA established the Suspended Counterparty Program to help address the risk to Fannie Mae, Freddie Mac, and the Federal Home Loan Banks ("the regulated entities") presented by individuals and entities with a history of fraud or other financial misconduct. Under this program, FHFA may issue orders suspending an individual or entity from ...

  20. gnu make

    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 ...

  21. Special Variables (GNU make)

    6.14 Other Special Variables. GNU make supports some variables that have special properties.. MAKEFILE_LIST. 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.

  22. use environment variable if set otherwise use default value in makefile

    31. 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.