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.

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

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

gmake variable assignment

Learn C++

1.4 — Variable assignment and initialization

In the previous lesson ( 1.3 -- Introduction to objects and variables ), we covered how to define a variable that we can use to store values. In this lesson, we’ll explore how to actually put values into variables and use those values.

As a reminder, here’s a short snippet that first allocates a single integer variable named x , then allocates two more integer variables named y and z :

Variable assignment

After a variable has been defined, you can give it a value (in a separate statement) using the = operator . This process is called assignment , and the = operator is called the assignment operator .

By default, assignment copies the value on the right-hand side of the = operator to the variable on the left-hand side of the operator. This is called copy assignment .

Here’s an example where we use assignment twice:

This prints:

When we assign value 7 to variable width , the value 5 that was there previously is overwritten. Normal variables can only hold one value at a time.

One of the most common mistakes that new programmers make is to confuse the assignment operator ( = ) with the equality operator ( == ). Assignment ( = ) is used to assign a value to a variable. Equality ( == ) is used to test whether two operands are equal in value.

Initialization

One downside of assignment is that it requires at least two statements: one to define the variable, and another to assign the value.

These two steps can be combined. When an object is defined, you can optionally give it an initial value. The process of specifying an initial value for an object is called initialization , and the syntax used to initialize an object is called an initializer .

In the above initialization of variable width , { 5 } is the initializer, and 5 is the initial value.

Different forms of initialization

Initialization in C++ is surprisingly complex, so we’ll present a simplified view here.

There are 6 basic ways to initialize variables in C++:

You may see the above forms written with different spacing (e.g. int d{7}; ). Whether you use extra spaces for readability or not is a matter of personal preference.

Default initialization

When no initializer is provided (such as for variable a above), this is called default initialization . In most cases, default initialization performs no initialization, and leaves a variable with an indeterminate value.

We’ll discuss this case further in lesson ( 1.6 -- Uninitialized variables and undefined behavior ).

Copy initialization

When an initial value is provided after an equals sign, this is called copy initialization . This form of initialization was inherited from C.

Much like copy assignment, this copies the value on the right-hand side of the equals into the variable being created on the left-hand side. In the above snippet, variable width will be initialized with value 5 .

Copy initialization had fallen out of favor in modern C++ due to being less efficient than other forms of initialization for some complex types. However, C++17 remedied the bulk of these issues, and copy initialization is now finding new advocates. You will also find it used in older code (especially code ported from C), or by developers who simply think it looks more natural and is easier to read.

For advanced readers

Copy initialization is also used whenever values are implicitly copied or converted, such as when passing arguments to a function by value, returning from a function by value, or catching exceptions by value.

Direct initialization

When an initial value is provided inside parenthesis, this is called direct initialization .

Direct initialization was initially introduced to allow for more efficient initialization of complex objects (those with class types, which we’ll cover in a future chapter). Just like copy initialization, direct initialization had fallen out of favor in modern C++, largely due to being superseded by list initialization. However, we now know that list initialization has a few quirks of its own, and so direct initialization is once again finding use in certain cases.

Direct initialization is also used when values are explicitly cast to another type.

One of the reasons direct initialization had fallen out of favor is because it makes it hard to differentiate variables from functions. For example:

List initialization

The modern way to initialize objects in C++ is to use a form of initialization that makes use of curly braces. This is called list initialization (or uniform initialization or brace initialization ).

List initialization comes in three forms:

As an aside…

Prior to the introduction of list initialization, some types of initialization required using copy initialization, and other types of initialization required using direct initialization. List initialization was introduced to provide a more consistent initialization syntax (which is why it is sometimes called “uniform initialization”) that works in most cases.

Additionally, list initialization provides a way to initialize objects with a list of values (which is why it is called “list initialization”). We show an example of this in lesson 16.2 -- Introduction to std::vector and list constructors .

List initialization has an added benefit: “narrowing conversions” in list initialization are ill-formed. This means that if you try to brace initialize a variable using a value that the variable can not safely hold, the compiler is required to produce a diagnostic (usually an error). For example:

In the above snippet, we’re trying to assign a number (4.5) that has a fractional part (the .5 part) to an integer variable (which can only hold numbers without fractional parts).

Copy and direct initialization would simply drop the fractional part, resulting in the initialization of value 4 into variable width . Your compiler may optionally warn you about this, since losing data is rarely desired. However, with list initialization, your compiler is required to generate a diagnostic in such cases.

Conversions that can be done without potential data loss are allowed.

To summarize, list initialization is generally preferred over the other initialization forms because it works in most cases (and is therefore most consistent), it disallows narrowing conversions, and it supports initialization with lists of values (something we’ll cover in a future lesson). While you are learning, we recommend sticking with list initialization (or value initialization).

Best practice

Prefer direct list initialization (or value initialization) for initializing your variables.

Author’s note

Bjarne Stroustrup (creator of C++) and Herb Sutter (C++ expert) also recommend using list initialization to initialize your variables.

