shell instead of the value of `SHELL'. Choosing a Shell in DOS and Windows ................................... Choosing a shell in MS-DOS and MS-Windows is much more complex than on other systems. On MS-DOS, if `SHELL' is not set, the value of the variable `COMSPEC' (which is always set) is used instead. The processing of lines that set the variable `SHELL' in Makefiles is different on MS-DOS. The stock shell, `command.com', is ridiculously limited in its functionality and many users of `make' tend to install a replacement shell. Therefore, on MS-DOS, `make' examines the value of `SHELL', and changes its behavior based on whether it points to a Unix-style or DOS-style shell. This allows reasonable functionality even if `SHELL' points to `command.com'. If `SHELL' points to a Unix-style shell, `make' on MS-DOS additionally checks whether that shell can indeed be found; if not, it ignores the line that sets `SHELL'. In MS-DOS, GNU `make' searches for the shell in the following places: 1. In the precise place pointed to by the value of `SHELL'. For example, if the makefile specifies `SHELL = /bin/sh', `make' will look in the directory `/bin' on the current drive. 2. In the current directory. 3. In each of the directories in the `PATH' variable, in order. In every directory it examines, `make' will first look for the specific file (`sh' in the example above). If this is not found, it will also look in that directory for that file with one of the known extensions which identify executable files. For example `.exe', `.com', `.bat', `.btm', `.sh', and some others. If any of these attempts is successful, the value of `SHELL' will be set to the full pathname of the shell as found. However, if none of these is found, the value of `SHELL' will not be changed, and thus the line that sets it will be effectively ignored. This is so `make' will only support features specific to a Unix-style shell if such a shell is actually installed on the system where `make' runs. Note that this extended search for the shell is limited to the cases where `SHELL' is set from the Makefile; if it is set in the environment or command line, you are expected to set it to the full pathname of the shell, exactly as things are on Unix. The effect of the above DOS-specific processing is that a Makefile that contains `SHELL = /bin/sh' (as many Unix makefiles do), will work on MS-DOS unaltered if you have e.g. `sh.exe' installed in some directory along your `PATH'.  File: make.info, Node: Parallel, Next: Errors, Prev: Execution, Up: Commands 5.4 Parallel Execution ====================== GNU `make' knows how to execute several commands at once. Normally, `make' will execute only one command at a time, waiting for it to finish before executing the next. However, the `-j' or `--jobs' option tells `make' to execute many commands simultaneously. On MS-DOS, the `-j' option has no effect, since that system doesn't support multi-processing. If the `-j' option is followed by an integer, this is the number of commands to execute at once; this is called the number of "job slots". If there is nothing looking like an integer after the `-j' option, there is no limit on the number of job slots. The default number of job slots is one, which means serial execution (one thing at a time). One unpleasant consequence of running several commands simultaneously is that output generated by the commands appears whenever each command sends it, so messages from different commands may be interspersed. Another problem is that two processes cannot both take input from the same device; so to make sure that only one command tries to take input from the terminal at once, `make' will invalidate the standard input streams of all but one running command. This means that attempting to read from standard input will usually be a fatal error (a `Broken pipe' signal) for most child processes if there are several. It is unpredictable which command will have a valid standard input stream (which will come from the terminal, or wherever you redirect the standard input of `make'). The first command run will always get it first, and the first command started after that one finishes will get it next, and so on. We will change how this aspect of `make' works if we find a better alternative. In the mean time, you should not rely on any command using standard input at all if you are using the parallel execution feature; but if you are not using this feature, then standard input works normally in all commands. Finally, handling recursive `make' invocations raises issues. For more information on this, see *Note Communicating Options to a Sub-`make': Options/Recursion. If a command fails (is killed by a signal or exits with a nonzero status), and errors are not ignored for that command (*note Errors in Commands: Errors.), the remaining command lines to remake the same target will not be run. If a command fails and the `-k' or `--keep-going' option was not given (*note Summary of Options: Options Summary.), `make' aborts execution. If make terminates for any reason (including a signal) with child processes running, it waits for them to finish before actually exiting. When the system is heavily loaded, you will probably want to run fewer jobs than when it is lightly loaded. You can use the `-l' option to tell `make' to limit the number of jobs to run at once, based on the load average. The `-l' or `--max-load' option is followed by a floating-point number. For example, -l 2.5 will not let `make' start more than one job if the load average is above 2.5. The `-l' option with no following number removes the load limit, if one was given with a previous `-l' option. More precisely, when `make' goes to start up a job, and it already has at least one job running, it checks the current load average; if it is not lower than the limit given with `-l', `make' waits until the load average goes below that limit, or until all the other jobs finish. By default, there is no load limit.  File: make.info, Node: Errors, Next: Interrupts, Prev: Parallel, Up: Commands 5.5 Errors in Commands ====================== After each shell command returns, `make' looks at its exit status. If the command completed successfully, the next command line is executed in a new shell; after the last command line is finished, the rule is finished. If there is an error (the exit status is nonzero), `make' gives up on the current rule, and perhaps on all rules. Sometimes the failure of a certain command does not indicate a problem. For example, you may use the `mkdir' command to ensure that a directory exists. If the directory already exists, `mkdir' will report an error, but you probably want `make' to continue regardless. To ignore errors in a command line, write a `-' at the beginning of the line's text (after the initial tab). The `-' is discarded before the command is passed to the shell for execution. For example, clean: -rm -f *.o This causes `rm' to continue even if it is unable to remove a file. When you run `make' with the `-i' or `--ignore-errors' flag, errors are ignored in all commands of all rules. A rule in the makefile for the special target `.IGNORE' has the same effect, if there are no prerequisites. These ways of ignoring errors are obsolete because `-' is more flexible. When errors are to be ignored, because of either a `-' or the `-i' flag, `make' treats an error return just like success, except that it prints out a message that tells you the status code the command exited with, and says that the error has been ignored. When an error happens that `make' has not been told to ignore, it implies that the current target cannot be correctly remade, and neither can any other that depends on it either directly or indirectly. No further commands will be executed for these targets, since their preconditions have not been achieved. Normally `make' gives up immediately in this circumstance, returning a nonzero status. However, if the `-k' or `--keep-going' flag is specified, `make' continues to consider the other prerequisites of the pending targets, remaking them if necessary, before it gives up and returns nonzero status. For example, after an error in compiling one object file, `make -k' will continue compiling other object files even though it already knows that linking them will be impossible. *Note Summary of Options: Options Summary. The usual behavior assumes that your purpose is to get the specified targets up to date; once `make' learns that this is impossible, it might as well report the failure immediately. The `-k' option says that the real purpose is to test as many of the changes made in the program as possible, perhaps to find several independent problems so that you can correct them all before the next attempt to compile. This is why Emacs' `compile' command passes the `-k' flag by default. Usually when a command fails, if it has changed the target file at all, the file is corrupted and cannot be used--or at least it is not completely updated. Yet the file's time stamp says that it is now up to date, so the next time `make' runs, it will not try to update that file. The situation is just the same as when the command is killed by a signal; *note Interrupts::. So generally the right thing to do is to delete the target file if the command fails after beginning to change the file. `make' will do this if `.DELETE_ON_ERROR' appears as a target. This is almost always what you want `make' to do, but it is not historical practice; so for compatibility, you must explicitly request it.  File: make.info, Node: Interrupts, Next: Recursion, Prev: Errors, Up: Commands 5.6 Interrupting or Killing `make' ================================== If `make' gets a fatal signal while a command is executing, it may delete the target file that the command was supposed to update. This is done if the target file's last-modification time has changed since `make' first checked it. The purpose of deleting the target is to make sure that it is remade from scratch when `make' is next run. Why is this? Suppose you type `Ctrl-c' while a compiler is running, and it has begun to write an object file `foo.o'. The `Ctrl-c' kills the compiler, resulting in an incomplete file whose last-modification time is newer than the source file `foo.c'. But `make' also receives the `Ctrl-c' signal and deletes this incomplete file. If `make' did not do this, the next invocation of `make' would think that `foo.o' did not require updating--resulting in a strange error message from the linker when it tries to link an object file half of which is missing. You can prevent the deletion of a target file in this way by making the special target `.PRECIOUS' depend on it. Before remaking a target, `make' checks to see whether it appears on the prerequisites of `.PRECIOUS', and thereby decides whether the target should be deleted if a signal happens. Some reasons why you might do this are that the target is updated in some atomic fashion, or exists only to record a modification-time (its contents do not matter), or must exist at all times to prevent other sorts of trouble.  File: make.info, Node: Recursion, Next: Sequences, Prev: Interrupts, Up: Commands 5.7 Recursive Use of `make' =========================== Recursive use of `make' means using `make' as a command in a makefile. This technique is useful when you want separate makefiles for various subsystems that compose a larger system. For example, suppose you have a subdirectory `subdir' which has its own makefile, and you would like the containing directory's makefile to run `make' on the subdirectory. You can do it by writing this: subsystem: cd subdir && $(MAKE) or, equivalently, this (*note Summary of Options: Options Summary.): subsystem: $(MAKE) -C subdir You can write recursive `make' commands just by copying this example, but there are many things to know about how they work and why, and about how the sub-`make' relates to the top-level `make'. You may also find it useful to declare targets that invoke recursive `make' commands as `.PHONY' (for more discussion on when this is useful, see *Note Phony Targets::). For your convenience, when GNU `make' starts (after it has processed any `-C' options) it sets the variable `CURDIR' to the pathname of the current working directory. This value is never touched by `make' again: in particular note that if you include files from other directories the value of `CURDIR' does not change. The value has the same precedence it would have if it were set in the makefile (by default, an environment variable `CURDIR' will not override this value). Note that setting this variable has no impact on the operation of `make' (it does not cause `make' to change its working directory, for example). * Menu: * MAKE Variable:: The special effects of using `$(MAKE)'. * Variables/Recursion:: How to communicate variables to a sub-`make'. * Options/Recursion:: How to communicate options to a sub-`make'. * -w Option:: How the `-w' or `--print-directory' option helps debug use of recursive `make' commands.  File: make.info, Node: MAKE Variable, Next: Variables/Recursion, Prev: Recursion, Up: Recursion 5.7.1 How the `MAKE' Variable Works ----------------------------------- Recursive `make' commands should always use the variable `MAKE', not the explicit command name `make', as shown here: subsystem: cd subdir && $(MAKE) The value of this variable is the file name with which `make' was invoked. If this file name was `/bin/make', then the command executed is `cd subdir && /bin/make'. If you use a special version of `make' to run the top-level makefile, the same special version will be executed for recursive invocations. As a special feature, using the variable `MAKE' in the commands of a rule alters the effects of the `-t' (`--touch'), `-n' (`--just-print'), or `-q' (`--question') option. Using the `MAKE' variable has the same effect as using a `+' character at the beginning of the command line. *Note Instead of Executing the Commands: Instead of Execution. This special feature is only enabled if the `MAKE' variable appears directly in the command script: it does not apply if the `MAKE' variable is referenced through expansion of another variable. In the latter case you must use the `+' token to get these special effects. Consider the command `make -t' in the above example. (The `-t' option marks targets as up to date without actually running any commands; see *Note Instead of Execution::.) Following the usual definition of `-t', a `make -t' command in the example would create a file named `subsystem' and do nothing else. What you really want it to do is run `cd subdir && make -t'; but that would require executing the command, and `-t' says not to execute commands. The special feature makes this do what you want: whenever a command line of a rule contains the variable `MAKE', the flags `-t', `-n' and `-q' do not apply to that line. Command lines containing `MAKE' are executed normally despite the presence of a flag that causes most commands not to be run. The usual `MAKEFLAGS' mechanism passes the flags to the sub-`make' (*note Communicating Options to a Sub-`make': Options/Recursion.), so your request to touch the files, or print the commands, is propagated to the subsystem.  File: make.info, Node: Variables/Recursion, Next: Options/Recursion, Prev: MAKE Variable, Up: Recursion 5.7.2 Communicating Variables to a Sub-`make' --------------------------------------------- Variable values of the top-level `make' can be passed to the sub-`make' through the environment by explicit request. These variables are defined in the sub-`make' as defaults, but do not override what is specified in the makefile used by the sub-`make' makefile unless you use the `-e' switch (*note Summary of Options: Options Summary.). To pass down, or "export", a variable, `make' adds the variable and its value to the environment for running each command. The sub-`make', in turn, uses the environment to initialize its table of variable values. *Note Variables from the Environment: Environment. Except by explicit request, `make' exports a variable only if it is either defined in the environment initially or set on the command line, and if its name consists only of letters, numbers, and underscores. Some shells cannot cope with environment variable names consisting of characters other than letters, numbers, and underscores. The value of the `make' variable `SHELL' is not exported. Instead, the value of the `SHELL' variable from the invoking environment is passed to the sub-`make'. You can force `make' to export its value for `SHELL' by using the `export' directive, described below. *Note Choosing the Shell::. The special variable `MAKEFLAGS' is always exported (unless you unexport it). `MAKEFILES' is exported if you set it to anything. `make' automatically passes down variable values that were defined on the command line, by putting them in the `MAKEFLAGS' variable. *Note Options/Recursion::. Variables are _not_ normally passed down if they were created by default by `make' (*note Variables Used by Implicit Rules: Implicit Variables.). The sub-`make' will define these for itself. If you want to export specific variables to a sub-`make', use the `export' directive, like this: export VARIABLE ... If you want to _prevent_ a variable from being exported, use the `unexport' directive, like this: unexport VARIABLE ... In both of these forms, the arguments to `export' and `unexport' are expanded, and so could be variables or functions which expand to a (list of) variable names to be (un)exported. As a convenience, you can define a variable and export it at the same time by doing: export VARIABLE = value has the same result as: VARIABLE = value export VARIABLE and export VARIABLE := value has the same result as: VARIABLE := value export VARIABLE Likewise, export VARIABLE += value is just like: VARIABLE += value export VARIABLE *Note Appending More Text to Variables: Appending. You may notice that the `export' and `unexport' directives work in `make' in the same way they work in the shell, `sh'. If you want all variables to be exported by default, you can use `export' by itself: export This tells `make' that variables which are not explicitly mentioned in an `export' or `unexport' directive should be exported. Any variable given in an `unexport' directive will still _not_ be exported. If you use `export' by itself to export variables by default, variables whose names contain characters other than alphanumerics and underscores will not be exported unless specifically mentioned in an `export' directive. The behavior elicited by an `export' directive by itself was the default in older versions of GNU `make'. If your makefiles depend on this behavior and you want to be compatible with old versions of `make', you can write a rule for the special target `.EXPORT_ALL_VARIABLES' instead of using the `export' directive. This will be ignored by old `make's, while the `export' directive will cause a syntax error. Likewise, you can use `unexport' by itself to tell `make' _not_ to export variables by default. Since this is the default behavior, you would only need to do this if `export' had been used by itself earlier (in an included makefile, perhaps). You *cannot* use `export' and `unexport' by themselves to have variables exported for some commands and not for others. The last `export' or `unexport' directive that appears by itself determines the behavior for the entire run of `make'. As a special feature, the variable `MAKELEVEL' is changed when it is passed down from level to level. This variable's value is a string which is the depth of the level as a decimal number. The value is `0' for the top-level `make'; `1' for a sub-`make', `2' for a sub-sub-`make', and so on. The incrementation happens when `make' sets up the environment for a command. The main use of `MAKELEVEL' is to test it in a conditional directive (*note Conditional Parts of Makefiles: Conditionals.); this way you can write a makefile that behaves one way if run recursively and another way if run directly by you. You can use the variable `MAKEFILES' to cause all sub-`make' commands to use additional makefiles. The value of `MAKEFILES' is a whitespace-separated list of file names. This variable, if defined in the outer-level makefile, is passed down through the environment; then it serves as a list of extra makefiles for the sub-`make' to read before the usual or specified ones. *Note The Variable `MAKEFILES': MAKEFILES Variable.  File: make.info, Node: Options/Recursion, Next: -w Option, Prev: Variables/Recursion, Up: Recursion 5.7.3 Communicating Options to a Sub-`make' ------------------------------------------- Flags such as `-s' and `-k' are passed automatically to the sub-`make' through the variable `MAKEFLAGS'. This variable is set up automatically by `make' to contain the flag letters that `make' received. Thus, if you do `make -ks' then `MAKEFLAGS' gets the value `ks'. As a consequence, every sub-`make' gets a value for `MAKEFLAGS' in its environment. In response, it takes the flags from that value and processes them as if they had been given as arguments. *Note Summary of Options: Options Summary. Likewise variables defined on the command line are passed to the sub-`make' through `MAKEFLAGS'. Words in the value of `MAKEFLAGS' that contain `=', `make' treats as variable definitions just as if they appeared on the command line. *Note Overriding Variables: Overriding. The options `-C', `-f', `-o', and `-W' are not put into `MAKEFLAGS'; these options are not passed down. The `-j' option is a special case (*note Parallel Execution: Parallel.). If you set it to some numeric value `N' and your operating system supports it (most any UNIX system will; others typically won't), the parent `make' and all the sub-`make's will communicate to ensure that there are only `N' jobs running at the same time between them all. Note that any job that is marked recursive (*note Instead of Executing the Commands: Instead of Execution.) doesn't count against the total jobs (otherwise we could get `N' sub-`make's running and have no slots left over for any real work!) If your operating system doesn't support the above communication, then `-j 1' is always put into `MAKEFLAGS' instead of the value you specified. This is because if the `-j' option were passed down to sub-`make's, you would get many more jobs running in parallel than you asked for. If you give `-j' with no numeric argument, meaning to run as many jobs as possible in parallel, this is passed down, since multiple infinities are no more than one. If you do not want to pass the other flags down, you must change the value of `MAKEFLAGS', like this: subsystem: cd subdir && $(MAKE) MAKEFLAGS= The command line variable definitions really appear in the variable `MAKEOVERRIDES', and `MAKEFLAGS' contains a reference to this variable. If you do want to pass flags down normally, but don't want to pass down the command line variable definitions, you can reset `MAKEOVERRIDES' to empty, like this: MAKEOVERRIDES = This is not usually useful to do. However, some systems have a small fixed limit on the size of the environment, and putting so much information into the value of `MAKEFLAGS' can exceed it. If you see the error message `Arg list too long', this may be the problem. (For strict compliance with POSIX.2, changing `MAKEOVERRIDES' does not affect `MAKEFLAGS' if the special target `.POSIX' appears in the makefile. You probably do not care about this.) A similar variable `MFLAGS' exists also, for historical compatibility. It has the same value as `MAKEFLAGS' except that it does not contain the command line variable definitions, and it always begins with a hyphen unless it is empty (`MAKEFLAGS' begins with a hyphen only when it begins with an option that has no single-letter version, such as `--warn-undefined-variables'). `MFLAGS' was traditionally used explicitly in the recursive `make' command, like this: subsystem: cd subdir && $(MAKE) $(MFLAGS) but now `MAKEFLAGS' makes this usage redundant. If you want your makefiles to be compatible with old `make' programs, use this technique; it will work fine with more modern `make' versions too. The `MAKEFLAGS' variable can also be useful if you want to have certain options, such as `-k' (*note Summary of Options: Options Summary.), set each time you run `make'. You simply put a value for `MAKEFLAGS' in your environment. You can also set `MAKEFLAGS' in a makefile, to specify additional flags that should also be in effect for that makefile. (Note that you cannot use `MFLAGS' this way. That variable is set only for compatibility; `make' does not interpret a value you set for it in any way.) When `make' interprets the value of `MAKEFLAGS' (either from the environment or from a makefile), it first prepends a hyphen if the value does not already begin with one. Then it chops the value into words separated by blanks, and parses these words as if they were options given on the command line (except that `-C', `-f', `-h', `-o', `-W', and their long-named versions are ignored; and there is no error for an invalid option). If you do put `MAKEFLAGS' in your environment, you should be sure not to include any options that will drastically affect the actions of `make' and undermine the purpose of makefiles and of `make' itself. For instance, the `-t', `-n', and `-q' options, if put in one of these variables, could have disastrous consequences and would certainly have at least surprising and probably annoying effects.  File: make.info, Node: -w Option, Prev: Options/Recursion, Up: Recursion 5.7.4 The `--print-directory' Option ------------------------------------ If you use several levels of recursive `make' invocations, the `-w' or `--print-directory' option can make the output a lot easier to understand by showing each directory as `make' starts processing it and as `make' finishes processing it. For example, if `make -w' is run in the directory `/u/gnu/make', `make' will print a line of the form: make: Entering directory `/u/gnu/make'. before doing anything else, and a line of the form: make: Leaving directory `/u/gnu/make'. when processing is completed. Normally, you do not need to specify this option because `make' does it for you: `-w' is turned on automatically when you use the `-C' option, and in sub-`make's. `make' will not automatically turn on `-w' if you also use `-s', which says to be silent, or if you use `--no-print-directory' to explicitly disable it.  File: make.info, Node: Sequences, Next: Empty Commands, Prev: Recursion, Up: Commands 5.8 Defining Canned Command Sequences ===================================== When the same sequence of commands is useful in making various targets, you can define it as a canned sequence with the `define' directive, and refer to the canned sequence from the rules for those targets. The canned sequence is actually a variable, so the name must not conflict with other variable names. Here is an example of defining a canned sequence of commands: define run-yacc yacc $(firstword $^) mv y.tab.c $@ endef Here `run-yacc' is the name of the variable being defined; `endef' marks the end of the definition; the lines in between are the commands. The `define' directive does not expand variable references and function calls in the canned sequence; the `$' characters, parentheses, variable names, and so on, all become part of the value of the variable you are defining. *Note Defining Variables Verbatim: Defining, for a complete explanation of `define'. The first command in this example runs Yacc on the first prerequisite of whichever rule uses the canned sequence. The output file from Yacc is always named `y.tab.c'. The second command moves the output to the rule's target file name. To use the canned sequence, substitute the variable into the commands of a rule. You can substitute it like any other variable (*note Basics of Variable References: Reference.). Because variables defined by `define' are recursively expanded variables, all the variable references you wrote inside the `define' are expanded now. For example: foo.c : foo.y $(run-yacc) `foo.y' will be substituted for the variable `$^' when it occurs in `run-yacc''s value, and `foo.c' for `$@'. This is a realistic example, but this particular one is not needed in practice because `make' has an implicit rule to figure out these commands based on the file names involved (*note Using Implicit Rules: Implicit Rules.). In command execution, each line of a canned sequence is treated just as if the line appeared on its own in the rule, preceded by a tab. In particular, `make' invokes a separate subshell for each line. You can use the special prefix characters that affect command lines (`@', `-', and `+') on each line of a canned sequence. *Note Writing the Commands in Rules: Commands. For example, using this canned sequence: define frobnicate @echo "frobnicating target $@" frob-step-1 $< -o $@-step-1 frob-step-2 $@-step-1 -o $@ endef `make' will not echo the first line, the `echo' command. But it _will_ echo the following two command lines. On the other hand, prefix characters on the command line that refers to a canned sequence apply to every line in the sequence. So the rule: frob.out: frob.in @$(frobnicate) does not echo _any_ commands. (*Note Command Echoing: Echoing, for a full explanation of `@'.)  File: make.info, Node: Empty Commands, Prev: Sequences, Up: Commands 5.9 Using Empty Commands ======================== It is sometimes useful to define commands which do nothing. This is done simply by giving a command that consists of nothing but whitespace. For example: target: ; defines an empty command string for `target'. You could also use a line beginning with a tab character to define an empty command string, but this would be confusing because such a line looks empty. You may be wondering why you would want to define a command string that does nothing. The only reason this is useful is to prevent a target from getting implicit commands (from implicit rules or the `.DEFAULT' special target; *note Implicit Rules:: and *note Defining Last-Resort Default Rules: Last Resort.). You may be inclined to define empty command strings for targets that are not actual files, but only exist so that their prerequisites can be remade. However, this is not the best way to do that, because the prerequisites may not be remade properly if the target file actually does exist. *Note Phony Targets: Phony Targets, for a better way to do this.  File: make.info, Node: Using Variables, Next: Conditionals, Prev: Commands, Up: Top 6 How to Use Variables ********************** A "variable" is a name defined in a makefile to represent a string of text, called the variable's "value". These values are substituted by explicit request into targets, prerequisites, commands, and other parts of the makefile. (In some other versions of `make', variables are called "macros".) Variables and functions in all parts of a makefile are expanded when read, except for the shell commands in rules, the right-hand sides of variable definitions using `=', and the bodies of variable definitions using the `define' directive. Variables can represent lists of file names, options to pass to compilers, programs to run, directories to look in for source files, directories to write output in, or anything else you can imagine. A variable name may be any sequence of characters not containing `:', `#', `=', or leading or trailing whitespace. However, variable names containing characters other than letters, numbers, and underscores should be avoided, as they may be given special meanings in the future, and with some shells they cannot be passed through the environment to a sub-`make' (*note Communicating Variables to a Sub-`make': Variables/Recursion.). Variable names are case-sensitive. The names `foo', `FOO', and `Foo' all refer to different variables. It is traditional to use upper case letters in variable names, but we recommend using lower case letters for variable names that serve internal purposes in the makefile, and reserving upper case for parameters that control implicit rules or for parameters that the user should override with command options (*note Overriding Variables: Overriding.). A few variables have names that are a single punctuation character or just a few characters. These are the "automatic variables", and they have particular specialized uses. *Note Automatic Variables::. * Menu: * Reference:: How to use the value of a variable. * Flavors:: Variables come in two flavors. * Advanced:: Advanced features for referencing a variable. * Values:: All the ways variables get their values. * Setting:: How to set a variable in the makefile. * Appending:: How to append more text to the old value of a variable. * Override Directive:: How to set a variable in the makefile even if the user has set it with a command argument. * Defining:: An alternate way to set a variable to a verbatim string. * Environment:: Variable values can come from the environment. * Target-specific:: Variable values can be defined on a per-target basis. * Pattern-specific:: Target-specific variable values can be applied to a group of targets that match a pattern.  File: make.info, Node: Reference, Next: Flavors, Prev: Using Variables, Up: Using Variables 6.1 Basics of Variable References ================================= To substitute a variable's value, write a dollar sign followed by the name of the variable in parentheses or braces: either `$(foo)' or `${foo}' is a valid reference to the variable `foo'. This special significance of `$' is why you must write `$$' to have the effect of a single dollar sign in a file name or command. Variable references can be used in any context: targets, prerequisites, commands, most directives, and new variable values. Here is an example of a common case, where a variable holds the names of all the object files in a program: objects = program.o foo.o utils.o program : $(objects) cc -o program $(objects) $(objects) : defs.h Variable references work by strict textual substitution. Thus, the rule foo = c prog.o : prog.$(foo) $(foo)$(foo) -$(foo) prog.$(foo) could be used to compile a C program `prog.c'. Since spaces before the variable value are ignored in variable assignments, the value of `foo' is precisely `c'. (Don't actually write your makefiles this way!) A dollar sign followed by a character other than a dollar sign, open-parenthesis or open-brace treats that single character as the variable name. Thus, you could reference the variable `x' with `$x'. However, this practice is strongly discouraged, except in the case of the automatic variables (*note Automatic Variables::).  File: make.info, Node: Flavors, Next: Advanced, Prev: Reference, Up: Using Variables 6.2 The Two Flavors of Variables ================================ There are two ways that a variable in GNU `make' can have a value; we call them the two "flavors" of variables. The two flavors are distinguished in how they are defined and in what they do when expanded. The first flavor of variable is a "recursively expanded" variable. Variables of this sort are defined by lines using `=' (*note Setting Variables: Setting.) or by the `define' directive (*note Defining Variables Verbatim: Defining.). The value you specify is installed verbatim; if it contains references to other variables, these references are expanded whenever this variable is substituted (in the course of expanding some other string). When this happens, it is called "recursive expansion". For example, foo = $(bar) bar = $(ugh) ugh = Huh? all:;echo $(foo) will echo `Huh?': `$(foo)' expands to `$(bar)' which expands to `$(ugh)' which finally expands to `Huh?'. This flavor of variable is the only sort supported by other versions of `make'. It has its advantages and its disadvantages. An advantage (most would say) is that: CFLAGS = $(include_dirs) -O include_dirs = -Ifoo -Ibar will do what was intended: when `CFLAGS' is expanded in a command, it will expand to `-Ifoo -Ibar -O'. A major disadvantage is that you cannot append something on the end of a variable, as in CFLAGS = $(CFLAGS) -O because it will cause an infinite loop in the variable expansion. (Actually `make' detects the infinite loop and reports an error.) Another disadvantage is that any functions (*note Functions for Transforming Text: Functions.) referenced in the definition will be executed every time the variable is expanded. This makes `make' run slower; worse, it causes the `wildcard' and `shell' functions to give unpredictable results because you cannot easily control when they are called, or even how many times. To avoid all the problems and inconveniences of recursively expanded variables, there is another flavor: simply expanded variables. "Simply expanded variables" are defined by lines using `:=' (*note Setting Variables: Setting.). The value of a simply expanded variable is scanned once and for all, expanding any references to other variables and functions, when the variable is defined. The actual value of the simply expanded variable is the result of expanding the text that you write. It does not contain any references to other variables; it contains their values _as of the time this variable was defined_. Therefore, x := foo y := $(x) bar x := later is equivalent to y := foo bar x := later When a simply expanded variable is referenced, its value is substituted verbatim. Here is a somewhat more complicated example, illustrating the use of `:=' in conjunction with the `shell' function. (*Note The `shell' Function: Shell Function.) This example also shows use of the variable `MAKELEVEL', which is changed when it is passed down from level to level. (*Note Communicating Variables to a Sub-`make': Variables/Recursion, for information about `MAKELEVEL'.) ifeq (0,${MAKELEVEL}) whoami := $(shell whoami) host-type := $(shell arch) MAKE := ${MAKE} host-type=${host-type} whoami=${whoami} endif An advantage of this use of `:=' is that a typical `descend into a directory' command then looks like this: ${subdirs}: ${MAKE} -C $@ all Simply expanded variables generally make complicated makefile programming more predictable because they work like variables in most programming languages. They allow you to redefine a variable using its own value (or its value processed in some way by one of the expansion functions) and to use the expansion functions much more efficiently (*note Functions for Transforming Text: Functions.). You can also use them to introduce controlled leading whitespace into variable values. Leading whitespace characters are discarded from your input before substitution of variable references and function calls; this means you can include leading spaces in a variable value by protecting them with variable references, like this: nullstring := space := $(nullstring) # end of the line Here the value of the variable `space' is precisely one space. The comment `# end of the line' is included here just for clarity. Since trailing space characters are _not_ stripped from variable values, just a space at the end of the line would have the same effect (but be rather hard to read). If you put whitespace at the end of a variable value, it is a good idea to put a comment like that at the end of the line to make your intent clear. Conversely, if you do _not_ want any whitespace characters at the end of your variable value, you must remember not to put a random comment on the end of the line after some whitespace, such as this: dir := /foo/bar # directory to put the frobs in Here the value of the variable `dir' is `/foo/bar ' (with four trailing spaces), which was probably not the intention. (Imagine something like `$(dir)/file' with this definition!) There is another assignment operator for variables, `?='. This is called a conditional variable assignment operator, because it only has an effect if the variable is not yet defined. This statement: FOO ?= bar is exactly equivalent to this (*note The `origin' Function: Origin Function.): ifeq ($(origin FOO), undefined) FOO = bar endif Note that a variable set to an empty value is still defined, so `?=' will not set that variable.  File: make.info, Node: Advanced, Next: Values, Prev: Flavors, Up: Using Variables 6.3 Advanced Features for Reference to Variables ================================================ This section describes some advanced features you can use to reference variables in more flexible ways. * Menu: * Substitution Refs:: Referencing a variable with substitutions on the value. * Computed Names:: Computing the name of the variable to refer to.  File: make.info, Node: Substitution Refs, Next: Computed Names, Prev: Advanced, Up: Advanced 6.3.1 Substitution References ----------------------------- A "substitution reference" substitutes the value of a variable with alterations that you specify. It has the form `$(VAR:A=B)' (or `${VAR:A=B}') and its meaning is to take the value of the variable VAR, replace every A at the end of a word with B in that value, and substitute the resulting string. When we say "at the end of a word", we mean that A must appear either followed by whitespace or at the end of the value in order to be replaced; other occurrences of A in the value are unaltered. For example: foo := a.o b.o c.o bar := $(foo:.o=.c) sets `bar' to `a.c b.c c.c'. *Note Setting Variables: Setting. A substitution reference is actually an abbreviation for use of the `patsubst' expansion function (*note Functions for String Substitution and Analysis: Text Functions.). We provide substitution references as well as `patsubst' for compatibility with other implementations of `make'. Another type of substitution reference lets you use the full power of the `patsubst' function. It has the same form `$(VAR:A=B)' described above, except that now A must contain a single `%' character. This case is equivalent to `$(patsubst A,B,$(VAR))'. *Note Functions for String Substitution and Analysis: Text Functions, for a description of the `patsubst' function. For example: foo := a.o b.o c.o bar := $(foo:%.o=%.c) sets `bar' to `a.c b.c c.c'.  File: make.info, Node: Computed Names, Prev: Substitution Refs, Up: Advanced 6.3.2 Computed Variable Names ----------------------------- Computed variable names are a complicated concept needed only for sophisticated makefile programming. For most purposes you need not consider them, except to know that making a variable with a dollar sign in its name might have strange results. However, if you are the type that wants to understand everything, or you are actually interested in what they do, read on. Variables may be referenced inside the name of a variable. This is called a "computed variable name" or a "nested variable reference". For example, x = y y = z a := $($(x)) defines `a' as `z': the `$(x)' inside `$($(x))' expands to `y', so `$($(x))' expands to `$(y)' which in turn expands to `z'. Here the name of the variable to reference is not stated explicitly; it is computed by expansion of `$(x)'. The reference `$(x)' here is nested within the outer variable reference. The previous example shows two levels of nesting, but any number of levels is possible. For example, here are three levels: x = y y = z z = u a := $($($(x))) Here the innermost `$(x)' expands to `y', so `$($(x))' expands to `$(y)' which in turn expands to `z'; now we have `$(z)', which becomes `u'. References to recursively-expanded variables within a variable name are reexpanded in the usual fashion. For example: x = $(y) y = z z = Hello a := $($(x)) defines `a' as `Hello': `$($(x))' becomes `$($(y))' which becomes `$(z)' which becomes `Hello'. Nested variable references can also contain modified references and function invocations (*note Functions for Transforming Text: Functions.), just like any other reference. For example, using the `subst' function (*note Functions for String Substitution and Analysis: Text Functions.): x = variable1 variable2 := Hello y = $(subst 1,2,$(x)) z = y a := $($($(z))) eventually defines `a' as `Hello'. It is doubtful that anyone would ever want to write a nested reference as convoluted as this one, but it works: `$($($(z)))' expands to `$($(y))' which becomes `$($(subst 1,2,$(x)))'. This gets the value `variable1' from `x' and changes it by substitution to `variable2', so that the entire string becomes `$(variable2)', a simple variable reference whose value is `Hello'. A computed variable name need not consist entirely of a single variable reference. It can contain several variable references, as well as some invariant text. For example, a_dirs := dira dirb 1_dirs := dir1 dir2 a_files := filea fileb 1_files := file1 file2 ifeq "$(use_a)" "yes" a1 := a else a1 := 1 endif ifeq "$(use_dirs)" "yes" df := dirs else df := files endif dirs := $($(a1)_$(df)) will give `dirs' the same value as `a_dirs', `1_dirs', `a_files' or `1_files' depending on the settings of `use_a' and `use_dirs'. Computed variable names can also be used in substitution references: a_objects := a.o b.o c.o 1_objects := 1.o 2.o 3.o sources := $($(a1)_objects:.o=.c) defines `sources' as either `a.c b.c c.c' or `1.c 2.c 3.c', depending on the value of `a1'. The only restriction on this sort of use of nested variable references is that they cannot specify part of the name of a function to be called. This is because the test for a recognized function name is done before the expansion of nested references. For example, ifdef do_sort func := sort else func := strip endif bar := a d b g q c foo := $($(func) $(bar)) attempts to give `foo' the value of the variable `sort a d b g q c' or `strip a d b g q c', rather than giving `a d b g q c' as the argument to either the `sort' or the `strip' function. This restriction could be removed in the future if that change is shown to be a good idea. You can also use computed variable names in the left-hand side of a variable assignment, or in a `define' directive, as in: dir = foo $(dir)_sources := $(wildcard $(dir)/*.c) define $(dir)_print lpr $($(dir)_sources) endef This example defines the variables `dir', `foo_sources', and `foo_print'. Note that "nested variable references" are quite different from "recursively expanded variables" (*note The Two Flavors of Variables: Flavors.), though both are used together in complex ways when doing makefile programming.  File: make.info, Node: Values, Next: Setting, Prev: Advanced, Up: Using Variables 6.4 How Variables Get Their Values ================================== Variables can get values in several different ways: * You can specify an overriding value when you run `make'. *Note Overriding Variables: Overriding. * You can specify a value in the makefile, either with an assignment (*note Setting Variables: Setting.) or with a verbatim definition (*note Defining Variables Verbatim: Defining.). * Variables in the environment become `make' variables. *Note Variables from the Environment: Environment. * Several "automatic" variables are given new values for each rule. Each of these has a single conventional use. *Note Automatic Variables::. * Several variables have constant initial values. *Note Variables Used by Implicit Rules: Implicit Variables.  File: make.info, Node: Setting, Next: Appending, Prev: Values, Up: Using Variables 6.5 Setting Variables ===================== To set a variable from the makefile, write a line starting with the variable name followed by `=' or `:='. Whatever follows the `=' or `:=' on the line becomes the value. For example, objects = main.o foo.o bar.o utils.o defines a variable named `objects'. Whitespace around the variable name and immediately after the `=' is ignored. Variables defined with `=' are "recursively expanded" variables. Variables defined with `:=' are "simply expanded" variables; these definitions can contain variable references which will be expanded before the definition is made. *Note The Two Flavors of Variables: Flavors. The variable name may contain function and variable references, which are expanded when the line is read to find the actual variable name to use. There is no limit on the length of the value of a variable except the amount of swapping space on the computer. When a variable definition is long, it is a good idea to break it into several lines by inserting backslash-newline at convenient places in the definition. This will not affect the functioning of `make', but it will make the makefile easier to read. Most variable names are considered to have the empty string as a value if you have never set them. Several variables have built-in initial values that are not empty, but you can set them in the usual ways (*note Variables Used by Implicit Rules: Implicit Variables.). Several special variables are set automatically to a new value for each rule; these are called the "automatic" variables (*note Automatic Variables::). If you'd like a variable to be set to a value only if it's not already set, then you can use the shorthand operator `?=' instead of `='. These two settings of the variable `FOO' are identical (*note The `origin' Function: Origin Function.): FOO ?= bar and ifeq ($(origin FOO), undefined) FOO = bar endif  File: make.info, Node: Appending, Next: Override Directive, Prev: Setting, Up: Using Variables 6.6 Appending More Text to Variables ==================================== Often it is useful to add more text to the value of a variable already defined. You do this with a line containing `+=', like this: objects += another.o This takes the value of the variable `objects', and adds the text `another.o' to it (preceded by a single space). Thus: objects = main.o foo.o bar.o utils.o objects += another.o sets `objects' to `main.o foo.o bar.o utils.o another.o'. Using `+=' is similar to: objects = main.o foo.o bar.o utils.o objects := $(objects) another.o but differs in ways that become important when you use more complex values. When the variable in question has not been defined before, `+=' acts just like normal `=': it defines a recursively-expanded variable. However, when there _is_ a previous definition, exactly what `+=' does depends on what flavor of variable you defined originally. *Note The Two Flavors of Variables: Flavors, for an explanation of the two flavors of variables. When you add to a variable's value with `+=', `make' acts essentially as if you had included the extra text in the initial definition of the variable. If you defined it first with `:=', making it a simply-expanded variable, `+=' adds to that simply-expanded definition, and expands the new text before appending it to the old value just as `:=' does (see *Note Setting Variables: Setting, for a full explanation of `:='). In fact, variable := value variable += more is exactly equivalent to: variable := value variable := $(variable) more On the other hand, when you use `+=' with a variable that you defined first to be recursively-expanded using plain `=', `make' does something a bit different. Recall that when you define a recursively-expanded variable, `make' does not expand the value you set for variable and function references immediately. Instead it stores the text verbatim, and saves these variable and function references to be expanded later, when you refer to the new variable (*note The Two Flavors of Variables: Flavors.). When you use `+=' on a recursively-expanded variable, it is this unexpanded text to which `make' appends the new text you specify. variable = value variable += more is roughly equivalent to: temp = value variable = $(temp) more except that of course it never defines a variable called `temp'. The importance of this comes when the variable's old value contains variable references. Take this common example: CFLAGS = $(includes) -O ... CFLAGS += -pg # enable profiling The first line defines the `CFLAGS' variable with a reference to another variable, `includes'. (`CFLAGS' is used by the rules for C compilation; *note Catalogue of Implicit Rules: Catalogue of Rules.) Using `=' for the definition makes `CFLAGS' a recursively-expanded variable, meaning `$(includes) -O' is _not_ expanded when `make' processes the definition of `CFLAGS'. Thus, `includes' need not be defined yet for its value to take effect. It only has to be defined before any reference to `CFLAGS'. If we tried to append to the value of `CFLAGS' without using `+=', we might do it like this: CFLAGS := $(CFLAGS) -pg # enable profiling This is pretty close, but not quite what we want. Using `:=' redefines `CFLAGS' as a simply-expanded variable; this means `make' expands the text `$(CFLAGS) -pg' before setting the variable. If `includes' is not yet defined, we get ` -O -pg', and a later definition of `includes' will have no effect. Conversely, by using `+=' we set `CFLAGS' to the _unexpanded_ value `$(includes) -O -pg'. Thus we preserve the reference to `includes', so if that variable gets defined at any later point, a reference like `$(CFLAGS)' still uses its value.  File: make.info, Node: Override Directive, Next: Defining, Prev: Appending, Up: Using Variables 6.7 The `override' Directive ============================ If a variable has been set with a command argument (*note Overriding Variables: Overriding.), then ordinary assignments in the makefile are ignored. If you want to set the variable in the makefile even though it was set with a command argument, you can use an `override' directive, which is a line that looks like this: override VARIABLE = VALUE or override VARIABLE := VALUE To append more text to a variable defined on the command line, use: override VARIABLE += MORE TEXT *Note Appending More Text to Variables: Appending. The `override' directive was not invented for escalation in the war between makefiles and command arguments. It was invented so you can alter and add to values that the user specifies with command arguments. For example, suppose you always want the `-g' switch when you run the C compiler, but you would like to allow the user to specify the other switches with a command argument just as usual. You could use this `override' directive: override CFLAGS += -g You can also use `override' directives with `define' directives. This is done as you might expect: override define foo bar endef *Note Defining Variables Verbatim: Defining.  File: make.info, Node: Defining, Next: Environment, Prev: Override Directive, Up: Using Variables 6.8 Defining Variables Verbatim =============================== Another way to set the value of a variable is to use the `define' directive. This directive has an unusual syntax which allows newline characters to be included in the value, which is convenient for defining both canned sequences of commands (*note Defining Canned Command Sequences: Sequences.), and also sections of makefile syntax to use with `eval' (*note Eval Function::). The `define' directive is followed on the same line by the name of the variable and nothing more. The value to give the variable appears on the following lines. The end of the value is marked by a line containing just the word `endef'. Aside from this difference in syntax, `define' works just like `=': it creates a recursively-expanded variable (*note The Two Flavors of Variables: Flavors.). The variable name may contain function and variable references, which are expanded when the directive is read to find the actual variable name to use. You may nest `define' directives: `make' will keep track of nested directives and report an error if they are not all properly closed with `endef'. Note that lines beginning with tab characters are considered part of a command script, so any `define' or `endef' strings appearing on such a line will not be considered `make' operators. define two-lines echo foo echo $(bar) endef The value in an ordinary assignment cannot contain a newline; but the newlines that separate the lines of the value in a `define' become part of the variable's value (except for the final newline which precedes the `endef' and is not considered part of the value). When used in a command script, the previous example is functionally equivalent to this: two-lines = echo foo; echo $(bar) since two commands separated by semicolon behave much like two separate shell commands. However, note that using two separate lines means `make' will invoke the shell twice, running an independent subshell for each line. *Note Command Execution: Execution. If you want variable definitions made with `define' to take precedence over command-line variable definitions, you can use the `override' directive together with `define': override define two-lines foo $(bar) endef *Note The `override' Directive: Override Directive.  File: make.info, Node: Environment, Next: Target-specific, Prev: Defining, Up: Using Variables 6.9 Variables from the Environment ================================== Variables in `make' can come from the environment in which `make' is run. Every environment variable that `make' sees when it starts up is transformed into a `make' variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the `-e' flag is specified, then values from the environment override assignments in the makefile. *Note Summary of Options: Options Summary. But this is not recommended practice.) Thus, by setting the variable `CFLAGS' in your environment, you can cause all C compilations in most makefiles to use the compiler switches you prefer. This is safe for variables with standard or conventional meanings because you know that no makefile will use them for other things. (Note this is not totally reliable; some makefiles set `CFLAGS' explicitly and therefore are not affected by the value in the environment.) When `make' runs a command script, variables defined in the makefile are placed into the environment of that command. This allows you to pass values to sub-`make' invocations (*note Recursive Use of `make': Recursion.). By default, only variables that came from the environment or the command line are passed to recursive invocations. You can use the `export' directive to pass other variables. *Note Communicating Variables to a Sub-`make': Variables/Recursion, for full details. Other use of variables from the environment is not recommended. It is not wise for makefiles to depend for their functioning on environment variables set up outside their control, since this would cause different users to get different results from the same makefile. This is against the whole purpose of most makefiles. Such problems would be especially likely with the variable `SHELL', which is normally present in the environment to specify the user's choice of interactive shell. It would be very undesirable for this choice to affect `make'; so, `make' handles the `SHELL' environment variable in a special way; see *Note Choosing the Shell::.  File: make.info, Node: Target-specific, Next: Pattern-specific, Prev: Environment, Up: Using Variables 6.10 Target-specific Variable Values ==================================== Variable values in `make' are usually global; that is, they are the same regardless of where they are evaluated (unless they're reset, of course). One exception to that is automatic variables (*note Automatic Variables::). The other exception is "target-specific variable values". This feature allows you to define different values for the same variable, based on the target that `make' is currently building. As with automatic variables, these values are only available within the context of a target's command script (and in other target-specific assignments). Set a target-specific variable value like this: TARGET ... : VARIABLE-ASSIGNMENT or like this: TARGET ... : override VARIABLE-ASSIGNMENT or like this: TARGET ... : export VARIABLE-ASSIGNMENT Multiple TARGET values create a target-specific variable value for each member of the target list individually. The VARIABLE-ASSIGNMENT can be any valid form of assignment; recursive (`='), static (`:='), appending (`+='), or conditional (`?='). All variables that appear within the VARIABLE-ASSIGNMENT are evaluated within the context of the target: thus, any previously-defined target-specific variable values will be in effect. Note that this variable is actually distinct from any "global" value: the two variables do not have to have the same flavor (recursive vs. static). Target-specific variables have the same priority as any other makefile variable. Variables provided on the command-line (and in the environment if the `-e' option is in force) will take precedence. Specifying the `override' directive will allow the target-specific variable value to be preferred. There is one more special feature of target-specific variables: when you define a target-specific variable that variable value is also in effect for all prerequisites of this target, and all their prerequisites, etc. (unless those prerequisites override that variable with their own target-specific variable value). So, for example, a statement like this: prog : CFLAGS = -g prog : prog.o foo.o bar.o will set `CFLAGS' to `-g' in the command script for `prog', but it will also set `CFLAGS' to `-g' in the command scripts that create `prog.o', `foo.o', and `bar.o', and any command scripts which create their prerequisites. Be aware that a given prerequisite will only be built once per invocation of make, at most. If the same file is a prerequisite of multiple targets, and each of those targets has a different value for the same target-specific variable, then the first target to be built will cause that prerequisite to be built and the prerequisite will inherit the target-specific value from the first target. It will ignore the target-specific values from any other targets.  File: make.info, Node: Pattern-specific, Prev: Target-specific, Up: Using Variables 6.11 Pattern-specific Variable Values ===================================== In addition to target-specific variable values (*note Target-specific Variable Values: Target-specific.), GNU `make' supports pattern-specific variable values. In this form, the variable is defined for any target that matches the pattern specified. If a target matches more than one pattern, all the matching pattern-specific variables are interpreted in the order in which they were defined in the makefile, and collected together into one set. Variables defined in this way are searched after any target-specific variables defined explicitly for that target, and before target-specific variables defined for the parent target. Set a pattern-specific variable value like this: PATTERN ... : VARIABLE-ASSIGNMENT or like this: PATTERN ... : override VARIABLE-ASSIGNMENT where PATTERN is a %-pattern. As with target-specific variable values, multiple PATTERN values create a pattern-specific vari