1 This is make.info, produced by makeinfo version 4.13 from make.texi.
3 This file documents the GNU `make' utility, which determines
4 automatically which pieces of a large program need to be recompiled,
5 and issues the commands to recompile them.
7 This is Edition 0.72, last updated 9 October 2013, of `The GNU Make
8 Manual', for GNU `make' version 4.0.
10 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
11 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
12 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
14 Permission is granted to copy, distribute and/or modify this
15 document under the terms of the GNU Free Documentation License,
16 Version 1.3 or any later version published by the Free Software
17 Foundation; with no Invariant Sections, with the Front-Cover Texts
18 being "A GNU Manual," and with the Back-Cover Texts as in (a)
19 below. A copy of the license is included in the section entitled
20 "GNU Free Documentation License."
22 (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
23 modify this GNU manual. Buying copies from the FSF supports it in
24 developing GNU and promoting software freedom."
26 INFO-DIR-SECTION Software development
28 * Make: (make). Remake files automatically.
32 File: make.info, Node: Top, Next: Overview, Prev: (dir), Up: (dir)
37 This file documents the GNU `make' utility, which determines
38 automatically which pieces of a large program need to be recompiled,
39 and issues the commands to recompile them.
41 This is Edition 0.72, last updated 9 October 2013, of `The GNU Make
42 Manual', for GNU `make' version 4.0.
44 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
45 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
46 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
48 Permission is granted to copy, distribute and/or modify this
49 document under the terms of the GNU Free Documentation License,
50 Version 1.3 or any later version published by the Free Software
51 Foundation; with no Invariant Sections, with the Front-Cover Texts
52 being "A GNU Manual," and with the Back-Cover Texts as in (a)
53 below. A copy of the license is included in the section entitled
54 "GNU Free Documentation License."
56 (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
57 modify this GNU manual. Buying copies from the FSF supports it in
58 developing GNU and promoting software freedom."
62 * Overview:: Overview of `make'.
63 * Introduction:: An introduction to `make'.
64 * Makefiles:: Makefiles tell `make' what to do.
65 * Rules:: Rules describe when a file must be remade.
66 * Recipes:: Recipes say how to remake a file.
67 * Using Variables:: You can use variables to avoid repetition.
68 * Conditionals:: Use or ignore parts of the makefile based
69 on the values of variables.
70 * Functions:: Many powerful ways to manipulate text.
71 * Invoking make: Running. How to invoke `make' on the command line.
72 * Implicit Rules:: Use implicit rules to treat many files alike,
73 based on their file names.
74 * Archives:: How `make' can update library archives.
75 * Extending make:: Using extensions to `make'.
76 * Features:: Features GNU `make' has over other `make's.
77 * Missing:: What GNU `make' lacks from other `make's.
78 * Makefile Conventions:: Conventions for writing makefiles for
80 * Quick Reference:: A quick reference for experienced users.
81 * Error Messages:: A list of common errors generated by `make'.
82 * Complex Makefile:: A real example of a straightforward,
83 but nontrivial, makefile.
85 * GNU Free Documentation License:: License for copying this manual.
86 * Concept Index:: Index of Concepts.
87 * Name Index:: Index of Functions, Variables, & Directives.
89 --- The Detailed Node Listing ---
93 * Preparing:: Preparing and running `make'.
94 * Reading:: On reading this text.
95 * Bugs:: Problems and bugs.
97 An Introduction to Makefiles
99 * Rule Introduction:: What a rule looks like.
100 * Simple Makefile:: A simple makefile.
101 * How Make Works:: How `make' processes this makefile.
102 * Variables Simplify:: Variables make makefiles simpler.
103 * make Deduces:: Letting `make' deduce the recipes.
104 * Combine By Prerequisite:: Another style of makefile.
105 * Cleanup:: Rules for cleaning the directory.
109 * Makefile Contents:: What makefiles contain.
110 * Makefile Names:: How to name your makefile.
111 * Include:: How one makefile can use another makefile.
112 * MAKEFILES Variable:: The environment can specify extra makefiles.
113 * Remaking Makefiles:: How makefiles get remade.
114 * Overriding Makefiles:: How to override part of one makefile
115 with another makefile.
116 * Reading Makefiles:: How makefiles are parsed.
117 * Secondary Expansion:: How and when secondary expansion is performed.
119 What Makefiles Contain
121 * Splitting Lines:: Splitting long lines in makefiles
125 * Rule Example:: An example explained.
126 * Rule Syntax:: General syntax explained.
127 * Prerequisite Types:: There are two types of prerequisites.
128 * Wildcards:: Using wildcard characters such as `*'.
129 * Directory Search:: Searching other directories for source files.
130 * Phony Targets:: Using a target that is not a real file's name.
131 * Force Targets:: You can use a target without a recipe
132 or prerequisites to mark other targets
134 * Empty Targets:: When only the date matters and the
136 * Special Targets:: Targets with special built-in meanings.
137 * Multiple Targets:: When to make use of several targets in a rule.
138 * Multiple Rules:: How to use several rules with the same target.
139 * Static Pattern:: Static pattern rules apply to multiple targets
140 and can vary the prerequisites according to
142 * Double-Colon:: How to use a special kind of rule to allow
143 several independent rules for one target.
144 * Automatic Prerequisites:: How to automatically generate rules giving
145 prerequisites from source files themselves.
147 Using Wildcard Characters in File Names
149 * Wildcard Examples:: Several examples.
150 * Wildcard Pitfall:: Problems to avoid.
151 * Wildcard Function:: How to cause wildcard expansion where
152 it does not normally take place.
154 Searching Directories for Prerequisites
156 * General Search:: Specifying a search path that applies
157 to every prerequisite.
158 * Selective Search:: Specifying a search path
159 for a specified class of names.
160 * Search Algorithm:: When and how search paths are applied.
161 * Recipes/Search:: How to write recipes that work together
163 * Implicit/Search:: How search paths affect implicit rules.
164 * Libraries/Search:: Directory search for link libraries.
168 * Static Usage:: The syntax of static pattern rules.
169 * Static versus Implicit:: When are they better than implicit rules?
171 Writing Recipes in Rules
173 * Recipe Syntax:: Recipe syntax features and pitfalls.
174 * Echoing:: How to control when recipes are echoed.
175 * Execution:: How recipes are executed.
176 * Parallel:: How recipes can be executed in parallel.
177 * Errors:: What happens after a recipe execution error.
178 * Interrupts:: What happens when a recipe is interrupted.
179 * Recursion:: Invoking `make' from makefiles.
180 * Canned Recipes:: Defining canned recipes.
181 * Empty Recipes:: Defining useful, do-nothing recipes.
185 * Splitting Recipe Lines:: Breaking long recipe lines for readability.
186 * Variables in Recipes:: Using `make' variables in recipes.
190 * One Shell:: One shell for all lines in a recipe.
191 * Choosing the Shell:: How `make' chooses the shell used
196 * Parallel Output:: Handling output during parallel execution
197 * Parallel Input:: Handling input during parallel execution
199 Recursive Use of `make'
201 * MAKE Variable:: The special effects of using `$(MAKE)'.
202 * Variables/Recursion:: How to communicate variables to a sub-`make'.
203 * Options/Recursion:: How to communicate options to a sub-`make'.
204 * -w Option:: How the `-w' or `--print-directory' option
205 helps debug use of recursive `make' commands.
209 * Reference:: How to use the value of a variable.
210 * Flavors:: Variables come in two flavors.
211 * Advanced:: Advanced features for referencing a variable.
212 * Values:: All the ways variables get their values.
213 * Setting:: How to set a variable in the makefile.
214 * Appending:: How to append more text to the old value
216 * Override Directive:: How to set a variable in the makefile even if
217 the user has set it with a command argument.
218 * Multi-Line:: An alternate way to set a variable
219 to a multi-line string.
220 * Undefine Directive:: How to undefine a variable so that it appears
221 as if it was never set.
222 * Environment:: Variable values can come from the environment.
223 * Target-specific:: Variable values can be defined on a per-target
225 * Pattern-specific:: Target-specific variable values can be applied
226 to a group of targets that match a pattern.
227 * Suppressing Inheritance:: Suppress inheritance of variables.
228 * Special Variables:: Variables with special meaning or behavior.
230 Advanced Features for Reference to Variables
232 * Substitution Refs:: Referencing a variable with
233 substitutions on the value.
234 * Computed Names:: Computing the name of the variable to refer to.
236 Conditional Parts of Makefiles
238 * Conditional Example:: Example of a conditional
239 * Conditional Syntax:: The syntax of conditionals.
240 * Testing Flags:: Conditionals that test flags.
242 Functions for Transforming Text
244 * Syntax of Functions:: How to write a function call.
245 * Text Functions:: General-purpose text manipulation functions.
246 * File Name Functions:: Functions for manipulating file names.
247 * Conditional Functions:: Functions that implement conditions.
248 * Foreach Function:: Repeat some text with controlled variation.
249 * File Function:: Write text to a file.
250 * Call Function:: Expand a user-defined function.
251 * Value Function:: Return the un-expanded value of a variable.
252 * Eval Function:: Evaluate the arguments as makefile syntax.
253 * Origin Function:: Find where a variable got its value.
254 * Flavor Function:: Find out the flavor of a variable.
255 * Make Control Functions:: Functions that control how make runs.
256 * Shell Function:: Substitute the output of a shell command.
257 * Guile Function:: Use GNU Guile embedded scripting language.
261 * Makefile Arguments:: How to specify which makefile to use.
262 * Goals:: How to use goal arguments to specify which
263 parts of the makefile to use.
264 * Instead of Execution:: How to use mode flags to specify what
265 kind of thing to do with the recipes
266 in the makefile other than simply
268 * Avoiding Compilation:: How to avoid recompiling certain files.
269 * Overriding:: How to override a variable to specify
270 an alternate compiler and other things.
271 * Testing:: How to proceed past some errors, to
273 * Options Summary:: Summary of Options
277 * Using Implicit:: How to use an existing implicit rule
278 to get the recipes for updating a file.
279 * Catalogue of Rules:: A list of built-in implicit rules.
280 * Implicit Variables:: How to change what predefined rules do.
281 * Chained Rules:: How to use a chain of implicit rules.
282 * Pattern Rules:: How to define new implicit rules.
283 * Last Resort:: How to define a recipe for rules which
285 * Suffix Rules:: The old-fashioned style of implicit rule.
286 * Implicit Rule Search:: The precise algorithm for applying
289 Defining and Redefining Pattern Rules
291 * Pattern Intro:: An introduction to pattern rules.
292 * Pattern Examples:: Examples of pattern rules.
293 * Automatic Variables:: How to use automatic variables in the
294 recipe of implicit rules.
295 * Pattern Match:: How patterns match.
296 * Match-Anything Rules:: Precautions you should take prior to
297 defining rules that can match any
298 target file whatever.
299 * Canceling Rules:: How to override or cancel built-in rules.
301 Using `make' to Update Archive Files
303 * Archive Members:: Archive members as targets.
304 * Archive Update:: The implicit rule for archive member targets.
305 * Archive Pitfalls:: Dangers to watch out for when using archives.
306 * Archive Suffix Rules:: You can write a special kind of suffix rule
307 for updating archives.
309 Implicit Rule for Archive Member Targets
311 * Archive Symbols:: How to update archive symbol directories.
315 * Guile Integration:: Using Guile as an embedded scripting language.
316 * Loading Objects:: Loading dynamic objects as extensions.
318 GNU Guile Integration
320 * Guile Types:: Converting Guile types to `make' strings.
321 * Guile Interface:: Invoking `make' functions from Guile.
322 * Guile Example:: Example using Guile in `make'.
324 Loading Dynamic Objects
326 * load Directive:: Loading dynamic objects as extensions.
327 * Remaking Loaded Objects:: How loaded objects get remade.
328 * Loaded Object API:: Programmatic interface for loaded objects.
329 * Loaded Object Example:: Example of a loaded object
332 File: make.info, Node: Overview, Next: Introduction, Prev: Top, Up: Top
337 The `make' utility automatically determines which pieces of a large
338 program need to be recompiled, and issues commands to recompile them.
339 This manual describes GNU `make', which was implemented by Richard
340 Stallman and Roland McGrath. Development since Version 3.76 has been
341 handled by Paul D. Smith.
343 GNU `make' conforms to section 6.2 of `IEEE Standard 1003.2-1992'
346 Our examples show C programs, since they are most common, but you
347 can use `make' with any programming language whose compiler can be run
348 with a shell command. Indeed, `make' is not limited to programs. You
349 can use it to describe any task where some files must be updated
350 automatically from others whenever the others change.
354 * Preparing:: Preparing and running `make'.
355 * Reading:: On reading this text.
356 * Bugs:: Problems and bugs.
359 File: make.info, Node: Preparing, Next: Reading, Prev: Overview, Up: Overview
361 Preparing and Running Make
362 ==========================
364 To prepare to use `make', you must write a file called the
365 "makefile" that describes the relationships among files in your program
366 and provides commands for updating each file. In a program, typically,
367 the executable file is updated from object files, which are in turn
368 made by compiling source files.
370 Once a suitable makefile exists, each time you change some source
371 files, this simple shell command:
375 suffices to perform all necessary recompilations. The `make' program
376 uses the makefile data base and the last-modification times of the
377 files to decide which of the files need to be updated. For each of
378 those files, it issues the recipes recorded in the data base.
380 You can provide command line arguments to `make' to control which
381 files should be recompiled, or how. *Note How to Run `make': Running.
384 File: make.info, Node: Reading, Next: Bugs, Prev: Preparing, Up: Overview
386 1.1 How to Read This Manual
387 ===========================
389 If you are new to `make', or are looking for a general introduction,
390 read the first few sections of each chapter, skipping the later
391 sections. In each chapter, the first few sections contain introductory
392 or general information and the later sections contain specialized or
393 technical information. The exception is the second chapter, *note An
394 Introduction to Makefiles: Introduction, all of which is introductory.
396 If you are familiar with other `make' programs, see *note Features
397 of GNU `make': Features, which lists the enhancements GNU `make' has,
398 and *note Incompatibilities and Missing Features: Missing, which
399 explains the few things GNU `make' lacks that others have.
401 For a quick summary, see *note Options Summary::, *note Quick
402 Reference::, and *note Special Targets::.
405 File: make.info, Node: Bugs, Prev: Reading, Up: Overview
407 1.2 Problems and Bugs
408 =====================
410 If you have problems with GNU `make' or think you've found a bug,
411 please report it to the developers; we cannot promise to do anything but
412 we might well want to fix it.
414 Before reporting a bug, make sure you've actually found a real bug.
415 Carefully reread the documentation and see if it really says you can do
416 what you're trying to do. If it's not clear whether you should be able
417 to do something or not, report that too; it's a bug in the
420 Before reporting a bug or trying to fix it yourself, try to isolate
421 it to the smallest possible makefile that reproduces the problem. Then
422 send us the makefile and the exact results `make' gave you, including
423 any error or warning messages. Please don't paraphrase these messages:
424 it's best to cut and paste them into your report. When generating this
425 small makefile, be sure to not use any non-free or unusual tools in
426 your recipes: you can almost always emulate what such a tool would do
427 with simple shell commands. Finally, be sure to explain what you
428 expected to occur; this will help us decide whether the problem was
429 really in the documentation.
431 Once you have a precise problem you can report it in one of two ways.
432 Either send electronic mail to:
436 or use our Web-based project management tool, at:
438 http://savannah.gnu.org/projects/make/
440 In addition to the information above, please be careful to include the
441 version number of `make' you are using. You can get this information
442 with the command `make --version'. Be sure also to include the type of
443 machine and operating system you are using. One way to obtain this
444 information is by looking at the final lines of output from the command
448 File: make.info, Node: Introduction, Next: Makefiles, Prev: Overview, Up: Top
450 2 An Introduction to Makefiles
451 ******************************
453 You need a file called a "makefile" to tell `make' what to do. Most
454 often, the makefile tells `make' how to compile and link a program.
456 In this chapter, we will discuss a simple makefile that describes
457 how to compile and link a text editor which consists of eight C source
458 files and three header files. The makefile can also tell `make' how to
459 run miscellaneous commands when explicitly asked (for example, to remove
460 certain files as a clean-up operation). To see a more complex example
461 of a makefile, see *note Complex Makefile::.
463 When `make' recompiles the editor, each changed C source file must
464 be recompiled. If a header file has changed, each C source file that
465 includes the header file must be recompiled to be safe. Each
466 compilation produces an object file corresponding to the source file.
467 Finally, if any source file has been recompiled, all the object files,
468 whether newly made or saved from previous compilations, must be linked
469 together to produce the new executable editor.
473 * Rule Introduction:: What a rule looks like.
474 * Simple Makefile:: A simple makefile.
475 * How Make Works:: How `make' processes this makefile.
476 * Variables Simplify:: Variables make makefiles simpler.
477 * make Deduces:: Letting `make' deduce the recipes.
478 * Combine By Prerequisite:: Another style of makefile.
479 * Cleanup:: Rules for cleaning the directory.
482 File: make.info, Node: Rule Introduction, Next: Simple Makefile, Prev: Introduction, Up: Introduction
484 2.1 What a Rule Looks Like
485 ==========================
487 A simple makefile consists of "rules" with the following shape:
489 TARGET ... : PREREQUISITES ...
494 A "target" is usually the name of a file that is generated by a
495 program; examples of targets are executable or object files. A target
496 can also be the name of an action to carry out, such as `clean' (*note
499 A "prerequisite" is a file that is used as input to create the
500 target. A target often depends on several files.
502 A "recipe" is an action that `make' carries out. A recipe may have
503 more than one command, either on the same line or each on its own line.
504 *Please note:* you need to put a tab character at the beginning of
505 every recipe line! This is an obscurity that catches the unwary. If
506 you prefer to prefix your recipes with a character other than tab, you
507 can set the `.RECIPEPREFIX' variable to an alternate character (*note
508 Special Variables::).
510 Usually a recipe is in a rule with prerequisites and serves to
511 create a target file if any of the prerequisites change. However, the
512 rule that specifies a recipe for the target need not have
513 prerequisites. For example, the rule containing the delete command
514 associated with the target `clean' does not have prerequisites.
516 A "rule", then, explains how and when to remake certain files which
517 are the targets of the particular rule. `make' carries out the recipe
518 on the prerequisites to create or update the target. A rule can also
519 explain how and when to carry out an action. *Note Writing Rules:
522 A makefile may contain other text besides rules, but a simple
523 makefile need only contain rules. Rules may look somewhat more
524 complicated than shown in this template, but all fit the pattern more
528 File: make.info, Node: Simple Makefile, Next: How Make Works, Prev: Rule Introduction, Up: Introduction
530 2.2 A Simple Makefile
531 =====================
533 Here is a straightforward makefile that describes the way an executable
534 file called `edit' depends on eight object files which, in turn, depend
535 on eight C source and three header files.
537 In this example, all the C files include `defs.h', but only those
538 defining editing commands include `command.h', and only low level files
539 that change the editor buffer include `buffer.h'.
541 edit : main.o kbd.o command.o display.o \
542 insert.o search.o files.o utils.o
543 cc -o edit main.o kbd.o command.o display.o \
544 insert.o search.o files.o utils.o
546 main.o : main.c defs.h
548 kbd.o : kbd.c defs.h command.h
550 command.o : command.c defs.h command.h
552 display.o : display.c defs.h buffer.h
554 insert.o : insert.c defs.h buffer.h
556 search.o : search.c defs.h buffer.h
558 files.o : files.c defs.h buffer.h command.h
560 utils.o : utils.c defs.h
563 rm edit main.o kbd.o command.o display.o \
564 insert.o search.o files.o utils.o
566 We split each long line into two lines using backslash/newline; this is
567 like using one long line, but is easier to read. *Note Splitting Long
568 Lines: Splitting Lines.
570 To use this makefile to create the executable file called `edit',
575 To use this makefile to delete the executable file and all the object
576 files from the directory, type:
580 In the example makefile, the targets include the executable file
581 `edit', and the object files `main.o' and `kbd.o'. The prerequisites
582 are files such as `main.c' and `defs.h'. In fact, each `.o' file is
583 both a target and a prerequisite. Recipes include `cc -c main.c' and
586 When a target is a file, it needs to be recompiled or relinked if any
587 of its prerequisites change. In addition, any prerequisites that are
588 themselves automatically generated should be updated first. In this
589 example, `edit' depends on each of the eight object files; the object
590 file `main.o' depends on the source file `main.c' and on the header
593 A recipe may follow each line that contains a target and
594 prerequisites. These recipes say how to update the target file. A tab
595 character (or whatever character is specified by the `.RECIPEPREFIX'
596 variable; *note Special Variables::) must come at the beginning of
597 every line in the recipe to distinguish recipes from other lines in the
598 makefile. (Bear in mind that `make' does not know anything about how
599 the recipes work. It is up to you to supply recipes that will update
600 the target file properly. All `make' does is execute the recipe you
601 have specified when the target file needs to be updated.)
603 The target `clean' is not a file, but merely the name of an action.
604 Since you normally do not want to carry out the actions in this rule,
605 `clean' is not a prerequisite of any other rule. Consequently, `make'
606 never does anything with it unless you tell it specifically. Note that
607 this rule not only is not a prerequisite, it also does not have any
608 prerequisites, so the only purpose of the rule is to run the specified
609 recipe. Targets that do not refer to files but are just actions are
610 called "phony targets". *Note Phony Targets::, for information about
611 this kind of target. *Note Errors in Recipes: Errors, to see how to
612 cause `make' to ignore errors from `rm' or any other command.
615 File: make.info, Node: How Make Works, Next: Variables Simplify, Prev: Simple Makefile, Up: Introduction
617 2.3 How `make' Processes a Makefile
618 ===================================
620 By default, `make' starts with the first target (not targets whose
621 names start with `.'). This is called the "default goal". ("Goals"
622 are the targets that `make' strives ultimately to update. You can
623 override this behavior using the command line (*note Arguments to
624 Specify the Goals: Goals.) or with the `.DEFAULT_GOAL' special variable
625 (*note Other Special Variables: Special Variables.).
627 In the simple example of the previous section, the default goal is to
628 update the executable program `edit'; therefore, we put that rule first.
630 Thus, when you give the command:
634 `make' reads the makefile in the current directory and begins by
635 processing the first rule. In the example, this rule is for relinking
636 `edit'; but before `make' can fully process this rule, it must process
637 the rules for the files that `edit' depends on, which in this case are
638 the object files. Each of these files is processed according to its
639 own rule. These rules say to update each `.o' file by compiling its
640 source file. The recompilation must be done if the source file, or any
641 of the header files named as prerequisites, is more recent than the
642 object file, or if the object file does not exist.
644 The other rules are processed because their targets appear as
645 prerequisites of the goal. If some other rule is not depended on by the
646 goal (or anything it depends on, etc.), that rule is not processed,
647 unless you tell `make' to do so (with a command such as `make clean').
649 Before recompiling an object file, `make' considers updating its
650 prerequisites, the source file and header files. This makefile does not
651 specify anything to be done for them--the `.c' and `.h' files are not
652 the targets of any rules--so `make' does nothing for these files. But
653 `make' would update automatically generated C programs, such as those
654 made by Bison or Yacc, by their own rules at this time.
656 After recompiling whichever object files need it, `make' decides
657 whether to relink `edit'. This must be done if the file `edit' does
658 not exist, or if any of the object files are newer than it. If an
659 object file was just recompiled, it is now newer than `edit', so `edit'
662 Thus, if we change the file `insert.c' and run `make', `make' will
663 compile that file to update `insert.o', and then link `edit'. If we
664 change the file `command.h' and run `make', `make' will recompile the
665 object files `kbd.o', `command.o' and `files.o' and then link the file
669 File: make.info, Node: Variables Simplify, Next: make Deduces, Prev: How Make Works, Up: Introduction
671 2.4 Variables Make Makefiles Simpler
672 ====================================
674 In our example, we had to list all the object files twice in the rule
675 for `edit' (repeated here):
677 edit : main.o kbd.o command.o display.o \
678 insert.o search.o files.o utils.o
679 cc -o edit main.o kbd.o command.o display.o \
680 insert.o search.o files.o utils.o
682 Such duplication is error-prone; if a new object file is added to the
683 system, we might add it to one list and forget the other. We can
684 eliminate the risk and simplify the makefile by using a variable.
685 "Variables" allow a text string to be defined once and substituted in
686 multiple places later (*note How to Use Variables: Using Variables.).
688 It is standard practice for every makefile to have a variable named
689 `objects', `OBJECTS', `objs', `OBJS', `obj', or `OBJ' which is a list
690 of all object file names. We would define such a variable `objects'
691 with a line like this in the makefile:
693 objects = main.o kbd.o command.o display.o \
694 insert.o search.o files.o utils.o
696 Then, each place we want to put a list of the object file names, we can
697 substitute the variable's value by writing `$(objects)' (*note How to
698 Use Variables: Using Variables.).
700 Here is how the complete simple makefile looks when you use a
701 variable for the object files:
703 objects = main.o kbd.o command.o display.o \
704 insert.o search.o files.o utils.o
707 cc -o edit $(objects)
708 main.o : main.c defs.h
710 kbd.o : kbd.c defs.h command.h
712 command.o : command.c defs.h command.h
714 display.o : display.c defs.h buffer.h
716 insert.o : insert.c defs.h buffer.h
718 search.o : search.c defs.h buffer.h
720 files.o : files.c defs.h buffer.h command.h
722 utils.o : utils.c defs.h
728 File: make.info, Node: make Deduces, Next: Combine By Prerequisite, Prev: Variables Simplify, Up: Introduction
730 2.5 Letting `make' Deduce the Recipes
731 =====================================
733 It is not necessary to spell out the recipes for compiling the
734 individual C source files, because `make' can figure them out: it has an
735 "implicit rule" for updating a `.o' file from a correspondingly named
736 `.c' file using a `cc -c' command. For example, it will use the recipe
737 `cc -c main.c -o main.o' to compile `main.c' into `main.o'. We can
738 therefore omit the recipes from the rules for the object files. *Note
739 Using Implicit Rules: Implicit Rules.
741 When a `.c' file is used automatically in this way, it is also
742 automatically added to the list of prerequisites. We can therefore omit
743 the `.c' files from the prerequisites, provided we omit the recipe.
745 Here is the entire example, with both of these changes, and a
746 variable `objects' as suggested above:
748 objects = main.o kbd.o command.o display.o \
749 insert.o search.o files.o utils.o
752 cc -o edit $(objects)
755 kbd.o : defs.h command.h
756 command.o : defs.h command.h
757 display.o : defs.h buffer.h
758 insert.o : defs.h buffer.h
759 search.o : defs.h buffer.h
760 files.o : defs.h buffer.h command.h
767 This is how we would write the makefile in actual practice. (The
768 complications associated with `clean' are described elsewhere. See
769 *note Phony Targets::, and *note Errors in Recipes: Errors.)
771 Because implicit rules are so convenient, they are important. You
772 will see them used frequently.
775 File: make.info, Node: Combine By Prerequisite, Next: Cleanup, Prev: make Deduces, Up: Introduction
777 2.6 Another Style of Makefile
778 =============================
780 When the objects of a makefile are created only by implicit rules, an
781 alternative style of makefile is possible. In this style of makefile,
782 you group entries by their prerequisites instead of by their targets.
783 Here is what one looks like:
785 objects = main.o kbd.o command.o display.o \
786 insert.o search.o files.o utils.o
789 cc -o edit $(objects)
792 kbd.o command.o files.o : command.h
793 display.o insert.o search.o files.o : buffer.h
795 Here `defs.h' is given as a prerequisite of all the object files;
796 `command.h' and `buffer.h' are prerequisites of the specific object
797 files listed for them.
799 Whether this is better is a matter of taste: it is more compact, but
800 some people dislike it because they find it clearer to put all the
801 information about each target in one place.
804 File: make.info, Node: Cleanup, Prev: Combine By Prerequisite, Up: Introduction
806 2.7 Rules for Cleaning the Directory
807 ====================================
809 Compiling a program is not the only thing you might want to write rules
810 for. Makefiles commonly tell how to do a few other things besides
811 compiling a program: for example, how to delete all the object files
812 and executables so that the directory is `clean'.
814 Here is how we could write a `make' rule for cleaning our example
820 In practice, we might want to write the rule in a somewhat more
821 complicated manner to handle unanticipated situations. We would do
828 This prevents `make' from getting confused by an actual file called
829 `clean' and causes it to continue in spite of errors from `rm'. (See
830 *note Phony Targets::, and *note Errors in Recipes: Errors.)
832 A rule such as this should not be placed at the beginning of the
833 makefile, because we do not want it to run by default! Thus, in the
834 example makefile, we want the rule for `edit', which recompiles the
835 editor, to remain the default goal.
837 Since `clean' is not a prerequisite of `edit', this rule will not
838 run at all if we give the command `make' with no arguments. In order
839 to make the rule run, we have to type `make clean'. *Note How to Run
843 File: make.info, Node: Makefiles, Next: Rules, Prev: Introduction, Up: Top
848 The information that tells `make' how to recompile a system comes from
849 reading a data base called the "makefile".
853 * Makefile Contents:: What makefiles contain.
854 * Makefile Names:: How to name your makefile.
855 * Include:: How one makefile can use another makefile.
856 * MAKEFILES Variable:: The environment can specify extra makefiles.
857 * Remaking Makefiles:: How makefiles get remade.
858 * Overriding Makefiles:: How to override part of one makefile
859 with another makefile.
860 * Reading Makefiles:: How makefiles are parsed.
861 * Secondary Expansion:: How and when secondary expansion is performed.
864 File: make.info, Node: Makefile Contents, Next: Makefile Names, Prev: Makefiles, Up: Makefiles
866 3.1 What Makefiles Contain
867 ==========================
869 Makefiles contain five kinds of things: "explicit rules", "implicit
870 rules", "variable definitions", "directives", and "comments". Rules,
871 variables, and directives are described at length in later chapters.
873 * An "explicit rule" says when and how to remake one or more files,
874 called the rule's "targets". It lists the other files that the
875 targets depend on, called the "prerequisites" of the target, and
876 may also give a recipe to use to create or update the targets.
877 *Note Writing Rules: Rules.
879 * An "implicit rule" says when and how to remake a class of files
880 based on their names. It describes how a target may depend on a
881 file with a name similar to the target and gives a recipe to
882 create or update such a target. *Note Using Implicit Rules:
885 * A "variable definition" is a line that specifies a text string
886 value for a variable that can be substituted into the text later.
887 The simple makefile example shows a variable definition for
888 `objects' as a list of all object files (*note Variables Make
889 Makefiles Simpler: Variables Simplify.).
891 * A "directive" is an instruction for `make' to do something special
892 while reading the makefile. These include:
894 * Reading another makefile (*note Including Other Makefiles:
897 * Deciding (based on the values of variables) whether to use or
898 ignore a part of the makefile (*note Conditional Parts of
899 Makefiles: Conditionals.).
901 * Defining a variable from a verbatim string containing
902 multiple lines (*note Defining Multi-Line Variables:
905 * `#' in a line of a makefile starts a "comment". It and the rest
906 of the line are ignored, except that a trailing backslash not
907 escaped by another backslash will continue the comment across
908 multiple lines. A line containing just a comment (with perhaps
909 spaces before it) is effectively blank, and is ignored. If you
910 want a literal `#', escape it with a backslash (e.g., `\#').
911 Comments may appear on any line in the makefile, although they are
912 treated specially in certain situations.
914 You cannot use comments within variable references or function
915 calls: any instance of `#' will be treated literally (rather than
916 as the start of a comment) inside a variable reference or function
919 Comments within a recipe are passed to the shell, just as with any
920 other recipe text. The shell decides how to interpret it: whether
921 or not this is a comment is up to the shell.
923 Within a `define' directive, comments are not ignored during the
924 definition of the variable, but rather kept intact in the value of
925 the variable. When the variable is expanded they will either be
926 treated as `make' comments or as recipe text, depending on the
927 context in which the variable is evaluated.
931 * Splitting Lines:: Splitting long lines in makefiles
934 File: make.info, Node: Splitting Lines, Prev: Makefile Contents, Up: Makefile Contents
936 3.1.1 Splitting Long Lines
937 --------------------------
939 Makefiles use a "line-based" syntax in which the newline character is
940 special and marks the end of a statement. GNU `make' has no limit on
941 the length of a statement line, up to the amount of memory in your
944 However, it is difficult to read lines which are too long to display
945 without wrapping or scrolling. So, you can format your makefiles for
946 readability by adding newlines into the middle of a statement: you do
947 this by escaping the internal newlines with a backslash (`\')
948 character. Where we need to make a distinction we will refer to
949 "physical lines" as a single line ending with a newline (regardless of
950 whether it is escaped) and a "logical line" being a complete statement
951 including all escaped newlines up to the first non-escaped newline.
953 The way in which backslash/newline combinations are handled depends
954 on whether the statement is a recipe line or a non-recipe line.
955 Handling of backslash/newline in a recipe line is discussed later
956 (*note Splitting Recipe Lines::).
958 Outside of recipe lines, backslash/newlines are converted into a
959 single space character. Once that is done, all whitespace around the
960 backslash/newline is condensed into a single space: this includes all
961 whitespace preceding the backslash, all whitespace at the beginning of
962 the line after the backslash/newline, and any consecutive
963 backslash/newline combinations.
965 If the `.POSIX' special target is defined then backslash/newline
966 handling is modified slightly to conform to POSIX.2: first, whitespace
967 preceding a backslash is not removed and second, consecutive
968 backslash/newlines are not condensed.
971 File: make.info, Node: Makefile Names, Next: Include, Prev: Makefile Contents, Up: Makefiles
973 3.2 What Name to Give Your Makefile
974 ===================================
976 By default, when `make' looks for the makefile, it tries the following
977 names, in order: `GNUmakefile', `makefile' and `Makefile'.
979 Normally you should call your makefile either `makefile' or
980 `Makefile'. (We recommend `Makefile' because it appears prominently
981 near the beginning of a directory listing, right near other important
982 files such as `README'.) The first name checked, `GNUmakefile', is not
983 recommended for most makefiles. You should use this name if you have a
984 makefile that is specific to GNU `make', and will not be understood by
985 other versions of `make'. Other `make' programs look for `makefile' and
986 `Makefile', but not `GNUmakefile'.
988 If `make' finds none of these names, it does not use any makefile.
989 Then you must specify a goal with a command argument, and `make' will
990 attempt to figure out how to remake it using only its built-in implicit
991 rules. *Note Using Implicit Rules: Implicit Rules.
993 If you want to use a nonstandard name for your makefile, you can
994 specify the makefile name with the `-f' or `--file' option. The
995 arguments `-f NAME' or `--file=NAME' tell `make' to read the file NAME
996 as the makefile. If you use more than one `-f' or `--file' option, you
997 can specify several makefiles. All the makefiles are effectively
998 concatenated in the order specified. The default makefile names
999 `GNUmakefile', `makefile' and `Makefile' are not checked automatically
1000 if you specify `-f' or `--file'.
1003 File: make.info, Node: Include, Next: MAKEFILES Variable, Prev: Makefile Names, Up: Makefiles
1005 3.3 Including Other Makefiles
1006 =============================
1008 The `include' directive tells `make' to suspend reading the current
1009 makefile and read one or more other makefiles before continuing. The
1010 directive is a line in the makefile that looks like this:
1012 include FILENAMES...
1014 FILENAMES can contain shell file name patterns. If FILENAMES is empty,
1015 nothing is included and no error is printed.
1017 Extra spaces are allowed and ignored at the beginning of the line,
1018 but the first character must not be a tab (or the value of
1019 `.RECIPEPREFIX')--if the line begins with a tab, it will be considered
1020 a recipe line. Whitespace is required between `include' and the file
1021 names, and between file names; extra whitespace is ignored there and at
1022 the end of the directive. A comment starting with `#' is allowed at
1023 the end of the line. If the file names contain any variable or
1024 function references, they are expanded. *Note How to Use Variables:
1027 For example, if you have three `.mk' files, `a.mk', `b.mk', and
1028 `c.mk', and `$(bar)' expands to `bish bash', then the following
1031 include foo *.mk $(bar)
1035 include foo a.mk b.mk c.mk bish bash
1037 When `make' processes an `include' directive, it suspends reading of
1038 the containing makefile and reads from each listed file in turn. When
1039 that is finished, `make' resumes reading the makefile in which the
1042 One occasion for using `include' directives is when several programs,
1043 handled by individual makefiles in various directories, need to use a
1044 common set of variable definitions (*note Setting Variables: Setting.)
1045 or pattern rules (*note Defining and Redefining Pattern Rules: Pattern
1048 Another such occasion is when you want to generate prerequisites from
1049 source files automatically; the prerequisites can be put in a file that
1050 is included by the main makefile. This practice is generally cleaner
1051 than that of somehow appending the prerequisites to the end of the main
1052 makefile as has been traditionally done with other versions of `make'.
1053 *Note Automatic Prerequisites::.
1055 If the specified name does not start with a slash, and the file is
1056 not found in the current directory, several other directories are
1057 searched. First, any directories you have specified with the `-I' or
1058 `--include-dir' option are searched (*note Summary of Options: Options
1059 Summary.). Then the following directories (if they exist) are
1060 searched, in this order: `PREFIX/include' (normally `/usr/local/include'
1061 (1)) `/usr/gnu/include', `/usr/local/include', `/usr/include'.
1063 If an included makefile cannot be found in any of these directories,
1064 a warning message is generated, but it is not an immediately fatal
1065 error; processing of the makefile containing the `include' continues.
1066 Once it has finished reading makefiles, `make' will try to remake any
1067 that are out of date or don't exist. *Note How Makefiles Are Remade:
1068 Remaking Makefiles. Only after it has tried to find a way to remake a
1069 makefile and failed, will `make' diagnose the missing makefile as a
1072 If you want `make' to simply ignore a makefile which does not exist
1073 or cannot be remade, with no error message, use the `-include'
1074 directive instead of `include', like this:
1076 -include FILENAMES...
1078 This acts like `include' in every way except that there is no error
1079 (not even a warning) if any of the FILENAMES (or any prerequisites of
1080 any of the FILENAMES) do not exist or cannot be remade.
1082 For compatibility with some other `make' implementations, `sinclude'
1083 is another name for `-include'.
1085 ---------- Footnotes ----------
1087 (1) GNU Make compiled for MS-DOS and MS-Windows behaves as if PREFIX
1088 has been defined to be the root of the DJGPP tree hierarchy.
1091 File: make.info, Node: MAKEFILES Variable, Next: Remaking Makefiles, Prev: Include, Up: Makefiles
1093 3.4 The Variable `MAKEFILES'
1094 ============================
1096 If the environment variable `MAKEFILES' is defined, `make' considers
1097 its value as a list of names (separated by whitespace) of additional
1098 makefiles to be read before the others. This works much like the
1099 `include' directive: various directories are searched for those files
1100 (*note Including Other Makefiles: Include.). In addition, the default
1101 goal is never taken from one of these makefiles (or any makefile
1102 included by them) and it is not an error if the files listed in
1103 `MAKEFILES' are not found.
1105 The main use of `MAKEFILES' is in communication between recursive
1106 invocations of `make' (*note Recursive Use of `make': Recursion.). It
1107 usually is not desirable to set the environment variable before a
1108 top-level invocation of `make', because it is usually better not to
1109 mess with a makefile from outside. However, if you are running `make'
1110 without a specific makefile, a makefile in `MAKEFILES' can do useful
1111 things to help the built-in implicit rules work better, such as
1112 defining search paths (*note Directory Search::).
1114 Some users are tempted to set `MAKEFILES' in the environment
1115 automatically on login, and program makefiles to expect this to be done.
1116 This is a very bad idea, because such makefiles will fail to work if
1117 run by anyone else. It is much better to write explicit `include'
1118 directives in the makefiles. *Note Including Other Makefiles: Include.
1121 File: make.info, Node: Remaking Makefiles, Next: Overriding Makefiles, Prev: MAKEFILES Variable, Up: Makefiles
1123 3.5 How Makefiles Are Remade
1124 ============================
1126 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1127 files. If a makefile can be remade from other files, you probably want
1128 `make' to get an up-to-date version of the makefile to read in.
1130 To this end, after reading in all makefiles, `make' will consider
1131 each as a goal target and attempt to update it. If a makefile has a
1132 rule which says how to update it (found either in that very makefile or
1133 in another one) or if an implicit rule applies to it (*note Using
1134 Implicit Rules: Implicit Rules.), it will be updated if necessary.
1135 After all makefiles have been checked, if any have actually been
1136 changed, `make' starts with a clean slate and reads all the makefiles
1137 over again. (It will also attempt to update each of them over again,
1138 but normally this will not change them again, since they are already up
1141 If you know that one or more of your makefiles cannot be remade and
1142 you want to keep `make' from performing an implicit rule search on
1143 them, perhaps for efficiency reasons, you can use any normal method of
1144 preventing implicit rule look-up to do so. For example, you can write
1145 an explicit rule with the makefile as the target, and an empty recipe
1146 (*note Using Empty Recipes: Empty Recipes.).
1148 If the makefiles specify a double-colon rule to remake a file with a
1149 recipe but no prerequisites, that file will always be remade (*note
1150 Double-Colon::). In the case of makefiles, a makefile that has a
1151 double-colon rule with a recipe but no prerequisites will be remade
1152 every time `make' is run, and then again after `make' starts over and
1153 reads the makefiles in again. This would cause an infinite loop:
1154 `make' would constantly remake the makefile, and never do anything
1155 else. So, to avoid this, `make' will *not* attempt to remake makefiles
1156 which are specified as targets of a double-colon rule with a recipe but
1159 If you do not specify any makefiles to be read with `-f' or `--file'
1160 options, `make' will try the default makefile names; *note What Name to
1161 Give Your Makefile: Makefile Names. Unlike makefiles explicitly
1162 requested with `-f' or `--file' options, `make' is not certain that
1163 these makefiles should exist. However, if a default makefile does not
1164 exist but can be created by running `make' rules, you probably want the
1165 rules to be run so that the makefile can be used.
1167 Therefore, if none of the default makefiles exists, `make' will try
1168 to make each of them in the same order in which they are searched for
1169 (*note What Name to Give Your Makefile: Makefile Names.) until it
1170 succeeds in making one, or it runs out of names to try. Note that it
1171 is not an error if `make' cannot find or make any makefile; a makefile
1172 is not always necessary.
1174 When you use the `-t' or `--touch' option (*note Instead of
1175 Executing Recipes: Instead of Execution.), you would not want to use an
1176 out-of-date makefile to decide which targets to touch. So the `-t'
1177 option has no effect on updating makefiles; they are really updated
1178 even if `-t' is specified. Likewise, `-q' (or `--question') and `-n'
1179 (or `--just-print') do not prevent updating of makefiles, because an
1180 out-of-date makefile would result in the wrong output for other targets.
1181 Thus, `make -f mfile -n foo' will update `mfile', read it in, and then
1182 print the recipe to update `foo' and its prerequisites without running
1183 it. The recipe printed for `foo' will be the one specified in the
1184 updated contents of `mfile'.
1186 However, on occasion you might actually wish to prevent updating of
1187 even the makefiles. You can do this by specifying the makefiles as
1188 goals in the command line as well as specifying them as makefiles.
1189 When the makefile name is specified explicitly as a goal, the options
1190 `-t' and so on do apply to them.
1192 Thus, `make -f mfile -n mfile foo' would read the makefile `mfile',
1193 print the recipe needed to update it without actually running it, and
1194 then print the recipe needed to update `foo' without running that. The
1195 recipe for `foo' will be the one specified by the existing contents of
1199 File: make.info, Node: Overriding Makefiles, Next: Reading Makefiles, Prev: Remaking Makefiles, Up: Makefiles
1201 3.6 Overriding Part of Another Makefile
1202 =======================================
1204 Sometimes it is useful to have a makefile that is mostly just like
1205 another makefile. You can often use the `include' directive to include
1206 one in the other, and add more targets or variable definitions.
1207 However, it is invalid for two makefiles to give different recipes for
1208 the same target. But there is another way.
1210 In the containing makefile (the one that wants to include the other),
1211 you can use a match-anything pattern rule to say that to remake any
1212 target that cannot be made from the information in the containing
1213 makefile, `make' should look in another makefile. *Note Pattern
1214 Rules::, for more information on pattern rules.
1216 For example, if you have a makefile called `Makefile' that says how
1217 to make the target `foo' (and other targets), you can write a makefile
1218 called `GNUmakefile' that contains:
1224 @$(MAKE) -f Makefile $@
1227 If you say `make foo', `make' will find `GNUmakefile', read it, and
1228 see that to make `foo', it needs to run the recipe `frobnicate > foo'.
1229 If you say `make bar', `make' will find no way to make `bar' in
1230 `GNUmakefile', so it will use the recipe from the pattern rule: `make
1231 -f Makefile bar'. If `Makefile' provides a rule for updating `bar',
1232 `make' will apply the rule. And likewise for any other target that
1233 `GNUmakefile' does not say how to make.
1235 The way this works is that the pattern rule has a pattern of just
1236 `%', so it matches any target whatever. The rule specifies a
1237 prerequisite `force', to guarantee that the recipe will be run even if
1238 the target file already exists. We give the `force' target an empty
1239 recipe to prevent `make' from searching for an implicit rule to build
1240 it--otherwise it would apply the same match-anything rule to `force'
1241 itself and create a prerequisite loop!
1244 File: make.info, Node: Reading Makefiles, Next: Secondary Expansion, Prev: Overriding Makefiles, Up: Makefiles
1246 3.7 How `make' Reads a Makefile
1247 ===============================
1249 GNU `make' does its work in two distinct phases. During the first
1250 phase it reads all the makefiles, included makefiles, etc. and
1251 internalizes all the variables and their values, implicit and explicit
1252 rules, and constructs a dependency graph of all the targets and their
1253 prerequisites. During the second phase, `make' uses these internal
1254 structures to determine what targets will need to be rebuilt and to
1255 invoke the rules necessary to do so.
1257 It's important to understand this two-phase approach because it has a
1258 direct impact on how variable and function expansion happens; this is
1259 often a source of some confusion when writing makefiles. Here we will
1260 present a summary of the phases in which expansion happens for different
1261 constructs within the makefile. We say that expansion is "immediate"
1262 if it happens during the first phase: in this case `make' will expand
1263 any variables or functions in that section of a construct as the
1264 makefile is parsed. We say that expansion is "deferred" if expansion
1265 is not performed immediately. Expansion of a deferred construct is not
1266 performed until either the construct appears later in an immediate
1267 context, or until the second phase.
1269 You may not be familiar with some of these constructs yet. You can
1270 reference this section as you become familiar with them, in later
1276 Variable definitions are parsed as follows:
1278 IMMEDIATE = DEFERRED
1279 IMMEDIATE ?= DEFERRED
1280 IMMEDIATE := IMMEDIATE
1281 IMMEDIATE ::= IMMEDIATE
1282 IMMEDIATE += DEFERRED or IMMEDIATE
1283 IMMEDIATE != IMMEDIATE
1301 define IMMEDIATE ::=
1306 DEFERRED or IMMEDIATE
1313 For the append operator, `+=', the right-hand side is considered
1314 immediate if the variable was previously set as a simple variable (`:='
1315 or `::='), and deferred otherwise.
1317 For the shell assignment operator, `!=', the right-hand side is
1318 evaluated immediately and handed to the shell. The result is stored in
1319 the variable named on the left, and that variable becomes a simple
1320 variable (and will thus be re-evaluated on each reference).
1322 Conditional Directives
1323 ----------------------
1325 Conditional directives are parsed immediately. This means, for
1326 example, that automatic variables cannot be used in conditional
1327 directives, as automatic variables are not set until the recipe for
1328 that rule is invoked. If you need to use automatic variables in a
1329 conditional directive you _must_ move the condition into the recipe and
1330 use shell conditional syntax instead.
1335 A rule is always expanded the same way, regardless of the form:
1337 IMMEDIATE : IMMEDIATE ; DEFERRED
1340 That is, the target and prerequisite sections are expanded
1341 immediately, and the recipe used to construct the target is always
1342 deferred. This general rule is true for explicit rules, pattern rules,
1343 suffix rules, static pattern rules, and simple prerequisite definitions.
1346 File: make.info, Node: Secondary Expansion, Prev: Reading Makefiles, Up: Makefiles
1348 3.8 Secondary Expansion
1349 =======================
1351 In the previous section we learned that GNU `make' works in two
1352 distinct phases: a read-in phase and a target-update phase (*note How
1353 `make' Reads a Makefile: Reading Makefiles.). GNU make also has the
1354 ability to enable a _second expansion_ of the prerequisites (only) for
1355 some or all targets defined in the makefile. In order for this second
1356 expansion to occur, the special target `.SECONDEXPANSION' must be
1357 defined before the first prerequisite list that makes use of this
1360 If that special target is defined then in between the two phases
1361 mentioned above, right at the end of the read-in phase, all the
1362 prerequisites of the targets defined after the special target are
1363 expanded a _second time_. In most circumstances this secondary
1364 expansion will have no effect, since all variable and function
1365 references will have been expanded during the initial parsing of the
1366 makefiles. In order to take advantage of the secondary expansion phase
1367 of the parser, then, it's necessary to _escape_ the variable or
1368 function reference in the makefile. In this case the first expansion
1369 merely un-escapes the reference but doesn't expand it, and expansion is
1370 left to the secondary expansion phase. For example, consider this
1376 myfile: $(ONEVAR) $$(TWOVAR)
1378 After the first expansion phase the prerequisites list of the
1379 `myfile' target will be `onefile' and `$(TWOVAR)'; the first
1380 (unescaped) variable reference to ONEVAR is expanded, while the second
1381 (escaped) variable reference is simply unescaped, without being
1382 recognized as a variable reference. Now during the secondary expansion
1383 the first word is expanded again but since it contains no variable or
1384 function references it remains the value `onefile', while the second
1385 word is now a normal reference to the variable TWOVAR, which is
1386 expanded to the value `twofile'. The final result is that there are
1387 two prerequisites, `onefile' and `twofile'.
1389 Obviously, this is not a very interesting case since the same result
1390 could more easily have been achieved simply by having both variables
1391 appear, unescaped, in the prerequisites list. One difference becomes
1392 apparent if the variables are reset; consider this example:
1400 Here the prerequisite of `onefile' will be expanded immediately, and
1401 resolve to the value `top', while the prerequisite of `twofile' will
1402 not be full expanded until the secondary expansion and yield a value of
1405 This is marginally more exciting, but the true power of this feature
1406 only becomes apparent when you discover that secondary expansions
1407 always take place within the scope of the automatic variables for that
1408 target. This means that you can use variables such as `$@', `$*', etc.
1409 during the second expansion and they will have their expected values,
1410 just as in the recipe. All you have to do is defer the expansion by
1411 escaping the `$'. Also, secondary expansion occurs for both explicit
1412 and implicit (pattern) rules. Knowing this, the possible uses for this
1413 feature increase dramatically. For example:
1416 main_OBJS := main.o try.o test.o
1417 lib_OBJS := lib.o api.o
1419 main lib: $$($$@_OBJS)
1421 Here, after the initial expansion the prerequisites of both the
1422 `main' and `lib' targets will be `$($@_OBJS)'. During the secondary
1423 expansion, the `$@' variable is set to the name of the target and so
1424 the expansion for the `main' target will yield `$(main_OBJS)', or
1425 `main.o try.o test.o', while the secondary expansion for the `lib'
1426 target will yield `$(lib_OBJS)', or `lib.o api.o'.
1428 You can also mix in functions here, as long as they are properly
1431 main_SRCS := main.c try.c test.c
1432 lib_SRCS := lib.c api.c
1435 main lib: $$(patsubst %.c,%.o,$$($$@_SRCS))
1437 This version allows users to specify source files rather than object
1438 files, but gives the same resulting prerequisites list as the previous
1441 Evaluation of automatic variables during the secondary expansion
1442 phase, especially of the target name variable `$$@', behaves similarly
1443 to evaluation within recipes. However, there are some subtle
1444 differences and "corner cases" which come into play for the different
1445 types of rule definitions that `make' understands. The subtleties of
1446 using the different automatic variables are described below.
1448 Secondary Expansion of Explicit Rules
1449 -------------------------------------
1451 During the secondary expansion of explicit rules, `$$@' and `$$%'
1452 evaluate, respectively, to the file name of the target and, when the
1453 target is an archive member, the target member name. The `$$<'
1454 variable evaluates to the first prerequisite in the first rule for this
1455 target. `$$^' and `$$+' evaluate to the list of all prerequisites of
1456 rules _that have already appeared_ for the same target (`$$+' with
1457 repetitions and `$$^' without). The following example will help
1458 illustrate these behaviors:
1462 foo: foo.1 bar.1 $$< $$^ $$+ # line #1
1464 foo: foo.2 bar.2 $$< $$^ $$+ # line #2
1466 foo: foo.3 bar.3 $$< $$^ $$+ # line #3
1468 In the first prerequisite list, all three variables (`$$<', `$$^',
1469 and `$$+') expand to the empty string. In the second, they will have
1470 values `foo.1', `foo.1 bar.1', and `foo.1 bar.1' respectively. In the
1471 third they will have values `foo.1', `foo.1 bar.1 foo.2 bar.2', and
1472 `foo.1 bar.1 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1' respectively.
1474 Rules undergo secondary expansion in makefile order, except that the
1475 rule with the recipe is always evaluated last.
1477 The variables `$$?' and `$$*' are not available and expand to the
1480 Secondary Expansion of Static Pattern Rules
1481 -------------------------------------------
1483 Rules for secondary expansion of static pattern rules are identical to
1484 those for explicit rules, above, with one exception: for static pattern
1485 rules the `$$*' variable is set to the pattern stem. As with explicit
1486 rules, `$$?' is not available and expands to the empty string.
1488 Secondary Expansion of Implicit Rules
1489 -------------------------------------
1491 As `make' searches for an implicit rule, it substitutes the stem and
1492 then performs secondary expansion for every rule with a matching target
1493 pattern. The value of the automatic variables is derived in the same
1494 fashion as for static pattern rules. As an example:
1502 %oo: $$< $$^ $$+ $$*
1504 When the implicit rule is tried for target `foo', `$$<' expands to
1505 `bar', `$$^' expands to `bar boo', `$$+' also expands to `bar boo', and
1506 `$$*' expands to `f'.
1508 Note that the directory prefix (D), as described in *note Implicit
1509 Rule Search Algorithm: Implicit Rule Search, is appended (after
1510 expansion) to all the patterns in the prerequisites list. As an
1517 %.o: $$(addsuffix /%.c,foo bar) foo.h
1520 The prerequisite list printed, after the secondary expansion and
1521 directory prefix reconstruction, will be `/tmp/foo/foo.c /tmp/bar/foo.c
1522 foo.h'. If you are not interested in this reconstruction, you can use
1523 `$$*' instead of `%' in the prerequisites list.
1526 File: make.info, Node: Rules, Next: Recipes, Prev: Makefiles, Up: Top
1531 A "rule" appears in the makefile and says when and how to remake
1532 certain files, called the rule's "targets" (most often only one per
1533 rule). It lists the other files that are the "prerequisites" of the
1534 target, and the "recipe" to use to create or update the target.
1536 The order of rules is not significant, except for determining the
1537 "default goal": the target for `make' to consider, if you do not
1538 otherwise specify one. The default goal is the target of the first
1539 rule in the first makefile. If the first rule has multiple targets,
1540 only the first target is taken as the default. There are two
1541 exceptions: a target starting with a period is not a default unless it
1542 contains one or more slashes, `/', as well; and, a target that defines
1543 a pattern rule has no effect on the default goal. (*Note Defining and
1544 Redefining Pattern Rules: Pattern Rules.)
1546 Therefore, we usually write the makefile so that the first rule is
1547 the one for compiling the entire program or all the programs described
1548 by the makefile (often with a target called `all'). *Note Arguments to
1549 Specify the Goals: Goals.
1553 * Rule Example:: An example explained.
1554 * Rule Syntax:: General syntax explained.
1555 * Prerequisite Types:: There are two types of prerequisites.
1556 * Wildcards:: Using wildcard characters such as `*'.
1557 * Directory Search:: Searching other directories for source files.
1558 * Phony Targets:: Using a target that is not a real file's name.
1559 * Force Targets:: You can use a target without a recipe
1560 or prerequisites to mark other targets
1562 * Empty Targets:: When only the date matters and the
1564 * Special Targets:: Targets with special built-in meanings.
1565 * Multiple Targets:: When to make use of several targets in a rule.
1566 * Multiple Rules:: How to use several rules with the same target.
1567 * Static Pattern:: Static pattern rules apply to multiple targets
1568 and can vary the prerequisites according to
1570 * Double-Colon:: How to use a special kind of rule to allow
1571 several independent rules for one target.
1572 * Automatic Prerequisites:: How to automatically generate rules giving
1573 prerequisites from source files themselves.
1576 File: make.info, Node: Rule Example, Next: Rule Syntax, Prev: Rules, Up: Rules
1581 Here is an example of a rule:
1583 foo.o : foo.c defs.h # module for twiddling the frobs
1586 Its target is `foo.o' and its prerequisites are `foo.c' and
1587 `defs.h'. It has one command in the recipe: `cc -c -g foo.c'. The
1588 recipe starts with a tab to identify it as a recipe.
1590 This rule says two things:
1592 * How to decide whether `foo.o' is out of date: it is out of date if
1593 it does not exist, or if either `foo.c' or `defs.h' is more recent
1596 * How to update the file `foo.o': by running `cc' as stated. The
1597 recipe does not explicitly mention `defs.h', but we presume that
1598 `foo.c' includes it, and that that is why `defs.h' was added to
1602 File: make.info, Node: Rule Syntax, Next: Prerequisite Types, Prev: Rule Example, Up: Rules
1607 In general, a rule looks like this:
1609 TARGETS : PREREQUISITES
1615 TARGETS : PREREQUISITES ; RECIPE
1619 The TARGETS are file names, separated by spaces. Wildcard
1620 characters may be used (*note Using Wildcard Characters in File Names:
1621 Wildcards.) and a name of the form `A(M)' represents member M in
1622 archive file A (*note Archive Members as Targets: Archive Members.).
1623 Usually there is only one target per rule, but occasionally there is a
1624 reason to have more (*note Multiple Targets in a Rule: Multiple
1627 The RECIPE lines start with a tab character (or the first character
1628 in the value of the `.RECIPEPREFIX' variable; *note Special
1629 Variables::). The first recipe line may appear on the line after the
1630 prerequisites, with a tab character, or may appear on the same line,
1631 with a semicolon. Either way, the effect is the same. There are other
1632 differences in the syntax of recipes. *Note Writing Recipes in Rules:
1635 Because dollar signs are used to start `make' variable references,
1636 if you really want a dollar sign in a target or prerequisite you must
1637 write two of them, `$$' (*note How to Use Variables: Using Variables.).
1638 If you have enabled secondary expansion (*note Secondary Expansion::)
1639 and you want a literal dollar sign in the prerequisites list, you must
1640 actually write _four_ dollar signs (`$$$$').
1642 You may split a long line by inserting a backslash followed by a
1643 newline, but this is not required, as `make' places no limit on the
1644 length of a line in a makefile.
1646 A rule tells `make' two things: when the targets are out of date,
1647 and how to update them when necessary.
1649 The criterion for being out of date is specified in terms of the
1650 PREREQUISITES, which consist of file names separated by spaces.
1651 (Wildcards and archive members (*note Archives::) are allowed here too.)
1652 A target is out of date if it does not exist or if it is older than any
1653 of the prerequisites (by comparison of last-modification times). The
1654 idea is that the contents of the target file are computed based on
1655 information in the prerequisites, so if any of the prerequisites
1656 changes, the contents of the existing target file are no longer
1659 How to update is specified by a RECIPE. This is one or more lines
1660 to be executed by the shell (normally `sh'), but with some extra
1661 features (*note Writing Recipes in Rules: Recipes.).
1664 File: make.info, Node: Prerequisite Types, Next: Wildcards, Prev: Rule Syntax, Up: Rules
1666 4.3 Types of Prerequisites
1667 ==========================
1669 There are actually two different types of prerequisites understood by
1670 GNU `make': normal prerequisites such as described in the previous
1671 section, and "order-only" prerequisites. A normal prerequisite makes
1672 two statements: first, it imposes an order in which recipes will be
1673 invoked: the recipes for all prerequisites of a target will be
1674 completed before the recipe for the target is run. Second, it imposes
1675 a dependency relationship: if any prerequisite is newer than the
1676 target, then the target is considered out-of-date and must be rebuilt.
1678 Normally, this is exactly what you want: if a target's prerequisite
1679 is updated, then the target should also be updated.
1681 Occasionally, however, you have a situation where you want to impose
1682 a specific ordering on the rules to be invoked _without_ forcing the
1683 target to be updated if one of those rules is executed. In that case,
1684 you want to define "order-only" prerequisites. Order-only
1685 prerequisites can be specified by placing a pipe symbol (`|') in the
1686 prerequisites list: any prerequisites to the left of the pipe symbol
1687 are normal; any prerequisites to the right are order-only:
1689 TARGETS : NORMAL-PREREQUISITES | ORDER-ONLY-PREREQUISITES
1691 The normal prerequisites section may of course be empty. Also, you
1692 may still declare multiple lines of prerequisites for the same target:
1693 they are appended appropriately (normal prerequisites are appended to
1694 the list of normal prerequisites; order-only prerequisites are appended
1695 to the list of order-only prerequisites). Note that if you declare the
1696 same file to be both a normal and an order-only prerequisite, the
1697 normal prerequisite takes precedence (since they have a strict superset
1698 of the behavior of an order-only prerequisite).
1700 Consider an example where your targets are to be placed in a separate
1701 directory, and that directory might not exist before `make' is run. In
1702 this situation, you want the directory to be created before any targets
1703 are placed into it but, because the timestamps on directories change
1704 whenever a file is added, removed, or renamed, we certainly don't want
1705 to rebuild all the targets whenever the directory's timestamp changes.
1706 One way to manage this is with order-only prerequisites: make the
1707 directory an order-only prerequisite on all the targets:
1710 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
1713 $(COMPILE.c) $(OUTPUT_OPTION) $<
1717 $(OBJS): | $(OBJDIR)
1722 Now the rule to create the `objdir' directory will be run, if
1723 needed, before any `.o' is built, but no `.o' will be built because the
1724 `objdir' directory timestamp changed.
1727 File: make.info, Node: Wildcards, Next: Directory Search, Prev: Prerequisite Types, Up: Rules
1729 4.4 Using Wildcard Characters in File Names
1730 ===========================================
1732 A single file name can specify many files using "wildcard characters".
1733 The wildcard characters in `make' are `*', `?' and `[...]', the same as
1734 in the Bourne shell. For example, `*.c' specifies a list of all the
1735 files (in the working directory) whose names end in `.c'.
1737 The character `~' at the beginning of a file name also has special
1738 significance. If alone, or followed by a slash, it represents your home
1739 directory. For example `~/bin' expands to `/home/you/bin'. If the `~'
1740 is followed by a word, the string represents the home directory of the
1741 user named by that word. For example `~john/bin' expands to
1742 `/home/john/bin'. On systems which don't have a home directory for
1743 each user (such as MS-DOS or MS-Windows), this functionality can be
1744 simulated by setting the environment variable HOME.
1746 Wildcard expansion is performed by `make' automatically in targets
1747 and in prerequisites. In recipes, the shell is responsible for
1748 wildcard expansion. In other contexts, wildcard expansion happens only
1749 if you request it explicitly with the `wildcard' function.
1751 The special significance of a wildcard character can be turned off by
1752 preceding it with a backslash. Thus, `foo\*bar' would refer to a
1753 specific file whose name consists of `foo', an asterisk, and `bar'.
1757 * Wildcard Examples:: Several examples.
1758 * Wildcard Pitfall:: Problems to avoid.
1759 * Wildcard Function:: How to cause wildcard expansion where
1760 it does not normally take place.
1763 File: make.info, Node: Wildcard Examples, Next: Wildcard Pitfall, Prev: Wildcards, Up: Wildcards
1765 4.4.1 Wildcard Examples
1766 -----------------------
1768 Wildcards can be used in the recipe of a rule, where they are expanded
1769 by the shell. For example, here is a rule to delete all the object
1775 Wildcards are also useful in the prerequisites of a rule. With the
1776 following rule in the makefile, `make print' will print all the `.c'
1777 files that have changed since the last time you printed them:
1783 This rule uses `print' as an empty target file; see *note Empty Target
1784 Files to Record Events: Empty Targets. (The automatic variable `$?' is
1785 used to print only those files that have changed; see *note Automatic
1788 Wildcard expansion does not happen when you define a variable.
1789 Thus, if you write this:
1793 then the value of the variable `objects' is the actual string `*.o'.
1794 However, if you use the value of `objects' in a target or prerequisite,
1795 wildcard expansion will take place there. If you use the value of
1796 `objects' in a recipe, the shell may perform wildcard expansion when
1797 the recipe runs. To set `objects' to the expansion, instead use:
1799 objects := $(wildcard *.o)
1801 *Note Wildcard Function::.
1804 File: make.info, Node: Wildcard Pitfall, Next: Wildcard Function, Prev: Wildcard Examples, Up: Wildcards
1806 4.4.2 Pitfalls of Using Wildcards
1807 ---------------------------------
1809 Now here is an example of a naive way of using wildcard expansion, that
1810 does not do what you would intend. Suppose you would like to say that
1811 the executable file `foo' is made from all the object files in the
1812 directory, and you write this:
1817 cc -o foo $(CFLAGS) $(objects)
1819 The value of `objects' is the actual string `*.o'. Wildcard expansion
1820 happens in the rule for `foo', so that each _existing_ `.o' file
1821 becomes a prerequisite of `foo' and will be recompiled if necessary.
1823 But what if you delete all the `.o' files? When a wildcard matches
1824 no files, it is left as it is, so then `foo' will depend on the
1825 oddly-named file `*.o'. Since no such file is likely to exist, `make'
1826 will give you an error saying it cannot figure out how to make `*.o'.
1827 This is not what you want!
1829 Actually it is possible to obtain the desired result with wildcard
1830 expansion, but you need more sophisticated techniques, including the
1831 `wildcard' function and string substitution. *Note The Function
1832 `wildcard': Wildcard Function.
1834 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes
1835 to separate directories in pathnames, like so:
1839 This is equivalent to the Unix-style `c:/foo/bar/baz.c' (the `c:'
1840 part is the so-called drive letter). When `make' runs on these
1841 systems, it supports backslashes as well as the Unix-style forward
1842 slashes in pathnames. However, this support does _not_ include the
1843 wildcard expansion, where backslash is a quote character. Therefore,
1844 you _must_ use Unix-style slashes in these cases.
1847 File: make.info, Node: Wildcard Function, Prev: Wildcard Pitfall, Up: Wildcards
1849 4.4.3 The Function `wildcard'
1850 -----------------------------
1852 Wildcard expansion happens automatically in rules. But wildcard
1853 expansion does not normally take place when a variable is set, or
1854 inside the arguments of a function. If you want to do wildcard
1855 expansion in such places, you need to use the `wildcard' function, like
1858 $(wildcard PATTERN...)
1860 This string, used anywhere in a makefile, is replaced by a
1861 space-separated list of names of existing files that match one of the
1862 given file name patterns. If no existing file name matches a pattern,
1863 then that pattern is omitted from the output of the `wildcard'
1864 function. Note that this is different from how unmatched wildcards
1865 behave in rules, where they are used verbatim rather than ignored
1866 (*note Wildcard Pitfall::).
1868 One use of the `wildcard' function is to get a list of all the C
1869 source files in a directory, like this:
1873 We can change the list of C source files into a list of object files
1874 by replacing the `.c' suffix with `.o' in the result, like this:
1876 $(patsubst %.c,%.o,$(wildcard *.c))
1878 (Here we have used another function, `patsubst'. *Note Functions for
1879 String Substitution and Analysis: Text Functions.)
1881 Thus, a makefile to compile all C source files in the directory and
1882 then link them together could be written as follows:
1884 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1887 cc -o foo $(objects)
1889 (This takes advantage of the implicit rule for compiling C programs, so
1890 there is no need to write explicit rules for compiling the files.
1891 *Note The Two Flavors of Variables: Flavors, for an explanation of
1892 `:=', which is a variant of `='.)
1895 File: make.info, Node: Directory Search, Next: Phony Targets, Prev: Wildcards, Up: Rules
1897 4.5 Searching Directories for Prerequisites
1898 ===========================================
1900 For large systems, it is often desirable to put sources in a separate
1901 directory from the binaries. The "directory search" features of `make'
1902 facilitate this by searching several directories automatically to find
1903 a prerequisite. When you redistribute the files among directories, you
1904 do not need to change the individual rules, just the search paths.
1908 * General Search:: Specifying a search path that applies
1909 to every prerequisite.
1910 * Selective Search:: Specifying a search path
1911 for a specified class of names.
1912 * Search Algorithm:: When and how search paths are applied.
1913 * Recipes/Search:: How to write recipes that work together
1915 * Implicit/Search:: How search paths affect implicit rules.
1916 * Libraries/Search:: Directory search for link libraries.
1919 File: make.info, Node: General Search, Next: Selective Search, Prev: Directory Search, Up: Directory Search
1921 4.5.1 `VPATH': Search Path for All Prerequisites
1922 ------------------------------------------------
1924 The value of the `make' variable `VPATH' specifies a list of
1925 directories that `make' should search. Most often, the directories are
1926 expected to contain prerequisite files that are not in the current
1927 directory; however, `make' uses `VPATH' as a search list for both
1928 prerequisites and targets of rules.
1930 Thus, if a file that is listed as a target or prerequisite does not
1931 exist in the current directory, `make' searches the directories listed
1932 in `VPATH' for a file with that name. If a file is found in one of
1933 them, that file may become the prerequisite (see below). Rules may then
1934 specify the names of files in the prerequisite list as if they all
1935 existed in the current directory. *Note Writing Recipes with Directory
1936 Search: Recipes/Search.
1938 In the `VPATH' variable, directory names are separated by colons or
1939 blanks. The order in which directories are listed is the order followed
1940 by `make' in its search. (On MS-DOS and MS-Windows, semi-colons are
1941 used as separators of directory names in `VPATH', since the colon can
1942 be used in the pathname itself, after the drive letter.)
1946 VPATH = src:../headers
1948 specifies a path containing two directories, `src' and `../headers',
1949 which `make' searches in that order.
1951 With this value of `VPATH', the following rule,
1955 is interpreted as if it were written like this:
1959 assuming the file `foo.c' does not exist in the current directory but
1960 is found in the directory `src'.
1963 File: make.info, Node: Selective Search, Next: Search Algorithm, Prev: General Search, Up: Directory Search
1965 4.5.2 The `vpath' Directive
1966 ---------------------------
1968 Similar to the `VPATH' variable, but more selective, is the `vpath'
1969 directive (note lower case), which allows you to specify a search path
1970 for a particular class of file names: those that match a particular
1971 pattern. Thus you can supply certain search directories for one class
1972 of file names and other directories (or none) for other file names.
1974 There are three forms of the `vpath' directive:
1976 `vpath PATTERN DIRECTORIES'
1977 Specify the search path DIRECTORIES for file names that match
1980 The search path, DIRECTORIES, is a list of directories to be
1981 searched, separated by colons (semi-colons on MS-DOS and
1982 MS-Windows) or blanks, just like the search path used in the
1986 Clear out the search path associated with PATTERN.
1989 Clear all search paths previously specified with `vpath'
1992 A `vpath' pattern is a string containing a `%' character. The
1993 string must match the file name of a prerequisite that is being searched
1994 for, the `%' character matching any sequence of zero or more characters
1995 (as in pattern rules; *note Defining and Redefining Pattern Rules:
1996 Pattern Rules.). For example, `%.h' matches files that end in `.h'.
1997 (If there is no `%', the pattern must match the prerequisite exactly,
1998 which is not useful very often.)
2000 `%' characters in a `vpath' directive's pattern can be quoted with
2001 preceding backslashes (`\'). Backslashes that would otherwise quote
2002 `%' characters can be quoted with more backslashes. Backslashes that
2003 quote `%' characters or other backslashes are removed from the pattern
2004 before it is compared to file names. Backslashes that are not in
2005 danger of quoting `%' characters go unmolested.
2007 When a prerequisite fails to exist in the current directory, if the
2008 PATTERN in a `vpath' directive matches the name of the prerequisite
2009 file, then the DIRECTORIES in that directive are searched just like
2010 (and before) the directories in the `VPATH' variable.
2014 vpath %.h ../headers
2016 tells `make' to look for any prerequisite whose name ends in `.h' in
2017 the directory `../headers' if the file is not found in the current
2020 If several `vpath' patterns match the prerequisite file's name, then
2021 `make' processes each matching `vpath' directive one by one, searching
2022 all the directories mentioned in each directive. `make' handles
2023 multiple `vpath' directives in the order in which they appear in the
2024 makefile; multiple directives with the same pattern are independent of
2033 will look for a file ending in `.c' in `foo', then `blish', then `bar',
2039 will look for a file ending in `.c' in `foo', then `bar', then `blish'.
2042 File: make.info, Node: Search Algorithm, Next: Recipes/Search, Prev: Selective Search, Up: Directory Search
2044 4.5.3 How Directory Searches are Performed
2045 ------------------------------------------
2047 When a prerequisite is found through directory search, regardless of
2048 type (general or selective), the pathname located may not be the one
2049 that `make' actually provides you in the prerequisite list. Sometimes
2050 the path discovered through directory search is thrown away.
2052 The algorithm `make' uses to decide whether to keep or abandon a
2053 path found via directory search is as follows:
2055 1. If a target file does not exist at the path specified in the
2056 makefile, directory search is performed.
2058 2. If the directory search is successful, that path is kept and this
2059 file is tentatively stored as the target.
2061 3. All prerequisites of this target are examined using this same
2064 4. After processing the prerequisites, the target may or may not need
2067 a. If the target does _not_ need to be rebuilt, the path to the
2068 file found during directory search is used for any
2069 prerequisite lists which contain this target. In short, if
2070 `make' doesn't need to rebuild the target then you use the
2071 path found via directory search.
2073 b. If the target _does_ need to be rebuilt (is out-of-date), the
2074 pathname found during directory search is _thrown away_, and
2075 the target is rebuilt using the file name specified in the
2076 makefile. In short, if `make' must rebuild, then the target
2077 is rebuilt locally, not in the directory found via directory
2080 This algorithm may seem complex, but in practice it is quite often
2081 exactly what you want.
2083 Other versions of `make' use a simpler algorithm: if the file does
2084 not exist, and it is found via directory search, then that pathname is
2085 always used whether or not the target needs to be built. Thus, if the
2086 target is rebuilt it is created at the pathname discovered during
2089 If, in fact, this is the behavior you want for some or all of your
2090 directories, you can use the `GPATH' variable to indicate this to
2093 `GPATH' has the same syntax and format as `VPATH' (that is, a space-
2094 or colon-delimited list of pathnames). If an out-of-date target is
2095 found by directory search in a directory that also appears in `GPATH',
2096 then that pathname is not thrown away. The target is rebuilt using the
2100 File: make.info, Node: Recipes/Search, Next: Implicit/Search, Prev: Search Algorithm, Up: Directory Search
2102 4.5.4 Writing Recipes with Directory Search
2103 -------------------------------------------
2105 When a prerequisite is found in another directory through directory
2106 search, this cannot change the recipe of the rule; they will execute as
2107 written. Therefore, you must write the recipe with care so that it
2108 will look for the prerequisite in the directory where `make' finds it.
2110 This is done with the "automatic variables" such as `$^' (*note
2111 Automatic Variables::). For instance, the value of `$^' is a list of
2112 all the prerequisites of the rule, including the names of the
2113 directories in which they were found, and the value of `$@' is the
2117 cc -c $(CFLAGS) $^ -o $@
2119 (The variable `CFLAGS' exists so you can specify flags for C
2120 compilation by implicit rules; we use it here for consistency so it will
2121 affect all C compilations uniformly; *note Variables Used by Implicit
2122 Rules: Implicit Variables.)
2124 Often the prerequisites include header files as well, which you do
2125 not want to mention in the recipe. The automatic variable `$<' is just
2126 the first prerequisite:
2128 VPATH = src:../headers
2129 foo.o : foo.c defs.h hack.h
2130 cc -c $(CFLAGS) $< -o $@
2133 File: make.info, Node: Implicit/Search, Next: Libraries/Search, Prev: Recipes/Search, Up: Directory Search
2135 4.5.5 Directory Search and Implicit Rules
2136 -----------------------------------------
2138 The search through the directories specified in `VPATH' or with `vpath'
2139 also happens during consideration of implicit rules (*note Using
2140 Implicit Rules: Implicit Rules.).
2142 For example, when a file `foo.o' has no explicit rule, `make'
2143 considers implicit rules, such as the built-in rule to compile `foo.c'
2144 if that file exists. If such a file is lacking in the current
2145 directory, the appropriate directories are searched for it. If `foo.c'
2146 exists (or is mentioned in the makefile) in any of the directories, the
2147 implicit rule for C compilation is applied.
2149 The recipes of implicit rules normally use automatic variables as a
2150 matter of necessity; consequently they will use the file names found by
2151 directory search with no extra effort.
2154 File: make.info, Node: Libraries/Search, Prev: Implicit/Search, Up: Directory Search
2156 4.5.6 Directory Search for Link Libraries
2157 -----------------------------------------
2159 Directory search applies in a special way to libraries used with the
2160 linker. This special feature comes into play when you write a
2161 prerequisite whose name is of the form `-lNAME'. (You can tell
2162 something strange is going on here because the prerequisite is normally
2163 the name of a file, and the _file name_ of a library generally looks
2164 like `libNAME.a', not like `-lNAME'.)
2166 When a prerequisite's name has the form `-lNAME', `make' handles it
2167 specially by searching for the file `libNAME.so', and, if it is not
2168 found, for the file `libNAME.a' in the current directory, in
2169 directories specified by matching `vpath' search paths and the `VPATH'
2170 search path, and then in the directories `/lib', `/usr/lib', and
2171 `PREFIX/lib' (normally `/usr/local/lib', but MS-DOS/MS-Windows versions
2172 of `make' behave as if PREFIX is defined to be the root of the DJGPP
2175 For example, if there is a `/usr/lib/libcurses.a' library on your
2176 system (and no `/usr/lib/libcurses.so' file), then
2178 foo : foo.c -lcurses
2181 would cause the command `cc foo.c /usr/lib/libcurses.a -o foo' to be
2182 executed when `foo' is older than `foo.c' or than
2183 `/usr/lib/libcurses.a'.
2185 Although the default set of files to be searched for is `libNAME.so'
2186 and `libNAME.a', this is customizable via the `.LIBPATTERNS' variable.
2187 Each word in the value of this variable is a pattern string. When a
2188 prerequisite like `-lNAME' is seen, `make' will replace the percent in
2189 each pattern in the list with NAME and perform the above directory
2190 searches using each library file name.
2192 The default value for `.LIBPATTERNS' is `lib%.so lib%.a', which
2193 provides the default behavior described above.
2195 You can turn off link library expansion completely by setting this
2196 variable to an empty value.
2199 File: make.info, Node: Phony Targets, Next: Force Targets, Prev: Directory Search, Up: Rules
2204 A phony target is one that is not really the name of a file; rather it
2205 is just a name for a recipe to be executed when you make an explicit
2206 request. There are two reasons to use a phony target: to avoid a
2207 conflict with a file of the same name, and to improve performance.
2209 If you write a rule whose recipe will not create the target file, the
2210 recipe will be executed every time the target comes up for remaking.
2216 Because the `rm' command does not create a file named `clean', probably
2217 no such file will ever exist. Therefore, the `rm' command will be
2218 executed every time you say `make clean'.
2220 The phony target will cease to work if anything ever does create a
2221 file named `clean' in this directory. Since it has no prerequisites,
2222 the file `clean' would inevitably be considered up to date, and its
2223 recipe would not be executed. To avoid this problem, you can explicitly
2224 declare the target to be phony, using the special target `.PHONY'
2225 (*note Special Built-in Target Names: Special Targets.) as follows:
2229 Once this is done, `make clean' will run the recipe regardless of
2230 whether there is a file named `clean'.
2232 Since it knows that phony targets do not name actual files that
2233 could be remade from other files, `make' skips the implicit rule search
2234 for phony targets (*note Implicit Rules::). This is why declaring a
2235 target phony is good for performance, even if you are not worried about
2236 the actual file existing.
2238 Thus, you first write the line that states that `clean' is a phony
2239 target, then you write the rule, like this:
2245 Another example of the usefulness of phony targets is in conjunction
2246 with recursive invocations of `make' (for more information, see *note
2247 Recursive Use of `make': Recursion.). In this case the makefile will
2248 often contain a variable which lists a number of sub-directories to be
2249 built. One way to handle this is with one rule whose recipe is a shell
2250 loop over the sub-directories, like this:
2252 SUBDIRS = foo bar baz
2255 for dir in $(SUBDIRS); do \
2259 There are problems with this method, however. First, any error
2260 detected in a sub-make is ignored by this rule, so it will continue to
2261 build the rest of the directories even when one fails. This can be
2262 overcome by adding shell commands to note the error and exit, but then
2263 it will do so even if `make' is invoked with the `-k' option, which is
2264 unfortunate. Second, and perhaps more importantly, you cannot take
2265 advantage of `make''s ability to build targets in parallel (*note
2266 Parallel Execution: Parallel.), since there is only one rule.
2268 By declaring the sub-directories as phony targets (you must do this
2269 as the sub-directory obviously always exists; otherwise it won't be
2270 built) you can remove these problems:
2272 SUBDIRS = foo bar baz
2274 .PHONY: subdirs $(SUBDIRS)
2283 Here we've also declared that the `foo' sub-directory cannot be
2284 built until after the `baz' sub-directory is complete; this kind of
2285 relationship declaration is particularly important when attempting
2288 A phony target should not be a prerequisite of a real target file;
2289 if it is, its recipe will be run every time `make' goes to update that
2290 file. As long as a phony target is never a prerequisite of a real
2291 target, the phony target recipe will be executed only when the phony
2292 target is a specified goal (*note Arguments to Specify the Goals:
2295 Phony targets can have prerequisites. When one directory contains
2296 multiple programs, it is most convenient to describe all of the
2297 programs in one makefile `./Makefile'. Since the target remade by
2298 default will be the first one in the makefile, it is common to make
2299 this a phony target named `all' and give it, as prerequisites, all the
2300 individual programs. For example:
2302 all : prog1 prog2 prog3
2305 prog1 : prog1.o utils.o
2306 cc -o prog1 prog1.o utils.o
2311 prog3 : prog3.o sort.o utils.o
2312 cc -o prog3 prog3.o sort.o utils.o
2314 Now you can say just `make' to remake all three programs, or specify as
2315 arguments the ones to remake (as in `make prog1 prog3'). Phoniness is
2316 not inherited: the prerequisites of a phony target are not themselves
2317 phony, unless explicitly declared to be so.
2319 When one phony target is a prerequisite of another, it serves as a
2320 subroutine of the other. For example, here `make cleanall' will delete
2321 the object files, the difference files, and the file `program':
2323 .PHONY: cleanall cleanobj cleandiff
2325 cleanall : cleanobj cleandiff
2335 File: make.info, Node: Force Targets, Next: Empty Targets, Prev: Phony Targets, Up: Rules
2337 4.7 Rules without Recipes or Prerequisites
2338 ==========================================
2340 If a rule has no prerequisites or recipe, and the target of the rule is
2341 a nonexistent file, then `make' imagines this target to have been
2342 updated whenever its rule is run. This implies that all targets
2343 depending on this one will always have their recipe run.
2345 An example will illustrate this:
2351 Here the target `FORCE' satisfies the special conditions, so the
2352 target `clean' that depends on it is forced to run its recipe. There
2353 is nothing special about the name `FORCE', but that is one name
2354 commonly used this way.
2356 As you can see, using `FORCE' this way has the same results as using
2359 Using `.PHONY' is more explicit and more efficient. However, other
2360 versions of `make' do not support `.PHONY'; thus `FORCE' appears in
2361 many makefiles. *Note Phony Targets::.
2364 File: make.info, Node: Empty Targets, Next: Special Targets, Prev: Force Targets, Up: Rules
2366 4.8 Empty Target Files to Record Events
2367 =======================================
2369 The "empty target" is a variant of the phony target; it is used to hold
2370 recipes for an action that you request explicitly from time to time.
2371 Unlike a phony target, this target file can really exist; but the file's
2372 contents do not matter, and usually are empty.
2374 The purpose of the empty target file is to record, with its
2375 last-modification time, when the rule's recipe was last executed. It
2376 does so because one of the commands in the recipe is a `touch' command
2377 to update the target file.
2379 The empty target file should have some prerequisites (otherwise it
2380 doesn't make sense). When you ask to remake the empty target, the
2381 recipe is executed if any prerequisite is more recent than the target;
2382 in other words, if a prerequisite has changed since the last time you
2383 remade the target. Here is an example:
2389 With this rule, `make print' will execute the `lpr' command if either
2390 source file has changed since the last `make print'. The automatic
2391 variable `$?' is used to print only those files that have changed
2392 (*note Automatic Variables::).
2395 File: make.info, Node: Special Targets, Next: Multiple Targets, Prev: Empty Targets, Up: Rules
2397 4.9 Special Built-in Target Names
2398 =================================
2400 Certain names have special meanings if they appear as targets.
2403 The prerequisites of the special target `.PHONY' are considered to
2404 be phony targets. When it is time to consider such a target,
2405 `make' will run its recipe unconditionally, regardless of whether
2406 a file with that name exists or what its last-modification time
2407 is. *Note Phony Targets: Phony Targets.
2410 The prerequisites of the special target `.SUFFIXES' are the list
2411 of suffixes to be used in checking for suffix rules. *Note
2412 Old-Fashioned Suffix Rules: Suffix Rules.
2415 The recipe specified for `.DEFAULT' is used for any target for
2416 which no rules are found (either explicit rules or implicit rules).
2417 *Note Last Resort::. If a `.DEFAULT' recipe is specified, every
2418 file mentioned as a prerequisite, but not as a target in a rule,
2419 will have that recipe executed on its behalf. *Note Implicit Rule
2420 Search Algorithm: Implicit Rule Search.
2423 The targets which `.PRECIOUS' depends on are given the following
2424 special treatment: if `make' is killed or interrupted during the
2425 execution of their recipes, the target is not deleted. *Note
2426 Interrupting or Killing `make': Interrupts. Also, if the target
2427 is an intermediate file, it will not be deleted after it is no
2428 longer needed, as is normally done. *Note Chains of Implicit
2429 Rules: Chained Rules. In this latter respect it overlaps with the
2430 `.SECONDARY' special target.
2432 You can also list the target pattern of an implicit rule (such as
2433 `%.o') as a prerequisite file of the special target `.PRECIOUS' to
2434 preserve intermediate files created by rules whose target patterns
2435 match that file's name.
2438 The targets which `.INTERMEDIATE' depends on are treated as
2439 intermediate files. *Note Chains of Implicit Rules: Chained Rules.
2440 `.INTERMEDIATE' with no prerequisites has no effect.
2443 The targets which `.SECONDARY' depends on are treated as
2444 intermediate files, except that they are never automatically
2445 deleted. *Note Chains of Implicit Rules: Chained Rules.
2447 `.SECONDARY' with no prerequisites causes all targets to be treated
2448 as secondary (i.e., no target is removed because it is considered
2452 If `.SECONDEXPANSION' is mentioned as a target anywhere in the
2453 makefile, then all prerequisite lists defined _after_ it appears
2454 will be expanded a second time after all makefiles have been read
2455 in. *Note Secondary Expansion: Secondary Expansion.
2458 If `.DELETE_ON_ERROR' is mentioned as a target anywhere in the
2459 makefile, then `make' will delete the target of a rule if it has
2460 changed and its recipe exits with a nonzero exit status, just as it
2461 does when it receives a signal. *Note Errors in Recipes: Errors.
2464 If you specify prerequisites for `.IGNORE', then `make' will
2465 ignore errors in execution of the recipe for those particular
2466 files. The recipe for `.IGNORE' (if any) is ignored.
2468 If mentioned as a target with no prerequisites, `.IGNORE' says to
2469 ignore errors in execution of recipes for all files. This usage of
2470 `.IGNORE' is supported only for historical compatibility. Since
2471 this affects every recipe in the makefile, it is not very useful;
2472 we recommend you use the more selective ways to ignore errors in
2473 specific recipes. *Note Errors in Recipes: Errors.
2475 `.LOW_RESOLUTION_TIME'
2476 If you specify prerequisites for `.LOW_RESOLUTION_TIME', `make'
2477 assumes that these files are created by commands that generate low
2478 resolution time stamps. The recipe for the `.LOW_RESOLUTION_TIME'
2481 The high resolution file time stamps of many modern file systems
2482 lessen the chance of `make' incorrectly concluding that a file is
2483 up to date. Unfortunately, some hosts do not provide a way to set
2484 a high resolution file time stamp, so commands like `cp -p' that
2485 explicitly set a file's time stamp must discard its sub-second
2486 part. If a file is created by such a command, you should list it
2487 as a prerequisite of `.LOW_RESOLUTION_TIME' so that `make' does
2488 not mistakenly conclude that the file is out of date. For example:
2490 .LOW_RESOLUTION_TIME: dst
2494 Since `cp -p' discards the sub-second part of `src''s time stamp,
2495 `dst' is typically slightly older than `src' even when it is up to
2496 date. The `.LOW_RESOLUTION_TIME' line causes `make' to consider
2497 `dst' to be up to date if its time stamp is at the start of the
2498 same second that `src''s time stamp is in.
2500 Due to a limitation of the archive format, archive member time
2501 stamps are always low resolution. You need not list archive
2502 members as prerequisites of `.LOW_RESOLUTION_TIME', as `make' does
2506 If you specify prerequisites for `.SILENT', then `make' will not
2507 print the recipe used to remake those particular files before
2508 executing them. The recipe for `.SILENT' is ignored.
2510 If mentioned as a target with no prerequisites, `.SILENT' says not
2511 to print any recipes before executing them. This usage of
2512 `.SILENT' is supported only for historical compatibility. We
2513 recommend you use the more selective ways to silence specific
2514 recipes. *Note Recipe Echoing: Echoing. If you want to silence
2515 all recipes for a particular run of `make', use the `-s' or
2516 `--silent' option (*note Options Summary::).
2518 `.EXPORT_ALL_VARIABLES'
2519 Simply by being mentioned as a target, this tells `make' to export
2520 all variables to child processes by default. *Note Communicating
2521 Variables to a Sub-`make': Variables/Recursion.
2524 If `.NOTPARALLEL' is mentioned as a target, then this invocation
2525 of `make' will be run serially, even if the `-j' option is given.
2526 Any recursively invoked `make' command will still run recipes in
2527 parallel (unless its makefile also contains this target). Any
2528 prerequisites on this target are ignored.
2531 If `.ONESHELL' is mentioned as a target, then when a target is
2532 built all lines of the recipe will be given to a single invocation
2533 of the shell rather than each line being invoked separately (*note
2534 Recipe Execution: Execution.).
2537 If `.POSIX' is mentioned as a target, then the makefile will be
2538 parsed and run in POSIX-conforming mode. This does _not_ mean
2539 that only POSIX-conforming makefiles will be accepted: all advanced
2540 GNU `make' features are still available. Rather, this target
2541 causes `make' to behave as required by POSIX in those areas where
2542 `make''s default behavior differs.
2544 In particular, if this target is mentioned then recipes will be
2545 invoked as if the shell had been passed the `-e' flag: the first
2546 failing command in a recipe will cause the recipe to fail
2549 Any defined implicit rule suffix also counts as a special target if
2550 it appears as a target, and so does the concatenation of two suffixes,
2551 such as `.c.o'. These targets are suffix rules, an obsolete way of
2552 defining implicit rules (but a way still widely used). In principle,
2553 any target name could be special in this way if you break it in two and
2554 add both pieces to the suffix list. In practice, suffixes normally
2555 begin with `.', so these special target names also begin with `.'.
2556 *Note Old-Fashioned Suffix Rules: Suffix Rules.
2559 File: make.info, Node: Multiple Targets, Next: Multiple Rules, Prev: Special Targets, Up: Rules
2561 4.10 Multiple Targets in a Rule
2562 ===============================
2564 A rule with multiple targets is equivalent to writing many rules, each
2565 with one target, and all identical aside from that. The same recipe
2566 applies to all the targets, but its effect may vary because you can
2567 substitute the actual target name into the recipe using `$@'. The rule
2568 contributes the same prerequisites to all the targets also.
2570 This is useful in two cases.
2572 * You want just prerequisites, no recipe. For example:
2574 kbd.o command.o files.o: command.h
2576 gives an additional prerequisite to each of the three object files
2579 * Similar recipes work for all the targets. The recipes do not need
2580 to be absolutely identical, since the automatic variable `$@' can
2581 be used to substitute the particular target to be remade into the
2582 commands (*note Automatic Variables::). For example:
2584 bigoutput littleoutput : text.g
2585 generate text.g -$(subst output,,$@) > $@
2590 generate text.g -big > bigoutput
2591 littleoutput : text.g
2592 generate text.g -little > littleoutput
2594 Here we assume the hypothetical program `generate' makes two types
2595 of output, one if given `-big' and one if given `-little'. *Note
2596 Functions for String Substitution and Analysis: Text Functions,
2597 for an explanation of the `subst' function.
2599 Suppose you would like to vary the prerequisites according to the
2600 target, much as the variable `$@' allows you to vary the recipe. You
2601 cannot do this with multiple targets in an ordinary rule, but you can
2602 do it with a "static pattern rule". *Note Static Pattern Rules: Static
2606 File: make.info, Node: Multiple Rules, Next: Static Pattern, Prev: Multiple Targets, Up: Rules
2608 4.11 Multiple Rules for One Target
2609 ==================================
2611 One file can be the target of several rules. All the prerequisites
2612 mentioned in all the rules are merged into one list of prerequisites for
2613 the target. If the target is older than any prerequisite from any rule,
2614 the recipe is executed.
2616 There can only be one recipe to be executed for a file. If more than
2617 one rule gives a recipe for the same file, `make' uses the last one
2618 given and prints an error message. (As a special case, if the file's
2619 name begins with a dot, no error message is printed. This odd behavior
2620 is only for compatibility with other implementations of `make'... you
2621 should avoid using it). Occasionally it is useful to have the same
2622 target invoke multiple recipes which are defined in different parts of
2623 your makefile; you can use "double-colon rules" (*note Double-Colon::)
2626 An extra rule with just prerequisites can be used to give a few extra
2627 prerequisites to many files at once. For example, makefiles often have
2628 a variable, such as `objects', containing a list of all the compiler
2629 output files in the system being made. An easy way to say that all of
2630 them must be recompiled if `config.h' changes is to write the following:
2632 objects = foo.o bar.o
2634 bar.o : defs.h test.h
2635 $(objects) : config.h
2637 This could be inserted or taken out without changing the rules that
2638 really specify how to make the object files, making it a convenient
2639 form to use if you wish to add the additional prerequisite
2642 Another wrinkle is that the additional prerequisites could be
2643 specified with a variable that you set with a command line argument to
2644 `make' (*note Overriding Variables: Overriding.). For example,
2647 $(objects) : $(extradeps)
2649 means that the command `make extradeps=foo.h' will consider `foo.h' as
2650 a prerequisite of each object file, but plain `make' will not.
2652 If none of the explicit rules for a target has a recipe, then `make'
2653 searches for an applicable implicit rule to find one *note Using
2654 Implicit Rules: Implicit Rules.).
2657 File: make.info, Node: Static Pattern, Next: Double-Colon, Prev: Multiple Rules, Up: Rules
2659 4.12 Static Pattern Rules
2660 =========================
2662 "Static pattern rules" are rules which specify multiple targets and
2663 construct the prerequisite names for each target based on the target
2664 name. They are more general than ordinary rules with multiple targets
2665 because the targets do not have to have identical prerequisites. Their
2666 prerequisites must be _analogous_, but not necessarily _identical_.
2670 * Static Usage:: The syntax of static pattern rules.
2671 * Static versus Implicit:: When are they better than implicit rules?
2674 File: make.info, Node: Static Usage, Next: Static versus Implicit, Prev: Static Pattern, Up: Static Pattern
2676 4.12.1 Syntax of Static Pattern Rules
2677 -------------------------------------
2679 Here is the syntax of a static pattern rule:
2681 TARGETS ...: TARGET-PATTERN: PREREQ-PATTERNS ...
2685 The TARGETS list specifies the targets that the rule applies to. The
2686 targets can contain wildcard characters, just like the targets of
2687 ordinary rules (*note Using Wildcard Characters in File Names:
2690 The TARGET-PATTERN and PREREQ-PATTERNS say how to compute the
2691 prerequisites of each target. Each target is matched against the
2692 TARGET-PATTERN to extract a part of the target name, called the "stem".
2693 This stem is substituted into each of the PREREQ-PATTERNS to make the
2694 prerequisite names (one from each PREREQ-PATTERN).
2696 Each pattern normally contains the character `%' just once. When the
2697 TARGET-PATTERN matches a target, the `%' can match any part of the
2698 target name; this part is called the "stem". The rest of the pattern
2699 must match exactly. For example, the target `foo.o' matches the
2700 pattern `%.o', with `foo' as the stem. The targets `foo.c' and
2701 `foo.out' do not match that pattern.
2703 The prerequisite names for each target are made by substituting the
2704 stem for the `%' in each prerequisite pattern. For example, if one
2705 prerequisite pattern is `%.c', then substitution of the stem `foo'
2706 gives the prerequisite name `foo.c'. It is legitimate to write a
2707 prerequisite pattern that does not contain `%'; then this prerequisite
2708 is the same for all targets.
2710 `%' characters in pattern rules can be quoted with preceding
2711 backslashes (`\'). Backslashes that would otherwise quote `%'
2712 characters can be quoted with more backslashes. Backslashes that quote
2713 `%' characters or other backslashes are removed from the pattern before
2714 it is compared to file names or has a stem substituted into it.
2715 Backslashes that are not in danger of quoting `%' characters go
2716 unmolested. For example, the pattern `the\%weird\\%pattern\\' has
2717 `the%weird\' preceding the operative `%' character, and `pattern\\'
2718 following it. The final two backslashes are left alone because they
2719 cannot affect any `%' character.
2721 Here is an example, which compiles each of `foo.o' and `bar.o' from
2722 the corresponding `.c' file:
2724 objects = foo.o bar.o
2728 $(objects): %.o: %.c
2729 $(CC) -c $(CFLAGS) $< -o $@
2731 Here `$<' is the automatic variable that holds the name of the
2732 prerequisite and `$@' is the automatic variable that holds the name of
2733 the target; see *note Automatic Variables::.
2735 Each target specified must match the target pattern; a warning is
2736 issued for each target that does not. If you have a list of files,
2737 only some of which will match the pattern, you can use the `filter'
2738 function to remove non-matching file names (*note Functions for String
2739 Substitution and Analysis: Text Functions.):
2741 files = foo.elc bar.o lose.o
2743 $(filter %.o,$(files)): %.o: %.c
2744 $(CC) -c $(CFLAGS) $< -o $@
2745 $(filter %.elc,$(files)): %.elc: %.el
2746 emacs -f batch-byte-compile $<
2748 In this example the result of `$(filter %.o,$(files))' is `bar.o
2749 lose.o', and the first static pattern rule causes each of these object
2750 files to be updated by compiling the corresponding C source file. The
2751 result of `$(filter %.elc,$(files))' is `foo.elc', so that file is made
2754 Another example shows how to use `$*' in static pattern rules:
2756 bigoutput littleoutput : %output : text.g
2757 generate text.g -$* > $@
2759 When the `generate' command is run, `$*' will expand to the stem,
2760 either `big' or `little'.
2763 File: make.info, Node: Static versus Implicit, Prev: Static Usage, Up: Static Pattern
2765 4.12.2 Static Pattern Rules versus Implicit Rules
2766 -------------------------------------------------
2768 A static pattern rule has much in common with an implicit rule defined
2769 as a pattern rule (*note Defining and Redefining Pattern Rules: Pattern
2770 Rules.). Both have a pattern for the target and patterns for
2771 constructing the names of prerequisites. The difference is in how
2772 `make' decides _when_ the rule applies.
2774 An implicit rule _can_ apply to any target that matches its pattern,
2775 but it _does_ apply only when the target has no recipe otherwise
2776 specified, and only when the prerequisites can be found. If more than
2777 one implicit rule appears applicable, only one applies; the choice
2778 depends on the order of rules.
2780 By contrast, a static pattern rule applies to the precise list of
2781 targets that you specify in the rule. It cannot apply to any other
2782 target and it invariably does apply to each of the targets specified.
2783 If two conflicting rules apply, and both have recipes, that's an error.
2785 The static pattern rule can be better than an implicit rule for these
2788 * You may wish to override the usual implicit rule for a few files
2789 whose names cannot be categorized syntactically but can be given
2790 in an explicit list.
2792 * If you cannot be sure of the precise contents of the directories
2793 you are using, you may not be sure which other irrelevant files
2794 might lead `make' to use the wrong implicit rule. The choice
2795 might depend on the order in which the implicit rule search is
2796 done. With static pattern rules, there is no uncertainty: each
2797 rule applies to precisely the targets specified.
2800 File: make.info, Node: Double-Colon, Next: Automatic Prerequisites, Prev: Static Pattern, Up: Rules
2802 4.13 Double-Colon Rules
2803 =======================
2805 "Double-colon" rules are explicit rules written with `::' instead of
2806 `:' after the target names. They are handled differently from ordinary
2807 rules when the same target appears in more than one rule. Pattern
2808 rules with double-colons have an entirely different meaning (*note
2809 Match-Anything Rules::).
2811 When a target appears in multiple rules, all the rules must be the
2812 same type: all ordinary, or all double-colon. If they are
2813 double-colon, each of them is independent of the others. Each
2814 double-colon rule's recipe is executed if the target is older than any
2815 prerequisites of that rule. If there are no prerequisites for that
2816 rule, its recipe is always executed (even if the target already
2817 exists). This can result in executing none, any, or all of the
2820 Double-colon rules with the same target are in fact completely
2821 separate from one another. Each double-colon rule is processed
2822 individually, just as rules with different targets are processed.
2824 The double-colon rules for a target are executed in the order they
2825 appear in the makefile. However, the cases where double-colon rules
2826 really make sense are those where the order of executing the recipes
2829 Double-colon rules are somewhat obscure and not often very useful;
2830 they provide a mechanism for cases in which the method used to update a
2831 target differs depending on which prerequisite files caused the update,
2832 and such cases are rare.
2834 Each double-colon rule should specify a recipe; if it does not, an
2835 implicit rule will be used if one applies. *Note Using Implicit Rules:
2839 File: make.info, Node: Automatic Prerequisites, Prev: Double-Colon, Up: Rules
2841 4.14 Generating Prerequisites Automatically
2842 ===========================================
2844 In the makefile for a program, many of the rules you need to write often
2845 say only that some object file depends on some header file. For
2846 example, if `main.c' uses `defs.h' via an `#include', you would write:
2850 You need this rule so that `make' knows that it must remake `main.o'
2851 whenever `defs.h' changes. You can see that for a large program you
2852 would have to write dozens of such rules in your makefile. And, you
2853 must always be very careful to update the makefile every time you add
2854 or remove an `#include'.
2856 To avoid this hassle, most modern C compilers can write these rules
2857 for you, by looking at the `#include' lines in the source files.
2858 Usually this is done with the `-M' option to the compiler. For
2859 example, the command:
2863 generates the output:
2865 main.o : main.c defs.h
2867 Thus you no longer have to write all those rules yourself. The
2868 compiler will do it for you.
2870 Note that such a rule constitutes mentioning `main.o' in a makefile,
2871 so it can never be considered an intermediate file by implicit rule
2872 search. This means that `make' won't ever remove the file after using
2873 it; *note Chains of Implicit Rules: Chained Rules.
2875 With old `make' programs, it was traditional practice to use this
2876 compiler feature to generate prerequisites on demand with a command like
2877 `make depend'. That command would create a file `depend' containing
2878 all the automatically-generated prerequisites; then the makefile could
2879 use `include' to read them in (*note Include::).
2881 In GNU `make', the feature of remaking makefiles makes this practice
2882 obsolete--you need never tell `make' explicitly to regenerate the
2883 prerequisites, because it always regenerates any makefile that is out
2884 of date. *Note Remaking Makefiles::.
2886 The practice we recommend for automatic prerequisite generation is
2887 to have one makefile corresponding to each source file. For each
2888 source file `NAME.c' there is a makefile `NAME.d' which lists what
2889 files the object file `NAME.o' depends on. That way only the source
2890 files that have changed need to be rescanned to produce the new
2893 Here is the pattern rule to generate a file of prerequisites (i.e.,
2894 a makefile) called `NAME.d' from a C source file called `NAME.c':
2897 @set -e; rm -f $@; \
2898 $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
2899 sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
2902 *Note Pattern Rules::, for information on defining pattern rules. The
2903 `-e' flag to the shell causes it to exit immediately if the `$(CC)'
2904 command (or any other command) fails (exits with a nonzero status).
2906 With the GNU C compiler, you may wish to use the `-MM' flag instead
2907 of `-M'. This omits prerequisites on system header files. *Note
2908 Options Controlling the Preprocessor: (gcc)Preprocessor Options, for
2911 The purpose of the `sed' command is to translate (for example):
2913 main.o : main.c defs.h
2917 main.o main.d : main.c defs.h
2919 This makes each `.d' file depend on all the source and header files
2920 that the corresponding `.o' file depends on. `make' then knows it must
2921 regenerate the prerequisites whenever any of the source or header files
2924 Once you've defined the rule to remake the `.d' files, you then use
2925 the `include' directive to read them all in. *Note Include::. For
2928 sources = foo.c bar.c
2930 include $(sources:.c=.d)
2932 (This example uses a substitution variable reference to translate the
2933 list of source files `foo.c bar.c' into a list of prerequisite
2934 makefiles, `foo.d bar.d'. *Note Substitution Refs::, for full
2935 information on substitution references.) Since the `.d' files are
2936 makefiles like any others, `make' will remake them as necessary with no
2937 further work from you. *Note Remaking Makefiles::.
2939 Note that the `.d' files contain target definitions; you should be
2940 sure to place the `include' directive _after_ the first, default goal
2941 in your makefiles or run the risk of having a random object file become
2942 the default goal. *Note How Make Works::.
2945 File: make.info, Node: Recipes, Next: Using Variables, Prev: Rules, Up: Top
2947 5 Writing Recipes in Rules
2948 **************************
2950 The recipe of a rule consists of one or more shell command lines to be
2951 executed, one at a time, in the order they appear. Typically, the
2952 result of executing these commands is that the target of the rule is
2955 Users use many different shell programs, but recipes in makefiles are
2956 always interpreted by `/bin/sh' unless the makefile specifies
2957 otherwise. *Note Recipe Execution: Execution.
2961 * Recipe Syntax:: Recipe syntax features and pitfalls.
2962 * Echoing:: How to control when recipes are echoed.
2963 * Execution:: How recipes are executed.
2964 * Parallel:: How recipes can be executed in parallel.
2965 * Errors:: What happens after a recipe execution error.
2966 * Interrupts:: What happens when a recipe is interrupted.
2967 * Recursion:: Invoking `make' from makefiles.
2968 * Canned Recipes:: Defining canned recipes.
2969 * Empty Recipes:: Defining useful, do-nothing recipes.
2972 File: make.info, Node: Recipe Syntax, Next: Echoing, Prev: Recipes, Up: Recipes
2977 Makefiles have the unusual property that there are really two distinct
2978 syntaxes in one file. Most of the makefile uses `make' syntax (*note
2979 Writing Makefiles: Makefiles.). However, recipes are meant to be
2980 interpreted by the shell and so they are written using shell syntax.
2981 The `make' program does not try to understand shell syntax: it performs
2982 only a very few specific translations on the content of the recipe
2983 before handing it to the shell.
2985 Each line in the recipe must start with a tab (or the first character
2986 in the value of the `.RECIPEPREFIX' variable; *note Special
2987 Variables::), except that the first recipe line may be attached to the
2988 target-and-prerequisites line with a semicolon in between. _Any_ line
2989 in the makefile that begins with a tab and appears in a "rule context"
2990 (that is, after a rule has been started until another rule or variable
2991 definition) will be considered part of a recipe for that rule. Blank
2992 lines and lines of just comments may appear among the recipe lines;
2995 Some consequences of these rules include:
2997 * A blank line that begins with a tab is not blank: it's an empty
2998 recipe (*note Empty Recipes::).
3000 * A comment in a recipe is not a `make' comment; it will be passed
3001 to the shell as-is. Whether the shell treats it as a comment or
3002 not depends on your shell.
3004 * A variable definition in a "rule context" which is indented by a
3005 tab as the first character on the line, will be considered part of
3006 a recipe, not a `make' variable definition, and passed to the
3009 * A conditional expression (`ifdef', `ifeq', etc. *note Syntax of
3010 Conditionals: Conditional Syntax.) in a "rule context" which is
3011 indented by a tab as the first character on the line, will be
3012 considered part of a recipe and be passed to the shell.
3017 * Splitting Recipe Lines:: Breaking long recipe lines for readability.
3018 * Variables in Recipes:: Using `make' variables in recipes.
3021 File: make.info, Node: Splitting Recipe Lines, Next: Variables in Recipes, Prev: Recipe Syntax, Up: Recipe Syntax
3023 5.1.1 Splitting Recipe Lines
3024 ----------------------------
3026 One of the few ways in which `make' does interpret recipes is checking
3027 for a backslash just before the newline. As in normal makefile syntax,
3028 a single logical recipe line can be split into multiple physical lines
3029 in the makefile by placing a backslash before each newline. A sequence
3030 of lines like this is considered a single recipe line, and one instance
3031 of the shell will be invoked to run it.
3033 However, in contrast to how they are treated in other places in a
3034 makefile (*note Splitting Long Lines: Splitting Lines.),
3035 backslash/newline pairs are _not_ removed from the recipe. Both the
3036 backslash and the newline characters are preserved and passed to the
3037 shell. How the backslash/newline is interpreted depends on your shell.
3038 If the first character of the next line after the backslash/newline is
3039 the recipe prefix character (a tab by default; *note Special
3040 Variables::), then that character (and only that character) is removed.
3041 Whitespace is never added to the recipe.
3043 For example, the recipe for the all target in this makefile:
3055 consists of four separate shell commands where the output is:
3062 As a more complex example, this makefile:
3064 all : ; @echo 'hello \
3065 world' ; echo "hello \
3068 will invoke one shell with a command of:
3071 world' ; echo "hello \
3074 which, according to shell quoting rules, will yield the following
3081 Notice how the backslash/newline pair was removed inside the string
3082 quoted with double quotes (`"..."'), but not from the string quoted
3083 with single quotes (`'...''). This is the way the default shell
3084 (`/bin/sh') handles backslash/newline pairs. If you specify a
3085 different shell in your makefiles it may treat them differently.
3087 Sometimes you want to split a long line inside of single quotes, but
3088 you don't want the backslash/newline to appear in the quoted content.
3089 This is often the case when passing scripts to languages such as Perl,
3090 where extraneous backslashes inside the script can change its meaning
3091 or even be a syntax error. One simple way of handling this is to place
3092 the quoted string, or even the entire command, into a `make' variable
3093 then use the variable in the recipe. In this situation the newline
3094 quoting rules for makefiles will be used, and the backslash/newline
3095 will be removed. If we rewrite our example above using this method:
3100 all : ; @echo $(HELLO)
3102 we will get output like this:
3106 If you like, you can also use target-specific variables (*note
3107 Target-specific Variable Values: Target-specific.) to obtain a tighter
3108 correspondence between the variable and the recipe that uses it.
3111 File: make.info, Node: Variables in Recipes, Prev: Splitting Recipe Lines, Up: Recipe Syntax
3113 5.1.2 Using Variables in Recipes
3114 --------------------------------
3116 The other way in which `make' processes recipes is by expanding any
3117 variable references in them (*note Basics of Variable References:
3118 Reference.). This occurs after make has finished reading all the
3119 makefiles and the target is determined to be out of date; so, the
3120 recipes for targets which are not rebuilt are never expanded.
3122 Variable and function references in recipes have identical syntax and
3123 semantics to references elsewhere in the makefile. They also have the
3124 same quoting rules: if you want a dollar sign to appear in your recipe,
3125 you must double it (`$$'). For shells like the default shell, that use
3126 dollar signs to introduce variables, it's important to keep clear in
3127 your mind whether the variable you want to reference is a `make'
3128 variable (use a single dollar sign) or a shell variable (use two dollar
3129 signs). For example:
3131 LIST = one two three
3133 for i in $(LIST); do \
3137 results in the following command being passed to the shell:
3139 for i in one two three; do \
3143 which generates the expected result:
3150 File: make.info, Node: Echoing, Next: Execution, Prev: Recipe Syntax, Up: Recipes
3155 Normally `make' prints each line of the recipe before it is executed.
3156 We call this "echoing" because it gives the appearance that you are
3157 typing the lines yourself.
3159 When a line starts with `@', the echoing of that line is suppressed.
3160 The `@' is discarded before the line is passed to the shell. Typically
3161 you would use this for a command whose only effect is to print
3162 something, such as an `echo' command to indicate progress through the
3165 @echo About to make distribution files
3167 When `make' is given the flag `-n' or `--just-print' it only echoes
3168 most recipes, without executing them. *Note Summary of Options:
3169 Options Summary. In this case even the recipe lines starting with `@'
3170 are printed. This flag is useful for finding out which recipes `make'
3171 thinks are necessary without actually doing them.
3173 The `-s' or `--silent' flag to `make' prevents all echoing, as if
3174 all recipes started with `@'. A rule in the makefile for the special
3175 target `.SILENT' without prerequisites has the same effect (*note
3176 Special Built-in Target Names: Special Targets.). `.SILENT' is
3177 essentially obsolete since `@' is more flexible.
3180 File: make.info, Node: Execution, Next: Parallel, Prev: Echoing, Up: Recipes
3182 5.3 Recipe Execution
3183 ====================
3185 When it is time to execute recipes to update a target, they are
3186 executed by invoking a new sub-shell for each line of the recipe,
3187 unless the `.ONESHELL' special target is in effect (*note Using One
3188 Shell: One Shell.) (In practice, `make' may take shortcuts that do not
3189 affect the results.)
3191 *Please note:* this implies that setting shell variables and
3192 invoking shell commands such as `cd' that set a context local to each
3193 process will not affect the following lines in the recipe.(1) If you
3194 want to use `cd' to affect the next statement, put both statements in a
3195 single recipe line. Then `make' will invoke one shell to run the
3196 entire line, and the shell will execute the statements in sequence.
3200 cd $(@D) && gobble $(@F) > ../$@
3202 Here we use the shell AND operator (`&&') so that if the `cd' command
3203 fails, the script will fail without trying to invoke the `gobble'
3204 command in the wrong directory, which could cause problems (in this
3205 case it would certainly cause `../foo' to be truncated, at least).
3209 * One Shell:: One shell for all lines in a recipe.
3210 * Choosing the Shell:: How `make' chooses the shell used
3213 ---------- Footnotes ----------
3215 (1) On MS-DOS, the value of current working directory is *global*, so
3216 changing it _will_ affect the following recipe lines on those systems.
3219 File: make.info, Node: One Shell, Next: Choosing the Shell, Prev: Execution, Up: Execution
3221 5.3.1 Using One Shell
3222 ---------------------
3224 Sometimes you would prefer that all the lines in the recipe be passed
3225 to a single invocation of the shell. There are generally two
3226 situations where this is useful: first, it can improve performance in
3227 makefiles where recipes consist of many command lines, by avoiding
3228 extra processes. Second, you might want newlines to be included in
3229 your recipe command (for example perhaps you are using a very different
3230 interpreter as your `SHELL'). If the `.ONESHELL' special target
3231 appears anywhere in the makefile then _all_ recipe lines for each
3232 target will be provided to a single invocation of the shell. Newlines
3233 between recipe lines will be preserved. For example:
3238 gobble $(@F) > ../$@
3240 would now work as expected even though the commands are on different
3243 If `.ONESHELL' is provided, then only the first line of the recipe
3244 will be checked for the special prefix characters (`@', `-', and `+').
3245 Subsequent lines will include the special characters in the recipe line
3246 when the `SHELL' is invoked. If you want your recipe to start with one
3247 of these special characters you'll need to arrange for them to not be
3248 the first characters on the first line, perhaps by adding a comment or
3249 similar. For example, this would be a syntax error in Perl because the
3250 first `@' is removed by make:
3253 SHELL = /usr/bin/perl
3259 However, either of these alternatives would work properly:
3262 SHELL = /usr/bin/perl
3265 # Make sure "@" is not the first character on the first line
3272 SHELL = /usr/bin/perl
3278 As a special feature, if `SHELL' is determined to be a POSIX-style
3279 shell, the special prefix characters in "internal" recipe lines will
3280 _removed_ before the recipe is processed. This feature is intended to
3281 allow existing makefiles to add the `.ONESHELL' special target and
3282 still run properly without extensive modifications. Since the special
3283 prefix characters are not legal at the beginning of a line in a POSIX
3284 shell script this is not a loss in functionality. For example, this
3290 @gobble $(@F) > ../$@
3292 Even with this special feature, however, makefiles with `.ONESHELL'
3293 will behave differently in ways that could be noticeable. For example,
3294 normally if any line in the recipe fails, that causes the rule to fail
3295 and no more recipe lines are processed. Under `.ONESHELL' a failure of
3296 any but the final recipe line will not be noticed by `make'. You can
3297 modify `.SHELLFLAGS' to add the `-e' option to the shell which will
3298 cause any failure anywhere in the command line to cause the shell to
3299 fail, but this could itself cause your recipe to behave differently.
3300 Ultimately you may need to harden your recipe lines to allow them to
3301 work with `.ONESHELL'.
3304 File: make.info, Node: Choosing the Shell, Prev: One Shell, Up: Execution
3306 5.3.2 Choosing the Shell
3307 ------------------------
3309 The program used as the shell is taken from the variable `SHELL'. If
3310 this variable is not set in your makefile, the program `/bin/sh' is
3311 used as the shell. The argument(s) passed to the shell are taken from
3312 the variable `.SHELLFLAGS'. The default value of `.SHELLFLAGS' is `-c'
3313 normally, or `-ec' in POSIX-conforming mode.
3315 Unlike most variables, the variable `SHELL' is never set from the
3316 environment. This is because the `SHELL' environment variable is used
3317 to specify your personal choice of shell program for interactive use.
3318 It would be very bad for personal choices like this to affect the
3319 functioning of makefiles. *Note Variables from the Environment:
3322 Furthermore, when you do set `SHELL' in your makefile that value is
3323 _not_ exported in the environment to recipe lines that `make' invokes.
3324 Instead, the value inherited from the user's environment, if any, is
3325 exported. You can override this behavior by explicitly exporting
3326 `SHELL' (*note Communicating Variables to a Sub-`make':
3327 Variables/Recursion.), forcing it to be passed in the environment to
3330 However, on MS-DOS and MS-Windows the value of `SHELL' in the
3331 environment *is* used, since on those systems most users do not set
3332 this variable, and therefore it is most likely set specifically to be
3333 used by `make'. On MS-DOS, if the setting of `SHELL' is not suitable
3334 for `make', you can set the variable `MAKESHELL' to the shell that
3335 `make' should use; if set it will be used as the shell instead of the
3338 Choosing a Shell in DOS and Windows
3339 ...................................
3341 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3344 On MS-DOS, if `SHELL' is not set, the value of the variable
3345 `COMSPEC' (which is always set) is used instead.
3347 The processing of lines that set the variable `SHELL' in Makefiles
3348 is different on MS-DOS. The stock shell, `command.com', is
3349 ridiculously limited in its functionality and many users of `make' tend
3350 to install a replacement shell. Therefore, on MS-DOS, `make' examines
3351 the value of `SHELL', and changes its behavior based on whether it
3352 points to a Unix-style or DOS-style shell. This allows reasonable
3353 functionality even if `SHELL' points to `command.com'.
3355 If `SHELL' points to a Unix-style shell, `make' on MS-DOS
3356 additionally checks whether that shell can indeed be found; if not, it
3357 ignores the line that sets `SHELL'. In MS-DOS, GNU `make' searches for
3358 the shell in the following places:
3360 1. In the precise place pointed to by the value of `SHELL'. For
3361 example, if the makefile specifies `SHELL = /bin/sh', `make' will
3362 look in the directory `/bin' on the current drive.
3364 2. In the current directory.
3366 3. In each of the directories in the `PATH' variable, in order.
3369 In every directory it examines, `make' will first look for the
3370 specific file (`sh' in the example above). If this is not found, it
3371 will also look in that directory for that file with one of the known
3372 extensions which identify executable files. For example `.exe',
3373 `.com', `.bat', `.btm', `.sh', and some others.
3375 If any of these attempts is successful, the value of `SHELL' will be
3376 set to the full pathname of the shell as found. However, if none of
3377 these is found, the value of `SHELL' will not be changed, and thus the
3378 line that sets it will be effectively ignored. This is so `make' will
3379 only support features specific to a Unix-style shell if such a shell is
3380 actually installed on the system where `make' runs.
3382 Note that this extended search for the shell is limited to the cases
3383 where `SHELL' is set from the Makefile; if it is set in the environment
3384 or command line, you are expected to set it to the full pathname of the
3385 shell, exactly as things are on Unix.
3387 The effect of the above DOS-specific processing is that a Makefile
3388 that contains `SHELL = /bin/sh' (as many Unix makefiles do), will work
3389 on MS-DOS unaltered if you have e.g. `sh.exe' installed in some
3390 directory along your `PATH'.
3393 File: make.info, Node: Parallel, Next: Errors, Prev: Execution, Up: Recipes
3395 5.4 Parallel Execution
3396 ======================
3398 GNU `make' knows how to execute several recipes at once. Normally,
3399 `make' will execute only one recipe at a time, waiting for it to finish
3400 before executing the next. However, the `-j' or `--jobs' option tells
3401 `make' to execute many recipes simultaneously. You can inhibit
3402 parallelism in a particular makefile with the `.NOTPARALLEL'
3403 pseudo-target (*note Special Built-in Target Names: Special Targets.).
3405 On MS-DOS, the `-j' option has no effect, since that system doesn't
3406 support multi-processing.
3408 If the `-j' option is followed by an integer, this is the number of
3409 recipes to execute at once; this is called the number of "job slots".
3410 If there is nothing looking like an integer after the `-j' option,
3411 there is no limit on the number of job slots. The default number of job
3412 slots is one, which means serial execution (one thing at a time).
3414 Handling recursive `make' invocations raises issues for parallel
3415 execution. For more information on this, see *note Communicating
3416 Options to a Sub-`make': Options/Recursion.
3418 If a recipe fails (is killed by a signal or exits with a nonzero
3419 status), and errors are not ignored for that recipe (*note Errors in
3420 Recipes: Errors.), the remaining recipe lines to remake the same target
3421 will not be run. If a recipe fails and the `-k' or `--keep-going'
3422 option was not given (*note Summary of Options: Options Summary.),
3423 `make' aborts execution. If make terminates for any reason (including
3424 a signal) with child processes running, it waits for them to finish
3425 before actually exiting.
3427 When the system is heavily loaded, you will probably want to run
3428 fewer jobs than when it is lightly loaded. You can use the `-l' option
3429 to tell `make' to limit the number of jobs to run at once, based on the
3430 load average. The `-l' or `--max-load' option is followed by a
3431 floating-point number. For example,
3435 will not let `make' start more than one job if the load average is
3436 above 2.5. The `-l' option with no following number removes the load
3437 limit, if one was given with a previous `-l' option.
3439 More precisely, when `make' goes to start up a job, and it already
3440 has at least one job running, it checks the current load average; if it
3441 is not lower than the limit given with `-l', `make' waits until the load
3442 average goes below that limit, or until all the other jobs finish.
3444 By default, there is no load limit.
3448 * Parallel Output:: Handling output during parallel execution
3449 * Parallel Input:: Handling input during parallel execution
3452 File: make.info, Node: Parallel Output, Next: Parallel Input, Prev: Parallel, Up: Parallel
3454 5.4.1 Output During Parallel Execution
3455 --------------------------------------
3457 When running several recipes in parallel the output from each recipe
3458 appears as soon as it is generated, with the result that messages from
3459 different recipes may be interspersed, sometimes even appearing on the
3460 same line. This can make reading the output very difficult.
3462 To avoid this you can use the `--output-sync' (`-O') option. This
3463 option instructs `make' to save the output from the commands it invokes
3464 and print it all once the commands are completed. Additionally, if
3465 there are multiple recursive `make' invocations running in parallel,
3466 they will communicate so that only one of them is generating output at
3469 If working directory printing is enabled (*note The
3470 `--print-directory' Option: -w Option.), the enter/leave messages are
3471 printed around each output grouping. If you prefer not to see these
3472 messages add the `--no-print-directory' option to `MAKEFLAGS'.
3474 There are four levels of granularity when synchronizing output,
3475 specified by giving an argument to the option (e.g., `-Oline' or
3476 `--output-sync=recurse').
3479 This is the default: all output is sent directly as it is
3480 generated and no synchronization is performed.
3483 Output from each individual line of the recipe is grouped and
3484 printed as soon as that line is complete. If a recipe consists of
3485 multiple lines, they may be interspersed with lines from other
3489 Output from the entire recipe for each target is grouped and
3490 printed once the target is complete. This is the default if the
3491 `--output-sync' or `-O' option is given with no argument.
3494 Output from each recursive invocation of `make' is grouped and
3495 printed once the recursive invocation is complete.
3498 Regardless of the mode chosen, the total build time will be the same.
3499 The only difference is in how the output appears.
3501 The `target' and `recurse' modes both collect the output of the
3502 entire recipe of a target and display it uninterrupted when the recipe
3503 completes. The difference between them is in how recipes that contain
3504 recursive invocations of `make' are treated (*note Recursive Use of
3505 `make': Recursion.). For all recipes which have no recursive lines,
3506 the `target' and `recurse' modes behave identically.
3508 If the `recurse' mode is chosen, recipes that contain recursive
3509 `make' invocations are treated the same as other targets: the output
3510 from the recipe, including the output from the recursive `make', is
3511 saved and printed after the entire recipe is complete. This ensures
3512 output from all the targets built by a given recursive `make' instance
3513 are grouped together, which may make the output easier to understand.
3514 However it also leads to long periods of time during the build where no
3515 output is seen, followed by large bursts of output. If you are not
3516 watching the build as it proceeds, but instead viewing a log of the
3517 build after the fact, this may be the best option for you.
3519 If you are watching the output, the long gaps of quiet during the
3520 build can be frustrating. The `target' output synchronization mode
3521 detects when `make' is going to be invoked recursively, using the
3522 standard methods, and it will not synchronize the output of those
3523 lines. The recursive `make' will perform the synchronization for its
3524 targets and the output from each will be displayed immediately when it
3525 completes. Be aware that output from recursive lines of the recipe are
3526 not synchronized (for example if the recursive line prints a message
3527 before running `make', that message will not be synchronized).
3529 The `line' mode can be useful for front-ends that are watching the
3530 output of `make' to track when recipes are started and completed.
3532 Some programs invoked by `make' may behave differently if they
3533 determine they're writing output to a terminal versus a file (often
3534 described as "interactive" vs. "non-interactive" modes). For example,
3535 many programs that can display colorized output will not do so if they
3536 determine they are not writing to a terminal. If your makefile invokes
3537 a program like this then using the output synchronization options will
3538 cause the program to believe it's running in "non-interactive" mode
3539 even though the output will ultimately go to the terminal.
3542 File: make.info, Node: Parallel Input, Prev: Parallel Output, Up: Parallel
3544 5.4.2 Input During Parallel Execution
3545 -------------------------------------
3547 Two processes cannot both take input from the same device at the same
3548 time. To make sure that only one recipe tries to take input from the
3549 terminal at once, `make' will invalidate the standard input streams of
3550 all but one running recipe. If another recipe attempts to read from
3551 standard input it will usually incur a fatal error (a `Broken pipe'
3554 It is unpredictable which recipe will have a valid standard input
3555 stream (which will come from the terminal, or wherever you redirect the
3556 standard input of `make'). The first recipe run will always get it
3557 first, and the first recipe started after that one finishes will get it
3560 We will change how this aspect of `make' works if we find a better
3561 alternative. In the mean time, you should not rely on any recipe using
3562 standard input at all if you are using the parallel execution feature;
3563 but if you are not using this feature, then standard input works
3564 normally in all recipes.
3567 File: make.info, Node: Errors, Next: Interrupts, Prev: Parallel, Up: Recipes
3569 5.5 Errors in Recipes
3570 =====================
3572 After each shell invocation returns, `make' looks at its exit status.
3573 If the shell completed successfully (the exit status is zero), the next
3574 line in the recipe is executed in a new shell; after the last line is
3575 finished, the rule is finished.
3577 If there is an error (the exit status is nonzero), `make' gives up on
3578 the current rule, and perhaps on all rules.
3580 Sometimes the failure of a certain recipe line does not indicate a
3581 problem. For example, you may use the `mkdir' command to ensure that a
3582 directory exists. If the directory already exists, `mkdir' will report
3583 an error, but you probably want `make' to continue regardless.
3585 To ignore errors in a recipe line, write a `-' at the beginning of
3586 the line's text (after the initial tab). The `-' is discarded before
3587 the line is passed to the shell for execution.
3594 This causes `make' to continue even if `rm' is unable to remove a file.
3596 When you run `make' with the `-i' or `--ignore-errors' flag, errors
3597 are ignored in all recipes of all rules. A rule in the makefile for
3598 the special target `.IGNORE' has the same effect, if there are no
3599 prerequisites. These ways of ignoring errors are obsolete because `-'
3602 When errors are to be ignored, because of either a `-' or the `-i'
3603 flag, `make' treats an error return just like success, except that it
3604 prints out a message that tells you the status code the shell exited
3605 with, and says that the error has been ignored.
3607 When an error happens that `make' has not been told to ignore, it
3608 implies that the current target cannot be correctly remade, and neither
3609 can any other that depends on it either directly or indirectly. No
3610 further recipes will be executed for these targets, since their
3611 preconditions have not been achieved.
3613 Normally `make' gives up immediately in this circumstance, returning
3614 a nonzero status. However, if the `-k' or `--keep-going' flag is
3615 specified, `make' continues to consider the other prerequisites of the
3616 pending targets, remaking them if necessary, before it gives up and
3617 returns nonzero status. For example, after an error in compiling one
3618 object file, `make -k' will continue compiling other object files even
3619 though it already knows that linking them will be impossible. *Note
3620 Summary of Options: Options Summary.
3622 The usual behavior assumes that your purpose is to get the specified
3623 targets up to date; once `make' learns that this is impossible, it
3624 might as well report the failure immediately. The `-k' option says
3625 that the real purpose is to test as many of the changes made in the
3626 program as possible, perhaps to find several independent problems so
3627 that you can correct them all before the next attempt to compile. This
3628 is why Emacs' `compile' command passes the `-k' flag by default.
3630 Usually when a recipe line fails, if it has changed the target file
3631 at all, the file is corrupted and cannot be used--or at least it is not
3632 completely updated. Yet the file's time stamp says that it is now up to
3633 date, so the next time `make' runs, it will not try to update that
3634 file. The situation is just the same as when the shell is killed by a
3635 signal; *note Interrupts::. So generally the right thing to do is to
3636 delete the target file if the recipe fails after beginning to change
3637 the file. `make' will do this if `.DELETE_ON_ERROR' appears as a
3638 target. This is almost always what you want `make' to do, but it is
3639 not historical practice; so for compatibility, you must explicitly
3643 File: make.info, Node: Interrupts, Next: Recursion, Prev: Errors, Up: Recipes
3645 5.6 Interrupting or Killing `make'
3646 ==================================
3648 If `make' gets a fatal signal while a shell is executing, it may delete
3649 the target file that the recipe was supposed to update. This is done
3650 if the target file's last-modification time has changed since `make'
3653 The purpose of deleting the target is to make sure that it is remade
3654 from scratch when `make' is next run. Why is this? Suppose you type
3655 `Ctrl-c' while a compiler is running, and it has begun to write an
3656 object file `foo.o'. The `Ctrl-c' kills the compiler, resulting in an
3657 incomplete file whose last-modification time is newer than the source
3658 file `foo.c'. But `make' also receives the `Ctrl-c' signal and deletes
3659 this incomplete file. If `make' did not do this, the next invocation
3660 of `make' would think that `foo.o' did not require updating--resulting
3661 in a strange error message from the linker when it tries to link an
3662 object file half of which is missing.
3664 You can prevent the deletion of a target file in this way by making
3665 the special target `.PRECIOUS' depend on it. Before remaking a target,
3666 `make' checks to see whether it appears on the prerequisites of
3667 `.PRECIOUS', and thereby decides whether the target should be deleted
3668 if a signal happens. Some reasons why you might do this are that the
3669 target is updated in some atomic fashion, or exists only to record a
3670 modification-time (its contents do not matter), or must exist at all
3671 times to prevent other sorts of trouble.
3674 File: make.info, Node: Recursion, Next: Canned Recipes, Prev: Interrupts, Up: Recipes
3676 5.7 Recursive Use of `make'
3677 ===========================
3679 Recursive use of `make' means using `make' as a command in a makefile.
3680 This technique is useful when you want separate makefiles for various
3681 subsystems that compose a larger system. For example, suppose you have
3682 a sub-directory `subdir' which has its own makefile, and you would like
3683 the containing directory's makefile to run `make' on the sub-directory.
3684 You can do it by writing this:
3687 cd subdir && $(MAKE)
3689 or, equivalently, this (*note Summary of Options: Options Summary.):
3694 You can write recursive `make' commands just by copying this example,
3695 but there are many things to know about how they work and why, and about
3696 how the sub-`make' relates to the top-level `make'. You may also find
3697 it useful to declare targets that invoke recursive `make' commands as
3698 `.PHONY' (for more discussion on when this is useful, see *note Phony
3701 For your convenience, when GNU `make' starts (after it has processed
3702 any `-C' options) it sets the variable `CURDIR' to the pathname of the
3703 current working directory. This value is never touched by `make'
3704 again: in particular note that if you include files from other
3705 directories the value of `CURDIR' does not change. The value has the
3706 same precedence it would have if it were set in the makefile (by
3707 default, an environment variable `CURDIR' will not override this
3708 value). Note that setting this variable has no impact on the operation
3709 of `make' (it does not cause `make' to change its working directory,
3714 * MAKE Variable:: The special effects of using `$(MAKE)'.
3715 * Variables/Recursion:: How to communicate variables to a sub-`make'.
3716 * Options/Recursion:: How to communicate options to a sub-`make'.
3717 * -w Option:: How the `-w' or `--print-directory' option
3718 helps debug use of recursive `make' commands.
3721 File: make.info, Node: MAKE Variable, Next: Variables/Recursion, Prev: Recursion, Up: Recursion
3723 5.7.1 How the `MAKE' Variable Works
3724 -----------------------------------
3726 Recursive `make' commands should always use the variable `MAKE', not
3727 the explicit command name `make', as shown here:
3730 cd subdir && $(MAKE)
3732 The value of this variable is the file name with which `make' was
3733 invoked. If this file name was `/bin/make', then the recipe executed
3734 is `cd subdir && /bin/make'. If you use a special version of `make' to
3735 run the top-level makefile, the same special version will be executed
3736 for recursive invocations.
3738 As a special feature, using the variable `MAKE' in the recipe of a
3739 rule alters the effects of the `-t' (`--touch'), `-n' (`--just-print'),
3740 or `-q' (`--question') option. Using the `MAKE' variable has the same
3741 effect as using a `+' character at the beginning of the recipe line.
3742 *Note Instead of Executing the Recipes: Instead of Execution. This
3743 special feature is only enabled if the `MAKE' variable appears directly
3744 in the recipe: it does not apply if the `MAKE' variable is referenced
3745 through expansion of another variable. In the latter case you must use
3746 the `+' token to get these special effects.
3748 Consider the command `make -t' in the above example. (The `-t'
3749 option marks targets as up to date without actually running any
3750 recipes; see *note Instead of Execution::.) Following the usual
3751 definition of `-t', a `make -t' command in the example would create a
3752 file named `subsystem' and do nothing else. What you really want it to
3753 do is run `cd subdir && make -t'; but that would require executing the
3754 recipe, and `-t' says not to execute recipes.
3756 The special feature makes this do what you want: whenever a recipe
3757 line of a rule contains the variable `MAKE', the flags `-t', `-n' and
3758 `-q' do not apply to that line. Recipe lines containing `MAKE' are
3759 executed normally despite the presence of a flag that causes most
3760 recipes not to be run. The usual `MAKEFLAGS' mechanism passes the
3761 flags to the sub-`make' (*note Communicating Options to a Sub-`make':
3762 Options/Recursion.), so your request to touch the files, or print the
3763 recipes, is propagated to the subsystem.
3766 File: make.info, Node: Variables/Recursion, Next: Options/Recursion, Prev: MAKE Variable, Up: Recursion
3768 5.7.2 Communicating Variables to a Sub-`make'
3769 ---------------------------------------------
3771 Variable values of the top-level `make' can be passed to the sub-`make'
3772 through the environment by explicit request. These variables are
3773 defined in the sub-`make' as defaults, but they do not override
3774 variables defined in the makefile used by the sub-`make' unless you use
3775 the `-e' switch (*note Summary of Options: Options Summary.).
3777 To pass down, or "export", a variable, `make' adds the variable and
3778 its value to the environment for running each line of the recipe. The
3779 sub-`make', in turn, uses the environment to initialize its table of
3780 variable values. *Note Variables from the Environment: Environment.
3782 Except by explicit request, `make' exports a variable only if it is
3783 either defined in the environment initially or set on the command line,
3784 and if its name consists only of letters, numbers, and underscores.
3785 Some shells cannot cope with environment variable names consisting of
3786 characters other than letters, numbers, and underscores.
3788 The value of the `make' variable `SHELL' is not exported. Instead,
3789 the value of the `SHELL' variable from the invoking environment is
3790 passed to the sub-`make'. You can force `make' to export its value for
3791 `SHELL' by using the `export' directive, described below. *Note
3792 Choosing the Shell::.
3794 The special variable `MAKEFLAGS' is always exported (unless you
3795 unexport it). `MAKEFILES' is exported if you set it to anything.
3797 `make' automatically passes down variable values that were defined
3798 on the command line, by putting them in the `MAKEFLAGS' variable.
3799 *Note Options/Recursion::.
3801 Variables are _not_ normally passed down if they were created by
3802 default by `make' (*note Variables Used by Implicit Rules: Implicit
3803 Variables.). The sub-`make' will define these for itself.
3805 If you want to export specific variables to a sub-`make', use the
3806 `export' directive, like this:
3810 If you want to _prevent_ a variable from being exported, use the
3811 `unexport' directive, like this:
3813 unexport VARIABLE ...
3815 In both of these forms, the arguments to `export' and `unexport' are
3816 expanded, and so could be variables or functions which expand to a
3817 (list of) variable names to be (un)exported.
3819 As a convenience, you can define a variable and export it at the same
3822 export VARIABLE = value
3824 has the same result as:
3831 export VARIABLE := value
3833 has the same result as:
3840 export VARIABLE += value
3847 *Note Appending More Text to Variables: Appending.
3849 You may notice that the `export' and `unexport' directives work in
3850 `make' in the same way they work in the shell, `sh'.
3852 If you want all variables to be exported by default, you can use
3857 This tells `make' that variables which are not explicitly mentioned in
3858 an `export' or `unexport' directive should be exported. Any variable
3859 given in an `unexport' directive will still _not_ be exported. If you
3860 use `export' by itself to export variables by default, variables whose
3861 names contain characters other than alphanumerics and underscores will
3862 not be exported unless specifically mentioned in an `export' directive.
3864 The behavior elicited by an `export' directive by itself was the
3865 default in older versions of GNU `make'. If your makefiles depend on
3866 this behavior and you want to be compatible with old versions of
3867 `make', you can write a rule for the special target
3868 `.EXPORT_ALL_VARIABLES' instead of using the `export' directive. This
3869 will be ignored by old `make's, while the `export' directive will cause
3872 Likewise, you can use `unexport' by itself to tell `make' _not_ to
3873 export variables by default. Since this is the default behavior, you
3874 would only need to do this if `export' had been used by itself earlier
3875 (in an included makefile, perhaps). You *cannot* use `export' and
3876 `unexport' by themselves to have variables exported for some recipes
3877 and not for others. The last `export' or `unexport' directive that
3878 appears by itself determines the behavior for the entire run of `make'.
3880 As a special feature, the variable `MAKELEVEL' is changed when it is
3881 passed down from level to level. This variable's value is a string
3882 which is the depth of the level as a decimal number. The value is `0'
3883 for the top-level `make'; `1' for a sub-`make', `2' for a
3884 sub-sub-`make', and so on. The incrementation happens when `make' sets
3885 up the environment for a recipe.
3887 The main use of `MAKELEVEL' is to test it in a conditional directive
3888 (*note Conditional Parts of Makefiles: Conditionals.); this way you can
3889 write a makefile that behaves one way if run recursively and another
3890 way if run directly by you.
3892 You can use the variable `MAKEFILES' to cause all sub-`make'
3893 commands to use additional makefiles. The value of `MAKEFILES' is a
3894 whitespace-separated list of file names. This variable, if defined in
3895 the outer-level makefile, is passed down through the environment; then
3896 it serves as a list of extra makefiles for the sub-`make' to read
3897 before the usual or specified ones. *Note The Variable `MAKEFILES':
3901 File: make.info, Node: Options/Recursion, Next: -w Option, Prev: Variables/Recursion, Up: Recursion
3903 5.7.3 Communicating Options to a Sub-`make'
3904 -------------------------------------------
3906 Flags such as `-s' and `-k' are passed automatically to the sub-`make'
3907 through the variable `MAKEFLAGS'. This variable is set up
3908 automatically by `make' to contain the flag letters that `make'
3909 received. Thus, if you do `make -ks' then `MAKEFLAGS' gets the value
3912 As a consequence, every sub-`make' gets a value for `MAKEFLAGS' in
3913 its environment. In response, it takes the flags from that value and
3914 processes them as if they had been given as arguments. *Note Summary
3915 of Options: Options Summary.
3917 Likewise variables defined on the command line are passed to the
3918 sub-`make' through `MAKEFLAGS'. Words in the value of `MAKEFLAGS' that
3919 contain `=', `make' treats as variable definitions just as if they
3920 appeared on the command line. *Note Overriding Variables: Overriding.
3922 The options `-C', `-f', `-o', and `-W' are not put into `MAKEFLAGS';
3923 these options are not passed down.
3925 The `-j' option is a special case (*note Parallel Execution:
3926 Parallel.). If you set it to some numeric value `N' and your operating
3927 system supports it (most any UNIX system will; others typically won't),
3928 the parent `make' and all the sub-`make's will communicate to ensure
3929 that there are only `N' jobs running at the same time between them all.
3930 Note that any job that is marked recursive (*note Instead of Executing
3931 Recipes: Instead of Execution.) doesn't count against the total jobs
3932 (otherwise we could get `N' sub-`make's running and have no slots left
3933 over for any real work!)
3935 If your operating system doesn't support the above communication,
3936 then `-j 1' is always put into `MAKEFLAGS' instead of the value you
3937 specified. This is because if the `-j' option were passed down to
3938 sub-`make's, you would get many more jobs running in parallel than you
3939 asked for. If you give `-j' with no numeric argument, meaning to run
3940 as many jobs as possible in parallel, this is passed down, since
3941 multiple infinities are no more than one.
3943 If you do not want to pass the other flags down, you must change the
3944 value of `MAKEFLAGS', like this:
3947 cd subdir && $(MAKE) MAKEFLAGS=
3949 The command line variable definitions really appear in the variable
3950 `MAKEOVERRIDES', and `MAKEFLAGS' contains a reference to this variable.
3951 If you do want to pass flags down normally, but don't want to pass down
3952 the command line variable definitions, you can reset `MAKEOVERRIDES' to
3957 This is not usually useful to do. However, some systems have a small
3958 fixed limit on the size of the environment, and putting so much
3959 information into the value of `MAKEFLAGS' can exceed it. If you see
3960 the error message `Arg list too long', this may be the problem. (For
3961 strict compliance with POSIX.2, changing `MAKEOVERRIDES' does not
3962 affect `MAKEFLAGS' if the special target `.POSIX' appears in the
3963 makefile. You probably do not care about this.)
3965 A similar variable `MFLAGS' exists also, for historical
3966 compatibility. It has the same value as `MAKEFLAGS' except that it
3967 does not contain the command line variable definitions, and it always
3968 begins with a hyphen unless it is empty (`MAKEFLAGS' begins with a
3969 hyphen only when it begins with an option that has no single-letter
3970 version, such as `--warn-undefined-variables'). `MFLAGS' was
3971 traditionally used explicitly in the recursive `make' command, like
3975 cd subdir && $(MAKE) $(MFLAGS)
3977 but now `MAKEFLAGS' makes this usage redundant. If you want your
3978 makefiles to be compatible with old `make' programs, use this
3979 technique; it will work fine with more modern `make' versions too.
3981 The `MAKEFLAGS' variable can also be useful if you want to have
3982 certain options, such as `-k' (*note Summary of Options: Options
3983 Summary.), set each time you run `make'. You simply put a value for
3984 `MAKEFLAGS' in your environment. You can also set `MAKEFLAGS' in a
3985 makefile, to specify additional flags that should also be in effect for
3986 that makefile. (Note that you cannot use `MFLAGS' this way. That
3987 variable is set only for compatibility; `make' does not interpret a
3988 value you set for it in any way.)
3990 When `make' interprets the value of `MAKEFLAGS' (either from the
3991 environment or from a makefile), it first prepends a hyphen if the value
3992 does not already begin with one. Then it chops the value into words
3993 separated by blanks, and parses these words as if they were options
3994 given on the command line (except that `-C', `-f', `-h', `-o', `-W',
3995 and their long-named versions are ignored; and there is no error for an
3998 If you do put `MAKEFLAGS' in your environment, you should be sure not
3999 to include any options that will drastically affect the actions of
4000 `make' and undermine the purpose of makefiles and of `make' itself.
4001 For instance, the `-t', `-n', and `-q' options, if put in one of these
4002 variables, could have disastrous consequences and would certainly have
4003 at least surprising and probably annoying effects.
4005 If you'd like to run other implementations of `make' in addition to
4006 GNU `make', and hence do not want to add GNU `make'-specific flags to
4007 the `MAKEFLAGS' variable, you can add them to the `GNUMAKEFLAGS'
4008 variable instead. This variable is parsed just before `MAKEFLAGS', in
4009 the same way as `MAKEFLAGS'. When `make' constructs `MAKEFLAGS' to
4010 pass to a recursive `make' it will include all flags, even those taken
4011 from `GNUMAKEFLAGS'. As a result, after parsing `GNUMAKEFLAGS' GNU
4012 `make' sets this variable to the empty string to avoid duplicating
4013 flags during recursion.
4015 It's best to use `GNUMAKEFLAGS' only with flags which won't
4016 materially change the behavior of your makefiles. If your makefiles
4017 require GNU make anyway then simply use `MAKEFLAGS'. Flags such as
4018 `--no-print-directory' or `--output-sync' may be appropriate for
4022 File: make.info, Node: -w Option, Prev: Options/Recursion, Up: Recursion
4024 5.7.4 The `--print-directory' Option
4025 ------------------------------------
4027 If you use several levels of recursive `make' invocations, the `-w' or
4028 `--print-directory' option can make the output a lot easier to
4029 understand by showing each directory as `make' starts processing it and
4030 as `make' finishes processing it. For example, if `make -w' is run in
4031 the directory `/u/gnu/make', `make' will print a line of the form:
4033 make: Entering directory `/u/gnu/make'.
4035 before doing anything else, and a line of the form:
4037 make: Leaving directory `/u/gnu/make'.
4039 when processing is completed.
4041 Normally, you do not need to specify this option because `make' does
4042 it for you: `-w' is turned on automatically when you use the `-C'
4043 option, and in sub-`make's. `make' will not automatically turn on `-w'
4044 if you also use `-s', which says to be silent, or if you use
4045 `--no-print-directory' to explicitly disable it.
4048 File: make.info, Node: Canned Recipes, Next: Empty Recipes, Prev: Recursion, Up: Recipes
4050 5.8 Defining Canned Recipes
4051 ===========================
4053 When the same sequence of commands is useful in making various targets,
4054 you can define it as a canned sequence with the `define' directive, and
4055 refer to the canned sequence from the recipes for those targets. The
4056 canned sequence is actually a variable, so the name must not conflict
4057 with other variable names.
4059 Here is an example of defining a canned recipe:
4062 yacc $(firstword $^)
4066 Here `run-yacc' is the name of the variable being defined; `endef'
4067 marks the end of the definition; the lines in between are the commands.
4068 The `define' directive does not expand variable references and function
4069 calls in the canned sequence; the `$' characters, parentheses, variable
4070 names, and so on, all become part of the value of the variable you are
4071 defining. *Note Defining Multi-Line Variables: Multi-Line, for a
4072 complete explanation of `define'.
4074 The first command in this example runs Yacc on the first
4075 prerequisite of whichever rule uses the canned sequence. The output
4076 file from Yacc is always named `y.tab.c'. The second command moves the
4077 output to the rule's target file name.
4079 To use the canned sequence, substitute the variable into the recipe
4080 of a rule. You can substitute it like any other variable (*note Basics
4081 of Variable References: Reference.). Because variables defined by
4082 `define' are recursively expanded variables, all the variable
4083 references you wrote inside the `define' are expanded now. For example:
4088 `foo.y' will be substituted for the variable `$^' when it occurs in
4089 `run-yacc''s value, and `foo.c' for `$@'.
4091 This is a realistic example, but this particular one is not needed in
4092 practice because `make' has an implicit rule to figure out these
4093 commands based on the file names involved (*note Using Implicit Rules:
4096 In recipe execution, each line of a canned sequence is treated just
4097 as if the line appeared on its own in the rule, preceded by a tab. In
4098 particular, `make' invokes a separate sub-shell for each line. You can
4099 use the special prefix characters that affect command lines (`@', `-',
4100 and `+') on each line of a canned sequence. *Note Writing Recipes in
4101 Rules: Recipes. For example, using this canned sequence:
4104 @echo "frobnicating target $@"
4105 frob-step-1 $< -o $@-step-1
4106 frob-step-2 $@-step-1 -o $@
4109 `make' will not echo the first line, the `echo' command. But it _will_
4110 echo the following two recipe lines.
4112 On the other hand, prefix characters on the recipe line that refers
4113 to a canned sequence apply to every line in the sequence. So the rule:
4118 does not echo _any_ recipe lines. (*Note Recipe Echoing: Echoing, for
4119 a full explanation of `@'.)
4122 File: make.info, Node: Empty Recipes, Prev: Canned Recipes, Up: Recipes
4124 5.9 Using Empty Recipes
4125 =======================
4127 It is sometimes useful to define recipes which do nothing. This is done
4128 simply by giving a recipe that consists of nothing but whitespace. For
4133 defines an empty recipe for `target'. You could also use a line
4134 beginning with a recipe prefix character to define an empty recipe, but
4135 this would be confusing because such a line looks empty.
4137 You may be wondering why you would want to define a recipe that does
4138 nothing. The only reason this is useful is to prevent a target from
4139 getting implicit recipes (from implicit rules or the `.DEFAULT' special
4140 target; *note Implicit Rules:: and *note Defining Last-Resort Default
4141 Rules: Last Resort.).
4143 You may be inclined to define empty recipes for targets that are not
4144 actual files, but only exist so that their prerequisites can be remade.
4145 However, this is not the best way to do that, because the prerequisites
4146 may not be remade properly if the target file actually does exist.
4147 *Note Phony Targets: Phony Targets, for a better way to do this.
4150 File: make.info, Node: Using Variables, Next: Conditionals, Prev: Recipes, Up: Top
4152 6 How to Use Variables
4153 **********************
4155 A "variable" is a name defined in a makefile to represent a string of
4156 text, called the variable's "value". These values are substituted by
4157 explicit request into targets, prerequisites, recipes, and other parts
4158 of the makefile. (In some other versions of `make', variables are
4161 Variables and functions in all parts of a makefile are expanded when
4162 read, except for in recipes, the right-hand sides of variable
4163 definitions using `=', and the bodies of variable definitions using the
4166 Variables can represent lists of file names, options to pass to
4167 compilers, programs to run, directories to look in for source files,
4168 directories to write output in, or anything else you can imagine.
4170 A variable name may be any sequence of characters not containing
4171 `:', `#', `=', or whitespace. However, variable names containing
4172 characters other than letters, numbers, and underscores should be
4173 considered carefully, as in some shells they cannot be passed through
4174 the environment to a sub-`make' (*note Communicating Variables to a
4175 Sub-`make': Variables/Recursion.). Variable names beginning with `.'
4176 and an uppercase letter may be given special meaning in future versions
4179 Variable names are case-sensitive. The names `foo', `FOO', and
4180 `Foo' all refer to different variables.
4182 It is traditional to use upper case letters in variable names, but we
4183 recommend using lower case letters for variable names that serve
4184 internal purposes in the makefile, and reserving upper case for
4185 parameters that control implicit rules or for parameters that the user
4186 should override with command options (*note Overriding Variables:
4189 A few variables have names that are a single punctuation character or
4190 just a few characters. These are the "automatic variables", and they
4191 have particular specialized uses. *Note Automatic Variables::.
4195 * Reference:: How to use the value of a variable.
4196 * Flavors:: Variables come in two flavors.
4197 * Advanced:: Advanced features for referencing a variable.
4198 * Values:: All the ways variables get their values.
4199 * Setting:: How to set a variable in the makefile.
4200 * Appending:: How to append more text to the old value
4202 * Override Directive:: How to set a variable in the makefile even if
4203 the user has set it with a command argument.
4204 * Multi-Line:: An alternate way to set a variable
4205 to a multi-line string.
4206 * Undefine Directive:: How to undefine a variable so that it appears
4207 as if it was never set.
4208 * Environment:: Variable values can come from the environment.
4209 * Target-specific:: Variable values can be defined on a per-target
4211 * Pattern-specific:: Target-specific variable values can be applied
4212 to a group of targets that match a pattern.
4213 * Suppressing Inheritance:: Suppress inheritance of variables.
4214 * Special Variables:: Variables with special meaning or behavior.
4217 File: make.info, Node: Reference, Next: Flavors, Prev: Using Variables, Up: Using Variables
4219 6.1 Basics of Variable References
4220 =================================
4222 To substitute a variable's value, write a dollar sign followed by the
4223 name of the variable in parentheses or braces: either `$(foo)' or
4224 `${foo}' is a valid reference to the variable `foo'. This special
4225 significance of `$' is why you must write `$$' to have the effect of a
4226 single dollar sign in a file name or recipe.
4228 Variable references can be used in any context: targets,
4229 prerequisites, recipes, most directives, and new variable values. Here
4230 is an example of a common case, where a variable holds the names of all
4231 the object files in a program:
4233 objects = program.o foo.o utils.o
4234 program : $(objects)
4235 cc -o program $(objects)
4239 Variable references work by strict textual substitution. Thus, the
4243 prog.o : prog.$(foo)
4244 $(foo)$(foo) -$(foo) prog.$(foo)
4246 could be used to compile a C program `prog.c'. Since spaces before the
4247 variable value are ignored in variable assignments, the value of `foo'
4248 is precisely `c'. (Don't actually write your makefiles this way!)
4250 A dollar sign followed by a character other than a dollar sign,
4251 open-parenthesis or open-brace treats that single character as the
4252 variable name. Thus, you could reference the variable `x' with `$x'.
4253 However, this practice is strongly discouraged, except in the case of
4254 the automatic variables (*note Automatic Variables::).
4257 File: make.info, Node: Flavors, Next: Advanced, Prev: Reference, Up: Using Variables
4259 6.2 The Two Flavors of Variables
4260 ================================
4262 There are two ways that a variable in GNU `make' can have a value; we
4263 call them the two "flavors" of variables. The two flavors are
4264 distinguished in how they are defined and in what they do when expanded.
4266 The first flavor of variable is a "recursively expanded" variable.
4267 Variables of this sort are defined by lines using `=' (*note Setting
4268 Variables: Setting.) or by the `define' directive (*note Defining
4269 Multi-Line Variables: Multi-Line.). The value you specify is installed
4270 verbatim; if it contains references to other variables, these
4271 references are expanded whenever this variable is substituted (in the
4272 course of expanding some other string). When this happens, it is
4273 called "recursive expansion".
4283 will echo `Huh?': `$(foo)' expands to `$(bar)' which expands to
4284 `$(ugh)' which finally expands to `Huh?'.
4286 This flavor of variable is the only sort supported by most other
4287 versions of `make'. It has its advantages and its disadvantages. An
4288 advantage (most would say) is that:
4290 CFLAGS = $(include_dirs) -O
4291 include_dirs = -Ifoo -Ibar
4293 will do what was intended: when `CFLAGS' is expanded in a recipe, it
4294 will expand to `-Ifoo -Ibar -O'. A major disadvantage is that you
4295 cannot append something on the end of a variable, as in
4297 CFLAGS = $(CFLAGS) -O
4299 because it will cause an infinite loop in the variable expansion.
4300 (Actually `make' detects the infinite loop and reports an error.)
4302 Another disadvantage is that any functions (*note Functions for
4303 Transforming Text: Functions.) referenced in the definition will be
4304 executed every time the variable is expanded. This makes `make' run
4305 slower; worse, it causes the `wildcard' and `shell' functions to give
4306 unpredictable results because you cannot easily control when they are
4307 called, or even how many times.
4309 To avoid all the problems and inconveniences of recursively expanded
4310 variables, there is another flavor: simply expanded variables.
4312 "Simply expanded variables" are defined by lines using `:=' or `::='
4313 (*note Setting Variables: Setting.). Both forms are equivalent in GNU
4314 `make'; however only the `::=' form is described by the POSIX standard
4315 (support for `::=' was added to the POSIX standard in 2012, so older
4316 versions of `make' won't accept this form either).
4318 The value of a simply expanded variable is scanned once and for all,
4319 expanding any references to other variables and functions, when the
4320 variable is defined. The actual value of the simply expanded variable
4321 is the result of expanding the text that you write. It does not
4322 contain any references to other variables; it contains their values _as
4323 of the time this variable was defined_. Therefore,
4334 When a simply expanded variable is referenced, its value is
4335 substituted verbatim.
4337 Here is a somewhat more complicated example, illustrating the use of
4338 `:=' in conjunction with the `shell' function. (*Note The `shell'
4339 Function: Shell Function.) This example also shows use of the variable
4340 `MAKELEVEL', which is changed when it is passed down from level to
4341 level. (*Note Communicating Variables to a Sub-`make':
4342 Variables/Recursion, for information about `MAKELEVEL'.)
4344 ifeq (0,${MAKELEVEL})
4345 whoami := $(shell whoami)
4346 host-type := $(shell arch)
4347 MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
4350 An advantage of this use of `:=' is that a typical `descend into a
4351 directory' recipe then looks like this:
4356 Simply expanded variables generally make complicated makefile
4357 programming more predictable because they work like variables in most
4358 programming languages. They allow you to redefine a variable using its
4359 own value (or its value processed in some way by one of the expansion
4360 functions) and to use the expansion functions much more efficiently
4361 (*note Functions for Transforming Text: Functions.).
4363 You can also use them to introduce controlled leading whitespace into
4364 variable values. Leading whitespace characters are discarded from your
4365 input before substitution of variable references and function calls;
4366 this means you can include leading spaces in a variable value by
4367 protecting them with variable references, like this:
4370 space := $(nullstring) # end of the line
4372 Here the value of the variable `space' is precisely one space. The
4373 comment `# end of the line' is included here just for clarity. Since
4374 trailing space characters are _not_ stripped from variable values, just
4375 a space at the end of the line would have the same effect (but be
4376 rather hard to read). If you put whitespace at the end of a variable
4377 value, it is a good idea to put a comment like that at the end of the
4378 line to make your intent clear. Conversely, if you do _not_ want any
4379 whitespace characters at the end of your variable value, you must
4380 remember not to put a random comment on the end of the line after some
4381 whitespace, such as this:
4383 dir := /foo/bar # directory to put the frobs in
4385 Here the value of the variable `dir' is `/foo/bar ' (with four
4386 trailing spaces), which was probably not the intention. (Imagine
4387 something like `$(dir)/file' with this definition!)
4389 There is another assignment operator for variables, `?='. This is
4390 called a conditional variable assignment operator, because it only has
4391 an effect if the variable is not yet defined. This statement:
4395 is exactly equivalent to this (*note The `origin' Function: Origin
4398 ifeq ($(origin FOO), undefined)
4402 Note that a variable set to an empty value is still defined, so `?='
4403 will not set that variable.
4406 File: make.info, Node: Advanced, Next: Values, Prev: Flavors, Up: Using Variables
4408 6.3 Advanced Features for Reference to Variables
4409 ================================================
4411 This section describes some advanced features you can use to reference
4412 variables in more flexible ways.
4416 * Substitution Refs:: Referencing a variable with
4417 substitutions on the value.
4418 * Computed Names:: Computing the name of the variable to refer to.
4421 File: make.info, Node: Substitution Refs, Next: Computed Names, Prev: Advanced, Up: Advanced
4423 6.3.1 Substitution References
4424 -----------------------------
4426 A "substitution reference" substitutes the value of a variable with
4427 alterations that you specify. It has the form `$(VAR:A=B)' (or
4428 `${VAR:A=B}') and its meaning is to take the value of the variable VAR,
4429 replace every A at the end of a word with B in that value, and
4430 substitute the resulting string.
4432 When we say "at the end of a word", we mean that A must appear
4433 either followed by whitespace or at the end of the value in order to be
4434 replaced; other occurrences of A in the value are unaltered. For
4440 sets `bar' to `a.c b.c c.c'. *Note Setting Variables: Setting.
4442 A substitution reference is actually an abbreviation for use of the
4443 `patsubst' expansion function (*note Functions for String Substitution
4444 and Analysis: Text Functions.). We provide substitution references as
4445 well as `patsubst' for compatibility with other implementations of
4448 Another type of substitution reference lets you use the full power of
4449 the `patsubst' function. It has the same form `$(VAR:A=B)' described
4450 above, except that now A must contain a single `%' character. This
4451 case is equivalent to `$(patsubst A,B,$(VAR))'. *Note Functions for
4452 String Substitution and Analysis: Text Functions, for a description of
4453 the `patsubst' function.
4458 bar := $(foo:%.o=%.c)
4460 sets `bar' to `a.c b.c c.c'.
4463 File: make.info, Node: Computed Names, Prev: Substitution Refs, Up: Advanced
4465 6.3.2 Computed Variable Names
4466 -----------------------------
4468 Computed variable names are a complicated concept needed only for
4469 sophisticated makefile programming. For most purposes you need not
4470 consider them, except to know that making a variable with a dollar sign
4471 in its name might have strange results. However, if you are the type
4472 that wants to understand everything, or you are actually interested in
4473 what they do, read on.
4475 Variables may be referenced inside the name of a variable. This is
4476 called a "computed variable name" or a "nested variable reference".
4483 defines `a' as `z': the `$(x)' inside `$($(x))' expands to `y', so
4484 `$($(x))' expands to `$(y)' which in turn expands to `z'. Here the
4485 name of the variable to reference is not stated explicitly; it is
4486 computed by expansion of `$(x)'. The reference `$(x)' here is nested
4487 within the outer variable reference.
4489 The previous example shows two levels of nesting, but any number of
4490 levels is possible. For example, here are three levels:
4497 Here the innermost `$(x)' expands to `y', so `$($(x))' expands to
4498 `$(y)' which in turn expands to `z'; now we have `$(z)', which becomes
4501 References to recursively-expanded variables within a variable name
4502 are re-expanded in the usual fashion. For example:
4509 defines `a' as `Hello': `$($(x))' becomes `$($(y))' which becomes
4510 `$(z)' which becomes `Hello'.
4512 Nested variable references can also contain modified references and
4513 function invocations (*note Functions for Transforming Text:
4514 Functions.), just like any other reference. For example, using the
4515 `subst' function (*note Functions for String Substitution and Analysis:
4520 y = $(subst 1,2,$(x))
4524 eventually defines `a' as `Hello'. It is doubtful that anyone would
4525 ever want to write a nested reference as convoluted as this one, but it
4526 works: `$($($(z)))' expands to `$($(y))' which becomes `$($(subst
4527 1,2,$(x)))'. This gets the value `variable1' from `x' and changes it
4528 by substitution to `variable2', so that the entire string becomes
4529 `$(variable2)', a simple variable reference whose value is `Hello'.
4531 A computed variable name need not consist entirely of a single
4532 variable reference. It can contain several variable references, as
4533 well as some invariant text. For example,
4538 a_files := filea fileb
4539 1_files := file1 file2
4541 ifeq "$(use_a)" "yes"
4547 ifeq "$(use_dirs)" "yes"
4553 dirs := $($(a1)_$(df))
4555 will give `dirs' the same value as `a_dirs', `1_dirs', `a_files' or
4556 `1_files' depending on the settings of `use_a' and `use_dirs'.
4558 Computed variable names can also be used in substitution references:
4560 a_objects := a.o b.o c.o
4561 1_objects := 1.o 2.o 3.o
4563 sources := $($(a1)_objects:.o=.c)
4565 defines `sources' as either `a.c b.c c.c' or `1.c 2.c 3.c', depending
4566 on the value of `a1'.
4568 The only restriction on this sort of use of nested variable
4569 references is that they cannot specify part of the name of a function
4570 to be called. This is because the test for a recognized function name
4571 is done before the expansion of nested references. For example,
4581 foo := $($(func) $(bar))
4583 attempts to give `foo' the value of the variable `sort a d b g q c' or
4584 `strip a d b g q c', rather than giving `a d b g q c' as the argument
4585 to either the `sort' or the `strip' function. This restriction could
4586 be removed in the future if that change is shown to be a good idea.
4588 You can also use computed variable names in the left-hand side of a
4589 variable assignment, or in a `define' directive, as in:
4592 $(dir)_sources := $(wildcard $(dir)/*.c)
4593 define $(dir)_print =
4594 lpr $($(dir)_sources)
4597 This example defines the variables `dir', `foo_sources', and
4600 Note that "nested variable references" are quite different from
4601 "recursively expanded variables" (*note The Two Flavors of Variables:
4602 Flavors.), though both are used together in complex ways when doing
4603 makefile programming.
4606 File: make.info, Node: Values, Next: Setting, Prev: Advanced, Up: Using Variables
4608 6.4 How Variables Get Their Values
4609 ==================================
4611 Variables can get values in several different ways:
4613 * You can specify an overriding value when you run `make'. *Note
4614 Overriding Variables: Overriding.
4616 * You can specify a value in the makefile, either with an assignment
4617 (*note Setting Variables: Setting.) or with a verbatim definition
4618 (*note Defining Multi-Line Variables: Multi-Line.).
4620 * Variables in the environment become `make' variables. *Note
4621 Variables from the Environment: Environment.
4623 * Several "automatic" variables are given new values for each rule.
4624 Each of these has a single conventional use. *Note Automatic
4627 * Several variables have constant initial values. *Note Variables
4628 Used by Implicit Rules: Implicit Variables.
4631 File: make.info, Node: Setting, Next: Appending, Prev: Values, Up: Using Variables
4633 6.5 Setting Variables
4634 =====================
4636 To set a variable from the makefile, write a line starting with the
4637 variable name followed by `=' `:=', or `::='. Whatever follows the
4638 `=', `:=', or `::=' on the line becomes the value. For example,
4640 objects = main.o foo.o bar.o utils.o
4642 defines a variable named `objects'. Whitespace around the variable
4643 name and immediately after the `=' is ignored.
4645 Variables defined with `=' are "recursively expanded" variables.
4646 Variables defined with `:=' or `::=' are "simply expanded" variables;
4647 these definitions can contain variable references which will be
4648 expanded before the definition is made. *Note The Two Flavors of
4651 The variable name may contain function and variable references, which
4652 are expanded when the line is read to find the actual variable name to
4655 There is no limit on the length of the value of a variable except the
4656 amount of memory on the computer. You can split the value of a
4657 variable into multiple physical lines for readability (*note Splitting
4658 Long Lines: Splitting Lines.).
4660 Most variable names are considered to have the empty string as a
4661 value if you have never set them. Several variables have built-in
4662 initial values that are not empty, but you can set them in the usual
4663 ways (*note Variables Used by Implicit Rules: Implicit Variables.).
4664 Several special variables are set automatically to a new value for each
4665 rule; these are called the "automatic" variables (*note Automatic
4668 If you'd like a variable to be set to a value only if it's not
4669 already set, then you can use the shorthand operator `?=' instead of
4670 `='. These two settings of the variable `FOO' are identical (*note The
4671 `origin' Function: Origin Function.):
4677 ifeq ($(origin FOO), undefined)
4681 The shell assignment operator `!=' can be used to execute a program
4682 and set a variable to its output. This operator first evaluates the
4683 right-hand side, then passes that result to the shell for execution.
4684 If the result of the execution ends in a newline, that one newline is
4685 removed; all other newlines are replaced by spaces. The resulting
4686 string is then placed into the named recursively-expanded variable.
4689 hash != printf '\043'
4690 file_list != find . -name '*.c'
4692 If the result of the execution could produce a `$', and you don't
4693 intend what follows that to be interpreted as a make variable or
4694 function reference, then you must replace every `$' with `$$' as part
4695 of the execution. Alternatively, you can set a simply expanded
4696 variable to the result of running a program using the `shell' function
4697 call. *Note The `shell' Function: Shell Function. For example:
4699 hash := $(shell printf '\043')
4700 var := $(shell find . -name "*.c")
4703 File: make.info, Node: Appending, Next: Override Directive, Prev: Setting, Up: Using Variables
4705 6.6 Appending More Text to Variables
4706 ====================================
4708 Often it is useful to add more text to the value of a variable already
4709 defined. You do this with a line containing `+=', like this:
4711 objects += another.o
4713 This takes the value of the variable `objects', and adds the text
4714 `another.o' to it (preceded by a single space). Thus:
4716 objects = main.o foo.o bar.o utils.o
4717 objects += another.o
4719 sets `objects' to `main.o foo.o bar.o utils.o another.o'.
4721 Using `+=' is similar to:
4723 objects = main.o foo.o bar.o utils.o
4724 objects := $(objects) another.o
4726 but differs in ways that become important when you use more complex
4729 When the variable in question has not been defined before, `+=' acts
4730 just like normal `=': it defines a recursively-expanded variable.
4731 However, when there _is_ a previous definition, exactly what `+=' does
4732 depends on what flavor of variable you defined originally. *Note The
4733 Two Flavors of Variables: Flavors, for an explanation of the two
4734 flavors of variables.
4736 When you add to a variable's value with `+=', `make' acts
4737 essentially as if you had included the extra text in the initial
4738 definition of the variable. If you defined it first with `:=' or
4739 `::=', making it a simply-expanded variable, `+=' adds to that
4740 simply-expanded definition, and expands the new text before appending
4741 it to the old value just as `:=' does (see *note Setting Variables:
4742 Setting, for a full explanation of `:=' or `::='). In fact,
4747 is exactly equivalent to:
4751 variable := $(variable) more
4753 On the other hand, when you use `+=' with a variable that you defined
4754 first to be recursively-expanded using plain `=', `make' does something
4755 a bit different. Recall that when you define a recursively-expanded
4756 variable, `make' does not expand the value you set for variable and
4757 function references immediately. Instead it stores the text verbatim,
4758 and saves these variable and function references to be expanded later,
4759 when you refer to the new variable (*note The Two Flavors of Variables:
4760 Flavors.). When you use `+=' on a recursively-expanded variable, it is
4761 this unexpanded text to which `make' appends the new text you specify.
4766 is roughly equivalent to:
4769 variable = $(temp) more
4771 except that of course it never defines a variable called `temp'. The
4772 importance of this comes when the variable's old value contains
4773 variable references. Take this common example:
4775 CFLAGS = $(includes) -O
4777 CFLAGS += -pg # enable profiling
4779 The first line defines the `CFLAGS' variable with a reference to another
4780 variable, `includes'. (`CFLAGS' is used by the rules for C
4781 compilation; *note Catalogue of Implicit Rules: Catalogue of Rules.)
4782 Using `=' for the definition makes `CFLAGS' a recursively-expanded
4783 variable, meaning `$(includes) -O' is _not_ expanded when `make'
4784 processes the definition of `CFLAGS'. Thus, `includes' need not be
4785 defined yet for its value to take effect. It only has to be defined
4786 before any reference to `CFLAGS'. If we tried to append to the value
4787 of `CFLAGS' without using `+=', we might do it like this:
4789 CFLAGS := $(CFLAGS) -pg # enable profiling
4791 This is pretty close, but not quite what we want. Using `:=' redefines
4792 `CFLAGS' as a simply-expanded variable; this means `make' expands the
4793 text `$(CFLAGS) -pg' before setting the variable. If `includes' is not
4794 yet defined, we get ` -O -pg', and a later definition of `includes'
4795 will have no effect. Conversely, by using `+=' we set `CFLAGS' to the
4796 _unexpanded_ value `$(includes) -O -pg'. Thus we preserve the
4797 reference to `includes', so if that variable gets defined at any later
4798 point, a reference like `$(CFLAGS)' still uses its value.
4801 File: make.info, Node: Override Directive, Next: Multi-Line, Prev: Appending, Up: Using Variables
4803 6.7 The `override' Directive
4804 ============================
4806 If a variable has been set with a command argument (*note Overriding
4807 Variables: Overriding.), then ordinary assignments in the makefile are
4808 ignored. If you want to set the variable in the makefile even though
4809 it was set with a command argument, you can use an `override'
4810 directive, which is a line that looks like this:
4812 override VARIABLE = VALUE
4816 override VARIABLE := VALUE
4818 To append more text to a variable defined on the command line, use:
4820 override VARIABLE += MORE TEXT
4822 *Note Appending More Text to Variables: Appending.
4824 Variable assignments marked with the `override' flag have a higher
4825 priority than all other assignments, except another `override'.
4826 Subsequent assignments or appends to this variable which are not marked
4827 `override' will be ignored.
4829 The `override' directive was not invented for escalation in the war
4830 between makefiles and command arguments. It was invented so you can
4831 alter and add to values that the user specifies with command arguments.
4833 For example, suppose you always want the `-g' switch when you run the
4834 C compiler, but you would like to allow the user to specify the other
4835 switches with a command argument just as usual. You could use this
4836 `override' directive:
4838 override CFLAGS += -g
4840 You can also use `override' directives with `define' directives.
4841 This is done as you might expect:
4843 override define foo =
4847 *Note Defining Multi-Line Variables: Multi-Line.
4850 File: make.info, Node: Multi-Line, Next: Undefine Directive, Prev: Override Directive, Up: Using Variables
4852 6.8 Defining Multi-Line Variables
4853 =================================
4855 Another way to set the value of a variable is to use the `define'
4856 directive. This directive has an unusual syntax which allows newline
4857 characters to be included in the value, which is convenient for
4858 defining both canned sequences of commands (*note Defining Canned
4859 Recipes: Canned Recipes.), and also sections of makefile syntax to use
4860 with `eval' (*note Eval Function::).
4862 The `define' directive is followed on the same line by the name of
4863 the variable being defined and an (optional) assignment operator, and
4864 nothing more. The value to give the variable appears on the following
4865 lines. The end of the value is marked by a line containing just the
4866 word `endef'. Aside from this difference in syntax, `define' works
4867 just like any other variable definition. The variable name may contain
4868 function and variable references, which are expanded when the directive
4869 is read to find the actual variable name to use.
4871 You may omit the variable assignment operator if you prefer. If
4872 omitted, `make' assumes it to be `=' and creates a recursively-expanded
4873 variable (*note The Two Flavors of Variables: Flavors.). When using a
4874 `+=' operator, the value is appended to the previous value as with any
4875 other append operation: with a single space separating the old and new
4878 You may nest `define' directives: `make' will keep track of nested
4879 directives and report an error if they are not all properly closed with
4880 `endef'. Note that lines beginning with the recipe prefix character
4881 are considered part of a recipe, so any `define' or `endef' strings
4882 appearing on such a line will not be considered `make' directives.
4889 The value in an ordinary assignment cannot contain a newline; but the
4890 newlines that separate the lines of the value in a `define' become part
4891 of the variable's value (except for the final newline which precedes
4892 the `endef' and is not considered part of the value).
4894 When used in a recipe, the previous example is functionally
4897 two-lines = echo foo; echo $(bar)
4899 since two commands separated by semicolon behave much like two separate
4900 shell commands. However, note that using two separate lines means
4901 `make' will invoke the shell twice, running an independent sub-shell
4902 for each line. *Note Recipe Execution: Execution.
4904 If you want variable definitions made with `define' to take
4905 precedence over command-line variable definitions, you can use the
4906 `override' directive together with `define':
4908 override define two-lines =
4913 *Note The `override' Directive: Override Directive.
4916 File: make.info, Node: Undefine Directive, Next: Environment, Prev: Multi-Line, Up: Using Variables
4918 6.9 Undefining Variables
4919 ========================
4921 If you want to clear a variable, setting its value to empty is usually
4922 sufficient. Expanding such a variable will yield the same result (empty
4923 string) regardless of whether it was set or not. However, if you are
4924 using the `flavor' (*note Flavor Function::) and `origin' (*note Origin
4925 Function::) functions, there is a difference between a variable that
4926 was never set and a variable with an empty value. In such situations
4927 you may want to use the `undefine' directive to make a variable appear
4928 as if it was never set. For example:
4936 $(info $(origin foo))
4937 $(info $(flavor bar))
4939 This example will print "undefined" for both variables.
4941 If you want to undefine a command-line variable definition, you can
4942 use the `override' directive together with `undefine', similar to how
4943 this is done for variable definitions:
4945 override undefine CFLAGS
4948 File: make.info, Node: Environment, Next: Target-specific, Prev: Undefine Directive, Up: Using Variables
4950 6.10 Variables from the Environment
4951 ===================================
4953 Variables in `make' can come from the environment in which `make' is
4954 run. Every environment variable that `make' sees when it starts up is
4955 transformed into a `make' variable with the same name and value.
4956 However, an explicit assignment in the makefile, or with a command
4957 argument, overrides the environment. (If the `-e' flag is specified,
4958 then values from the environment override assignments in the makefile.
4959 *Note Summary of Options: Options Summary. But this is not recommended
4962 Thus, by setting the variable `CFLAGS' in your environment, you can
4963 cause all C compilations in most makefiles to use the compiler switches
4964 you prefer. This is safe for variables with standard or conventional
4965 meanings because you know that no makefile will use them for other
4966 things. (Note this is not totally reliable; some makefiles set
4967 `CFLAGS' explicitly and therefore are not affected by the value in the
4970 When `make' runs a recipe, variables defined in the makefile are
4971 placed into the environment of each shell. This allows you to pass
4972 values to sub-`make' invocations (*note Recursive Use of `make':
4973 Recursion.). By default, only variables that came from the environment
4974 or the command line are passed to recursive invocations. You can use
4975 the `export' directive to pass other variables. *Note Communicating
4976 Variables to a Sub-`make': Variables/Recursion, for full details.
4978 Other use of variables from the environment is not recommended. It
4979 is not wise for makefiles to depend for their functioning on
4980 environment variables set up outside their control, since this would
4981 cause different users to get different results from the same makefile.
4982 This is against the whole purpose of most makefiles.
4984 Such problems would be especially likely with the variable `SHELL',
4985 which is normally present in the environment to specify the user's
4986 choice of interactive shell. It would be very undesirable for this
4987 choice to affect `make'; so, `make' handles the `SHELL' environment
4988 variable in a special way; see *note Choosing the Shell::.
4991 File: make.info, Node: Target-specific, Next: Pattern-specific, Prev: Environment, Up: Using Variables
4993 6.11 Target-specific Variable Values
4994 ====================================
4996 Variable values in `make' are usually global; that is, they are the
4997 same regardless of where they are evaluated (unless they're reset, of
4998 course). One exception to that is automatic variables (*note Automatic
5001 The other exception is "target-specific variable values". This
5002 feature allows you to define different values for the same variable,
5003 based on the target that `make' is currently building. As with
5004 automatic variables, these values are only available within the context
5005 of a target's recipe (and in other target-specific assignments).
5007 Set a target-specific variable value like this:
5009 TARGET ... : VARIABLE-ASSIGNMENT
5011 Target-specific variable assignments can be prefixed with any or all
5012 of the special keywords `export', `override', or `private'; these apply
5013 their normal behavior to this instance of the variable only.
5015 Multiple TARGET values create a target-specific variable value for
5016 each member of the target list individually.
5018 The VARIABLE-ASSIGNMENT can be any valid form of assignment;
5019 recursive (`='), simple (`:=' or `::='), appending (`+='), or
5020 conditional (`?='). All variables that appear within the
5021 VARIABLE-ASSIGNMENT are evaluated within the context of the target:
5022 thus, any previously-defined target-specific variable values will be in
5023 effect. Note that this variable is actually distinct from any "global"
5024 value: the two variables do not have to have the same flavor (recursive
5027 Target-specific variables have the same priority as any other
5028 makefile variable. Variables provided on the command line (and in the
5029 environment if the `-e' option is in force) will take precedence.
5030 Specifying the `override' directive will allow the target-specific
5031 variable value to be preferred.
5033 There is one more special feature of target-specific variables: when
5034 you define a target-specific variable that variable value is also in
5035 effect for all prerequisites of this target, and all their
5036 prerequisites, etc. (unless those prerequisites override that variable
5037 with their own target-specific variable value). So, for example, a
5038 statement like this:
5041 prog : prog.o foo.o bar.o
5043 will set `CFLAGS' to `-g' in the recipe for `prog', but it will also
5044 set `CFLAGS' to `-g' in the recipes that create `prog.o', `foo.o', and
5045 `bar.o', and any recipes which create their prerequisites.
5047 Be aware that a given prerequisite will only be built once per
5048 invocation of make, at most. If the same file is a prerequisite of
5049 multiple targets, and each of those targets has a different value for
5050 the same target-specific variable, then the first target to be built
5051 will cause that prerequisite to be built and the prerequisite will
5052 inherit the target-specific value from the first target. It will
5053 ignore the target-specific values from any other targets.
5056 File: make.info, Node: Pattern-specific, Next: Suppressing Inheritance, Prev: Target-specific, Up: Using Variables
5058 6.12 Pattern-specific Variable Values
5059 =====================================
5061 In addition to target-specific variable values (*note Target-specific
5062 Variable Values: Target-specific.), GNU `make' supports
5063 pattern-specific variable values. In this form, the variable is
5064 defined for any target that matches the pattern specified.
5066 Set a pattern-specific variable value like this:
5068 PATTERN ... : VARIABLE-ASSIGNMENT
5069 where PATTERN is a %-pattern. As with target-specific variable
5070 values, multiple PATTERN values create a pattern-specific variable
5071 value for each pattern individually. The VARIABLE-ASSIGNMENT can be
5072 any valid form of assignment. Any command line variable setting will
5073 take precedence, unless `override' is specified.
5079 will assign `CFLAGS' the value of `-O' for all targets matching the
5082 If a target matches more than one pattern, the matching
5083 pattern-specific variables with longer stems are interpreted first.
5084 This results in more specific variables taking precedence over the more
5085 generic ones, for example:
5088 $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
5090 lib/%.o: CFLAGS := -fPIC -g
5093 all: foo.o lib/bar.o
5095 In this example the first definition of the `CFLAGS' variable will
5096 be used to update `lib/bar.o' even though the second one also applies
5097 to this target. Pattern-specific variables which result in the same
5098 stem length are considered in the order in which they were defined in
5101 Pattern-specific variables are searched after any target-specific
5102 variables defined explicitly for that target, and before target-specific
5103 variables defined for the parent target.
5106 File: make.info, Node: Suppressing Inheritance, Next: Special Variables, Prev: Pattern-specific, Up: Using Variables
5108 6.13 Suppressing Inheritance
5109 ============================
5111 As described in previous sections, `make' variables are inherited by
5112 prerequisites. This capability allows you to modify the behavior of a
5113 prerequisite based on which targets caused it to be rebuilt. For
5114 example, you might set a target-specific variable on a `debug' target,
5115 then running `make debug' will cause that variable to be inherited by
5116 all prerequisites of `debug', while just running `make all' (for
5117 example) would not have that assignment.
5119 Sometimes, however, you may not want a variable to be inherited. For
5120 these situations, `make' provides the `private' modifier. Although
5121 this modifier can be used with any variable assignment, it makes the
5122 most sense with target- and pattern-specific variables. Any variable
5123 marked `private' will be visible to its local target but will not be
5124 inherited by prerequisites of that target. A global variable marked
5125 `private' will be visible in the global scope but will not be inherited
5126 by any target, and hence will not be visible in any recipe.
5128 As an example, consider this makefile:
5131 prog: private EXTRA_CFLAGS = -L/usr/local/lib
5134 Due to the `private' modifier, `a.o' and `b.o' will not inherit the
5135 `EXTRA_CFLAGS' variable assignment from the `prog' target.
5138 File: make.info, Node: Special Variables, Prev: Suppressing Inheritance, Up: Using Variables
5140 6.14 Other Special Variables
5141 ============================
5143 GNU `make' supports some variables that have special properties.
5146 Contains the name of each makefile that is parsed by `make', in
5147 the order in which it was parsed. The name is appended just
5148 before `make' begins to parse the makefile. Thus, if the first
5149 thing a makefile does is examine the last word in this variable, it
5150 will be the name of the current makefile. Once the current
5151 makefile has used `include', however, the last word will be the
5152 just-included makefile.
5154 If a makefile named `Makefile' has this content:
5156 name1 := $(lastword $(MAKEFILE_LIST))
5160 name2 := $(lastword $(MAKEFILE_LIST))
5163 @echo name1 = $(name1)
5164 @echo name2 = $(name2)
5166 then you would expect to see this output:
5172 Sets the default goal to be used if no targets were specified on
5173 the command line (*note Arguments to Specify the Goals: Goals.).
5174 The `.DEFAULT_GOAL' variable allows you to discover the current
5175 default goal, restart the default goal selection algorithm by
5176 clearing its value, or to explicitly set the default goal. The
5177 following example illustrates these cases:
5179 # Query the default goal.
5180 ifeq ($(.DEFAULT_GOAL),)
5181 $(warning no default goal is set)
5187 $(warning default goal is $(.DEFAULT_GOAL))
5189 # Reset the default goal.
5195 $(warning default goal is $(.DEFAULT_GOAL))
5198 .DEFAULT_GOAL := foo
5200 This makefile prints:
5202 no default goal is set
5207 Note that assigning more than one target name to `.DEFAULT_GOAL' is
5208 invalid and will result in an error.
5211 This variable is set only if this instance of `make' has restarted
5212 (*note How Makefiles Are Remade: Remaking Makefiles.): it will
5213 contain the number of times this instance has restarted. Note
5214 this is not the same as recursion (counted by the `MAKELEVEL'
5215 variable). You should not set, modify, or export this variable.
5218 The first character of the value of this variable is used as the
5219 character make assumes is introducing a recipe line. If the
5220 variable is empty (as it is by default) that character is the
5221 standard tab character. For example, this is a valid makefile:
5225 > @echo Hello, world
5227 The value of `.RECIPEPREFIX' can be changed multiple times; once
5228 set it stays in effect for all rules parsed until it is modified.
5231 Expands to a list of the _names_ of all global variables defined
5232 so far. This includes variables which have empty values, as well
5233 as built-in variables (*note Variables Used by Implicit Rules:
5234 Implicit Variables.), but does not include any variables which are
5235 only defined in a target-specific context. Note that any value
5236 you assign to this variable will be ignored; it will always return
5240 Expands to a list of special features supported by this version of
5241 `make'. Possible values include, but are not limited to:
5244 Supports `ar' (archive) files using special file name syntax.
5245 *Note Using `make' to Update Archive Files: Archives.
5248 Supports the `-L' (`--check-symlink-times') flag. *Note
5249 Summary of Options: Options Summary.
5252 Supports "else if" non-nested conditionals. *Note Syntax of
5253 Conditionals: Conditional Syntax.
5256 Supports "job server" enhanced parallel builds. *Note
5257 Parallel Execution: Parallel.
5260 Supports the `.ONESHELL' special target. *Note Using One
5264 Supports order-only prerequisites. *Note Types of
5265 Prerequisites: Prerequisite Types.
5268 Supports secondary expansion of prerequisite lists.
5271 Uses the "shortest stem" method of choosing which pattern, of
5272 multiple applicable options, will be used. *Note How
5273 Patterns Match: Pattern Match.
5276 Supports target-specific and pattern-specific variable
5277 assignments. *Note Target-specific Variable Values:
5281 Supports the `undefine' directive. *Note Undefine
5285 Has GNU Guile available as an embedded extension language.
5286 *Note GNU Guile Integration: Guile Integration.
5289 Supports dynamically loadable objects for creating custom
5290 extensions. *Note Loading Dynamic Objects: Loading Objects.
5293 Expands to a list of directories that `make' searches for included
5294 makefiles (*note Including Other Makefiles: Include.).
5298 File: make.info, Node: Conditionals, Next: Functions, Prev: Using Variables, Up: Top
5300 7 Conditional Parts of Makefiles
5301 ********************************
5303 A "conditional" directive causes part of a makefile to be obeyed or
5304 ignored depending on the values of variables. Conditionals can compare
5305 the value of one variable to another, or the value of a variable to a
5306 constant string. Conditionals control what `make' actually "sees" in
5307 the makefile, so they _cannot_ be used to control recipes at the time
5312 * Conditional Example:: Example of a conditional
5313 * Conditional Syntax:: The syntax of conditionals.
5314 * Testing Flags:: Conditionals that test flags.
5317 File: make.info, Node: Conditional Example, Next: Conditional Syntax, Prev: Conditionals, Up: Conditionals
5319 7.1 Example of a Conditional
5320 ============================
5322 The following example of a conditional tells `make' to use one set of
5323 libraries if the `CC' variable is `gcc', and a different set of
5324 libraries otherwise. It works by controlling which of two recipe lines
5325 will be used for the rule. The result is that `CC=gcc' as an argument
5326 to `make' changes not only which compiler is used but also which
5327 libraries are linked.
5329 libs_for_gcc = -lgnu
5334 $(CC) -o foo $(objects) $(libs_for_gcc)
5336 $(CC) -o foo $(objects) $(normal_libs)
5339 This conditional uses three directives: one `ifeq', one `else' and
5342 The `ifeq' directive begins the conditional, and specifies the
5343 condition. It contains two arguments, separated by a comma and
5344 surrounded by parentheses. Variable substitution is performed on both
5345 arguments and then they are compared. The lines of the makefile
5346 following the `ifeq' are obeyed if the two arguments match; otherwise
5349 The `else' directive causes the following lines to be obeyed if the
5350 previous conditional failed. In the example above, this means that the
5351 second alternative linking command is used whenever the first
5352 alternative is not used. It is optional to have an `else' in a
5355 The `endif' directive ends the conditional. Every conditional must
5356 end with an `endif'. Unconditional makefile text follows.
5358 As this example illustrates, conditionals work at the textual level:
5359 the lines of the conditional are treated as part of the makefile, or
5360 ignored, according to the condition. This is why the larger syntactic
5361 units of the makefile, such as rules, may cross the beginning or the
5362 end of the conditional.
5364 When the variable `CC' has the value `gcc', the above example has
5368 $(CC) -o foo $(objects) $(libs_for_gcc)
5370 When the variable `CC' has any other value, the effect is this:
5373 $(CC) -o foo $(objects) $(normal_libs)
5375 Equivalent results can be obtained in another way by
5376 conditionalizing a variable assignment and then using the variable
5379 libs_for_gcc = -lgnu
5383 libs=$(libs_for_gcc)
5389 $(CC) -o foo $(objects) $(libs)
5392 File: make.info, Node: Conditional Syntax, Next: Testing Flags, Prev: Conditional Example, Up: Conditionals
5394 7.2 Syntax of Conditionals
5395 ==========================
5397 The syntax of a simple conditional with no `else' is as follows:
5399 CONDITIONAL-DIRECTIVE
5403 The TEXT-IF-TRUE may be any lines of text, to be considered as part of
5404 the makefile if the condition is true. If the condition is false, no
5405 text is used instead.
5407 The syntax of a complex conditional is as follows:
5409 CONDITIONAL-DIRECTIVE
5417 CONDITIONAL-DIRECTIVE-ONE
5419 else CONDITIONAL-DIRECTIVE-TWO
5422 TEXT-IF-ONE-AND-TWO-ARE-FALSE
5425 There can be as many "`else' CONDITIONAL-DIRECTIVE" clauses as
5426 necessary. Once a given condition is true, TEXT-IF-TRUE is used and no
5427 other clause is used; if no condition is true then TEXT-IF-FALSE is
5428 used. The TEXT-IF-TRUE and TEXT-IF-FALSE can be any number of lines of
5431 The syntax of the CONDITIONAL-DIRECTIVE is the same whether the
5432 conditional is simple or complex; after an `else' or not. There are
5433 four different directives that test different conditions. Here is a
5437 `ifeq 'ARG1' 'ARG2''
5438 `ifeq "ARG1" "ARG2"'
5439 `ifeq "ARG1" 'ARG2''
5440 `ifeq 'ARG1' "ARG2"'
5441 Expand all variable references in ARG1 and ARG2 and compare them.
5442 If they are identical, the TEXT-IF-TRUE is effective; otherwise,
5443 the TEXT-IF-FALSE, if any, is effective.
5445 Often you want to test if a variable has a non-empty value. When
5446 the value results from complex expansions of variables and
5447 functions, expansions you would consider empty may actually
5448 contain whitespace characters and thus are not seen as empty.
5449 However, you can use the `strip' function (*note Text Functions::)
5450 to avoid interpreting whitespace as a non-empty value. For
5453 ifeq ($(strip $(foo)),)
5457 will evaluate TEXT-IF-EMPTY even if the expansion of `$(foo)'
5458 contains whitespace characters.
5460 `ifneq (ARG1, ARG2)'
5461 `ifneq 'ARG1' 'ARG2''
5462 `ifneq "ARG1" "ARG2"'
5463 `ifneq "ARG1" 'ARG2''
5464 `ifneq 'ARG1' "ARG2"'
5465 Expand all variable references in ARG1 and ARG2 and compare them.
5466 If they are different, the TEXT-IF-TRUE is effective; otherwise,
5467 the TEXT-IF-FALSE, if any, is effective.
5469 `ifdef VARIABLE-NAME'
5470 The `ifdef' form takes the _name_ of a variable as its argument,
5471 not a reference to a variable. The value of that variable has a
5472 non-empty value, the TEXT-IF-TRUE is effective; otherwise, the
5473 TEXT-IF-FALSE, if any, is effective. Variables that have never
5474 been defined have an empty value. The text VARIABLE-NAME is
5475 expanded, so it could be a variable or function that expands to
5476 the name of a variable. For example:
5484 The variable reference `$(foo)' is expanded, yielding `bar', which
5485 is considered to be the name of a variable. The variable `bar' is
5486 not expanded, but its value is examined to determine if it is
5489 Note that `ifdef' only tests whether a variable has a value. It
5490 does not expand the variable to see if that value is nonempty.
5491 Consequently, tests using `ifdef' return true for all definitions
5492 except those like `foo ='. To test for an empty value, use
5493 `ifeq ($(foo),)'. For example,
5503 sets `frobozz' to `yes', while:
5512 sets `frobozz' to `no'.
5514 `ifndef VARIABLE-NAME'
5515 If the variable VARIABLE-NAME has an empty value, the TEXT-IF-TRUE
5516 is effective; otherwise, the TEXT-IF-FALSE, if any, is effective.
5517 The rules for expansion and testing of VARIABLE-NAME are identical
5518 to the `ifdef' directive.
5520 Extra spaces are allowed and ignored at the beginning of the
5521 conditional directive line, but a tab is not allowed. (If the line
5522 begins with a tab, it will be considered part of a recipe for a rule.)
5523 Aside from this, extra spaces or tabs may be inserted with no effect
5524 anywhere except within the directive name or within an argument. A
5525 comment starting with `#' may appear at the end of the line.
5527 The other two directives that play a part in a conditional are `else'
5528 and `endif'. Each of these directives is written as one word, with no
5529 arguments. Extra spaces are allowed and ignored at the beginning of the
5530 line, and spaces or tabs at the end. A comment starting with `#' may
5531 appear at the end of the line.
5533 Conditionals affect which lines of the makefile `make' uses. If the
5534 condition is true, `make' reads the lines of the TEXT-IF-TRUE as part
5535 of the makefile; if the condition is false, `make' ignores those lines
5536 completely. It follows that syntactic units of the makefile, such as
5537 rules, may safely be split across the beginning or the end of the
5540 `make' evaluates conditionals when it reads a makefile.
5541 Consequently, you cannot use automatic variables in the tests of
5542 conditionals because they are not defined until recipes are run (*note
5543 Automatic Variables::).
5545 To prevent intolerable confusion, it is not permitted to start a
5546 conditional in one makefile and end it in another. However, you may
5547 write an `include' directive within a conditional, provided you do not
5548 attempt to terminate the conditional inside the included file.
5551 File: make.info, Node: Testing Flags, Prev: Conditional Syntax, Up: Conditionals
5553 7.3 Conditionals that Test Flags
5554 ================================
5556 You can write a conditional that tests `make' command flags such as
5557 `-t' by using the variable `MAKEFLAGS' together with the `findstring'
5558 function (*note Functions for String Substitution and Analysis: Text
5559 Functions.). This is useful when `touch' is not enough to make a file
5562 The `findstring' function determines whether one string appears as a
5563 substring of another. If you want to test for the `-t' flag, use `t'
5564 as the first string and the value of `MAKEFLAGS' as the other.
5566 For example, here is how to arrange to use `ranlib -t' to finish
5567 marking an archive file up to date:
5570 ifneq (,$(findstring t,$(MAKEFLAGS)))
5572 +ranlib -t archive.a
5577 The `+' prefix marks those recipe lines as "recursive" so that they
5578 will be executed despite use of the `-t' flag. *Note Recursive Use of
5582 File: make.info, Node: Functions, Next: Running, Prev: Conditionals, Up: Top
5584 8 Functions for Transforming Text
5585 *********************************
5587 "Functions" allow you to do text processing in the makefile to compute
5588 the files to operate on or the commands to use in recipes. You use a
5589 function in a "function call", where you give the name of the function
5590 and some text (the "arguments") for the function to operate on. The
5591 result of the function's processing is substituted into the makefile at
5592 the point of the call, just as a variable might be substituted.
5596 * Syntax of Functions:: How to write a function call.
5597 * Text Functions:: General-purpose text manipulation functions.
5598 * File Name Functions:: Functions for manipulating file names.
5599 * Conditional Functions:: Functions that implement conditions.
5600 * Foreach Function:: Repeat some text with controlled variation.
5601 * File Function:: Write text to a file.
5602 * Call Function:: Expand a user-defined function.
5603 * Value Function:: Return the un-expanded value of a variable.
5604 * Eval Function:: Evaluate the arguments as makefile syntax.
5605 * Origin Function:: Find where a variable got its value.
5606 * Flavor Function:: Find out the flavor of a variable.
5607 * Make Control Functions:: Functions that control how make runs.
5608 * Shell Function:: Substitute the output of a shell command.
5609 * Guile Function:: Use GNU Guile embedded scripting language.
5612 File: make.info, Node: Syntax of Functions, Next: Text Functions, Prev: Functions, Up: Functions
5614 8.1 Function Call Syntax
5615 ========================
5617 A function call resembles a variable reference. It can appear anywhere
5618 a variable reference can appear, and it is expanded using the same
5619 rules as variable references. A function call looks like this:
5621 $(FUNCTION ARGUMENTS)
5625 ${FUNCTION ARGUMENTS}
5627 Here FUNCTION is a function name; one of a short list of names that
5628 are part of `make'. You can also essentially create your own functions
5629 by using the `call' built-in function.
5631 The ARGUMENTS are the arguments of the function. They are separated
5632 from the function name by one or more spaces or tabs, and if there is
5633 more than one argument, then they are separated by commas. Such
5634 whitespace and commas are not part of an argument's value. The
5635 delimiters which you use to surround the function call, whether
5636 parentheses or braces, can appear in an argument only in matching pairs;
5637 the other kind of delimiters may appear singly. If the arguments
5638 themselves contain other function calls or variable references, it is
5639 wisest to use the same kind of delimiters for all the references; write
5640 `$(subst a,b,$(x))', not `$(subst a,b,${x})'. This is because it is
5641 clearer, and because only one type of delimiter is matched to find the
5642 end of the reference.
5644 The text written for each argument is processed by substitution of
5645 variables and function calls to produce the argument value, which is
5646 the text on which the function acts. The substitution is done in the
5647 order in which the arguments appear.
5649 Commas and unmatched parentheses or braces cannot appear in the text
5650 of an argument as written; leading spaces cannot appear in the text of
5651 the first argument as written. These characters can be put into the
5652 argument value by variable substitution. First define variables
5653 `comma' and `space' whose values are isolated comma and space
5654 characters, then substitute these variables where such characters are
5659 space:= $(empty) $(empty)
5661 bar:= $(subst $(space),$(comma),$(foo))
5662 # bar is now `a,b,c'.
5664 Here the `subst' function replaces each space with a comma, through the
5665 value of `foo', and substitutes the result.
5668 File: make.info, Node: Text Functions, Next: File Name Functions, Prev: Syntax of Functions, Up: Functions
5670 8.2 Functions for String Substitution and Analysis
5671 ==================================================
5673 Here are some functions that operate on strings:
5675 `$(subst FROM,TO,TEXT)'
5676 Performs a textual replacement on the text TEXT: each occurrence
5677 of FROM is replaced by TO. The result is substituted for the
5678 function call. For example,
5680 $(subst ee,EE,feet on the street)
5682 substitutes the string `fEEt on the strEEt'.
5684 `$(patsubst PATTERN,REPLACEMENT,TEXT)'
5685 Finds whitespace-separated words in TEXT that match PATTERN and
5686 replaces them with REPLACEMENT. Here PATTERN may contain a `%'
5687 which acts as a wildcard, matching any number of any characters
5688 within a word. If REPLACEMENT also contains a `%', the `%' is
5689 replaced by the text that matched the `%' in PATTERN. Only the
5690 first `%' in the PATTERN and REPLACEMENT is treated this way; any
5691 subsequent `%' is unchanged.
5693 `%' characters in `patsubst' function invocations can be quoted
5694 with preceding backslashes (`\'). Backslashes that would
5695 otherwise quote `%' characters can be quoted with more backslashes.
5696 Backslashes that quote `%' characters or other backslashes are
5697 removed from the pattern before it is compared file names or has a
5698 stem substituted into it. Backslashes that are not in danger of
5699 quoting `%' characters go unmolested. For example, the pattern
5700 `the\%weird\\%pattern\\' has `the%weird\' preceding the operative
5701 `%' character, and `pattern\\' following it. The final two
5702 backslashes are left alone because they cannot affect any `%'
5705 Whitespace between words is folded into single space characters;
5706 leading and trailing whitespace is discarded.
5710 $(patsubst %.c,%.o,x.c.c bar.c)
5712 produces the value `x.c.o bar.o'.
5714 Substitution references (*note Substitution References:
5715 Substitution Refs.) are a simpler way to get the effect of the
5716 `patsubst' function:
5718 $(VAR:PATTERN=REPLACEMENT)
5722 $(patsubst PATTERN,REPLACEMENT,$(VAR))
5724 The second shorthand simplifies one of the most common uses of
5725 `patsubst': replacing the suffix at the end of file names.
5727 $(VAR:SUFFIX=REPLACEMENT)
5731 $(patsubst %SUFFIX,%REPLACEMENT,$(VAR))
5733 For example, you might have a list of object files:
5735 objects = foo.o bar.o baz.o
5737 To get the list of corresponding source files, you could simply
5742 instead of using the general form:
5744 $(patsubst %.o,%.c,$(objects))
5747 Removes leading and trailing whitespace from STRING and replaces
5748 each internal sequence of one or more whitespace characters with a
5749 single space. Thus, `$(strip a b c )' results in `a b c'.
5751 The function `strip' can be very useful when used in conjunction
5752 with conditionals. When comparing something with the empty string
5753 `' using `ifeq' or `ifneq', you usually want a string of just
5754 whitespace to match the empty string (*note Conditionals::).
5756 Thus, the following may fail to have the desired results:
5759 ifneq "$(needs_made)" ""
5762 all:;@echo 'Nothing to make!'
5765 Replacing the variable reference `$(needs_made)' with the function
5766 call `$(strip $(needs_made))' in the `ifneq' directive would make
5769 `$(findstring FIND,IN)'
5770 Searches IN for an occurrence of FIND. If it occurs, the value is
5771 FIND; otherwise, the value is empty. You can use this function in
5772 a conditional to test for the presence of a specific substring in
5773 a given string. Thus, the two examples,
5775 $(findstring a,a b c)
5778 produce the values `a' and `' (the empty string), respectively.
5779 *Note Testing Flags::, for a practical application of `findstring'.
5781 `$(filter PATTERN...,TEXT)'
5782 Returns all whitespace-separated words in TEXT that _do_ match any
5783 of the PATTERN words, removing any words that _do not_ match. The
5784 patterns are written using `%', just like the patterns used in the
5785 `patsubst' function above.
5787 The `filter' function can be used to separate out different types
5788 of strings (such as file names) in a variable. For example:
5790 sources := foo.c bar.c baz.s ugh.h
5792 cc $(filter %.c %.s,$(sources)) -o foo
5794 says that `foo' depends of `foo.c', `bar.c', `baz.s' and `ugh.h'
5795 but only `foo.c', `bar.c' and `baz.s' should be specified in the
5796 command to the compiler.
5798 `$(filter-out PATTERN...,TEXT)'
5799 Returns all whitespace-separated words in TEXT that _do not_ match
5800 any of the PATTERN words, removing the words that _do_ match one
5801 or more. This is the exact opposite of the `filter' function.
5805 objects=main1.o foo.o main2.o bar.o
5806 mains=main1.o main2.o
5808 the following generates a list which contains all the object files
5811 $(filter-out $(mains),$(objects))
5814 Sorts the words of LIST in lexical order, removing duplicate
5815 words. The output is a list of words separated by single spaces.
5818 $(sort foo bar lose)
5820 returns the value `bar foo lose'.
5822 Incidentally, since `sort' removes duplicate words, you can use it
5823 for this purpose even if you don't care about the sort order.
5826 Returns the Nth word of TEXT. The legitimate values of N start
5827 from 1. If N is bigger than the number of words in TEXT, the
5828 value is empty. For example,
5830 $(word 2, foo bar baz)
5834 `$(wordlist S,E,TEXT)'
5835 Returns the list of words in TEXT starting with word S and ending
5836 with word E (inclusive). The legitimate values of S start from 1;
5837 E may start from 0. If S is bigger than the number of words in
5838 TEXT, the value is empty. If E is bigger than the number of words
5839 in TEXT, words up to the end of TEXT are returned. If S is
5840 greater than E, nothing is returned. For example,
5842 $(wordlist 2, 3, foo bar baz)
5847 Returns the number of words in TEXT. Thus, the last word of TEXT
5848 is `$(word $(words TEXT),TEXT)'.
5850 `$(firstword NAMES...)'
5851 The argument NAMES is regarded as a series of names, separated by
5852 whitespace. The value is the first name in the series. The rest
5853 of the names are ignored.
5857 $(firstword foo bar)
5859 produces the result `foo'. Although `$(firstword TEXT)' is the
5860 same as `$(word 1,TEXT)', the `firstword' function is retained for
5863 `$(lastword NAMES...)'
5864 The argument NAMES is regarded as a series of names, separated by
5865 whitespace. The value is the last name in the series.
5871 produces the result `bar'. Although `$(lastword TEXT)' is the
5872 same as `$(word $(words TEXT),TEXT)', the `lastword' function was
5873 added for its simplicity and better performance.
5875 Here is a realistic example of the use of `subst' and `patsubst'.
5876 Suppose that a makefile uses the `VPATH' variable to specify a list of
5877 directories that `make' should search for prerequisite files (*note
5878 `VPATH' Search Path for All Prerequisites: General Search.). This
5879 example shows how to tell the C compiler to search for header files in
5880 the same list of directories.
5882 The value of `VPATH' is a list of directories separated by colons,
5883 such as `src:../headers'. First, the `subst' function is used to
5884 change the colons to spaces:
5886 $(subst :, ,$(VPATH))
5888 This produces `src ../headers'. Then `patsubst' is used to turn each
5889 directory name into a `-I' flag. These can be added to the value of
5890 the variable `CFLAGS', which is passed automatically to the C compiler,
5893 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
5895 The effect is to append the text `-Isrc -I../headers' to the previously
5896 given value of `CFLAGS'. The `override' directive is used so that the
5897 new value is assigned even if the previous value of `CFLAGS' was
5898 specified with a command argument (*note The `override' Directive:
5899 Override Directive.).
5902 File: make.info, Node: File Name Functions, Next: Conditional Functions, Prev: Text Functions, Up: Functions
5904 8.3 Functions for File Names
5905 ============================
5907 Several of the built-in expansion functions relate specifically to
5908 taking apart file names or lists of file names.
5910 Each of the following functions performs a specific transformation
5911 on a file name. The argument of the function is regarded as a series
5912 of file names, separated by whitespace. (Leading and trailing
5913 whitespace is ignored.) Each file name in the series is transformed in
5914 the same way and the results are concatenated with single spaces
5918 Extracts the directory-part of each file name in NAMES. The
5919 directory-part of the file name is everything up through (and
5920 including) the last slash in it. If the file name contains no
5921 slash, the directory part is the string `./'. For example,
5923 $(dir src/foo.c hacks)
5925 produces the result `src/ ./'.
5927 `$(notdir NAMES...)'
5928 Extracts all but the directory-part of each file name in NAMES.
5929 If the file name contains no slash, it is left unchanged.
5930 Otherwise, everything through the last slash is removed from it.
5932 A file name that ends with a slash becomes an empty string. This
5933 is unfortunate, because it means that the result does not always
5934 have the same number of whitespace-separated file names as the
5935 argument had; but we do not see any other valid alternative.
5939 $(notdir src/foo.c hacks)
5941 produces the result `foo.c hacks'.
5943 `$(suffix NAMES...)'
5944 Extracts the suffix of each file name in NAMES. If the file name
5945 contains a period, the suffix is everything starting with the last
5946 period. Otherwise, the suffix is the empty string. This
5947 frequently means that the result will be empty when NAMES is not,
5948 and if NAMES contains multiple file names, the result may contain
5953 $(suffix src/foo.c src-1.0/bar.c hacks)
5955 produces the result `.c .c'.
5957 `$(basename NAMES...)'
5958 Extracts all but the suffix of each file name in NAMES. If the
5959 file name contains a period, the basename is everything starting
5960 up to (and not including) the last period. Periods in the
5961 directory part are ignored. If there is no period, the basename
5962 is the entire file name. For example,
5964 $(basename src/foo.c src-1.0/bar hacks)
5966 produces the result `src/foo src-1.0/bar hacks'.
5968 `$(addsuffix SUFFIX,NAMES...)'
5969 The argument NAMES is regarded as a series of names, separated by
5970 whitespace; SUFFIX is used as a unit. The value of SUFFIX is
5971 appended to the end of each individual name and the resulting
5972 larger names are concatenated with single spaces between them.
5975 $(addsuffix .c,foo bar)
5977 produces the result `foo.c bar.c'.
5979 `$(addprefix PREFIX,NAMES...)'
5980 The argument NAMES is regarded as a series of names, separated by
5981 whitespace; PREFIX is used as a unit. The value of PREFIX is
5982 prepended to the front of each individual name and the resulting
5983 larger names are concatenated with single spaces between them.
5986 $(addprefix src/,foo bar)
5988 produces the result `src/foo src/bar'.
5990 `$(join LIST1,LIST2)'
5991 Concatenates the two arguments word by word: the two first words
5992 (one from each argument) concatenated form the first word of the
5993 result, the two second words form the second word of the result,
5994 and so on. So the Nth word of the result comes from the Nth word
5995 of each argument. If one argument has more words that the other,
5996 the extra words are copied unchanged into the result.
5998 For example, `$(join a b,.c .o)' produces `a.c b.o'.
6000 Whitespace between the words in the lists is not preserved; it is
6001 replaced with a single space.
6003 This function can merge the results of the `dir' and `notdir'
6004 functions, to produce the original list of files which was given
6005 to those two functions.
6007 `$(wildcard PATTERN)'
6008 The argument PATTERN is a file name pattern, typically containing
6009 wildcard characters (as in shell file name patterns). The result
6010 of `wildcard' is a space-separated list of the names of existing
6011 files that match the pattern. *Note Using Wildcard Characters in
6012 File Names: Wildcards.
6014 `$(realpath NAMES...)'
6015 For each file name in NAMES return the canonical absolute name. A
6016 canonical name does not contain any `.' or `..' components, nor
6017 any repeated path separators (`/') or symlinks. In case of a
6018 failure the empty string is returned. Consult the `realpath(3)'
6019 documentation for a list of possible failure causes.
6021 `$(abspath NAMES...)'
6022 For each file name in NAMES return an absolute name that does not
6023 contain any `.' or `..' components, nor any repeated path
6024 separators (`/'). Note that, in contrast to `realpath' function,
6025 `abspath' does not resolve symlinks and does not require the file
6026 names to refer to an existing file or directory. Use the
6027 `wildcard' function to test for existence.
6030 File: make.info, Node: Conditional Functions, Next: Foreach Function, Prev: File Name Functions, Up: Functions
6032 8.4 Functions for Conditionals
6033 ==============================
6035 There are three functions that provide conditional expansion. A key
6036 aspect of these functions is that not all of the arguments are expanded
6037 initially. Only those arguments which need to be expanded, will be
6040 `$(if CONDITION,THEN-PART[,ELSE-PART])'
6041 The `if' function provides support for conditional expansion in a
6042 functional context (as opposed to the GNU `make' makefile
6043 conditionals such as `ifeq' (*note Syntax of Conditionals:
6044 Conditional Syntax.).
6046 The first argument, CONDITION, first has all preceding and
6047 trailing whitespace stripped, then is expanded. If it expands to
6048 any non-empty string, then the condition is considered to be true.
6049 If it expands to an empty string, the condition is considered to
6052 If the condition is true then the second argument, THEN-PART, is
6053 evaluated and this is used as the result of the evaluation of the
6054 entire `if' function.
6056 If the condition is false then the third argument, ELSE-PART, is
6057 evaluated and this is the result of the `if' function. If there is
6058 no third argument, the `if' function evaluates to nothing (the
6061 Note that only one of the THEN-PART or the ELSE-PART will be
6062 evaluated, never both. Thus, either can contain side-effects
6063 (such as `shell' function calls, etc.)
6065 `$(or CONDITION1[,CONDITION2[,CONDITION3...]])'
6066 The `or' function provides a "short-circuiting" OR operation.
6067 Each argument is expanded, in order. If an argument expands to a
6068 non-empty string the processing stops and the result of the
6069 expansion is that string. If, after all arguments are expanded,
6070 all of them are false (empty), then the result of the expansion is
6073 `$(and CONDITION1[,CONDITION2[,CONDITION3...]])'
6074 The `and' function provides a "short-circuiting" AND operation.
6075 Each argument is expanded, in order. If an argument expands to an
6076 empty string the processing stops and the result of the expansion
6077 is the empty string. If all arguments expand to a non-empty
6078 string then the result of the expansion is the expansion of the
6083 File: make.info, Node: Foreach Function, Next: File Function, Prev: Conditional Functions, Up: Functions
6085 8.5 The `foreach' Function
6086 ==========================
6088 The `foreach' function is very different from other functions. It
6089 causes one piece of text to be used repeatedly, each time with a
6090 different substitution performed on it. It resembles the `for' command
6091 in the shell `sh' and the `foreach' command in the C-shell `csh'.
6093 The syntax of the `foreach' function is:
6095 $(foreach VAR,LIST,TEXT)
6097 The first two arguments, VAR and LIST, are expanded before anything
6098 else is done; note that the last argument, TEXT, is *not* expanded at
6099 the same time. Then for each word of the expanded value of LIST, the
6100 variable named by the expanded value of VAR is set to that word, and
6101 TEXT is expanded. Presumably TEXT contains references to that
6102 variable, so its expansion will be different each time.
6104 The result is that TEXT is expanded as many times as there are
6105 whitespace-separated words in LIST. The multiple expansions of TEXT
6106 are concatenated, with spaces between them, to make the result of
6109 This simple example sets the variable `files' to the list of all
6110 files in the directories in the list `dirs':
6113 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
6115 Here TEXT is `$(wildcard $(dir)/*)'. The first repetition finds the
6116 value `a' for `dir', so it produces the same result as `$(wildcard
6117 a/*)'; the second repetition produces the result of `$(wildcard b/*)';
6118 and the third, that of `$(wildcard c/*)'.
6120 This example has the same result (except for setting `dirs') as the
6123 files := $(wildcard a/* b/* c/* d/*)
6125 When TEXT is complicated, you can improve readability by giving it a
6126 name, with an additional variable:
6128 find_files = $(wildcard $(dir)/*)
6130 files := $(foreach dir,$(dirs),$(find_files))
6132 Here we use the variable `find_files' this way. We use plain `=' to
6133 define a recursively-expanding variable, so that its value contains an
6134 actual function call to be re-expanded under the control of `foreach';
6135 a simply-expanded variable would not do, since `wildcard' would be
6136 called only once at the time of defining `find_files'.
6138 The `foreach' function has no permanent effect on the variable VAR;
6139 its value and flavor after the `foreach' function call are the same as
6140 they were beforehand. The other values which are taken from LIST are
6141 in effect only temporarily, during the execution of `foreach'. The
6142 variable VAR is a simply-expanded variable during the execution of
6143 `foreach'. If VAR was undefined before the `foreach' function call, it
6144 is undefined after the call. *Note The Two Flavors of Variables:
6147 You must take care when using complex variable expressions that
6148 result in variable names because many strange things are valid variable
6149 names, but are probably not what you intended. For example,
6151 files := $(foreach Esta-escrito-en-espanol!,b c ch,$(find_files))
6153 might be useful if the value of `find_files' references the variable
6154 whose name is `Esta-escrito-en-espanol!' (es un nombre bastante largo,
6155 no?), but it is more likely to be a mistake.
6158 File: make.info, Node: File Function, Next: Call Function, Prev: Foreach Function, Up: Functions
6160 8.6 The `file' Function
6161 =======================
6163 The `file' function allows the makefile to write to a file. Two modes
6164 of writing are supported: overwrite, where the text is written to the
6165 beginning of the file and any existing content is lost, and append,
6166 where the text is written to the end of the file, preserving the
6167 existing content. In all cases the file is created if it does not
6170 The syntax of the `file' function is:
6172 $(file OP FILENAME,TEXT)
6174 The operator OP can be either `>' which indicates overwrite mode, or
6175 `>>' which indicates append mode. The FILENAME indicates the file to
6176 be written to. There may optionally be whitespace between the operator
6179 When the `file' function is expanded all its arguments are expanded
6180 first, then the file indicated by FILENAME will be opened in the mode
6181 described by OP. Finally TEXT will be written to the file. If TEXT
6182 does not already end in a newline, a final newline will be written.
6183 The result of evaluating the `file' function is always the empty string.
6185 It is a fatal error if the file cannot be opened for writing, or if
6186 the write operation fails.
6188 For example, the `file' function can be useful if your build system
6189 has a limited command line size and your recipe runs a command that can
6190 accept arguments from a file as well. Many commands use the convention
6191 that an argument prefixed with an `@' specifies a file containing more
6192 arguments. Then you might write your recipe in this way:
6196 $(CMD) $(CMDFLAGS) @$@.in
6199 If the command required each argument to be on a separate line of the
6200 input file, you might write your recipe like this:
6203 $(file >$@.in,) $(foreach O,$^,$(file >>$@.in,$O))
6204 $(CMD) $(CMDFLAGS) @$@.in
6208 File: make.info, Node: Call Function, Next: Value Function, Prev: File Function, Up: Functions
6210 8.7 The `call' Function
6211 =======================
6213 The `call' function is unique in that it can be used to create new
6214 parameterized functions. You can write a complex expression as the
6215 value of a variable, then use `call' to expand it with different values.
6217 The syntax of the `call' function is:
6219 $(call VARIABLE,PARAM,PARAM,...)
6221 When `make' expands this function, it assigns each PARAM to
6222 temporary variables `$(1)', `$(2)', etc. The variable `$(0)' will
6223 contain VARIABLE. There is no maximum number of parameter arguments.
6224 There is no minimum, either, but it doesn't make sense to use `call'
6227 Then VARIABLE is expanded as a `make' variable in the context of
6228 these temporary assignments. Thus, any reference to `$(1)' in the
6229 value of VARIABLE will resolve to the first PARAM in the invocation of
6232 Note that VARIABLE is the _name_ of a variable, not a _reference_ to
6233 that variable. Therefore you would not normally use a `$' or
6234 parentheses when writing it. (You can, however, use a variable
6235 reference in the name if you want the name not to be a constant.)
6237 If VARIABLE is the name of a built-in function, the built-in function
6238 is always invoked (even if a `make' variable by that name also exists).
6240 The `call' function expands the PARAM arguments before assigning
6241 them to temporary variables. This means that VARIABLE values
6242 containing references to built-in functions that have special expansion
6243 rules, like `foreach' or `if', may not work as you expect.
6245 Some examples may make this clearer.
6247 This macro simply reverses its arguments:
6251 foo = $(call reverse,a,b)
6253 Here FOO will contain `b a'.
6255 This one is slightly more interesting: it defines a macro to search
6256 for the first instance of a program in `PATH':
6258 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
6260 LS := $(call pathsearch,ls)
6262 Now the variable LS contains `/bin/ls' or similar.
6264 The `call' function can be nested. Each recursive invocation gets
6265 its own local values for `$(1)', etc. that mask the values of
6266 higher-level `call'. For example, here is an implementation of a "map"
6269 map = $(foreach a,$(2),$(call $(1),$(a)))
6271 Now you can MAP a function that normally takes only one argument,
6272 such as `origin', to multiple values in one step:
6274 o = $(call map,origin,o map MAKE)
6276 and end up with O containing something like `file file default'.
6278 A final caution: be careful when adding whitespace to the arguments
6279 to `call'. As with other functions, any whitespace contained in the
6280 second and subsequent arguments is kept; this can cause strange
6281 effects. It's generally safest to remove all extraneous whitespace when
6282 providing parameters to `call'.
6285 File: make.info, Node: Value Function, Next: Eval Function, Prev: Call Function, Up: Functions
6287 8.8 The `value' Function
6288 ========================
6290 The `value' function provides a way for you to use the value of a
6291 variable _without_ having it expanded. Please note that this does not
6292 undo expansions which have already occurred; for example if you create
6293 a simply expanded variable its value is expanded during the definition;
6294 in that case the `value' function will return the same result as using
6295 the variable directly.
6297 The syntax of the `value' function is:
6301 Note that VARIABLE is the _name_ of a variable, not a _reference_ to
6302 that variable. Therefore you would not normally use a `$' or
6303 parentheses when writing it. (You can, however, use a variable
6304 reference in the name if you want the name not to be a constant.)
6306 The result of this function is a string containing the value of
6307 VARIABLE, without any expansion occurring. For example, in this
6316 The first output line would be `ATH', since the "$P" would be expanded
6317 as a `make' variable, while the second output line would be the current
6318 value of your `$PATH' environment variable, since the `value' function
6319 avoided the expansion.
6321 The `value' function is most often used in conjunction with the
6322 `eval' function (*note Eval Function::).
6325 File: make.info, Node: Eval Function, Next: Origin Function, Prev: Value Function, Up: Functions
6327 8.9 The `eval' Function
6328 =======================
6330 The `eval' function is very special: it allows you to define new
6331 makefile constructs that are not constant; which are the result of
6332 evaluating other variables and functions. The argument to the `eval'
6333 function is expanded, then the results of that expansion are parsed as
6334 makefile syntax. The expanded results can define new `make' variables,
6335 targets, implicit or explicit rules, etc.
6337 The result of the `eval' function is always the empty string; thus,
6338 it can be placed virtually anywhere in a makefile without causing
6341 It's important to realize that the `eval' argument is expanded
6342 _twice_; first by the `eval' function, then the results of that
6343 expansion are expanded again when they are parsed as makefile syntax.
6344 This means you may need to provide extra levels of escaping for "$"
6345 characters when using `eval'. The `value' function (*note Value
6346 Function::) can sometimes be useful in these situations, to circumvent
6347 unwanted expansions.
6349 Here is an example of how `eval' can be used; this example combines
6350 a number of concepts and other functions. Although it might seem
6351 overly complex to use `eval' in this example, rather than just writing
6352 out the rules, consider two things: first, the template definition (in
6353 `PROGRAM_template') could need to be much more complex than it is here;
6354 and second, you might put the complex, "generic" part of this example
6355 into another makefile, then include it in all the individual makefiles.
6356 Now your individual makefiles are quite straightforward.
6358 PROGRAMS = server client
6360 server_OBJS = server.o server_priv.o server_access.o
6361 server_LIBS = priv protocol
6363 client_OBJS = client.o client_api.o client_mem.o
6364 client_LIBS = protocol
6366 # Everything after this is generic
6371 define PROGRAM_template =
6372 $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
6373 ALL_OBJS += $$($(1)_OBJS)
6376 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
6379 $(LINK.o) $^ $(LDLIBS) -o $@
6382 rm -f $(ALL_OBJS) $(PROGRAMS)
6385 File: make.info, Node: Origin Function, Next: Flavor Function, Prev: Eval Function, Up: Functions
6387 8.10 The `origin' Function
6388 ==========================
6390 The `origin' function is unlike most other functions in that it does
6391 not operate on the values of variables; it tells you something _about_
6392 a variable. Specifically, it tells you where it came from.
6394 The syntax of the `origin' function is:
6398 Note that VARIABLE is the _name_ of a variable to inquire about, not
6399 a _reference_ to that variable. Therefore you would not normally use a
6400 `$' or parentheses when writing it. (You can, however, use a variable
6401 reference in the name if you want the name not to be a constant.)
6403 The result of this function is a string telling you how the variable
6404 VARIABLE was defined:
6407 if VARIABLE was never defined.
6410 if VARIABLE has a default definition, as is usual with `CC' and so
6411 on. *Note Variables Used by Implicit Rules: Implicit Variables.
6412 Note that if you have redefined a default variable, the `origin'
6413 function will return the origin of the later definition.
6416 if VARIABLE was inherited from the environment provided to `make'.
6418 `environment override'
6419 if VARIABLE was inherited from the environment provided to `make',
6420 and is overriding a setting for VARIABLE in the makefile as a
6421 result of the `-e' option (*note Summary of Options: Options
6425 if VARIABLE was defined in a makefile.
6428 if VARIABLE was defined on the command line.
6431 if VARIABLE was defined with an `override' directive in a makefile
6432 (*note The `override' Directive: Override Directive.).
6435 if VARIABLE is an automatic variable defined for the execution of
6436 the recipe for each rule (*note Automatic Variables::).
6438 This information is primarily useful (other than for your curiosity)
6439 to determine if you want to believe the value of a variable. For
6440 example, suppose you have a makefile `foo' that includes another
6441 makefile `bar'. You want a variable `bletch' to be defined in `bar' if
6442 you run the command `make -f bar', even if the environment contains a
6443 definition of `bletch'. However, if `foo' defined `bletch' before
6444 including `bar', you do not want to override that definition. This
6445 could be done by using an `override' directive in `foo', giving that
6446 definition precedence over the later definition in `bar';
6447 unfortunately, the `override' directive would also override any command
6448 line definitions. So, `bar' could include:
6451 ifeq "$(origin bletch)" "environment"
6452 bletch = barf, gag, etc.
6456 If `bletch' has been defined from the environment, this will redefine
6459 If you want to override a previous definition of `bletch' if it came
6460 from the environment, even under `-e', you could instead write:
6462 ifneq "$(findstring environment,$(origin bletch))" ""
6463 bletch = barf, gag, etc.
6466 Here the redefinition takes place if `$(origin bletch)' returns
6467 either `environment' or `environment override'. *Note Functions for
6468 String Substitution and Analysis: Text Functions.
6471 File: make.info, Node: Flavor Function, Next: Make Control Functions, Prev: Origin Function, Up: Functions
6473 8.11 The `flavor' Function
6474 ==========================
6476 The `flavor' function, like the `origin' function, does not operate on
6477 the values of variables but rather it tells you something _about_ a
6478 variable. Specifically, it tells you the flavor of a variable (*note
6479 The Two Flavors of Variables: Flavors.).
6481 The syntax of the `flavor' function is:
6485 Note that VARIABLE is the _name_ of a variable to inquire about, not
6486 a _reference_ to that variable. Therefore you would not normally use a
6487 `$' or parentheses when writing it. (You can, however, use a variable
6488 reference in the name if you want the name not to be a constant.)
6490 The result of this function is a string that identifies the flavor
6491 of the variable VARIABLE:
6494 if VARIABLE was never defined.
6497 if VARIABLE is a recursively expanded variable.
6500 if VARIABLE is a simply expanded variable.
6504 File: make.info, Node: Make Control Functions, Next: Shell Function, Prev: Flavor Function, Up: Functions
6506 8.12 Functions That Control Make
6507 ================================
6509 These functions control the way make runs. Generally, they are used to
6510 provide information to the user of the makefile or to cause make to stop
6511 if some sort of environmental error is detected.
6514 Generates a fatal error where the message is TEXT. Note that the
6515 error is generated whenever this function is evaluated. So, if
6516 you put it inside a recipe or on the right side of a recursive
6517 variable assignment, it won't be evaluated until later. The TEXT
6518 will be expanded before the error is generated.
6523 $(error error is $(ERROR1))
6526 will generate a fatal error during the read of the makefile if the
6527 `make' variable `ERROR1' is defined. Or,
6529 ERR = $(error found an error!)
6534 will generate a fatal error while `make' is running, if the `err'
6537 `$(warning TEXT...)'
6538 This function works similarly to the `error' function, above,
6539 except that `make' doesn't exit. Instead, TEXT is expanded and
6540 the resulting message is displayed, but processing of the makefile
6543 The result of the expansion of this function is the empty string.
6546 This function does nothing more than print its (expanded)
6547 argument(s) to standard output. No makefile name or line number
6548 is added. The result of the expansion of this function is the
6552 File: make.info, Node: Shell Function, Next: Guile Function, Prev: Make Control Functions, Up: Functions
6554 8.13 The `shell' Function
6555 =========================
6557 The `shell' function is unlike any other function other than the
6558 `wildcard' function (*note The Function `wildcard': Wildcard Function.)
6559 in that it communicates with the world outside of `make'.
6561 The `shell' function performs the same function that backquotes
6562 (``') perform in most shells: it does "command expansion". This means
6563 that it takes as an argument a shell command and evaluates to the
6564 output of the command. The only processing `make' does on the result
6565 is to convert each newline (or carriage-return / newline pair) to a
6566 single space. If there is a trailing (carriage-return and) newline it
6567 will simply be removed.
6569 The commands run by calls to the `shell' function are run when the
6570 function calls are expanded (*note How `make' Reads a Makefile: Reading
6571 Makefiles.). Because this function involves spawning a new shell, you
6572 should carefully consider the performance implications of using the
6573 `shell' function within recursively expanded variables vs. simply
6574 expanded variables (*note The Two Flavors of Variables: Flavors.).
6576 Here are some examples of the use of the `shell' function:
6578 contents := $(shell cat foo)
6580 sets `contents' to the contents of the file `foo', with a space (rather
6581 than a newline) separating each line.
6583 files := $(shell echo *.c)
6585 sets `files' to the expansion of `*.c'. Unless `make' is using a very
6586 strange shell, this has the same result as `$(wildcard *.c)' (as long
6587 as at least one `.c' file exists).
6590 File: make.info, Node: Guile Function, Prev: Shell Function, Up: Functions
6592 8.14 The `guile' Function
6593 =========================
6595 If GNU `make' is built with support for GNU Guile as an embedded
6596 extension language then the `guile' function will be available. The
6597 `guile' function takes one argument which is first expanded by `make'
6598 in the normal fashion, then passed to the GNU Guile evaluator. The
6599 result of the evaluator is converted into a string and used as the
6600 expansion of the `guile' function in the makefile. See *note GNU Guile
6601 Integration: Guile Integration. for details on writing extensions to
6604 You can determine whether GNU Guile support is available by checking
6605 the `.FEATURES' variable for the word GUILE.
6608 File: make.info, Node: Running, Next: Implicit Rules, Prev: Functions, Up: Top
6613 A makefile that says how to recompile a program can be used in more
6614 than one way. The simplest use is to recompile every file that is out
6615 of date. Usually, makefiles are written so that if you run `make' with
6616 no arguments, it does just that.
6618 But you might want to update only some of the files; you might want
6619 to use a different compiler or different compiler options; you might
6620 want just to find out which files are out of date without changing them.
6622 By giving arguments when you run `make', you can do any of these
6623 things and many others.
6625 The exit status of `make' is always one of three values:
6627 The exit status is zero if `make' is successful.
6630 The exit status is two if `make' encounters any errors. It will
6631 print messages describing the particular errors.
6634 The exit status is one if you use the `-q' flag and `make'
6635 determines that some target is not already up to date. *Note
6636 Instead of Executing Recipes: Instead of Execution.
6640 * Makefile Arguments:: How to specify which makefile to use.
6641 * Goals:: How to use goal arguments to specify which
6642 parts of the makefile to use.
6643 * Instead of Execution:: How to use mode flags to specify what
6644 kind of thing to do with the recipes
6645 in the makefile other than simply
6647 * Avoiding Compilation:: How to avoid recompiling certain files.
6648 * Overriding:: How to override a variable to specify
6649 an alternate compiler and other things.
6650 * Testing:: How to proceed past some errors, to
6652 * Options Summary:: Summary of Options
6655 File: make.info, Node: Makefile Arguments, Next: Goals, Prev: Running, Up: Running
6657 9.1 Arguments to Specify the Makefile
6658 =====================================
6660 The way to specify the name of the makefile is with the `-f' or
6661 `--file' option (`--makefile' also works). For example, `-f altmake'
6662 says to use the file `altmake' as the makefile.
6664 If you use the `-f' flag several times and follow each `-f' with an
6665 argument, all the specified files are used jointly as makefiles.
6667 If you do not use the `-f' or `--file' flag, the default is to try
6668 `GNUmakefile', `makefile', and `Makefile', in that order, and use the
6669 first of these three which exists or can be made (*note Writing
6670 Makefiles: Makefiles.).
6673 File: make.info, Node: Goals, Next: Instead of Execution, Prev: Makefile Arguments, Up: Running
6675 9.2 Arguments to Specify the Goals
6676 ==================================
6678 The "goals" are the targets that `make' should strive ultimately to
6679 update. Other targets are updated as well if they appear as
6680 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
6682 By default, the goal is the first target in the makefile (not
6683 counting targets that start with a period). Therefore, makefiles are
6684 usually written so that the first target is for compiling the entire
6685 program or programs they describe. If the first rule in the makefile
6686 has several targets, only the first target in the rule becomes the
6687 default goal, not the whole list. You can manage the selection of the
6688 default goal from within your makefile using the `.DEFAULT_GOAL'
6689 variable (*note Other Special Variables: Special Variables.).
6691 You can also specify a different goal or goals with command line
6692 arguments to `make'. Use the name of the goal as an argument. If you
6693 specify several goals, `make' processes each of them in turn, in the
6694 order you name them.
6696 Any target in the makefile may be specified as a goal (unless it
6697 starts with `-' or contains an `=', in which case it will be parsed as
6698 a switch or variable definition, respectively). Even targets not in
6699 the makefile may be specified, if `make' can find implicit rules that
6700 say how to make them.
6702 `Make' will set the special variable `MAKECMDGOALS' to the list of
6703 goals you specified on the command line. If no goals were given on the
6704 command line, this variable is empty. Note that this variable should
6705 be used only in special circumstances.
6707 An example of appropriate use is to avoid including `.d' files
6708 during `clean' rules (*note Automatic Prerequisites::), so `make' won't
6709 create them only to immediately remove them again:
6711 sources = foo.c bar.c
6713 ifneq ($(MAKECMDGOALS),clean)
6714 include $(sources:.c=.d)
6717 One use of specifying a goal is if you want to compile only a part of
6718 the program, or only one of several programs. Specify as a goal each
6719 file that you wish to remake. For example, consider a directory
6720 containing several programs, with a makefile that starts like this:
6723 all: size nm ld ar as
6725 If you are working on the program `size', you might want to say
6726 `make size' so that only the files of that program are recompiled.
6728 Another use of specifying a goal is to make files that are not
6729 normally made. For example, there may be a file of debugging output,
6730 or a version of the program that is compiled specially for testing,
6731 which has a rule in the makefile but is not a prerequisite of the
6734 Another use of specifying a goal is to run the recipe associated with
6735 a phony target (*note Phony Targets::) or empty target (*note Empty
6736 Target Files to Record Events: Empty Targets.). Many makefiles contain
6737 a phony target named `clean' which deletes everything except source
6738 files. Naturally, this is done only if you request it explicitly with
6739 `make clean'. Following is a list of typical phony and empty target
6740 names. *Note Standard Targets::, for a detailed list of all the
6741 standard target names which GNU software packages use.
6744 Make all the top-level targets the makefile knows about.
6747 Delete all files that are normally created by running `make'.
6750 Like `clean', but may refrain from deleting a few files that people
6751 normally don't want to recompile. For example, the `mostlyclean'
6752 target for GCC does not delete `libgcc.a', because recompiling it
6753 is rarely necessary and takes a lot of time.
6758 Any of these targets might be defined to delete _more_ files than
6759 `clean' does. For example, this would delete configuration files
6760 or links that you would normally create as preparation for
6761 compilation, even if the makefile itself cannot create these files.
6764 Copy the executable file into a directory that users typically
6765 search for commands; copy any auxiliary files that the executable
6766 uses into the directories where it will look for them.
6769 Print listings of the source files that have changed.
6772 Create a tar file of the source files.
6775 Create a shell archive (shar file) of the source files.
6778 Create a distribution file of the source files. This might be a
6779 tar file, or a shar file, or a compressed version of one of the
6780 above, or even more than one of the above.
6783 Update a tags table for this program.
6787 Perform self tests on the program this makefile builds.
6790 File: make.info, Node: Instead of Execution, Next: Avoiding Compilation, Prev: Goals, Up: Running
6792 9.3 Instead of Executing Recipes
6793 ================================
6795 The makefile tells `make' how to tell whether a target is up to date,
6796 and how to update each target. But updating the targets is not always
6797 what you want. Certain options specify other activities for `make'.
6803 "No-op". Causes `make' to print the recipes that are needed to
6804 make the targets up to date, but not actually execute them. Note
6805 that some recipes are still executed, even with this flag (*note
6806 How the `MAKE' Variable Works: MAKE Variable.). Also any recipes
6807 needed to update included makefiles are still executed (*note How
6808 Makefiles Are Remade: Remaking Makefiles.).
6812 "Touch". Marks targets as up to date without actually changing
6813 them. In other words, `make' pretends to update the targets but
6814 does not really change their contents; instead only their modified
6819 "Question". Silently check whether the targets are up to date, but
6820 do not execute recipes; the exit code shows whether any updates are
6827 "What if". Each `-W' flag is followed by a file name. The given
6828 files' modification times are recorded by `make' as being the
6829 present time, although the actual modification times remain the
6830 same. You can use the `-W' flag in conjunction with the `-n' flag
6831 to see what would happen if you were to modify specific files.
6833 With the `-n' flag, `make' prints the recipe that it would normally
6834 execute but usually does not execute it.
6836 With the `-t' flag, `make' ignores the recipes in the rules and uses
6837 (in effect) the command `touch' for each target that needs to be
6838 remade. The `touch' command is also printed, unless `-s' or `.SILENT'
6839 is used. For speed, `make' does not actually invoke the program
6840 `touch'. It does the work directly.
6842 With the `-q' flag, `make' prints nothing and executes no recipes,
6843 but the exit status code it returns is zero if and only if the targets
6844 to be considered are already up to date. If the exit status is one,
6845 then some updating needs to be done. If `make' encounters an error,
6846 the exit status is two, so you can distinguish an error from a target
6847 that is not up to date.
6849 It is an error to use more than one of these three flags in the same
6850 invocation of `make'.
6852 The `-n', `-t', and `-q' options do not affect recipe lines that
6853 begin with `+' characters or contain the strings `$(MAKE)' or
6854 `${MAKE}'. Note that only the line containing the `+' character or the
6855 strings `$(MAKE)' or `${MAKE}' is run regardless of these options.
6856 Other lines in the same rule are not run unless they too begin with `+'
6857 or contain `$(MAKE)' or `${MAKE}' (*Note How the `MAKE' Variable Works:
6860 The `-t' flag prevents phony targets (*note Phony Targets::) from
6861 being updated, unless there are recipe lines beginning with `+' or
6862 containing `$(MAKE)' or `${MAKE}'.
6864 The `-W' flag provides two features:
6866 * If you also use the `-n' or `-q' flag, you can see what `make'
6867 would do if you were to modify some files.
6869 * Without the `-n' or `-q' flag, when `make' is actually executing
6870 recipes, the `-W' flag can direct `make' to act as if some files
6871 had been modified, without actually running the recipes for those
6874 Note that the options `-p' and `-v' allow you to obtain other
6875 information about `make' or about the makefiles in use (*note Summary
6876 of Options: Options Summary.).
6879 File: make.info, Node: Avoiding Compilation, Next: Overriding, Prev: Instead of Execution, Up: Running
6881 9.4 Avoiding Recompilation of Some Files
6882 ========================================
6884 Sometimes you may have changed a source file but you do not want to
6885 recompile all the files that depend on it. For example, suppose you add
6886 a macro or a declaration to a header file that many other files depend
6887 on. Being conservative, `make' assumes that any change in the header
6888 file requires recompilation of all dependent files, but you know that
6889 they do not need to be recompiled and you would rather not waste the
6890 time waiting for them to compile.
6892 If you anticipate the problem before changing the header file, you
6893 can use the `-t' flag. This flag tells `make' not to run the recipes
6894 in the rules, but rather to mark the target up to date by changing its
6895 last-modification date. You would follow this procedure:
6897 1. Use the command `make' to recompile the source files that really
6898 need recompilation, ensuring that the object files are up-to-date
6901 2. Make the changes in the header files.
6903 3. Use the command `make -t' to mark all the object files as up to
6904 date. The next time you run `make', the changes in the header
6905 files will not cause any recompilation.
6907 If you have already changed the header file at a time when some files
6908 do need recompilation, it is too late to do this. Instead, you can use
6909 the `-o FILE' flag, which marks a specified file as "old" (*note
6910 Summary of Options: Options Summary.). This means that the file itself
6911 will not be remade, and nothing else will be remade on its account.
6912 Follow this procedure:
6914 1. Recompile the source files that need compilation for reasons
6915 independent of the particular header file, with `make -o
6916 HEADERFILE'. If several header files are involved, use a separate
6917 `-o' option for each header file.
6919 2. Touch all the object files with `make -t'.
6922 File: make.info, Node: Overriding, Next: Testing, Prev: Avoiding Compilation, Up: Running
6924 9.5 Overriding Variables
6925 ========================
6927 An argument that contains `=' specifies the value of a variable: `V=X'
6928 sets the value of the variable V to X. If you specify a value in this
6929 way, all ordinary assignments of the same variable in the makefile are
6930 ignored; we say they have been "overridden" by the command line
6933 The most common way to use this facility is to pass extra flags to
6934 compilers. For example, in a properly written makefile, the variable
6935 `CFLAGS' is included in each recipe that runs the C compiler, so a file
6936 `foo.c' would be compiled something like this:
6938 cc -c $(CFLAGS) foo.c
6940 Thus, whatever value you set for `CFLAGS' affects each compilation
6941 that occurs. The makefile probably specifies the usual value for
6942 `CFLAGS', like this:
6946 Each time you run `make', you can override this value if you wish.
6947 For example, if you say `make CFLAGS='-g -O'', each C compilation will
6948 be done with `cc -c -g -O'. (This also illustrates how you can use
6949 quoting in the shell to enclose spaces and other special characters in
6950 the value of a variable when you override it.)
6952 The variable `CFLAGS' is only one of many standard variables that
6953 exist just so that you can change them this way. *Note Variables Used
6954 by Implicit Rules: Implicit Variables, for a complete list.
6956 You can also program the makefile to look at additional variables of
6957 your own, giving the user the ability to control other aspects of how
6958 the makefile works by changing the variables.
6960 When you override a variable with a command line argument, you can
6961 define either a recursively-expanded variable or a simply-expanded
6962 variable. The examples shown above make a recursively-expanded
6963 variable; to make a simply-expanded variable, write `:=' or `::='
6964 instead of `='. But, unless you want to include a variable reference
6965 or function call in the _value_ that you specify, it makes no
6966 difference which kind of variable you create.
6968 There is one way that the makefile can change a variable that you
6969 have overridden. This is to use the `override' directive, which is a
6970 line that looks like this: `override VARIABLE = VALUE' (*note The
6971 `override' Directive: Override Directive.).
6974 File: make.info, Node: Testing, Next: Options Summary, Prev: Overriding, Up: Running
6976 9.6 Testing the Compilation of a Program
6977 ========================================
6979 Normally, when an error happens in executing a shell command, `make'
6980 gives up immediately, returning a nonzero status. No further recipes
6981 are executed for any target. The error implies that the goal cannot be
6982 correctly remade, and `make' reports this as soon as it knows.
6984 When you are compiling a program that you have just changed, this is
6985 not what you want. Instead, you would rather that `make' try compiling
6986 every file that can be tried, to show you as many compilation errors as
6989 On these occasions, you should use the `-k' or `--keep-going' flag.
6990 This tells `make' to continue to consider the other prerequisites of
6991 the pending targets, remaking them if necessary, before it gives up and
6992 returns nonzero status. For example, after an error in compiling one
6993 object file, `make -k' will continue compiling other object files even
6994 though it already knows that linking them will be impossible. In
6995 addition to continuing after failed shell commands, `make -k' will
6996 continue as much as possible after discovering that it does not know
6997 how to make a target or prerequisite file. This will always cause an
6998 error message, but without `-k', it is a fatal error (*note Summary of
6999 Options: Options Summary.).
7001 The usual behavior of `make' assumes that your purpose is to get the
7002 goals up to date; once `make' learns that this is impossible, it might
7003 as well report the failure immediately. The `-k' flag says that the
7004 real purpose is to test as much as possible of the changes made in the
7005 program, perhaps to find several independent problems so that you can
7006 correct them all before the next attempt to compile. This is why Emacs'
7007 `M-x compile' command passes the `-k' flag by default.