In modern C++, there are some cases where list initialization does not work as expected. We cover one such case in lesson 16.2 -- Introduction to std::vector and list constructors .

Because of such quirks, some experienced developers now advocate for using a mix of copy, direct, and list initialization, depending on the circumstance. Once you are familiar enough with the language to understand the nuances of each initialization type and the reasoning behind such recommendations, you can evaluate on your own whether you find these arguments persuasive.

Value initialization and zero initialization

When a variable is initialized using empty braces, value initialization takes place. In most cases, value initialization will initialize the variable to zero (or empty, if that’s more appropriate for a given type). In such cases where zeroing occurs, this is called zero initialization .

Q: When should I initialize with { 0 } vs {}?

Use an explicit initialization value if you’re actually using that value.

Use value initialization if the value is temporary and will be replaced.

Initialize your variables

Initialize your variables upon creation. You may eventually find cases where you want to ignore this advice for a specific reason (e.g. a performance critical section of code that uses a lot of variables), and that’s okay, as long as the choice is made deliberately.

Related content

For more discussion on this topic, Bjarne Stroustrup (creator of C++) and Herb Sutter (C++ expert) make this recommendation themselves here .

We explore what happens if you try to use a variable that doesn’t have a well-defined value in lesson 1.6 -- Uninitialized variables and undefined behavior .

Initialize your variables upon creation.

Initializing multiple variables

In the last section, we noted that it is possible to define multiple variables of the same type in a single statement by separating the names with a comma:

We also noted that best practice is to avoid this syntax altogether. However, since you may encounter other code that uses this style, it’s still useful to talk a little bit more about it, if for no other reason than to reinforce some of the reasons you should be avoiding it.

You can initialize multiple variables defined on the same line:

Unfortunately, there’s a common pitfall here that can occur when the programmer mistakenly tries to initialize both variables by using one initialization statement:

In the top statement, variable “a” will be left uninitialized, and the compiler may or may not complain. If it doesn’t, this is a great way to have your program intermittently crash or produce sporadic results. We’ll talk more about what happens if you use uninitialized variables shortly.

The best way to remember that this is wrong is to consider the case of direct initialization or brace initialization:

Because the parenthesis or braces are typically placed right next to the variable name, this makes it seem a little more clear that the value 5 is only being used to initialize variable b and d , not a or c .

Unused initialized variables warnings

Modern compilers will typically generate warnings if a variable is initialized but not used (since this is rarely desirable). And if “treat warnings as errors” is enabled, these warnings will be promoted to errors and cause the compilation to fail.

Consider the following innocent looking program:

When compiling this with the g++ compiler, the following error is generated:

and the program fails to compile.

There are a few easy ways to fix this.

  • If the variable really is unused, then the easiest option is to remove the defintion of x (or comment it out). After all, if it’s not used, then removing it won’t affect anything.
  • Another option is to simply use the variable somewhere:

But this requires some effort to write code that uses it, and has the downside of potentially changing your program’s behavior.

The [[maybe_unused]] attribute C++17

In some cases, neither of the above options are desirable. Consider the case where we have a set of math/physics values that we use in many different programs:

If we use these values a lot, we probably have these saved somewhere and copy/paste/import them all together.

However, in any program where we don’t use all of these values, the compiler will likely complain about each variable that isn’t actually used. While we could go through and remove/comment out the unused ones for each program, this takes time and energy. And later if we need one that we’ve previously removed, we’ll have to go back and re-add it.

To address such cases, C++17 introduced the [[maybe_unused]] attribute, which allows us to tell the compiler that we’re okay with a variable being unused. The compiler will not generate unused variable warnings for such variables.

The following program should generate no warnings/errors:

Additionally, the compiler will likely optimize these variables out of the program, so they have no performance impact.

The [[maybe_unused]] attribute should only be applied selectively to variables that have a specific and legitimate reason for being unused.

In future lessons, we’ll often define variables we don’t use again, in order to demonstrate certain concepts. Making use of [[maybe_unused]] allows us to do so without compilation warnings/errors.

Question #1

What is the difference between initialization and assignment?

Show Solution

Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.

Question #2

What form of initialization should you prefer when you want to initialize a variable with a specific value?

Direct list initialization (aka. direct brace initialization).

Question #3

What are default initialization and value initialization? What is the behavior of each? Which should you prefer?

Default initialization is when a variable initialization has no initializer (e.g. int x; ). In most cases, the variable is left with an indeterminate value.

Value initialization is when a variable initialization has an empty brace (e.g. int x{}; ). In most cases this will perform zero-initialization.

You should prefer value initialization to default initialization.

guest

Next: Running , Previous: Conditionals , Up: Top   [ Contents ][ Index ]

8 Functions for Transforming Text

Functions allow you to do text processing in the makefile to compute the files to operate on or the commands to use in recipes. You use a function in a function call , where you give the name of the function and some text (the arguments ) for the function to operate on. The result of the function’s processing is substituted into the makefile at the point of the call, just as a variable might be substituted.

