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.71, last updated 19 July 2010, of `The GNU Make
8 Manual', for GNU `make' version 3.82.
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 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.2 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.71, last updated 19 July 2010, of `The GNU Make
42 Manual', for GNU `make' version 3.82.
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 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.2 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 * Features:: Features GNU `make' has over other `make's.
76 * Missing:: What GNU `make' lacks from other `make's.
77 * Makefile Conventions:: Conventions for writing makefiles for
79 * Quick Reference:: A quick reference for experienced users.
80 * Error Messages:: A list of common errors generated by `make'.
81 * Complex Makefile:: A real example of a straightforward,
82 but nontrivial, makefile.
84 * GNU Free Documentation License:: License for copying this manual
85 * Concept Index:: Index of Concepts
86 * Name Index:: Index of Functions, Variables, & Directives
88 --- The Detailed Node Listing ---
92 * Preparing:: Preparing and running make
93 * Reading:: On reading this text
94 * Bugs:: Problems and bugs
96 An Introduction to Makefiles
98 * Rule Introduction:: What a rule looks like.
99 * Simple Makefile:: A simple makefile
100 * How Make Works:: How `make' processes this makefile
101 * Variables Simplify:: Variables make makefiles simpler
102 * make Deduces:: Letting `make' deduce the recipe
103 * Combine By Prerequisite:: Another style of makefile
104 * Cleanup:: Rules for cleaning the directory
108 * Makefile Contents:: What makefiles contain.
109 * Makefile Names:: How to name your makefile.
110 * Include:: How one makefile can use another makefile.
111 * MAKEFILES Variable:: The environment can specify extra makefiles.
112 * Remaking Makefiles:: How makefiles get remade.
113 * Overriding Makefiles:: How to override part of one makefile
114 with another makefile.
115 * Reading Makefiles:: How makefiles are parsed.
116 * Secondary Expansion:: How and when secondary expansion is performed.
120 * Rule Example:: An example explained.
121 * Rule Syntax:: General syntax explained.
122 * Prerequisite Types:: There are two types of prerequisites.
123 * Wildcards:: Using wildcard characters such as `*'.
124 * Directory Search:: Searching other directories for source files.
125 * Phony Targets:: Using a target that is not a real file's name.
126 * Force Targets:: You can use a target without a recipe
127 or prerequisites to mark other targets
129 * Empty Targets:: When only the date matters and the
131 * Special Targets:: Targets with special built-in meanings.
132 * Multiple Targets:: When to make use of several targets in a rule.
133 * Multiple Rules:: How to use several rules with the same target.
134 * Static Pattern:: Static pattern rules apply to multiple targets
135 and can vary the prerequisites according to
137 * Double-Colon:: How to use a special kind of rule to allow
138 several independent rules for one target.
139 * Automatic Prerequisites:: How to automatically generate rules giving
140 prerequisites from source files themselves.
142 Using Wildcard Characters in File Names
144 * Wildcard Examples:: Several examples
145 * Wildcard Pitfall:: Problems to avoid.
146 * Wildcard Function:: How to cause wildcard expansion where
147 it does not normally take place.
149 Searching Directories for Prerequisites
151 * General Search:: Specifying a search path that applies
152 to every prerequisite.
153 * Selective Search:: Specifying a search path
154 for a specified class of names.
155 * Search Algorithm:: When and how search paths are applied.
156 * Recipes/Search:: How to write recipes that work together
158 * Implicit/Search:: How search paths affect implicit rules.
159 * Libraries/Search:: Directory search for link libraries.
163 * Static Usage:: The syntax of static pattern rules.
164 * Static versus Implicit:: When are they better than implicit rules?
166 Writing Recipes in Rules
168 * Recipe Syntax:: Recipe syntax features and pitfalls.
169 * Echoing:: How to control when recipes are echoed.
170 * Execution:: How recipes are executed.
171 * Parallel:: How recipes can be executed in parallel.
172 * Errors:: What happens after a recipe execution error.
173 * Interrupts:: What happens when a recipe is interrupted.
174 * Recursion:: Invoking `make' from makefiles.
175 * Canned Recipes:: Defining canned recipes.
176 * Empty Recipes:: Defining useful, do-nothing recipes.
180 * Splitting Lines:: Breaking long recipe lines for readability.
181 * Variables in Recipes:: Using `make' variables in recipes.
185 * Choosing the Shell:: How `make' chooses the shell used
188 Recursive Use of `make'
190 * MAKE Variable:: The special effects of using `$(MAKE)'.
191 * Variables/Recursion:: How to communicate variables to a sub-`make'.
192 * Options/Recursion:: How to communicate options to a sub-`make'.
193 * -w Option:: How the `-w' or `--print-directory' option
194 helps debug use of recursive `make' commands.
198 * Reference:: How to use the value of a variable.
199 * Flavors:: Variables come in two flavors.
200 * Advanced:: Advanced features for referencing a variable.
201 * Values:: All the ways variables get their values.
202 * Setting:: How to set a variable in the makefile.
203 * Appending:: How to append more text to the old value
205 * Override Directive:: How to set a variable in the makefile even if
206 the user has set it with a command argument.
207 * Multi-Line:: An alternate way to set a variable
208 to a multi-line string.
209 * Environment:: Variable values can come from the environment.
210 * Target-specific:: Variable values can be defined on a per-target
212 * Pattern-specific:: Target-specific variable values can be applied
213 to a group of targets that match a pattern.
214 * Suppressing Inheritance:: Suppress inheritance of variables.
215 * Special Variables:: Variables with special meaning or behavior.
217 Advanced Features for Reference to Variables
219 * Substitution Refs:: Referencing a variable with
220 substitutions on the value.
221 * Computed Names:: Computing the name of the variable to refer to.
223 Conditional Parts of Makefiles
225 * Conditional Example:: Example of a conditional
226 * Conditional Syntax:: The syntax of conditionals.
227 * Testing Flags:: Conditionals that test flags.
229 Functions for Transforming Text
231 * Syntax of Functions:: How to write a function call.
232 * Text Functions:: General-purpose text manipulation functions.
233 * File Name Functions:: Functions for manipulating file names.
234 * Conditional Functions:: Functions that implement conditions.
235 * Foreach Function:: Repeat some text with controlled variation.
236 * Call Function:: Expand a user-defined function.
237 * Value Function:: Return the un-expanded value of a variable.
238 * Eval Function:: Evaluate the arguments as makefile syntax.
239 * Origin Function:: Find where a variable got its value.
240 * Flavor Function:: Find out the flavor of a variable.
241 * Shell Function:: Substitute the output of a shell command.
242 * Make Control Functions:: Functions that control how make runs.
246 * Makefile Arguments:: How to specify which makefile to use.
247 * Goals:: How to use goal arguments to specify which
248 parts of the makefile to use.
249 * Instead of Execution:: How to use mode flags to specify what
250 kind of thing to do with the recipes
251 in the makefile other than simply
253 * Avoiding Compilation:: How to avoid recompiling certain files.
254 * Overriding:: How to override a variable to specify
255 an alternate compiler and other things.
256 * Testing:: How to proceed past some errors, to
258 * Options Summary:: Summary of Options
262 * Using Implicit:: How to use an existing implicit rule
263 to get the recipe for updating a file.
264 * Catalogue of Rules:: A list of built-in implicit rules.
265 * Implicit Variables:: How to change what predefined rules do.
266 * Chained Rules:: How to use a chain of implicit rules.
267 * Pattern Rules:: How to define new implicit rules.
268 * Last Resort:: How to define a recipe for rules which
270 * Suffix Rules:: The old-fashioned style of implicit rule.
271 * Implicit Rule Search:: The precise algorithm for applying
274 Defining and Redefining Pattern Rules
276 * Pattern Intro:: An introduction to pattern rules.
277 * Pattern Examples:: Examples of pattern rules.
278 * Automatic Variables:: How to use automatic variables in the
279 recipe of implicit rules.
280 * Pattern Match:: How patterns match.
281 * Match-Anything Rules:: Precautions you should take prior to
282 defining rules that can match any
283 target file whatever.
284 * Canceling Rules:: How to override or cancel built-in rules.
286 Using `make' to Update Archive Files
288 * Archive Members:: Archive members as targets.
289 * Archive Update:: The implicit rule for archive member targets.
290 * Archive Pitfalls:: Dangers to watch out for when using archives.
291 * Archive Suffix Rules:: You can write a special kind of suffix rule
292 for updating archives.
294 Implicit Rule for Archive Member Targets
296 * Archive Symbols:: How to update archive symbol directories.
299 File: make.info, Node: Overview, Next: Introduction, Prev: Top, Up: Top
304 The `make' utility automatically determines which pieces of a large
305 program need to be recompiled, and issues commands to recompile them.
306 This manual describes GNU `make', which was implemented by Richard
307 Stallman and Roland McGrath. Development since Version 3.76 has been
308 handled by Paul D. Smith.
310 GNU `make' conforms to section 6.2 of `IEEE Standard 1003.2-1992'
313 Our examples show C programs, since they are most common, but you
314 can use `make' with any programming language whose compiler can be run
315 with a shell command. Indeed, `make' is not limited to programs. You
316 can use it to describe any task where some files must be updated
317 automatically from others whenever the others change.
321 * Preparing:: Preparing and Running Make
322 * Reading:: On Reading this Text
323 * Bugs:: Problems and Bugs
326 File: make.info, Node: Preparing, Next: Reading, Prev: Overview, Up: Overview
328 Preparing and Running Make
329 ==========================
331 To prepare to use `make', you must write a file called the
332 "makefile" that describes the relationships among files in your program
333 and provides commands for updating each file. In a program, typically,
334 the executable file is updated from object files, which are in turn
335 made by compiling source files.
337 Once a suitable makefile exists, each time you change some source
338 files, this simple shell command:
342 suffices to perform all necessary recompilations. The `make' program
343 uses the makefile data base and the last-modification times of the
344 files to decide which of the files need to be updated. For each of
345 those files, it issues the recipes recorded in the data base.
347 You can provide command line arguments to `make' to control which
348 files should be recompiled, or how. *Note How to Run `make': Running.
351 File: make.info, Node: Reading, Next: Bugs, Prev: Preparing, Up: Overview
353 1.1 How to Read This Manual
354 ===========================
356 If you are new to `make', or are looking for a general introduction,
357 read the first few sections of each chapter, skipping the later
358 sections. In each chapter, the first few sections contain introductory
359 or general information and the later sections contain specialized or
360 technical information. The exception is the second chapter, *note An
361 Introduction to Makefiles: Introduction, all of which is introductory.
363 If you are familiar with other `make' programs, see *note Features
364 of GNU `make': Features, which lists the enhancements GNU `make' has,
365 and *note Incompatibilities and Missing Features: Missing, which
366 explains the few things GNU `make' lacks that others have.
368 For a quick summary, see *note Options Summary::, *note Quick
369 Reference::, and *note Special Targets::.
372 File: make.info, Node: Bugs, Prev: Reading, Up: Overview
374 1.2 Problems and Bugs
375 =====================
377 If you have problems with GNU `make' or think you've found a bug,
378 please report it to the developers; we cannot promise to do anything but
379 we might well want to fix it.
381 Before reporting a bug, make sure you've actually found a real bug.
382 Carefully reread the documentation and see if it really says you can do
383 what you're trying to do. If it's not clear whether you should be able
384 to do something or not, report that too; it's a bug in the
387 Before reporting a bug or trying to fix it yourself, try to isolate
388 it to the smallest possible makefile that reproduces the problem. Then
389 send us the makefile and the exact results `make' gave you, including
390 any error or warning messages. Please don't paraphrase these messages:
391 it's best to cut and paste them into your report. When generating this
392 small makefile, be sure to not use any non-free or unusual tools in
393 your recipes: you can almost always emulate what such a tool would do
394 with simple shell commands. Finally, be sure to explain what you
395 expected to occur; this will help us decide whether the problem was
396 really in the documentation.
398 Once you have a precise problem you can report it in one of two ways.
399 Either send electronic mail to:
403 or use our Web-based project management tool, at:
405 http://savannah.gnu.org/projects/make/
407 In addition to the information above, please be careful to include the
408 version number of `make' you are using. You can get this information
409 with the command `make --version'. Be sure also to include the type of
410 machine and operating system you are using. One way to obtain this
411 information is by looking at the final lines of output from the command
415 File: make.info, Node: Introduction, Next: Makefiles, Prev: Overview, Up: Top
417 2 An Introduction to Makefiles
418 ******************************
420 You need a file called a "makefile" to tell `make' what to do. Most
421 often, the makefile tells `make' how to compile and link a program.
423 In this chapter, we will discuss a simple makefile that describes
424 how to compile and link a text editor which consists of eight C source
425 files and three header files. The makefile can also tell `make' how to
426 run miscellaneous commands when explicitly asked (for example, to remove
427 certain files as a clean-up operation). To see a more complex example
428 of a makefile, see *note Complex Makefile::.
430 When `make' recompiles the editor, each changed C source file must
431 be recompiled. If a header file has changed, each C source file that
432 includes the header file must be recompiled to be safe. Each
433 compilation produces an object file corresponding to the source file.
434 Finally, if any source file has been recompiled, all the object files,
435 whether newly made or saved from previous compilations, must be linked
436 together to produce the new executable editor.
440 * Rule Introduction:: What a rule looks like.
441 * Simple Makefile:: A Simple Makefile
442 * How Make Works:: How `make' Processes This Makefile
443 * Variables Simplify:: Variables Make Makefiles Simpler
444 * make Deduces:: Letting `make' Deduce the Recipes
445 * Combine By Prerequisite:: Another Style of Makefile
446 * Cleanup:: Rules for Cleaning the Directory
449 File: make.info, Node: Rule Introduction, Next: Simple Makefile, Prev: Introduction, Up: Introduction
451 2.1 What a Rule Looks Like
452 ==========================
454 A simple makefile consists of "rules" with the following shape:
456 TARGET ... : PREREQUISITES ...
461 A "target" is usually the name of a file that is generated by a
462 program; examples of targets are executable or object files. A target
463 can also be the name of an action to carry out, such as `clean' (*note
466 A "prerequisite" is a file that is used as input to create the
467 target. A target often depends on several files.
469 A "recipe" is an action that `make' carries out. A recipe may have
470 more than one command, either on the same line or each on its own line.
471 *Please note:* you need to put a tab character at the beginning of
472 every recipe line! This is an obscurity that catches the unwary. If
473 you prefer to prefix your recipes with a character other than tab, you
474 can set the `.RECIPEPREFIX' variable to an alternate character (*note
475 Special Variables::).
477 Usually a recipe is in a rule with prerequisites and serves to
478 create a target file if any of the prerequisites change. However, the
479 rule that specifies a recipe for the target need not have
480 prerequisites. For example, the rule containing the delete command
481 associated with the target `clean' does not have prerequisites.
483 A "rule", then, explains how and when to remake certain files which
484 are the targets of the particular rule. `make' carries out the recipe
485 on the prerequisites to create or update the target. A rule can also
486 explain how and when to carry out an action. *Note Writing Rules:
489 A makefile may contain other text besides rules, but a simple
490 makefile need only contain rules. Rules may look somewhat more
491 complicated than shown in this template, but all fit the pattern more
495 File: make.info, Node: Simple Makefile, Next: How Make Works, Prev: Rule Introduction, Up: Introduction
497 2.2 A Simple Makefile
498 =====================
500 Here is a straightforward makefile that describes the way an executable
501 file called `edit' depends on eight object files which, in turn, depend
502 on eight C source and three header files.
504 In this example, all the C files include `defs.h', but only those
505 defining editing commands include `command.h', and only low level files
506 that change the editor buffer include `buffer.h'.
508 edit : main.o kbd.o command.o display.o \
509 insert.o search.o files.o utils.o
510 cc -o edit main.o kbd.o command.o display.o \
511 insert.o search.o files.o utils.o
513 main.o : main.c defs.h
515 kbd.o : kbd.c defs.h command.h
517 command.o : command.c defs.h command.h
519 display.o : display.c defs.h buffer.h
521 insert.o : insert.c defs.h buffer.h
523 search.o : search.c defs.h buffer.h
525 files.o : files.c defs.h buffer.h command.h
527 utils.o : utils.c defs.h
530 rm edit main.o kbd.o command.o display.o \
531 insert.o search.o files.o utils.o
533 We split each long line into two lines using backslash-newline; this is
534 like using one long line, but is easier to read.
536 To use this makefile to create the executable file called `edit',
541 To use this makefile to delete the executable file and all the object
542 files from the directory, type:
546 In the example makefile, the targets include the executable file
547 `edit', and the object files `main.o' and `kbd.o'. The prerequisites
548 are files such as `main.c' and `defs.h'. In fact, each `.o' file is
549 both a target and a prerequisite. Recipes include `cc -c main.c' and
552 When a target is a file, it needs to be recompiled or relinked if any
553 of its prerequisites change. In addition, any prerequisites that are
554 themselves automatically generated should be updated first. In this
555 example, `edit' depends on each of the eight object files; the object
556 file `main.o' depends on the source file `main.c' and on the header
559 A recipe may follow each line that contains a target and
560 prerequisites. These recipes say how to update the target file. A tab
561 character (or whatever character is specified by the `.RECIPEPREFIX'
562 variable; *note Special Variables::) must come at the beginning of
563 every line in the recipe to distinguish recipes from other lines in the
564 makefile. (Bear in mind that `make' does not know anything about how
565 the recipes work. It is up to you to supply recipes that will update
566 the target file properly. All `make' does is execute the recipe you
567 have specified when the target file needs to be updated.)
569 The target `clean' is not a file, but merely the name of an action.
570 Since you normally do not want to carry out the actions in this rule,
571 `clean' is not a prerequisite of any other rule. Consequently, `make'
572 never does anything with it unless you tell it specifically. Note that
573 this rule not only is not a prerequisite, it also does not have any
574 prerequisites, so the only purpose of the rule is to run the specified
575 recipe. Targets that do not refer to files but are just actions are
576 called "phony targets". *Note Phony Targets::, for information about
577 this kind of target. *Note Errors in Recipes: Errors, to see how to
578 cause `make' to ignore errors from `rm' or any other command.
581 File: make.info, Node: How Make Works, Next: Variables Simplify, Prev: Simple Makefile, Up: Introduction
583 2.3 How `make' Processes a Makefile
584 ===================================
586 By default, `make' starts with the first target (not targets whose
587 names start with `.'). This is called the "default goal". ("Goals"
588 are the targets that `make' strives ultimately to update. You can
589 override this behavior using the command line (*note Arguments to
590 Specify the Goals: Goals.) or with the `.DEFAULT_GOAL' special variable
591 (*note Other Special Variables: Special Variables.).
593 In the simple example of the previous section, the default goal is to
594 update the executable program `edit'; therefore, we put that rule first.
596 Thus, when you give the command:
600 `make' reads the makefile in the current directory and begins by
601 processing the first rule. In the example, this rule is for relinking
602 `edit'; but before `make' can fully process this rule, it must process
603 the rules for the files that `edit' depends on, which in this case are
604 the object files. Each of these files is processed according to its
605 own rule. These rules say to update each `.o' file by compiling its
606 source file. The recompilation must be done if the source file, or any
607 of the header files named as prerequisites, is more recent than the
608 object file, or if the object file does not exist.
610 The other rules are processed because their targets appear as
611 prerequisites of the goal. If some other rule is not depended on by the
612 goal (or anything it depends on, etc.), that rule is not processed,
613 unless you tell `make' to do so (with a command such as `make clean').
615 Before recompiling an object file, `make' considers updating its
616 prerequisites, the source file and header files. This makefile does not
617 specify anything to be done for them--the `.c' and `.h' files are not
618 the targets of any rules--so `make' does nothing for these files. But
619 `make' would update automatically generated C programs, such as those
620 made by Bison or Yacc, by their own rules at this time.
622 After recompiling whichever object files need it, `make' decides
623 whether to relink `edit'. This must be done if the file `edit' does
624 not exist, or if any of the object files are newer than it. If an
625 object file was just recompiled, it is now newer than `edit', so `edit'
628 Thus, if we change the file `insert.c' and run `make', `make' will
629 compile that file to update `insert.o', and then link `edit'. If we
630 change the file `command.h' and run `make', `make' will recompile the
631 object files `kbd.o', `command.o' and `files.o' and then link the file
635 File: make.info, Node: Variables Simplify, Next: make Deduces, Prev: How Make Works, Up: Introduction
637 2.4 Variables Make Makefiles Simpler
638 ====================================
640 In our example, we had to list all the object files twice in the rule
641 for `edit' (repeated here):
643 edit : main.o kbd.o command.o display.o \
644 insert.o search.o files.o utils.o
645 cc -o edit main.o kbd.o command.o display.o \
646 insert.o search.o files.o utils.o
648 Such duplication is error-prone; if a new object file is added to the
649 system, we might add it to one list and forget the other. We can
650 eliminate the risk and simplify the makefile by using a variable.
651 "Variables" allow a text string to be defined once and substituted in
652 multiple places later (*note How to Use Variables: Using Variables.).
654 It is standard practice for every makefile to have a variable named
655 `objects', `OBJECTS', `objs', `OBJS', `obj', or `OBJ' which is a list
656 of all object file names. We would define such a variable `objects'
657 with a line like this in the makefile:
659 objects = main.o kbd.o command.o display.o \
660 insert.o search.o files.o utils.o
662 Then, each place we want to put a list of the object file names, we can
663 substitute the variable's value by writing `$(objects)' (*note How to
664 Use Variables: Using Variables.).
666 Here is how the complete simple makefile looks when you use a
667 variable for the object files:
669 objects = main.o kbd.o command.o display.o \
670 insert.o search.o files.o utils.o
673 cc -o edit $(objects)
674 main.o : main.c defs.h
676 kbd.o : kbd.c defs.h command.h
678 command.o : command.c defs.h command.h
680 display.o : display.c defs.h buffer.h
682 insert.o : insert.c defs.h buffer.h
684 search.o : search.c defs.h buffer.h
686 files.o : files.c defs.h buffer.h command.h
688 utils.o : utils.c defs.h
694 File: make.info, Node: make Deduces, Next: Combine By Prerequisite, Prev: Variables Simplify, Up: Introduction
696 2.5 Letting `make' Deduce the Recipes
697 =====================================
699 It is not necessary to spell out the recipes for compiling the
700 individual C source files, because `make' can figure them out: it has an
701 "implicit rule" for updating a `.o' file from a correspondingly named
702 `.c' file using a `cc -c' command. For example, it will use the recipe
703 `cc -c main.c -o main.o' to compile `main.c' into `main.o'. We can
704 therefore omit the recipes from the rules for the object files. *Note
705 Using Implicit Rules: Implicit Rules.
707 When a `.c' file is used automatically in this way, it is also
708 automatically added to the list of prerequisites. We can therefore omit
709 the `.c' files from the prerequisites, provided we omit the recipe.
711 Here is the entire example, with both of these changes, and a
712 variable `objects' as suggested above:
714 objects = main.o kbd.o command.o display.o \
715 insert.o search.o files.o utils.o
718 cc -o edit $(objects)
721 kbd.o : defs.h command.h
722 command.o : defs.h command.h
723 display.o : defs.h buffer.h
724 insert.o : defs.h buffer.h
725 search.o : defs.h buffer.h
726 files.o : defs.h buffer.h command.h
733 This is how we would write the makefile in actual practice. (The
734 complications associated with `clean' are described elsewhere. See
735 *note Phony Targets::, and *note Errors in Recipes: Errors.)
737 Because implicit rules are so convenient, they are important. You
738 will see them used frequently.
741 File: make.info, Node: Combine By Prerequisite, Next: Cleanup, Prev: make Deduces, Up: Introduction
743 2.6 Another Style of Makefile
744 =============================
746 When the objects of a makefile are created only by implicit rules, an
747 alternative style of makefile is possible. In this style of makefile,
748 you group entries by their prerequisites instead of by their targets.
749 Here is what one looks like:
751 objects = main.o kbd.o command.o display.o \
752 insert.o search.o files.o utils.o
755 cc -o edit $(objects)
758 kbd.o command.o files.o : command.h
759 display.o insert.o search.o files.o : buffer.h
761 Here `defs.h' is given as a prerequisite of all the object files;
762 `command.h' and `buffer.h' are prerequisites of the specific object
763 files listed for them.
765 Whether this is better is a matter of taste: it is more compact, but
766 some people dislike it because they find it clearer to put all the
767 information about each target in one place.
770 File: make.info, Node: Cleanup, Prev: Combine By Prerequisite, Up: Introduction
772 2.7 Rules for Cleaning the Directory
773 ====================================
775 Compiling a program is not the only thing you might want to write rules
776 for. Makefiles commonly tell how to do a few other things besides
777 compiling a program: for example, how to delete all the object files
778 and executables so that the directory is `clean'.
780 Here is how we could write a `make' rule for cleaning our example
786 In practice, we might want to write the rule in a somewhat more
787 complicated manner to handle unanticipated situations. We would do
794 This prevents `make' from getting confused by an actual file called
795 `clean' and causes it to continue in spite of errors from `rm'. (See
796 *note Phony Targets::, and *note Errors in Recipes: Errors.)
798 A rule such as this should not be placed at the beginning of the
799 makefile, because we do not want it to run by default! Thus, in the
800 example makefile, we want the rule for `edit', which recompiles the
801 editor, to remain the default goal.
803 Since `clean' is not a prerequisite of `edit', this rule will not
804 run at all if we give the command `make' with no arguments. In order
805 to make the rule run, we have to type `make clean'. *Note How to Run
809 File: make.info, Node: Makefiles, Next: Rules, Prev: Introduction, Up: Top
814 The information that tells `make' how to recompile a system comes from
815 reading a data base called the "makefile".
819 * Makefile Contents:: What makefiles contain.
820 * Makefile Names:: How to name your makefile.
821 * Include:: How one makefile can use another makefile.
822 * MAKEFILES Variable:: The environment can specify extra makefiles.
823 * Remaking Makefiles:: How makefiles get remade.
824 * Overriding Makefiles:: How to override part of one makefile
825 with another makefile.
826 * Reading Makefiles:: How makefiles are parsed.
827 * Secondary Expansion:: How and when secondary expansion is performed.
830 File: make.info, Node: Makefile Contents, Next: Makefile Names, Prev: Makefiles, Up: Makefiles
832 3.1 What Makefiles Contain
833 ==========================
835 Makefiles contain five kinds of things: "explicit rules", "implicit
836 rules", "variable definitions", "directives", and "comments". Rules,
837 variables, and directives are described at length in later chapters.
839 * An "explicit rule" says when and how to remake one or more files,
840 called the rule's "targets". It lists the other files that the
841 targets depend on, called the "prerequisites" of the target, and
842 may also give a recipe to use to create or update the targets.
843 *Note Writing Rules: Rules.
845 * An "implicit rule" says when and how to remake a class of files
846 based on their names. It describes how a target may depend on a
847 file with a name similar to the target and gives a recipe to
848 create or update such a target. *Note Using Implicit Rules:
851 * A "variable definition" is a line that specifies a text string
852 value for a variable that can be substituted into the text later.
853 The simple makefile example shows a variable definition for
854 `objects' as a list of all object files (*note Variables Make
855 Makefiles Simpler: Variables Simplify.).
857 * A "directive" is an instruction for `make' to do something special
858 while reading the makefile. These include:
860 * Reading another makefile (*note Including Other Makefiles:
863 * Deciding (based on the values of variables) whether to use or
864 ignore a part of the makefile (*note Conditional Parts of
865 Makefiles: Conditionals.).
867 * Defining a variable from a verbatim string containing
868 multiple lines (*note Defining Multi-Line Variables:
871 * `#' in a line of a makefile starts a "comment". It and the rest
872 of the line are ignored, except that a trailing backslash not
873 escaped by another backslash will continue the comment across
874 multiple lines. A line containing just a comment (with perhaps
875 spaces before it) is effectively blank, and is ignored. If you
876 want a literal `#', escape it with a backslash (e.g., `\#').
877 Comments may appear on any line in the makefile, although they are
878 treated specially in certain situations.
880 You cannot use comments within variable references or function
881 calls: any instance of `#' will be treated literally (rather than
882 as the start of a comment) inside a variable reference or function
885 Comments within a recipe are passed to the shell, just as with any
886 other recipe text. The shell decides how to interpret it: whether
887 or not this is a comment is up to the shell.
889 Within a `define' directive, comments are not ignored during the
890 definition of the variable, but rather kept intact in the value of
891 the variable. When the variable is expanded they will either be
892 treated as `make' comments or as recipe text, depending on the
893 context in which the variable is evaluated.
896 File: make.info, Node: Makefile Names, Next: Include, Prev: Makefile Contents, Up: Makefiles
898 3.2 What Name to Give Your Makefile
899 ===================================
901 By default, when `make' looks for the makefile, it tries the following
902 names, in order: `GNUmakefile', `makefile' and `Makefile'.
904 Normally you should call your makefile either `makefile' or
905 `Makefile'. (We recommend `Makefile' because it appears prominently
906 near the beginning of a directory listing, right near other important
907 files such as `README'.) The first name checked, `GNUmakefile', is not
908 recommended for most makefiles. You should use this name if you have a
909 makefile that is specific to GNU `make', and will not be understood by
910 other versions of `make'. Other `make' programs look for `makefile' and
911 `Makefile', but not `GNUmakefile'.
913 If `make' finds none of these names, it does not use any makefile.
914 Then you must specify a goal with a command argument, and `make' will
915 attempt to figure out how to remake it using only its built-in implicit
916 rules. *Note Using Implicit Rules: Implicit Rules.
918 If you want to use a nonstandard name for your makefile, you can
919 specify the makefile name with the `-f' or `--file' option. The
920 arguments `-f NAME' or `--file=NAME' tell `make' to read the file NAME
921 as the makefile. If you use more than one `-f' or `--file' option, you
922 can specify several makefiles. All the makefiles are effectively
923 concatenated in the order specified. The default makefile names
924 `GNUmakefile', `makefile' and `Makefile' are not checked automatically
925 if you specify `-f' or `--file'.
928 File: make.info, Node: Include, Next: MAKEFILES Variable, Prev: Makefile Names, Up: Makefiles
930 3.3 Including Other Makefiles
931 =============================
933 The `include' directive tells `make' to suspend reading the current
934 makefile and read one or more other makefiles before continuing. The
935 directive is a line in the makefile that looks like this:
939 FILENAMES can contain shell file name patterns. If FILENAMES is empty,
940 nothing is included and no error is printed.
942 Extra spaces are allowed and ignored at the beginning of the line,
943 but the first character must not be a tab (or the value of
944 `.RECIPEPREFIX')--if the line begins with a tab, it will be considered
945 a recipe line. Whitespace is required between `include' and the file
946 names, and between file names; extra whitespace is ignored there and at
947 the end of the directive. A comment starting with `#' is allowed at
948 the end of the line. If the file names contain any variable or
949 function references, they are expanded. *Note How to Use Variables:
952 For example, if you have three `.mk' files, `a.mk', `b.mk', and
953 `c.mk', and `$(bar)' expands to `bish bash', then the following
956 include foo *.mk $(bar)
960 include foo a.mk b.mk c.mk bish bash
962 When `make' processes an `include' directive, it suspends reading of
963 the containing makefile and reads from each listed file in turn. When
964 that is finished, `make' resumes reading the makefile in which the
967 One occasion for using `include' directives is when several programs,
968 handled by individual makefiles in various directories, need to use a
969 common set of variable definitions (*note Setting Variables: Setting.)
970 or pattern rules (*note Defining and Redefining Pattern Rules: Pattern
973 Another such occasion is when you want to generate prerequisites from
974 source files automatically; the prerequisites can be put in a file that
975 is included by the main makefile. This practice is generally cleaner
976 than that of somehow appending the prerequisites to the end of the main
977 makefile as has been traditionally done with other versions of `make'.
978 *Note Automatic Prerequisites::.
980 If the specified name does not start with a slash, and the file is
981 not found in the current directory, several other directories are
982 searched. First, any directories you have specified with the `-I' or
983 `--include-dir' option are searched (*note Summary of Options: Options
984 Summary.). Then the following directories (if they exist) are
985 searched, in this order: `PREFIX/include' (normally `/usr/local/include'
986 (1)) `/usr/gnu/include', `/usr/local/include', `/usr/include'.
988 If an included makefile cannot be found in any of these directories,
989 a warning message is generated, but it is not an immediately fatal
990 error; processing of the makefile containing the `include' continues.
991 Once it has finished reading makefiles, `make' will try to remake any
992 that are out of date or don't exist. *Note How Makefiles Are Remade:
993 Remaking Makefiles. Only after it has tried to find a way to remake a
994 makefile and failed, will `make' diagnose the missing makefile as a
997 If you want `make' to simply ignore a makefile which does not exist
998 or cannot be remade, with no error message, use the `-include'
999 directive instead of `include', like this:
1001 -include FILENAMES...
1003 This acts like `include' in every way except that there is no error
1004 (not even a warning) if any of the FILENAMES (or any prerequisites of
1005 any of the FILENAMES) do not exist or cannot be remade.
1007 For compatibility with some other `make' implementations, `sinclude'
1008 is another name for `-include'.
1010 ---------- Footnotes ----------
1012 (1) GNU Make compiled for MS-DOS and MS-Windows behaves as if PREFIX
1013 has been defined to be the root of the DJGPP tree hierarchy.
1016 File: make.info, Node: MAKEFILES Variable, Next: Remaking Makefiles, Prev: Include, Up: Makefiles
1018 3.4 The Variable `MAKEFILES'
1019 ============================
1021 If the environment variable `MAKEFILES' is defined, `make' considers
1022 its value as a list of names (separated by whitespace) of additional
1023 makefiles to be read before the others. This works much like the
1024 `include' directive: various directories are searched for those files
1025 (*note Including Other Makefiles: Include.). In addition, the default
1026 goal is never taken from one of these makefiles (or any makefile
1027 included by them) and it is not an error if the files listed in
1028 `MAKEFILES' are not found.
1030 The main use of `MAKEFILES' is in communication between recursive
1031 invocations of `make' (*note Recursive Use of `make': Recursion.). It
1032 usually is not desirable to set the environment variable before a
1033 top-level invocation of `make', because it is usually better not to
1034 mess with a makefile from outside. However, if you are running `make'
1035 without a specific makefile, a makefile in `MAKEFILES' can do useful
1036 things to help the built-in implicit rules work better, such as
1037 defining search paths (*note Directory Search::).
1039 Some users are tempted to set `MAKEFILES' in the environment
1040 automatically on login, and program makefiles to expect this to be done.
1041 This is a very bad idea, because such makefiles will fail to work if
1042 run by anyone else. It is much better to write explicit `include'
1043 directives in the makefiles. *Note Including Other Makefiles: Include.
1046 File: make.info, Node: Remaking Makefiles, Next: Overriding Makefiles, Prev: MAKEFILES Variable, Up: Makefiles
1048 3.5 How Makefiles Are Remade
1049 ============================
1051 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1052 files. If a makefile can be remade from other files, you probably want
1053 `make' to get an up-to-date version of the makefile to read in.
1055 To this end, after reading in all makefiles, `make' will consider
1056 each as a goal target and attempt to update it. If a makefile has a
1057 rule which says how to update it (found either in that very makefile or
1058 in another one) or if an implicit rule applies to it (*note Using
1059 Implicit Rules: Implicit Rules.), it will be updated if necessary.
1060 After all makefiles have been checked, if any have actually been
1061 changed, `make' starts with a clean slate and reads all the makefiles
1062 over again. (It will also attempt to update each of them over again,
1063 but normally this will not change them again, since they are already up
1066 If you know that one or more of your makefiles cannot be remade and
1067 you want to keep `make' from performing an implicit rule search on
1068 them, perhaps for efficiency reasons, you can use any normal method of
1069 preventing implicit rule lookup to do so. For example, you can write
1070 an explicit rule with the makefile as the target, and an empty recipe
1071 (*note Using Empty Recipes: Empty Recipes.).
1073 If the makefiles specify a double-colon rule to remake a file with a
1074 recipe but no prerequisites, that file will always be remade (*note
1075 Double-Colon::). In the case of makefiles, a makefile that has a
1076 double-colon rule with a recipe but no prerequisites will be remade
1077 every time `make' is run, and then again after `make' starts over and
1078 reads the makefiles in again. This would cause an infinite loop:
1079 `make' would constantly remake the makefile, and never do anything
1080 else. So, to avoid this, `make' will *not* attempt to remake makefiles
1081 which are specified as targets of a double-colon rule with a recipe but
1084 If you do not specify any makefiles to be read with `-f' or `--file'
1085 options, `make' will try the default makefile names; *note What Name to
1086 Give Your Makefile: Makefile Names. Unlike makefiles explicitly
1087 requested with `-f' or `--file' options, `make' is not certain that
1088 these makefiles should exist. However, if a default makefile does not
1089 exist but can be created by running `make' rules, you probably want the
1090 rules to be run so that the makefile can be used.
1092 Therefore, if none of the default makefiles exists, `make' will try
1093 to make each of them in the same order in which they are searched for
1094 (*note What Name to Give Your Makefile: Makefile Names.) until it
1095 succeeds in making one, or it runs out of names to try. Note that it
1096 is not an error if `make' cannot find or make any makefile; a makefile
1097 is not always necessary.
1099 When you use the `-t' or `--touch' option (*note Instead of
1100 Executing Recipes: Instead of Execution.), you would not want to use an
1101 out-of-date makefile to decide which targets to touch. So the `-t'
1102 option has no effect on updating makefiles; they are really updated
1103 even if `-t' is specified. Likewise, `-q' (or `--question') and `-n'
1104 (or `--just-print') do not prevent updating of makefiles, because an
1105 out-of-date makefile would result in the wrong output for other targets.
1106 Thus, `make -f mfile -n foo' will update `mfile', read it in, and then
1107 print the recipe to update `foo' and its prerequisites without running
1108 it. The recipe printed for `foo' will be the one specified in the
1109 updated contents of `mfile'.
1111 However, on occasion you might actually wish to prevent updating of
1112 even the makefiles. You can do this by specifying the makefiles as
1113 goals in the command line as well as specifying them as makefiles.
1114 When the makefile name is specified explicitly as a goal, the options
1115 `-t' and so on do apply to them.
1117 Thus, `make -f mfile -n mfile foo' would read the makefile `mfile',
1118 print the recipe needed to update it without actually running it, and
1119 then print the recipe needed to update `foo' without running that. The
1120 recipe for `foo' will be the one specified by the existing contents of
1124 File: make.info, Node: Overriding Makefiles, Next: Reading Makefiles, Prev: Remaking Makefiles, Up: Makefiles
1126 3.6 Overriding Part of Another Makefile
1127 =======================================
1129 Sometimes it is useful to have a makefile that is mostly just like
1130 another makefile. You can often use the `include' directive to include
1131 one in the other, and add more targets or variable definitions.
1132 However, it is illegal for two makefiles to give different recipes for
1133 the same target. But there is another way.
1135 In the containing makefile (the one that wants to include the other),
1136 you can use a match-anything pattern rule to say that to remake any
1137 target that cannot be made from the information in the containing
1138 makefile, `make' should look in another makefile. *Note Pattern
1139 Rules::, for more information on pattern rules.
1141 For example, if you have a makefile called `Makefile' that says how
1142 to make the target `foo' (and other targets), you can write a makefile
1143 called `GNUmakefile' that contains:
1149 @$(MAKE) -f Makefile $@
1152 If you say `make foo', `make' will find `GNUmakefile', read it, and
1153 see that to make `foo', it needs to run the recipe `frobnicate > foo'.
1154 If you say `make bar', `make' will find no way to make `bar' in
1155 `GNUmakefile', so it will use the recipe from the pattern rule: `make
1156 -f Makefile bar'. If `Makefile' provides a rule for updating `bar',
1157 `make' will apply the rule. And likewise for any other target that
1158 `GNUmakefile' does not say how to make.
1160 The way this works is that the pattern rule has a pattern of just
1161 `%', so it matches any target whatever. The rule specifies a
1162 prerequisite `force', to guarantee that the recipe will be run even if
1163 the target file already exists. We give the `force' target an empty
1164 recipe to prevent `make' from searching for an implicit rule to build
1165 it--otherwise it would apply the same match-anything rule to `force'
1166 itself and create a prerequisite loop!
1169 File: make.info, Node: Reading Makefiles, Next: Secondary Expansion, Prev: Overriding Makefiles, Up: Makefiles
1171 3.7 How `make' Reads a Makefile
1172 ===============================
1174 GNU `make' does its work in two distinct phases. During the first
1175 phase it reads all the makefiles, included makefiles, etc. and
1176 internalizes all the variables and their values, implicit and explicit
1177 rules, and constructs a dependency graph of all the targets and their
1178 prerequisites. During the second phase, `make' uses these internal
1179 structures to determine what targets will need to be rebuilt and to
1180 invoke the rules necessary to do so.
1182 It's important to understand this two-phase approach because it has a
1183 direct impact on how variable and function expansion happens; this is
1184 often a source of some confusion when writing makefiles. Here we will
1185 present a summary of the phases in which expansion happens for different
1186 constructs within the makefile. We say that expansion is "immediate"
1187 if it happens during the first phase: in this case `make' will expand
1188 any variables or functions in that section of a construct as the
1189 makefile is parsed. We say that expansion is "deferred" if expansion
1190 is not performed immediately. Expansion of a deferred construct is not
1191 performed until either the construct appears later in an immediate
1192 context, or until the second phase.
1194 You may not be familiar with some of these constructs yet. You can
1195 reference this section as you become familiar with them, in later
1201 Variable definitions are parsed as follows:
1203 IMMEDIATE = DEFERRED
1204 IMMEDIATE ?= DEFERRED
1205 IMMEDIATE := IMMEDIATE
1206 IMMEDIATE += DEFERRED or IMMEDIATE
1225 DEFERRED or IMMEDIATE
1228 For the append operator, `+=', the right-hand side is considered
1229 immediate if the variable was previously set as a simple variable
1230 (`:='), and deferred otherwise.
1232 Conditional Directives
1233 ----------------------
1235 Conditional directives are parsed immediately. This means, for
1236 example, that automatic variables cannot be used in conditional
1237 directives, as automatic variables are not set until the recipe for
1238 that rule is invoked. If you need to use automatic variables in a
1239 conditional directive you _must_ move the condition into the recipe and
1240 use shell conditional syntax instead.
1245 A rule is always expanded the same way, regardless of the form:
1247 IMMEDIATE : IMMEDIATE ; DEFERRED
1250 That is, the target and prerequisite sections are expanded
1251 immediately, and the recipe used to construct the target is always
1252 deferred. This general rule is true for explicit rules, pattern rules,
1253 suffix rules, static pattern rules, and simple prerequisite definitions.
1256 File: make.info, Node: Secondary Expansion, Prev: Reading Makefiles, Up: Makefiles
1258 3.8 Secondary Expansion
1259 =======================
1261 In the previous section we learned that GNU `make' works in two
1262 distinct phases: a read-in phase and a target-update phase (*note How
1263 `make' Reads a Makefile: Reading Makefiles.). GNU make also has the
1264 ability to enable a _second expansion_ of the prerequisites (only) for
1265 some or all targets defined in the makefile. In order for this second
1266 expansion to occur, the special target `.SECONDEXPANSION' must be
1267 defined before the first prerequisite list that makes use of this
1270 If that special target is defined then in between the two phases
1271 mentioned above, right at the end of the read-in phase, all the
1272 prerequisites of the targets defined after the special target are
1273 expanded a _second time_. In most circumstances this secondary
1274 expansion will have no effect, since all variable and function
1275 references will have been expanded during the initial parsing of the
1276 makefiles. In order to take advantage of the secondary expansion phase
1277 of the parser, then, it's necessary to _escape_ the variable or
1278 function reference in the makefile. In this case the first expansion
1279 merely un-escapes the reference but doesn't expand it, and expansion is
1280 left to the secondary expansion phase. For example, consider this
1286 myfile: $(ONEVAR) $$(TWOVAR)
1288 After the first expansion phase the prerequisites list of the
1289 `myfile' target will be `onefile' and `$(TWOVAR)'; the first
1290 (unescaped) variable reference to ONEVAR is expanded, while the second
1291 (escaped) variable reference is simply unescaped, without being
1292 recognized as a variable reference. Now during the secondary expansion
1293 the first word is expanded again but since it contains no variable or
1294 function references it remains the static value `onefile', while the
1295 second word is now a normal reference to the variable TWOVAR, which is
1296 expanded to the value `twofile'. The final result is that there are
1297 two prerequisites, `onefile' and `twofile'.
1299 Obviously, this is not a very interesting case since the same result
1300 could more easily have been achieved simply by having both variables
1301 appear, unescaped, in the prerequisites list. One difference becomes
1302 apparent if the variables are reset; consider this example:
1310 Here the prerequisite of `onefile' will be expanded immediately, and
1311 resolve to the value `top', while the prerequisite of `twofile' will
1312 not be full expanded until the secondary expansion and yield a value of
1315 This is marginally more exciting, but the true power of this feature
1316 only becomes apparent when you discover that secondary expansions
1317 always take place within the scope of the automatic variables for that
1318 target. This means that you can use variables such as `$@', `$*', etc.
1319 during the second expansion and they will have their expected values,
1320 just as in the recipe. All you have to do is defer the expansion by
1321 escaping the `$'. Also, secondary expansion occurs for both explicit
1322 and implicit (pattern) rules. Knowing this, the possible uses for this
1323 feature increase dramatically. For example:
1326 main_OBJS := main.o try.o test.o
1327 lib_OBJS := lib.o api.o
1329 main lib: $$($$@_OBJS)
1331 Here, after the initial expansion the prerequisites of both the
1332 `main' and `lib' targets will be `$($@_OBJS)'. During the secondary
1333 expansion, the `$@' variable is set to the name of the target and so
1334 the expansion for the `main' target will yield `$(main_OBJS)', or
1335 `main.o try.o test.o', while the secondary expansion for the `lib'
1336 target will yield `$(lib_OBJS)', or `lib.o api.o'.
1338 You can also mix in functions here, as long as they are properly
1341 main_SRCS := main.c try.c test.c
1342 lib_SRCS := lib.c api.c
1345 main lib: $$(patsubst %.c,%.o,$$($$@_SRCS))
1347 This version allows users to specify source files rather than object
1348 files, but gives the same resulting prerequisites list as the previous
1351 Evaluation of automatic variables during the secondary expansion
1352 phase, especially of the target name variable `$$@', behaves similarly
1353 to evaluation within recipes. However, there are some subtle
1354 differences and "corner cases" which come into play for the different
1355 types of rule definitions that `make' understands. The subtleties of
1356 using the different automatic variables are described below.
1358 Secondary Expansion of Explicit Rules
1359 -------------------------------------
1361 During the secondary expansion of explicit rules, `$$@' and `$$%'
1362 evaluate, respectively, to the file name of the target and, when the
1363 target is an archive member, the target member name. The `$$<'
1364 variable evaluates to the first prerequisite in the first rule for this
1365 target. `$$^' and `$$+' evaluate to the list of all prerequisites of
1366 rules _that have already appeared_ for the same target (`$$+' with
1367 repetitions and `$$^' without). The following example will help
1368 illustrate these behaviors:
1372 foo: foo.1 bar.1 $$< $$^ $$+ # line #1
1374 foo: foo.2 bar.2 $$< $$^ $$+ # line #2
1376 foo: foo.3 bar.3 $$< $$^ $$+ # line #3
1378 In the first prerequisite list, all three variables (`$$<', `$$^',
1379 and `$$+') expand to the empty string. In the second, they will have
1380 values `foo.1', `foo.1 bar.1', and `foo.1 bar.1' respectively. In the
1381 third they will have values `foo.1', `foo.1 bar.1 foo.2 bar.2', and
1382 `foo.1 bar.1 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1' respectively.
1384 Rules undergo secondary expansion in makefile order, except that the
1385 rule with the recipe is always evaluated last.
1387 The variables `$$?' and `$$*' are not available and expand to the
1390 Secondary Expansion of Static Pattern Rules
1391 -------------------------------------------
1393 Rules for secondary expansion of static pattern rules are identical to
1394 those for explicit rules, above, with one exception: for static pattern
1395 rules the `$$*' variable is set to the pattern stem. As with explicit
1396 rules, `$$?' is not available and expands to the empty string.
1398 Secondary Expansion of Implicit Rules
1399 -------------------------------------
1401 As `make' searches for an implicit rule, it substitutes the stem and
1402 then performs secondary expansion for every rule with a matching target
1403 pattern. The value of the automatic variables is derived in the same
1404 fashion as for static pattern rules. As an example:
1412 %oo: $$< $$^ $$+ $$*
1414 When the implicit rule is tried for target `foo', `$$<' expands to
1415 `bar', `$$^' expands to `bar boo', `$$+' also expands to `bar boo', and
1416 `$$*' expands to `f'.
1418 Note that the directory prefix (D), as described in *note Implicit
1419 Rule Search Algorithm: Implicit Rule Search, is appended (after
1420 expansion) to all the patterns in the prerequisites list. As an
1427 %.o: $$(addsuffix /%.c,foo bar) foo.h
1429 The prerequisite list after the secondary expansion and directory
1430 prefix reconstruction will be `/tmp/foo/foo.c /tmp/var/bar/foo.c
1431 foo.h'. If you are not interested in this reconstruction, you can use
1432 `$$*' instead of `%' in the prerequisites list.
1435 File: make.info, Node: Rules, Next: Recipes, Prev: Makefiles, Up: Top
1440 A "rule" appears in the makefile and says when and how to remake
1441 certain files, called the rule's "targets" (most often only one per
1442 rule). It lists the other files that are the "prerequisites" of the
1443 target, and the "recipe" to use to create or update the target.
1445 The order of rules is not significant, except for determining the
1446 "default goal": the target for `make' to consider, if you do not
1447 otherwise specify one. The default goal is the target of the first
1448 rule in the first makefile. If the first rule has multiple targets,
1449 only the first target is taken as the default. There are two
1450 exceptions: a target starting with a period is not a default unless it
1451 contains one or more slashes, `/', as well; and, a target that defines
1452 a pattern rule has no effect on the default goal. (*Note Defining and
1453 Redefining Pattern Rules: Pattern Rules.)
1455 Therefore, we usually write the makefile so that the first rule is
1456 the one for compiling the entire program or all the programs described
1457 by the makefile (often with a target called `all'). *Note Arguments to
1458 Specify the Goals: Goals.
1462 * Rule Example:: An example explained.
1463 * Rule Syntax:: General syntax explained.
1464 * Prerequisite Types:: There are two types of prerequisites.
1465 * Wildcards:: Using wildcard characters such as `*'.
1466 * Directory Search:: Searching other directories for source files.
1467 * Phony Targets:: Using a target that is not a real file's name.
1468 * Force Targets:: You can use a target without recipes
1469 or prerequisites to mark other targets
1471 * Empty Targets:: When only the date matters and the
1473 * Special Targets:: Targets with special built-in meanings.
1474 * Multiple Targets:: When to make use of several targets in a rule.
1475 * Multiple Rules:: How to use several rules with the same target.
1476 * Static Pattern:: Static pattern rules apply to multiple targets
1477 and can vary the prerequisites according to
1479 * Double-Colon:: How to use a special kind of rule to allow
1480 several independent rules for one target.
1481 * Automatic Prerequisites:: How to automatically generate rules giving
1482 prerequisites from source files themselves.
1485 File: make.info, Node: Rule Example, Next: Rule Syntax, Prev: Rules, Up: Rules
1490 Here is an example of a rule:
1492 foo.o : foo.c defs.h # module for twiddling the frobs
1495 Its target is `foo.o' and its prerequisites are `foo.c' and
1496 `defs.h'. It has one command in the recipe: `cc -c -g foo.c'. The
1497 recipe starts with a tab to identify it as a recipe.
1499 This rule says two things:
1501 * How to decide whether `foo.o' is out of date: it is out of date if
1502 it does not exist, or if either `foo.c' or `defs.h' is more recent
1505 * How to update the file `foo.o': by running `cc' as stated. The
1506 recipe does not explicitly mention `defs.h', but we presume that
1507 `foo.c' includes it, and that that is why `defs.h' was added to
1511 File: make.info, Node: Rule Syntax, Next: Prerequisite Types, Prev: Rule Example, Up: Rules
1516 In general, a rule looks like this:
1518 TARGETS : PREREQUISITES
1524 TARGETS : PREREQUISITES ; RECIPE
1528 The TARGETS are file names, separated by spaces. Wildcard
1529 characters may be used (*note Using Wildcard Characters in File Names:
1530 Wildcards.) and a name of the form `A(M)' represents member M in
1531 archive file A (*note Archive Members as Targets: Archive Members.).
1532 Usually there is only one target per rule, but occasionally there is a
1533 reason to have more (*note Multiple Targets in a Rule: Multiple
1536 The RECIPE lines start with a tab character (or the first character
1537 in the value of the `.RECIPEPREFIX' variable; *note Special
1538 Variables::). The first recipe line may appear on the line after the
1539 prerequisites, with a tab character, or may appear on the same line,
1540 with a semicolon. Either way, the effect is the same. There are other
1541 differences in the syntax of recipes. *Note Writing Recipes in Rules:
1544 Because dollar signs are used to start `make' variable references,
1545 if you really want a dollar sign in a target or prerequisite you must
1546 write two of them, `$$' (*note How to Use Variables: Using Variables.).
1547 If you have enabled secondary expansion (*note Secondary Expansion::)
1548 and you want a literal dollar sign in the prerequisites list, you must
1549 actually write _four_ dollar signs (`$$$$').
1551 You may split a long line by inserting a backslash followed by a
1552 newline, but this is not required, as `make' places no limit on the
1553 length of a line in a makefile.
1555 A rule tells `make' two things: when the targets are out of date,
1556 and how to update them when necessary.
1558 The criterion for being out of date is specified in terms of the
1559 PREREQUISITES, which consist of file names separated by spaces.
1560 (Wildcards and archive members (*note Archives::) are allowed here too.)
1561 A target is out of date if it does not exist or if it is older than any
1562 of the prerequisites (by comparison of last-modification times). The
1563 idea is that the contents of the target file are computed based on
1564 information in the prerequisites, so if any of the prerequisites
1565 changes, the contents of the existing target file are no longer
1568 How to update is specified by a RECIPE. This is one or more lines
1569 to be executed by the shell (normally `sh'), but with some extra
1570 features (*note Writing Recipes in Rules: Recipes.).
1573 File: make.info, Node: Prerequisite Types, Next: Wildcards, Prev: Rule Syntax, Up: Rules
1575 4.3 Types of Prerequisites
1576 ==========================
1578 There are actually two different types of prerequisites understood by
1579 GNU `make': normal prerequisites such as described in the previous
1580 section, and "order-only" prerequisites. A normal prerequisite makes
1581 two statements: first, it imposes an order in which recipes will be
1582 invoked: the recipes for all prerequisites of a target will be
1583 completed before the recipe for the target is run. Second, it imposes
1584 a dependency relationship: if any prerequisite is newer than the
1585 target, then the target is considered out-of-date and must be rebuilt.
1587 Normally, this is exactly what you want: if a target's prerequisite
1588 is updated, then the target should also be updated.
1590 Occasionally, however, you have a situation where you want to impose
1591 a specific ordering on the rules to be invoked _without_ forcing the
1592 target to be updated if one of those rules is executed. In that case,
1593 you want to define "order-only" prerequisites. Order-only
1594 prerequisites can be specified by placing a pipe symbol (`|') in the
1595 prerequisites list: any prerequisites to the left of the pipe symbol
1596 are normal; any prerequisites to the right are order-only:
1598 TARGETS : NORMAL-PREREQUISITES | ORDER-ONLY-PREREQUISITES
1600 The normal prerequisites section may of course be empty. Also, you
1601 may still declare multiple lines of prerequisites for the same target:
1602 they are appended appropriately (normal prerequisites are appended to
1603 the list of normal prerequisites; order-only prerequisites are appended
1604 to the list of order-only prerequisites). Note that if you declare the
1605 same file to be both a normal and an order-only prerequisite, the
1606 normal prerequisite takes precedence (since they have a strict superset
1607 of the behavior of an order-only prerequisite).
1609 Consider an example where your targets are to be placed in a separate
1610 directory, and that directory might not exist before `make' is run. In
1611 this situation, you want the directory to be created before any targets
1612 are placed into it but, because the timestamps on directories change
1613 whenever a file is added, removed, or renamed, we certainly don't want
1614 to rebuild all the targets whenever the directory's timestamp changes.
1615 One way to manage this is with order-only prerequisites: make the
1616 directory an order-only prerequisite on all the targets:
1619 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
1622 $(COMPILE.c) $(OUTPUT_OPTION) $<
1626 $(OBJS): | $(OBJDIR)
1631 Now the rule to create the `objdir' directory will be run, if
1632 needed, before any `.o' is built, but no `.o' will be built because the
1633 `objdir' directory timestamp changed.
1636 File: make.info, Node: Wildcards, Next: Directory Search, Prev: Prerequisite Types, Up: Rules
1638 4.4 Using Wildcard Characters in File Names
1639 ===========================================
1641 A single file name can specify many files using "wildcard characters".
1642 The wildcard characters in `make' are `*', `?' and `[...]', the same as
1643 in the Bourne shell. For example, `*.c' specifies a list of all the
1644 files (in the working directory) whose names end in `.c'.
1646 The character `~' at the beginning of a file name also has special
1647 significance. If alone, or followed by a slash, it represents your home
1648 directory. For example `~/bin' expands to `/home/you/bin'. If the `~'
1649 is followed by a word, the string represents the home directory of the
1650 user named by that word. For example `~john/bin' expands to
1651 `/home/john/bin'. On systems which don't have a home directory for
1652 each user (such as MS-DOS or MS-Windows), this functionality can be
1653 simulated by setting the environment variable HOME.
1655 Wildcard expansion is performed by `make' automatically in targets
1656 and in prerequisites. In recipes, the shell is responsible for
1657 wildcard expansion. In other contexts, wildcard expansion happens only
1658 if you request it explicitly with the `wildcard' function.
1660 The special significance of a wildcard character can be turned off by
1661 preceding it with a backslash. Thus, `foo\*bar' would refer to a
1662 specific file whose name consists of `foo', an asterisk, and `bar'.
1666 * Wildcard Examples:: Several examples
1667 * Wildcard Pitfall:: Problems to avoid.
1668 * Wildcard Function:: How to cause wildcard expansion where
1669 it does not normally take place.
1672 File: make.info, Node: Wildcard Examples, Next: Wildcard Pitfall, Prev: Wildcards, Up: Wildcards
1674 4.4.1 Wildcard Examples
1675 -----------------------
1677 Wildcards can be used in the recipe of a rule, where they are expanded
1678 by the shell. For example, here is a rule to delete all the object
1684 Wildcards are also useful in the prerequisites of a rule. With the
1685 following rule in the makefile, `make print' will print all the `.c'
1686 files that have changed since the last time you printed them:
1692 This rule uses `print' as an empty target file; see *note Empty Target
1693 Files to Record Events: Empty Targets. (The automatic variable `$?' is
1694 used to print only those files that have changed; see *note Automatic
1697 Wildcard expansion does not happen when you define a variable.
1698 Thus, if you write this:
1702 then the value of the variable `objects' is the actual string `*.o'.
1703 However, if you use the value of `objects' in a target or prerequisite,
1704 wildcard expansion will take place there. If you use the value of
1705 `objects' in a recipe, the shell may perform wildcard expansion when
1706 the recipe runs. To set `objects' to the expansion, instead use:
1708 objects := $(wildcard *.o)
1710 *Note Wildcard Function::.
1713 File: make.info, Node: Wildcard Pitfall, Next: Wildcard Function, Prev: Wildcard Examples, Up: Wildcards
1715 4.4.2 Pitfalls of Using Wildcards
1716 ---------------------------------
1718 Now here is an example of a naive way of using wildcard expansion, that
1719 does not do what you would intend. Suppose you would like to say that
1720 the executable file `foo' is made from all the object files in the
1721 directory, and you write this:
1726 cc -o foo $(CFLAGS) $(objects)
1728 The value of `objects' is the actual string `*.o'. Wildcard expansion
1729 happens in the rule for `foo', so that each _existing_ `.o' file
1730 becomes a prerequisite of `foo' and will be recompiled if necessary.
1732 But what if you delete all the `.o' files? When a wildcard matches
1733 no files, it is left as it is, so then `foo' will depend on the
1734 oddly-named file `*.o'. Since no such file is likely to exist, `make'
1735 will give you an error saying it cannot figure out how to make `*.o'.
1736 This is not what you want!
1738 Actually it is possible to obtain the desired result with wildcard
1739 expansion, but you need more sophisticated techniques, including the
1740 `wildcard' function and string substitution. *Note The Function
1741 `wildcard': Wildcard Function.
1743 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes
1744 to separate directories in pathnames, like so:
1748 This is equivalent to the Unix-style `c:/foo/bar/baz.c' (the `c:'
1749 part is the so-called drive letter). When `make' runs on these
1750 systems, it supports backslashes as well as the Unix-style forward
1751 slashes in pathnames. However, this support does _not_ include the
1752 wildcard expansion, where backslash is a quote character. Therefore,
1753 you _must_ use Unix-style slashes in these cases.
1756 File: make.info, Node: Wildcard Function, Prev: Wildcard Pitfall, Up: Wildcards
1758 4.4.3 The Function `wildcard'
1759 -----------------------------
1761 Wildcard expansion happens automatically in rules. But wildcard
1762 expansion does not normally take place when a variable is set, or
1763 inside the arguments of a function. If you want to do wildcard
1764 expansion in such places, you need to use the `wildcard' function, like
1767 $(wildcard PATTERN...)
1769 This string, used anywhere in a makefile, is replaced by a
1770 space-separated list of names of existing files that match one of the
1771 given file name patterns. If no existing file name matches a pattern,
1772 then that pattern is omitted from the output of the `wildcard'
1773 function. Note that this is different from how unmatched wildcards
1774 behave in rules, where they are used verbatim rather than ignored
1775 (*note Wildcard Pitfall::).
1777 One use of the `wildcard' function is to get a list of all the C
1778 source files in a directory, like this:
1782 We can change the list of C source files into a list of object files
1783 by replacing the `.c' suffix with `.o' in the result, like this:
1785 $(patsubst %.c,%.o,$(wildcard *.c))
1787 (Here we have used another function, `patsubst'. *Note Functions for
1788 String Substitution and Analysis: Text Functions.)
1790 Thus, a makefile to compile all C source files in the directory and
1791 then link them together could be written as follows:
1793 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1796 cc -o foo $(objects)
1798 (This takes advantage of the implicit rule for compiling C programs, so
1799 there is no need to write explicit rules for compiling the files.
1800 *Note The Two Flavors of Variables: Flavors, for an explanation of
1801 `:=', which is a variant of `='.)
1804 File: make.info, Node: Directory Search, Next: Phony Targets, Prev: Wildcards, Up: Rules
1806 4.5 Searching Directories for Prerequisites
1807 ===========================================
1809 For large systems, it is often desirable to put sources in a separate
1810 directory from the binaries. The "directory search" features of `make'
1811 facilitate this by searching several directories automatically to find
1812 a prerequisite. When you redistribute the files among directories, you
1813 do not need to change the individual rules, just the search paths.
1817 * General Search:: Specifying a search path that applies
1818 to every prerequisite.
1819 * Selective Search:: Specifying a search path
1820 for a specified class of names.
1821 * Search Algorithm:: When and how search paths are applied.
1822 * Recipes/Search:: How to write recipes that work together
1824 * Implicit/Search:: How search paths affect implicit rules.
1825 * Libraries/Search:: Directory search for link libraries.
1828 File: make.info, Node: General Search, Next: Selective Search, Prev: Directory Search, Up: Directory Search
1830 4.5.1 `VPATH': Search Path for All Prerequisites
1831 ------------------------------------------------
1833 The value of the `make' variable `VPATH' specifies a list of
1834 directories that `make' should search. Most often, the directories are
1835 expected to contain prerequisite files that are not in the current
1836 directory; however, `make' uses `VPATH' as a search list for both
1837 prerequisites and targets of rules.
1839 Thus, if a file that is listed as a target or prerequisite does not
1840 exist in the current directory, `make' searches the directories listed
1841 in `VPATH' for a file with that name. If a file is found in one of
1842 them, that file may become the prerequisite (see below). Rules may then
1843 specify the names of files in the prerequisite list as if they all
1844 existed in the current directory. *Note Writing Recipes with Directory
1845 Search: Recipes/Search.
1847 In the `VPATH' variable, directory names are separated by colons or
1848 blanks. The order in which directories are listed is the order followed
1849 by `make' in its search. (On MS-DOS and MS-Windows, semi-colons are
1850 used as separators of directory names in `VPATH', since the colon can
1851 be used in the pathname itself, after the drive letter.)
1855 VPATH = src:../headers
1857 specifies a path containing two directories, `src' and `../headers',
1858 which `make' searches in that order.
1860 With this value of `VPATH', the following rule,
1864 is interpreted as if it were written like this:
1868 assuming the file `foo.c' does not exist in the current directory but
1869 is found in the directory `src'.
1872 File: make.info, Node: Selective Search, Next: Search Algorithm, Prev: General Search, Up: Directory Search
1874 4.5.2 The `vpath' Directive
1875 ---------------------------
1877 Similar to the `VPATH' variable, but more selective, is the `vpath'
1878 directive (note lower case), which allows you to specify a search path
1879 for a particular class of file names: those that match a particular
1880 pattern. Thus you can supply certain search directories for one class
1881 of file names and other directories (or none) for other file names.
1883 There are three forms of the `vpath' directive:
1885 `vpath PATTERN DIRECTORIES'
1886 Specify the search path DIRECTORIES for file names that match
1889 The search path, DIRECTORIES, is a list of directories to be
1890 searched, separated by colons (semi-colons on MS-DOS and
1891 MS-Windows) or blanks, just like the search path used in the
1895 Clear out the search path associated with PATTERN.
1898 Clear all search paths previously specified with `vpath'
1901 A `vpath' pattern is a string containing a `%' character. The
1902 string must match the file name of a prerequisite that is being searched
1903 for, the `%' character matching any sequence of zero or more characters
1904 (as in pattern rules; *note Defining and Redefining Pattern Rules:
1905 Pattern Rules.). For example, `%.h' matches files that end in `.h'.
1906 (If there is no `%', the pattern must match the prerequisite exactly,
1907 which is not useful very often.)
1909 `%' characters in a `vpath' directive's pattern can be quoted with
1910 preceding backslashes (`\'). Backslashes that would otherwise quote
1911 `%' characters can be quoted with more backslashes. Backslashes that
1912 quote `%' characters or other backslashes are removed from the pattern
1913 before it is compared to file names. Backslashes that are not in
1914 danger of quoting `%' characters go unmolested.
1916 When a prerequisite fails to exist in the current directory, if the
1917 PATTERN in a `vpath' directive matches the name of the prerequisite
1918 file, then the DIRECTORIES in that directive are searched just like
1919 (and before) the directories in the `VPATH' variable.
1923 vpath %.h ../headers
1925 tells `make' to look for any prerequisite whose name ends in `.h' in
1926 the directory `../headers' if the file is not found in the current
1929 If several `vpath' patterns match the prerequisite file's name, then
1930 `make' processes each matching `vpath' directive one by one, searching
1931 all the directories mentioned in each directive. `make' handles
1932 multiple `vpath' directives in the order in which they appear in the
1933 makefile; multiple directives with the same pattern are independent of
1942 will look for a file ending in `.c' in `foo', then `blish', then `bar',
1948 will look for a file ending in `.c' in `foo', then `bar', then `blish'.
1951 File: make.info, Node: Search Algorithm, Next: Recipes/Search, Prev: Selective Search, Up: Directory Search
1953 4.5.3 How Directory Searches are Performed
1954 ------------------------------------------
1956 When a prerequisite is found through directory search, regardless of
1957 type (general or selective), the pathname located may not be the one
1958 that `make' actually provides you in the prerequisite list. Sometimes
1959 the path discovered through directory search is thrown away.
1961 The algorithm `make' uses to decide whether to keep or abandon a
1962 path found via directory search is as follows:
1964 1. If a target file does not exist at the path specified in the
1965 makefile, directory search is performed.
1967 2. If the directory search is successful, that path is kept and this
1968 file is tentatively stored as the target.
1970 3. All prerequisites of this target are examined using this same
1973 4. After processing the prerequisites, the target may or may not need
1976 a. If the target does _not_ need to be rebuilt, the path to the
1977 file found during directory search is used for any
1978 prerequisite lists which contain this target. In short, if
1979 `make' doesn't need to rebuild the target then you use the
1980 path found via directory search.
1982 b. If the target _does_ need to be rebuilt (is out-of-date), the
1983 pathname found during directory search is _thrown away_, and
1984 the target is rebuilt using the file name specified in the
1985 makefile. In short, if `make' must rebuild, then the target
1986 is rebuilt locally, not in the directory found via directory
1989 This algorithm may seem complex, but in practice it is quite often
1990 exactly what you want.
1992 Other versions of `make' use a simpler algorithm: if the file does
1993 not exist, and it is found via directory search, then that pathname is
1994 always used whether or not the target needs to be built. Thus, if the
1995 target is rebuilt it is created at the pathname discovered during
1998 If, in fact, this is the behavior you want for some or all of your
1999 directories, you can use the `GPATH' variable to indicate this to
2002 `GPATH' has the same syntax and format as `VPATH' (that is, a space-
2003 or colon-delimited list of pathnames). If an out-of-date target is
2004 found by directory search in a directory that also appears in `GPATH',
2005 then that pathname is not thrown away. The target is rebuilt using the
2009 File: make.info, Node: Recipes/Search, Next: Implicit/Search, Prev: Search Algorithm, Up: Directory Search
2011 4.5.4 Writing Recipes with Directory Search
2012 -------------------------------------------
2014 When a prerequisite is found in another directory through directory
2015 search, this cannot change the recipe of the rule; they will execute as
2016 written. Therefore, you must write the recipe with care so that it
2017 will look for the prerequisite in the directory where `make' finds it.
2019 This is done with the "automatic variables" such as `$^' (*note
2020 Automatic Variables::). For instance, the value of `$^' is a list of
2021 all the prerequisites of the rule, including the names of the
2022 directories in which they were found, and the value of `$@' is the
2026 cc -c $(CFLAGS) $^ -o $@
2028 (The variable `CFLAGS' exists so you can specify flags for C
2029 compilation by implicit rules; we use it here for consistency so it will
2030 affect all C compilations uniformly; *note Variables Used by Implicit
2031 Rules: Implicit Variables.)
2033 Often the prerequisites include header files as well, which you do
2034 not want to mention in the recipe. The automatic variable `$<' is just
2035 the first prerequisite:
2037 VPATH = src:../headers
2038 foo.o : foo.c defs.h hack.h
2039 cc -c $(CFLAGS) $< -o $@
2042 File: make.info, Node: Implicit/Search, Next: Libraries/Search, Prev: Recipes/Search, Up: Directory Search
2044 4.5.5 Directory Search and Implicit Rules
2045 -----------------------------------------
2047 The search through the directories specified in `VPATH' or with `vpath'
2048 also happens during consideration of implicit rules (*note Using
2049 Implicit Rules: Implicit Rules.).
2051 For example, when a file `foo.o' has no explicit rule, `make'
2052 considers implicit rules, such as the built-in rule to compile `foo.c'
2053 if that file exists. If such a file is lacking in the current
2054 directory, the appropriate directories are searched for it. If `foo.c'
2055 exists (or is mentioned in the makefile) in any of the directories, the
2056 implicit rule for C compilation is applied.
2058 The recipes of implicit rules normally use automatic variables as a
2059 matter of necessity; consequently they will use the file names found by
2060 directory search with no extra effort.
2063 File: make.info, Node: Libraries/Search, Prev: Implicit/Search, Up: Directory Search
2065 4.5.6 Directory Search for Link Libraries
2066 -----------------------------------------
2068 Directory search applies in a special way to libraries used with the
2069 linker. This special feature comes into play when you write a
2070 prerequisite whose name is of the form `-lNAME'. (You can tell
2071 something strange is going on here because the prerequisite is normally
2072 the name of a file, and the _file name_ of a library generally looks
2073 like `libNAME.a', not like `-lNAME'.)
2075 When a prerequisite's name has the form `-lNAME', `make' handles it
2076 specially by searching for the file `libNAME.so', and, if it is not
2077 found, for the file `libNAME.a' in the current directory, in
2078 directories specified by matching `vpath' search paths and the `VPATH'
2079 search path, and then in the directories `/lib', `/usr/lib', and
2080 `PREFIX/lib' (normally `/usr/local/lib', but MS-DOS/MS-Windows versions
2081 of `make' behave as if PREFIX is defined to be the root of the DJGPP
2084 For example, if there is a `/usr/lib/libcurses.a' library on your
2085 system (and no `/usr/lib/libcurses.so' file), then
2087 foo : foo.c -lcurses
2090 would cause the command `cc foo.c /usr/lib/libcurses.a -o foo' to be
2091 executed when `foo' is older than `foo.c' or than
2092 `/usr/lib/libcurses.a'.
2094 Although the default set of files to be searched for is `libNAME.so'
2095 and `libNAME.a', this is customizable via the `.LIBPATTERNS' variable.
2096 Each word in the value of this variable is a pattern string. When a
2097 prerequisite like `-lNAME' is seen, `make' will replace the percent in
2098 each pattern in the list with NAME and perform the above directory
2099 searches using each library filename.
2101 The default value for `.LIBPATTERNS' is `lib%.so lib%.a', which
2102 provides the default behavior described above.
2104 You can turn off link library expansion completely by setting this
2105 variable to an empty value.
2108 File: make.info, Node: Phony Targets, Next: Force Targets, Prev: Directory Search, Up: Rules
2113 A phony target is one that is not really the name of a file; rather it
2114 is just a name for a recipe to be executed when you make an explicit
2115 request. There are two reasons to use a phony target: to avoid a
2116 conflict with a file of the same name, and to improve performance.
2118 If you write a rule whose recipe will not create the target file, the
2119 recipe will be executed every time the target comes up for remaking.
2125 Because the `rm' command does not create a file named `clean', probably
2126 no such file will ever exist. Therefore, the `rm' command will be
2127 executed every time you say `make clean'.
2129 The phony target will cease to work if anything ever does create a
2130 file named `clean' in this directory. Since it has no prerequisites,
2131 the file `clean' would inevitably be considered up to date, and its
2132 recipe would not be executed. To avoid this problem, you can explicitly
2133 declare the target to be phony, using the special target `.PHONY'
2134 (*note Special Built-in Target Names: Special Targets.) as follows:
2138 Once this is done, `make clean' will run the recipe regardless of
2139 whether there is a file named `clean'.
2141 Since it knows that phony targets do not name actual files that
2142 could be remade from other files, `make' skips the implicit rule search
2143 for phony targets (*note Implicit Rules::). This is why declaring a
2144 target phony is good for performance, even if you are not worried about
2145 the actual file existing.
2147 Thus, you first write the line that states that `clean' is a phony
2148 target, then you write the rule, like this:
2154 Another example of the usefulness of phony targets is in conjunction
2155 with recursive invocations of `make' (for more information, see *note
2156 Recursive Use of `make': Recursion.). In this case the makefile will
2157 often contain a variable which lists a number of subdirectories to be
2158 built. One way to handle this is with one rule whose recipe is a shell
2159 loop over the subdirectories, like this:
2161 SUBDIRS = foo bar baz
2164 for dir in $(SUBDIRS); do \
2168 There are problems with this method, however. First, any error
2169 detected in a submake is ignored by this rule, so it will continue to
2170 build the rest of the directories even when one fails. This can be
2171 overcome by adding shell commands to note the error and exit, but then
2172 it will do so even if `make' is invoked with the `-k' option, which is
2173 unfortunate. Second, and perhaps more importantly, you cannot take
2174 advantage of `make''s ability to build targets in parallel (*note
2175 Parallel Execution: Parallel.), since there is only one rule.
2177 By declaring the subdirectories as phony targets (you must do this as
2178 the subdirectory obviously always exists; otherwise it won't be built)
2179 you can remove these problems:
2181 SUBDIRS = foo bar baz
2183 .PHONY: subdirs $(SUBDIRS)
2192 Here we've also declared that the `foo' subdirectory cannot be built
2193 until after the `baz' subdirectory is complete; this kind of
2194 relationship declaration is particularly important when attempting
2197 A phony target should not be a prerequisite of a real target file;
2198 if it is, its recipe will be run every time `make' goes to update that
2199 file. As long as a phony target is never a prerequisite of a real
2200 target, the phony target recipe will be executed only when the phony
2201 target is a specified goal (*note Arguments to Specify the Goals:
2204 Phony targets can have prerequisites. When one directory contains
2205 multiple programs, it is most convenient to describe all of the
2206 programs in one makefile `./Makefile'. Since the target remade by
2207 default will be the first one in the makefile, it is common to make
2208 this a phony target named `all' and give it, as prerequisites, all the
2209 individual programs. For example:
2211 all : prog1 prog2 prog3
2214 prog1 : prog1.o utils.o
2215 cc -o prog1 prog1.o utils.o
2220 prog3 : prog3.o sort.o utils.o
2221 cc -o prog3 prog3.o sort.o utils.o
2223 Now you can say just `make' to remake all three programs, or specify as
2224 arguments the ones to remake (as in `make prog1 prog3'). Phoniness is
2225 not inherited: the prerequisites of a phony target are not themselves
2226 phony, unless explicitly declared to be so.
2228 When one phony target is a prerequisite of another, it serves as a
2229 subroutine of the other. For example, here `make cleanall' will delete
2230 the object files, the difference files, and the file `program':
2232 .PHONY: cleanall cleanobj cleandiff
2234 cleanall : cleanobj cleandiff
2244 File: make.info, Node: Force Targets, Next: Empty Targets, Prev: Phony Targets, Up: Rules
2246 4.7 Rules without Recipes or Prerequisites
2247 ==========================================
2249 If a rule has no prerequisites or recipe, and the target of the rule is
2250 a nonexistent file, then `make' imagines this target to have been
2251 updated whenever its rule is run. This implies that all targets
2252 depending on this one will always have their recipe run.
2254 An example will illustrate this:
2260 Here the target `FORCE' satisfies the special conditions, so the
2261 target `clean' that depends on it is forced to run its recipe. There
2262 is nothing special about the name `FORCE', but that is one name
2263 commonly used this way.
2265 As you can see, using `FORCE' this way has the same results as using
2268 Using `.PHONY' is more explicit and more efficient. However, other
2269 versions of `make' do not support `.PHONY'; thus `FORCE' appears in
2270 many makefiles. *Note Phony Targets::.
2273 File: make.info, Node: Empty Targets, Next: Special Targets, Prev: Force Targets, Up: Rules
2275 4.8 Empty Target Files to Record Events
2276 =======================================
2278 The "empty target" is a variant of the phony target; it is used to hold
2279 recipes for an action that you request explicitly from time to time.
2280 Unlike a phony target, this target file can really exist; but the file's
2281 contents do not matter, and usually are empty.
2283 The purpose of the empty target file is to record, with its
2284 last-modification time, when the rule's recipe was last executed. It
2285 does so because one of the commands in the recipe is a `touch' command
2286 to update the target file.
2288 The empty target file should have some prerequisites (otherwise it
2289 doesn't make sense). When you ask to remake the empty target, the
2290 recipe is executed if any prerequisite is more recent than the target;
2291 in other words, if a prerequisite has changed since the last time you
2292 remade the target. Here is an example:
2298 With this rule, `make print' will execute the `lpr' command if either
2299 source file has changed since the last `make print'. The automatic
2300 variable `$?' is used to print only those files that have changed
2301 (*note Automatic Variables::).
2304 File: make.info, Node: Special Targets, Next: Multiple Targets, Prev: Empty Targets, Up: Rules
2306 4.9 Special Built-in Target Names
2307 =================================
2309 Certain names have special meanings if they appear as targets.
2312 The prerequisites of the special target `.PHONY' are considered to
2313 be phony targets. When it is time to consider such a target,
2314 `make' will run its recipe unconditionally, regardless of whether
2315 a file with that name exists or what its last-modification time
2316 is. *Note Phony Targets: Phony Targets.
2319 The prerequisites of the special target `.SUFFIXES' are the list
2320 of suffixes to be used in checking for suffix rules. *Note
2321 Old-Fashioned Suffix Rules: Suffix Rules.
2324 The recipe specified for `.DEFAULT' is used for any target for
2325 which no rules are found (either explicit rules or implicit rules).
2326 *Note Last Resort::. If a `.DEFAULT' recipe is specified, every
2327 file mentioned as a prerequisite, but not as a target in a rule,
2328 will have that recipe executed on its behalf. *Note Implicit Rule
2329 Search Algorithm: Implicit Rule Search.
2332 The targets which `.PRECIOUS' depends on are given the following
2333 special treatment: if `make' is killed or interrupted during the
2334 execution of their recipes, the target is not deleted. *Note
2335 Interrupting or Killing `make': Interrupts. Also, if the target
2336 is an intermediate file, it will not be deleted after it is no
2337 longer needed, as is normally done. *Note Chains of Implicit
2338 Rules: Chained Rules. In this latter respect it overlaps with the
2339 `.SECONDARY' special target.
2341 You can also list the target pattern of an implicit rule (such as
2342 `%.o') as a prerequisite file of the special target `.PRECIOUS' to
2343 preserve intermediate files created by rules whose target patterns
2344 match that file's name.
2347 The targets which `.INTERMEDIATE' depends on are treated as
2348 intermediate files. *Note Chains of Implicit Rules: Chained Rules.
2349 `.INTERMEDIATE' with no prerequisites has no effect.
2352 The targets which `.SECONDARY' depends on are treated as
2353 intermediate files, except that they are never automatically
2354 deleted. *Note Chains of Implicit Rules: Chained Rules.
2356 `.SECONDARY' with no prerequisites causes all targets to be treated
2357 as secondary (i.e., no target is removed because it is considered
2361 If `.SECONDEXPANSION' is mentioned as a target anywhere in the
2362 makefile, then all prerequisite lists defined _after_ it appears
2363 will be expanded a second time after all makefiles have been read
2364 in. *Note Secondary Expansion: Secondary Expansion.
2367 If `.DELETE_ON_ERROR' is mentioned as a target anywhere in the
2368 makefile, then `make' will delete the target of a rule if it has
2369 changed and its recipe exits with a nonzero exit status, just as it
2370 does when it receives a signal. *Note Errors in Recipes: Errors.
2373 If you specify prerequisites for `.IGNORE', then `make' will
2374 ignore errors in execution of the recipe for those particular
2375 files. The recipe for `.IGNORE' (if any) is ignored.
2377 If mentioned as a target with no prerequisites, `.IGNORE' says to
2378 ignore errors in execution of recipes for all files. This usage of
2379 `.IGNORE' is supported only for historical compatibility. Since
2380 this affects every recipe in the makefile, it is not very useful;
2381 we recommend you use the more selective ways to ignore errors in
2382 specific recipes. *Note Errors in Recipes: Errors.
2384 `.LOW_RESOLUTION_TIME'
2385 If you specify prerequisites for `.LOW_RESOLUTION_TIME', `make'
2386 assumes that these files are created by commands that generate low
2387 resolution time stamps. The recipe for the `.LOW_RESOLUTION_TIME'
2390 The high resolution file time stamps of many modern file systems
2391 lessen the chance of `make' incorrectly concluding that a file is
2392 up to date. Unfortunately, some hosts do not provide a way to set
2393 a high resolution file time stamp, so commands like `cp -p' that
2394 explicitly set a file's time stamp must discard its subsecond part.
2395 If a file is created by such a command, you should list it as a
2396 prerequisite of `.LOW_RESOLUTION_TIME' so that `make' does not
2397 mistakenly conclude that the file is out of date. For example:
2399 .LOW_RESOLUTION_TIME: dst
2403 Since `cp -p' discards the subsecond part of `src''s time stamp,
2404 `dst' is typically slightly older than `src' even when it is up to
2405 date. The `.LOW_RESOLUTION_TIME' line causes `make' to consider
2406 `dst' to be up to date if its time stamp is at the start of the
2407 same second that `src''s time stamp is in.
2409 Due to a limitation of the archive format, archive member time
2410 stamps are always low resolution. You need not list archive
2411 members as prerequisites of `.LOW_RESOLUTION_TIME', as `make' does
2415 If you specify prerequisites for `.SILENT', then `make' will not
2416 print the recipe used to remake those particular files before
2417 executing them. The recipe for `.SILENT' is ignored.
2419 If mentioned as a target with no prerequisites, `.SILENT' says not
2420 to print any recipes before executing them. This usage of
2421 `.SILENT' is supported only for historical compatibility. We
2422 recommend you use the more selective ways to silence specific
2423 recipes. *Note Recipe Echoing: Echoing. If you want to silence
2424 all recipes for a particular run of `make', use the `-s' or
2425 `--silent' option (*note Options Summary::).
2427 `.EXPORT_ALL_VARIABLES'
2428 Simply by being mentioned as a target, this tells `make' to export
2429 all variables to child processes by default. *Note Communicating
2430 Variables to a Sub-`make': Variables/Recursion.
2433 If `.NOTPARALLEL' is mentioned as a target, then this invocation
2434 of `make' will be run serially, even if the `-j' option is given.
2435 Any recursively invoked `make' command will still run recipes in
2436 parallel (unless its makefile also contains this target). Any
2437 prerequisites on this target are ignored.
2440 If `.ONESHELL' is mentioned as a target, then when a target is
2441 built all lines of the recipe will be given to a single invocation
2442 of the shell rather than each line being invoked separately (*note
2443 Recipe Execution: Execution.).
2446 If `.POSIX' is mentioned as a target, then the makefile will be
2447 parsed and run in POSIX-conforming mode. This does _not_ mean
2448 that only POSIX-conforming makefiles will be accepted: all advanced
2449 GNU `make' features are still available. Rather, this target
2450 causes `make' to behave as required by POSIX in those areas where
2451 `make''s default behavior differs.
2453 In particular, if this target is mentioned then recipes will be
2454 invoked as if the shell had been passed the `-e' flag: the first
2455 failing command in a recipe will cause the recipe to fail
2458 Any defined implicit rule suffix also counts as a special target if
2459 it appears as a target, and so does the concatenation of two suffixes,
2460 such as `.c.o'. These targets are suffix rules, an obsolete way of
2461 defining implicit rules (but a way still widely used). In principle,
2462 any target name could be special in this way if you break it in two and
2463 add both pieces to the suffix list. In practice, suffixes normally
2464 begin with `.', so these special target names also begin with `.'.
2465 *Note Old-Fashioned Suffix Rules: Suffix Rules.
2468 File: make.info, Node: Multiple Targets, Next: Multiple Rules, Prev: Special Targets, Up: Rules
2470 4.10 Multiple Targets in a Rule
2471 ===============================
2473 A rule with multiple targets is equivalent to writing many rules, each
2474 with one target, and all identical aside from that. The same recipe
2475 applies to all the targets, but its effect may vary because you can
2476 substitute the actual target name into the recipe using `$@'. The rule
2477 contributes the same prerequisites to all the targets also.
2479 This is useful in two cases.
2481 * You want just prerequisites, no recipe. For example:
2483 kbd.o command.o files.o: command.h
2485 gives an additional prerequisite to each of the three object files
2488 * Similar recipes work for all the targets. The recipes do not need
2489 to be absolutely identical, since the automatic variable `$@' can
2490 be used to substitute the particular target to be remade into the
2491 commands (*note Automatic Variables::). For example:
2493 bigoutput littleoutput : text.g
2494 generate text.g -$(subst output,,$@) > $@
2499 generate text.g -big > bigoutput
2500 littleoutput : text.g
2501 generate text.g -little > littleoutput
2503 Here we assume the hypothetical program `generate' makes two types
2504 of output, one if given `-big' and one if given `-little'. *Note
2505 Functions for String Substitution and Analysis: Text Functions,
2506 for an explanation of the `subst' function.
2508 Suppose you would like to vary the prerequisites according to the
2509 target, much as the variable `$@' allows you to vary the recipe. You
2510 cannot do this with multiple targets in an ordinary rule, but you can
2511 do it with a "static pattern rule". *Note Static Pattern Rules: Static
2515 File: make.info, Node: Multiple Rules, Next: Static Pattern, Prev: Multiple Targets, Up: Rules
2517 4.11 Multiple Rules for One Target
2518 ==================================
2520 One file can be the target of several rules. All the prerequisites
2521 mentioned in all the rules are merged into one list of prerequisites for
2522 the target. If the target is older than any prerequisite from any rule,
2523 the recipe is executed.
2525 There can only be one recipe to be executed for a file. If more than
2526 one rule gives a recipe for the same file, `make' uses the last one
2527 given and prints an error message. (As a special case, if the file's
2528 name begins with a dot, no error message is printed. This odd behavior
2529 is only for compatibility with other implementations of `make'... you
2530 should avoid using it). Occasionally it is useful to have the same
2531 target invoke multiple recipes which are defined in different parts of
2532 your makefile; you can use "double-colon rules" (*note Double-Colon::)
2535 An extra rule with just prerequisites can be used to give a few extra
2536 prerequisites to many files at once. For example, makefiles often have
2537 a variable, such as `objects', containing a list of all the compiler
2538 output files in the system being made. An easy way to say that all of
2539 them must be recompiled if `config.h' changes is to write the following:
2541 objects = foo.o bar.o
2543 bar.o : defs.h test.h
2544 $(objects) : config.h
2546 This could be inserted or taken out without changing the rules that
2547 really specify how to make the object files, making it a convenient
2548 form to use if you wish to add the additional prerequisite
2551 Another wrinkle is that the additional prerequisites could be
2552 specified with a variable that you set with a command line argument to
2553 `make' (*note Overriding Variables: Overriding.). For example,
2556 $(objects) : $(extradeps)
2558 means that the command `make extradeps=foo.h' will consider `foo.h' as
2559 a prerequisite of each object file, but plain `make' will not.
2561 If none of the explicit rules for a target has a recipe, then `make'
2562 searches for an applicable implicit rule to find one *note Using
2563 Implicit Rules: Implicit Rules.).
2566 File: make.info, Node: Static Pattern, Next: Double-Colon, Prev: Multiple Rules, Up: Rules
2568 4.12 Static Pattern Rules
2569 =========================
2571 "Static pattern rules" are rules which specify multiple targets and
2572 construct the prerequisite names for each target based on the target
2573 name. They are more general than ordinary rules with multiple targets
2574 because the targets do not have to have identical prerequisites. Their
2575 prerequisites must be _analogous_, but not necessarily _identical_.
2579 * Static Usage:: The syntax of static pattern rules.
2580 * Static versus Implicit:: When are they better than implicit rules?
2583 File: make.info, Node: Static Usage, Next: Static versus Implicit, Prev: Static Pattern, Up: Static Pattern
2585 4.12.1 Syntax of Static Pattern Rules
2586 -------------------------------------
2588 Here is the syntax of a static pattern rule:
2590 TARGETS ...: TARGET-PATTERN: PREREQ-PATTERNS ...
2594 The TARGETS list specifies the targets that the rule applies to. The
2595 targets can contain wildcard characters, just like the targets of
2596 ordinary rules (*note Using Wildcard Characters in File Names:
2599 The TARGET-PATTERN and PREREQ-PATTERNS say how to compute the
2600 prerequisites of each target. Each target is matched against the
2601 TARGET-PATTERN to extract a part of the target name, called the "stem".
2602 This stem is substituted into each of the PREREQ-PATTERNS to make the
2603 prerequisite names (one from each PREREQ-PATTERN).
2605 Each pattern normally contains the character `%' just once. When the
2606 TARGET-PATTERN matches a target, the `%' can match any part of the
2607 target name; this part is called the "stem". The rest of the pattern
2608 must match exactly. For example, the target `foo.o' matches the
2609 pattern `%.o', with `foo' as the stem. The targets `foo.c' and
2610 `foo.out' do not match that pattern.
2612 The prerequisite names for each target are made by substituting the
2613 stem for the `%' in each prerequisite pattern. For example, if one
2614 prerequisite pattern is `%.c', then substitution of the stem `foo'
2615 gives the prerequisite name `foo.c'. It is legitimate to write a
2616 prerequisite pattern that does not contain `%'; then this prerequisite
2617 is the same for all targets.
2619 `%' characters in pattern rules can be quoted with preceding
2620 backslashes (`\'). Backslashes that would otherwise quote `%'
2621 characters can be quoted with more backslashes. Backslashes that quote
2622 `%' characters or other backslashes are removed from the pattern before
2623 it is compared to file names or has a stem substituted into it.
2624 Backslashes that are not in danger of quoting `%' characters go
2625 unmolested. For example, the pattern `the\%weird\\%pattern\\' has
2626 `the%weird\' preceding the operative `%' character, and `pattern\\'
2627 following it. The final two backslashes are left alone because they
2628 cannot affect any `%' character.
2630 Here is an example, which compiles each of `foo.o' and `bar.o' from
2631 the corresponding `.c' file:
2633 objects = foo.o bar.o
2637 $(objects): %.o: %.c
2638 $(CC) -c $(CFLAGS) $< -o $@
2640 Here `$<' is the automatic variable that holds the name of the
2641 prerequisite and `$@' is the automatic variable that holds the name of
2642 the target; see *note Automatic Variables::.
2644 Each target specified must match the target pattern; a warning is
2645 issued for each target that does not. If you have a list of files,
2646 only some of which will match the pattern, you can use the `filter'
2647 function to remove nonmatching file names (*note Functions for String
2648 Substitution and Analysis: Text Functions.):
2650 files = foo.elc bar.o lose.o
2652 $(filter %.o,$(files)): %.o: %.c
2653 $(CC) -c $(CFLAGS) $< -o $@
2654 $(filter %.elc,$(files)): %.elc: %.el
2655 emacs -f batch-byte-compile $<
2657 In this example the result of `$(filter %.o,$(files))' is `bar.o
2658 lose.o', and the first static pattern rule causes each of these object
2659 files to be updated by compiling the corresponding C source file. The
2660 result of `$(filter %.elc,$(files))' is `foo.elc', so that file is made
2663 Another example shows how to use `$*' in static pattern rules:
2665 bigoutput littleoutput : %output : text.g
2666 generate text.g -$* > $@
2668 When the `generate' command is run, `$*' will expand to the stem,
2669 either `big' or `little'.
2672 File: make.info, Node: Static versus Implicit, Prev: Static Usage, Up: Static Pattern
2674 4.12.2 Static Pattern Rules versus Implicit Rules
2675 -------------------------------------------------
2677 A static pattern rule has much in common with an implicit rule defined
2678 as a pattern rule (*note Defining and Redefining Pattern Rules: Pattern
2679 Rules.). Both have a pattern for the target and patterns for
2680 constructing the names of prerequisites. The difference is in how
2681 `make' decides _when_ the rule applies.
2683 An implicit rule _can_ apply to any target that matches its pattern,
2684 but it _does_ apply only when the target has no recipe otherwise
2685 specified, and only when the prerequisites can be found. If more than
2686 one implicit rule appears applicable, only one applies; the choice
2687 depends on the order of rules.
2689 By contrast, a static pattern rule applies to the precise list of
2690 targets that you specify in the rule. It cannot apply to any other
2691 target and it invariably does apply to each of the targets specified.
2692 If two conflicting rules apply, and both have recipes, that's an error.
2694 The static pattern rule can be better than an implicit rule for these
2697 * You may wish to override the usual implicit rule for a few files
2698 whose names cannot be categorized syntactically but can be given
2699 in an explicit list.
2701 * If you cannot be sure of the precise contents of the directories
2702 you are using, you may not be sure which other irrelevant files
2703 might lead `make' to use the wrong implicit rule. The choice
2704 might depend on the order in which the implicit rule search is
2705 done. With static pattern rules, there is no uncertainty: each
2706 rule applies to precisely the targets specified.
2709 File: make.info, Node: Double-Colon, Next: Automatic Prerequisites, Prev: Static Pattern, Up: Rules
2711 4.13 Double-Colon Rules
2712 =======================
2714 "Double-colon" rules are explicit rules written with `::' instead of
2715 `:' after the target names. They are handled differently from ordinary
2716 rules when the same target appears in more than one rule. Pattern
2717 rules with double-colons have an entirely different meaning (*note
2718 Match-Anything Rules::).
2720 When a target appears in multiple rules, all the rules must be the
2721 same type: all ordinary, or all double-colon. If they are
2722 double-colon, each of them is independent of the others. Each
2723 double-colon rule's recipe is executed if the target is older than any
2724 prerequisites of that rule. If there are no prerequisites for that
2725 rule, its recipe is always executed (even if the target already
2726 exists). This can result in executing none, any, or all of the
2729 Double-colon rules with the same target are in fact completely
2730 separate from one another. Each double-colon rule is processed
2731 individually, just as rules with different targets are processed.
2733 The double-colon rules for a target are executed in the order they
2734 appear in the makefile. However, the cases where double-colon rules
2735 really make sense are those where the order of executing the recipes
2738 Double-colon rules are somewhat obscure and not often very useful;
2739 they provide a mechanism for cases in which the method used to update a
2740 target differs depending on which prerequisite files caused the update,
2741 and such cases are rare.
2743 Each double-colon rule should specify a recipe; if it does not, an
2744 implicit rule will be used if one applies. *Note Using Implicit Rules:
2748 File: make.info, Node: Automatic Prerequisites, Prev: Double-Colon, Up: Rules
2750 4.14 Generating Prerequisites Automatically
2751 ===========================================
2753 In the makefile for a program, many of the rules you need to write often
2754 say only that some object file depends on some header file. For
2755 example, if `main.c' uses `defs.h' via an `#include', you would write:
2759 You need this rule so that `make' knows that it must remake `main.o'
2760 whenever `defs.h' changes. You can see that for a large program you
2761 would have to write dozens of such rules in your makefile. And, you
2762 must always be very careful to update the makefile every time you add
2763 or remove an `#include'.
2765 To avoid this hassle, most modern C compilers can write these rules
2766 for you, by looking at the `#include' lines in the source files.
2767 Usually this is done with the `-M' option to the compiler. For
2768 example, the command:
2772 generates the output:
2774 main.o : main.c defs.h
2776 Thus you no longer have to write all those rules yourself. The
2777 compiler will do it for you.
2779 Note that such a prerequisite constitutes mentioning `main.o' in a
2780 makefile, so it can never be considered an intermediate file by implicit
2781 rule search. This means that `make' won't ever remove the file after
2782 using it; *note Chains of Implicit Rules: Chained Rules.
2784 With old `make' programs, it was traditional practice to use this
2785 compiler feature to generate prerequisites on demand with a command like
2786 `make depend'. That command would create a file `depend' containing
2787 all the automatically-generated prerequisites; then the makefile could
2788 use `include' to read them in (*note Include::).
2790 In GNU `make', the feature of remaking makefiles makes this practice
2791 obsolete--you need never tell `make' explicitly to regenerate the
2792 prerequisites, because it always regenerates any makefile that is out
2793 of date. *Note Remaking Makefiles::.
2795 The practice we recommend for automatic prerequisite generation is
2796 to have one makefile corresponding to each source file. For each
2797 source file `NAME.c' there is a makefile `NAME.d' which lists what
2798 files the object file `NAME.o' depends on. That way only the source
2799 files that have changed need to be rescanned to produce the new
2802 Here is the pattern rule to generate a file of prerequisites (i.e.,
2803 a makefile) called `NAME.d' from a C source file called `NAME.c':
2806 @set -e; rm -f $@; \
2807 $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
2808 sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
2811 *Note Pattern Rules::, for information on defining pattern rules. The
2812 `-e' flag to the shell causes it to exit immediately if the `$(CC)'
2813 command (or any other command) fails (exits with a nonzero status).
2815 With the GNU C compiler, you may wish to use the `-MM' flag instead
2816 of `-M'. This omits prerequisites on system header files. *Note
2817 Options Controlling the Preprocessor: (gcc.info)Preprocessor Options,
2820 The purpose of the `sed' command is to translate (for example):
2822 main.o : main.c defs.h
2826 main.o main.d : main.c defs.h
2828 This makes each `.d' file depend on all the source and header files
2829 that the corresponding `.o' file depends on. `make' then knows it must
2830 regenerate the prerequisites whenever any of the source or header files
2833 Once you've defined the rule to remake the `.d' files, you then use
2834 the `include' directive to read them all in. *Note Include::. For
2837 sources = foo.c bar.c
2839 include $(sources:.c=.d)
2841 (This example uses a substitution variable reference to translate the
2842 list of source files `foo.c bar.c' into a list of prerequisite
2843 makefiles, `foo.d bar.d'. *Note Substitution Refs::, for full
2844 information on substitution references.) Since the `.d' files are
2845 makefiles like any others, `make' will remake them as necessary with no
2846 further work from you. *Note Remaking Makefiles::.
2848 Note that the `.d' files contain target definitions; you should be
2849 sure to place the `include' directive _after_ the first, default goal
2850 in your makefiles or run the risk of having a random object file become
2851 the default goal. *Note How Make Works::.
2854 File: make.info, Node: Recipes, Next: Using Variables, Prev: Rules, Up: Top
2856 5 Writing Recipes in Rules
2857 **************************
2859 The recipe of a rule consists of one or more shell command lines to be
2860 executed, one at a time, in the order they appear. Typically, the
2861 result of executing these commands is that the target of the rule is
2864 Users use many different shell programs, but recipes in makefiles are
2865 always interpreted by `/bin/sh' unless the makefile specifies
2866 otherwise. *Note Recipe Execution: Execution.
2870 * Recipe Syntax:: Recipe syntax features and pitfalls.
2871 * Echoing:: How to control when recipes are echoed.
2872 * Execution:: How recipes are executed.
2873 * Parallel:: How recipes can be executed in parallel.
2874 * Errors:: What happens after a recipe execution error.
2875 * Interrupts:: What happens when a recipe is interrupted.
2876 * Recursion:: Invoking `make' from makefiles.
2877 * Canned Recipes:: Defining canned recipes.
2878 * Empty Recipes:: Defining useful, do-nothing recipes.
2881 File: make.info, Node: Recipe Syntax, Next: Echoing, Prev: Recipes, Up: Recipes
2886 Makefiles have the unusual property that there are really two distinct
2887 syntaxes in one file. Most of the makefile uses `make' syntax (*note
2888 Writing Makefiles: Makefiles.). However, recipes are meant to be
2889 interpreted by the shell and so they are written using shell syntax.
2890 The `make' program does not try to understand shell syntax: it performs
2891 only a very few specific translations on the content of the recipe
2892 before handing it to the shell.
2894 Each line in the recipe must start with a tab (or the first character
2895 in the value of the `.RECIPEPREFIX' variable; *note Special
2896 Variables::), except that the first recipe line may be attached to the
2897 target-and-prerequisites line with a semicolon in between. _Any_ line
2898 in the makefile that begins with a tab and appears in a "rule context"
2899 (that is, after a rule has been started until another rule or variable
2900 definition) will be considered part of a recipe for that rule. Blank
2901 lines and lines of just comments may appear among the recipe lines;
2904 Some consequences of these rules include:
2906 * A blank line that begins with a tab is not blank: it's an empty
2907 recipe (*note Empty Recipes::).
2909 * A comment in a recipe is not a `make' comment; it will be passed
2910 to the shell as-is. Whether the shell treats it as a comment or
2911 not depends on your shell.
2913 * A variable definition in a "rule context" which is indented by a
2914 tab as the first character on the line, will be considered part of
2915 a recipe, not a `make' variable definition, and passed to the
2918 * A conditional expression (`ifdef', `ifeq', etc. *note Syntax of
2919 Conditionals: Conditional Syntax.) in a "rule context" which is
2920 indented by a tab as the first character on the line, will be
2921 considered part of a recipe and be passed to the shell.
2926 * Splitting Lines:: Breaking long recipe lines for readability.
2927 * Variables in Recipes:: Using `make' variables in recipes.
2930 File: make.info, Node: Splitting Lines, Next: Variables in Recipes, Prev: Recipe Syntax, Up: Recipe Syntax
2932 5.1.1 Splitting Recipe Lines
2933 ----------------------------
2935 One of the few ways in which `make' does interpret recipes is checking
2936 for a backslash just before the newline. As in normal makefile syntax,
2937 a single logical recipe line can be split into multiple physical lines
2938 in the makefile by placing a backslash before each newline. A sequence
2939 of lines like this is considered a single recipe line, and one instance
2940 of the shell will be invoked to run it.
2942 However, in contrast to how they are treated in other places in a
2943 makefile, backslash-newline pairs are _not_ removed from the recipe.
2944 Both the backslash and the newline characters are preserved and passed
2945 to the shell. How the backslash-newline is interpreted depends on your
2946 shell. If the first character of the next line after the
2947 backslash-newline is the recipe prefix character (a tab by default;
2948 *note Special Variables::), then that character (and only that
2949 character) is removed. Whitespace is never added to the recipe.
2951 For example, the recipe for the all target in this makefile:
2963 consists of four separate shell commands where the output is:
2970 As a more complex example, this makefile:
2972 all : ; @echo 'hello \
2973 world' ; echo "hello \
2976 will invoke one shell with a command of:
2979 world' ; echo "hello \
2982 which, according to shell quoting rules, will yield the following
2989 Notice how the backslash/newline pair was removed inside the string
2990 quoted with double quotes (`"..."'), but not from the string quoted
2991 with single quotes (`'...''). This is the way the default shell
2992 (`/bin/sh') handles backslash/newline pairs. If you specify a
2993 different shell in your makefiles it may treat them differently.
2995 Sometimes you want to split a long line inside of single quotes, but
2996 you don't want the backslash-newline to appear in the quoted content.
2997 This is often the case when passing scripts to languages such as Perl,
2998 where extraneous backslashes inside the script can change its meaning
2999 or even be a syntax error. One simple way of handling this is to place
3000 the quoted string, or even the entire command, into a `make' variable
3001 then use the variable in the recipe. In this situation the newline
3002 quoting rules for makefiles will be used, and the backslash-newline
3003 will be removed. If we rewrite our example above using this method:
3008 all : ; @echo $(HELLO)
3010 we will get output like this:
3014 If you like, you can also use target-specific variables (*note
3015 Target-specific Variable Values: Target-specific.) to obtain a tighter
3016 correspondence between the variable and the recipe that uses it.
3019 File: make.info, Node: Variables in Recipes, Prev: Splitting Lines, Up: Recipe Syntax
3021 5.1.2 Using Variables in Recipes
3022 --------------------------------
3024 The other way in which `make' processes recipes is by expanding any
3025 variable references in them (*note Basics of Variable References:
3026 Reference.). This occurs after make has finished reading all the
3027 makefiles and the target is determined to be out of date; so, the
3028 recipes for targets which are not rebuilt are never expanded.
3030 Variable and function references in recipes have identical syntax and
3031 semantics to references elsewhere in the makefile. They also have the
3032 same quoting rules: if you want a dollar sign to appear in your recipe,
3033 you must double it (`$$'). For shells like the default shell, that use
3034 dollar signs to introduce variables, it's important to keep clear in
3035 your mind whether the variable you want to reference is a `make'
3036 variable (use a single dollar sign) or a shell variable (use two dollar
3037 signs). For example:
3039 LIST = one two three
3041 for i in $(LIST); do \
3045 results in the following command being passed to the shell:
3047 for i in one two three; do \
3051 which generates the expected result:
3058 File: make.info, Node: Echoing, Next: Execution, Prev: Recipe Syntax, Up: Recipes
3063 Normally `make' prints each line of the recipe before it is executed.
3064 We call this "echoing" because it gives the appearance that you are
3065 typing the lines yourself.
3067 When a line starts with `@', the echoing of that line is suppressed.
3068 The `@' is discarded before the line is passed to the shell. Typically
3069 you would use this for a command whose only effect is to print
3070 something, such as an `echo' command to indicate progress through the
3073 @echo About to make distribution files
3075 When `make' is given the flag `-n' or `--just-print' it only echoes
3076 most recipes, without executing them. *Note Summary of Options:
3077 Options Summary. In this case even the recipe lines starting with `@'
3078 are printed. This flag is useful for finding out which recipes `make'
3079 thinks are necessary without actually doing them.
3081 The `-s' or `--silent' flag to `make' prevents all echoing, as if
3082 all recipes started with `@'. A rule in the makefile for the special
3083 target `.SILENT' without prerequisites has the same effect (*note
3084 Special Built-in Target Names: Special Targets.). `.SILENT' is
3085 essentially obsolete since `@' is more flexible.
3088 File: make.info, Node: Execution, Next: Parallel, Prev: Echoing, Up: Recipes
3090 5.3 Recipe Execution
3091 ====================
3093 When it is time to execute recipes to update a target, they are
3094 executed by invoking a new subshell for each line of the recipe, unless
3095 the `.ONESHELL' special target is in effect (*note Using One Shell: One
3096 Shell.) (In practice, `make' may take shortcuts that do not affect the
3099 *Please note:* this implies that setting shell variables and
3100 invoking shell commands such as `cd' that set a context local to each
3101 process will not affect the following lines in the recipe.(1) If you
3102 want to use `cd' to affect the next statement, put both statements in a
3103 single recipe line. Then `make' will invoke one shell to run the
3104 entire line, and the shell will execute the statements in sequence.
3108 cd $(@D) && gobble $(@F) > ../$@
3110 Here we use the shell AND operator (`&&') so that if the `cd' command
3111 fails, the script will fail without trying to invoke the `gobble'
3112 command in the wrong directory, which could cause problems (in this
3113 case it would certainly cause `../foo' to be truncated, at least).
3117 * One Shell:: One shell for all lines in a recipe
3118 * Choosing the Shell:: How `make' chooses the shell used
3121 ---------- Footnotes ----------
3123 (1) On MS-DOS, the value of current working directory is *global*, so
3124 changing it _will_ affect the following recipe lines on those systems.
3127 File: make.info, Node: One Shell, Next: Choosing the Shell, Prev: Execution, Up: Execution
3129 5.3.1 Using One Shell
3130 ---------------------
3132 Sometimes you would prefer that all the lines in the recipe be passed
3133 to a single invocation of the shell. There are generally two
3134 situations where this is useful: first, it can improve performance in
3135 makefiles where recipes consist of many command lines, by avoiding
3136 extra processes. Second, you might want newlines to be included in
3137 your recipe command (for example perhaps you are using a very different
3138 interpreter as your `SHELL'). If the `.ONESHELL' special target
3139 appears anywhere in the makefile then _all_ recipe lines for each
3140 target will be provided to a single invocation of the shell. Newlines
3141 between recipe lines will be preserved. For example:
3146 gobble $(@F) > ../$@
3148 would now work as expected even though the commands are on different
3151 If `.ONESHELL' is provided, then only the first line of the recipe
3152 will be checked for the special prefix characters (`@', `-', and `+').
3153 Subsequent lines will include the special characters in the recipe line
3154 when the `SHELL' is invoked. If you want your recipe to start with one
3155 of these special characters you'll need to arrange for them to not be
3156 the first characters on the first line, perhaps by adding a comment or
3157 similar. For example, this would be a syntax error in Perl because the
3158 first `@' is removed by make:
3161 SHELL = /usr/bin/perl
3167 However, either of these alternatives would work properly:
3170 SHELL = /usr/bin/perl
3173 # Make sure "@" is not the first character on the first line
3180 SHELL = /usr/bin/perl
3186 As a special feature, if `SHELL' is determined to be a POSIX-style
3187 shell, the special prefix characters in "internal" recipe lines will
3188 _removed_ before the recipe is processed. This feature is intended to
3189 allow existing makefiles to add the `.ONESHELL' special target and
3190 still run properly without extensive modifications. Since the special
3191 prefix characters are not legal at the beginning of a line in a POSIX
3192 shell script this is not a loss in functionality. For example, this
3198 @gobble $(@F) > ../$@
3200 Even with this special feature, however, makefiles with `.ONESHELL'
3201 will behave differently in ways that could be noticeable. For example,
3202 normally if any line in the recipe fails, that causes the rule to fail
3203 and no more recipe lines are processed. Under `.ONESHELL' a failure of
3204 any but the final recipe line will not be noticed by `make'. You can
3205 modify `.SHELLFLAGS' to add the `-e' option to the shell which will
3206 cause any failure anywhere in the command line to cause the shell to
3207 fail, but this could itself cause your recipe to behave differently.
3208 Ultimately you may need to harden your recipe lines to allow them to
3209 work with `.ONESHELL'.
3212 File: make.info, Node: Choosing the Shell, Prev: One Shell, Up: Execution
3214 5.3.2 Choosing the Shell
3215 ------------------------
3217 The program used as the shell is taken from the variable `SHELL'. If
3218 this variable is not set in your makefile, the program `/bin/sh' is
3219 used as the shell. The argument(s) passed to the shell are taken from
3220 the variable `.SHELLFLAGS'. The default value of `.SHELLFLAGS' is `-c'
3221 normally, or `-ec' in POSIX-conforming mode.
3223 Unlike most variables, the variable `SHELL' is never set from the
3224 environment. This is because the `SHELL' environment variable is used
3225 to specify your personal choice of shell program for interactive use.
3226 It would be very bad for personal choices like this to affect the
3227 functioning of makefiles. *Note Variables from the Environment:
3230 Furthermore, when you do set `SHELL' in your makefile that value is
3231 _not_ exported in the environment to recipe lines that `make' invokes.
3232 Instead, the value inherited from the user's environment, if any, is
3233 exported. You can override this behavior by explicitly exporting
3234 `SHELL' (*note Communicating Variables to a Sub-`make':
3235 Variables/Recursion.), forcing it to be passed in the environment to
3238 However, on MS-DOS and MS-Windows the value of `SHELL' in the
3239 environment *is* used, since on those systems most users do not set
3240 this variable, and therefore it is most likely set specifically to be
3241 used by `make'. On MS-DOS, if the setting of `SHELL' is not suitable
3242 for `make', you can set the variable `MAKESHELL' to the shell that
3243 `make' should use; if set it will be used as the shell instead of the
3246 Choosing a Shell in DOS and Windows
3247 ...................................
3249 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3252 On MS-DOS, if `SHELL' is not set, the value of the variable
3253 `COMSPEC' (which is always set) is used instead.
3255 The processing of lines that set the variable `SHELL' in Makefiles
3256 is different on MS-DOS. The stock shell, `command.com', is
3257 ridiculously limited in its functionality and many users of `make' tend
3258 to install a replacement shell. Therefore, on MS-DOS, `make' examines
3259 the value of `SHELL', and changes its behavior based on whether it
3260 points to a Unix-style or DOS-style shell. This allows reasonable
3261 functionality even if `SHELL' points to `command.com'.
3263 If `SHELL' points to a Unix-style shell, `make' on MS-DOS
3264 additionally checks whether that shell can indeed be found; if not, it
3265 ignores the line that sets `SHELL'. In MS-DOS, GNU `make' searches for
3266 the shell in the following places:
3268 1. In the precise place pointed to by the value of `SHELL'. For
3269 example, if the makefile specifies `SHELL = /bin/sh', `make' will
3270 look in the directory `/bin' on the current drive.
3272 2. In the current directory.
3274 3. In each of the directories in the `PATH' variable, in order.
3277 In every directory it examines, `make' will first look for the
3278 specific file (`sh' in the example above). If this is not found, it
3279 will also look in that directory for that file with one of the known
3280 extensions which identify executable files. For example `.exe',
3281 `.com', `.bat', `.btm', `.sh', and some others.
3283 If any of these attempts is successful, the value of `SHELL' will be
3284 set to the full pathname of the shell as found. However, if none of
3285 these is found, the value of `SHELL' will not be changed, and thus the
3286 line that sets it will be effectively ignored. This is so `make' will
3287 only support features specific to a Unix-style shell if such a shell is
3288 actually installed on the system where `make' runs.
3290 Note that this extended search for the shell is limited to the cases
3291 where `SHELL' is set from the Makefile; if it is set in the environment
3292 or command line, you are expected to set it to the full pathname of the
3293 shell, exactly as things are on Unix.
3295 The effect of the above DOS-specific processing is that a Makefile
3296 that contains `SHELL = /bin/sh' (as many Unix makefiles do), will work
3297 on MS-DOS unaltered if you have e.g. `sh.exe' installed in some
3298 directory along your `PATH'.
3301 File: make.info, Node: Parallel, Next: Errors, Prev: Execution, Up: Recipes
3303 5.4 Parallel Execution
3304 ======================
3306 GNU `make' knows how to execute several recipes at once. Normally,
3307 `make' will execute only one recipe at a time, waiting for it to finish
3308 before executing the next. However, the `-j' or `--jobs' option tells
3309 `make' to execute many recipes simultaneously. You can inhibit
3310 parallelism in a particular makefile with the `.NOTPARALLEL'
3311 pseudo-target (*note Special Built-in Target Names: Special Targets.).
3313 On MS-DOS, the `-j' option has no effect, since that system doesn't
3314 support multi-processing.
3316 If the `-j' option is followed by an integer, this is the number of
3317 recipes to execute at once; this is called the number of "job slots".
3318 If there is nothing looking like an integer after the `-j' option,
3319 there is no limit on the number of job slots. The default number of job
3320 slots is one, which means serial execution (one thing at a time).
3322 One unpleasant consequence of running several recipes simultaneously
3323 is that output generated by the recipes appears whenever each recipe
3324 sends it, so messages from different recipes may be interspersed.
3326 Another problem is that two processes cannot both take input from the
3327 same device; so to make sure that only one recipe tries to take input
3328 from the terminal at once, `make' will invalidate the standard input
3329 streams of all but one running recipe. This means that attempting to
3330 read from standard input will usually be a fatal error (a `Broken pipe'
3331 signal) for most child processes if there are several.
3333 It is unpredictable which recipe will have a valid standard input
3334 stream (which will come from the terminal, or wherever you redirect the
3335 standard input of `make'). The first recipe run will always get it
3336 first, and the first recipe started after that one finishes will get it
3339 We will change how this aspect of `make' works if we find a better
3340 alternative. In the mean time, you should not rely on any recipe using
3341 standard input at all if you are using the parallel execution feature;
3342 but if you are not using this feature, then standard input works
3343 normally in all recipes.
3345 Finally, handling recursive `make' invocations raises issues. For
3346 more information on this, see *note Communicating Options to a
3347 Sub-`make': Options/Recursion.
3349 If a recipe fails (is killed by a signal or exits with a nonzero
3350 status), and errors are not ignored for that recipe (*note Errors in
3351 Recipes: Errors.), the remaining recipe lines to remake the same target
3352 will not be run. If a recipe fails and the `-k' or `--keep-going'
3353 option was not given (*note Summary of Options: Options Summary.),
3354 `make' aborts execution. If make terminates for any reason (including
3355 a signal) with child processes running, it waits for them to finish
3356 before actually exiting.
3358 When the system is heavily loaded, you will probably want to run
3359 fewer jobs than when it is lightly loaded. You can use the `-l' option
3360 to tell `make' to limit the number of jobs to run at once, based on the
3361 load average. The `-l' or `--max-load' option is followed by a
3362 floating-point number. For example,
3366 will not let `make' start more than one job if the load average is
3367 above 2.5. The `-l' option with no following number removes the load
3368 limit, if one was given with a previous `-l' option.
3370 More precisely, when `make' goes to start up a job, and it already
3371 has at least one job running, it checks the current load average; if it
3372 is not lower than the limit given with `-l', `make' waits until the load
3373 average goes below that limit, or until all the other jobs finish.
3375 By default, there is no load limit.
3378 File: make.info, Node: Errors, Next: Interrupts, Prev: Parallel, Up: Recipes
3380 5.5 Errors in Recipes
3381 =====================
3383 After each shell invocation returns, `make' looks at its exit status.
3384 If the shell completed successfully (the exit status is zero), the next
3385 line in the recipe is executed in a new shell; after the last line is
3386 finished, the rule is finished.
3388 If there is an error (the exit status is nonzero), `make' gives up on
3389 the current rule, and perhaps on all rules.
3391 Sometimes the failure of a certain recipe line does not indicate a
3392 problem. For example, you may use the `mkdir' command to ensure that a
3393 directory exists. If the directory already exists, `mkdir' will report
3394 an error, but you probably want `make' to continue regardless.
3396 To ignore errors in a recipe line, write a `-' at the beginning of
3397 the line's text (after the initial tab). The `-' is discarded before
3398 the line is passed to the shell for execution.
3405 This causes `make' to continue even if `rm' is unable to remove a file.
3407 When you run `make' with the `-i' or `--ignore-errors' flag, errors
3408 are ignored in all recipes of all rules. A rule in the makefile for
3409 the special target `.IGNORE' has the same effect, if there are no
3410 prerequisites. These ways of ignoring errors are obsolete because `-'
3413 When errors are to be ignored, because of either a `-' or the `-i'
3414 flag, `make' treats an error return just like success, except that it
3415 prints out a message that tells you the status code the shell exited
3416 with, and says that the error has been ignored.
3418 When an error happens that `make' has not been told to ignore, it
3419 implies that the current target cannot be correctly remade, and neither
3420 can any other that depends on it either directly or indirectly. No
3421 further recipes will be executed for these targets, since their
3422 preconditions have not been achieved.
3424 Normally `make' gives up immediately in this circumstance, returning
3425 a nonzero status. However, if the `-k' or `--keep-going' flag is
3426 specified, `make' continues to consider the other prerequisites of the
3427 pending targets, remaking them if necessary, before it gives up and
3428 returns nonzero status. For example, after an error in compiling one
3429 object file, `make -k' will continue compiling other object files even
3430 though it already knows that linking them will be impossible. *Note
3431 Summary of Options: Options Summary.
3433 The usual behavior assumes that your purpose is to get the specified
3434 targets up to date; once `make' learns that this is impossible, it
3435 might as well report the failure immediately. The `-k' option says
3436 that the real purpose is to test as many of the changes made in the
3437 program as possible, perhaps to find several independent problems so
3438 that you can correct them all before the next attempt to compile. This
3439 is why Emacs' `compile' command passes the `-k' flag by default.
3441 Usually when a recipe line fails, if it has changed the target file
3442 at all, the file is corrupted and cannot be used--or at least it is not
3443 completely updated. Yet the file's time stamp says that it is now up to
3444 date, so the next time `make' runs, it will not try to update that
3445 file. The situation is just the same as when the shell is killed by a
3446 signal; *note Interrupts::. So generally the right thing to do is to
3447 delete the target file if the recipe fails after beginning to change
3448 the file. `make' will do this if `.DELETE_ON_ERROR' appears as a
3449 target. This is almost always what you want `make' to do, but it is
3450 not historical practice; so for compatibility, you must explicitly
3454 File: make.info, Node: Interrupts, Next: Recursion, Prev: Errors, Up: Recipes
3456 5.6 Interrupting or Killing `make'
3457 ==================================
3459 If `make' gets a fatal signal while a shell is executing, it may delete
3460 the target file that the recipe was supposed to update. This is done
3461 if the target file's last-modification time has changed since `make'
3464 The purpose of deleting the target is to make sure that it is remade
3465 from scratch when `make' is next run. Why is this? Suppose you type
3466 `Ctrl-c' while a compiler is running, and it has begun to write an
3467 object file `foo.o'. The `Ctrl-c' kills the compiler, resulting in an
3468 incomplete file whose last-modification time is newer than the source
3469 file `foo.c'. But `make' also receives the `Ctrl-c' signal and deletes
3470 this incomplete file. If `make' did not do this, the next invocation
3471 of `make' would think that `foo.o' did not require updating--resulting
3472 in a strange error message from the linker when it tries to link an
3473 object file half of which is missing.
3475 You can prevent the deletion of a target file in this way by making
3476 the special target `.PRECIOUS' depend on it. Before remaking a target,
3477 `make' checks to see whether it appears on the prerequisites of
3478 `.PRECIOUS', and thereby decides whether the target should be deleted
3479 if a signal happens. Some reasons why you might do this are that the
3480 target is updated in some atomic fashion, or exists only to record a
3481 modification-time (its contents do not matter), or must exist at all
3482 times to prevent other sorts of trouble.
3485 File: make.info, Node: Recursion, Next: Canned Recipes, Prev: Interrupts, Up: Recipes
3487 5.7 Recursive Use of `make'
3488 ===========================
3490 Recursive use of `make' means using `make' as a command in a makefile.
3491 This technique is useful when you want separate makefiles for various
3492 subsystems that compose a larger system. For example, suppose you have
3493 a subdirectory `subdir' which has its own makefile, and you would like
3494 the containing directory's makefile to run `make' on the subdirectory.
3495 You can do it by writing this:
3498 cd subdir && $(MAKE)
3500 or, equivalently, this (*note Summary of Options: Options Summary.):
3505 You can write recursive `make' commands just by copying this example,
3506 but there are many things to know about how they work and why, and about
3507 how the sub-`make' relates to the top-level `make'. You may also find
3508 it useful to declare targets that invoke recursive `make' commands as
3509 `.PHONY' (for more discussion on when this is useful, see *note Phony
3512 For your convenience, when GNU `make' starts (after it has processed
3513 any `-C' options) it sets the variable `CURDIR' to the pathname of the
3514 current working directory. This value is never touched by `make'
3515 again: in particular note that if you include files from other
3516 directories the value of `CURDIR' does not change. The value has the
3517 same precedence it would have if it were set in the makefile (by
3518 default, an environment variable `CURDIR' will not override this
3519 value). Note that setting this variable has no impact on the operation
3520 of `make' (it does not cause `make' to change its working directory,
3525 * MAKE Variable:: The special effects of using `$(MAKE)'.
3526 * Variables/Recursion:: How to communicate variables to a sub-`make'.
3527 * Options/Recursion:: How to communicate options to a sub-`make'.
3528 * -w Option:: How the `-w' or `--print-directory' option
3529 helps debug use of recursive `make' commands.
3532 File: make.info, Node: MAKE Variable, Next: Variables/Recursion, Prev: Recursion, Up: Recursion
3534 5.7.1 How the `MAKE' Variable Works
3535 -----------------------------------
3537 Recursive `make' commands should always use the variable `MAKE', not
3538 the explicit command name `make', as shown here:
3541 cd subdir && $(MAKE)
3543 The value of this variable is the file name with which `make' was
3544 invoked. If this file name was `/bin/make', then the recipe executed
3545 is `cd subdir && /bin/make'. If you use a special version of `make' to
3546 run the top-level makefile, the same special version will be executed
3547 for recursive invocations.
3549 As a special feature, using the variable `MAKE' in the recipe of a
3550 rule alters the effects of the `-t' (`--touch'), `-n' (`--just-print'),
3551 or `-q' (`--question') option. Using the `MAKE' variable has the same
3552 effect as using a `+' character at the beginning of the recipe line.
3553 *Note Instead of Executing the Recipes: Instead of Execution. This
3554 special feature is only enabled if the `MAKE' variable appears directly
3555 in the recipe: it does not apply if the `MAKE' variable is referenced
3556 through expansion of another variable. In the latter case you must use
3557 the `+' token to get these special effects.
3559 Consider the command `make -t' in the above example. (The `-t'
3560 option marks targets as up to date without actually running any
3561 recipes; see *note Instead of Execution::.) Following the usual
3562 definition of `-t', a `make -t' command in the example would create a
3563 file named `subsystem' and do nothing else. What you really want it to
3564 do is run `cd subdir && make -t'; but that would require executing the
3565 recipe, and `-t' says not to execute recipes.
3567 The special feature makes this do what you want: whenever a recipe
3568 line of a rule contains the variable `MAKE', the flags `-t', `-n' and
3569 `-q' do not apply to that line. Recipe lines containing `MAKE' are
3570 executed normally despite the presence of a flag that causes most
3571 recipes not to be run. The usual `MAKEFLAGS' mechanism passes the
3572 flags to the sub-`make' (*note Communicating Options to a Sub-`make':
3573 Options/Recursion.), so your request to touch the files, or print the
3574 recipes, is propagated to the subsystem.
3577 File: make.info, Node: Variables/Recursion, Next: Options/Recursion, Prev: MAKE Variable, Up: Recursion
3579 5.7.2 Communicating Variables to a Sub-`make'
3580 ---------------------------------------------
3582 Variable values of the top-level `make' can be passed to the sub-`make'
3583 through the environment by explicit request. These variables are
3584 defined in the sub-`make' as defaults, but do not override what is
3585 specified in the makefile used by the sub-`make' makefile unless you
3586 use the `-e' switch (*note Summary of Options: Options Summary.).
3588 To pass down, or "export", a variable, `make' adds the variable and
3589 its value to the environment for running each line of the recipe. The
3590 sub-`make', in turn, uses the environment to initialize its table of
3591 variable values. *Note Variables from the Environment: Environment.
3593 Except by explicit request, `make' exports a variable only if it is
3594 either defined in the environment initially or set on the command line,
3595 and if its name consists only of letters, numbers, and underscores.
3596 Some shells cannot cope with environment variable names consisting of
3597 characters other than letters, numbers, and underscores.
3599 The value of the `make' variable `SHELL' is not exported. Instead,
3600 the value of the `SHELL' variable from the invoking environment is
3601 passed to the sub-`make'. You can force `make' to export its value for
3602 `SHELL' by using the `export' directive, described below. *Note
3603 Choosing the Shell::.
3605 The special variable `MAKEFLAGS' is always exported (unless you
3606 unexport it). `MAKEFILES' is exported if you set it to anything.
3608 `make' automatically passes down variable values that were defined
3609 on the command line, by putting them in the `MAKEFLAGS' variable.
3610 *Note Options/Recursion::.
3612 Variables are _not_ normally passed down if they were created by
3613 default by `make' (*note Variables Used by Implicit Rules: Implicit
3614 Variables.). The sub-`make' will define these for itself.
3616 If you want to export specific variables to a sub-`make', use the
3617 `export' directive, like this:
3621 If you want to _prevent_ a variable from being exported, use the
3622 `unexport' directive, like this:
3624 unexport VARIABLE ...
3626 In both of these forms, the arguments to `export' and `unexport' are
3627 expanded, and so could be variables or functions which expand to a
3628 (list of) variable names to be (un)exported.
3630 As a convenience, you can define a variable and export it at the same
3633 export VARIABLE = value
3635 has the same result as:
3642 export VARIABLE := value
3644 has the same result as:
3651 export VARIABLE += value
3658 *Note Appending More Text to Variables: Appending.
3660 You may notice that the `export' and `unexport' directives work in
3661 `make' in the same way they work in the shell, `sh'.
3663 If you want all variables to be exported by default, you can use
3668 This tells `make' that variables which are not explicitly mentioned in
3669 an `export' or `unexport' directive should be exported. Any variable
3670 given in an `unexport' directive will still _not_ be exported. If you
3671 use `export' by itself to export variables by default, variables whose
3672 names contain characters other than alphanumerics and underscores will
3673 not be exported unless specifically mentioned in an `export' directive.
3675 The behavior elicited by an `export' directive by itself was the
3676 default in older versions of GNU `make'. If your makefiles depend on
3677 this behavior and you want to be compatible with old versions of
3678 `make', you can write a rule for the special target
3679 `.EXPORT_ALL_VARIABLES' instead of using the `export' directive. This
3680 will be ignored by old `make's, while the `export' directive will cause
3683 Likewise, you can use `unexport' by itself to tell `make' _not_ to
3684 export variables by default. Since this is the default behavior, you
3685 would only need to do this if `export' had been used by itself earlier
3686 (in an included makefile, perhaps). You *cannot* use `export' and
3687 `unexport' by themselves to have variables exported for some recipes
3688 and not for others. The last `export' or `unexport' directive that
3689 appears by itself determines the behavior for the entire run of `make'.
3691 As a special feature, the variable `MAKELEVEL' is changed when it is
3692 passed down from level to level. This variable's value is a string
3693 which is the depth of the level as a decimal number. The value is `0'
3694 for the top-level `make'; `1' for a sub-`make', `2' for a
3695 sub-sub-`make', and so on. The incrementation happens when `make' sets
3696 up the environment for a recipe.
3698 The main use of `MAKELEVEL' is to test it in a conditional directive
3699 (*note Conditional Parts of Makefiles: Conditionals.); this way you can
3700 write a makefile that behaves one way if run recursively and another
3701 way if run directly by you.
3703 You can use the variable `MAKEFILES' to cause all sub-`make'
3704 commands to use additional makefiles. The value of `MAKEFILES' is a
3705 whitespace-separated list of file names. This variable, if defined in
3706 the outer-level makefile, is passed down through the environment; then
3707 it serves as a list of extra makefiles for the sub-`make' to read
3708 before the usual or specified ones. *Note The Variable `MAKEFILES':
3712 File: make.info, Node: Options/Recursion, Next: -w Option, Prev: Variables/Recursion, Up: Recursion
3714 5.7.3 Communicating Options to a Sub-`make'
3715 -------------------------------------------
3717 Flags such as `-s' and `-k' are passed automatically to the sub-`make'
3718 through the variable `MAKEFLAGS'. This variable is set up
3719 automatically by `make' to contain the flag letters that `make'
3720 received. Thus, if you do `make -ks' then `MAKEFLAGS' gets the value
3723 As a consequence, every sub-`make' gets a value for `MAKEFLAGS' in
3724 its environment. In response, it takes the flags from that value and
3725 processes them as if they had been given as arguments. *Note Summary
3726 of Options: Options Summary.
3728 Likewise variables defined on the command line are passed to the
3729 sub-`make' through `MAKEFLAGS'. Words in the value of `MAKEFLAGS' that
3730 contain `=', `make' treats as variable definitions just as if they
3731 appeared on the command line. *Note Overriding Variables: Overriding.
3733 The options `-C', `-f', `-o', and `-W' are not put into `MAKEFLAGS';
3734 these options are not passed down.
3736 The `-j' option is a special case (*note Parallel Execution:
3737 Parallel.). If you set it to some numeric value `N' and your operating
3738 system supports it (most any UNIX system will; others typically won't),
3739 the parent `make' and all the sub-`make's will communicate to ensure
3740 that there are only `N' jobs running at the same time between them all.
3741 Note that any job that is marked recursive (*note Instead of Executing
3742 Recipes: Instead of Execution.) doesn't count against the total jobs
3743 (otherwise we could get `N' sub-`make's running and have no slots left
3744 over for any real work!)
3746 If your operating system doesn't support the above communication,
3747 then `-j 1' is always put into `MAKEFLAGS' instead of the value you
3748 specified. This is because if the `-j' option were passed down to
3749 sub-`make's, you would get many more jobs running in parallel than you
3750 asked for. If you give `-j' with no numeric argument, meaning to run
3751 as many jobs as possible in parallel, this is passed down, since
3752 multiple infinities are no more than one.
3754 If you do not want to pass the other flags down, you must change the
3755 value of `MAKEFLAGS', like this:
3758 cd subdir && $(MAKE) MAKEFLAGS=
3760 The command line variable definitions really appear in the variable
3761 `MAKEOVERRIDES', and `MAKEFLAGS' contains a reference to this variable.
3762 If you do want to pass flags down normally, but don't want to pass down
3763 the command line variable definitions, you can reset `MAKEOVERRIDES' to
3768 This is not usually useful to do. However, some systems have a small
3769 fixed limit on the size of the environment, and putting so much
3770 information into the value of `MAKEFLAGS' can exceed it. If you see
3771 the error message `Arg list too long', this may be the problem. (For
3772 strict compliance with POSIX.2, changing `MAKEOVERRIDES' does not
3773 affect `MAKEFLAGS' if the special target `.POSIX' appears in the
3774 makefile. You probably do not care about this.)
3776 A similar variable `MFLAGS' exists also, for historical
3777 compatibility. It has the same value as `MAKEFLAGS' except that it
3778 does not contain the command line variable definitions, and it always
3779 begins with a hyphen unless it is empty (`MAKEFLAGS' begins with a
3780 hyphen only when it begins with an option that has no single-letter
3781 version, such as `--warn-undefined-variables'). `MFLAGS' was
3782 traditionally used explicitly in the recursive `make' command, like
3786 cd subdir && $(MAKE) $(MFLAGS)
3788 but now `MAKEFLAGS' makes this usage redundant. If you want your
3789 makefiles to be compatible with old `make' programs, use this
3790 technique; it will work fine with more modern `make' versions too.
3792 The `MAKEFLAGS' variable can also be useful if you want to have
3793 certain options, such as `-k' (*note Summary of Options: Options
3794 Summary.), set each time you run `make'. You simply put a value for
3795 `MAKEFLAGS' in your environment. You can also set `MAKEFLAGS' in a
3796 makefile, to specify additional flags that should also be in effect for
3797 that makefile. (Note that you cannot use `MFLAGS' this way. That
3798 variable is set only for compatibility; `make' does not interpret a
3799 value you set for it in any way.)
3801 When `make' interprets the value of `MAKEFLAGS' (either from the
3802 environment or from a makefile), it first prepends a hyphen if the value
3803 does not already begin with one. Then it chops the value into words
3804 separated by blanks, and parses these words as if they were options
3805 given on the command line (except that `-C', `-f', `-h', `-o', `-W',
3806 and their long-named versions are ignored; and there is no error for an
3809 If you do put `MAKEFLAGS' in your environment, you should be sure not
3810 to include any options that will drastically affect the actions of
3811 `make' and undermine the purpose of makefiles and of `make' itself.
3812 For instance, the `-t', `-n', and `-q' options, if put in one of these
3813 variables, could have disastrous consequences and would certainly have
3814 at least surprising and probably annoying effects.
3817 File: make.info, Node: -w Option, Prev: Options/Recursion, Up: Recursion
3819 5.7.4 The `--print-directory' Option
3820 ------------------------------------
3822 If you use several levels of recursive `make' invocations, the `-w' or
3823 `--print-directory' option can make the output a lot easier to
3824 understand by showing each directory as `make' starts processing it and
3825 as `make' finishes processing it. For example, if `make -w' is run in
3826 the directory `/u/gnu/make', `make' will print a line of the form:
3828 make: Entering directory `/u/gnu/make'.
3830 before doing anything else, and a line of the form:
3832 make: Leaving directory `/u/gnu/make'.
3834 when processing is completed.
3836 Normally, you do not need to specify this option because `make' does
3837 it for you: `-w' is turned on automatically when you use the `-C'
3838 option, and in sub-`make's. `make' will not automatically turn on `-w'
3839 if you also use `-s', which says to be silent, or if you use
3840 `--no-print-directory' to explicitly disable it.
3843 File: make.info, Node: Canned Recipes, Next: Empty Recipes, Prev: Recursion, Up: Recipes
3845 5.8 Defining Canned Recipes
3846 ===========================
3848 When the same sequence of commands is useful in making various targets,
3849 you can define it as a canned sequence with the `define' directive, and
3850 refer to the canned sequence from the recipes for those targets. The
3851 canned sequence is actually a variable, so the name must not conflict
3852 with other variable names.
3854 Here is an example of defining a canned recipe:
3857 yacc $(firstword $^)
3861 Here `run-yacc' is the name of the variable being defined; `endef'
3862 marks the end of the definition; the lines in between are the commands.
3863 The `define' directive does not expand variable references and function
3864 calls in the canned sequence; the `$' characters, parentheses, variable
3865 names, and so on, all become part of the value of the variable you are
3866 defining. *Note Defining Multi-Line Variables: Multi-Line, for a
3867 complete explanation of `define'.
3869 The first command in this example runs Yacc on the first
3870 prerequisite of whichever rule uses the canned sequence. The output
3871 file from Yacc is always named `y.tab.c'. The second command moves the
3872 output to the rule's target file name.
3874 To use the canned sequence, substitute the variable into the recipe
3875 of a rule. You can substitute it like any other variable (*note Basics
3876 of Variable References: Reference.). Because variables defined by
3877 `define' are recursively expanded variables, all the variable
3878 references you wrote inside the `define' are expanded now. For example:
3883 `foo.y' will be substituted for the variable `$^' when it occurs in
3884 `run-yacc''s value, and `foo.c' for `$@'.
3886 This is a realistic example, but this particular one is not needed in
3887 practice because `make' has an implicit rule to figure out these
3888 commands based on the file names involved (*note Using Implicit Rules:
3891 In recipe execution, each line of a canned sequence is treated just
3892 as if the line appeared on its own in the rule, preceded by a tab. In
3893 particular, `make' invokes a separate subshell for each line. You can
3894 use the special prefix characters that affect command lines (`@', `-',
3895 and `+') on each line of a canned sequence. *Note Writing Recipes in
3896 Rules: Recipes. For example, using this canned sequence:
3899 @echo "frobnicating target $@"
3900 frob-step-1 $< -o $@-step-1
3901 frob-step-2 $@-step-1 -o $@
3904 `make' will not echo the first line, the `echo' command. But it _will_
3905 echo the following two recipe lines.
3907 On the other hand, prefix characters on the recipe line that refers
3908 to a canned sequence apply to every line in the sequence. So the rule:
3913 does not echo _any_ recipe lines. (*Note Recipe Echoing: Echoing, for
3914 a full explanation of `@'.)
3917 File: make.info, Node: Empty Recipes, Prev: Canned Recipes, Up: Recipes
3919 5.9 Using Empty Recipes
3920 =======================
3922 It is sometimes useful to define recipes which do nothing. This is done
3923 simply by giving a recipe that consists of nothing but whitespace. For
3928 defines an empty recipe for `target'. You could also use a line
3929 beginning with a recipe prefix character to define an empty recipe, but
3930 this would be confusing because such a line looks empty.
3932 You may be wondering why you would want to define a recipe that does
3933 nothing. The only reason this is useful is to prevent a target from
3934 getting implicit recipes (from implicit rules or the `.DEFAULT' special
3935 target; *note Implicit Rules:: and *note Defining Last-Resort Default
3936 Rules: Last Resort.).
3938 You may be inclined to define empty recipes for targets that are not
3939 actual files, but only exist so that their prerequisites can be remade.
3940 However, this is not the best way to do that, because the prerequisites
3941 may not be remade properly if the target file actually does exist.
3942 *Note Phony Targets: Phony Targets, for a better way to do this.
3945 File: make.info, Node: Using Variables, Next: Conditionals, Prev: Recipes, Up: Top
3947 6 How to Use Variables
3948 **********************
3950 A "variable" is a name defined in a makefile to represent a string of
3951 text, called the variable's "value". These values are substituted by
3952 explicit request into targets, prerequisites, recipes, and other parts
3953 of the makefile. (In some other versions of `make', variables are
3956 Variables and functions in all parts of a makefile are expanded when
3957 read, except for in recipes, the right-hand sides of variable
3958 definitions using `=', and the bodies of variable definitions using the
3961 Variables can represent lists of file names, options to pass to
3962 compilers, programs to run, directories to look in for source files,
3963 directories to write output in, or anything else you can imagine.
3965 A variable name may be any sequence of characters not containing `:',
3966 `#', `=', or leading or trailing whitespace. However, variable names
3967 containing characters other than letters, numbers, and underscores
3968 should be avoided, as they may be given special meanings in the future,
3969 and with some shells they cannot be passed through the environment to a
3970 sub-`make' (*note Communicating Variables to a Sub-`make':
3971 Variables/Recursion.).
3973 Variable names are case-sensitive. The names `foo', `FOO', and
3974 `Foo' all refer to different variables.
3976 It is traditional to use upper case letters in variable names, but we
3977 recommend using lower case letters for variable names that serve
3978 internal purposes in the makefile, and reserving upper case for
3979 parameters that control implicit rules or for parameters that the user
3980 should override with command options (*note Overriding Variables:
3983 A few variables have names that are a single punctuation character or
3984 just a few characters. These are the "automatic variables", and they
3985 have particular specialized uses. *Note Automatic Variables::.
3989 * Reference:: How to use the value of a variable.
3990 * Flavors:: Variables come in two flavors.
3991 * Advanced:: Advanced features for referencing a variable.
3992 * Values:: All the ways variables get their values.
3993 * Setting:: How to set a variable in the makefile.
3994 * Appending:: How to append more text to the old value
3996 * Override Directive:: How to set a variable in the makefile even if
3997 the user has set it with a command argument.
3998 * Multi-Line:: An alternate way to set a variable
3999 to a multi-line string.
4000 * Undefine Directive:: How to undefine a variable so that it appears
4001 as if it was never set.
4002 * Environment:: Variable values can come from the environment.
4003 * Target-specific:: Variable values can be defined on a per-target
4005 * Pattern-specific:: Target-specific variable values can be applied
4006 to a group of targets that match a pattern.
4007 * Suppressing Inheritance:: Suppress inheritance of variables.
4008 * Special Variables:: Variables with special meaning or behavior.
4011 File: make.info, Node: Reference, Next: Flavors, Prev: Using Variables, Up: Using Variables
4013 6.1 Basics of Variable References
4014 =================================
4016 To substitute a variable's value, write a dollar sign followed by the
4017 name of the variable in parentheses or braces: either `$(foo)' or
4018 `${foo}' is a valid reference to the variable `foo'. This special
4019 significance of `$' is why you must write `$$' to have the effect of a
4020 single dollar sign in a file name or recipe.
4022 Variable references can be used in any context: targets,
4023 prerequisites, recipes, most directives, and new variable values. Here
4024 is an example of a common case, where a variable holds the names of all
4025 the object files in a program:
4027 objects = program.o foo.o utils.o
4028 program : $(objects)
4029 cc -o program $(objects)
4033 Variable references work by strict textual substitution. Thus, the
4037 prog.o : prog.$(foo)
4038 $(foo)$(foo) -$(foo) prog.$(foo)
4040 could be used to compile a C program `prog.c'. Since spaces before the
4041 variable value are ignored in variable assignments, the value of `foo'
4042 is precisely `c'. (Don't actually write your makefiles this way!)
4044 A dollar sign followed by a character other than a dollar sign,
4045 open-parenthesis or open-brace treats that single character as the
4046 variable name. Thus, you could reference the variable `x' with `$x'.
4047 However, this practice is strongly discouraged, except in the case of
4048 the automatic variables (*note Automatic Variables::).
4051 File: make.info, Node: Flavors, Next: Advanced, Prev: Reference, Up: Using Variables
4053 6.2 The Two Flavors of Variables
4054 ================================
4056 There are two ways that a variable in GNU `make' can have a value; we
4057 call them the two "flavors" of variables. The two flavors are
4058 distinguished in how they are defined and in what they do when expanded.
4060 The first flavor of variable is a "recursively expanded" variable.
4061 Variables of this sort are defined by lines using `=' (*note Setting
4062 Variables: Setting.) or by the `define' directive (*note Defining
4063 Multi-Line Variables: Multi-Line.). The value you specify is installed
4064 verbatim; if it contains references to other variables, these
4065 references are expanded whenever this variable is substituted (in the
4066 course of expanding some other string). When this happens, it is
4067 called "recursive expansion".
4077 will echo `Huh?': `$(foo)' expands to `$(bar)' which expands to
4078 `$(ugh)' which finally expands to `Huh?'.
4080 This flavor of variable is the only sort supported by other versions
4081 of `make'. It has its advantages and its disadvantages. An advantage
4082 (most would say) is that:
4084 CFLAGS = $(include_dirs) -O
4085 include_dirs = -Ifoo -Ibar
4087 will do what was intended: when `CFLAGS' is expanded in a recipe, it
4088 will expand to `-Ifoo -Ibar -O'. A major disadvantage is that you
4089 cannot append something on the end of a variable, as in
4091 CFLAGS = $(CFLAGS) -O
4093 because it will cause an infinite loop in the variable expansion.
4094 (Actually `make' detects the infinite loop and reports an error.)
4096 Another disadvantage is that any functions (*note Functions for
4097 Transforming Text: Functions.) referenced in the definition will be
4098 executed every time the variable is expanded. This makes `make' run
4099 slower; worse, it causes the `wildcard' and `shell' functions to give
4100 unpredictable results because you cannot easily control when they are
4101 called, or even how many times.
4103 To avoid all the problems and inconveniences of recursively expanded
4104 variables, there is another flavor: simply expanded variables.
4106 "Simply expanded variables" are defined by lines using `:=' (*note
4107 Setting Variables: Setting.). The value of a simply expanded variable
4108 is scanned once and for all, expanding any references to other
4109 variables and functions, when the variable is defined. The actual
4110 value of the simply expanded variable is the result of expanding the
4111 text that you write. It does not contain any references to other
4112 variables; it contains their values _as of the time this variable was
4113 defined_. Therefore,
4124 When a simply expanded variable is referenced, its value is
4125 substituted verbatim.
4127 Here is a somewhat more complicated example, illustrating the use of
4128 `:=' in conjunction with the `shell' function. (*Note The `shell'
4129 Function: Shell Function.) This example also shows use of the variable
4130 `MAKELEVEL', which is changed when it is passed down from level to
4131 level. (*Note Communicating Variables to a Sub-`make':
4132 Variables/Recursion, for information about `MAKELEVEL'.)
4134 ifeq (0,${MAKELEVEL})
4135 whoami := $(shell whoami)
4136 host-type := $(shell arch)
4137 MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
4140 An advantage of this use of `:=' is that a typical `descend into a
4141 directory' recipe then looks like this:
4146 Simply expanded variables generally make complicated makefile
4147 programming more predictable because they work like variables in most
4148 programming languages. They allow you to redefine a variable using its
4149 own value (or its value processed in some way by one of the expansion
4150 functions) and to use the expansion functions much more efficiently
4151 (*note Functions for Transforming Text: Functions.).
4153 You can also use them to introduce controlled leading whitespace into
4154 variable values. Leading whitespace characters are discarded from your
4155 input before substitution of variable references and function calls;
4156 this means you can include leading spaces in a variable value by
4157 protecting them with variable references, like this:
4160 space := $(nullstring) # end of the line
4162 Here the value of the variable `space' is precisely one space. The
4163 comment `# end of the line' is included here just for clarity. Since
4164 trailing space characters are _not_ stripped from variable values, just
4165 a space at the end of the line would have the same effect (but be
4166 rather hard to read). If you put whitespace at the end of a variable
4167 value, it is a good idea to put a comment like that at the end of the
4168 line to make your intent clear. Conversely, if you do _not_ want any
4169 whitespace characters at the end of your variable value, you must
4170 remember not to put a random comment on the end of the line after some
4171 whitespace, such as this:
4173 dir := /foo/bar # directory to put the frobs in
4175 Here the value of the variable `dir' is `/foo/bar ' (with four
4176 trailing spaces), which was probably not the intention. (Imagine
4177 something like `$(dir)/file' with this definition!)
4179 There is another assignment operator for variables, `?='. This is
4180 called a conditional variable assignment operator, because it only has
4181 an effect if the variable is not yet defined. This statement:
4185 is exactly equivalent to this (*note The `origin' Function: Origin
4188 ifeq ($(origin FOO), undefined)
4192 Note that a variable set to an empty value is still defined, so `?='
4193 will not set that variable.
4196 File: make.info, Node: Advanced, Next: Values, Prev: Flavors, Up: Using Variables
4198 6.3 Advanced Features for Reference to Variables
4199 ================================================
4201 This section describes some advanced features you can use to reference
4202 variables in more flexible ways.
4206 * Substitution Refs:: Referencing a variable with
4207 substitutions on the value.
4208 * Computed Names:: Computing the name of the variable to refer to.
4211 File: make.info, Node: Substitution Refs, Next: Computed Names, Prev: Advanced, Up: Advanced
4213 6.3.1 Substitution References
4214 -----------------------------
4216 A "substitution reference" substitutes the value of a variable with
4217 alterations that you specify. It has the form `$(VAR:A=B)' (or
4218 `${VAR:A=B}') and its meaning is to take the value of the variable VAR,
4219 replace every A at the end of a word with B in that value, and
4220 substitute the resulting string.
4222 When we say "at the end of a word", we mean that A must appear
4223 either followed by whitespace or at the end of the value in order to be
4224 replaced; other occurrences of A in the value are unaltered. For
4230 sets `bar' to `a.c b.c c.c'. *Note Setting Variables: Setting.
4232 A substitution reference is actually an abbreviation for use of the
4233 `patsubst' expansion function (*note Functions for String Substitution
4234 and Analysis: Text Functions.). We provide substitution references as
4235 well as `patsubst' for compatibility with other implementations of
4238 Another type of substitution reference lets you use the full power of
4239 the `patsubst' function. It has the same form `$(VAR:A=B)' described
4240 above, except that now A must contain a single `%' character. This
4241 case is equivalent to `$(patsubst A,B,$(VAR))'. *Note Functions for
4242 String Substitution and Analysis: Text Functions, for a description of
4243 the `patsubst' function.
4248 bar := $(foo:%.o=%.c)
4250 sets `bar' to `a.c b.c c.c'.
4253 File: make.info, Node: Computed Names, Prev: Substitution Refs, Up: Advanced
4255 6.3.2 Computed Variable Names
4256 -----------------------------
4258 Computed variable names are a complicated concept needed only for
4259 sophisticated makefile programming. For most purposes you need not
4260 consider them, except to know that making a variable with a dollar sign
4261 in its name might have strange results. However, if you are the type
4262 that wants to understand everything, or you are actually interested in
4263 what they do, read on.
4265 Variables may be referenced inside the name of a variable. This is
4266 called a "computed variable name" or a "nested variable reference".
4273 defines `a' as `z': the `$(x)' inside `$($(x))' expands to `y', so
4274 `$($(x))' expands to `$(y)' which in turn expands to `z'. Here the
4275 name of the variable to reference is not stated explicitly; it is
4276 computed by expansion of `$(x)'. The reference `$(x)' here is nested
4277 within the outer variable reference.
4279 The previous example shows two levels of nesting, but any number of
4280 levels is possible. For example, here are three levels:
4287 Here the innermost `$(x)' expands to `y', so `$($(x))' expands to
4288 `$(y)' which in turn expands to `z'; now we have `$(z)', which becomes
4291 References to recursively-expanded variables within a variable name
4292 are reexpanded in the usual fashion. For example:
4299 defines `a' as `Hello': `$($(x))' becomes `$($(y))' which becomes
4300 `$(z)' which becomes `Hello'.
4302 Nested variable references can also contain modified references and
4303 function invocations (*note Functions for Transforming Text:
4304 Functions.), just like any other reference. For example, using the
4305 `subst' function (*note Functions for String Substitution and Analysis:
4310 y = $(subst 1,2,$(x))
4314 eventually defines `a' as `Hello'. It is doubtful that anyone would
4315 ever want to write a nested reference as convoluted as this one, but it
4316 works: `$($($(z)))' expands to `$($(y))' which becomes `$($(subst
4317 1,2,$(x)))'. This gets the value `variable1' from `x' and changes it
4318 by substitution to `variable2', so that the entire string becomes
4319 `$(variable2)', a simple variable reference whose value is `Hello'.
4321 A computed variable name need not consist entirely of a single
4322 variable reference. It can contain several variable references, as
4323 well as some invariant text. For example,
4328 a_files := filea fileb
4329 1_files := file1 file2
4331 ifeq "$(use_a)" "yes"
4337 ifeq "$(use_dirs)" "yes"
4343 dirs := $($(a1)_$(df))
4345 will give `dirs' the same value as `a_dirs', `1_dirs', `a_files' or
4346 `1_files' depending on the settings of `use_a' and `use_dirs'.
4348 Computed variable names can also be used in substitution references:
4350 a_objects := a.o b.o c.o
4351 1_objects := 1.o 2.o 3.o
4353 sources := $($(a1)_objects:.o=.c)
4355 defines `sources' as either `a.c b.c c.c' or `1.c 2.c 3.c', depending
4356 on the value of `a1'.
4358 The only restriction on this sort of use of nested variable
4359 references is that they cannot specify part of the name of a function
4360 to be called. This is because the test for a recognized function name
4361 is done before the expansion of nested references. For example,
4371 foo := $($(func) $(bar))
4373 attempts to give `foo' the value of the variable `sort a d b g q c' or
4374 `strip a d b g q c', rather than giving `a d b g q c' as the argument
4375 to either the `sort' or the `strip' function. This restriction could
4376 be removed in the future if that change is shown to be a good idea.
4378 You can also use computed variable names in the left-hand side of a
4379 variable assignment, or in a `define' directive, as in:
4382 $(dir)_sources := $(wildcard $(dir)/*.c)
4383 define $(dir)_print =
4384 lpr $($(dir)_sources)
4387 This example defines the variables `dir', `foo_sources', and
4390 Note that "nested variable references" are quite different from
4391 "recursively expanded variables" (*note The Two Flavors of Variables:
4392 Flavors.), though both are used together in complex ways when doing
4393 makefile programming.
4396 File: make.info, Node: Values, Next: Setting, Prev: Advanced, Up: Using Variables
4398 6.4 How Variables Get Their Values
4399 ==================================
4401 Variables can get values in several different ways:
4403 * You can specify an overriding value when you run `make'. *Note
4404 Overriding Variables: Overriding.
4406 * You can specify a value in the makefile, either with an assignment
4407 (*note Setting Variables: Setting.) or with a verbatim definition
4408 (*note Defining Multi-Line Variables: Multi-Line.).
4410 * Variables in the environment become `make' variables. *Note
4411 Variables from the Environment: Environment.
4413 * Several "automatic" variables are given new values for each rule.
4414 Each of these has a single conventional use. *Note Automatic
4417 * Several variables have constant initial values. *Note Variables
4418 Used by Implicit Rules: Implicit Variables.
4421 File: make.info, Node: Setting, Next: Appending, Prev: Values, Up: Using Variables
4423 6.5 Setting Variables
4424 =====================
4426 To set a variable from the makefile, write a line starting with the
4427 variable name followed by `=' or `:='. Whatever follows the `=' or
4428 `:=' on the line becomes the value. For example,
4430 objects = main.o foo.o bar.o utils.o
4432 defines a variable named `objects'. Whitespace around the variable
4433 name and immediately after the `=' is ignored.
4435 Variables defined with `=' are "recursively expanded" variables.
4436 Variables defined with `:=' are "simply expanded" variables; these
4437 definitions can contain variable references which will be expanded
4438 before the definition is made. *Note The Two Flavors of Variables:
4441 The variable name may contain function and variable references, which
4442 are expanded when the line is read to find the actual variable name to
4445 There is no limit on the length of the value of a variable except the
4446 amount of swapping space on the computer. When a variable definition is
4447 long, it is a good idea to break it into several lines by inserting
4448 backslash-newline at convenient places in the definition. This will not
4449 affect the functioning of `make', but it will make the makefile easier
4452 Most variable names are considered to have the empty string as a
4453 value if you have never set them. Several variables have built-in
4454 initial values that are not empty, but you can set them in the usual
4455 ways (*note Variables Used by Implicit Rules: Implicit Variables.).
4456 Several special variables are set automatically to a new value for each
4457 rule; these are called the "automatic" variables (*note Automatic
4460 If you'd like a variable to be set to a value only if it's not
4461 already set, then you can use the shorthand operator `?=' instead of
4462 `='. These two settings of the variable `FOO' are identical (*note The
4463 `origin' Function: Origin Function.):
4469 ifeq ($(origin FOO), undefined)
4474 File: make.info, Node: Appending, Next: Override Directive, Prev: Setting, Up: Using Variables
4476 6.6 Appending More Text to Variables
4477 ====================================
4479 Often it is useful to add more text to the value of a variable already
4480 defined. You do this with a line containing `+=', like this:
4482 objects += another.o
4484 This takes the value of the variable `objects', and adds the text
4485 `another.o' to it (preceded by a single space). Thus:
4487 objects = main.o foo.o bar.o utils.o
4488 objects += another.o
4490 sets `objects' to `main.o foo.o bar.o utils.o another.o'.
4492 Using `+=' is similar to:
4494 objects = main.o foo.o bar.o utils.o
4495 objects := $(objects) another.o
4497 but differs in ways that become important when you use more complex
4500 When the variable in question has not been defined before, `+=' acts
4501 just like normal `=': it defines a recursively-expanded variable.
4502 However, when there _is_ a previous definition, exactly what `+=' does
4503 depends on what flavor of variable you defined originally. *Note The
4504 Two Flavors of Variables: Flavors, for an explanation of the two
4505 flavors of variables.
4507 When you add to a variable's value with `+=', `make' acts
4508 essentially as if you had included the extra text in the initial
4509 definition of the variable. If you defined it first with `:=', making
4510 it a simply-expanded variable, `+=' adds to that simply-expanded
4511 definition, and expands the new text before appending it to the old
4512 value just as `:=' does (see *note Setting Variables: Setting, for a
4513 full explanation of `:='). In fact,
4518 is exactly equivalent to:
4522 variable := $(variable) more
4524 On the other hand, when you use `+=' with a variable that you defined
4525 first to be recursively-expanded using plain `=', `make' does something
4526 a bit different. Recall that when you define a recursively-expanded
4527 variable, `make' does not expand the value you set for variable and
4528 function references immediately. Instead it stores the text verbatim,
4529 and saves these variable and function references to be expanded later,
4530 when you refer to the new variable (*note The Two Flavors of Variables:
4531 Flavors.). When you use `+=' on a recursively-expanded variable, it is
4532 this unexpanded text to which `make' appends the new text you specify.
4537 is roughly equivalent to:
4540 variable = $(temp) more
4542 except that of course it never defines a variable called `temp'. The
4543 importance of this comes when the variable's old value contains
4544 variable references. Take this common example:
4546 CFLAGS = $(includes) -O
4548 CFLAGS += -pg # enable profiling
4550 The first line defines the `CFLAGS' variable with a reference to another
4551 variable, `includes'. (`CFLAGS' is used by the rules for C
4552 compilation; *note Catalogue of Implicit Rules: Catalogue of Rules.)
4553 Using `=' for the definition makes `CFLAGS' a recursively-expanded
4554 variable, meaning `$(includes) -O' is _not_ expanded when `make'
4555 processes the definition of `CFLAGS'. Thus, `includes' need not be
4556 defined yet for its value to take effect. It only has to be defined
4557 before any reference to `CFLAGS'. If we tried to append to the value
4558 of `CFLAGS' without using `+=', we might do it like this:
4560 CFLAGS := $(CFLAGS) -pg # enable profiling
4562 This is pretty close, but not quite what we want. Using `:=' redefines
4563 `CFLAGS' as a simply-expanded variable; this means `make' expands the
4564 text `$(CFLAGS) -pg' before setting the variable. If `includes' is not
4565 yet defined, we get ` -O -pg', and a later definition of `includes'
4566 will have no effect. Conversely, by using `+=' we set `CFLAGS' to the
4567 _unexpanded_ value `$(includes) -O -pg'. Thus we preserve the
4568 reference to `includes', so if that variable gets defined at any later
4569 point, a reference like `$(CFLAGS)' still uses its value.
4572 File: make.info, Node: Override Directive, Next: Multi-Line, Prev: Appending, Up: Using Variables
4574 6.7 The `override' Directive
4575 ============================
4577 If a variable has been set with a command argument (*note Overriding
4578 Variables: Overriding.), then ordinary assignments in the makefile are
4579 ignored. If you want to set the variable in the makefile even though
4580 it was set with a command argument, you can use an `override'
4581 directive, which is a line that looks like this:
4583 override VARIABLE = VALUE
4587 override VARIABLE := VALUE
4589 To append more text to a variable defined on the command line, use:
4591 override VARIABLE += MORE TEXT
4593 *Note Appending More Text to Variables: Appending.
4595 Variable assignments marked with the `override' flag have a higher
4596 priority than all other assignments, except another `override'.
4597 Subsequent assignments or appends to this variable which are not marked
4598 `override' will be ignored.
4600 The `override' directive was not invented for escalation in the war
4601 between makefiles and command arguments. It was invented so you can
4602 alter and add to values that the user specifies with command arguments.
4604 For example, suppose you always want the `-g' switch when you run the
4605 C compiler, but you would like to allow the user to specify the other
4606 switches with a command argument just as usual. You could use this
4607 `override' directive:
4609 override CFLAGS += -g
4611 You can also use `override' directives with `define' directives.
4612 This is done as you might expect:
4614 override define foo =
4618 *Note Defining Multi-Line Variables: Multi-Line.
4621 File: make.info, Node: Multi-Line, Next: Undefine Directive, Prev: Override Directive, Up: Using Variables
4623 6.8 Defining Multi-Line Variables
4624 =================================
4626 Another way to set the value of a variable is to use the `define'
4627 directive. This directive has an unusual syntax which allows newline
4628 characters to be included in the value, which is convenient for
4629 defining both canned sequences of commands (*note Defining Canned
4630 Recipes: Canned Recipes.), and also sections of makefile syntax to use
4631 with `eval' (*note Eval Function::).
4633 The `define' directive is followed on the same line by the name of
4634 the variable being defined and an (optional) assignment operator, and
4635 nothing more. The value to give the variable appears on the following
4636 lines. The end of the value is marked by a line containing just the
4637 word `endef'. Aside from this difference in syntax, `define' works
4638 just like any other variable definition. The variable name may contain
4639 function and variable references, which are expanded when the directive
4640 is read to find the actual variable name to use.
4642 You may omit the variable assignment operator if you prefer. If
4643 omitted, `make' assumes it to be `=' and creates a recursively-expanded
4644 variable (*note The Two Flavors of Variables: Flavors.). When using a
4645 `+=' operator, the value is appended to the previous value as with any
4646 other append operation: with a single space separating the old and new
4649 You may nest `define' directives: `make' will keep track of nested
4650 directives and report an error if they are not all properly closed with
4651 `endef'. Note that lines beginning with the recipe prefix character
4652 are considered part of a recipe, so any `define' or `endef' strings
4653 appearing on such a line will not be considered `make' directives.
4660 The value in an ordinary assignment cannot contain a newline; but the
4661 newlines that separate the lines of the value in a `define' become part
4662 of the variable's value (except for the final newline which precedes
4663 the `endef' and is not considered part of the value).
4665 When used in a recipe, the previous example is functionally
4668 two-lines = echo foo; echo $(bar)
4670 since two commands separated by semicolon behave much like two separate
4671 shell commands. However, note that using two separate lines means
4672 `make' will invoke the shell twice, running an independent subshell for
4673 each line. *Note Recipe Execution: Execution.
4675 If you want variable definitions made with `define' to take
4676 precedence over command-line variable definitions, you can use the
4677 `override' directive together with `define':
4679 override define two-lines =
4684 *Note The `override' Directive: Override Directive.
4687 File: make.info, Node: Undefine Directive, Next: Environment, Prev: Multi-Line, Up: Using Variables
4689 6.9 Undefining Variables
4690 ========================
4692 If you want to clear a variable, setting its value to empty is usually
4693 sufficient. Expanding such a variable will yield the same result (empty
4694 string) regardless of whether it was set or not. However, if you are
4695 using the `flavor' (*note Flavor Function::) and `origin' (*note Origin
4696 Function::) functions, there is a difference between a variable that
4697 was never set and a variable with an empty value. In such situations
4698 you may want to use the `undefine' directive to make a variable appear
4699 as if it was never set. For example:
4707 $(info $(origin foo))
4708 $(info $(flavor bar))
4710 This example will print "undefined" for both variables.
4712 If you want to undefine a command-line variable definition, you can
4713 use the `override' directive together with `undefine', similar to how
4714 this is done for variable definitions:
4716 override undefine CFLAGS
4719 File: make.info, Node: Environment, Next: Target-specific, Prev: Undefine Directive, Up: Using Variables
4721 6.10 Variables from the Environment
4722 ===================================
4724 Variables in `make' can come from the environment in which `make' is
4725 run. Every environment variable that `make' sees when it starts up is
4726 transformed into a `make' variable with the same name and value.
4727 However, an explicit assignment in the makefile, or with a command
4728 argument, overrides the environment. (If the `-e' flag is specified,
4729 then values from the environment override assignments in the makefile.
4730 *Note Summary of Options: Options Summary. But this is not recommended
4733 Thus, by setting the variable `CFLAGS' in your environment, you can
4734 cause all C compilations in most makefiles to use the compiler switches
4735 you prefer. This is safe for variables with standard or conventional
4736 meanings because you know that no makefile will use them for other
4737 things. (Note this is not totally reliable; some makefiles set
4738 `CFLAGS' explicitly and therefore are not affected by the value in the
4741 When `make' runs a recipe, variables defined in the makefile are
4742 placed into the environment of each shell. This allows you to pass
4743 values to sub-`make' invocations (*note Recursive Use of `make':
4744 Recursion.). By default, only variables that came from the environment
4745 or the command line are passed to recursive invocations. You can use
4746 the `export' directive to pass other variables. *Note Communicating
4747 Variables to a Sub-`make': Variables/Recursion, for full details.
4749 Other use of variables from the environment is not recommended. It
4750 is not wise for makefiles to depend for their functioning on
4751 environment variables set up outside their control, since this would
4752 cause different users to get different results from the same makefile.
4753 This is against the whole purpose of most makefiles.
4755 Such problems would be especially likely with the variable `SHELL',
4756 which is normally present in the environment to specify the user's
4757 choice of interactive shell. It would be very undesirable for this
4758 choice to affect `make'; so, `make' handles the `SHELL' environment
4759 variable in a special way; see *note Choosing the Shell::.
4762 File: make.info, Node: Target-specific, Next: Pattern-specific, Prev: Environment, Up: Using Variables
4764 6.11 Target-specific Variable Values
4765 ====================================
4767 Variable values in `make' are usually global; that is, they are the
4768 same regardless of where they are evaluated (unless they're reset, of
4769 course). One exception to that is automatic variables (*note Automatic
4772 The other exception is "target-specific variable values". This
4773 feature allows you to define different values for the same variable,
4774 based on the target that `make' is currently building. As with
4775 automatic variables, these values are only available within the context
4776 of a target's recipe (and in other target-specific assignments).
4778 Set a target-specific variable value like this:
4780 TARGET ... : VARIABLE-ASSIGNMENT
4782 Target-specific variable assignments can be prefixed with any or all
4783 of the special keywords `export', `override', or `private'; these apply
4784 their normal behavior to this instance of the variable only.
4786 Multiple TARGET values create a target-specific variable value for
4787 each member of the target list individually.
4789 The VARIABLE-ASSIGNMENT can be any valid form of assignment;
4790 recursive (`='), static (`:='), appending (`+='), or conditional
4791 (`?='). All variables that appear within the VARIABLE-ASSIGNMENT are
4792 evaluated within the context of the target: thus, any
4793 previously-defined target-specific variable values will be in effect.
4794 Note that this variable is actually distinct from any "global" value:
4795 the two variables do not have to have the same flavor (recursive vs.
4798 Target-specific variables have the same priority as any other
4799 makefile variable. Variables provided on the command line (and in the
4800 environment if the `-e' option is in force) will take precedence.
4801 Specifying the `override' directive will allow the target-specific
4802 variable value to be preferred.
4804 There is one more special feature of target-specific variables: when
4805 you define a target-specific variable that variable value is also in
4806 effect for all prerequisites of this target, and all their
4807 prerequisites, etc. (unless those prerequisites override that variable
4808 with their own target-specific variable value). So, for example, a
4809 statement like this:
4812 prog : prog.o foo.o bar.o
4814 will set `CFLAGS' to `-g' in the recipe for `prog', but it will also
4815 set `CFLAGS' to `-g' in the recipes that create `prog.o', `foo.o', and
4816 `bar.o', and any recipes which create their prerequisites.
4818 Be aware that a given prerequisite will only be built once per
4819 invocation of make, at most. If the same file is a prerequisite of
4820 multiple targets, and each of those targets has a different value for
4821 the same target-specific variable, then the first target to be built
4822 will cause that prerequisite to be built and the prerequisite will
4823 inherit the target-specific value from the first target. It will
4824 ignore the target-specific values from any other targets.
4827 File: make.info, Node: Pattern-specific, Next: Suppressing Inheritance, Prev: Target-specific, Up: Using Variables
4829 6.12 Pattern-specific Variable Values
4830 =====================================
4832 In addition to target-specific variable values (*note Target-specific
4833 Variable Values: Target-specific.), GNU `make' supports
4834 pattern-specific variable values. In this form, the variable is
4835 defined for any target that matches the pattern specified.
4837 Set a pattern-specific variable value like this:
4839 PATTERN ... : VARIABLE-ASSIGNMENT
4840 where PATTERN is a %-pattern. As with target-specific variable
4841 values, multiple PATTERN values create a pattern-specific variable
4842 value for each pattern individually. The VARIABLE-ASSIGNMENT can be
4843 any valid form of assignment. Any command line variable setting will
4844 take precedence, unless `override' is specified.
4850 will assign `CFLAGS' the value of `-O' for all targets matching the
4853 If a target matches more than one pattern, the matching
4854 pattern-specific variables with longer stems are interpreted first.
4855 This results in more specific variables taking precedence over the more
4856 generic ones, for example:
4859 $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
4861 lib/%.o: CFLAGS := -fPIC -g
4864 all: foo.o lib/bar.o
4866 In this example the first definition of the `CFLAGS' variable will
4867 be used to update `lib/bar.o' even though the second one also applies
4868 to this target. Pattern-specific variables which result in the same
4869 stem length are considered in the order in which they were defined in
4872 Pattern-specific variables are searched after any target-specific
4873 variables defined explicitly for that target, and before target-specific
4874 variables defined for the parent target.
4877 File: make.info, Node: Suppressing Inheritance, Next: Special Variables, Prev: Pattern-specific, Up: Using Variables
4879 6.13 Suppressing Inheritance
4880 ============================
4882 As described in previous sections, `make' variables are inherited by
4883 prerequisites. This capability allows you to modify the behavior of a
4884 prerequisite based on which targets caused it to be rebuilt. For
4885 example, you might set a target-specific variable on a `debug' target,
4886 then running `make debug' will cause that variable to be inherited by
4887 all prerequisites of `debug', while just running `make all' (for
4888 example) would not have that assignment.
4890 Sometimes, however, you may not want a variable to be inherited. For
4891 these situations, `make' provides the `private' modifier. Although
4892 this modifier can be used with any variable assignment, it makes the
4893 most sense with target- and pattern-specific variables. Any variable
4894 marked `private' will be visible to its local target but will not be
4895 inherited by prerequisites of that target. A global variable marked
4896 `private' will be visible in the global scope but will not be inherited
4897 by any target, and hence will not be visible in any recipe.
4899 As an example, consider this makefile:
4902 prog: private EXTRA_CFLAGS = -L/usr/local/lib
4905 Due to the `private' modifier, `a.o' and `b.o' will not inherit the
4906 `EXTRA_CFLAGS' variable assignment from the `progs' target.
4909 File: make.info, Node: Special Variables, Prev: Suppressing Inheritance, Up: Using Variables
4911 6.14 Other Special Variables
4912 ============================
4914 GNU `make' supports some variables that have special properties.
4917 Contains the name of each makefile that is parsed by `make', in
4918 the order in which it was parsed. The name is appended just
4919 before `make' begins to parse the makefile. Thus, if the first
4920 thing a makefile does is examine the last word in this variable, it
4921 will be the name of the current makefile. Once the current
4922 makefile has used `include', however, the last word will be the
4923 just-included makefile.
4925 If a makefile named `Makefile' has this content:
4927 name1 := $(lastword $(MAKEFILE_LIST))
4931 name2 := $(lastword $(MAKEFILE_LIST))
4934 @echo name1 = $(name1)
4935 @echo name2 = $(name2)
4937 then you would expect to see this output:
4943 Sets the default goal to be used if no targets were specified on
4944 the command line (*note Arguments to Specify the Goals: Goals.).
4945 The `.DEFAULT_GOAL' variable allows you to discover the current
4946 default goal, restart the default goal selection algorithm by
4947 clearing its value, or to explicitly set the default goal. The
4948 following example illustrates these cases:
4950 # Query the default goal.
4951 ifeq ($(.DEFAULT_GOAL),)
4952 $(warning no default goal is set)
4958 $(warning default goal is $(.DEFAULT_GOAL))
4960 # Reset the default goal.
4966 $(warning default goal is $(.DEFAULT_GOAL))
4969 .DEFAULT_GOAL := foo
4971 This makefile prints:
4973 no default goal is set
4978 Note that assigning more than one target name to `.DEFAULT_GOAL' is
4979 illegal and will result in an error.
4982 This variable is set only if this instance of `make' has restarted
4983 (*note How Makefiles Are Remade: Remaking Makefiles.): it will
4984 contain the number of times this instance has restarted. Note
4985 this is not the same as recursion (counted by the `MAKELEVEL'
4986 variable). You should not set, modify, or export this variable.
4989 The first character of the value of this variable is used as the
4990 character make assumes is introducing a recipe line. If the
4991 variable is empty (as it is by default) that character is the
4992 standard tab character. For example, this is a valid makefile:
4996 > @echo Hello, world
4998 The value of `.RECIPEPREFIX' can be changed multiple times; once
4999 set it stays in effect for all rules parsed until it is modified.
5002 Expands to a list of the _names_ of all global variables defined
5003 so far. This includes variables which have empty values, as well
5004 as built-in variables (*note Variables Used by Implicit Rules:
5005 Implicit Variables.), but does not include any variables which are
5006 only defined in a target-specific context. Note that any value
5007 you assign to this variable will be ignored; it will always return
5011 Expands to a list of special features supported by this version of
5012 `make'. Possible values include:
5015 Supports `ar' (archive) files using special filename syntax.
5016 *Note Using `make' to Update Archive Files: Archives.
5019 Supports the `-L' (`--check-symlink-times') flag. *Note
5020 Summary of Options: Options Summary.
5023 Supports "else if" non-nested conditionals. *Note Syntax of
5024 Conditionals: Conditional Syntax.
5027 Supports "job server" enhanced parallel builds. *Note
5028 Parallel Execution: Parallel.
5031 Supports secondary expansion of prerequisite lists.
5034 Supports order-only prerequisites. *Note Types of
5035 Prerequisites: Prerequisite Types.
5038 Supports target-specific and pattern-specific variable
5039 assignments. *Note Target-specific Variable Values:
5044 Expands to a list of directories that `make' searches for included
5045 makefiles (*note Including Other Makefiles: Include.).
5049 File: make.info, Node: Conditionals, Next: Functions, Prev: Using Variables, Up: Top
5051 7 Conditional Parts of Makefiles
5052 ********************************
5054 A "conditional" directive causes part of a makefile to be obeyed or
5055 ignored depending on the values of variables. Conditionals can compare
5056 the value of one variable to another, or the value of a variable to a
5057 constant string. Conditionals control what `make' actually "sees" in
5058 the makefile, so they _cannot_ be used to control recipes at the time
5063 * Conditional Example:: Example of a conditional
5064 * Conditional Syntax:: The syntax of conditionals.
5065 * Testing Flags:: Conditionals that test flags.
5068 File: make.info, Node: Conditional Example, Next: Conditional Syntax, Prev: Conditionals, Up: Conditionals
5070 7.1 Example of a Conditional
5071 ============================
5073 The following example of a conditional tells `make' to use one set of
5074 libraries if the `CC' variable is `gcc', and a different set of
5075 libraries otherwise. It works by controlling which of two recipe lines
5076 will be used for the rule. The result is that `CC=gcc' as an argument
5077 to `make' changes not only which compiler is used but also which
5078 libraries are linked.
5080 libs_for_gcc = -lgnu
5085 $(CC) -o foo $(objects) $(libs_for_gcc)
5087 $(CC) -o foo $(objects) $(normal_libs)
5090 This conditional uses three directives: one `ifeq', one `else' and
5093 The `ifeq' directive begins the conditional, and specifies the
5094 condition. It contains two arguments, separated by a comma and
5095 surrounded by parentheses. Variable substitution is performed on both
5096 arguments and then they are compared. The lines of the makefile
5097 following the `ifeq' are obeyed if the two arguments match; otherwise
5100 The `else' directive causes the following lines to be obeyed if the
5101 previous conditional failed. In the example above, this means that the
5102 second alternative linking command is used whenever the first
5103 alternative is not used. It is optional to have an `else' in a
5106 The `endif' directive ends the conditional. Every conditional must
5107 end with an `endif'. Unconditional makefile text follows.
5109 As this example illustrates, conditionals work at the textual level:
5110 the lines of the conditional are treated as part of the makefile, or
5111 ignored, according to the condition. This is why the larger syntactic
5112 units of the makefile, such as rules, may cross the beginning or the
5113 end of the conditional.
5115 When the variable `CC' has the value `gcc', the above example has
5119 $(CC) -o foo $(objects) $(libs_for_gcc)
5121 When the variable `CC' has any other value, the effect is this:
5124 $(CC) -o foo $(objects) $(normal_libs)
5126 Equivalent results can be obtained in another way by
5127 conditionalizing a variable assignment and then using the variable
5130 libs_for_gcc = -lgnu
5134 libs=$(libs_for_gcc)
5140 $(CC) -o foo $(objects) $(libs)
5143 File: make.info, Node: Conditional Syntax, Next: Testing Flags, Prev: Conditional Example, Up: Conditionals
5145 7.2 Syntax of Conditionals
5146 ==========================
5148 The syntax of a simple conditional with no `else' is as follows:
5150 CONDITIONAL-DIRECTIVE
5154 The TEXT-IF-TRUE may be any lines of text, to be considered as part of
5155 the makefile if the condition is true. If the condition is false, no
5156 text is used instead.
5158 The syntax of a complex conditional is as follows:
5160 CONDITIONAL-DIRECTIVE
5168 CONDITIONAL-DIRECTIVE
5170 else CONDITIONAL-DIRECTIVE
5176 There can be as many "`else' CONDITIONAL-DIRECTIVE" clauses as
5177 necessary. Once a given condition is true, TEXT-IF-TRUE is used and no
5178 other clause is used; if no condition is true then TEXT-IF-FALSE is
5179 used. The TEXT-IF-TRUE and TEXT-IF-FALSE can be any number of lines of
5182 The syntax of the CONDITIONAL-DIRECTIVE is the same whether the
5183 conditional is simple or complex; after an `else' or not. There are
5184 four different directives that test different conditions. Here is a
5188 `ifeq 'ARG1' 'ARG2''
5189 `ifeq "ARG1" "ARG2"'
5190 `ifeq "ARG1" 'ARG2''
5191 `ifeq 'ARG1' "ARG2"'
5192 Expand all variable references in ARG1 and ARG2 and compare them.
5193 If they are identical, the TEXT-IF-TRUE is effective; otherwise,
5194 the TEXT-IF-FALSE, if any, is effective.
5196 Often you want to test if a variable has a non-empty value. When
5197 the value results from complex expansions of variables and
5198 functions, expansions you would consider empty may actually
5199 contain whitespace characters and thus are not seen as empty.
5200 However, you can use the `strip' function (*note Text Functions::)
5201 to avoid interpreting whitespace as a non-empty value. For
5204 ifeq ($(strip $(foo)),)
5208 will evaluate TEXT-IF-EMPTY even if the expansion of `$(foo)'
5209 contains whitespace characters.
5211 `ifneq (ARG1, ARG2)'
5212 `ifneq 'ARG1' 'ARG2''
5213 `ifneq "ARG1" "ARG2"'
5214 `ifneq "ARG1" 'ARG2''
5215 `ifneq 'ARG1' "ARG2"'
5216 Expand all variable references in ARG1 and ARG2 and compare them.
5217 If they are different, the TEXT-IF-TRUE is effective; otherwise,
5218 the TEXT-IF-FALSE, if any, is effective.
5220 `ifdef VARIABLE-NAME'
5221 The `ifdef' form takes the _name_ of a variable as its argument,
5222 not a reference to a variable. The value of that variable has a
5223 non-empty value, the TEXT-IF-TRUE is effective; otherwise, the
5224 TEXT-IF-FALSE, if any, is effective. Variables that have never
5225 been defined have an empty value. The text VARIABLE-NAME is
5226 expanded, so it could be a variable or function that expands to
5227 the name of a variable. For example:
5235 The variable reference `$(foo)' is expanded, yielding `bar', which
5236 is considered to be the name of a variable. The variable `bar' is
5237 not expanded, but its value is examined to determine if it is
5240 Note that `ifdef' only tests whether a variable has a value. It
5241 does not expand the variable to see if that value is nonempty.
5242 Consequently, tests using `ifdef' return true for all definitions
5243 except those like `foo ='. To test for an empty value, use
5244 `ifeq ($(foo),)'. For example,
5254 sets `frobozz' to `yes', while:
5263 sets `frobozz' to `no'.
5265 `ifndef VARIABLE-NAME'
5266 If the variable VARIABLE-NAME has an empty value, the TEXT-IF-TRUE
5267 is effective; otherwise, the TEXT-IF-FALSE, if any, is effective.
5268 The rules for expansion and testing of VARIABLE-NAME are identical
5269 to the `ifdef' directive.
5271 Extra spaces are allowed and ignored at the beginning of the
5272 conditional directive line, but a tab is not allowed. (If the line
5273 begins with a tab, it will be considered part of a recipe for a rule.)
5274 Aside from this, extra spaces or tabs may be inserted with no effect
5275 anywhere except within the directive name or within an argument. A
5276 comment starting with `#' may appear at the end of the line.
5278 The other two directives that play a part in a conditional are `else'
5279 and `endif'. Each of these directives is written as one word, with no
5280 arguments. Extra spaces are allowed and ignored at the beginning of the
5281 line, and spaces or tabs at the end. A comment starting with `#' may
5282 appear at the end of the line.
5284 Conditionals affect which lines of the makefile `make' uses. If the
5285 condition is true, `make' reads the lines of the TEXT-IF-TRUE as part
5286 of the makefile; if the condition is false, `make' ignores those lines
5287 completely. It follows that syntactic units of the makefile, such as
5288 rules, may safely be split across the beginning or the end of the
5291 `make' evaluates conditionals when it reads a makefile.
5292 Consequently, you cannot use automatic variables in the tests of
5293 conditionals because they are not defined until recipes are run (*note
5294 Automatic Variables::).
5296 To prevent intolerable confusion, it is not permitted to start a
5297 conditional in one makefile and end it in another. However, you may
5298 write an `include' directive within a conditional, provided you do not
5299 attempt to terminate the conditional inside the included file.
5302 File: make.info, Node: Testing Flags, Prev: Conditional Syntax, Up: Conditionals
5304 7.3 Conditionals that Test Flags
5305 ================================
5307 You can write a conditional that tests `make' command flags such as
5308 `-t' by using the variable `MAKEFLAGS' together with the `findstring'
5309 function (*note Functions for String Substitution and Analysis: Text
5310 Functions.). This is useful when `touch' is not enough to make a file
5313 The `findstring' function determines whether one string appears as a
5314 substring of another. If you want to test for the `-t' flag, use `t'
5315 as the first string and the value of `MAKEFLAGS' as the other.
5317 For example, here is how to arrange to use `ranlib -t' to finish
5318 marking an archive file up to date:
5321 ifneq (,$(findstring t,$(MAKEFLAGS)))
5323 +ranlib -t archive.a
5328 The `+' prefix marks those recipe lines as "recursive" so that they
5329 will be executed despite use of the `-t' flag. *Note Recursive Use of
5333 File: make.info, Node: Functions, Next: Running, Prev: Conditionals, Up: Top
5335 8 Functions for Transforming Text
5336 *********************************
5338 "Functions" allow you to do text processing in the makefile to compute
5339 the files to operate on or the commands to use in recipes. You use a
5340 function in a "function call", where you give the name of the function
5341 and some text (the "arguments") for the function to operate on. The
5342 result of the function's processing is substituted into the makefile at
5343 the point of the call, just as a variable might be substituted.
5347 * Syntax of Functions:: How to write a function call.
5348 * Text Functions:: General-purpose text manipulation functions.
5349 * File Name Functions:: Functions for manipulating file names.
5350 * Conditional Functions:: Functions that implement conditions.
5351 * Foreach Function:: Repeat some text with controlled variation.
5352 * Call Function:: Expand a user-defined function.
5353 * Value Function:: Return the un-expanded value of a variable.
5354 * Eval Function:: Evaluate the arguments as makefile syntax.
5355 * Origin Function:: Find where a variable got its value.
5356 * Flavor Function:: Find out the flavor of a variable.
5357 * Shell Function:: Substitute the output of a shell command.
5358 * Make Control Functions:: Functions that control how make runs.
5361 File: make.info, Node: Syntax of Functions, Next: Text Functions, Prev: Functions, Up: Functions
5363 8.1 Function Call Syntax
5364 ========================
5366 A function call resembles a variable reference. It looks like this:
5368 $(FUNCTION ARGUMENTS)
5372 ${FUNCTION ARGUMENTS}
5374 Here FUNCTION is a function name; one of a short list of names that
5375 are part of `make'. You can also essentially create your own functions
5376 by using the `call' builtin function.
5378 The ARGUMENTS are the arguments of the function. They are separated
5379 from the function name by one or more spaces or tabs, and if there is
5380 more than one argument, then they are separated by commas. Such
5381 whitespace and commas are not part of an argument's value. The
5382 delimiters which you use to surround the function call, whether
5383 parentheses or braces, can appear in an argument only in matching pairs;
5384 the other kind of delimiters may appear singly. If the arguments
5385 themselves contain other function calls or variable references, it is
5386 wisest to use the same kind of delimiters for all the references; write
5387 `$(subst a,b,$(x))', not `$(subst a,b,${x})'. This is because it is
5388 clearer, and because only one type of delimiter is matched to find the
5389 end of the reference.
5391 The text written for each argument is processed by substitution of
5392 variables and function calls to produce the argument value, which is
5393 the text on which the function acts. The substitution is done in the
5394 order in which the arguments appear.
5396 Commas and unmatched parentheses or braces cannot appear in the text
5397 of an argument as written; leading spaces cannot appear in the text of
5398 the first argument as written. These characters can be put into the
5399 argument value by variable substitution. First define variables
5400 `comma' and `space' whose values are isolated comma and space
5401 characters, then substitute these variables where such characters are
5406 space:= $(empty) $(empty)
5408 bar:= $(subst $(space),$(comma),$(foo))
5409 # bar is now `a,b,c'.
5411 Here the `subst' function replaces each space with a comma, through the
5412 value of `foo', and substitutes the result.
5415 File: make.info, Node: Text Functions, Next: File Name Functions, Prev: Syntax of Functions, Up: Functions
5417 8.2 Functions for String Substitution and Analysis
5418 ==================================================
5420 Here are some functions that operate on strings:
5422 `$(subst FROM,TO,TEXT)'
5423 Performs a textual replacement on the text TEXT: each occurrence
5424 of FROM is replaced by TO. The result is substituted for the
5425 function call. For example,
5427 $(subst ee,EE,feet on the street)
5429 substitutes the string `fEEt on the strEEt'.
5431 `$(patsubst PATTERN,REPLACEMENT,TEXT)'
5432 Finds whitespace-separated words in TEXT that match PATTERN and
5433 replaces them with REPLACEMENT. Here PATTERN may contain a `%'
5434 which acts as a wildcard, matching any number of any characters
5435 within a word. If REPLACEMENT also contains a `%', the `%' is
5436 replaced by the text that matched the `%' in PATTERN. Only the
5437 first `%' in the PATTERN and REPLACEMENT is treated this way; any
5438 subsequent `%' is unchanged.
5440 `%' characters in `patsubst' function invocations can be quoted
5441 with preceding backslashes (`\'). Backslashes that would
5442 otherwise quote `%' characters can be quoted with more backslashes.
5443 Backslashes that quote `%' characters or other backslashes are
5444 removed from the pattern before it is compared file names or has a
5445 stem substituted into it. Backslashes that are not in danger of
5446 quoting `%' characters go unmolested. For example, the pattern
5447 `the\%weird\\%pattern\\' has `the%weird\' preceding the operative
5448 `%' character, and `pattern\\' following it. The final two
5449 backslashes are left alone because they cannot affect any `%'
5452 Whitespace between words is folded into single space characters;
5453 leading and trailing whitespace is discarded.
5457 $(patsubst %.c,%.o,x.c.c bar.c)
5459 produces the value `x.c.o bar.o'.
5461 Substitution references (*note Substitution References:
5462 Substitution Refs.) are a simpler way to get the effect of the
5463 `patsubst' function:
5465 $(VAR:PATTERN=REPLACEMENT)
5469 $(patsubst PATTERN,REPLACEMENT,$(VAR))
5471 The second shorthand simplifies one of the most common uses of
5472 `patsubst': replacing the suffix at the end of file names.
5474 $(VAR:SUFFIX=REPLACEMENT)
5478 $(patsubst %SUFFIX,%REPLACEMENT,$(VAR))
5480 For example, you might have a list of object files:
5482 objects = foo.o bar.o baz.o
5484 To get the list of corresponding source files, you could simply
5489 instead of using the general form:
5491 $(patsubst %.o,%.c,$(objects))
5494 Removes leading and trailing whitespace from STRING and replaces
5495 each internal sequence of one or more whitespace characters with a
5496 single space. Thus, `$(strip a b c )' results in `a b c'.
5498 The function `strip' can be very useful when used in conjunction
5499 with conditionals. When comparing something with the empty string
5500 `' using `ifeq' or `ifneq', you usually want a string of just
5501 whitespace to match the empty string (*note Conditionals::).
5503 Thus, the following may fail to have the desired results:
5506 ifneq "$(needs_made)" ""
5509 all:;@echo 'Nothing to make!'
5512 Replacing the variable reference `$(needs_made)' with the function
5513 call `$(strip $(needs_made))' in the `ifneq' directive would make
5516 `$(findstring FIND,IN)'
5517 Searches IN for an occurrence of FIND. If it occurs, the value is
5518 FIND; otherwise, the value is empty. You can use this function in
5519 a conditional to test for the presence of a specific substring in
5520 a given string. Thus, the two examples,
5522 $(findstring a,a b c)
5525 produce the values `a' and `' (the empty string), respectively.
5526 *Note Testing Flags::, for a practical application of `findstring'.
5528 `$(filter PATTERN...,TEXT)'
5529 Returns all whitespace-separated words in TEXT that _do_ match any
5530 of the PATTERN words, removing any words that _do not_ match. The
5531 patterns are written using `%', just like the patterns used in the
5532 `patsubst' function above.
5534 The `filter' function can be used to separate out different types
5535 of strings (such as file names) in a variable. For example:
5537 sources := foo.c bar.c baz.s ugh.h
5539 cc $(filter %.c %.s,$(sources)) -o foo
5541 says that `foo' depends of `foo.c', `bar.c', `baz.s' and `ugh.h'
5542 but only `foo.c', `bar.c' and `baz.s' should be specified in the
5543 command to the compiler.
5545 `$(filter-out PATTERN...,TEXT)'
5546 Returns all whitespace-separated words in TEXT that _do not_ match
5547 any of the PATTERN words, removing the words that _do_ match one
5548 or more. This is the exact opposite of the `filter' function.
5552 objects=main1.o foo.o main2.o bar.o
5553 mains=main1.o main2.o
5555 the following generates a list which contains all the object files
5558 $(filter-out $(mains),$(objects))
5561 Sorts the words of LIST in lexical order, removing duplicate
5562 words. The output is a list of words separated by single spaces.
5565 $(sort foo bar lose)
5567 returns the value `bar foo lose'.
5569 Incidentally, since `sort' removes duplicate words, you can use it
5570 for this purpose even if you don't care about the sort order.
5573 Returns the Nth word of TEXT. The legitimate values of N start
5574 from 1. If N is bigger than the number of words in TEXT, the
5575 value is empty. For example,
5577 $(word 2, foo bar baz)
5581 `$(wordlist S,E,TEXT)'
5582 Returns the list of words in TEXT starting with word S and ending
5583 with word E (inclusive). The legitimate values of S start from 1;
5584 E may start from 0. If S is bigger than the number of words in
5585 TEXT, the value is empty. If E is bigger than the number of words
5586 in TEXT, words up to the end of TEXT are returned. If S is
5587 greater than E, nothing is returned. For example,
5589 $(wordlist 2, 3, foo bar baz)
5594 Returns the number of words in TEXT. Thus, the last word of TEXT
5595 is `$(word $(words TEXT),TEXT)'.
5597 `$(firstword NAMES...)'
5598 The argument NAMES is regarded as a series of names, separated by
5599 whitespace. The value is the first name in the series. The rest
5600 of the names are ignored.
5604 $(firstword foo bar)
5606 produces the result `foo'. Although `$(firstword TEXT)' is the
5607 same as `$(word 1,TEXT)', the `firstword' function is retained for
5610 `$(lastword NAMES...)'
5611 The argument NAMES is regarded as a series of names, separated by
5612 whitespace. The value is the last name in the series.
5618 produces the result `bar'. Although `$(lastword TEXT)' is the
5619 same as `$(word $(words TEXT),TEXT)', the `lastword' function was
5620 added for its simplicity and better performance.
5622 Here is a realistic example of the use of `subst' and `patsubst'.
5623 Suppose that a makefile uses the `VPATH' variable to specify a list of
5624 directories that `make' should search for prerequisite files (*note
5625 `VPATH' Search Path for All Prerequisites: General Search.). This
5626 example shows how to tell the C compiler to search for header files in
5627 the same list of directories.
5629 The value of `VPATH' is a list of directories separated by colons,
5630 such as `src:../headers'. First, the `subst' function is used to
5631 change the colons to spaces:
5633 $(subst :, ,$(VPATH))
5635 This produces `src ../headers'. Then `patsubst' is used to turn each
5636 directory name into a `-I' flag. These can be added to the value of
5637 the variable `CFLAGS', which is passed automatically to the C compiler,
5640 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
5642 The effect is to append the text `-Isrc -I../headers' to the previously
5643 given value of `CFLAGS'. The `override' directive is used so that the
5644 new value is assigned even if the previous value of `CFLAGS' was
5645 specified with a command argument (*note The `override' Directive:
5646 Override Directive.).
5649 File: make.info, Node: File Name Functions, Next: Conditional Functions, Prev: Text Functions, Up: Functions
5651 8.3 Functions for File Names
5652 ============================
5654 Several of the built-in expansion functions relate specifically to
5655 taking apart file names or lists of file names.
5657 Each of the following functions performs a specific transformation
5658 on a file name. The argument of the function is regarded as a series
5659 of file names, separated by whitespace. (Leading and trailing
5660 whitespace is ignored.) Each file name in the series is transformed in
5661 the same way and the results are concatenated with single spaces
5665 Extracts the directory-part of each file name in NAMES. The
5666 directory-part of the file name is everything up through (and
5667 including) the last slash in it. If the file name contains no
5668 slash, the directory part is the string `./'. For example,
5670 $(dir src/foo.c hacks)
5672 produces the result `src/ ./'.
5674 `$(notdir NAMES...)'
5675 Extracts all but the directory-part of each file name in NAMES.
5676 If the file name contains no slash, it is left unchanged.
5677 Otherwise, everything through the last slash is removed from it.
5679 A file name that ends with a slash becomes an empty string. This
5680 is unfortunate, because it means that the result does not always
5681 have the same number of whitespace-separated file names as the
5682 argument had; but we do not see any other valid alternative.
5686 $(notdir src/foo.c hacks)
5688 produces the result `foo.c hacks'.
5690 `$(suffix NAMES...)'
5691 Extracts the suffix of each file name in NAMES. If the file name
5692 contains a period, the suffix is everything starting with the last
5693 period. Otherwise, the suffix is the empty string. This
5694 frequently means that the result will be empty when NAMES is not,
5695 and if NAMES contains multiple file names, the result may contain
5700 $(suffix src/foo.c src-1.0/bar.c hacks)
5702 produces the result `.c .c'.
5704 `$(basename NAMES...)'
5705 Extracts all but the suffix of each file name in NAMES. If the
5706 file name contains a period, the basename is everything starting
5707 up to (and not including) the last period. Periods in the
5708 directory part are ignored. If there is no period, the basename
5709 is the entire file name. For example,
5711 $(basename src/foo.c src-1.0/bar hacks)
5713 produces the result `src/foo src-1.0/bar hacks'.
5715 `$(addsuffix SUFFIX,NAMES...)'
5716 The argument NAMES is regarded as a series of names, separated by
5717 whitespace; SUFFIX is used as a unit. The value of SUFFIX is
5718 appended to the end of each individual name and the resulting
5719 larger names are concatenated with single spaces between them.
5722 $(addsuffix .c,foo bar)
5724 produces the result `foo.c bar.c'.
5726 `$(addprefix PREFIX,NAMES...)'
5727 The argument NAMES is regarded as a series of names, separated by
5728 whitespace; PREFIX is used as a unit. The value of PREFIX is
5729 prepended to the front of each individual name and the resulting
5730 larger names are concatenated with single spaces between them.
5733 $(addprefix src/,foo bar)
5735 produces the result `src/foo src/bar'.
5737 `$(join LIST1,LIST2)'
5738 Concatenates the two arguments word by word: the two first words
5739 (one from each argument) concatenated form the first word of the
5740 result, the two second words form the second word of the result,
5741 and so on. So the Nth word of the result comes from the Nth word
5742 of each argument. If one argument has more words that the other,
5743 the extra words are copied unchanged into the result.
5745 For example, `$(join a b,.c .o)' produces `a.c b.o'.
5747 Whitespace between the words in the lists is not preserved; it is
5748 replaced with a single space.
5750 This function can merge the results of the `dir' and `notdir'
5751 functions, to produce the original list of files which was given
5752 to those two functions.
5754 `$(wildcard PATTERN)'
5755 The argument PATTERN is a file name pattern, typically containing
5756 wildcard characters (as in shell file name patterns). The result
5757 of `wildcard' is a space-separated list of the names of existing
5758 files that match the pattern. *Note Using Wildcard Characters in
5759 File Names: Wildcards.
5761 `$(realpath NAMES...)'
5762 For each file name in NAMES return the canonical absolute name. A
5763 canonical name does not contain any `.' or `..' components, nor
5764 any repeated path separators (`/') or symlinks. In case of a
5765 failure the empty string is returned. Consult the `realpath(3)'
5766 documentation for a list of possible failure causes.
5768 `$(abspath NAMES...)'
5769 For each file name in NAMES return an absolute name that does not
5770 contain any `.' or `..' components, nor any repeated path
5771 separators (`/'). Note that, in contrast to `realpath' function,
5772 `abspath' does not resolve symlinks and does not require the file
5773 names to refer to an existing file or directory. Use the
5774 `wildcard' function to test for existence.
5777 File: make.info, Node: Conditional Functions, Next: Foreach Function, Prev: File Name Functions, Up: Functions
5779 8.4 Functions for Conditionals
5780 ==============================
5782 There are three functions that provide conditional expansion. A key
5783 aspect of these functions is that not all of the arguments are expanded
5784 initially. Only those arguments which need to be expanded, will be
5787 `$(if CONDITION,THEN-PART[,ELSE-PART])'
5788 The `if' function provides support for conditional expansion in a
5789 functional context (as opposed to the GNU `make' makefile
5790 conditionals such as `ifeq' (*note Syntax of Conditionals:
5791 Conditional Syntax.).
5793 The first argument, CONDITION, first has all preceding and
5794 trailing whitespace stripped, then is expanded. If it expands to
5795 any non-empty string, then the condition is considered to be true.
5796 If it expands to an empty string, the condition is considered to
5799 If the condition is true then the second argument, THEN-PART, is
5800 evaluated and this is used as the result of the evaluation of the
5801 entire `if' function.
5803 If the condition is false then the third argument, ELSE-PART, is
5804 evaluated and this is the result of the `if' function. If there is
5805 no third argument, the `if' function evaluates to nothing (the
5808 Note that only one of the THEN-PART or the ELSE-PART will be
5809 evaluated, never both. Thus, either can contain side-effects
5810 (such as `shell' function calls, etc.)
5812 `$(or CONDITION1[,CONDITION2[,CONDITION3...]])'
5813 The `or' function provides a "short-circuiting" OR operation.
5814 Each argument is expanded, in order. If an argument expands to a
5815 non-empty string the processing stops and the result of the
5816 expansion is that string. If, after all arguments are expanded,
5817 all of them are false (empty), then the result of the expansion is
5820 `$(and CONDITION1[,CONDITION2[,CONDITION3...]])'
5821 The `and' function provides a "short-circuiting" AND operation.
5822 Each argument is expanded, in order. If an argument expands to an
5823 empty string the processing stops and the result of the expansion
5824 is the empty string. If all arguments expand to a non-empty
5825 string then the result of the expansion is the expansion of the
5830 File: make.info, Node: Foreach Function, Next: Call Function, Prev: Conditional Functions, Up: Functions
5832 8.5 The `foreach' Function
5833 ==========================
5835 The `foreach' function is very different from other functions. It
5836 causes one piece of text to be used repeatedly, each time with a
5837 different substitution performed on it. It resembles the `for' command
5838 in the shell `sh' and the `foreach' command in the C-shell `csh'.
5840 The syntax of the `foreach' function is:
5842 $(foreach VAR,LIST,TEXT)
5844 The first two arguments, VAR and LIST, are expanded before anything
5845 else is done; note that the last argument, TEXT, is *not* expanded at
5846 the same time. Then for each word of the expanded value of LIST, the
5847 variable named by the expanded value of VAR is set to that word, and
5848 TEXT is expanded. Presumably TEXT contains references to that
5849 variable, so its expansion will be different each time.
5851 The result is that TEXT is expanded as many times as there are
5852 whitespace-separated words in LIST. The multiple expansions of TEXT
5853 are concatenated, with spaces between them, to make the result of
5856 This simple example sets the variable `files' to the list of all
5857 files in the directories in the list `dirs':
5860 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
5862 Here TEXT is `$(wildcard $(dir)/*)'. The first repetition finds the
5863 value `a' for `dir', so it produces the same result as `$(wildcard
5864 a/*)'; the second repetition produces the result of `$(wildcard b/*)';
5865 and the third, that of `$(wildcard c/*)'.
5867 This example has the same result (except for setting `dirs') as the
5870 files := $(wildcard a/* b/* c/* d/*)
5872 When TEXT is complicated, you can improve readability by giving it a
5873 name, with an additional variable:
5875 find_files = $(wildcard $(dir)/*)
5877 files := $(foreach dir,$(dirs),$(find_files))
5879 Here we use the variable `find_files' this way. We use plain `=' to
5880 define a recursively-expanding variable, so that its value contains an
5881 actual function call to be reexpanded under the control of `foreach'; a
5882 simply-expanded variable would not do, since `wildcard' would be called
5883 only once at the time of defining `find_files'.
5885 The `foreach' function has no permanent effect on the variable VAR;
5886 its value and flavor after the `foreach' function call are the same as
5887 they were beforehand. The other values which are taken from LIST are
5888 in effect only temporarily, during the execution of `foreach'. The
5889 variable VAR is a simply-expanded variable during the execution of
5890 `foreach'. If VAR was undefined before the `foreach' function call, it
5891 is undefined after the call. *Note The Two Flavors of Variables:
5894 You must take care when using complex variable expressions that
5895 result in variable names because many strange things are valid variable
5896 names, but are probably not what you intended. For example,
5898 files := $(foreach Esta escrito en espanol!,b c ch,$(find_files))
5900 might be useful if the value of `find_files' references the variable
5901 whose name is `Esta escrito en espanol!' (es un nombre bastante largo,
5902 no?), but it is more likely to be a mistake.
5905 File: make.info, Node: Call Function, Next: Value Function, Prev: Foreach Function, Up: Functions
5907 8.6 The `call' Function
5908 =======================
5910 The `call' function is unique in that it can be used to create new
5911 parameterized functions. You can write a complex expression as the
5912 value of a variable, then use `call' to expand it with different values.
5914 The syntax of the `call' function is:
5916 $(call VARIABLE,PARAM,PARAM,...)
5918 When `make' expands this function, it assigns each PARAM to
5919 temporary variables `$(1)', `$(2)', etc. The variable `$(0)' will
5920 contain VARIABLE. There is no maximum number of parameter arguments.
5921 There is no minimum, either, but it doesn't make sense to use `call'
5924 Then VARIABLE is expanded as a `make' variable in the context of
5925 these temporary assignments. Thus, any reference to `$(1)' in the
5926 value of VARIABLE will resolve to the first PARAM in the invocation of
5929 Note that VARIABLE is the _name_ of a variable, not a _reference_ to
5930 that variable. Therefore you would not normally use a `$' or
5931 parentheses when writing it. (You can, however, use a variable
5932 reference in the name if you want the name not to be a constant.)
5934 If VARIABLE is the name of a builtin function, the builtin function
5935 is always invoked (even if a `make' variable by that name also exists).
5937 The `call' function expands the PARAM arguments before assigning
5938 them to temporary variables. This means that VARIABLE values
5939 containing references to builtin functions that have special expansion
5940 rules, like `foreach' or `if', may not work as you expect.
5942 Some examples may make this clearer.
5944 This macro simply reverses its arguments:
5948 foo = $(call reverse,a,b)
5950 Here FOO will contain `b a'.
5952 This one is slightly more interesting: it defines a macro to search
5953 for the first instance of a program in `PATH':
5955 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
5957 LS := $(call pathsearch,ls)
5959 Now the variable LS contains `/bin/ls' or similar.
5961 The `call' function can be nested. Each recursive invocation gets
5962 its own local values for `$(1)', etc. that mask the values of
5963 higher-level `call'. For example, here is an implementation of a "map"
5966 map = $(foreach a,$(2),$(call $(1),$(a)))
5968 Now you can MAP a function that normally takes only one argument,
5969 such as `origin', to multiple values in one step:
5971 o = $(call map,origin,o map MAKE)
5973 and end up with O containing something like `file file default'.
5975 A final caution: be careful when adding whitespace to the arguments
5976 to `call'. As with other functions, any whitespace contained in the
5977 second and subsequent arguments is kept; this can cause strange
5978 effects. It's generally safest to remove all extraneous whitespace when
5979 providing parameters to `call'.
5982 File: make.info, Node: Value Function, Next: Eval Function, Prev: Call Function, Up: Functions
5984 8.7 The `value' Function
5985 ========================
5987 The `value' function provides a way for you to use the value of a
5988 variable _without_ having it expanded. Please note that this does not
5989 undo expansions which have already occurred; for example if you create
5990 a simply expanded variable its value is expanded during the definition;
5991 in that case the `value' function will return the same result as using
5992 the variable directly.
5994 The syntax of the `value' function is:
5998 Note that VARIABLE is the _name_ of a variable; not a _reference_ to
5999 that variable. Therefore you would not normally use a `$' or
6000 parentheses when writing it. (You can, however, use a variable
6001 reference in the name if you want the name not to be a constant.)
6003 The result of this function is a string containing the value of
6004 VARIABLE, without any expansion occurring. For example, in this
6013 The first output line would be `ATH', since the "$P" would be expanded
6014 as a `make' variable, while the second output line would be the current
6015 value of your `$PATH' environment variable, since the `value' function
6016 avoided the expansion.
6018 The `value' function is most often used in conjunction with the
6019 `eval' function (*note Eval Function::).
6022 File: make.info, Node: Eval Function, Next: Origin Function, Prev: Value Function, Up: Functions
6024 8.8 The `eval' Function
6025 =======================
6027 The `eval' function is very special: it allows you to define new
6028 makefile constructs that are not constant; which are the result of
6029 evaluating other variables and functions. The argument to the `eval'
6030 function is expanded, then the results of that expansion are parsed as
6031 makefile syntax. The expanded results can define new `make' variables,
6032 targets, implicit or explicit rules, etc.
6034 The result of the `eval' function is always the empty string; thus,
6035 it can be placed virtually anywhere in a makefile without causing
6038 It's important to realize that the `eval' argument is expanded
6039 _twice_; first by the `eval' function, then the results of that
6040 expansion are expanded again when they are parsed as makefile syntax.
6041 This means you may need to provide extra levels of escaping for "$"
6042 characters when using `eval'. The `value' function (*note Value
6043 Function::) can sometimes be useful in these situations, to circumvent
6044 unwanted expansions.
6046 Here is an example of how `eval' can be used; this example combines
6047 a number of concepts and other functions. Although it might seem
6048 overly complex to use `eval' in this example, rather than just writing
6049 out the rules, consider two things: first, the template definition (in
6050 `PROGRAM_template') could need to be much more complex than it is here;
6051 and second, you might put the complex, "generic" part of this example
6052 into another makefile, then include it in all the individual makefiles.
6053 Now your individual makefiles are quite straightforward.
6055 PROGRAMS = server client
6057 server_OBJS = server.o server_priv.o server_access.o
6058 server_LIBS = priv protocol
6060 client_OBJS = client.o client_api.o client_mem.o
6061 client_LIBS = protocol
6063 # Everything after this is generic
6068 define PROGRAM_template =
6069 $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
6070 ALL_OBJS += $$($(1)_OBJS)
6073 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
6076 $(LINK.o) $^ $(LDLIBS) -o $@
6079 rm -f $(ALL_OBJS) $(PROGRAMS)
6082 File: make.info, Node: Origin Function, Next: Flavor Function, Prev: Eval Function, Up: Functions
6084 8.9 The `origin' Function
6085 =========================
6087 The `origin' function is unlike most other functions in that it does
6088 not operate on the values of variables; it tells you something _about_
6089 a variable. Specifically, it tells you where it came from.
6091 The syntax of the `origin' function is:
6095 Note that VARIABLE is the _name_ of a variable to inquire about; not
6096 a _reference_ to that variable. Therefore you would not normally use a
6097 `$' or parentheses when writing it. (You can, however, use a variable
6098 reference in the name if you want the name not to be a constant.)
6100 The result of this function is a string telling you how the variable
6101 VARIABLE was defined:
6104 if VARIABLE was never defined.
6107 if VARIABLE has a default definition, as is usual with `CC' and so
6108 on. *Note Variables Used by Implicit Rules: Implicit Variables.
6109 Note that if you have redefined a default variable, the `origin'
6110 function will return the origin of the later definition.
6113 if VARIABLE was inherited from the environment provided to `make'.
6115 `environment override'
6116 if VARIABLE was inherited from the environment provided to `make',
6117 and is overriding a setting for VARIABLE in the makefile as a
6118 result of the `-e' option (*note Summary of Options: Options
6122 if VARIABLE was defined in a makefile.
6125 if VARIABLE was defined on the command line.
6128 if VARIABLE was defined with an `override' directive in a makefile
6129 (*note The `override' Directive: Override Directive.).
6132 if VARIABLE is an automatic variable defined for the execution of
6133 the recipe for each rule (*note Automatic Variables::).
6135 This information is primarily useful (other than for your curiosity)
6136 to determine if you want to believe the value of a variable. For
6137 example, suppose you have a makefile `foo' that includes another
6138 makefile `bar'. You want a variable `bletch' to be defined in `bar' if
6139 you run the command `make -f bar', even if the environment contains a
6140 definition of `bletch'. However, if `foo' defined `bletch' before
6141 including `bar', you do not want to override that definition. This
6142 could be done by using an `override' directive in `foo', giving that
6143 definition precedence over the later definition in `bar';
6144 unfortunately, the `override' directive would also override any command
6145 line definitions. So, `bar' could include:
6148 ifeq "$(origin bletch)" "environment"
6149 bletch = barf, gag, etc.
6153 If `bletch' has been defined from the environment, this will redefine
6156 If you want to override a previous definition of `bletch' if it came
6157 from the environment, even under `-e', you could instead write:
6159 ifneq "$(findstring environment,$(origin bletch))" ""
6160 bletch = barf, gag, etc.
6163 Here the redefinition takes place if `$(origin bletch)' returns
6164 either `environment' or `environment override'. *Note Functions for
6165 String Substitution and Analysis: Text Functions.
6168 File: make.info, Node: Flavor Function, Next: Shell Function, Prev: Origin Function, Up: Functions
6170 8.10 The `flavor' Function
6171 ==========================
6173 The `flavor' function is unlike most other functions (and like `origin'
6174 function) in that it does not operate on the values of variables; it
6175 tells you something _about_ a variable. Specifically, it tells you the
6176 flavor of a variable (*note The Two Flavors of Variables: Flavors.).
6178 The syntax of the `flavor' function is:
6182 Note that VARIABLE is the _name_ of a variable to inquire about; not
6183 a _reference_ to that variable. Therefore you would not normally use a
6184 `$' or parentheses when writing it. (You can, however, use a variable
6185 reference in the name if you want the name not to be a constant.)
6187 The result of this function is a string that identifies the flavor
6188 of the variable VARIABLE:
6191 if VARIABLE was never defined.
6194 if VARIABLE is a recursively expanded variable.
6197 if VARIABLE is a simply expanded variable.
6201 File: make.info, Node: Shell Function, Next: Make Control Functions, Prev: Flavor Function, Up: Functions
6203 8.11 The `shell' Function
6204 =========================
6206 The `shell' function is unlike any other function other than the
6207 `wildcard' function (*note The Function `wildcard': Wildcard Function.)
6208 in that it communicates with the world outside of `make'.
6210 The `shell' function performs the same function that backquotes
6211 (``') perform in most shells: it does "command expansion". This means
6212 that it takes as an argument a shell command and evaluates to the
6213 output of the command. The only processing `make' does on the result
6214 is to convert each newline (or carriage-return / newline pair) to a
6215 single space. If there is a trailing (carriage-return and) newline it
6216 will simply be removed.
6218 The commands run by calls to the `shell' function are run when the
6219 function calls are expanded (*note How `make' Reads a Makefile: Reading
6220 Makefiles.). Because this function involves spawning a new shell, you
6221 should carefully consider the performance implications of using the
6222 `shell' function within recursively expanded variables vs. simply
6223 expanded variables (*note The Two Flavors of Variables: Flavors.).
6225 Here are some examples of the use of the `shell' function:
6227 contents := $(shell cat foo)
6229 sets `contents' to the contents of the file `foo', with a space (rather
6230 than a newline) separating each line.
6232 files := $(shell echo *.c)
6234 sets `files' to the expansion of `*.c'. Unless `make' is using a very
6235 strange shell, this has the same result as `$(wildcard *.c)' (as long
6236 as at least one `.c' file exists).
6239 File: make.info, Node: Make Control Functions, Prev: Shell Function, Up: Functions
6241 8.12 Functions That Control Make
6242 ================================
6244 These functions control the way make runs. Generally, they are used to
6245 provide information to the user of the makefile or to cause make to stop
6246 if some sort of environmental error is detected.
6249 Generates a fatal error where the message is TEXT. Note that the
6250 error is generated whenever this function is evaluated. So, if
6251 you put it inside a recipe or on the right side of a recursive
6252 variable assignment, it won't be evaluated until later. The TEXT
6253 will be expanded before the error is generated.
6258 $(error error is $(ERROR1))
6261 will generate a fatal error during the read of the makefile if the
6262 `make' variable `ERROR1' is defined. Or,
6264 ERR = $(error found an error!)
6269 will generate a fatal error while `make' is running, if the `err'
6272 `$(warning TEXT...)'
6273 This function works similarly to the `error' function, above,
6274 except that `make' doesn't exit. Instead, TEXT is expanded and
6275 the resulting message is displayed, but processing of the makefile
6278 The result of the expansion of this function is the empty string.
6281 This function does nothing more than print its (expanded)
6282 argument(s) to standard output. No makefile name or line number
6283 is added. The result of the expansion of this function is the
6287 File: make.info, Node: Running, Next: Implicit Rules, Prev: Functions, Up: Top
6292 A makefile that says how to recompile a program can be used in more
6293 than one way. The simplest use is to recompile every file that is out
6294 of date. Usually, makefiles are written so that if you run `make' with
6295 no arguments, it does just that.
6297 But you might want to update only some of the files; you might want
6298 to use a different compiler or different compiler options; you might
6299 want just to find out which files are out of date without changing them.
6301 By giving arguments when you run `make', you can do any of these
6302 things and many others.
6304 The exit status of `make' is always one of three values:
6306 The exit status is zero if `make' is successful.
6309 The exit status is two if `make' encounters any errors. It will
6310 print messages describing the particular errors.
6313 The exit status is one if you use the `-q' flag and `make'
6314 determines that some target is not already up to date. *Note
6315 Instead of Executing Recipes: Instead of Execution.
6319 * Makefile Arguments:: How to specify which makefile to use.
6320 * Goals:: How to use goal arguments to specify which
6321 parts of the makefile to use.
6322 * Instead of Execution:: How to use mode flags to specify what
6323 kind of thing to do with the recipes
6324 in the makefile other than simply
6326 * Avoiding Compilation:: How to avoid recompiling certain files.
6327 * Overriding:: How to override a variable to specify
6328 an alternate compiler and other things.
6329 * Testing:: How to proceed past some errors, to
6331 * Options Summary:: Summary of Options
6334 File: make.info, Node: Makefile Arguments, Next: Goals, Prev: Running, Up: Running
6336 9.1 Arguments to Specify the Makefile
6337 =====================================
6339 The way to specify the name of the makefile is with the `-f' or
6340 `--file' option (`--makefile' also works). For example, `-f altmake'
6341 says to use the file `altmake' as the makefile.
6343 If you use the `-f' flag several times and follow each `-f' with an
6344 argument, all the specified files are used jointly as makefiles.
6346 If you do not use the `-f' or `--file' flag, the default is to try
6347 `GNUmakefile', `makefile', and `Makefile', in that order, and use the
6348 first of these three which exists or can be made (*note Writing
6349 Makefiles: Makefiles.).
6352 File: make.info, Node: Goals, Next: Instead of Execution, Prev: Makefile Arguments, Up: Running
6354 9.2 Arguments to Specify the Goals
6355 ==================================
6357 The "goals" are the targets that `make' should strive ultimately to
6358 update. Other targets are updated as well if they appear as
6359 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
6361 By default, the goal is the first target in the makefile (not
6362 counting targets that start with a period). Therefore, makefiles are
6363 usually written so that the first target is for compiling the entire
6364 program or programs they describe. If the first rule in the makefile
6365 has several targets, only the first target in the rule becomes the
6366 default goal, not the whole list. You can manage the selection of the
6367 default goal from within your makefile using the `.DEFAULT_GOAL'
6368 variable (*note Other Special Variables: Special Variables.).
6370 You can also specify a different goal or goals with command line
6371 arguments to `make'. Use the name of the goal as an argument. If you
6372 specify several goals, `make' processes each of them in turn, in the
6373 order you name them.
6375 Any target in the makefile may be specified as a goal (unless it
6376 starts with `-' or contains an `=', in which case it will be parsed as
6377 a switch or variable definition, respectively). Even targets not in
6378 the makefile may be specified, if `make' can find implicit rules that
6379 say how to make them.
6381 `Make' will set the special variable `MAKECMDGOALS' to the list of
6382 goals you specified on the command line. If no goals were given on the
6383 command line, this variable is empty. Note that this variable should
6384 be used only in special circumstances.
6386 An example of appropriate use is to avoid including `.d' files
6387 during `clean' rules (*note Automatic Prerequisites::), so `make' won't
6388 create them only to immediately remove them again:
6390 sources = foo.c bar.c
6392 ifneq ($(MAKECMDGOALS),clean)
6393 include $(sources:.c=.d)
6396 One use of specifying a goal is if you want to compile only a part of
6397 the program, or only one of several programs. Specify as a goal each
6398 file that you wish to remake. For example, consider a directory
6399 containing several programs, with a makefile that starts like this:
6402 all: size nm ld ar as
6404 If you are working on the program `size', you might want to say
6405 `make size' so that only the files of that program are recompiled.
6407 Another use of specifying a goal is to make files that are not
6408 normally made. For example, there may be a file of debugging output,
6409 or a version of the program that is compiled specially for testing,
6410 which has a rule in the makefile but is not a prerequisite of the
6413 Another use of specifying a goal is to run the recipe associated with
6414 a phony target (*note Phony Targets::) or empty target (*note Empty
6415 Target Files to Record Events: Empty Targets.). Many makefiles contain
6416 a phony target named `clean' which deletes everything except source
6417 files. Naturally, this is done only if you request it explicitly with
6418 `make clean'. Following is a list of typical phony and empty target
6419 names. *Note Standard Targets::, for a detailed list of all the
6420 standard target names which GNU software packages use.
6423 Make all the top-level targets the makefile knows about.
6426 Delete all files that are normally created by running `make'.
6429 Like `clean', but may refrain from deleting a few files that people
6430 normally don't want to recompile. For example, the `mostlyclean'
6431 target for GCC does not delete `libgcc.a', because recompiling it
6432 is rarely necessary and takes a lot of time.
6437 Any of these targets might be defined to delete _more_ files than
6438 `clean' does. For example, this would delete configuration files
6439 or links that you would normally create as preparation for
6440 compilation, even if the makefile itself cannot create these files.
6443 Copy the executable file into a directory that users typically
6444 search for commands; copy any auxiliary files that the executable
6445 uses into the directories where it will look for them.
6448 Print listings of the source files that have changed.
6451 Create a tar file of the source files.
6454 Create a shell archive (shar file) of the source files.
6457 Create a distribution file of the source files. This might be a
6458 tar file, or a shar file, or a compressed version of one of the
6459 above, or even more than one of the above.
6462 Update a tags table for this program.
6466 Perform self tests on the program this makefile builds.
6469 File: make.info, Node: Instead of Execution, Next: Avoiding Compilation, Prev: Goals, Up: Running
6471 9.3 Instead of Executing Recipes
6472 ================================
6474 The makefile tells `make' how to tell whether a target is up to date,
6475 and how to update each target. But updating the targets is not always
6476 what you want. Certain options specify other activities for `make'.
6482 "No-op". The activity is to print what recipe would be used to
6483 make the targets up to date, but not actually execute it. Some
6484 recipes are still executed, even with this flag (*note How the
6485 `MAKE' Variable Works: MAKE Variable.).
6489 "Touch". The activity is to mark the targets as up to date without
6490 actually changing them. In other words, `make' pretends to compile
6491 the targets but does not really change their contents.
6495 "Question". The activity is to find out silently whether the
6496 targets are up to date already; but execute no recipe in either
6497 case. In other words, neither compilation nor output will occur.
6503 "What if". Each `-W' flag is followed by a file name. The given
6504 files' modification times are recorded by `make' as being the
6505 present time, although the actual modification times remain the
6506 same. You can use the `-W' flag in conjunction with the `-n' flag
6507 to see what would happen if you were to modify specific files.
6509 With the `-n' flag, `make' prints the recipe that it would normally
6510 execute but usually does not execute it.
6512 With the `-t' flag, `make' ignores the recipes in the rules and uses
6513 (in effect) the command `touch' for each target that needs to be
6514 remade. The `touch' command is also printed, unless `-s' or `.SILENT'
6515 is used. For speed, `make' does not actually invoke the program
6516 `touch'. It does the work directly.
6518 With the `-q' flag, `make' prints nothing and executes no recipes,
6519 but the exit status code it returns is zero if and only if the targets
6520 to be considered are already up to date. If the exit status is one,
6521 then some updating needs to be done. If `make' encounters an error,
6522 the exit status is two, so you can distinguish an error from a target
6523 that is not up to date.
6525 It is an error to use more than one of these three flags in the same
6526 invocation of `make'.
6528 The `-n', `-t', and `-q' options do not affect recipe lines that
6529 begin with `+' characters or contain the strings `$(MAKE)' or
6530 `${MAKE}'. Note that only the line containing the `+' character or the
6531 strings `$(MAKE)' or `${MAKE}' is run regardless of these options.
6532 Other lines in the same rule are not run unless they too begin with `+'
6533 or contain `$(MAKE)' or `${MAKE}' (*Note How the `MAKE' Variable Works:
6536 The `-t' flag prevents phony targets (*note Phony Targets::) from
6537 being updated, unless there are recipe lines beginning with `+' or
6538 containing `$(MAKE)' or `${MAKE}'.
6540 The `-W' flag provides two features:
6542 * If you also use the `-n' or `-q' flag, you can see what `make'
6543 would do if you were to modify some files.
6545 * Without the `-n' or `-q' flag, when `make' is actually executing
6546 recipes, the `-W' flag can direct `make' to act as if some files
6547 had been modified, without actually running the recipes for those
6550 Note that the options `-p' and `-v' allow you to obtain other
6551 information about `make' or about the makefiles in use (*note Summary
6552 of Options: Options Summary.).
6555 File: make.info, Node: Avoiding Compilation, Next: Overriding, Prev: Instead of Execution, Up: Running
6557 9.4 Avoiding Recompilation of Some Files
6558 ========================================
6560 Sometimes you may have changed a source file but you do not want to
6561 recompile all the files that depend on it. For example, suppose you add
6562 a macro or a declaration to a header file that many other files depend
6563 on. Being conservative, `make' assumes that any change in the header
6564 file requires recompilation of all dependent files, but you know that
6565 they do not need to be recompiled and you would rather not waste the
6566 time waiting for them to compile.
6568 If you anticipate the problem before changing the header file, you
6569 can use the `-t' flag. This flag tells `make' not to run the recipes
6570 in the rules, but rather to mark the target up to date by changing its
6571 last-modification date. You would follow this procedure:
6573 1. Use the command `make' to recompile the source files that really
6574 need recompilation, ensuring that the object files are up-to-date
6577 2. Make the changes in the header files.
6579 3. Use the command `make -t' to mark all the object files as up to
6580 date. The next time you run `make', the changes in the header
6581 files will not cause any recompilation.
6583 If you have already changed the header file at a time when some files
6584 do need recompilation, it is too late to do this. Instead, you can use
6585 the `-o FILE' flag, which marks a specified file as "old" (*note
6586 Summary of Options: Options Summary.). This means that the file itself
6587 will not be remade, and nothing else will be remade on its account.
6588 Follow this procedure:
6590 1. Recompile the source files that need compilation for reasons
6591 independent of the particular header file, with `make -o
6592 HEADERFILE'. If several header files are involved, use a separate
6593 `-o' option for each header file.
6595 2. Touch all the object files with `make -t'.
6598 File: make.info, Node: Overriding, Next: Testing, Prev: Avoiding Compilation, Up: Running
6600 9.5 Overriding Variables
6601 ========================
6603 An argument that contains `=' specifies the value of a variable: `V=X'
6604 sets the value of the variable V to X. If you specify a value in this
6605 way, all ordinary assignments of the same variable in the makefile are
6606 ignored; we say they have been "overridden" by the command line
6609 The most common way to use this facility is to pass extra flags to
6610 compilers. For example, in a properly written makefile, the variable
6611 `CFLAGS' is included in each recipe that runs the C compiler, so a file
6612 `foo.c' would be compiled something like this:
6614 cc -c $(CFLAGS) foo.c
6616 Thus, whatever value you set for `CFLAGS' affects each compilation
6617 that occurs. The makefile probably specifies the usual value for
6618 `CFLAGS', like this:
6622 Each time you run `make', you can override this value if you wish.
6623 For example, if you say `make CFLAGS='-g -O'', each C compilation will
6624 be done with `cc -c -g -O'. (This also illustrates how you can use
6625 quoting in the shell to enclose spaces and other special characters in
6626 the value of a variable when you override it.)
6628 The variable `CFLAGS' is only one of many standard variables that
6629 exist just so that you can change them this way. *Note Variables Used
6630 by Implicit Rules: Implicit Variables, for a complete list.
6632 You can also program the makefile to look at additional variables of
6633 your own, giving the user the ability to control other aspects of how
6634 the makefile works by changing the variables.
6636 When you override a variable with a command line argument, you can
6637 define either a recursively-expanded variable or a simply-expanded
6638 variable. The examples shown above make a recursively-expanded
6639 variable; to make a simply-expanded variable, write `:=' instead of
6640 `='. But, unless you want to include a variable reference or function
6641 call in the _value_ that you specify, it makes no difference which kind
6642 of variable you create.
6644 There is one way that the makefile can change a variable that you
6645 have overridden. This is to use the `override' directive, which is a
6646 line that looks like this: `override VARIABLE = VALUE' (*note The
6647 `override' Directive: Override Directive.).
6650 File: make.info, Node: Testing, Next: Options Summary, Prev: Overriding, Up: Running
6652 9.6 Testing the Compilation of a Program
6653 ========================================
6655 Normally, when an error happens in executing a shell command, `make'
6656 gives up immediately, returning a nonzero status. No further recipes
6657 are executed for any target. The error implies that the goal cannot be
6658 correctly remade, and `make' reports this as soon as it knows.
6660 When you are compiling a program that you have just changed, this is
6661 not what you want. Instead, you would rather that `make' try compiling
6662 every file that can be tried, to show you as many compilation errors as
6665 On these occasions, you should use the `-k' or `--keep-going' flag.
6666 This tells `make' to continue to consider the other prerequisites of
6667 the pending targets, remaking them if necessary, before it gives up and
6668 returns nonzero status. For example, after an error in compiling one
6669 object file, `make -k' will continue compiling other object files even
6670 though it already knows that linking them will be impossible. In
6671 addition to continuing after failed shell commands, `make -k' will
6672 continue as much as possible after discovering that it does not know
6673 how to make a target or prerequisite file. This will always cause an
6674 error message, but without `-k', it is a fatal error (*note Summary of
6675 Options: Options Summary.).
6677 The usual behavior of `make' assumes that your purpose is to get the
6678 goals up to date; once `make' learns that this is impossible, it might
6679 as well report the failure immediately. The `-k' flag says that the
6680 real purpose is to test as much as possible of the changes made in the
6681 program, perhaps to find several independent problems so that you can
6682 correct them all before the next attempt to compile. This is why Emacs'
6683 `M-x compile' command passes the `-k' flag by default.
6686 File: make.info, Node: Options Summary, Prev: Testing, Up: Running
6688 9.7 Summary of Options
6689 ======================
6691 Here is a table of all the options `make' understands:
6695 These options are ignored for compatibility with other versions of
6700 Consider all targets out-of-date. GNU `make' proceeds to consider
6701 targets and their prerequisites using the normal algorithms;
6702 however, all targets so considered are always remade regardless of
6703 the status of their prerequisites. To avoid infinite recursion, if
6704 `MAKE_RESTARTS' (*note Other Special Variables: Special
6705 Variables.) is set to a number greater than 0 this option is
6706 disabled when considering whether to remake makefiles (*note How
6707 Makefiles Are Remade: Remaking Makefiles.).
6711 Change to directory DIR before reading the makefiles. If multiple
6712 `-C' options are specified, each is interpreted relative to the
6713 previous one: `-C / -C etc' is equivalent to `-C /etc'. This is
6714 typically used with recursive invocations of `make' (*note
6715 Recursive Use of `make': Recursion.).
6718 Print debugging information in addition to normal processing. The
6719 debugging information says which files are being considered for
6720 remaking, which file-times are being compared and with what
6721 results, which files actually need to be remade, which implicit
6722 rules are considered and which are applied--everything interesting
6723 about how `make' decides what to do. The `-d' option is
6724 equivalent to `--debug=a' (see below).
6727 Print debugging information in addition to normal processing.
6728 Various levels and types of output can be chosen. With no
6729 arguments, print the "basic" level of debugging. Possible
6730 arguments are below; only the first character is considered, and
6731 values must be comma- or space-separated.
6734 All types of debugging output are enabled. This is
6735 equivalent to using `-d'.
6738 Basic debugging prints each target that was found to be
6739 out-of-date, and whether the build was successful or not.
6742 A level above `basic'; includes messages about which
6743 makefiles were parsed, prerequisites that did not need to be
6744 rebuilt, etc. This option also enables `basic' messages.
6747 Prints messages describing the implicit rule searches for
6748 each target. This option also enables `basic' messages.
6751 Prints messages giving details on the invocation of specific
6755 By default, the above messages are not enabled while trying
6756 to remake the makefiles. This option enables messages while
6757 rebuilding makefiles, too. Note that the `all' option does
6758 enable this option. This option also enables `basic'
6762 `--environment-overrides'
6763 Give variables taken from the environment precedence over
6764 variables from makefiles. *Note Variables from the Environment:
6768 Evaluate STRING as makefile syntax. This is a command-line
6769 version of the `eval' function (*note Eval Function::). The
6770 evaluation is performed after the default rules and variables have
6771 been defined, but before any makefiles are read.
6776 Read the file named FILE as a makefile. *Note Writing Makefiles:
6781 Remind you of the options that `make' understands and then exit.
6785 Ignore all errors in recipes executed to remake files. *Note
6786 Errors in Recipes: Errors.
6790 Specifies a directory DIR to search for included makefiles. *Note
6791 Including Other Makefiles: Include. If several `-I' options are
6792 used to specify several directories, the directories are searched
6793 in the order specified.
6797 Specifies the number of recipes (jobs) to run simultaneously.
6798 With no argument, `make' runs as many recipes simultaneously as
6799 possible. If there is more than one `-j' option, the last one is
6800 effective. *Note Parallel Execution: Parallel, for more
6801 information on how recipes are run. Note that this option is
6806 Continue as much as possible after an error. While the target that
6807 failed, and those that depend on it, cannot be remade, the other
6808 prerequisites of these targets can be processed all the same.
6809 *Note Testing the Compilation of a Program: Testing.
6812 `--load-average[=LOAD]'
6814 Specifies that no new recipes should be started if there are other
6815 recipes running and the load average is at least LOAD (a
6816 floating-point number). With no argument, removes a previous load
6817 limit. *Note Parallel Execution: Parallel.
6820 `--check-symlink-times'
6821 On systems that support symbolic links, this option causes `make'
6822 to consider the timestamps on any symbolic links in addition to the
6823 timestamp on the file referenced by those links. When this option
6824 is provided, the most recent timestamp among the file and the
6825 symbolic links is taken as the modification time for this target
6832 Print the recipe that would be executed, but do not execute it
6833 (except in certain circumstances). *Note Instead of Executing
6834 Recipes: Instead of Execution.
6839 Do not remake the file FILE even if it is older than its
6840 prerequisites, and do not remake anything on account of changes in
6841 FILE. Essentially the file is treated as very old and its rules
6842 are ignored. *Note Avoiding Recompilation of Some Files: Avoiding
6847 Print the data base (rules and variable values) that results from
6848 reading the makefiles; then execute as usual or as otherwise
6849 specified. This also prints the version information given by the
6850 `-v' switch (see below). To print the data base without trying to
6851 remake any files, use `make -qp'. To print the data base of
6852 predefined rules and variables, use `make -p -f /dev/null'. The
6853 data base output contains filename and linenumber information for
6854 recipe and variable definitions, so it can be a useful debugging
6855 tool in complex environments.
6859 "Question mode". Do not run any recipes, or print anything; just
6860 return an exit status that is zero if the specified targets are
6861 already up to date, one if any remaking is required, or two if an
6862 error is encountered. *Note Instead of Executing Recipes: Instead
6866 `--no-builtin-rules'
6867 Eliminate use of the built-in implicit rules (*note Using Implicit
6868 Rules: Implicit Rules.). You can still define your own by writing
6869 pattern rules (*note Defining and Redefining Pattern Rules:
6870 Pattern Rules.). The `-r' option also clears out the default list
6871 of suffixes for suffix rules (*note Old-Fashioned Suffix Rules:
6872 Suffix Rules.). But you can still define your own suffixes with a
6873 rule for `.SUFFIXES', and then define your own suffix rules. Note
6874 that only _rules_ are affected by the `-r' option; default
6875 variables remain in effect (*note Variables Used by Implicit
6876 Rules: Implicit Variables.); see the `-R' option below.
6879 `--no-builtin-variables'
6880 Eliminate use of the built-in rule-specific variables (*note
6881 Variables Used by Implicit Rules: Implicit Variables.). You can
6882 still define your own, of course. The `-R' option also
6883 automatically enables the `-r' option (see above), since it
6884 doesn't make sense to have implicit rules without any definitions
6885 for the variables that they use.
6890 Silent operation; do not print the recipes as they are executed.
6891 *Note Recipe Echoing: Echoing.
6896 Cancel the effect of the `-k' option. This is never necessary
6897 except in a recursive `make' where `-k' might be inherited from
6898 the top-level `make' via `MAKEFLAGS' (*note Recursive Use of
6899 `make': Recursion.) or if you set `-k' in `MAKEFLAGS' in your
6904 Touch files (mark them up to date without really changing them)
6905 instead of running their recipes. This is used to pretend that the
6906 recipes were done, in order to fool future invocations of `make'.
6907 *Note Instead of Executing Recipes: Instead of Execution.
6911 Print the version of the `make' program plus a copyright, a list
6912 of authors, and a notice that there is no warranty; then exit.
6916 Print a message containing the working directory both before and
6917 after executing the makefile. This may be useful for tracking
6918 down errors from complicated nests of recursive `make' commands.
6919 *Note Recursive Use of `make': Recursion. (In practice, you
6920 rarely need to specify this option since `make' does it for you;
6921 see *note The `--print-directory' Option: -w Option.)
6923 `--no-print-directory'
6924 Disable printing of the working directory under `-w'. This option
6925 is useful when `-w' is turned on automatically, but you do not
6926 want to see the extra messages. *Note The `--print-directory'
6933 Pretend that the target FILE has just been modified. When used
6934 with the `-n' flag, this shows you what would happen if you were
6935 to modify that file. Without `-n', it is almost the same as
6936 running a `touch' command on the given file before running `make',
6937 except that the modification time is changed only in the
6938 imagination of `make'. *Note Instead of Executing Recipes:
6939 Instead of Execution.
6941 `--warn-undefined-variables'
6942 Issue a warning message whenever `make' sees a reference to an
6943 undefined variable. This can be helpful when you are trying to
6944 debug makefiles which use variables in complex ways.
6947 File: make.info, Node: Implicit Rules, Next: Archives, Prev: Running, Up: Top
6949 10 Using Implicit Rules
6950 ***********************
6952 Certain standard ways of remaking target files are used very often. For
6953 example, one customary way to make an object file is from a C source
6954 file using the C compiler, `cc'.
6956 "Implicit rules" tell `make' how to use customary techniques so that
6957 you do not have to specify them in detail when you want to use them.
6958 For example, there is an implicit rule for C compilation. File names
6959 determine which implicit rules are run. For example, C compilation
6960 typically takes a `.c' file and makes a `.o' file. So `make' applies
6961 the implicit rule for C compilation when it sees this combination of
6964 A chain of implicit rules can apply in sequence; for example, `make'
6965 will remake a `.o' file from a `.y' file by way of a `.c' file.
6967 The built-in implicit rules use several variables in their recipes so
6968 that, by changing the values of the variables, you can change the way
6969 the implicit rule works. For example, the variable `CFLAGS' controls
6970 the flags given to the C compiler by the implicit rule for C
6973 You can define your own implicit rules by writing "pattern rules".
6975 "Suffix rules" are a more limited way to define implicit rules.
6976 Pattern rules are more general and clearer, but suffix rules are
6977 retained for compatibility.
6981 * Using Implicit:: How to use an existing implicit rule
6982 to get the recipes for updating a file.
6983 * Catalogue of Rules:: A list of built-in implicit rules.
6984 * Implicit Variables:: How to change what predefined rules do.
6985 * Chained Rules:: How to use a chain of implicit rules.
6986 * Pattern Rules:: How to define new implicit rules.
6987 * Last Resort:: How to define recipes for rules which
6989 * Suffix Rules:: The old-fashioned style of implicit rule.
6990 * Implicit Rule Search:: The precise algorithm for applying
6994 File: make.info, Node: Using Implicit, Next: Catalogue of Rules, Prev: Implicit Rules, Up: Implicit Rules
6996 10.1 Using Implicit Rules
6997 =========================
6999 To allow `make' to find a customary method for updating a target file,
7000 all you have to do is refrain from specifying recipes yourself. Either
7001 write a rule with no recipe, or don't write a rule at all. Then `make'
7002 will figure out which implicit rule to use based on which kind of
7003 source file exists or can be made.
7005 For example, suppose the makefile looks like this:
7008 cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
7010 Because you mention `foo.o' but do not give a rule for it, `make' will
7011 automatically look for an implicit rule that tells how to update it.
7012 This happens whether or not the file `foo.o' currently exists.
7014 If an implicit rule is found, it can supply both a recipe and one or
7015 more prerequisites (the source files). You would want to write a rule
7016 for `foo.o' with no recipe if you need to specify additional
7017 prerequisites, such as header files, that the implicit rule cannot
7020 Each implicit rule has a target pattern and prerequisite patterns.
7021 There may be many implicit rules with the same target pattern. For
7022 example, numerous rules make `.o' files: one, from a `.c' file with the
7023 C compiler; another, from a `.p' file with the Pascal compiler; and so
7024 on. The rule that actually applies is the one whose prerequisites
7025 exist or can be made. So, if you have a file `foo.c', `make' will run
7026 the C compiler; otherwise, if you have a file `foo.p', `make' will run
7027 the Pascal compiler; and so on.
7029 Of course, when you write the makefile, you know which implicit rule
7030 you want `make' to use, and you know it will choose that one because you
7031 know which possible prerequisite files are supposed to exist. *Note
7032 Catalogue of Implicit Rules: Catalogue of Rules, for a catalogue of all
7033 the predefined implicit rules.
7035 Above, we said an implicit rule applies if the required
7036 prerequisites "exist or can be made". A file "can be made" if it is
7037 mentioned explicitly in the makefile as a target or a prerequisite, or
7038 if an implicit rule can be recursively found for how to make it. When
7039 an implicit prerequisite is the result of another implicit rule, we say
7040 that "chaining" is occurring. *Note Chains of Implicit Rules: Chained
7043 In general, `make' searches for an implicit rule for each target, and
7044 for each double-colon rule, that has no recipe. A file that is
7045 mentioned only as a prerequisite is considered a target whose rule
7046 specifies nothing, so implicit rule search happens for it. *Note
7047 Implicit Rule Search Algorithm: Implicit Rule Search, for the details
7048 of how the search is done.
7050 Note that explicit prerequisites do not influence implicit rule
7051 search. For example, consider this explicit rule:
7055 The prerequisite on `foo.p' does not necessarily mean that `make' will
7056 remake `foo.o' according to the implicit rule to make an object file, a
7057 `.o' file, from a Pascal source file, a `.p' file. For example, if
7058 `foo.c' also exists, the implicit rule to make an object file from a C
7059 source file is used instead, because it appears before the Pascal rule
7060 in the list of predefined implicit rules (*note Catalogue of Implicit
7061 Rules: Catalogue of Rules.).
7063 If you do not want an implicit rule to be used for a target that has
7064 no recipe, you can give that target an empty recipe by writing a
7065 semicolon (*note Defining Empty Recipes: Empty Recipes.).