Next: Text Functions , Previous: Functions , Up: Functions   [ Contents ][ Index ]

8.1 Function Call Syntax

A function call resembles a variable reference. It can appear anywhere a variable reference can appear, and it is expanded using the same rules as variable references. A function call looks like this:

or like this:

Here function is a function name; one of a short list of names that are part of make . You can also essentially create your own functions by using the call built-in function.

The arguments are the arguments of the function. They are separated from the function name by one or more spaces or tabs, and if there is more than one argument, then they are separated by commas. Such whitespace and commas are not part of an argument’s value. The delimiters which you use to surround the function call, whether parentheses or braces, can appear in an argument only in matching pairs; the other kind of delimiters may appear singly. If the arguments themselves contain other function calls or variable references, it is wisest to use the same kind of delimiters for all the references; write ‘ $(subst a,b,$(x)) ’ , not ‘ $(subst a,b,${x}) ’ . This is because it is clearer, and because only one type of delimiter is matched to find the end of the reference.

The text written for each argument is processed by substitution of variables and function calls to produce the argument value, which is the text on which the function acts. The substitution is done in the order in which the arguments appear.

Commas and unmatched parentheses or braces cannot appear in the text of an argument as written; leading spaces cannot appear in the text of the first argument as written. These characters can be put into the argument value by variable substitution. First define variables comma and space whose values are isolated comma and space characters, then substitute these variables where such characters are wanted, like this:

Here the subst function replaces each space with a comma, through the value of foo , and substitutes the result.

Next: File Name Functions , Previous: Syntax of Functions , Up: Functions   [ Contents ][ Index ]

8.2 Functions for String Substitution and Analysis

Here are some functions that operate on strings:

Performs a textual replacement on the text text : each occurrence of from is replaced by to . The result is substituted for the function call. For example,

produces the value ‘ fEEt on the strEEt ’.

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.

‘ % ’ characters in patsubst function invocations can be quoted with preceding backslashes (‘ \ ’). Backslashes that would otherwise quote ‘ % ’ characters can be quoted with more backslashes. Backslashes that quote ‘ % ’ characters or other backslashes are removed from the pattern before it is compared file names or has a stem substituted into it. Backslashes that are not in danger of quoting ‘ % ’ characters go unmolested. For example, the pattern the\%weird\\%pattern\\ has ‘ the%weird\ ’ preceding the operative ‘ % ’ character, and ‘ pattern\\ ’ following it. The final two backslashes are left alone because they cannot affect any ‘ % ’ character.

Whitespace between words is folded into single space characters; leading and trailing whitespace is discarded.

For example,

produces the value ‘ x.c.o bar.o ’.

Substitution references (see Substitution References ) are a simpler way to get the effect of the patsubst function:

is equivalent to

The second shorthand simplifies one of the most common uses of patsubst : replacing the suffix at the end of file names.

For example, you might have a list of object files:

To get the list of corresponding source files, you could simply write:

instead of using the general form:

Removes leading and trailing whitespace from string and replaces each internal sequence of one or more whitespace characters with a single space. Thus, ‘ $(strip a b c ) ’ results in ‘ a b c ’ .

The function strip can be very useful when used in conjunction with conditionals. When comparing something with the empty string ‘ ’ using ifeq or ifneq , you usually want a string of just whitespace to match the empty string (see Conditionals ).

Thus, the following may fail to have the desired results:

Replacing the variable reference ‘ $(needs_made) ’ with the function call ‘ $(strip  $(needs_made)) ’ in the ifneq directive would make it more robust.

Searches in for an occurrence of find . If it occurs, the value is find ; otherwise, the value is empty. You can use this function in a conditional to test for the presence of a specific substring in a given string. Thus, the two examples,

produce the values ‘ a ’ and ‘ ’ (the empty string), respectively. See Testing Flags , for a practical application of findstring .

Returns all whitespace-separated words in text that do match any of the pattern words, removing any words that do not match. The patterns are written using ‘ % ’, just like the patterns used in the patsubst function above.

The filter function can be used to separate out different types of strings (such as file names) in a variable. For example:

says that foo depends of foo.c , bar.c , baz.s and ugh.h but only foo.c , bar.c and baz.s should be specified in the command to the compiler.

Returns all whitespace-separated words in text that do not match any of the pattern words, removing the words that do match one or more. This is the exact opposite of the filter function.

For example, given:

the following generates a list which contains all the object files not in ‘ mains ’:

Sorts the words of list in lexical order, removing duplicate words. The output is a list of words separated by single spaces. Thus,

returns the value ‘ bar foo lose ’.

Incidentally, since sort removes duplicate words, you can use it for this purpose even if you don’t care about the sort order.

Returns the n th word of text . The legitimate values of n start from 1. If n is bigger than the number of words in text , the value is empty. For example,

returns ‘ bar ’.

Returns the list of words in text starting with word s and ending with word e (inclusive). The legitimate values of s start from 1; e may start from 0. If s is bigger than the number of words in text , the value is empty. If e is bigger than the number of words in text , words up to the end of text are returned. If s is greater than e , nothing is returned. For example,

returns ‘ bar baz ’.

Returns the number of words in text . Thus, the last word of text is $(word $(words  text ), text ) .

The argument names is regarded as a series of names, separated by whitespace. The value is the first name in the series. The rest of the names are ignored.

produces the result ‘ foo ’. Although $(firstword text ) is the same as $(word 1, text ) , the firstword function is retained for its simplicity.

The argument names is regarded as a series of names, separated by whitespace. The value is the last name in the series.

produces the result ‘ bar ’. Although $(lastword text ) is the same as $(word $(words text ), text ) , the lastword function was added for its simplicity and better performance.

Here is a realistic example of the use of subst and patsubst . Suppose that a makefile uses the VPATH variable to specify a list of directories that make should search for prerequisite files (see VPATH Search Path for All Prerequisites ). This example shows how to tell the C compiler to search for header files in the same list of directories.

The value of VPATH is a list of directories separated by colons, such as ‘ src:../headers ’. First, the subst function is used to change the colons to spaces:

This produces ‘ src ../headers ’. Then patsubst is used to turn each directory name into a ‘ -I ’ flag. These can be added to the value of the variable CFLAGS , which is passed automatically to the C compiler, like this:

The effect is to append the text ‘ -Isrc -I../headers ’ to the previously given value of CFLAGS . The override directive is used so that the new value is assigned even if the previous value of CFLAGS was specified with a command argument (see The override Directive ).

Next: Conditional Functions , Previous: Text Functions , Up: Functions   [ Contents ][ Index ]

8.3 Functions for File Names

Several of the built-in expansion functions relate specifically to taking apart file names or lists of file names.

Each of the following functions performs a specific transformation on a file name. The argument of the function is regarded as a series of file names, separated by whitespace. (Leading and trailing whitespace is ignored.) Each file name in the series is transformed in the same way and the results are concatenated with single spaces between them.

Extracts the directory-part of each file name in names . The directory-part of the file name is everything up through (and including) the last slash in it. If the file name contains no slash, the directory part is the string ‘ ./ ’. For example,

produces the result ‘ src/ ./ ’.

Extracts all but the directory-part of each file name in names . If the file name contains no slash, it is left unchanged. Otherwise, everything through the last slash is removed from it.

A file name that ends with a slash becomes an empty string. This is unfortunate, because it means that the result does not always have the same number of whitespace-separated file names as the argument had; but we do not see any other valid alternative.

produces the result ‘ foo.c hacks ’.

Extracts the suffix of each file name in names . If the file name contains a period, the suffix is everything starting with the last period. Otherwise, the suffix is the empty string. This frequently means that the result will be empty when names is not, and if names contains multiple file names, the result may contain fewer file names.

produces the result ‘ .c .c ’.

Extracts all but the suffix of each file name in names . If the file name contains a period, the basename is everything starting up to (and not including) the last period. Periods in the directory part are ignored. If there is no period, the basename is the entire file name. For example,

produces the result ‘ src/foo src-1.0/bar hacks ’.

The argument names is regarded as a series of names, separated by whitespace; suffix is used as a unit. The value of suffix is appended to the end of each individual name and the resulting larger names are concatenated with single spaces between them. For example,

produces the result ‘ foo.c bar.c ’.

The argument names is regarded as a series of names, separated by whitespace; prefix is used as a unit. The value of prefix is prepended to the front of each individual name and the resulting larger names are concatenated with single spaces between them. For example,

produces the result ‘ src/foo src/bar ’.

Concatenates the two arguments word by word: the two first words (one from each argument) concatenated form the first word of the result, the two second words form the second word of the result, and so on. So the n th word of the result comes from the n th word of each argument. If one argument has more words that the other, the extra words are copied unchanged into the result.

For example, ‘ $(join a b,.c .o) ’ produces ‘ a.c b.o ’.

Whitespace between the words in the lists is not preserved; it is replaced with a single space.

This function can merge the results of the dir and notdir functions, to produce the original list of files which was given to those two functions.

The argument pattern is a file name pattern, typically containing wildcard characters (as in shell file name patterns). The result of wildcard is a space-separated list of the names of existing files that match the pattern. See Using Wildcard Characters in File Names .

For each file name in names return the canonical absolute name. A canonical name does not contain any . or .. components, nor any repeated path separators ( / ) or symlinks. In case of a failure the empty string is returned. Consult the realpath(3) documentation for a list of possible failure causes.

For each file name in names return an absolute name that does not contain any . or .. components, nor any repeated path separators ( / ). Note that, in contrast to realpath function, abspath does not resolve symlinks and does not require the file names to refer to an existing file or directory. Use the wildcard function to test for existence.

Next: Foreach Function , Previous: File Name Functions , Up: Functions   [ Contents ][ Index ]

8.4 Functions for Conditionals

There are three functions that provide conditional expansion. A key aspect of these functions is that not all of the arguments are expanded initially. Only those arguments which need to be expanded, will be expanded.

The if function provides support for conditional expansion in a functional context (as opposed to the GNU make makefile conditionals such as ifeq (see Syntax of Conditionals )).

The first argument, condition , first has all preceding and trailing whitespace stripped, then is expanded. If it expands to any non-empty string, then the condition is considered to be true. If it expands to an empty string, the condition is considered to be false.

If the condition is true then the second argument, then-part , is evaluated and this is used as the result of the evaluation of the entire if function.

If the condition is false then the third argument, else-part , is evaluated and this is the result of the if function. If there is no third argument, the if function evaluates to nothing (the empty string).

Note that only one of the then-part or the else-part will be evaluated, never both. Thus, either can contain side-effects (such as shell function calls, etc.)

The or function provides a “short-circuiting” OR operation. Each argument is expanded, in order. If an argument expands to a non-empty string the processing stops and the result of the expansion is that string. If, after all arguments are expanded, all of them are false (empty), then the result of the expansion is the empty string.

The and function provides a “short-circuiting” AND operation. Each argument is expanded, in order. If an argument expands to an empty string the processing stops and the result of the expansion is the empty string. If all arguments expand to a non-empty string then the result of the expansion is the expansion of the last argument.

Next: File Function , Previous: Conditional Functions , Up: Functions   [ Contents ][ Index ]

8.5 The foreach Function

The foreach function is very different from other functions. It causes one piece of text to be used repeatedly, each time with a different substitution performed on it. It resembles the for command in the shell sh and the foreach command in the C-shell csh .

The syntax of the foreach function is:

The first two arguments, var and list , are expanded before anything else is done; note that the last argument, text , is not expanded at the same time. Then for each word of the expanded value of list , the variable named by the expanded value of var is set to that word, and text is expanded. Presumably text contains references to that variable, so its expansion will be different each time.

The result is that text is expanded as many times as there are whitespace-separated words in list . The multiple expansions of text are concatenated, with spaces between them, to make the result of foreach .

This simple example sets the variable ‘ files ’ to the list of all files in the directories in the list ‘ dirs ’:

Here text is ‘ $(wildcard $(dir)/*) ’. The first repetition finds the value ‘ a ’ for dir , so it produces the same result as ‘ $(wildcard a/*) ’; the second repetition produces the result of ‘ $(wildcard b/*) ’; and the third, that of ‘ $(wildcard c/*) ’.

This example has the same result (except for setting ‘ dirs ’) as the following example:

When text is complicated, you can improve readability by giving it a name, with an additional variable:

Here we use the variable find_files this way. We use plain ‘ = ’ to define a recursively-expanding variable, so that its value contains an actual function call to be re-expanded under the control of foreach ; a simply-expanded variable would not do, since wildcard would be called only once at the time of defining find_files .

The foreach function has no permanent effect on the variable var ; its value and flavor after the foreach function call are the same as they were beforehand. The other values which are taken from list are in effect only temporarily, during the execution of foreach . The variable var is a simply-expanded variable during the execution of foreach . If var was undefined before the foreach function call, it is undefined after the call. See The Two Flavors of Variables .

You must take care when using complex variable expressions that result in variable names because many strange things are valid variable names, but are probably not what you intended. For example,

might be useful if the value of find_files references the variable whose name is ‘ Esta-escrito-en-espanol! ’ (es un nombre bastante largo, no?), but it is more likely to be a mistake.

Next: Call Function , Previous: Foreach Function , Up: Functions   [ Contents ][ Index ]

8.6 The file Function

The file function allows the makefile to write to or read from a file. Two modes of writing are supported: overwrite, where the text is written to the beginning of the file and any existing content is lost, and append, where the text is written to the end of the file, preserving the existing content. In both cases the file is created if it does not exist. It is a fatal error if the file cannot be opened for writing, or if the write operation fails. The file function expands to the empty string when writing to a file.

When reading from a file, the file function expands to the verbatim contents of the file, except that the final newline (if there is one) will be stripped. Attempting to read from a non-existent file expands to the empty string.

The syntax of the file function is:

When the file function is evaluated all its arguments are expanded first, then the file indicated by filename will be opened in the mode described by op .

The operator op can be > to indicate the file will be overwritten with new content, >> to indicate the current contents of the file will be appended to, or < to indicate the contents of the file will be read in. The filename specifies the file to be written to or read from. There may optionally be whitespace between the operator and the file name.

When reading files, it is an error to provide a text value.

When writing files, text will be written to the file. If text does not already end in a newline a final newline will be written (even if text is the empty string). If the text argument is not given at all, nothing will be written.

For example, the file function can be useful if your build system has a limited command line size and your recipe runs a command that can accept arguments from a file as well. Many commands use the convention that an argument prefixed with an @ specifies a file containing more arguments. Then you might write your recipe in this way:

If the command required each argument to be on a separate line of the input file, you might write your recipe like this:

Next: Value Function , Previous: File Function , Up: Functions   [ Contents ][ Index ]

8.7 The call Function

The call function is unique in that it can be used to create new parameterized functions. You can write a complex expression as the value of a variable, then use call to expand it with different values.

The syntax of the call function is:

When make expands this function, it assigns each param to temporary variables $(1) , $(2) , etc. The variable $(0) will contain variable . There is no maximum number of parameter arguments. There is no minimum, either, but it doesn’t make sense to use call with no parameters.

Then variable is expanded as a make variable in the context of these temporary assignments. Thus, any reference to $(1) in the value of variable will resolve to the first param in the invocation of call .

Note that variable is the name of a variable, not a reference to that variable. Therefore you would not normally use a ‘ $ ’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)

If variable is the name of a built-in function, the built-in function is always invoked (even if a make variable by that name also exists).

The call function expands the param arguments before assigning them to temporary variables. This means that variable values containing references to built-in functions that have special expansion rules, like foreach or if , may not work as you expect.

Some examples may make this clearer.

This macro simply reverses its arguments:

Here foo will contain ‘ b a ’.

This one is slightly more interesting: it defines a macro to search for the first instance of a program in PATH :

Now the variable LS contains /bin/ls or similar.

The call function can be nested. Each recursive invocation gets its own local values for $(1) , etc. that mask the values of higher-level call . For example, here is an implementation of a map function:

Now you can map a function that normally takes only one argument, such as origin , to multiple values in one step:

and end up with o containing something like ‘ file file default ’.

A final caution: be careful when adding whitespace to the arguments to call . As with other functions, any whitespace contained in the second and subsequent arguments is kept; this can cause strange effects. It’s generally safest to remove all extraneous whitespace when providing parameters to call .

Next: Eval Function , Previous: Call Function , Up: Functions   [ Contents ][ Index ]

8.8 The value Function

The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.

The syntax of the value function is:

The result of this function is a string containing the value of variable , without any expansion occurring. For example, in this makefile:

The first output line would be ATH , since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.

The value function is most often used in conjunction with the eval function (see Eval Function ).

Next: Origin Function , Previous: Value Function , Up: Functions   [ Contents ][ Index ]

8.9 The eval Function

The eval function is very special: it allows you to define new makefile constructs that are not constant; which are the result of evaluating other variables and functions. The argument to the eval function is expanded, then the results of that expansion are parsed as makefile syntax. The expanded results can define new make variables, targets, implicit or explicit rules, etc.

The result of the eval function is always the empty string; thus, it can be placed virtually anywhere in a makefile without causing syntax errors.

It’s important to realize that the eval argument is expanded twice ; first by the eval function, then the results of that expansion are expanded again when they are parsed as makefile syntax. This means you may need to provide extra levels of escaping for “$” characters when using eval . The value function (see Value Function ) can sometimes be useful in these situations, to circumvent unwanted expansions.

Here is an example of how eval can be used; this example combines a number of concepts and other functions. Although it might seem overly complex to use eval in this example, rather than just writing out the rules, consider two things: first, the template definition (in PROGRAM_template ) could need to be much more complex than it is here; and second, you might put the complex, “generic” part of this example into another makefile, then include it in all the individual makefiles. Now your individual makefiles are quite straightforward.

Next: Flavor Function , Previous: Eval Function , Up: Functions   [ Contents ][ Index ]

8.10 The origin Function

The origin function is unlike most other functions in that it does not operate on the values of variables; it tells you something about a variable. Specifically, it tells you where it came from.

The syntax of the origin function is:

Note that variable is the name of a variable to inquire about, not a reference to that variable. Therefore you would not normally use a ‘ $ ’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)

The result of this function is a string telling you how the variable variable was defined:

if variable was never defined.

if variable has a default definition, as is usual with CC and so on. See Variables Used by Implicit Rules . Note that if you have redefined a default variable, the origin function will return the origin of the later definition.

if variable was inherited from the environment provided to make .

if variable was inherited from the environment provided to make , and is overriding a setting for variable in the makefile as a result of the ‘ -e ’ option (see Summary of Options ).

if variable was defined in a makefile.

if variable was defined on the command line.

if variable was defined with an override directive in a makefile (see The override Directive ).

if variable is an automatic variable defined for the execution of the recipe for each rule (see Automatic Variables ).

This information is primarily useful (other than for your curiosity) to determine if you want to believe the value of a variable. For example, suppose you have a makefile foo that includes another makefile bar . You want a variable bletch to be defined in bar if you run the command ‘ make  -f  bar ’ , even if the environment contains a definition of bletch . However, if foo defined bletch before including bar , you do not want to override that definition. This could be done by using an override directive in foo , giving that definition precedence over the later definition in bar ; unfortunately, the override directive would also override any command line definitions. So, bar could include:

If bletch has been defined from the environment, this will redefine it.

If you want to override a previous definition of bletch if it came from the environment, even under ‘ -e ’, you could instead write:

Here the redefinition takes place if ‘ $(origin bletch) ’ returns either ‘ environment ’ or ‘ environment override ’. See Functions for String Substitution and Analysis .

Next: Make Control Functions , Previous: Origin Function , Up: Functions   [ Contents ][ Index ]

8.11 The flavor Function

The flavor function, like the origin function, does not operate on the values of variables but rather it tells you something about a variable. Specifically, it tells you the flavor of a variable (see The Two Flavors of Variables ).

The syntax of the flavor function is:

The result of this function is a string that identifies the flavor of the variable variable :

if variable is a recursively expanded variable.

if variable is a simply expanded variable.

Next: Shell Function , Previous: Flavor Function , Up: Functions   [ Contents ][ Index ]

8.12 Functions That Control Make

These functions control the way make runs. Generally, they are used to provide information to the user of the makefile or to cause make to stop if some sort of environmental error is detected.

Generates a fatal error where the message is text . Note that the error is generated whenever this function is evaluated. So, if you put it inside a recipe or on the right side of a recursive variable assignment, it won’t be evaluated until later. The text will be expanded before the error is generated.

will generate a fatal error during the read of the makefile if the make variable ERROR1 is defined. Or,

will generate a fatal error while make is running, if the err target is invoked.

This function works similarly to the error function, above, except that make doesn’t exit. Instead, text is expanded and the resulting message is displayed, but processing of the makefile continues.

The result of the expansion of this function is the empty string.

This function does nothing more than print its (expanded) argument(s) to standard output. No makefile name or line number is added. The result of the expansion of this function is the empty string.

Next: Guile Function , Previous: Make Control Functions , Up: Functions   [ Contents ][ Index ]

8.13 The shell Function

The shell function is unlike any other function other than the wildcard function (see The Function wildcard ) in that it communicates with the world outside of make .

The shell function performs the same function that backquotes (‘ ` ’) perform in most shells: it does command expansion . This means that it takes as an argument a shell command and evaluates to the output of the command. The only processing make does on the result is to convert each newline (or carriage-return / newline pair) to a single space. If there is a trailing (carriage-return and) newline it will simply be removed.

The commands run by calls to the shell function are run when the function calls are expanded (see How make Reads a Makefile ). Because this function involves spawning a new shell, you should carefully consider the performance implications of using the shell function within recursively expanded variables vs. simply expanded variables (see The Two Flavors of Variables ).

After the shell function or ‘ != ’ assignment operator is used, its exit status is placed in the .SHELLSTATUS variable.

Here are some examples of the use of the shell function:

sets contents to the contents of the file foo , with a space (rather than a newline) separating each line.

sets files to the expansion of ‘ *.c ’. Unless make is using a very strange shell, this has the same result as ‘ $(wildcard *.c) ’ (as long as at least one ‘ .c ’ file exists).

Previous: Shell Function , Up: Functions   [ Contents ][ Index ]

8.14 The guile Function

If GNU make is built with support for GNU Guile as an embedded extension language then the guile function will be available. The guile function takes one argument which is first expanded by make in the normal fashion, then passed to the GNU Guile evaluator. The result of the evaluator is converted into a string and used as the expansion of the guile function in the makefile. See GNU Guile Integration for details on writing extensions to make in Guile.

You can determine whether GNU Guile support is available by checking the .FEATURES variable for the word guile .

Next: Conditional Variable Assignment , Previous: Simply Expanded Variable Assignment , Up: The Two Flavors of Variables   [ Contents ][ Index ]

6.2.3 Immediately Expanded Variable Assignment

Another form of assignment allows for immediate expansion, but unlike simple assignment the resulting variable is recursive: it will be re-expanded again on every use. In order to avoid unexpected results, after the value is immediately expanded it will automatically be quoted: all instances of $ in the value after expansion will be converted into $$ . This type of assignment uses the ‘ :::= ’ operator. For example,

results in the OUT variable containing the text ‘ first ’, while here:

results in the OUT variable containing the text ‘ one$$two ’. The value is expanded when the variable is assigned, so the result is the expansion of the first value of var , ‘ one$two ’; then the value is re-escaped before the assignment is complete giving the final result of ‘ one$$two ’.

The variable OUT is thereafter considered a recursive variable, so it will be re-expanded when it is used.

This seems functionally equivalent to the ‘ := ’ / ‘ ::= ’ operators, but there are a few differences:

First, after assignment the variable is a normal recursive variable; when you append to it with ‘ += ’ the value on the right-hand side is not expanded immediately. If you prefer the ‘ += ’ operator to expand the right-hand side immediately you should use the ‘ := ’ / ‘ ::= ’ assignment instead.

Second, these variables are slightly less efficient than simply expanded variables since they do need to be re-expanded when they are used, rather than merely copied. However since all variable references are escaped this expansion simply un-escapes the value, it won’t expand any variables or run any functions.

Here is another example:

After this, the value of OUT is the text ‘ one$$two $(var) ’. When this variable is used it will be expanded and the result will be ‘ one$two three$four ’.

This style of assignment is equivalent to the traditional BSD make ‘ := ’ operator; as you can see it works slightly differently than the GNU make ‘ := ’ operator. The :::= operator is added to the POSIX specification in Issue 8 to provide portability.

IMAGES

  1. Variables

    gmake variable assignment

  2. Python 2.7 Use Global Variable In Function

    gmake variable assignment

  3. Python Assign Expression To A Variable Andit Stack

    gmake variable assignment

  4. 02 Variable Assignment

    gmake variable assignment

  5. An In-Depth Introduction To Start Coding in PHP Today

    gmake variable assignment

  6. CCS/TMS320F28379D: Facing error gmake after compiling the imported project from Controlsuit for

    gmake variable assignment

VIDEO

  1. Seat Away Level 679

  2. 11 April 2024

  3. Chúc mọi người nge nhạc vv

  4. April 16, 2024

  5. #jaishreeram #motivation #trendingshorts #sohrts #desiworkwout

  6. 206cc duo ouverture

COMMENTS

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

  2. GNU make

    Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. But an explicit assignment in the makefile, or with a command argument, overrides the environment.

  3. What is the difference between the GNU Makefile variable assignments

    Lazy Set VARIABLE = value Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared. Immediate Set VARIABLE := value Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

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

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

  6. Understanding and Using Makefile Variables

    Command-Line Arguments. 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: override FOO = Hello BAR = World all: @echo "${FOO} ${BAR}"

  7. 3. Variables and Macros

    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. define create-jar. @echo Creating $@...

  8. 1.4

    1.4 — Variable assignment and initialization. Alex May 26, 2024. In the previous lesson ( 1.3 -- Introduction to objects and variables ), we covered how to define a variable that we can use to store values. In this lesson, we'll explore how to actually put values into variables and use those values. As a reminder, here's a short snippet ...

  9. Variables in makefiles

    Variables in makefiles. Variables in a makefile work much the same as variables in a shell script. They are words to which a string of characters can be assigned. Once a string has been assigned to the variable, every reference to the variable in the rest of the makefile is replaced by the string. Variable names are usually chosen to be in all ...

  10. GNU Make

    Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. But an explicit assignment in the makefile, or with a command argument, overrides the environment.

  11. gnu make

    These are prefedined make variables. From the GNU make manual: Every rule that produces an object file uses the variable OUTPUT_OPTION. make defines this variable either to contain '-o $@', or to be empty, depending on a compile-time option. and. make follows the convention that the rule to compile a .x source file uses the variable COMPILE.x.

  12. Functions (GNU make)

    Then variable is expanded as a make variable in the context of these temporary assignments. Thus, any reference to $(1) in the value of variable will resolve to the first param in the invocation of call. Note that variable is the name of a variable, not a reference to that variable.

  13. Top (GNU make)

    5.7.2 Communicating Variables to a Sub-make; 5.7.3 Communicating Options to a Sub-make; 5.7.4 The '--print-directory' Option; 5.8 Defining Canned Recipes; 5.9 Using Empty Recipes; 6 How to Use Variables. 6.1 Basics of Variable References; 6.2 The Two Flavors of Variables. 6.2.1 Recursively Expanded Variable Assignment; 6.2.2 Simply Expanded ...

  14. GNU make

    Then variable is expanded as a make variable in the context of these temporary assignments. Thus, any reference to $(1) in the value of variable will resolve to the first param in the invocation of call. Note that variable is the name of a variable, not a reference to that variable.

  15. How to assign value to variable in Makefile?

    1) Make resolves conditional parts of the makefile before it executes any rule. This: all: LAST_EXIT=0. ifeq ($(LAST_EXIT), 0) #echo a message indicating success. endif. will not report success (unless you set the value of LAST_EXIT somewhere above the rule). 2) Each command in a recipe executes in its own subshell; shell variable values are ...

  16. Conditional Assignment (GNU make)

    Conditional Assignment (GNU make) Previous: Immediately Expanded Variable Assignment , Up: The Two Flavors of Variables [ Contents ][ Index ] 6.2.4 Conditional Variable Assignment

  17. multiple target specific gnu make variables?

    In GNU make you specify the target multiple times to accommodate the required number of variable assignments, like as: x: Y := foo x: Z := bar x: @echo Y=$(Y) -- Z=$(Z) Share. Improve this answer. Follow ... Target-specific make variables. 1. Using environment variables for shorter recipes in GNU Make. 3. Make target with two words. 4.

  18. Environment variable expansion in gmake

    In gmake, if my variable is set to empty, I dont want to enter into if block and variable is set to non empty I want to enter into if block. Please help me in this. ... gmake: How to assign global variable from shell command? 0. make/gmake: given a variable starting with multiple ../, create a variable with one less ../ ...

  19. Immediate Assignment (GNU make)

    First, after assignment the variable is a normal recursive variable; when you append to it with ' += ' the value on the right-hand side is not expanded immediately. If you prefer the ' += ' operator to expand the right-hand side immediately you should use the ' := ' / ' ::= ' assignment instead. Second, these variables are ...