1 This is make.info, produced by makeinfo version 6.6 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, and
5 issues the commands to recompile them.
7 This is Edition 0.75, last updated 19 January 2020, of 'The GNU Make
8 Manual', for GNU 'make' version 4.3.
10 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
11 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
12 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Free
13 Software Foundation, Inc.
15 Permission is granted to copy, distribute and/or modify this
16 document under the terms of the GNU Free Documentation License,
17 Version 1.3 or any later version published by the Free Software
18 Foundation; with no Invariant Sections, with the Front-Cover Texts
19 being "A GNU Manual," and with the Back-Cover Texts as in (a)
20 below. A copy of the license is included in the section entitled
21 "GNU Free Documentation License."
23 (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
24 modify this GNU manual. Buying copies from the FSF supports it in
25 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, and
39 issues the commands to recompile them.
41 This is Edition 0.75, last updated 19 January 2020, of 'The GNU Make
42 Manual', for GNU 'make' version 4.3.
44 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
45 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
46 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Free
47 Software Foundation, Inc.
49 Permission is granted to copy, distribute and/or modify this
50 document under the terms of the GNU Free Documentation License,
51 Version 1.3 or any later version published by the Free Software
52 Foundation; with no Invariant Sections, with the Front-Cover Texts
53 being "A GNU Manual," and with the Back-Cover Texts as in (a)
54 below. A copy of the license is included in the section entitled
55 "GNU Free Documentation License."
57 (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
58 modify this GNU manual. Buying copies from the FSF supports it in
59 developing GNU and promoting software freedom."
63 * Overview:: Overview of 'make'.
64 * Introduction:: An introduction to 'make'.
65 * Makefiles:: Makefiles tell 'make' what to do.
66 * Rules:: Rules describe when a file must be remade.
67 * Recipes:: Recipes say how to remake a file.
68 * Using Variables:: You can use variables to avoid repetition.
69 * Conditionals:: Use or ignore parts of the makefile based
70 on the values of variables.
71 * Functions:: Many powerful ways to manipulate text.
72 * Invoking make: Running. How to invoke 'make' on the command line.
73 * Implicit Rules:: Use implicit rules to treat many files alike,
74 based on their file names.
75 * Archives:: How 'make' can update library archives.
76 * Extending make:: Using extensions to 'make'.
77 * Integrating make:: Integrating 'make' with other tools.
78 * Features:: Features GNU 'make' has over other 'make's.
79 * Missing:: What GNU 'make' lacks from other 'make's.
80 * Makefile Conventions:: Conventions for writing makefiles for
82 * Quick Reference:: A quick reference for experienced users.
83 * Error Messages:: A list of common errors generated by 'make'.
84 * Complex Makefile:: A real example of a straightforward,
85 but nontrivial, makefile.
87 * GNU Free Documentation License:: License for copying this manual.
88 * Concept Index:: Index of Concepts.
89 * Name Index:: Index of Functions, Variables, & Directives.
91 -- The Detailed Node Listing --
95 * Preparing:: Preparing and running 'make'.
96 * Reading:: On reading this text.
97 * Bugs:: Problems and bugs.
99 An Introduction to Makefiles
101 * Rule Introduction:: What a rule looks like.
102 * Simple Makefile:: A simple makefile.
103 * How Make Works:: How 'make' processes this makefile.
104 * Variables Simplify:: Variables make makefiles simpler.
105 * make Deduces:: Letting 'make' deduce the recipes.
106 * Combine By Prerequisite:: Another style of makefile.
107 * Cleanup:: Rules for cleaning the directory.
111 * Makefile Contents:: What makefiles contain.
112 * Makefile Names:: How to name your makefile.
113 * Include:: How one makefile can use another makefile.
114 * MAKEFILES Variable:: The environment can specify extra makefiles.
115 * Remaking Makefiles:: How makefiles get remade.
116 * Overriding Makefiles:: How to override part of one makefile
117 with another makefile.
118 * Reading Makefiles:: How makefiles are read in.
119 * Parsing Makefiles:: How makefiles are parsed.
120 * Secondary Expansion:: How and when secondary expansion is performed.
122 What Makefiles Contain
124 * Splitting Lines:: Splitting long lines in makefiles
128 * Rule Example:: An example explained.
129 * Rule Syntax:: General syntax explained.
130 * Prerequisite Types:: There are two types of prerequisites.
131 * Wildcards:: Using wildcard characters such as '*'.
132 * Directory Search:: Searching other directories for source files.
133 * Phony Targets:: Using a target that is not a real file's name.
134 * Force Targets:: You can use a target without a recipe
135 or prerequisites to mark other targets
137 * Empty Targets:: When only the date matters and the
139 * Special Targets:: Targets with special built-in meanings.
140 * Multiple Targets:: When to make use of several targets in a rule.
141 * Multiple Rules:: How to use several rules with the same target.
142 * Static Pattern:: Static pattern rules apply to multiple targets
143 and can vary the prerequisites according to
145 * Double-Colon:: How to use a special kind of rule to allow
146 several independent rules for one target.
147 * Automatic Prerequisites:: How to automatically generate rules giving
148 prerequisites from source files themselves.
150 Using Wildcard Characters in File Names
152 * Wildcard Examples:: Several examples.
153 * Wildcard Pitfall:: Problems to avoid.
154 * Wildcard Function:: How to cause wildcard expansion where
155 it does not normally take place.
157 Searching Directories for Prerequisites
159 * General Search:: Specifying a search path that applies
160 to every prerequisite.
161 * Selective Search:: Specifying a search path
162 for a specified class of names.
163 * Search Algorithm:: When and how search paths are applied.
164 * Recipes/Search:: How to write recipes that work together
166 * Implicit/Search:: How search paths affect implicit rules.
167 * Libraries/Search:: Directory search for link libraries.
171 * Static Usage:: The syntax of static pattern rules.
172 * Static versus Implicit:: When are they better than implicit rules?
174 Writing Recipes in Rules
176 * Recipe Syntax:: Recipe syntax features and pitfalls.
177 * Echoing:: How to control when recipes are echoed.
178 * Execution:: How recipes are executed.
179 * Parallel:: How recipes can be executed in parallel.
180 * Errors:: What happens after a recipe execution error.
181 * Interrupts:: What happens when a recipe is interrupted.
182 * Recursion:: Invoking 'make' from makefiles.
183 * Canned Recipes:: Defining canned recipes.
184 * Empty Recipes:: Defining useful, do-nothing recipes.
188 * Splitting Recipe Lines:: Breaking long recipe lines for readability.
189 * Variables in Recipes:: Using 'make' variables in recipes.
193 * One Shell:: One shell for all lines in a recipe.
194 * Choosing the Shell:: How 'make' chooses the shell used
199 * Parallel Output:: Handling output during parallel execution
200 * Parallel Input:: Handling input during parallel execution
202 Recursive Use of 'make'
204 * MAKE Variable:: The special effects of using '$(MAKE)'.
205 * Variables/Recursion:: How to communicate variables to a sub-'make'.
206 * Options/Recursion:: How to communicate options to a sub-'make'.
207 * -w Option:: How the '-w' or '--print-directory' option
208 helps debug use of recursive 'make' commands.
212 * Reference:: How to use the value of a variable.
213 * Flavors:: Variables come in two flavors.
214 * Advanced:: Advanced features for referencing a variable.
215 * Values:: All the ways variables get their values.
216 * Setting:: How to set a variable in the makefile.
217 * Appending:: How to append more text to the old value
219 * Override Directive:: How to set a variable in the makefile even if
220 the user has set it with a command argument.
221 * Multi-Line:: An alternate way to set a variable
222 to a multi-line string.
223 * Undefine Directive:: How to undefine a variable so that it appears
224 as if it was never set.
225 * Environment:: Variable values can come from the environment.
226 * Target-specific:: Variable values can be defined on a per-target
228 * Pattern-specific:: Target-specific variable values can be applied
229 to a group of targets that match a pattern.
230 * Suppressing Inheritance:: Suppress inheritance of variables.
231 * Special Variables:: Variables with special meaning or behavior.
233 Advanced Features for Reference to Variables
235 * Substitution Refs:: Referencing a variable with
236 substitutions on the value.
237 * Computed Names:: Computing the name of the variable to refer to.
239 Conditional Parts of Makefiles
241 * Conditional Example:: Example of a conditional
242 * Conditional Syntax:: The syntax of conditionals.
243 * Testing Flags:: Conditionals that test flags.
245 Functions for Transforming Text
247 * Syntax of Functions:: How to write a function call.
248 * Text Functions:: General-purpose text manipulation functions.
249 * File Name Functions:: Functions for manipulating file names.
250 * Conditional Functions:: Functions that implement conditions.
251 * Foreach Function:: Repeat some text with controlled variation.
252 * File Function:: Write text to a file.
253 * Call Function:: Expand a user-defined function.
254 * Value Function:: Return the un-expanded value of a variable.
255 * Eval Function:: Evaluate the arguments as makefile syntax.
256 * Origin Function:: Find where a variable got its value.
257 * Flavor Function:: Find out the flavor of a variable.
258 * Make Control Functions:: Functions that control how make runs.
259 * Shell Function:: Substitute the output of a shell command.
260 * Guile Function:: Use GNU Guile embedded scripting language.
264 * Makefile Arguments:: How to specify which makefile to use.
265 * Goals:: How to use goal arguments to specify which
266 parts of the makefile to use.
267 * Instead of Execution:: How to use mode flags to specify what
268 kind of thing to do with the recipes
269 in the makefile other than simply
271 * Avoiding Compilation:: How to avoid recompiling certain files.
272 * Overriding:: How to override a variable to specify
273 an alternate compiler and other things.
274 * Testing:: How to proceed past some errors, to
276 * Options Summary:: Summary of Options
280 * Using Implicit:: How to use an existing implicit rule
281 to get the recipes for updating a file.
282 * Catalogue of Rules:: A list of built-in rules.
283 * Implicit Variables:: How to change what predefined rules do.
284 * Chained Rules:: How to use a chain of implicit rules.
285 * Pattern Rules:: How to define new implicit rules.
286 * Last Resort:: How to define a recipe for rules which
288 * Suffix Rules:: The old-fashioned style of implicit rule.
289 * Implicit Rule Search:: The precise algorithm for applying
292 Defining and Redefining Pattern Rules
294 * Pattern Intro:: An introduction to pattern rules.
295 * Pattern Examples:: Examples of pattern rules.
296 * Automatic Variables:: How to use automatic variables in the
297 recipe of implicit rules.
298 * Pattern Match:: How patterns match.
299 * Match-Anything Rules:: Precautions you should take prior to
300 defining rules that can match any
301 target file whatever.
302 * Canceling Rules:: How to override or cancel built-in rules.
304 Using 'make' to Update Archive Files
306 * Archive Members:: Archive members as targets.
307 * Archive Update:: The implicit rule for archive member targets.
308 * Archive Pitfalls:: Dangers to watch out for when using archives.
309 * Archive Suffix Rules:: You can write a special kind of suffix rule
310 for updating archives.
312 Implicit Rule for Archive Member Targets
314 * Archive Symbols:: How to update archive symbol directories.
318 * Guile Integration:: Using Guile as an embedded scripting language.
319 * Loading Objects:: Loading dynamic objects as extensions.
321 GNU Guile Integration
323 * Guile Types:: Converting Guile types to 'make' strings.
324 * Guile Interface:: Invoking 'make' functions from Guile.
325 * Guile Example:: Example using Guile in 'make'.
327 Loading Dynamic Objects
329 * load Directive:: Loading dynamic objects as extensions.
330 * Remaking Loaded Objects:: How loaded objects get remade.
331 * Loaded Object API:: Programmatic interface for loaded objects.
332 * Loaded Object Example:: Example of a loaded object
334 Integrating GNU 'make'
336 * Job Slots:: Share job slots with GNU 'make'.
337 * Terminal Output:: Control output to terminals.
339 Sharing Job Slots with GNU 'make'
341 * POSIX Jobserver:: Using the jobserver on POSIX systems.
342 * Windows Jobserver:: Using the jobserver on Windows systems.
346 File: make.info, Node: Overview, Next: Introduction, Prev: Top, Up: Top
351 The 'make' utility automatically determines which pieces of a large
352 program need to be recompiled, and issues commands to recompile them.
353 This manual describes GNU 'make', which was implemented by Richard
354 Stallman and Roland McGrath. Development since Version 3.76 has been
355 handled by Paul D. Smith.
357 GNU 'make' conforms to section 6.2 of 'IEEE Standard 1003.2-1992'
360 Our examples show C programs, since they are most common, but you can
361 use 'make' with any programming language whose compiler can be run with
362 a shell command. Indeed, 'make' is not limited to programs. You can
363 use it to describe any task where some files must be updated
364 automatically from others whenever the others change.
368 * Preparing:: Preparing and running 'make'.
369 * Reading:: On reading this text.
370 * Bugs:: Problems and bugs.
373 File: make.info, Node: Preparing, Next: Reading, Prev: Overview, Up: Overview
375 Preparing and Running Make
376 ==========================
378 To prepare to use 'make', you must write a file called the "makefile"
379 that describes the relationships among files in your program and
380 provides commands for updating each file. In a program, typically, the
381 executable file is updated from object files, which are in turn made by
382 compiling source files.
384 Once a suitable makefile exists, each time you change some source
385 files, this simple shell command:
389 suffices to perform all necessary recompilations. The 'make' program
390 uses the makefile data base and the last-modification times of the files
391 to decide which of the files need to be updated. For each of those
392 files, it issues the recipes recorded in the data base.
394 You can provide command line arguments to 'make' to control which
395 files should be recompiled, or how. *Note How to Run 'make': Running.
398 File: make.info, Node: Reading, Next: Bugs, Prev: Preparing, Up: Overview
400 1.1 How to Read This Manual
401 ===========================
403 If you are new to 'make', or are looking for a general introduction,
404 read the first few sections of each chapter, skipping the later
405 sections. In each chapter, the first few sections contain introductory
406 or general information and the later sections contain specialized or
407 technical information. The exception is the second chapter, *note An
408 Introduction to Makefiles: Introduction, all of which is introductory.
410 If you are familiar with other 'make' programs, see *note Features of
411 GNU 'make': Features, which lists the enhancements GNU 'make' has, and
412 *note Incompatibilities and Missing Features: Missing, which explains
413 the few things GNU 'make' lacks that others have.
415 For a quick summary, see *note Options Summary::, *note Quick
416 Reference::, and *note Special Targets::.
419 File: make.info, Node: Bugs, Prev: Reading, Up: Overview
421 1.2 Problems and Bugs
422 =====================
424 If you have problems with GNU 'make' or think you've found a bug, please
425 report it to the developers; we cannot promise to do anything but we
426 might well want to fix it.
428 Before reporting a bug, make sure you've actually found a real bug.
429 Carefully reread the documentation and see if it really says you can do
430 what you're trying to do. If it's not clear whether you should be able
431 to do something or not, report that too; it's a bug in the
434 Before reporting a bug or trying to fix it yourself, try to isolate
435 it to the smallest possible makefile that reproduces the problem. Then
436 send us the makefile and the exact results 'make' gave you, including
437 any error or warning messages. Please don't paraphrase these messages:
438 it's best to cut and paste them into your report. When generating this
439 small makefile, be sure to not use any non-free or unusual tools in your
440 recipes: you can almost always emulate what such a tool would do with
441 simple shell commands. Finally, be sure to explain what you expected to
442 occur; this will help us decide whether the problem was really in the
445 Once you have a precise problem you can report it in one of two ways.
446 Either send electronic mail to:
450 or use our Web-based project management tool, at:
452 http://savannah.gnu.org/projects/make/
454 In addition to the information above, please be careful to include the
455 version number of 'make' you are using. You can get this information
456 with the command 'make --version'. Be sure also to include the type of
457 machine and operating system you are using. One way to obtain this
458 information is by looking at the final lines of output from the command
462 File: make.info, Node: Introduction, Next: Makefiles, Prev: Overview, Up: Top
464 2 An Introduction to Makefiles
465 ******************************
467 You need a file called a "makefile" to tell 'make' what to do. Most
468 often, the makefile tells 'make' how to compile and link a program.
470 In this chapter, we will discuss a simple makefile that describes how
471 to compile and link a text editor which consists of eight C source files
472 and three header files. The makefile can also tell 'make' how to run
473 miscellaneous commands when explicitly asked (for example, to remove
474 certain files as a clean-up operation). To see a more complex example
475 of a makefile, see *note Complex Makefile::.
477 When 'make' recompiles the editor, each changed C source file must be
478 recompiled. If a header file has changed, each C source file that
479 includes the header file must be recompiled to be safe. Each
480 compilation produces an object file corresponding to the source file.
481 Finally, if any source file has been recompiled, all the object files,
482 whether newly made or saved from previous compilations, must be linked
483 together to produce the new executable editor.
487 * Rule Introduction:: What a rule looks like.
488 * Simple Makefile:: A simple makefile.
489 * How Make Works:: How 'make' processes this makefile.
490 * Variables Simplify:: Variables make makefiles simpler.
491 * make Deduces:: Letting 'make' deduce the recipes.
492 * Combine By Prerequisite:: Another style of makefile.
493 * Cleanup:: Rules for cleaning the directory.
496 File: make.info, Node: Rule Introduction, Next: Simple Makefile, Prev: Introduction, Up: Introduction
498 2.1 What a Rule Looks Like
499 ==========================
501 A simple makefile consists of "rules" with the following shape:
503 TARGET ... : PREREQUISITES ...
508 A "target" is usually the name of a file that is generated by a
509 program; examples of targets are executable or object files. A target
510 can also be the name of an action to carry out, such as 'clean' (*note
513 A "prerequisite" is a file that is used as input to create the
514 target. A target often depends on several files.
516 A "recipe" is an action that 'make' carries out. A recipe may have
517 more than one command, either on the same line or each on its own line.
518 *Please note:* you need to put a tab character at the beginning of every
519 recipe line! This is an obscurity that catches the unwary. If you
520 prefer to prefix your recipes with a character other than tab, you can
521 set the '.RECIPEPREFIX' variable to an alternate character (*note
522 Special Variables::).
524 Usually a recipe is in a rule with prerequisites and serves to create
525 a target file if any of the prerequisites change. However, the rule
526 that specifies a recipe for the target need not have prerequisites. For
527 example, the rule containing the delete command associated with the
528 target 'clean' does not have prerequisites.
530 A "rule", then, explains how and when to remake certain files which
531 are the targets of the particular rule. 'make' carries out the recipe
532 on the prerequisites to create or update the target. A rule can also
533 explain how and when to carry out an action. *Note Writing Rules:
536 A makefile may contain other text besides rules, but a simple
537 makefile need only contain rules. Rules may look somewhat more
538 complicated than shown in this template, but all fit the pattern more or
542 File: make.info, Node: Simple Makefile, Next: How Make Works, Prev: Rule Introduction, Up: Introduction
544 2.2 A Simple Makefile
545 =====================
547 Here is a straightforward makefile that describes the way an executable
548 file called 'edit' depends on eight object files which, in turn, depend
549 on eight C source and three header files.
551 In this example, all the C files include 'defs.h', but only those
552 defining editing commands include 'command.h', and only low level files
553 that change the editor buffer include 'buffer.h'.
555 edit : main.o kbd.o command.o display.o \
556 insert.o search.o files.o utils.o
557 cc -o edit main.o kbd.o command.o display.o \
558 insert.o search.o files.o utils.o
560 main.o : main.c defs.h
562 kbd.o : kbd.c defs.h command.h
564 command.o : command.c defs.h command.h
566 display.o : display.c defs.h buffer.h
568 insert.o : insert.c defs.h buffer.h
570 search.o : search.c defs.h buffer.h
572 files.o : files.c defs.h buffer.h command.h
574 utils.o : utils.c defs.h
577 rm edit main.o kbd.o command.o display.o \
578 insert.o search.o files.o utils.o
580 We split each long line into two lines using backslash/newline; this is
581 like using one long line, but is easier to read. *Note Splitting Long
582 Lines: Splitting Lines.
584 To use this makefile to create the executable file called 'edit',
589 To use this makefile to delete the executable file and all the object
590 files from the directory, type:
594 In the example makefile, the targets include the executable file
595 'edit', and the object files 'main.o' and 'kbd.o'. The prerequisites
596 are files such as 'main.c' and 'defs.h'. In fact, each '.o' file is
597 both a target and a prerequisite. Recipes include 'cc -c main.c' and
600 When a target is a file, it needs to be recompiled or relinked if any
601 of its prerequisites change. In addition, any prerequisites that are
602 themselves automatically generated should be updated first. In this
603 example, 'edit' depends on each of the eight object files; the object
604 file 'main.o' depends on the source file 'main.c' and on the header file
607 A recipe may follow each line that contains a target and
608 prerequisites. These recipes say how to update the target file. A tab
609 character (or whatever character is specified by the '.RECIPEPREFIX'
610 variable; *note Special Variables::) must come at the beginning of every
611 line in the recipe to distinguish recipes from other lines in the
612 makefile. (Bear in mind that 'make' does not know anything about how
613 the recipes work. It is up to you to supply recipes that will update
614 the target file properly. All 'make' does is execute the recipe you
615 have specified when the target file needs to be updated.)
617 The target 'clean' is not a file, but merely the name of an action.
618 Since you normally do not want to carry out the actions in this rule,
619 'clean' is not a prerequisite of any other rule. Consequently, 'make'
620 never does anything with it unless you tell it specifically. Note that
621 this rule not only is not a prerequisite, it also does not have any
622 prerequisites, so the only purpose of the rule is to run the specified
623 recipe. Targets that do not refer to files but are just actions are
624 called "phony targets". *Note Phony Targets::, for information about
625 this kind of target. *Note Errors in Recipes: Errors, to see how to
626 cause 'make' to ignore errors from 'rm' or any other command.
629 File: make.info, Node: How Make Works, Next: Variables Simplify, Prev: Simple Makefile, Up: Introduction
631 2.3 How 'make' Processes a Makefile
632 ===================================
634 By default, 'make' starts with the first target (not targets whose names
635 start with '.'). This is called the "default goal". ("Goals" are the
636 targets that 'make' strives ultimately to update. You can override this
637 behavior using the command line (*note Arguments to Specify the Goals:
638 Goals.) or with the '.DEFAULT_GOAL' special variable (*note Other
639 Special Variables: Special Variables.).
641 In the simple example of the previous section, the default goal is to
642 update the executable program 'edit'; therefore, we put that rule first.
644 Thus, when you give the command:
648 'make' reads the makefile in the current directory and begins by
649 processing the first rule. In the example, this rule is for relinking
650 'edit'; but before 'make' can fully process this rule, it must process
651 the rules for the files that 'edit' depends on, which in this case are
652 the object files. Each of these files is processed according to its own
653 rule. These rules say to update each '.o' file by compiling its source
654 file. The recompilation must be done if the source file, or any of the
655 header files named as prerequisites, is more recent than the object
656 file, or if the object file does not exist.
658 The other rules are processed because their targets appear as
659 prerequisites of the goal. If some other rule is not depended on by the
660 goal (or anything it depends on, etc.), that rule is not processed,
661 unless you tell 'make' to do so (with a command such as 'make clean').
663 Before recompiling an object file, 'make' considers updating its
664 prerequisites, the source file and header files. This makefile does not
665 specify anything to be done for them--the '.c' and '.h' files are not
666 the targets of any rules--so 'make' does nothing for these files. But
667 'make' would update automatically generated C programs, such as those
668 made by Bison or Yacc, by their own rules at this time.
670 After recompiling whichever object files need it, 'make' decides
671 whether to relink 'edit'. This must be done if the file 'edit' does not
672 exist, or if any of the object files are newer than it. If an object
673 file was just recompiled, it is now newer than 'edit', so 'edit' is
676 Thus, if we change the file 'insert.c' and run 'make', 'make' will
677 compile that file to update 'insert.o', and then link 'edit'. If we
678 change the file 'command.h' and run 'make', 'make' will recompile the
679 object files 'kbd.o', 'command.o' and 'files.o' and then link the file
683 File: make.info, Node: Variables Simplify, Next: make Deduces, Prev: How Make Works, Up: Introduction
685 2.4 Variables Make Makefiles Simpler
686 ====================================
688 In our example, we had to list all the object files twice in the rule
689 for 'edit' (repeated here):
691 edit : main.o kbd.o command.o display.o \
692 insert.o search.o files.o utils.o
693 cc -o edit main.o kbd.o command.o display.o \
694 insert.o search.o files.o utils.o
696 Such duplication is error-prone; if a new object file is added to the
697 system, we might add it to one list and forget the other. We can
698 eliminate the risk and simplify the makefile by using a variable.
699 "Variables" allow a text string to be defined once and substituted in
700 multiple places later (*note How to Use Variables: Using Variables.).
702 It is standard practice for every makefile to have a variable named
703 'objects', 'OBJECTS', 'objs', 'OBJS', 'obj', or 'OBJ' which is a list of
704 all object file names. We would define such a variable 'objects' with a
705 line like this in the makefile:
707 objects = main.o kbd.o command.o display.o \
708 insert.o search.o files.o utils.o
710 Then, each place we want to put a list of the object file names, we can
711 substitute the variable's value by writing '$(objects)' (*note How to
712 Use Variables: Using Variables.).
714 Here is how the complete simple makefile looks when you use a
715 variable for the object files:
717 objects = main.o kbd.o command.o display.o \
718 insert.o search.o files.o utils.o
721 cc -o edit $(objects)
722 main.o : main.c defs.h
724 kbd.o : kbd.c defs.h command.h
726 command.o : command.c defs.h command.h
728 display.o : display.c defs.h buffer.h
730 insert.o : insert.c defs.h buffer.h
732 search.o : search.c defs.h buffer.h
734 files.o : files.c defs.h buffer.h command.h
736 utils.o : utils.c defs.h
742 File: make.info, Node: make Deduces, Next: Combine By Prerequisite, Prev: Variables Simplify, Up: Introduction
744 2.5 Letting 'make' Deduce the Recipes
745 =====================================
747 It is not necessary to spell out the recipes for compiling the
748 individual C source files, because 'make' can figure them out: it has an
749 "implicit rule" for updating a '.o' file from a correspondingly named
750 '.c' file using a 'cc -c' command. For example, it will use the recipe
751 'cc -c main.c -o main.o' to compile 'main.c' into 'main.o'. We can
752 therefore omit the recipes from the rules for the object files. *Note
753 Using Implicit Rules: Implicit Rules.
755 When a '.c' file is used automatically in this way, it is also
756 automatically added to the list of prerequisites. We can therefore omit
757 the '.c' files from the prerequisites, provided we omit the recipe.
759 Here is the entire example, with both of these changes, and a
760 variable 'objects' as suggested above:
762 objects = main.o kbd.o command.o display.o \
763 insert.o search.o files.o utils.o
766 cc -o edit $(objects)
769 kbd.o : defs.h command.h
770 command.o : defs.h command.h
771 display.o : defs.h buffer.h
772 insert.o : defs.h buffer.h
773 search.o : defs.h buffer.h
774 files.o : defs.h buffer.h command.h
781 This is how we would write the makefile in actual practice. (The
782 complications associated with 'clean' are described elsewhere. See
783 *note Phony Targets::, and *note Errors in Recipes: Errors.)
785 Because implicit rules are so convenient, they are important. You
786 will see them used frequently.
789 File: make.info, Node: Combine By Prerequisite, Next: Cleanup, Prev: make Deduces, Up: Introduction
791 2.6 Another Style of Makefile
792 =============================
794 When the objects of a makefile are created only by implicit rules, an
795 alternative style of makefile is possible. In this style of makefile,
796 you group entries by their prerequisites instead of by their targets.
797 Here is what one looks like:
799 objects = main.o kbd.o command.o display.o \
800 insert.o search.o files.o utils.o
803 cc -o edit $(objects)
806 kbd.o command.o files.o : command.h
807 display.o insert.o search.o files.o : buffer.h
809 Here 'defs.h' is given as a prerequisite of all the object files;
810 'command.h' and 'buffer.h' are prerequisites of the specific object
811 files listed for them.
813 Whether this is better is a matter of taste: it is more compact, but
814 some people dislike it because they find it clearer to put all the
815 information about each target in one place.
818 File: make.info, Node: Cleanup, Prev: Combine By Prerequisite, Up: Introduction
820 2.7 Rules for Cleaning the Directory
821 ====================================
823 Compiling a program is not the only thing you might want to write rules
824 for. Makefiles commonly tell how to do a few other things besides
825 compiling a program: for example, how to delete all the object files and
826 executables so that the directory is 'clean'.
828 Here is how we could write a 'make' rule for cleaning our example
834 In practice, we might want to write the rule in a somewhat more
835 complicated manner to handle unanticipated situations. We would do
842 This prevents 'make' from getting confused by an actual file called
843 'clean' and causes it to continue in spite of errors from 'rm'. (See
844 *note Phony Targets::, and *note Errors in Recipes: Errors.)
846 A rule such as this should not be placed at the beginning of the
847 makefile, because we do not want it to run by default! Thus, in the
848 example makefile, we want the rule for 'edit', which recompiles the
849 editor, to remain the default goal.
851 Since 'clean' is not a prerequisite of 'edit', this rule will not run
852 at all if we give the command 'make' with no arguments. In order to
853 make the rule run, we have to type 'make clean'. *Note How to Run
857 File: make.info, Node: Makefiles, Next: Rules, Prev: Introduction, Up: Top
862 The information that tells 'make' how to recompile a system comes from
863 reading a data base called the "makefile".
867 * Makefile Contents:: What makefiles contain.
868 * Makefile Names:: How to name your makefile.
869 * Include:: How one makefile can use another makefile.
870 * MAKEFILES Variable:: The environment can specify extra makefiles.
871 * Remaking Makefiles:: How makefiles get remade.
872 * Overriding Makefiles:: How to override part of one makefile
873 with another makefile.
874 * Reading Makefiles:: How makefiles are read in.
875 * Parsing Makefiles:: How makefiles are parsed.
876 * Secondary Expansion:: How and when secondary expansion is performed.
879 File: make.info, Node: Makefile Contents, Next: Makefile Names, Prev: Makefiles, Up: Makefiles
881 3.1 What Makefiles Contain
882 ==========================
884 Makefiles contain five kinds of things: "explicit rules", "implicit
885 rules", "variable definitions", "directives", and "comments". Rules,
886 variables, and directives are described at length in later chapters.
888 * An "explicit rule" says when and how to remake one or more files,
889 called the rule's "targets". It lists the other files that the
890 targets depend on, called the "prerequisites" of the target, and
891 may also give a recipe to use to create or update the targets.
892 *Note Writing Rules: Rules.
894 * An "implicit rule" says when and how to remake a class of files
895 based on their names. It describes how a target may depend on a
896 file with a name similar to the target and gives a recipe to create
897 or update such a target. *Note Using Implicit Rules: Implicit
900 * A "variable definition" is a line that specifies a text string
901 value for a variable that can be substituted into the text later.
902 The simple makefile example shows a variable definition for
903 'objects' as a list of all object files (*note Variables Make
904 Makefiles Simpler: Variables Simplify.).
906 * A "directive" is an instruction for 'make' to do something special
907 while reading the makefile. These include:
909 * Reading another makefile (*note Including Other Makefiles:
912 * Deciding (based on the values of variables) whether to use or
913 ignore a part of the makefile (*note Conditional Parts of
914 Makefiles: Conditionals.).
916 * Defining a variable from a verbatim string containing multiple
917 lines (*note Defining Multi-Line Variables: Multi-Line.).
919 * '#' in a line of a makefile starts a "comment". It and the rest of
920 the line are ignored, except that a trailing backslash not escaped
921 by another backslash will continue the comment across multiple
922 lines. A line containing just a comment (with perhaps spaces
923 before it) is effectively blank, and is ignored. If you want a
924 literal '#', escape it with a backslash (e.g., '\#'). Comments may
925 appear on any line in the makefile, although they are treated
926 specially in certain situations.
928 You cannot use comments within variable references or function
929 calls: any instance of '#' will be treated literally (rather than
930 as the start of a comment) inside a variable reference or function
933 Comments within a recipe are passed to the shell, just as with any
934 other recipe text. The shell decides how to interpret it: whether
935 or not this is a comment is up to the shell.
937 Within a 'define' directive, comments are not ignored during the
938 definition of the variable, but rather kept intact in the value of
939 the variable. When the variable is expanded they will either be
940 treated as 'make' comments or as recipe text, depending on the
941 context in which the variable is evaluated.
945 * Splitting Lines:: Splitting long lines in makefiles
948 File: make.info, Node: Splitting Lines, Prev: Makefile Contents, Up: Makefile Contents
950 3.1.1 Splitting Long Lines
951 --------------------------
953 Makefiles use a "line-based" syntax in which the newline character is
954 special and marks the end of a statement. GNU 'make' has no limit on
955 the length of a statement line, up to the amount of memory in your
958 However, it is difficult to read lines which are too long to display
959 without wrapping or scrolling. So, you can format your makefiles for
960 readability by adding newlines into the middle of a statement: you do
961 this by escaping the internal newlines with a backslash ('\') character.
962 Where we need to make a distinction we will refer to "physical lines" as
963 a single line ending with a newline (regardless of whether it is
964 escaped) and a "logical line" being a complete statement including all
965 escaped newlines up to the first non-escaped newline.
967 The way in which backslash/newline combinations are handled depends
968 on whether the statement is a recipe line or a non-recipe line.
969 Handling of backslash/newline in a recipe line is discussed later (*note
970 Splitting Recipe Lines::).
972 Outside of recipe lines, backslash/newlines are converted into a
973 single space character. Once that is done, all whitespace around the
974 backslash/newline is condensed into a single space: this includes all
975 whitespace preceding the backslash, all whitespace at the beginning of
976 the line after the backslash/newline, and any consecutive
977 backslash/newline combinations.
979 If the '.POSIX' special target is defined then backslash/newline
980 handling is modified slightly to conform to POSIX.2: first, whitespace
981 preceding a backslash is not removed and second, consecutive
982 backslash/newlines are not condensed.
984 Splitting Without Adding Whitespace
985 ...................................
987 If you need to split a line but do _not_ want any whitespace added, you
988 can utilize a subtle trick: replace your backslash/newline pairs with
989 the three characters dollar sign/backslash/newline:
994 After 'make' removes the backslash/newline and condenses the
995 following line into a single space, this is equivalent to:
999 Then 'make' will perform variable expansion. The variable reference
1000 '$ ' refers to a variable with the one-character name " " (space) which
1001 does not exist, and so expands to the empty string, giving a final
1002 assignment which is the equivalent of:
1007 File: make.info, Node: Makefile Names, Next: Include, Prev: Makefile Contents, Up: Makefiles
1009 3.2 What Name to Give Your Makefile
1010 ===================================
1012 By default, when 'make' looks for the makefile, it tries the following
1013 names, in order: 'GNUmakefile', 'makefile' and 'Makefile'.
1015 Normally you should call your makefile either 'makefile' or
1016 'Makefile'. (We recommend 'Makefile' because it appears prominently
1017 near the beginning of a directory listing, right near other important
1018 files such as 'README'.) The first name checked, 'GNUmakefile', is not
1019 recommended for most makefiles. You should use this name if you have a
1020 makefile that is specific to GNU 'make', and will not be understood by
1021 other versions of 'make'. Other 'make' programs look for 'makefile' and
1022 'Makefile', but not 'GNUmakefile'.
1024 If 'make' finds none of these names, it does not use any makefile.
1025 Then you must specify a goal with a command argument, and 'make' will
1026 attempt to figure out how to remake it using only its built-in implicit
1027 rules. *Note Using Implicit Rules: Implicit Rules.
1029 If you want to use a nonstandard name for your makefile, you can
1030 specify the makefile name with the '-f' or '--file' option. The
1031 arguments '-f NAME' or '--file=NAME' tell 'make' to read the file NAME
1032 as the makefile. If you use more than one '-f' or '--file' option, you
1033 can specify several makefiles. All the makefiles are effectively
1034 concatenated in the order specified. The default makefile names
1035 'GNUmakefile', 'makefile' and 'Makefile' are not checked automatically
1036 if you specify '-f' or '--file'.
1039 File: make.info, Node: Include, Next: MAKEFILES Variable, Prev: Makefile Names, Up: Makefiles
1041 3.3 Including Other Makefiles
1042 =============================
1044 The 'include' directive tells 'make' to suspend reading the current
1045 makefile and read one or more other makefiles before continuing. The
1046 directive is a line in the makefile that looks like this:
1048 include FILENAMES...
1050 FILENAMES can contain shell file name patterns. If FILENAMES is empty,
1051 nothing is included and no error is printed.
1053 Extra spaces are allowed and ignored at the beginning of the line,
1054 but the first character must not be a tab (or the value of
1055 '.RECIPEPREFIX')--if the line begins with a tab, it will be considered a
1056 recipe line. Whitespace is required between 'include' and the file
1057 names, and between file names; extra whitespace is ignored there and at
1058 the end of the directive. A comment starting with '#' is allowed at the
1059 end of the line. If the file names contain any variable or function
1060 references, they are expanded. *Note How to Use Variables: Using
1063 For example, if you have three '.mk' files, 'a.mk', 'b.mk', and
1064 'c.mk', and '$(bar)' expands to 'bish bash', then the following
1067 include foo *.mk $(bar)
1071 include foo a.mk b.mk c.mk bish bash
1073 When 'make' processes an 'include' directive, it suspends reading of
1074 the containing makefile and reads from each listed file in turn. When
1075 that is finished, 'make' resumes reading the makefile in which the
1078 One occasion for using 'include' directives is when several programs,
1079 handled by individual makefiles in various directories, need to use a
1080 common set of variable definitions (*note Setting Variables: Setting.)
1081 or pattern rules (*note Defining and Redefining Pattern Rules: Pattern
1084 Another such occasion is when you want to generate prerequisites from
1085 source files automatically; the prerequisites can be put in a file that
1086 is included by the main makefile. This practice is generally cleaner
1087 than that of somehow appending the prerequisites to the end of the main
1088 makefile as has been traditionally done with other versions of 'make'.
1089 *Note Automatic Prerequisites::.
1091 If the specified name does not start with a slash, and the file is
1092 not found in the current directory, several other directories are
1093 searched. First, any directories you have specified with the '-I' or
1094 '--include-dir' option are searched (*note Summary of Options: Options
1095 Summary.). Then the following directories (if they exist) are searched,
1096 in this order: 'PREFIX/include' (normally '/usr/local/include' (1))
1097 '/usr/gnu/include', '/usr/local/include', '/usr/include'.
1099 If an included makefile cannot be found in any of these directories,
1100 a warning message is generated, but it is not an immediately fatal
1101 error; processing of the makefile containing the 'include' continues.
1102 Once it has finished reading makefiles, 'make' will try to remake any
1103 that are out of date or don't exist. *Note How Makefiles Are Remade:
1104 Remaking Makefiles. Only after it has tried to find a way to remake a
1105 makefile and failed, will 'make' diagnose the missing makefile as a
1108 If you want 'make' to simply ignore a makefile which does not exist
1109 or cannot be remade, with no error message, use the '-include' directive
1110 instead of 'include', like this:
1112 -include FILENAMES...
1114 This acts like 'include' in every way except that there is no error
1115 (not even a warning) if any of the FILENAMES (or any prerequisites of
1116 any of the FILENAMES) do not exist or cannot be remade.
1118 For compatibility with some other 'make' implementations, 'sinclude'
1119 is another name for '-include'.
1121 ---------- Footnotes ----------
1123 (1) GNU Make compiled for MS-DOS and MS-Windows behaves as if PREFIX
1124 has been defined to be the root of the DJGPP tree hierarchy.
1127 File: make.info, Node: MAKEFILES Variable, Next: Remaking Makefiles, Prev: Include, Up: Makefiles
1129 3.4 The Variable 'MAKEFILES'
1130 ============================
1132 If the environment variable 'MAKEFILES' is defined, 'make' considers its
1133 value as a list of names (separated by whitespace) of additional
1134 makefiles to be read before the others. This works much like the
1135 'include' directive: various directories are searched for those files
1136 (*note Including Other Makefiles: Include.). In addition, the default
1137 goal is never taken from one of these makefiles (or any makefile
1138 included by them) and it is not an error if the files listed in
1139 'MAKEFILES' are not found.
1141 The main use of 'MAKEFILES' is in communication between recursive
1142 invocations of 'make' (*note Recursive Use of 'make': Recursion.). It
1143 usually is not desirable to set the environment variable before a
1144 top-level invocation of 'make', because it is usually better not to mess
1145 with a makefile from outside. However, if you are running 'make'
1146 without a specific makefile, a makefile in 'MAKEFILES' can do useful
1147 things to help the built-in implicit rules work better, such as defining
1148 search paths (*note Directory Search::).
1150 Some users are tempted to set 'MAKEFILES' in the environment
1151 automatically on login, and program makefiles to expect this to be done.
1152 This is a very bad idea, because such makefiles will fail to work if run
1153 by anyone else. It is much better to write explicit 'include'
1154 directives in the makefiles. *Note Including Other Makefiles: Include.
1157 File: make.info, Node: Remaking Makefiles, Next: Overriding Makefiles, Prev: MAKEFILES Variable, Up: Makefiles
1159 3.5 How Makefiles Are Remade
1160 ============================
1162 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1163 files. If a makefile can be remade from other files, you probably want
1164 'make' to get an up-to-date version of the makefile to read in.
1166 To this end, after reading in all makefiles 'make' will consider each
1167 as a goal target and attempt to update it. If a makefile has a rule
1168 which says how to update it (found either in that very makefile or in
1169 another one) or if an implicit rule applies to it (*note Using Implicit
1170 Rules: Implicit Rules.), it will be updated if necessary. After all
1171 makefiles have been checked, if any have actually been changed, 'make'
1172 starts with a clean slate and reads all the makefiles over again. (It
1173 will also attempt to update each of them over again, but normally this
1174 will not change them again, since they are already up to date.) Each
1175 restart will cause the special variable 'MAKE_RESTARTS' to be updated
1176 (*note Special Variables::).
1178 If you know that one or more of your makefiles cannot be remade and
1179 you want to keep 'make' from performing an implicit rule search on them,
1180 perhaps for efficiency reasons, you can use any normal method of
1181 preventing implicit rule look-up to do so. For example, you can write
1182 an explicit rule with the makefile as the target, and an empty recipe
1183 (*note Using Empty Recipes: Empty Recipes.).
1185 If the makefiles specify a double-colon rule to remake a file with a
1186 recipe but no prerequisites, that file will always be remade (*note
1187 Double-Colon::). In the case of makefiles, a makefile that has a
1188 double-colon rule with a recipe but no prerequisites will be remade
1189 every time 'make' is run, and then again after 'make' starts over and
1190 reads the makefiles in again. This would cause an infinite loop: 'make'
1191 would constantly remake the makefile, and never do anything else. So,
1192 to avoid this, 'make' will *not* attempt to remake makefiles which are
1193 specified as targets of a double-colon rule with a recipe but no
1196 If you do not specify any makefiles to be read with '-f' or '--file'
1197 options, 'make' will try the default makefile names; *note What Name to
1198 Give Your Makefile: Makefile Names. Unlike makefiles explicitly
1199 requested with '-f' or '--file' options, 'make' is not certain that
1200 these makefiles should exist. However, if a default makefile does not
1201 exist but can be created by running 'make' rules, you probably want the
1202 rules to be run so that the makefile can be used.
1204 Therefore, if none of the default makefiles exists, 'make' will try
1205 to make each of them in the same order in which they are searched for
1206 (*note What Name to Give Your Makefile: Makefile Names.) until it
1207 succeeds in making one, or it runs out of names to try. Note that it is
1208 not an error if 'make' cannot find or make any makefile; a makefile is
1209 not always necessary.
1211 When you use the '-t' or '--touch' option (*note Instead of Executing
1212 Recipes: Instead of Execution.), you would not want to use an
1213 out-of-date makefile to decide which targets to touch. So the '-t'
1214 option has no effect on updating makefiles; they are really updated even
1215 if '-t' is specified. Likewise, '-q' (or '--question') and '-n' (or
1216 '--just-print') do not prevent updating of makefiles, because an
1217 out-of-date makefile would result in the wrong output for other targets.
1218 Thus, 'make -f mfile -n foo' will update 'mfile', read it in, and then
1219 print the recipe to update 'foo' and its prerequisites without running
1220 it. The recipe printed for 'foo' will be the one specified in the
1221 updated contents of 'mfile'.
1223 However, on occasion you might actually wish to prevent updating of
1224 even the makefiles. You can do this by specifying the makefiles as
1225 goals in the command line as well as specifying them as makefiles. When
1226 the makefile name is specified explicitly as a goal, the options '-t'
1227 and so on do apply to them.
1229 Thus, 'make -f mfile -n mfile foo' would read the makefile 'mfile',
1230 print the recipe needed to update it without actually running it, and
1231 then print the recipe needed to update 'foo' without running that. The
1232 recipe for 'foo' will be the one specified by the existing contents of
1236 File: make.info, Node: Overriding Makefiles, Next: Reading Makefiles, Prev: Remaking Makefiles, Up: Makefiles
1238 3.6 Overriding Part of Another Makefile
1239 =======================================
1241 Sometimes it is useful to have a makefile that is mostly just like
1242 another makefile. You can often use the 'include' directive to include
1243 one in the other, and add more targets or variable definitions.
1244 However, it is invalid for two makefiles to give different recipes for
1245 the same target. But there is another way.
1247 In the containing makefile (the one that wants to include the other),
1248 you can use a match-anything pattern rule to say that to remake any
1249 target that cannot be made from the information in the containing
1250 makefile, 'make' should look in another makefile. *Note Pattern
1251 Rules::, for more information on pattern rules.
1253 For example, if you have a makefile called 'Makefile' that says how
1254 to make the target 'foo' (and other targets), you can write a makefile
1255 called 'GNUmakefile' that contains:
1261 @$(MAKE) -f Makefile $@
1264 If you say 'make foo', 'make' will find 'GNUmakefile', read it, and
1265 see that to make 'foo', it needs to run the recipe 'frobnicate > foo'.
1266 If you say 'make bar', 'make' will find no way to make 'bar' in
1267 'GNUmakefile', so it will use the recipe from the pattern rule: 'make -f
1268 Makefile bar'. If 'Makefile' provides a rule for updating 'bar', 'make'
1269 will apply the rule. And likewise for any other target that
1270 'GNUmakefile' does not say how to make.
1272 The way this works is that the pattern rule has a pattern of just
1273 '%', so it matches any target whatever. The rule specifies a
1274 prerequisite 'force', to guarantee that the recipe will be run even if
1275 the target file already exists. We give the 'force' target an empty
1276 recipe to prevent 'make' from searching for an implicit rule to build
1277 it--otherwise it would apply the same match-anything rule to 'force'
1278 itself and create a prerequisite loop!
1281 File: make.info, Node: Reading Makefiles, Next: Parsing Makefiles, Prev: Overriding Makefiles, Up: Makefiles
1283 3.7 How 'make' Reads a Makefile
1284 ===============================
1286 GNU 'make' does its work in two distinct phases. During the first phase
1287 it reads all the makefiles, included makefiles, etc. and internalizes
1288 all the variables and their values and implicit and explicit rules, and
1289 builds a dependency graph of all the targets and their prerequisites.
1290 During the second phase, 'make' uses this internalized data to determine
1291 which targets need to be updated and run the recipes necessary to update
1294 It's important to understand this two-phase approach because it has a
1295 direct impact on how variable and function expansion happens; this is
1296 often a source of some confusion when writing makefiles. Below is a
1297 summary of the different constructs that can be found in a makefile, and
1298 the phase in which expansion happens for each part of the construct.
1300 We say that expansion is "immediate" if it happens during the first
1301 phase: 'make' will expand that part of the construct as the makefile is
1302 parsed. We say that expansion is "deferred" if it is not immediate.
1303 Expansion of a deferred construct part is delayed until the expansion is
1304 used: either when it is referenced in an immediate context, or when it
1305 is needed during the second phase.
1307 You may not be familiar with some of these constructs yet. You can
1308 reference this section as you become familiar with them, in later
1314 Variable definitions are parsed as follows:
1316 IMMEDIATE = DEFERRED
1317 IMMEDIATE ?= DEFERRED
1318 IMMEDIATE := IMMEDIATE
1319 IMMEDIATE ::= IMMEDIATE
1320 IMMEDIATE += DEFERRED or IMMEDIATE
1321 IMMEDIATE != IMMEDIATE
1339 define IMMEDIATE ::=
1344 DEFERRED or IMMEDIATE
1351 For the append operator '+=', the right-hand side is considered
1352 immediate if the variable was previously set as a simple variable (':='
1353 or '::='), and deferred otherwise.
1355 For the shell assignment operator '!=', the right-hand side is
1356 evaluated immediately and handed to the shell. The result is stored in
1357 the variable named on the left, and that variable becomes a simple
1358 variable (and will thus be re-evaluated on each reference).
1360 Conditional Directives
1361 ----------------------
1363 Conditional directives are parsed immediately. This means, for example,
1364 that automatic variables cannot be used in conditional directives, as
1365 automatic variables are not set until the recipe for that rule is
1366 invoked. If you need to use automatic variables in a conditional
1367 directive you _must_ move the condition into the recipe and use shell
1368 conditional syntax instead.
1373 A rule is always expanded the same way, regardless of the form:
1375 IMMEDIATE : IMMEDIATE ; DEFERRED
1378 That is, the target and prerequisite sections are expanded
1379 immediately, and the recipe used to build the target is always deferred.
1380 This is true for explicit rules, pattern rules, suffix rules, static
1381 pattern rules, and simple prerequisite definitions.
1384 File: make.info, Node: Parsing Makefiles, Next: Secondary Expansion, Prev: Reading Makefiles, Up: Makefiles
1386 3.8 How Makefiles Are Parsed
1387 ============================
1389 GNU 'make' parses makefiles line-by-line. Parsing proceeds using the
1392 1. Read in a full logical line, including backslash-escaped lines
1393 (*note Splitting Long Lines: Splitting Lines.).
1395 2. Remove comments (*note What Makefiles Contain: Makefile Contents.).
1397 3. If the line begins with the recipe prefix character and we are in a
1398 rule context, add the line to the current recipe and read the next
1399 line (*note Recipe Syntax::).
1401 4. Expand elements of the line which appear in an _immediate_
1402 expansion context (*note How 'make' Reads a Makefile: Reading
1405 5. Scan the line for a separator character, such as ':' or '=', to
1406 determine whether the line is a macro assignment or a rule (*note
1409 6. Internalize the resulting operation and read the next line.
1411 An important consequence of this is that a macro can expand to an
1412 entire rule, _if it is one line long_. This will work:
1414 myrule = target : ; echo built
1418 However, this will not work because 'make' does not re-split lines
1419 after it has expanded them:
1428 The above makefile results in the definition of a target 'target'
1429 with prerequisites 'echo' and 'built', as if the makefile contained
1430 'target: echo built', rather than a rule with a recipe. Newlines still
1431 present in a line after expansion is complete are ignored as normal
1434 In order to properly expand a multi-line macro you must use the
1435 'eval' function: this causes the 'make' parser to be run on the results
1436 of the expanded macro (*note Eval Function::).
1439 File: make.info, Node: Secondary Expansion, Prev: Parsing Makefiles, Up: Makefiles
1441 3.9 Secondary Expansion
1442 =======================
1444 Previously we learned that GNU 'make' works in two distinct phases: a
1445 read-in phase and a target-update phase (*note How 'make' Reads a
1446 Makefile: Reading Makefiles.). GNU make also has the ability to enable
1447 a _second expansion_ of the prerequisites (only) for some or all targets
1448 defined in the makefile. In order for this second expansion to occur,
1449 the special target '.SECONDEXPANSION' must be defined before the first
1450 prerequisite list that makes use of this feature.
1452 If that special target is defined then in between the two phases
1453 mentioned above, right at the end of the read-in phase, all the
1454 prerequisites of the targets defined after the special target are
1455 expanded a _second time_. In most circumstances this secondary
1456 expansion will have no effect, since all variable and function
1457 references will have been expanded during the initial parsing of the
1458 makefiles. In order to take advantage of the secondary expansion phase
1459 of the parser, then, it's necessary to _escape_ the variable or function
1460 reference in the makefile. In this case the first expansion merely
1461 un-escapes the reference but doesn't expand it, and expansion is left to
1462 the secondary expansion phase. For example, consider this makefile:
1467 myfile: $(ONEVAR) $$(TWOVAR)
1469 After the first expansion phase the prerequisites list of the
1470 'myfile' target will be 'onefile' and '$(TWOVAR)'; the first (unescaped)
1471 variable reference to ONEVAR is expanded, while the second (escaped)
1472 variable reference is simply unescaped, without being recognized as a
1473 variable reference. Now during the secondary expansion the first word
1474 is expanded again but since it contains no variable or function
1475 references it remains the value 'onefile', while the second word is now
1476 a normal reference to the variable TWOVAR, which is expanded to the
1477 value 'twofile'. The final result is that there are two prerequisites,
1478 'onefile' and 'twofile'.
1480 Obviously, this is not a very interesting case since the same result
1481 could more easily have been achieved simply by having both variables
1482 appear, unescaped, in the prerequisites list. One difference becomes
1483 apparent if the variables are reset; consider this example:
1491 Here the prerequisite of 'onefile' will be expanded immediately, and
1492 resolve to the value 'top', while the prerequisite of 'twofile' will not
1493 be full expanded until the secondary expansion and yield a value of
1496 This is marginally more exciting, but the true power of this feature
1497 only becomes apparent when you discover that secondary expansions always
1498 take place within the scope of the automatic variables for that target.
1499 This means that you can use variables such as '$@', '$*', etc. during
1500 the second expansion and they will have their expected values, just as
1501 in the recipe. All you have to do is defer the expansion by escaping
1502 the '$'. Also, secondary expansion occurs for both explicit and
1503 implicit (pattern) rules. Knowing this, the possible uses for this
1504 feature increase dramatically. For example:
1507 main_OBJS := main.o try.o test.o
1508 lib_OBJS := lib.o api.o
1510 main lib: $$($$@_OBJS)
1512 Here, after the initial expansion the prerequisites of both the
1513 'main' and 'lib' targets will be '$($@_OBJS)'. During the secondary
1514 expansion, the '$@' variable is set to the name of the target and so the
1515 expansion for the 'main' target will yield '$(main_OBJS)', or 'main.o
1516 try.o test.o', while the secondary expansion for the 'lib' target will
1517 yield '$(lib_OBJS)', or 'lib.o api.o'.
1519 You can also mix in functions here, as long as they are properly
1522 main_SRCS := main.c try.c test.c
1523 lib_SRCS := lib.c api.c
1526 main lib: $$(patsubst %.c,%.o,$$($$@_SRCS))
1528 This version allows users to specify source files rather than object
1529 files, but gives the same resulting prerequisites list as the previous
1532 Evaluation of automatic variables during the secondary expansion
1533 phase, especially of the target name variable '$$@', behaves similarly
1534 to evaluation within recipes. However, there are some subtle
1535 differences and "corner cases" which come into play for the different
1536 types of rule definitions that 'make' understands. The subtleties of
1537 using the different automatic variables are described below.
1539 Secondary Expansion of Explicit Rules
1540 -------------------------------------
1542 During the secondary expansion of explicit rules, '$$@' and '$$%'
1543 evaluate, respectively, to the file name of the target and, when the
1544 target is an archive member, the target member name. The '$$<' variable
1545 evaluates to the first prerequisite in the first rule for this target.
1546 '$$^' and '$$+' evaluate to the list of all prerequisites of rules _that
1547 have already appeared_ for the same target ('$$+' with repetitions and
1548 '$$^' without). The following example will help illustrate these
1553 foo: foo.1 bar.1 $$< $$^ $$+ # line #1
1555 foo: foo.2 bar.2 $$< $$^ $$+ # line #2
1557 foo: foo.3 bar.3 $$< $$^ $$+ # line #3
1559 In the first prerequisite list, all three variables ('$$<', '$$^',
1560 and '$$+') expand to the empty string. In the second, they will have
1561 values 'foo.1', 'foo.1 bar.1', and 'foo.1 bar.1' respectively. In the
1562 third they will have values 'foo.1', 'foo.1 bar.1 foo.2 bar.2', and
1563 'foo.1 bar.1 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1' respectively.
1565 Rules undergo secondary expansion in makefile order, except that the
1566 rule with the recipe is always evaluated last.
1568 The variables '$$?' and '$$*' are not available and expand to the
1571 Secondary Expansion of Static Pattern Rules
1572 -------------------------------------------
1574 Rules for secondary expansion of static pattern rules are identical to
1575 those for explicit rules, above, with one exception: for static pattern
1576 rules the '$$*' variable is set to the pattern stem. As with explicit
1577 rules, '$$?' is not available and expands to the empty string.
1579 Secondary Expansion of Implicit Rules
1580 -------------------------------------
1582 As 'make' searches for an implicit rule, it substitutes the stem and
1583 then performs secondary expansion for every rule with a matching target
1584 pattern. The value of the automatic variables is derived in the same
1585 fashion as for static pattern rules. As an example:
1593 %oo: $$< $$^ $$+ $$*
1595 When the implicit rule is tried for target 'foo', '$$<' expands to
1596 'bar', '$$^' expands to 'bar boo', '$$+' also expands to 'bar boo', and
1597 '$$*' expands to 'f'.
1599 Note that the directory prefix (D), as described in *note Implicit
1600 Rule Search Algorithm: Implicit Rule Search, is appended (after
1601 expansion) to all the patterns in the prerequisites list. As an
1608 %.o: $$(addsuffix /%.c,foo bar) foo.h
1611 The prerequisite list printed, after the secondary expansion and
1612 directory prefix reconstruction, will be '/tmp/foo/foo.c /tmp/bar/foo.c
1613 foo.h'. If you are not interested in this reconstruction, you can use
1614 '$$*' instead of '%' in the prerequisites list.
1617 File: make.info, Node: Rules, Next: Recipes, Prev: Makefiles, Up: Top
1622 A "rule" appears in the makefile and says when and how to remake certain
1623 files, called the rule's "targets" (most often only one per rule). It
1624 lists the other files that are the "prerequisites" of the target, and
1625 the "recipe" to use to create or update the target.
1627 The order of rules is not significant, except for determining the
1628 "default goal": the target for 'make' to consider, if you do not
1629 otherwise specify one. The default goal is the target of the first rule
1630 in the first makefile. If the first rule has multiple targets, only the
1631 first target is taken as the default. There are two exceptions: a
1632 target starting with a period is not a default unless it contains one or
1633 more slashes, '/', as well; and, a target that defines a pattern rule
1634 has no effect on the default goal. (*Note Defining and Redefining
1635 Pattern Rules: Pattern Rules.)
1637 Therefore, we usually write the makefile so that the first rule is
1638 the one for compiling the entire program or all the programs described
1639 by the makefile (often with a target called 'all'). *Note Arguments to
1640 Specify the Goals: Goals.
1644 * Rule Example:: An example explained.
1645 * Rule Syntax:: General syntax explained.
1646 * Prerequisite Types:: There are two types of prerequisites.
1647 * Wildcards:: Using wildcard characters such as '*'.
1648 * Directory Search:: Searching other directories for source files.
1649 * Phony Targets:: Using a target that is not a real file's name.
1650 * Force Targets:: You can use a target without a recipe
1651 or prerequisites to mark other targets
1653 * Empty Targets:: When only the date matters and the
1655 * Special Targets:: Targets with special built-in meanings.
1656 * Multiple Targets:: When to make use of several targets in a rule.
1657 * Multiple Rules:: How to use several rules with the same target.
1658 * Static Pattern:: Static pattern rules apply to multiple targets
1659 and can vary the prerequisites according to
1661 * Double-Colon:: How to use a special kind of rule to allow
1662 several independent rules for one target.
1663 * Automatic Prerequisites:: How to automatically generate rules giving
1664 prerequisites from source files themselves.
1667 File: make.info, Node: Rule Example, Next: Rule Syntax, Prev: Rules, Up: Rules
1672 Here is an example of a rule:
1674 foo.o : foo.c defs.h # module for twiddling the frobs
1677 Its target is 'foo.o' and its prerequisites are 'foo.c' and 'defs.h'.
1678 It has one command in the recipe: 'cc -c -g foo.c'. The recipe starts
1679 with a tab to identify it as a recipe.
1681 This rule says two things:
1683 * How to decide whether 'foo.o' is out of date: it is out of date if
1684 it does not exist, or if either 'foo.c' or 'defs.h' is more recent
1687 * How to update the file 'foo.o': by running 'cc' as stated. The
1688 recipe does not explicitly mention 'defs.h', but we presume that
1689 'foo.c' includes it, and that is why 'defs.h' was added to the
1693 File: make.info, Node: Rule Syntax, Next: Prerequisite Types, Prev: Rule Example, Up: Rules
1698 In general, a rule looks like this:
1700 TARGETS : PREREQUISITES
1706 TARGETS : PREREQUISITES ; RECIPE
1710 The TARGETS are file names, separated by spaces. Wildcard characters
1711 may be used (*note Using Wildcard Characters in File Names: Wildcards.)
1712 and a name of the form 'A(M)' represents member M in archive file A
1713 (*note Archive Members as Targets: Archive Members.). Usually there is
1714 only one target per rule, but occasionally there is a reason to have
1715 more (*note Multiple Targets in a Rule: Multiple Targets.).
1717 The RECIPE lines start with a tab character (or the first character
1718 in the value of the '.RECIPEPREFIX' variable; *note Special
1719 Variables::). The first recipe line may appear on the line after the
1720 prerequisites, with a tab character, or may appear on the same line,
1721 with a semicolon. Either way, the effect is the same. There are other
1722 differences in the syntax of recipes. *Note Writing Recipes in Rules:
1725 Because dollar signs are used to start 'make' variable references, if
1726 you really want a dollar sign in a target or prerequisite you must write
1727 two of them, '$$' (*note How to Use Variables: Using Variables.). If
1728 you have enabled secondary expansion (*note Secondary Expansion::) and
1729 you want a literal dollar sign in the prerequisites list, you must
1730 actually write _four_ dollar signs ('$$$$').
1732 You may split a long line by inserting a backslash followed by a
1733 newline, but this is not required, as 'make' places no limit on the
1734 length of a line in a makefile.
1736 A rule tells 'make' two things: when the targets are out of date, and
1737 how to update them when necessary.
1739 The criterion for being out of date is specified in terms of the
1740 PREREQUISITES, which consist of file names separated by spaces.
1741 (Wildcards and archive members (*note Archives::) are allowed here too.)
1742 A target is out of date if it does not exist or if it is older than any
1743 of the prerequisites (by comparison of last-modification times). The
1744 idea is that the contents of the target file are computed based on
1745 information in the prerequisites, so if any of the prerequisites
1746 changes, the contents of the existing target file are no longer
1749 How to update is specified by a RECIPE. This is one or more lines to
1750 be executed by the shell (normally 'sh'), but with some extra features
1751 (*note Writing Recipes in Rules: Recipes.).
1754 File: make.info, Node: Prerequisite Types, Next: Wildcards, Prev: Rule Syntax, Up: Rules
1756 4.3 Types of Prerequisites
1757 ==========================
1759 There are actually two different types of prerequisites understood by
1760 GNU 'make': normal prerequisites such as described in the previous
1761 section, and "order-only" prerequisites. A normal prerequisite makes
1762 two statements: first, it imposes an order in which recipes will be
1763 invoked: the recipes for all prerequisites of a target will be completed
1764 before the recipe for the target is run. Second, it imposes a
1765 dependency relationship: if any prerequisite is newer than the target,
1766 then the target is considered out-of-date and must be rebuilt.
1768 Normally, this is exactly what you want: if a target's prerequisite
1769 is updated, then the target should also be updated.
1771 Occasionally, however, you have a situation where you want to impose
1772 a specific ordering on the rules to be invoked _without_ forcing the
1773 target to be updated if one of those rules is executed. In that case,
1774 you want to define "order-only" prerequisites. Order-only prerequisites
1775 can be specified by placing a pipe symbol ('|') in the prerequisites
1776 list: any prerequisites to the left of the pipe symbol are normal; any
1777 prerequisites to the right are order-only:
1779 TARGETS : NORMAL-PREREQUISITES | ORDER-ONLY-PREREQUISITES
1781 The normal prerequisites section may of course be empty. Also, you
1782 may still declare multiple lines of prerequisites for the same target:
1783 they are appended appropriately (normal prerequisites are appended to
1784 the list of normal prerequisites; order-only prerequisites are appended
1785 to the list of order-only prerequisites). Note that if you declare the
1786 same file to be both a normal and an order-only prerequisite, the normal
1787 prerequisite takes precedence (since they have a strict superset of the
1788 behavior of an order-only prerequisite).
1790 Consider an example where your targets are to be placed in a separate
1791 directory, and that directory might not exist before 'make' is run. In
1792 this situation, you want the directory to be created before any targets
1793 are placed into it but, because the timestamps on directories change
1794 whenever a file is added, removed, or renamed, we certainly don't want
1795 to rebuild all the targets whenever the directory's timestamp changes.
1796 One way to manage this is with order-only prerequisites: make the
1797 directory an order-only prerequisite on all the targets:
1800 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
1803 $(COMPILE.c) $(OUTPUT_OPTION) $<
1807 $(OBJS): | $(OBJDIR)
1812 Now the rule to create the 'objdir' directory will be run, if needed,
1813 before any '.o' is built, but no '.o' will be built because the 'objdir'
1814 directory timestamp changed.
1817 File: make.info, Node: Wildcards, Next: Directory Search, Prev: Prerequisite Types, Up: Rules
1819 4.4 Using Wildcard Characters in File Names
1820 ===========================================
1822 A single file name can specify many files using "wildcard characters".
1823 The wildcard characters in 'make' are '*', '?' and '[...]', the same as
1824 in the Bourne shell. For example, '*.c' specifies a list of all the
1825 files (in the working directory) whose names end in '.c'.
1827 The character '~' at the beginning of a file name also has special
1828 significance. If alone, or followed by a slash, it represents your home
1829 directory. For example '~/bin' expands to '/home/you/bin'. If the '~'
1830 is followed by a word, the string represents the home directory of the
1831 user named by that word. For example '~john/bin' expands to
1832 '/home/john/bin'. On systems which don't have a home directory for each
1833 user (such as MS-DOS or MS-Windows), this functionality can be simulated
1834 by setting the environment variable HOME.
1836 Wildcard expansion is performed by 'make' automatically in targets
1837 and in prerequisites. In recipes, the shell is responsible for wildcard
1838 expansion. In other contexts, wildcard expansion happens only if you
1839 request it explicitly with the 'wildcard' function.
1841 The special significance of a wildcard character can be turned off by
1842 preceding it with a backslash. Thus, 'foo\*bar' would refer to a
1843 specific file whose name consists of 'foo', an asterisk, and 'bar'.
1847 * Wildcard Examples:: Several examples.
1848 * Wildcard Pitfall:: Problems to avoid.
1849 * Wildcard Function:: How to cause wildcard expansion where
1850 it does not normally take place.
1853 File: make.info, Node: Wildcard Examples, Next: Wildcard Pitfall, Prev: Wildcards, Up: Wildcards
1855 4.4.1 Wildcard Examples
1856 -----------------------
1858 Wildcards can be used in the recipe of a rule, where they are expanded
1859 by the shell. For example, here is a rule to delete all the object
1865 Wildcards are also useful in the prerequisites of a rule. With the
1866 following rule in the makefile, 'make print' will print all the '.c'
1867 files that have changed since the last time you printed them:
1873 This rule uses 'print' as an empty target file; see *note Empty Target
1874 Files to Record Events: Empty Targets. (The automatic variable '$?' is
1875 used to print only those files that have changed; see *note Automatic
1878 Wildcard expansion does not happen when you define a variable. Thus,
1883 then the value of the variable 'objects' is the actual string '*.o'.
1884 However, if you use the value of 'objects' in a target or prerequisite,
1885 wildcard expansion will take place there. If you use the value of
1886 'objects' in a recipe, the shell may perform wildcard expansion when the
1887 recipe runs. To set 'objects' to the expansion, instead use:
1889 objects := $(wildcard *.o)
1891 *Note Wildcard Function::.
1894 File: make.info, Node: Wildcard Pitfall, Next: Wildcard Function, Prev: Wildcard Examples, Up: Wildcards
1896 4.4.2 Pitfalls of Using Wildcards
1897 ---------------------------------
1899 Now here is an example of a naive way of using wildcard expansion, that
1900 does not do what you would intend. Suppose you would like to say that
1901 the executable file 'foo' is made from all the object files in the
1902 directory, and you write this:
1907 cc -o foo $(CFLAGS) $(objects)
1909 The value of 'objects' is the actual string '*.o'. Wildcard expansion
1910 happens in the rule for 'foo', so that each _existing_ '.o' file becomes
1911 a prerequisite of 'foo' and will be recompiled if necessary.
1913 But what if you delete all the '.o' files? When a wildcard matches
1914 no files, it is left as it is, so then 'foo' will depend on the
1915 oddly-named file '*.o'. Since no such file is likely to exist, 'make'
1916 will give you an error saying it cannot figure out how to make '*.o'.
1917 This is not what you want!
1919 Actually it is possible to obtain the desired result with wildcard
1920 expansion, but you need more sophisticated techniques, including the
1921 'wildcard' function and string substitution. *Note The Function
1922 'wildcard': Wildcard Function.
1924 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes
1925 to separate directories in pathnames, like so:
1929 This is equivalent to the Unix-style 'c:/foo/bar/baz.c' (the 'c:'
1930 part is the so-called drive letter). When 'make' runs on these systems,
1931 it supports backslashes as well as the Unix-style forward slashes in
1932 pathnames. However, this support does _not_ include the wildcard
1933 expansion, where backslash is a quote character. Therefore, you _must_
1934 use Unix-style slashes in these cases.
1937 File: make.info, Node: Wildcard Function, Prev: Wildcard Pitfall, Up: Wildcards
1939 4.4.3 The Function 'wildcard'
1940 -----------------------------
1942 Wildcard expansion happens automatically in rules. But wildcard
1943 expansion does not normally take place when a variable is set, or inside
1944 the arguments of a function. If you want to do wildcard expansion in
1945 such places, you need to use the 'wildcard' function, like this:
1947 $(wildcard PATTERN...)
1949 This string, used anywhere in a makefile, is replaced by a
1950 space-separated list of names of existing files that match one of the
1951 given file name patterns. If no existing file name matches a pattern,
1952 then that pattern is omitted from the output of the 'wildcard' function.
1953 Note that this is different from how unmatched wildcards behave in
1954 rules, where they are used verbatim rather than ignored (*note Wildcard
1957 One use of the 'wildcard' function is to get a list of all the C
1958 source files in a directory, like this:
1962 We can change the list of C source files into a list of object files
1963 by replacing the '.c' suffix with '.o' in the result, like this:
1965 $(patsubst %.c,%.o,$(wildcard *.c))
1967 (Here we have used another function, 'patsubst'. *Note Functions for
1968 String Substitution and Analysis: Text Functions.)
1970 Thus, a makefile to compile all C source files in the directory and
1971 then link them together could be written as follows:
1973 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1976 cc -o foo $(objects)
1978 (This takes advantage of the implicit rule for compiling C programs, so
1979 there is no need to write explicit rules for compiling the files. *Note
1980 The Two Flavors of Variables: Flavors, for an explanation of ':=', which
1981 is a variant of '='.)
1984 File: make.info, Node: Directory Search, Next: Phony Targets, Prev: Wildcards, Up: Rules
1986 4.5 Searching Directories for Prerequisites
1987 ===========================================
1989 For large systems, it is often desirable to put sources in a separate
1990 directory from the binaries. The "directory search" features of 'make'
1991 facilitate this by searching several directories automatically to find a
1992 prerequisite. When you redistribute the files among directories, you do
1993 not need to change the individual rules, just the search paths.
1997 * General Search:: Specifying a search path that applies
1998 to every prerequisite.
1999 * Selective Search:: Specifying a search path
2000 for a specified class of names.
2001 * Search Algorithm:: When and how search paths are applied.
2002 * Recipes/Search:: How to write recipes that work together
2004 * Implicit/Search:: How search paths affect implicit rules.
2005 * Libraries/Search:: Directory search for link libraries.
2008 File: make.info, Node: General Search, Next: Selective Search, Prev: Directory Search, Up: Directory Search
2010 4.5.1 'VPATH': Search Path for All Prerequisites
2011 ------------------------------------------------
2013 The value of the 'make' variable 'VPATH' specifies a list of directories
2014 that 'make' should search. Most often, the directories are expected to
2015 contain prerequisite files that are not in the current directory;
2016 however, 'make' uses 'VPATH' as a search list for both prerequisites and
2019 Thus, if a file that is listed as a target or prerequisite does not
2020 exist in the current directory, 'make' searches the directories listed
2021 in 'VPATH' for a file with that name. If a file is found in one of
2022 them, that file may become the prerequisite (see below). Rules may then
2023 specify the names of files in the prerequisite list as if they all
2024 existed in the current directory. *Note Writing Recipes with Directory
2025 Search: Recipes/Search.
2027 In the 'VPATH' variable, directory names are separated by colons or
2028 blanks. The order in which directories are listed is the order followed
2029 by 'make' in its search. (On MS-DOS and MS-Windows, semi-colons are
2030 used as separators of directory names in 'VPATH', since the colon can be
2031 used in the pathname itself, after the drive letter.)
2035 VPATH = src:../headers
2037 specifies a path containing two directories, 'src' and '../headers',
2038 which 'make' searches in that order.
2040 With this value of 'VPATH', the following rule,
2044 is interpreted as if it were written like this:
2048 assuming the file 'foo.c' does not exist in the current directory but is
2049 found in the directory 'src'.
2052 File: make.info, Node: Selective Search, Next: Search Algorithm, Prev: General Search, Up: Directory Search
2054 4.5.2 The 'vpath' Directive
2055 ---------------------------
2057 Similar to the 'VPATH' variable, but more selective, is the 'vpath'
2058 directive (note lower case), which allows you to specify a search path
2059 for a particular class of file names: those that match a particular
2060 pattern. Thus you can supply certain search directories for one class
2061 of file names and other directories (or none) for other file names.
2063 There are three forms of the 'vpath' directive:
2065 'vpath PATTERN DIRECTORIES'
2066 Specify the search path DIRECTORIES for file names that match
2069 The search path, DIRECTORIES, is a list of directories to be
2070 searched, separated by colons (semi-colons on MS-DOS and
2071 MS-Windows) or blanks, just like the search path used in the
2075 Clear out the search path associated with PATTERN.
2079 Clear all search paths previously specified with 'vpath'
2082 A 'vpath' pattern is a string containing a '%' character. The string
2083 must match the file name of a prerequisite that is being searched for,
2084 the '%' character matching any sequence of zero or more characters (as
2085 in pattern rules; *note Defining and Redefining Pattern Rules: Pattern
2086 Rules.). For example, '%.h' matches files that end in '.h'. (If there
2087 is no '%', the pattern must match the prerequisite exactly, which is not
2090 '%' characters in a 'vpath' directive's pattern can be quoted with
2091 preceding backslashes ('\'). Backslashes that would otherwise quote '%'
2092 characters can be quoted with more backslashes. Backslashes that quote
2093 '%' characters or other backslashes are removed from the pattern before
2094 it is compared to file names. Backslashes that are not in danger of
2095 quoting '%' characters go unmolested.
2097 When a prerequisite fails to exist in the current directory, if the
2098 PATTERN in a 'vpath' directive matches the name of the prerequisite
2099 file, then the DIRECTORIES in that directive are searched just like (and
2100 before) the directories in the 'VPATH' variable.
2104 vpath %.h ../headers
2106 tells 'make' to look for any prerequisite whose name ends in '.h' in the
2107 directory '../headers' if the file is not found in the current
2110 If several 'vpath' patterns match the prerequisite file's name, then
2111 'make' processes each matching 'vpath' directive one by one, searching
2112 all the directories mentioned in each directive. 'make' handles
2113 multiple 'vpath' directives in the order in which they appear in the
2114 makefile; multiple directives with the same pattern are independent of
2123 will look for a file ending in '.c' in 'foo', then 'blish', then 'bar',
2129 will look for a file ending in '.c' in 'foo', then 'bar', then 'blish'.
2132 File: make.info, Node: Search Algorithm, Next: Recipes/Search, Prev: Selective Search, Up: Directory Search
2134 4.5.3 How Directory Searches are Performed
2135 ------------------------------------------
2137 When a prerequisite is found through directory search, regardless of
2138 type (general or selective), the pathname located may not be the one
2139 that 'make' actually provides you in the prerequisite list. Sometimes
2140 the path discovered through directory search is thrown away.
2142 The algorithm 'make' uses to decide whether to keep or abandon a path
2143 found via directory search is as follows:
2145 1. If a target file does not exist at the path specified in the
2146 makefile, directory search is performed.
2148 2. If the directory search is successful, that path is kept and this
2149 file is tentatively stored as the target.
2151 3. All prerequisites of this target are examined using this same
2154 4. After processing the prerequisites, the target may or may not need
2157 a. If the target does _not_ need to be rebuilt, the path to the
2158 file found during directory search is used for any
2159 prerequisite lists which contain this target. In short, if
2160 'make' doesn't need to rebuild the target then you use the
2161 path found via directory search.
2163 b. If the target _does_ need to be rebuilt (is out-of-date), the
2164 pathname found during directory search is _thrown away_, and
2165 the target is rebuilt using the file name specified in the
2166 makefile. In short, if 'make' must rebuild, then the target
2167 is rebuilt locally, not in the directory found via directory
2170 This algorithm may seem complex, but in practice it is quite often
2171 exactly what you want.
2173 Other versions of 'make' use a simpler algorithm: if the file does
2174 not exist, and it is found via directory search, then that pathname is
2175 always used whether or not the target needs to be built. Thus, if the
2176 target is rebuilt it is created at the pathname discovered during
2179 If, in fact, this is the behavior you want for some or all of your
2180 directories, you can use the 'GPATH' variable to indicate this to
2183 'GPATH' has the same syntax and format as 'VPATH' (that is, a space-
2184 or colon-delimited list of pathnames). If an out-of-date target is
2185 found by directory search in a directory that also appears in 'GPATH',
2186 then that pathname is not thrown away. The target is rebuilt using the
2190 File: make.info, Node: Recipes/Search, Next: Implicit/Search, Prev: Search Algorithm, Up: Directory Search
2192 4.5.4 Writing Recipes with Directory Search
2193 -------------------------------------------
2195 When a prerequisite is found in another directory through directory
2196 search, this cannot change the recipe of the rule; they will execute as
2197 written. Therefore, you must write the recipe with care so that it will
2198 look for the prerequisite in the directory where 'make' finds it.
2200 This is done with the "automatic variables" such as '$^' (*note
2201 Automatic Variables::). For instance, the value of '$^' is a list of
2202 all the prerequisites of the rule, including the names of the
2203 directories in which they were found, and the value of '$@' is the
2207 cc -c $(CFLAGS) $^ -o $@
2209 (The variable 'CFLAGS' exists so you can specify flags for C compilation
2210 by implicit rules; we use it here for consistency so it will affect all
2211 C compilations uniformly; *note Variables Used by Implicit Rules:
2212 Implicit Variables.)
2214 Often the prerequisites include header files as well, which you do
2215 not want to mention in the recipe. The automatic variable '$<' is just
2216 the first prerequisite:
2218 VPATH = src:../headers
2219 foo.o : foo.c defs.h hack.h
2220 cc -c $(CFLAGS) $< -o $@
2223 File: make.info, Node: Implicit/Search, Next: Libraries/Search, Prev: Recipes/Search, Up: Directory Search
2225 4.5.5 Directory Search and Implicit Rules
2226 -----------------------------------------
2228 The search through the directories specified in 'VPATH' or with 'vpath'
2229 also happens during consideration of implicit rules (*note Using
2230 Implicit Rules: Implicit Rules.).
2232 For example, when a file 'foo.o' has no explicit rule, 'make'
2233 considers implicit rules, such as the built-in rule to compile 'foo.c'
2234 if that file exists. If such a file is lacking in the current
2235 directory, the appropriate directories are searched for it. If 'foo.c'
2236 exists (or is mentioned in the makefile) in any of the directories, the
2237 implicit rule for C compilation is applied.
2239 The recipes of implicit rules normally use automatic variables as a
2240 matter of necessity; consequently they will use the file names found by
2241 directory search with no extra effort.
2244 File: make.info, Node: Libraries/Search, Prev: Implicit/Search, Up: Directory Search
2246 4.5.6 Directory Search for Link Libraries
2247 -----------------------------------------
2249 Directory search applies in a special way to libraries used with the
2250 linker. This special feature comes into play when you write a
2251 prerequisite whose name is of the form '-lNAME'. (You can tell
2252 something strange is going on here because the prerequisite is normally
2253 the name of a file, and the _file name_ of a library generally looks
2254 like 'libNAME.a', not like '-lNAME'.)
2256 When a prerequisite's name has the form '-lNAME', 'make' handles it
2257 specially by searching for the file 'libNAME.so', and, if it is not
2258 found, for the file 'libNAME.a' in the current directory, in directories
2259 specified by matching 'vpath' search paths and the 'VPATH' search path,
2260 and then in the directories '/lib', '/usr/lib', and 'PREFIX/lib'
2261 (normally '/usr/local/lib', but MS-DOS/MS-Windows versions of 'make'
2262 behave as if PREFIX is defined to be the root of the DJGPP installation
2265 For example, if there is a '/usr/lib/libcurses.a' library on your
2266 system (and no '/usr/lib/libcurses.so' file), then
2268 foo : foo.c -lcurses
2271 would cause the command 'cc foo.c /usr/lib/libcurses.a -o foo' to be
2272 executed when 'foo' is older than 'foo.c' or than
2273 '/usr/lib/libcurses.a'.
2275 Although the default set of files to be searched for is 'libNAME.so'
2276 and 'libNAME.a', this is customizable via the '.LIBPATTERNS' variable.
2277 Each word in the value of this variable is a pattern string. When a
2278 prerequisite like '-lNAME' is seen, 'make' will replace the percent in
2279 each pattern in the list with NAME and perform the above directory
2280 searches using each library file name.
2282 The default value for '.LIBPATTERNS' is 'lib%.so lib%.a', which
2283 provides the default behavior described above.
2285 You can turn off link library expansion completely by setting this
2286 variable to an empty value.
2289 File: make.info, Node: Phony Targets, Next: Force Targets, Prev: Directory Search, Up: Rules
2294 A phony target is one that is not really the name of a file; rather it
2295 is just a name for a recipe to be executed when you make an explicit
2296 request. There are two reasons to use a phony target: to avoid a
2297 conflict with a file of the same name, and to improve performance.
2299 If you write a rule whose recipe will not create the target file, the
2300 recipe will be executed every time the target comes up for remaking.
2306 Because the 'rm' command does not create a file named 'clean', probably
2307 no such file will ever exist. Therefore, the 'rm' command will be
2308 executed every time you say 'make clean'.
2310 In this example, the 'clean' target will not work properly if a file
2311 named 'clean' is ever created in this directory. Since it has no
2312 prerequisites, 'clean' would always be considered up to date and its
2313 recipe would not be executed. To avoid this problem you can explicitly
2314 declare the target to be phony by making it a prerequisite of the
2315 special target '.PHONY' (*note Special Built-in Target Names: Special
2316 Targets.) as follows:
2322 Once this is done, 'make clean' will run the recipe regardless of
2323 whether there is a file named 'clean'.
2325 Phony targets are also useful in conjunction with recursive
2326 invocations of 'make' (*note Recursive Use of 'make': Recursion.). In
2327 this situation the makefile will often contain a variable which lists a
2328 number of sub-directories to be built. A simplistic way to handle this
2329 is to define one rule with a recipe that loops over the sub-directories,
2332 SUBDIRS = foo bar baz
2335 for dir in $(SUBDIRS); do \
2339 There are problems with this method, however. First, any error
2340 detected in a sub-make is ignored by this rule, so it will continue to
2341 build the rest of the directories even when one fails. This can be
2342 overcome by adding shell commands to note the error and exit, but then
2343 it will do so even if 'make' is invoked with the '-k' option, which is
2344 unfortunate. Second, and perhaps more importantly, you cannot take
2345 advantage of 'make''s ability to build targets in parallel (*note
2346 Parallel Execution: Parallel.), since there is only one rule.
2348 By declaring the sub-directories as '.PHONY' targets (you must do
2349 this as the sub-directory obviously always exists; otherwise it won't be
2350 built) you can remove these problems:
2352 SUBDIRS = foo bar baz
2354 .PHONY: subdirs $(SUBDIRS)
2363 Here we've also declared that the 'foo' sub-directory cannot be built
2364 until after the 'baz' sub-directory is complete; this kind of
2365 relationship declaration is particularly important when attempting
2368 The implicit rule search (*note Implicit Rules::) is skipped for
2369 '.PHONY' targets. This is why declaring a target as '.PHONY' is good
2370 for performance, even if you are not worried about the actual file
2373 A phony target should not be a prerequisite of a real target file; if
2374 it is, its recipe will be run every time 'make' goes to update that
2375 file. As long as a phony target is never a prerequisite of a real
2376 target, the phony target recipe will be executed only when the phony
2377 target is a specified goal (*note Arguments to Specify the Goals:
2380 Phony targets can have prerequisites. When one directory contains
2381 multiple programs, it is most convenient to describe all of the programs
2382 in one makefile './Makefile'. Since the target remade by default will
2383 be the first one in the makefile, it is common to make this a phony
2384 target named 'all' and give it, as prerequisites, all the individual
2385 programs. For example:
2387 all : prog1 prog2 prog3
2390 prog1 : prog1.o utils.o
2391 cc -o prog1 prog1.o utils.o
2396 prog3 : prog3.o sort.o utils.o
2397 cc -o prog3 prog3.o sort.o utils.o
2399 Now you can say just 'make' to remake all three programs, or specify as
2400 arguments the ones to remake (as in 'make prog1 prog3'). Phoniness is
2401 not inherited: the prerequisites of a phony target are not themselves
2402 phony, unless explicitly declared to be so.
2404 When one phony target is a prerequisite of another, it serves as a
2405 subroutine of the other. For example, here 'make cleanall' will delete
2406 the object files, the difference files, and the file 'program':
2408 .PHONY: cleanall cleanobj cleandiff
2410 cleanall : cleanobj cleandiff
2420 File: make.info, Node: Force Targets, Next: Empty Targets, Prev: Phony Targets, Up: Rules
2422 4.7 Rules without Recipes or Prerequisites
2423 ==========================================
2425 If a rule has no prerequisites or recipe, and the target of the rule is
2426 a nonexistent file, then 'make' imagines this target to have been
2427 updated whenever its rule is run. This implies that all targets
2428 depending on this one will always have their recipe run.
2430 An example will illustrate this:
2436 Here the target 'FORCE' satisfies the special conditions, so the
2437 target 'clean' that depends on it is forced to run its recipe. There is
2438 nothing special about the name 'FORCE', but that is one name commonly
2441 As you can see, using 'FORCE' this way has the same results as using
2444 Using '.PHONY' is more explicit and more efficient. However, other
2445 versions of 'make' do not support '.PHONY'; thus 'FORCE' appears in many
2446 makefiles. *Note Phony Targets::.
2449 File: make.info, Node: Empty Targets, Next: Special Targets, Prev: Force Targets, Up: Rules
2451 4.8 Empty Target Files to Record Events
2452 =======================================
2454 The "empty target" is a variant of the phony target; it is used to hold
2455 recipes for an action that you request explicitly from time to time.
2456 Unlike a phony target, this target file can really exist; but the file's
2457 contents do not matter, and usually are empty.
2459 The purpose of the empty target file is to record, with its
2460 last-modification time, when the rule's recipe was last executed. It
2461 does so because one of the commands in the recipe is a 'touch' command
2462 to update the target file.
2464 The empty target file should have some prerequisites (otherwise it
2465 doesn't make sense). When you ask to remake the empty target, the
2466 recipe is executed if any prerequisite is more recent than the target;
2467 in other words, if a prerequisite has changed since the last time you
2468 remade the target. Here is an example:
2474 With this rule, 'make print' will execute the 'lpr' command if either
2475 source file has changed since the last 'make print'. The automatic
2476 variable '$?' is used to print only those files that have changed (*note
2477 Automatic Variables::).
2480 File: make.info, Node: Special Targets, Next: Multiple Targets, Prev: Empty Targets, Up: Rules
2482 4.9 Special Built-in Target Names
2483 =================================
2485 Certain names have special meanings if they appear as targets.
2489 The prerequisites of the special target '.PHONY' are considered to
2490 be phony targets. When it is time to consider such a target,
2491 'make' will run its recipe unconditionally, regardless of whether a
2492 file with that name exists or what its last-modification time is.
2493 *Note Phony Targets: Phony Targets.
2497 The prerequisites of the special target '.SUFFIXES' are the list of
2498 suffixes to be used in checking for suffix rules. *Note
2499 Old-Fashioned Suffix Rules: Suffix Rules.
2503 The recipe specified for '.DEFAULT' is used for any target for
2504 which no rules are found (either explicit rules or implicit rules).
2505 *Note Last Resort::. If a '.DEFAULT' recipe is specified, every
2506 file mentioned as a prerequisite, but not as a target in a rule,
2507 will have that recipe executed on its behalf. *Note Implicit Rule
2508 Search Algorithm: Implicit Rule Search.
2512 The targets which '.PRECIOUS' depends on are given the following
2513 special treatment: if 'make' is killed or interrupted during the
2514 execution of their recipes, the target is not deleted. *Note
2515 Interrupting or Killing 'make': Interrupts. Also, if the target is
2516 an intermediate file, it will not be deleted after it is no longer
2517 needed, as is normally done. *Note Chains of Implicit Rules:
2518 Chained Rules. In this latter respect it overlaps with the
2519 '.SECONDARY' special target.
2521 You can also list the target pattern of an implicit rule (such as
2522 '%.o') as a prerequisite file of the special target '.PRECIOUS' to
2523 preserve intermediate files created by rules whose target patterns
2524 match that file's name.
2528 The targets which '.INTERMEDIATE' depends on are treated as
2529 intermediate files. *Note Chains of Implicit Rules: Chained Rules.
2530 '.INTERMEDIATE' with no prerequisites has no effect.
2534 The targets which '.SECONDARY' depends on are treated as
2535 intermediate files, except that they are never automatically
2536 deleted. *Note Chains of Implicit Rules: Chained Rules.
2538 '.SECONDARY' with no prerequisites causes all targets to be treated
2539 as secondary (i.e., no target is removed because it is considered
2544 If '.SECONDEXPANSION' is mentioned as a target anywhere in the
2545 makefile, then all prerequisite lists defined _after_ it appears
2546 will be expanded a second time after all makefiles have been read
2547 in. *Note Secondary Expansion: Secondary Expansion.
2551 If '.DELETE_ON_ERROR' is mentioned as a target anywhere in the
2552 makefile, then 'make' will delete the target of a rule if it has
2553 changed and its recipe exits with a nonzero exit status, just as it
2554 does when it receives a signal. *Note Errors in Recipes: Errors.
2558 If you specify prerequisites for '.IGNORE', then 'make' will ignore
2559 errors in execution of the recipe for those particular files. The
2560 recipe for '.IGNORE' (if any) is ignored.
2562 If mentioned as a target with no prerequisites, '.IGNORE' says to
2563 ignore errors in execution of recipes for all files. This usage of
2564 '.IGNORE' is supported only for historical compatibility. Since
2565 this affects every recipe in the makefile, it is not very useful;
2566 we recommend you use the more selective ways to ignore errors in
2567 specific recipes. *Note Errors in Recipes: Errors.
2569 '.LOW_RESOLUTION_TIME'
2571 If you specify prerequisites for '.LOW_RESOLUTION_TIME', 'make'
2572 assumes that these files are created by commands that generate low
2573 resolution time stamps. The recipe for the '.LOW_RESOLUTION_TIME'
2576 The high resolution file time stamps of many modern file systems
2577 lessen the chance of 'make' incorrectly concluding that a file is
2578 up to date. Unfortunately, some hosts do not provide a way to set
2579 a high resolution file time stamp, so commands like 'cp -p' that
2580 explicitly set a file's time stamp must discard its sub-second
2581 part. If a file is created by such a command, you should list it
2582 as a prerequisite of '.LOW_RESOLUTION_TIME' so that 'make' does not
2583 mistakenly conclude that the file is out of date. For example:
2585 .LOW_RESOLUTION_TIME: dst
2589 Since 'cp -p' discards the sub-second part of 'src''s time stamp,
2590 'dst' is typically slightly older than 'src' even when it is up to
2591 date. The '.LOW_RESOLUTION_TIME' line causes 'make' to consider
2592 'dst' to be up to date if its time stamp is at the start of the
2593 same second that 'src''s time stamp is in.
2595 Due to a limitation of the archive format, archive member time
2596 stamps are always low resolution. You need not list archive
2597 members as prerequisites of '.LOW_RESOLUTION_TIME', as 'make' does
2602 If you specify prerequisites for '.SILENT', then 'make' will not
2603 print the recipe used to remake those particular files before
2604 executing them. The recipe for '.SILENT' is ignored.
2606 If mentioned as a target with no prerequisites, '.SILENT' says not
2607 to print any recipes before executing them. You may also use more
2608 selective ways to silence specific recipe command lines. *Note
2609 Recipe Echoing: Echoing. If you want to silence all recipes for a
2610 particular run of 'make', use the '-s' or '--silent' option (*note
2613 '.EXPORT_ALL_VARIABLES'
2615 Simply by being mentioned as a target, this tells 'make' to export
2616 all variables to child processes by default. *Note Communicating
2617 Variables to a Sub-'make': Variables/Recursion.
2621 If '.NOTPARALLEL' is mentioned as a target, then this invocation of
2622 'make' will be run serially, even if the '-j' option is given. Any
2623 recursively invoked 'make' command will still run recipes in
2624 parallel (unless its makefile also contains this target). Any
2625 prerequisites on this target are ignored.
2629 If '.ONESHELL' is mentioned as a target, then when a target is
2630 built all lines of the recipe will be given to a single invocation
2631 of the shell rather than each line being invoked separately (*note
2632 Recipe Execution: Execution.).
2636 If '.POSIX' is mentioned as a target, then the makefile will be
2637 parsed and run in POSIX-conforming mode. This does _not_ mean that
2638 only POSIX-conforming makefiles will be accepted: all advanced GNU
2639 'make' features are still available. Rather, this target causes
2640 'make' to behave as required by POSIX in those areas where 'make''s
2641 default behavior differs.
2643 In particular, if this target is mentioned then recipes will be
2644 invoked as if the shell had been passed the '-e' flag: the first
2645 failing command in a recipe will cause the recipe to fail
2648 Any defined implicit rule suffix also counts as a special target if
2649 it appears as a target, and so does the concatenation of two suffixes,
2650 such as '.c.o'. These targets are suffix rules, an obsolete way of
2651 defining implicit rules (but a way still widely used). In principle,
2652 any target name could be special in this way if you break it in two and
2653 add both pieces to the suffix list. In practice, suffixes normally
2654 begin with '.', so these special target names also begin with '.'.
2655 *Note Old-Fashioned Suffix Rules: Suffix Rules.
2658 File: make.info, Node: Multiple Targets, Next: Multiple Rules, Prev: Special Targets, Up: Rules
2660 4.10 Multiple Targets in a Rule
2661 ===============================
2663 When an explicit rule has multiple targets they can be treated in one of
2664 two possible ways: as independent targets or as grouped targets. The
2665 manner in which they are treated is determined by the separator that
2666 appears after the list of targets.
2668 Rules with Independent Targets
2669 ..............................
2671 Rules that use the standard target separator, ':', define independent
2672 targets. This is equivalent to writing the same rule once for each
2673 target, with duplicated prerequisites and recipes. Typically, the
2674 recipe would use automatic variables such as '$@' to specify which
2675 target is being built.
2677 Rules with independent targets are useful in two cases:
2679 * You want just prerequisites, no recipe. For example:
2681 kbd.o command.o files.o: command.h
2683 gives an additional prerequisite to each of the three object files
2684 mentioned. It is equivalent to writing:
2687 command.o: command.h
2690 * Similar recipes work for all the targets. The automatic variable
2691 '$@' can be used to substitute the particular target to be remade
2692 into the commands (*note Automatic Variables::). For example:
2694 bigoutput littleoutput : text.g
2695 generate text.g -$(subst output,,$@) > $@
2700 generate text.g -big > bigoutput
2701 littleoutput : text.g
2702 generate text.g -little > littleoutput
2704 Here we assume the hypothetical program 'generate' makes two types
2705 of output, one if given '-big' and one if given '-little'. *Note
2706 Functions for String Substitution and Analysis: Text Functions, for
2707 an explanation of the 'subst' function.
2709 Suppose you would like to vary the prerequisites according to the
2710 target, much as the variable '$@' allows you to vary the recipe. You
2711 cannot do this with multiple targets in an ordinary rule, but you can do
2712 it with a "static pattern rule". *Note Static Pattern Rules: Static
2715 Rules with Grouped Targets
2716 ..........................
2718 If instead of independent targets you have a recipe that generates
2719 multiple files from a single invocation, you can express that
2720 relationship by declaring your rule to use _grouped targets_. A grouped
2721 target rule uses the separator '&:' (the '&' here is used to imply
2724 When 'make' builds any one of the grouped targets, it understands
2725 that all the other targets in the group are also created as a result of
2726 the invocation of the recipe. Furthermore, if only some of the grouped
2727 targets are out of date or missing 'make' will realize that running the
2728 recipe will update all of the targets.
2730 As an example, this rule defines a grouped target:
2732 foo bar biz &: baz boz
2737 During the execution of a grouped target's recipe, the automatic
2738 variable '$@' is set to the name of the particular target in the group
2739 which triggered the rule. Caution must be used if relying on this
2740 variable in the recipe of a grouped target rule.
2742 Unlike independent targets, a grouped target rule _must_ include a
2743 recipe. However, targets that are members of a grouped target may also
2744 appear in independent target rule definitions that do not have recipes.
2746 Each target may have only one recipe associated with it. If a
2747 grouped target appears in either an independent target rule or in
2748 another grouped target rule with a recipe, you will get a warning and
2749 the latter recipe will replace the former recipe. Additionally the
2750 target will be removed from the previous group and appear only in the
2753 If you would like a target to appear in multiple groups, then you
2754 must use the double-colon grouped target separator, '&::' when declaring
2755 all of the groups containing that target. Grouped double-colon targets
2756 are each considered independently, and each grouped double-colon rule's
2757 recipe is executed at most once, if at least one of its multiple targets
2761 File: make.info, Node: Multiple Rules, Next: Static Pattern, Prev: Multiple Targets, Up: Rules
2763 4.11 Multiple Rules for One Target
2764 ==================================
2766 One file can be the target of several rules. All the prerequisites
2767 mentioned in all the rules are merged into one list of prerequisites for
2768 the target. If the target is older than any prerequisite from any rule,
2769 the recipe is executed.
2771 There can only be one recipe to be executed for a file. If more than
2772 one rule gives a recipe for the same file, 'make' uses the last one
2773 given and prints an error message. (As a special case, if the file's
2774 name begins with a dot, no error message is printed. This odd behavior
2775 is only for compatibility with other implementations of 'make'... you
2776 should avoid using it). Occasionally it is useful to have the same
2777 target invoke multiple recipes which are defined in different parts of
2778 your makefile; you can use "double-colon rules" (*note Double-Colon::)
2781 An extra rule with just prerequisites can be used to give a few extra
2782 prerequisites to many files at once. For example, makefiles often have
2783 a variable, such as 'objects', containing a list of all the compiler
2784 output files in the system being made. An easy way to say that all of
2785 them must be recompiled if 'config.h' changes is to write the following:
2787 objects = foo.o bar.o
2789 bar.o : defs.h test.h
2790 $(objects) : config.h
2792 This could be inserted or taken out without changing the rules that
2793 really specify how to make the object files, making it a convenient form
2794 to use if you wish to add the additional prerequisite intermittently.
2796 Another wrinkle is that the additional prerequisites could be
2797 specified with a variable that you set with a command line argument to
2798 'make' (*note Overriding Variables: Overriding.). For example,
2801 $(objects) : $(extradeps)
2803 means that the command 'make extradeps=foo.h' will consider 'foo.h' as a
2804 prerequisite of each object file, but plain 'make' will not.
2806 If none of the explicit rules for a target has a recipe, then 'make'
2807 searches for an applicable implicit rule to find one *note Using
2808 Implicit Rules: Implicit Rules.).
2811 File: make.info, Node: Static Pattern, Next: Double-Colon, Prev: Multiple Rules, Up: Rules
2813 4.12 Static Pattern Rules
2814 =========================
2816 "Static pattern rules" are rules which specify multiple targets and
2817 construct the prerequisite names for each target based on the target
2818 name. They are more general than ordinary rules with multiple targets
2819 because the targets do not have to have identical prerequisites. Their
2820 prerequisites must be _analogous_, but not necessarily _identical_.
2824 * Static Usage:: The syntax of static pattern rules.
2825 * Static versus Implicit:: When are they better than implicit rules?
2828 File: make.info, Node: Static Usage, Next: Static versus Implicit, Prev: Static Pattern, Up: Static Pattern
2830 4.12.1 Syntax of Static Pattern Rules
2831 -------------------------------------
2833 Here is the syntax of a static pattern rule:
2835 TARGETS ...: TARGET-PATTERN: PREREQ-PATTERNS ...
2839 The TARGETS list specifies the targets that the rule applies to. The
2840 targets can contain wildcard characters, just like the targets of
2841 ordinary rules (*note Using Wildcard Characters in File Names:
2844 The TARGET-PATTERN and PREREQ-PATTERNS say how to compute the
2845 prerequisites of each target. Each target is matched against the
2846 TARGET-PATTERN to extract a part of the target name, called the "stem".
2847 This stem is substituted into each of the PREREQ-PATTERNS to make the
2848 prerequisite names (one from each PREREQ-PATTERN).
2850 Each pattern normally contains the character '%' just once. When the
2851 TARGET-PATTERN matches a target, the '%' can match any part of the
2852 target name; this part is called the "stem". The rest of the pattern
2853 must match exactly. For example, the target 'foo.o' matches the pattern
2854 '%.o', with 'foo' as the stem. The targets 'foo.c' and 'foo.out' do not
2857 The prerequisite names for each target are made by substituting the
2858 stem for the '%' in each prerequisite pattern. For example, if one
2859 prerequisite pattern is '%.c', then substitution of the stem 'foo' gives
2860 the prerequisite name 'foo.c'. It is legitimate to write a prerequisite
2861 pattern that does not contain '%'; then this prerequisite is the same
2864 '%' characters in pattern rules can be quoted with preceding
2865 backslashes ('\'). Backslashes that would otherwise quote '%'
2866 characters can be quoted with more backslashes. Backslashes that quote
2867 '%' characters or other backslashes are removed from the pattern before
2868 it is compared to file names or has a stem substituted into it.
2869 Backslashes that are not in danger of quoting '%' characters go
2870 unmolested. For example, the pattern 'the\%weird\\%pattern\\' has
2871 'the%weird\' preceding the operative '%' character, and 'pattern\\'
2872 following it. The final two backslashes are left alone because they
2873 cannot affect any '%' character.
2875 Here is an example, which compiles each of 'foo.o' and 'bar.o' from
2876 the corresponding '.c' file:
2878 objects = foo.o bar.o
2882 $(objects): %.o: %.c
2883 $(CC) -c $(CFLAGS) $< -o $@
2885 Here '$<' is the automatic variable that holds the name of the
2886 prerequisite and '$@' is the automatic variable that holds the name of
2887 the target; see *note Automatic Variables::.
2889 Each target specified must match the target pattern; a warning is
2890 issued for each target that does not. If you have a list of files, only
2891 some of which will match the pattern, you can use the 'filter' function
2892 to remove non-matching file names (*note Functions for String
2893 Substitution and Analysis: Text Functions.):
2895 files = foo.elc bar.o lose.o
2897 $(filter %.o,$(files)): %.o: %.c
2898 $(CC) -c $(CFLAGS) $< -o $@
2899 $(filter %.elc,$(files)): %.elc: %.el
2900 emacs -f batch-byte-compile $<
2902 In this example the result of '$(filter %.o,$(files))' is 'bar.o
2903 lose.o', and the first static pattern rule causes each of these object
2904 files to be updated by compiling the corresponding C source file. The
2905 result of '$(filter %.elc,$(files))' is 'foo.elc', so that file is made
2908 Another example shows how to use '$*' in static pattern rules:
2910 bigoutput littleoutput : %output : text.g
2911 generate text.g -$* > $@
2913 When the 'generate' command is run, '$*' will expand to the stem, either
2917 File: make.info, Node: Static versus Implicit, Prev: Static Usage, Up: Static Pattern
2919 4.12.2 Static Pattern Rules versus Implicit Rules
2920 -------------------------------------------------
2922 A static pattern rule has much in common with an implicit rule defined
2923 as a pattern rule (*note Defining and Redefining Pattern Rules: Pattern
2924 Rules.). Both have a pattern for the target and patterns for
2925 constructing the names of prerequisites. The difference is in how
2926 'make' decides _when_ the rule applies.
2928 An implicit rule _can_ apply to any target that matches its pattern,
2929 but it _does_ apply only when the target has no recipe otherwise
2930 specified, and only when the prerequisites can be found. If more than
2931 one implicit rule appears applicable, only one applies; the choice
2932 depends on the order of rules.
2934 By contrast, a static pattern rule applies to the precise list of
2935 targets that you specify in the rule. It cannot apply to any other
2936 target and it invariably does apply to each of the targets specified.
2937 If two conflicting rules apply, and both have recipes, that's an error.
2939 The static pattern rule can be better than an implicit rule for these
2942 * You may wish to override the usual implicit rule for a few files
2943 whose names cannot be categorized syntactically but can be given in
2946 * If you cannot be sure of the precise contents of the directories
2947 you are using, you may not be sure which other irrelevant files
2948 might lead 'make' to use the wrong implicit rule. The choice might
2949 depend on the order in which the implicit rule search is done.
2950 With static pattern rules, there is no uncertainty: each rule
2951 applies to precisely the targets specified.
2954 File: make.info, Node: Double-Colon, Next: Automatic Prerequisites, Prev: Static Pattern, Up: Rules
2956 4.13 Double-Colon Rules
2957 =======================
2959 "Double-colon" rules are explicit rules written with '::' instead of ':'
2960 after the target names. They are handled differently from ordinary
2961 rules when the same target appears in more than one rule. Pattern rules
2962 with double-colons have an entirely different meaning (*note
2963 Match-Anything Rules::).
2965 When a target appears in multiple rules, all the rules must be the
2966 same type: all ordinary, or all double-colon. If they are double-colon,
2967 each of them is independent of the others. Each double-colon rule's
2968 recipe is executed if the target is older than any prerequisites of that
2969 rule. If there are no prerequisites for that rule, its recipe is always
2970 executed (even if the target already exists). This can result in
2971 executing none, any, or all of the double-colon rules.
2973 Double-colon rules with the same target are in fact completely
2974 separate from one another. Each double-colon rule is processed
2975 individually, just as rules with different targets are processed.
2977 The double-colon rules for a target are executed in the order they
2978 appear in the makefile. However, the cases where double-colon rules
2979 really make sense are those where the order of executing the recipes
2982 Double-colon rules are somewhat obscure and not often very useful;
2983 they provide a mechanism for cases in which the method used to update a
2984 target differs depending on which prerequisite files caused the update,
2985 and such cases are rare.
2987 Each double-colon rule should specify a recipe; if it does not, an
2988 implicit rule will be used if one applies. *Note Using Implicit Rules:
2992 File: make.info, Node: Automatic Prerequisites, Prev: Double-Colon, Up: Rules
2994 4.14 Generating Prerequisites Automatically
2995 ===========================================
2997 In the makefile for a program, many of the rules you need to write often
2998 say only that some object file depends on some header file. For
2999 example, if 'main.c' uses 'defs.h' via an '#include', you would write:
3003 You need this rule so that 'make' knows that it must remake 'main.o'
3004 whenever 'defs.h' changes. You can see that for a large program you
3005 would have to write dozens of such rules in your makefile. And, you
3006 must always be very careful to update the makefile every time you add or
3007 remove an '#include'.
3009 To avoid this hassle, most modern C compilers can write these rules
3010 for you, by looking at the '#include' lines in the source files.
3011 Usually this is done with the '-M' option to the compiler. For example,
3016 generates the output:
3018 main.o : main.c defs.h
3020 Thus you no longer have to write all those rules yourself. The compiler
3023 Note that such a rule constitutes mentioning 'main.o' in a makefile,
3024 so it can never be considered an intermediate file by implicit rule
3025 search. This means that 'make' won't ever remove the file after using
3026 it; *note Chains of Implicit Rules: Chained Rules.
3028 With old 'make' programs, it was traditional practice to use this
3029 compiler feature to generate prerequisites on demand with a command like
3030 'make depend'. That command would create a file 'depend' containing all
3031 the automatically-generated prerequisites; then the makefile could use
3032 'include' to read them in (*note Include::).
3034 In GNU 'make', the feature of remaking makefiles makes this practice
3035 obsolete--you need never tell 'make' explicitly to regenerate the
3036 prerequisites, because it always regenerates any makefile that is out of
3037 date. *Note Remaking Makefiles::.
3039 The practice we recommend for automatic prerequisite generation is to
3040 have one makefile corresponding to each source file. For each source
3041 file 'NAME.c' there is a makefile 'NAME.d' which lists what files the
3042 object file 'NAME.o' depends on. That way only the source files that
3043 have changed need to be rescanned to produce the new prerequisites.
3045 Here is the pattern rule to generate a file of prerequisites (i.e., a
3046 makefile) called 'NAME.d' from a C source file called 'NAME.c':
3049 @set -e; rm -f $@; \
3050 $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
3051 sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
3054 *Note Pattern Rules::, for information on defining pattern rules. The
3055 '-e' flag to the shell causes it to exit immediately if the '$(CC)'
3056 command (or any other command) fails (exits with a nonzero status).
3058 With the GNU C compiler, you may wish to use the '-MM' flag instead
3059 of '-M'. This omits prerequisites on system header files. *Note
3060 Options Controlling the Preprocessor: (gcc)Preprocessor Options, for
3063 The purpose of the 'sed' command is to translate (for example):
3065 main.o : main.c defs.h
3069 main.o main.d : main.c defs.h
3071 This makes each '.d' file depend on all the source and header files that
3072 the corresponding '.o' file depends on. 'make' then knows it must
3073 regenerate the prerequisites whenever any of the source or header files
3076 Once you've defined the rule to remake the '.d' files, you then use
3077 the 'include' directive to read them all in. *Note Include::. For
3080 sources = foo.c bar.c
3082 include $(sources:.c=.d)
3084 (This example uses a substitution variable reference to translate the
3085 list of source files 'foo.c bar.c' into a list of prerequisite
3086 makefiles, 'foo.d bar.d'. *Note Substitution Refs::, for full
3087 information on substitution references.) Since the '.d' files are
3088 makefiles like any others, 'make' will remake them as necessary with no
3089 further work from you. *Note Remaking Makefiles::.
3091 Note that the '.d' files contain target definitions; you should be
3092 sure to place the 'include' directive _after_ the first, default goal in
3093 your makefiles or run the risk of having a random object file become the
3094 default goal. *Note How Make Works::.
3097 File: make.info, Node: Recipes, Next: Using Variables, Prev: Rules, Up: Top
3099 5 Writing Recipes in Rules
3100 **************************
3102 The recipe of a rule consists of one or more shell command lines to be
3103 executed, one at a time, in the order they appear. Typically, the
3104 result of executing these commands is that the target of the rule is
3107 Users use many different shell programs, but recipes in makefiles are
3108 always interpreted by '/bin/sh' unless the makefile specifies otherwise.
3109 *Note Recipe Execution: Execution.
3113 * Recipe Syntax:: Recipe syntax features and pitfalls.
3114 * Echoing:: How to control when recipes are echoed.
3115 * Execution:: How recipes are executed.
3116 * Parallel:: How recipes can be executed in parallel.
3117 * Errors:: What happens after a recipe execution error.
3118 * Interrupts:: What happens when a recipe is interrupted.
3119 * Recursion:: Invoking 'make' from makefiles.
3120 * Canned Recipes:: Defining canned recipes.
3121 * Empty Recipes:: Defining useful, do-nothing recipes.
3124 File: make.info, Node: Recipe Syntax, Next: Echoing, Prev: Recipes, Up: Recipes
3129 Makefiles have the unusual property that there are really two distinct
3130 syntaxes in one file. Most of the makefile uses 'make' syntax (*note
3131 Writing Makefiles: Makefiles.). However, recipes are meant to be
3132 interpreted by the shell and so they are written using shell syntax.
3133 The 'make' program does not try to understand shell syntax: it performs
3134 only a very few specific translations on the content of the recipe
3135 before handing it to the shell.
3137 Each line in the recipe must start with a tab (or the first character
3138 in the value of the '.RECIPEPREFIX' variable; *note Special
3139 Variables::), except that the first recipe line may be attached to the
3140 target-and-prerequisites line with a semicolon in between. _Any_ line
3141 in the makefile that begins with a tab and appears in a "rule context"
3142 (that is, after a rule has been started until another rule or variable
3143 definition) will be considered part of a recipe for that rule. Blank
3144 lines and lines of just comments may appear among the recipe lines; they
3147 Some consequences of these rules include:
3149 * A blank line that begins with a tab is not blank: it's an empty
3150 recipe (*note Empty Recipes::).
3152 * A comment in a recipe is not a 'make' comment; it will be passed to
3153 the shell as-is. Whether the shell treats it as a comment or not
3154 depends on your shell.
3156 * A variable definition in a "rule context" which is indented by a
3157 tab as the first character on the line, will be considered part of
3158 a recipe, not a 'make' variable definition, and passed to the
3161 * A conditional expression ('ifdef', 'ifeq', etc. *note Syntax of
3162 Conditionals: Conditional Syntax.) in a "rule context" which is
3163 indented by a tab as the first character on the line, will be
3164 considered part of a recipe and be passed to the shell.
3168 * Splitting Recipe Lines:: Breaking long recipe lines for readability.
3169 * Variables in Recipes:: Using 'make' variables in recipes.
3172 File: make.info, Node: Splitting Recipe Lines, Next: Variables in Recipes, Prev: Recipe Syntax, Up: Recipe Syntax
3174 5.1.1 Splitting Recipe Lines
3175 ----------------------------
3177 One of the few ways in which 'make' does interpret recipes is checking
3178 for a backslash just before the newline. As in normal makefile syntax,
3179 a single logical recipe line can be split into multiple physical lines
3180 in the makefile by placing a backslash before each newline. A sequence
3181 of lines like this is considered a single recipe line, and one instance
3182 of the shell will be invoked to run it.
3184 However, in contrast to how they are treated in other places in a
3185 makefile (*note Splitting Long Lines: Splitting Lines.),
3186 backslash/newline pairs are _not_ removed from the recipe. Both the
3187 backslash and the newline characters are preserved and passed to the
3188 shell. How the backslash/newline is interpreted depends on your shell.
3189 If the first character of the next line after the backslash/newline is
3190 the recipe prefix character (a tab by default; *note Special
3191 Variables::), then that character (and only that character) is removed.
3192 Whitespace is never added to the recipe.
3194 For example, the recipe for the all target in this makefile:
3206 consists of four separate shell commands where the output is:
3213 As a more complex example, this makefile:
3215 all : ; @echo 'hello \
3216 world' ; echo "hello \
3219 will invoke one shell with a command of:
3222 world' ; echo "hello \
3225 which, according to shell quoting rules, will yield the following
3232 Notice how the backslash/newline pair was removed inside the string
3233 quoted with double quotes ('"..."'), but not from the string quoted with
3234 single quotes (''...''). This is the way the default shell ('/bin/sh')
3235 handles backslash/newline pairs. If you specify a different shell in
3236 your makefiles it may treat them differently.
3238 Sometimes you want to split a long line inside of single quotes, but
3239 you don't want the backslash/newline to appear in the quoted content.
3240 This is often the case when passing scripts to languages such as Perl,
3241 where extraneous backslashes inside the script can change its meaning or
3242 even be a syntax error. One simple way of handling this is to place the
3243 quoted string, or even the entire command, into a 'make' variable then
3244 use the variable in the recipe. In this situation the newline quoting
3245 rules for makefiles will be used, and the backslash/newline will be
3246 removed. If we rewrite our example above using this method:
3251 all : ; @echo $(HELLO)
3253 we will get output like this:
3257 If you like, you can also use target-specific variables (*note
3258 Target-specific Variable Values: Target-specific.) to obtain a tighter
3259 correspondence between the variable and the recipe that uses it.
3262 File: make.info, Node: Variables in Recipes, Prev: Splitting Recipe Lines, Up: Recipe Syntax
3264 5.1.2 Using Variables in Recipes
3265 --------------------------------
3267 The other way in which 'make' processes recipes is by expanding any
3268 variable references in them (*note Basics of Variable References:
3269 Reference.). This occurs after make has finished reading all the
3270 makefiles and the target is determined to be out of date; so, the
3271 recipes for targets which are not rebuilt are never expanded.
3273 Variable and function references in recipes have identical syntax and
3274 semantics to references elsewhere in the makefile. They also have the
3275 same quoting rules: if you want a dollar sign to appear in your recipe,
3276 you must double it ('$$'). For shells like the default shell, that use
3277 dollar signs to introduce variables, it's important to keep clear in
3278 your mind whether the variable you want to reference is a 'make'
3279 variable (use a single dollar sign) or a shell variable (use two dollar
3280 signs). For example:
3282 LIST = one two three
3284 for i in $(LIST); do \
3288 results in the following command being passed to the shell:
3290 for i in one two three; do \
3294 which generates the expected result:
3301 File: make.info, Node: Echoing, Next: Execution, Prev: Recipe Syntax, Up: Recipes
3306 Normally 'make' prints each line of the recipe before it is executed.
3307 We call this "echoing" because it gives the appearance that you are
3308 typing the lines yourself.
3310 When a line starts with '@', the echoing of that line is suppressed.
3311 The '@' is discarded before the line is passed to the shell. Typically
3312 you would use this for a command whose only effect is to print
3313 something, such as an 'echo' command to indicate progress through the
3316 @echo About to make distribution files
3318 When 'make' is given the flag '-n' or '--just-print' it only echoes
3319 most recipes, without executing them. *Note Summary of Options: Options
3320 Summary. In this case even the recipe lines starting with '@' are
3321 printed. This flag is useful for finding out which recipes 'make'
3322 thinks are necessary without actually doing them.
3324 The '-s' or '--silent' flag to 'make' prevents all echoing, as if all
3325 recipes started with '@'. A rule in the makefile for the special target
3326 '.SILENT' without prerequisites has the same effect (*note Special
3327 Built-in Target Names: Special Targets.).
3330 File: make.info, Node: Execution, Next: Parallel, Prev: Echoing, Up: Recipes
3332 5.3 Recipe Execution
3333 ====================
3335 When it is time to execute recipes to update a target, they are executed
3336 by invoking a new sub-shell for each line of the recipe, unless the
3337 '.ONESHELL' special target is in effect (*note Using One Shell: One
3338 Shell.) (In practice, 'make' may take shortcuts that do not affect the
3341 *Please note:* this implies that setting shell variables and invoking
3342 shell commands such as 'cd' that set a context local to each process
3343 will not affect the following lines in the recipe.(1) If you want to
3344 use 'cd' to affect the next statement, put both statements in a single
3345 recipe line. Then 'make' will invoke one shell to run the entire line,
3346 and the shell will execute the statements in sequence. For example:
3349 cd $(<D) && gobble $(<F) > ../$@
3351 Here we use the shell AND operator ('&&') so that if the 'cd' command
3352 fails, the script will fail without trying to invoke the 'gobble'
3353 command in the wrong directory, which could cause problems (in this case
3354 it would certainly cause '../foo' to be truncated, at least).
3358 * One Shell:: One shell for all lines in a recipe.
3359 * Choosing the Shell:: How 'make' chooses the shell used
3362 ---------- Footnotes ----------
3364 (1) On MS-DOS, the value of current working directory is *global*, so
3365 changing it _will_ affect the following recipe lines on those systems.
3368 File: make.info, Node: One Shell, Next: Choosing the Shell, Prev: Execution, Up: Execution
3370 5.3.1 Using One Shell
3371 ---------------------
3373 Sometimes you would prefer that all the lines in the recipe be passed to
3374 a single invocation of the shell. There are generally two situations
3375 where this is useful: first, it can improve performance in makefiles
3376 where recipes consist of many command lines, by avoiding extra
3377 processes. Second, you might want newlines to be included in your
3378 recipe command (for example perhaps you are using a very different
3379 interpreter as your 'SHELL'). If the '.ONESHELL' special target appears
3380 anywhere in the makefile then _all_ recipe lines for each target will be
3381 provided to a single invocation of the shell. Newlines between recipe
3382 lines will be preserved. For example:
3387 gobble $(@F) > ../$@
3389 would now work as expected even though the commands are on different
3392 If '.ONESHELL' is provided, then only the first line of the recipe
3393 will be checked for the special prefix characters ('@', '-', and '+').
3394 Subsequent lines will include the special characters in the recipe line
3395 when the 'SHELL' is invoked. If you want your recipe to start with one
3396 of these special characters you'll need to arrange for them to not be
3397 the first characters on the first line, perhaps by adding a comment or
3398 similar. For example, this would be a syntax error in Perl because the
3399 first '@' is removed by make:
3402 SHELL = /usr/bin/perl
3408 However, either of these alternatives would work properly:
3411 SHELL = /usr/bin/perl
3414 # Make sure "@" is not the first character on the first line
3421 SHELL = /usr/bin/perl
3427 As a special feature, if 'SHELL' is determined to be a POSIX-style
3428 shell, the special prefix characters in "internal" recipe lines will be
3429 _removed_ before the recipe is processed. This feature is intended to
3430 allow existing makefiles to add the '.ONESHELL' special target and still
3431 run properly without extensive modifications. Since the special prefix
3432 characters are not legal at the beginning of a line in a POSIX shell
3433 script this is not a loss in functionality. For example, this works as
3439 @gobble $(@F) > ../$@
3441 Even with this special feature, however, makefiles with '.ONESHELL'
3442 will behave differently in ways that could be noticeable. For example,
3443 normally if any line in the recipe fails, that causes the rule to fail
3444 and no more recipe lines are processed. Under '.ONESHELL' a failure of
3445 any but the final recipe line will not be noticed by 'make'. You can
3446 modify '.SHELLFLAGS' to add the '-e' option to the shell which will
3447 cause any failure anywhere in the command line to cause the shell to
3448 fail, but this could itself cause your recipe to behave differently.
3449 Ultimately you may need to harden your recipe lines to allow them to
3450 work with '.ONESHELL'.
3453 File: make.info, Node: Choosing the Shell, Prev: One Shell, Up: Execution
3455 5.3.2 Choosing the Shell
3456 ------------------------
3458 The program used as the shell is taken from the variable 'SHELL'. If
3459 this variable is not set in your makefile, the program '/bin/sh' is used
3460 as the shell. The argument(s) passed to the shell are taken from the
3461 variable '.SHELLFLAGS'. The default value of '.SHELLFLAGS' is '-c'
3462 normally, or '-ec' in POSIX-conforming mode.
3464 Unlike most variables, the variable 'SHELL' is never set from the
3465 environment. This is because the 'SHELL' environment variable is used
3466 to specify your personal choice of shell program for interactive use.
3467 It would be very bad for personal choices like this to affect the
3468 functioning of makefiles. *Note Variables from the Environment:
3471 Furthermore, when you do set 'SHELL' in your makefile that value is
3472 _not_ exported in the environment to recipe lines that 'make' invokes.
3473 Instead, the value inherited from the user's environment, if any, is
3474 exported. You can override this behavior by explicitly exporting
3475 'SHELL' (*note Communicating Variables to a Sub-'make':
3476 Variables/Recursion.), forcing it to be passed in the environment to
3479 However, on MS-DOS and MS-Windows the value of 'SHELL' in the
3480 environment *is* used, since on those systems most users do not set this
3481 variable, and therefore it is most likely set specifically to be used by
3482 'make'. On MS-DOS, if the setting of 'SHELL' is not suitable for
3483 'make', you can set the variable 'MAKESHELL' to the shell that 'make'
3484 should use; if set it will be used as the shell instead of the value of
3487 Choosing a Shell in DOS and Windows
3488 ...................................
3490 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3493 On MS-DOS, if 'SHELL' is not set, the value of the variable 'COMSPEC'
3494 (which is always set) is used instead.
3496 The processing of lines that set the variable 'SHELL' in Makefiles is
3497 different on MS-DOS. The stock shell, 'command.com', is ridiculously
3498 limited in its functionality and many users of 'make' tend to install a
3499 replacement shell. Therefore, on MS-DOS, 'make' examines the value of
3500 'SHELL', and changes its behavior based on whether it points to a
3501 Unix-style or DOS-style shell. This allows reasonable functionality
3502 even if 'SHELL' points to 'command.com'.
3504 If 'SHELL' points to a Unix-style shell, 'make' on MS-DOS
3505 additionally checks whether that shell can indeed be found; if not, it
3506 ignores the line that sets 'SHELL'. In MS-DOS, GNU 'make' searches for
3507 the shell in the following places:
3509 1. In the precise place pointed to by the value of 'SHELL'. For
3510 example, if the makefile specifies 'SHELL = /bin/sh', 'make' will
3511 look in the directory '/bin' on the current drive.
3513 2. In the current directory.
3515 3. In each of the directories in the 'PATH' variable, in order.
3517 In every directory it examines, 'make' will first look for the
3518 specific file ('sh' in the example above). If this is not found, it
3519 will also look in that directory for that file with one of the known
3520 extensions which identify executable files. For example '.exe', '.com',
3521 '.bat', '.btm', '.sh', and some others.
3523 If any of these attempts is successful, the value of 'SHELL' will be
3524 set to the full pathname of the shell as found. However, if none of
3525 these is found, the value of 'SHELL' will not be changed, and thus the
3526 line that sets it will be effectively ignored. This is so 'make' will
3527 only support features specific to a Unix-style shell if such a shell is
3528 actually installed on the system where 'make' runs.
3530 Note that this extended search for the shell is limited to the cases
3531 where 'SHELL' is set from the Makefile; if it is set in the environment
3532 or command line, you are expected to set it to the full pathname of the
3533 shell, exactly as things are on Unix.
3535 The effect of the above DOS-specific processing is that a Makefile
3536 that contains 'SHELL = /bin/sh' (as many Unix makefiles do), will work
3537 on MS-DOS unaltered if you have e.g. 'sh.exe' installed in some
3538 directory along your 'PATH'.
3541 File: make.info, Node: Parallel, Next: Errors, Prev: Execution, Up: Recipes
3543 5.4 Parallel Execution
3544 ======================
3546 GNU 'make' knows how to execute several recipes at once. Normally,
3547 'make' will execute only one recipe at a time, waiting for it to finish
3548 before executing the next. However, the '-j' or '--jobs' option tells
3549 'make' to execute many recipes simultaneously. You can inhibit
3550 parallelism in a particular makefile with the '.NOTPARALLEL'
3551 pseudo-target (*note Special Built-in Target Names: Special Targets.).
3553 On MS-DOS, the '-j' option has no effect, since that system doesn't
3554 support multi-processing.
3556 If the '-j' option is followed by an integer, this is the number of
3557 recipes to execute at once; this is called the number of "job slots".
3558 If there is nothing looking like an integer after the '-j' option, there
3559 is no limit on the number of job slots. The default number of job slots
3560 is one, which means serial execution (one thing at a time).
3562 Handling recursive 'make' invocations raises issues for parallel
3563 execution. For more information on this, see *note Communicating
3564 Options to a Sub-'make': Options/Recursion.
3566 If a recipe fails (is killed by a signal or exits with a nonzero
3567 status), and errors are not ignored for that recipe (*note Errors in
3568 Recipes: Errors.), the remaining recipe lines to remake the same target
3569 will not be run. If a recipe fails and the '-k' or '--keep-going'
3570 option was not given (*note Summary of Options: Options Summary.),
3571 'make' aborts execution. If make terminates for any reason (including a
3572 signal) with child processes running, it waits for them to finish before
3575 When the system is heavily loaded, you will probably want to run
3576 fewer jobs than when it is lightly loaded. You can use the '-l' option
3577 to tell 'make' to limit the number of jobs to run at once, based on the
3578 load average. The '-l' or '--max-load' option is followed by a
3579 floating-point number. For example,
3583 will not let 'make' start more than one job if the load average is above
3584 2.5. The '-l' option with no following number removes the load limit,
3585 if one was given with a previous '-l' option.
3587 More precisely, when 'make' goes to start up a job, and it already
3588 has at least one job running, it checks the current load average; if it
3589 is not lower than the limit given with '-l', 'make' waits until the load
3590 average goes below that limit, or until all the other jobs finish.
3592 By default, there is no load limit.
3596 * Parallel Output:: Handling output during parallel execution
3597 * Parallel Input:: Handling input during parallel execution
3600 File: make.info, Node: Parallel Output, Next: Parallel Input, Prev: Parallel, Up: Parallel
3602 5.4.1 Output During Parallel Execution
3603 --------------------------------------
3605 When running several recipes in parallel the output from each recipe
3606 appears as soon as it is generated, with the result that messages from
3607 different recipes may be interspersed, sometimes even appearing on the
3608 same line. This can make reading the output very difficult.
3610 To avoid this you can use the '--output-sync' ('-O') option. This
3611 option instructs 'make' to save the output from the commands it invokes
3612 and print it all once the commands are completed. Additionally, if
3613 there are multiple recursive 'make' invocations running in parallel,
3614 they will communicate so that only one of them is generating output at a
3617 If working directory printing is enabled (*note The
3618 '--print-directory' Option: -w Option.), the enter/leave messages are
3619 printed around each output grouping. If you prefer not to see these
3620 messages add the '--no-print-directory' option to 'MAKEFLAGS'.
3622 There are four levels of granularity when synchronizing output,
3623 specified by giving an argument to the option (e.g., '-Oline' or
3624 '--output-sync=recurse').
3627 This is the default: all output is sent directly as it is generated
3628 and no synchronization is performed.
3631 Output from each individual line of the recipe is grouped and
3632 printed as soon as that line is complete. If a recipe consists of
3633 multiple lines, they may be interspersed with lines from other
3637 Output from the entire recipe for each target is grouped and
3638 printed once the target is complete. This is the default if the
3639 '--output-sync' or '-O' option is given with no argument.
3642 Output from each recursive invocation of 'make' is grouped and
3643 printed once the recursive invocation is complete.
3645 Regardless of the mode chosen, the total build time will be the same.
3646 The only difference is in how the output appears.
3648 The 'target' and 'recurse' modes both collect the output of the
3649 entire recipe of a target and display it uninterrupted when the recipe
3650 completes. The difference between them is in how recipes that contain
3651 recursive invocations of 'make' are treated (*note Recursive Use of
3652 'make': Recursion.). For all recipes which have no recursive lines, the
3653 'target' and 'recurse' modes behave identically.
3655 If the 'recurse' mode is chosen, recipes that contain recursive
3656 'make' invocations are treated the same as other targets: the output
3657 from the recipe, including the output from the recursive 'make', is
3658 saved and printed after the entire recipe is complete. This ensures
3659 output from all the targets built by a given recursive 'make' instance
3660 are grouped together, which may make the output easier to understand.
3661 However it also leads to long periods of time during the build where no
3662 output is seen, followed by large bursts of output. If you are not
3663 watching the build as it proceeds, but instead viewing a log of the
3664 build after the fact, this may be the best option for you.
3666 If you are watching the output, the long gaps of quiet during the
3667 build can be frustrating. The 'target' output synchronization mode
3668 detects when 'make' is going to be invoked recursively, using the
3669 standard methods, and it will not synchronize the output of those lines.
3670 The recursive 'make' will perform the synchronization for its targets
3671 and the output from each will be displayed immediately when it
3672 completes. Be aware that output from recursive lines of the recipe are
3673 not synchronized (for example if the recursive line prints a message
3674 before running 'make', that message will not be synchronized).
3676 The 'line' mode can be useful for front-ends that are watching the
3677 output of 'make' to track when recipes are started and completed.
3679 Some programs invoked by 'make' may behave differently if they
3680 determine they're writing output to a terminal versus a file (often
3681 described as "interactive" vs. "non-interactive" modes). For example,
3682 many programs that can display colorized output will not do so if they
3683 determine they are not writing to a terminal. If your makefile invokes
3684 a program like this then using the output synchronization options will
3685 cause the program to believe it's running in "non-interactive" mode even
3686 though the output will ultimately go to the terminal.
3689 File: make.info, Node: Parallel Input, Prev: Parallel Output, Up: Parallel
3691 5.4.2 Input During Parallel Execution
3692 -------------------------------------
3694 Two processes cannot both take input from the same device at the same
3695 time. To make sure that only one recipe tries to take input from the
3696 terminal at once, 'make' will invalidate the standard input streams of
3697 all but one running recipe. If another recipe attempts to read from
3698 standard input it will usually incur a fatal error (a 'Broken pipe'
3701 It is unpredictable which recipe will have a valid standard input
3702 stream (which will come from the terminal, or wherever you redirect the
3703 standard input of 'make'). The first recipe run will always get it
3704 first, and the first recipe started after that one finishes will get it
3707 We will change how this aspect of 'make' works if we find a better
3708 alternative. In the mean time, you should not rely on any recipe using
3709 standard input at all if you are using the parallel execution feature;
3710 but if you are not using this feature, then standard input works
3711 normally in all recipes.
3714 File: make.info, Node: Errors, Next: Interrupts, Prev: Parallel, Up: Recipes
3716 5.5 Errors in Recipes
3717 =====================
3719 After each shell invocation returns, 'make' looks at its exit status.
3720 If the shell completed successfully (the exit status is zero), the next
3721 line in the recipe is executed in a new shell; after the last line is
3722 finished, the rule is finished.
3724 If there is an error (the exit status is nonzero), 'make' gives up on
3725 the current rule, and perhaps on all rules.
3727 Sometimes the failure of a certain recipe line does not indicate a
3728 problem. For example, you may use the 'mkdir' command to ensure that a
3729 directory exists. If the directory already exists, 'mkdir' will report
3730 an error, but you probably want 'make' to continue regardless.
3732 To ignore errors in a recipe line, write a '-' at the beginning of
3733 the line's text (after the initial tab). The '-' is discarded before
3734 the line is passed to the shell for execution.
3741 This causes 'make' to continue even if 'rm' is unable to remove a file.
3743 When you run 'make' with the '-i' or '--ignore-errors' flag, errors
3744 are ignored in all recipes of all rules. A rule in the makefile for the
3745 special target '.IGNORE' has the same effect, if there are no
3746 prerequisites. This is less flexible but sometimes useful.
3748 When errors are to be ignored, because of either a '-' or the '-i'
3749 flag, 'make' treats an error return just like success, except that it
3750 prints out a message that tells you the status code the shell exited
3751 with, and says that the error has been ignored.
3753 When an error happens that 'make' has not been told to ignore, it
3754 implies that the current target cannot be correctly remade, and neither
3755 can any other that depends on it either directly or indirectly. No
3756 further recipes will be executed for these targets, since their
3757 preconditions have not been achieved.
3759 Normally 'make' gives up immediately in this circumstance, returning
3760 a nonzero status. However, if the '-k' or '--keep-going' flag is
3761 specified, 'make' continues to consider the other prerequisites of the
3762 pending targets, remaking them if necessary, before it gives up and
3763 returns nonzero status. For example, after an error in compiling one
3764 object file, 'make -k' will continue compiling other object files even
3765 though it already knows that linking them will be impossible. *Note
3766 Summary of Options: Options Summary.
3768 The usual behavior assumes that your purpose is to get the specified
3769 targets up to date; once 'make' learns that this is impossible, it might
3770 as well report the failure immediately. The '-k' option says that the
3771 real purpose is to test as many of the changes made in the program as
3772 possible, perhaps to find several independent problems so that you can
3773 correct them all before the next attempt to compile. This is why Emacs'
3774 'compile' command passes the '-k' flag by default.
3776 Usually when a recipe line fails, if it has changed the target file
3777 at all, the file is corrupted and cannot be used--or at least it is not
3778 completely updated. Yet the file's time stamp says that it is now up to
3779 date, so the next time 'make' runs, it will not try to update that file.
3780 The situation is just the same as when the shell is killed by a signal;
3781 *note Interrupts::. So generally the right thing to do is to delete the
3782 target file if the recipe fails after beginning to change the file.
3783 'make' will do this if '.DELETE_ON_ERROR' appears as a target. This is
3784 almost always what you want 'make' to do, but it is not historical
3785 practice; so for compatibility, you must explicitly request it.
3788 File: make.info, Node: Interrupts, Next: Recursion, Prev: Errors, Up: Recipes
3790 5.6 Interrupting or Killing 'make'
3791 ==================================
3793 If 'make' gets a fatal signal while a shell is executing, it may delete
3794 the target file that the recipe was supposed to update. This is done if
3795 the target file's last-modification time has changed since 'make' first
3798 The purpose of deleting the target is to make sure that it is remade
3799 from scratch when 'make' is next run. Why is this? Suppose you type
3800 'Ctrl-c' while a compiler is running, and it has begun to write an
3801 object file 'foo.o'. The 'Ctrl-c' kills the compiler, resulting in an
3802 incomplete file whose last-modification time is newer than the source
3803 file 'foo.c'. But 'make' also receives the 'Ctrl-c' signal and deletes
3804 this incomplete file. If 'make' did not do this, the next invocation of
3805 'make' would think that 'foo.o' did not require updating--resulting in a
3806 strange error message from the linker when it tries to link an object
3807 file half of which is missing.
3809 You can prevent the deletion of a target file in this way by making
3810 the special target '.PRECIOUS' depend on it. Before remaking a target,
3811 'make' checks to see whether it appears on the prerequisites of
3812 '.PRECIOUS', and thereby decides whether the target should be deleted if
3813 a signal happens. Some reasons why you might do this are that the
3814 target is updated in some atomic fashion, or exists only to record a
3815 modification-time (its contents do not matter), or must exist at all
3816 times to prevent other sorts of trouble.
3818 Although 'make' does its best to clean up there are certain
3819 situations in which cleanup is impossible. For example, 'make' may be
3820 killed by an uncatchable signal. Or, one of the programs make invokes
3821 may be killed or crash, leaving behind an up-to-date but corrupt target
3822 file: 'make' will not realize that this failure requires the target to
3823 be cleaned. Or 'make' itself may encounter a bug and crash.
3825 For these reasons it's best to write _defensive recipes_, which won't
3826 leave behind corrupted targets even if they fail. Most commonly these
3827 recipes create temporary files rather than updating the target directly,
3828 then rename the temporary file to the final target name. Some compilers
3829 already behave this way, so that you don't need to write a defensive
3833 File: make.info, Node: Recursion, Next: Canned Recipes, Prev: Interrupts, Up: Recipes
3835 5.7 Recursive Use of 'make'
3836 ===========================
3838 Recursive use of 'make' means using 'make' as a command in a makefile.
3839 This technique is useful when you want separate makefiles for various
3840 subsystems that compose a larger system. For example, suppose you have
3841 a sub-directory 'subdir' which has its own makefile, and you would like
3842 the containing directory's makefile to run 'make' on the sub-directory.
3843 You can do it by writing this:
3846 cd subdir && $(MAKE)
3848 or, equivalently, this (*note Summary of Options: Options Summary.):
3853 You can write recursive 'make' commands just by copying this example,
3854 but there are many things to know about how they work and why, and about
3855 how the sub-'make' relates to the top-level 'make'. You may also find
3856 it useful to declare targets that invoke recursive 'make' commands as
3857 '.PHONY' (for more discussion on when this is useful, see *note Phony
3860 For your convenience, when GNU 'make' starts (after it has processed
3861 any '-C' options) it sets the variable 'CURDIR' to the pathname of the
3862 current working directory. This value is never touched by 'make' again:
3863 in particular note that if you include files from other directories the
3864 value of 'CURDIR' does not change. The value has the same precedence it
3865 would have if it were set in the makefile (by default, an environment
3866 variable 'CURDIR' will not override this value). Note that setting this
3867 variable has no impact on the operation of 'make' (it does not cause
3868 'make' to change its working directory, for example).
3872 * MAKE Variable:: The special effects of using '$(MAKE)'.
3873 * Variables/Recursion:: How to communicate variables to a sub-'make'.
3874 * Options/Recursion:: How to communicate options to a sub-'make'.
3875 * -w Option:: How the '-w' or '--print-directory' option
3876 helps debug use of recursive 'make' commands.
3879 File: make.info, Node: MAKE Variable, Next: Variables/Recursion, Prev: Recursion, Up: Recursion
3881 5.7.1 How the 'MAKE' Variable Works
3882 -----------------------------------
3884 Recursive 'make' commands should always use the variable 'MAKE', not the
3885 explicit command name 'make', as shown here:
3888 cd subdir && $(MAKE)
3890 The value of this variable is the file name with which 'make' was
3891 invoked. If this file name was '/bin/make', then the recipe executed is
3892 'cd subdir && /bin/make'. If you use a special version of 'make' to run
3893 the top-level makefile, the same special version will be executed for
3894 recursive invocations.
3896 As a special feature, using the variable 'MAKE' in the recipe of a
3897 rule alters the effects of the '-t' ('--touch'), '-n' ('--just-print'),
3898 or '-q' ('--question') option. Using the 'MAKE' variable has the same
3899 effect as using a '+' character at the beginning of the recipe line.
3900 *Note Instead of Executing the Recipes: Instead of Execution. This
3901 special feature is only enabled if the 'MAKE' variable appears directly
3902 in the recipe: it does not apply if the 'MAKE' variable is referenced
3903 through expansion of another variable. In the latter case you must use
3904 the '+' token to get these special effects.
3906 Consider the command 'make -t' in the above example. (The '-t'
3907 option marks targets as up to date without actually running any recipes;
3908 see *note Instead of Execution::.) Following the usual definition of
3909 '-t', a 'make -t' command in the example would create a file named
3910 'subsystem' and do nothing else. What you really want it to do is run
3911 'cd subdir && make -t'; but that would require executing the recipe, and
3912 '-t' says not to execute recipes.
3914 The special feature makes this do what you want: whenever a recipe
3915 line of a rule contains the variable 'MAKE', the flags '-t', '-n' and
3916 '-q' do not apply to that line. Recipe lines containing 'MAKE' are
3917 executed normally despite the presence of a flag that causes most
3918 recipes not to be run. The usual 'MAKEFLAGS' mechanism passes the flags
3919 to the sub-'make' (*note Communicating Options to a Sub-'make':
3920 Options/Recursion.), so your request to touch the files, or print the
3921 recipes, is propagated to the subsystem.
3924 File: make.info, Node: Variables/Recursion, Next: Options/Recursion, Prev: MAKE Variable, Up: Recursion
3926 5.7.2 Communicating Variables to a Sub-'make'
3927 ---------------------------------------------
3929 Variable values of the top-level 'make' can be passed to the sub-'make'
3930 through the environment by explicit request. These variables are
3931 defined in the sub-'make' as defaults, but they do not override
3932 variables defined in the makefile used by the sub-'make' unless you use
3933 the '-e' switch (*note Summary of Options: Options Summary.).
3935 To pass down, or "export", a variable, 'make' adds the variable and
3936 its value to the environment for running each line of the recipe. The
3937 sub-'make', in turn, uses the environment to initialize its table of
3938 variable values. *Note Variables from the Environment: Environment.
3940 Except by explicit request, 'make' exports a variable only if it is
3941 either defined in the environment initially or set on the command line,
3942 and if its name consists only of letters, numbers, and underscores.
3943 Some shells cannot cope with environment variable names consisting of
3944 characters other than letters, numbers, and underscores.
3946 The value of the 'make' variable 'SHELL' is not exported. Instead,
3947 the value of the 'SHELL' variable from the invoking environment is
3948 passed to the sub-'make'. You can force 'make' to export its value for
3949 'SHELL' by using the 'export' directive, described below. *Note
3950 Choosing the Shell::.
3952 The special variable 'MAKEFLAGS' is always exported (unless you
3953 unexport it). 'MAKEFILES' is exported if you set it to anything.
3955 'make' automatically passes down variable values that were defined on
3956 the command line, by putting them in the 'MAKEFLAGS' variable. *Note
3957 Options/Recursion::.
3959 Variables are _not_ normally passed down if they were created by
3960 default by 'make' (*note Variables Used by Implicit Rules: Implicit
3961 Variables.). The sub-'make' will define these for itself.
3963 If you want to export specific variables to a sub-'make', use the
3964 'export' directive, like this:
3968 If you want to _prevent_ a variable from being exported, use the
3969 'unexport' directive, like this:
3971 unexport VARIABLE ...
3973 In both of these forms, the arguments to 'export' and 'unexport' are
3974 expanded, and so could be variables or functions which expand to a (list
3975 of) variable names to be (un)exported.
3977 As a convenience, you can define a variable and export it at the same
3980 export VARIABLE = value
3982 has the same result as:
3989 export VARIABLE := value
3991 has the same result as:
3998 export VARIABLE += value
4005 *Note Appending More Text to Variables: Appending.
4007 You may notice that the 'export' and 'unexport' directives work in
4008 'make' in the same way they work in the shell, 'sh'.
4010 If you want all variables to be exported by default, you can use
4015 This tells 'make' that variables which are not explicitly mentioned in
4016 an 'export' or 'unexport' directive should be exported. Any variable
4017 given in an 'unexport' directive will still _not_ be exported. If you
4018 use 'export' by itself to export variables by default, variables whose
4019 names contain characters other than alphanumerics and underscores will
4020 not be exported unless specifically mentioned in an 'export' directive.
4022 The behavior elicited by an 'export' directive by itself was the
4023 default in older versions of GNU 'make'. If your makefiles depend on
4024 this behavior and you want to be compatible with old versions of 'make',
4025 you can write a rule for the special target '.EXPORT_ALL_VARIABLES'
4026 instead of using the 'export' directive. This will be ignored by old
4027 'make's, while the 'export' directive will cause a syntax error.
4029 Likewise, you can use 'unexport' by itself to tell 'make' _not_ to
4030 export variables by default. Since this is the default behavior, you
4031 would only need to do this if 'export' had been used by itself earlier
4032 (in an included makefile, perhaps). You *cannot* use 'export' and
4033 'unexport' by themselves to have variables exported for some recipes and
4034 not for others. The last 'export' or 'unexport' directive that appears
4035 by itself determines the behavior for the entire run of 'make'.
4037 As a special feature, the variable 'MAKELEVEL' is changed when it is
4038 passed down from level to level. This variable's value is a string
4039 which is the depth of the level as a decimal number. The value is '0'
4040 for the top-level 'make'; '1' for a sub-'make', '2' for a
4041 sub-sub-'make', and so on. The incrementation happens when 'make' sets
4042 up the environment for a recipe.
4044 The main use of 'MAKELEVEL' is to test it in a conditional directive
4045 (*note Conditional Parts of Makefiles: Conditionals.); this way you can
4046 write a makefile that behaves one way if run recursively and another way
4047 if run directly by you.
4049 You can use the variable 'MAKEFILES' to cause all sub-'make' commands
4050 to use additional makefiles. The value of 'MAKEFILES' is a
4051 whitespace-separated list of file names. This variable, if defined in
4052 the outer-level makefile, is passed down through the environment; then
4053 it serves as a list of extra makefiles for the sub-'make' to read before
4054 the usual or specified ones. *Note The Variable 'MAKEFILES': MAKEFILES
4058 File: make.info, Node: Options/Recursion, Next: -w Option, Prev: Variables/Recursion, Up: Recursion
4060 5.7.3 Communicating Options to a Sub-'make'
4061 -------------------------------------------
4063 Flags such as '-s' and '-k' are passed automatically to the sub-'make'
4064 through the variable 'MAKEFLAGS'. This variable is set up automatically
4065 by 'make' to contain the flag letters that 'make' received. Thus, if
4066 you do 'make -ks' then 'MAKEFLAGS' gets the value 'ks'.
4068 As a consequence, every sub-'make' gets a value for 'MAKEFLAGS' in
4069 its environment. In response, it takes the flags from that value and
4070 processes them as if they had been given as arguments. *Note Summary of
4071 Options: Options Summary.
4073 Likewise variables defined on the command line are passed to the
4074 sub-'make' through 'MAKEFLAGS'. Words in the value of 'MAKEFLAGS' that
4075 contain '=', 'make' treats as variable definitions just as if they
4076 appeared on the command line. *Note Overriding Variables: Overriding.
4078 The options '-C', '-f', '-o', and '-W' are not put into 'MAKEFLAGS';
4079 these options are not passed down.
4081 The '-j' option is a special case (*note Parallel Execution:
4082 Parallel.). If you set it to some numeric value 'N' and your operating
4083 system supports it (most any UNIX system will; others typically won't),
4084 the parent 'make' and all the sub-'make's will communicate to ensure
4085 that there are only 'N' jobs running at the same time between them all.
4086 Note that any job that is marked recursive (*note Instead of Executing
4087 Recipes: Instead of Execution.) doesn't count against the total jobs
4088 (otherwise we could get 'N' sub-'make's running and have no slots left
4089 over for any real work!)
4091 If your operating system doesn't support the above communication,
4092 then no '-j' is added to 'MAKEFLAGS', so that sub-'make's run in
4093 non-parallel mode. If the '-j' option were passed down to sub-'make's
4094 you would get many more jobs running in parallel than you asked for. If
4095 you give '-j' with no numeric argument, meaning to run as many jobs as
4096 possible in parallel, this is passed down, since multiple infinities are
4099 If you do not want to pass the other flags down, you must change the
4100 value of 'MAKEFLAGS', like this:
4103 cd subdir && $(MAKE) MAKEFLAGS=
4105 The command line variable definitions really appear in the variable
4106 'MAKEOVERRIDES', and 'MAKEFLAGS' contains a reference to this variable.
4107 If you do want to pass flags down normally, but don't want to pass down
4108 the command line variable definitions, you can reset 'MAKEOVERRIDES' to
4113 This is not usually useful to do. However, some systems have a small
4114 fixed limit on the size of the environment, and putting so much
4115 information into the value of 'MAKEFLAGS' can exceed it. If you see the
4116 error message 'Arg list too long', this may be the problem. (For strict
4117 compliance with POSIX.2, changing 'MAKEOVERRIDES' does not affect
4118 'MAKEFLAGS' if the special target '.POSIX' appears in the makefile. You
4119 probably do not care about this.)
4121 A similar variable 'MFLAGS' exists also, for historical
4122 compatibility. It has the same value as 'MAKEFLAGS' except that it does
4123 not contain the command line variable definitions, and it always begins
4124 with a hyphen unless it is empty ('MAKEFLAGS' begins with a hyphen only
4125 when it begins with an option that has no single-letter version, such as
4126 '--warn-undefined-variables'). 'MFLAGS' was traditionally used
4127 explicitly in the recursive 'make' command, like this:
4130 cd subdir && $(MAKE) $(MFLAGS)
4132 but now 'MAKEFLAGS' makes this usage redundant. If you want your
4133 makefiles to be compatible with old 'make' programs, use this technique;
4134 it will work fine with more modern 'make' versions too.
4136 The 'MAKEFLAGS' variable can also be useful if you want to have
4137 certain options, such as '-k' (*note Summary of Options: Options
4138 Summary.), set each time you run 'make'. You simply put a value for
4139 'MAKEFLAGS' in your environment. You can also set 'MAKEFLAGS' in a
4140 makefile, to specify additional flags that should also be in effect for
4141 that makefile. (Note that you cannot use 'MFLAGS' this way. That
4142 variable is set only for compatibility; 'make' does not interpret a
4143 value you set for it in any way.)
4145 When 'make' interprets the value of 'MAKEFLAGS' (either from the
4146 environment or from a makefile), it first prepends a hyphen if the value
4147 does not already begin with one. Then it chops the value into words
4148 separated by blanks, and parses these words as if they were options
4149 given on the command line (except that '-C', '-f', '-h', '-o', '-W', and
4150 their long-named versions are ignored; and there is no error for an
4153 If you do put 'MAKEFLAGS' in your environment, you should be sure not
4154 to include any options that will drastically affect the actions of
4155 'make' and undermine the purpose of makefiles and of 'make' itself. For
4156 instance, the '-t', '-n', and '-q' options, if put in one of these
4157 variables, could have disastrous consequences and would certainly have
4158 at least surprising and probably annoying effects.
4160 If you'd like to run other implementations of 'make' in addition to
4161 GNU 'make', and hence do not want to add GNU 'make'-specific flags to
4162 the 'MAKEFLAGS' variable, you can add them to the 'GNUMAKEFLAGS'
4163 variable instead. This variable is parsed just before 'MAKEFLAGS', in
4164 the same way as 'MAKEFLAGS'. When 'make' constructs 'MAKEFLAGS' to pass
4165 to a recursive 'make' it will include all flags, even those taken from
4166 'GNUMAKEFLAGS'. As a result, after parsing 'GNUMAKEFLAGS' GNU 'make'
4167 sets this variable to the empty string to avoid duplicating flags during
4170 It's best to use 'GNUMAKEFLAGS' only with flags which won't
4171 materially change the behavior of your makefiles. If your makefiles
4172 require GNU make anyway then simply use 'MAKEFLAGS'. Flags such as
4173 '--no-print-directory' or '--output-sync' may be appropriate for
4177 File: make.info, Node: -w Option, Prev: Options/Recursion, Up: Recursion
4179 5.7.4 The '--print-directory' Option
4180 ------------------------------------
4182 If you use several levels of recursive 'make' invocations, the '-w' or
4183 '--print-directory' option can make the output a lot easier to
4184 understand by showing each directory as 'make' starts processing it and
4185 as 'make' finishes processing it. For example, if 'make -w' is run in
4186 the directory '/u/gnu/make', 'make' will print a line of the form:
4188 make: Entering directory `/u/gnu/make'.
4190 before doing anything else, and a line of the form:
4192 make: Leaving directory `/u/gnu/make'.
4194 when processing is completed.
4196 Normally, you do not need to specify this option because 'make' does
4197 it for you: '-w' is turned on automatically when you use the '-C'
4198 option, and in sub-'make's. 'make' will not automatically turn on '-w'
4199 if you also use '-s', which says to be silent, or if you use
4200 '--no-print-directory' to explicitly disable it.
4203 File: make.info, Node: Canned Recipes, Next: Empty Recipes, Prev: Recursion, Up: Recipes
4205 5.8 Defining Canned Recipes
4206 ===========================
4208 When the same sequence of commands is useful in making various targets,
4209 you can define it as a canned sequence with the 'define' directive, and
4210 refer to the canned sequence from the recipes for those targets. The
4211 canned sequence is actually a variable, so the name must not conflict
4212 with other variable names.
4214 Here is an example of defining a canned recipe:
4217 yacc $(firstword $^)
4221 Here 'run-yacc' is the name of the variable being defined; 'endef' marks
4222 the end of the definition; the lines in between are the commands. The
4223 'define' directive does not expand variable references and function
4224 calls in the canned sequence; the '$' characters, parentheses, variable
4225 names, and so on, all become part of the value of the variable you are
4226 defining. *Note Defining Multi-Line Variables: Multi-Line, for a
4227 complete explanation of 'define'.
4229 The first command in this example runs Yacc on the first prerequisite
4230 of whichever rule uses the canned sequence. The output file from Yacc
4231 is always named 'y.tab.c'. The second command moves the output to the
4232 rule's target file name.
4234 To use the canned sequence, substitute the variable into the recipe
4235 of a rule. You can substitute it like any other variable (*note Basics
4236 of Variable References: Reference.). Because variables defined by
4237 'define' are recursively expanded variables, all the variable references
4238 you wrote inside the 'define' are expanded now. For example:
4243 'foo.y' will be substituted for the variable '$^' when it occurs in
4244 'run-yacc''s value, and 'foo.c' for '$@'.
4246 This is a realistic example, but this particular one is not needed in
4247 practice because 'make' has an implicit rule to figure out these
4248 commands based on the file names involved (*note Using Implicit Rules:
4251 In recipe execution, each line of a canned sequence is treated just
4252 as if the line appeared on its own in the rule, preceded by a tab. In
4253 particular, 'make' invokes a separate sub-shell for each line. You can
4254 use the special prefix characters that affect command lines ('@', '-',
4255 and '+') on each line of a canned sequence. *Note Writing Recipes in
4256 Rules: Recipes. For example, using this canned sequence:
4259 @echo "frobnicating target $@"
4260 frob-step-1 $< -o $@-step-1
4261 frob-step-2 $@-step-1 -o $@
4264 'make' will not echo the first line, the 'echo' command. But it _will_
4265 echo the following two recipe lines.
4267 On the other hand, prefix characters on the recipe line that refers
4268 to a canned sequence apply to every line in the sequence. So the rule:
4273 does not echo _any_ recipe lines. (*Note Recipe Echoing: Echoing, for a
4274 full explanation of '@'.)
4277 File: make.info, Node: Empty Recipes, Prev: Canned Recipes, Up: Recipes
4279 5.9 Using Empty Recipes
4280 =======================
4282 It is sometimes useful to define recipes which do nothing. This is done
4283 simply by giving a recipe that consists of nothing but whitespace. For
4288 defines an empty recipe for 'target'. You could also use a line
4289 beginning with a recipe prefix character to define an empty recipe, but
4290 this would be confusing because such a line looks empty.
4292 You may be wondering why you would want to define a recipe that does
4293 nothing. One reason this is useful is to prevent a target from getting
4294 implicit recipes (from implicit rules or the '.DEFAULT' special target;
4295 *note Implicit Rules:: and *note Defining Last-Resort Default Rules:
4298 Empty recipes can also be used to avoid errors for targets that will
4299 be created as a side-effect of another recipe: if the target does not
4300 exist the empty recipe ensures that 'make' won't complain that it
4301 doesn't know how to build the target, and 'make' will assume the target
4304 You may be inclined to define empty recipes for targets that are not
4305 actual files, but only exist so that their prerequisites can be remade.
4306 However, this is not the best way to do that, because the prerequisites
4307 may not be remade properly if the target file actually does exist.
4308 *Note Phony Targets: Phony Targets, for a better way to do this.
4311 File: make.info, Node: Using Variables, Next: Conditionals, Prev: Recipes, Up: Top
4313 6 How to Use Variables
4314 **********************
4316 A "variable" is a name defined in a makefile to represent a string of
4317 text, called the variable's "value". These values are substituted by
4318 explicit request into targets, prerequisites, recipes, and other parts
4319 of the makefile. (In some other versions of 'make', variables are
4322 Variables and functions in all parts of a makefile are expanded when
4323 read, except for in recipes, the right-hand sides of variable
4324 definitions using '=', and the bodies of variable definitions using the
4327 Variables can represent lists of file names, options to pass to
4328 compilers, programs to run, directories to look in for source files,
4329 directories to write output in, or anything else you can imagine.
4331 A variable name may be any sequence of characters not containing ':',
4332 '#', '=', or whitespace. However, variable names containing characters
4333 other than letters, numbers, and underscores should be considered
4334 carefully, as in some shells they cannot be passed through the
4335 environment to a sub-'make' (*note Communicating Variables to a
4336 Sub-'make': Variables/Recursion.). Variable names beginning with '.'
4337 and an uppercase letter may be given special meaning in future versions
4340 Variable names are case-sensitive. The names 'foo', 'FOO', and 'Foo'
4341 all refer to different variables.
4343 It is traditional to use upper case letters in variable names, but we
4344 recommend using lower case letters for variable names that serve
4345 internal purposes in the makefile, and reserving upper case for
4346 parameters that control implicit rules or for parameters that the user
4347 should override with command options (*note Overriding Variables:
4350 A few variables have names that are a single punctuation character or
4351 just a few characters. These are the "automatic variables", and they
4352 have particular specialized uses. *Note Automatic Variables::.
4356 * Reference:: How to use the value of a variable.
4357 * Flavors:: Variables come in two flavors.
4358 * Advanced:: Advanced features for referencing a variable.
4359 * Values:: All the ways variables get their values.
4360 * Setting:: How to set a variable in the makefile.
4361 * Appending:: How to append more text to the old value
4363 * Override Directive:: How to set a variable in the makefile even if
4364 the user has set it with a command argument.
4365 * Multi-Line:: An alternate way to set a variable
4366 to a multi-line string.
4367 * Undefine Directive:: How to undefine a variable so that it appears
4368 as if it was never set.
4369 * Environment:: Variable values can come from the environment.
4370 * Target-specific:: Variable values can be defined on a per-target
4372 * Pattern-specific:: Target-specific variable values can be applied
4373 to a group of targets that match a pattern.
4374 * Suppressing Inheritance:: Suppress inheritance of variables.
4375 * Special Variables:: Variables with special meaning or behavior.
4378 File: make.info, Node: Reference, Next: Flavors, Prev: Using Variables, Up: Using Variables
4380 6.1 Basics of Variable References
4381 =================================
4383 To substitute a variable's value, write a dollar sign followed by the
4384 name of the variable in parentheses or braces: either '$(foo)' or
4385 '${foo}' is a valid reference to the variable 'foo'. This special
4386 significance of '$' is why you must write '$$' to have the effect of a
4387 single dollar sign in a file name or recipe.
4389 Variable references can be used in any context: targets,
4390 prerequisites, recipes, most directives, and new variable values. Here
4391 is an example of a common case, where a variable holds the names of all
4392 the object files in a program:
4394 objects = program.o foo.o utils.o
4395 program : $(objects)
4396 cc -o program $(objects)
4400 Variable references work by strict textual substitution. Thus, the
4404 prog.o : prog.$(foo)
4405 $(foo)$(foo) -$(foo) prog.$(foo)
4407 could be used to compile a C program 'prog.c'. Since spaces before the
4408 variable value are ignored in variable assignments, the value of 'foo'
4409 is precisely 'c'. (Don't actually write your makefiles this way!)
4411 A dollar sign followed by a character other than a dollar sign,
4412 open-parenthesis or open-brace treats that single character as the
4413 variable name. Thus, you could reference the variable 'x' with '$x'.
4414 However, this practice can lead to confusion (e.g., '$foo' refers to the
4415 variable 'f' followed by the string 'oo') so we recommend using
4416 parentheses or braces around all variables, even single-letter
4417 variables, unless omitting them gives significant readability
4418 improvements. One place where readability is often improved is
4419 automatic variables (*note Automatic Variables::).
4422 File: make.info, Node: Flavors, Next: Advanced, Prev: Reference, Up: Using Variables
4424 6.2 The Two Flavors of Variables
4425 ================================
4427 There are two ways that a variable in GNU 'make' can have a value; we
4428 call them the two "flavors" of variables. The two flavors are
4429 distinguished in how they are defined and in what they do when expanded.
4431 The first flavor of variable is a "recursively expanded" variable.
4432 Variables of this sort are defined by lines using '=' (*note Setting
4433 Variables: Setting.) or by the 'define' directive (*note Defining
4434 Multi-Line Variables: Multi-Line.). The value you specify is installed
4435 verbatim; if it contains references to other variables, these references
4436 are expanded whenever this variable is substituted (in the course of
4437 expanding some other string). When this happens, it is called
4438 "recursive expansion".
4448 will echo 'Huh?': '$(foo)' expands to '$(bar)' which expands to '$(ugh)'
4449 which finally expands to 'Huh?'.
4451 This flavor of variable is the only sort supported by most other
4452 versions of 'make'. It has its advantages and its disadvantages. An
4453 advantage (most would say) is that:
4455 CFLAGS = $(include_dirs) -O
4456 include_dirs = -Ifoo -Ibar
4458 will do what was intended: when 'CFLAGS' is expanded in a recipe, it
4459 will expand to '-Ifoo -Ibar -O'. A major disadvantage is that you
4460 cannot append something on the end of a variable, as in
4462 CFLAGS = $(CFLAGS) -O
4464 because it will cause an infinite loop in the variable expansion.
4465 (Actually 'make' detects the infinite loop and reports an error.)
4467 Another disadvantage is that any functions (*note Functions for
4468 Transforming Text: Functions.) referenced in the definition will be
4469 executed every time the variable is expanded. This makes 'make' run
4470 slower; worse, it causes the 'wildcard' and 'shell' functions to give
4471 unpredictable results because you cannot easily control when they are
4472 called, or even how many times.
4474 To avoid all the problems and inconveniences of recursively expanded
4475 variables, there is another flavor: simply expanded variables.
4477 "Simply expanded variables" are defined by lines using ':=' or '::='
4478 (*note Setting Variables: Setting.). Both forms are equivalent in GNU
4479 'make'; however only the '::=' form is described by the POSIX standard
4480 (support for '::=' was added to the POSIX standard in 2012, so older
4481 versions of 'make' won't accept this form either).
4483 The value of a simply expanded variable is scanned once and for all,
4484 expanding any references to other variables and functions, when the
4485 variable is defined. The actual value of the simply expanded variable
4486 is the result of expanding the text that you write. It does not contain
4487 any references to other variables; it contains their values _as of the
4488 time this variable was defined_. Therefore,
4499 When a simply expanded variable is referenced, its value is
4500 substituted verbatim.
4502 Here is a somewhat more complicated example, illustrating the use of
4503 ':=' in conjunction with the 'shell' function. (*Note The 'shell'
4504 Function: Shell Function.) This example also shows use of the variable
4505 'MAKELEVEL', which is changed when it is passed down from level to
4506 level. (*Note Communicating Variables to a Sub-'make':
4507 Variables/Recursion, for information about 'MAKELEVEL'.)
4509 ifeq (0,${MAKELEVEL})
4510 whoami := $(shell whoami)
4511 host-type := $(shell arch)
4512 MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
4515 An advantage of this use of ':=' is that a typical 'descend into a
4516 directory' recipe then looks like this:
4521 Simply expanded variables generally make complicated makefile
4522 programming more predictable because they work like variables in most
4523 programming languages. They allow you to redefine a variable using its
4524 own value (or its value processed in some way by one of the expansion
4525 functions) and to use the expansion functions much more efficiently
4526 (*note Functions for Transforming Text: Functions.).
4528 You can also use them to introduce controlled leading whitespace into
4529 variable values. Leading whitespace characters are discarded from your
4530 input before substitution of variable references and function calls;
4531 this means you can include leading spaces in a variable value by
4532 protecting them with variable references, like this:
4535 space := $(nullstring) # end of the line
4537 Here the value of the variable 'space' is precisely one space. The
4538 comment '# end of the line' is included here just for clarity. Since
4539 trailing space characters are _not_ stripped from variable values, just
4540 a space at the end of the line would have the same effect (but be rather
4541 hard to read). If you put whitespace at the end of a variable value, it
4542 is a good idea to put a comment like that at the end of the line to make
4543 your intent clear. Conversely, if you do _not_ want any whitespace
4544 characters at the end of your variable value, you must remember not to
4545 put a random comment on the end of the line after some whitespace, such
4548 dir := /foo/bar # directory to put the frobs in
4550 Here the value of the variable 'dir' is '/foo/bar ' (with four
4551 trailing spaces), which was probably not the intention. (Imagine
4552 something like '$(dir)/file' with this definition!)
4554 There is another assignment operator for variables, '?='. This is
4555 called a conditional variable assignment operator, because it only has
4556 an effect if the variable is not yet defined. This statement:
4560 is exactly equivalent to this (*note The 'origin' Function: Origin
4563 ifeq ($(origin FOO), undefined)
4567 Note that a variable set to an empty value is still defined, so '?='
4568 will not set that variable.
4571 File: make.info, Node: Advanced, Next: Values, Prev: Flavors, Up: Using Variables
4573 6.3 Advanced Features for Reference to Variables
4574 ================================================
4576 This section describes some advanced features you can use to reference
4577 variables in more flexible ways.
4581 * Substitution Refs:: Referencing a variable with
4582 substitutions on the value.
4583 * Computed Names:: Computing the name of the variable to refer to.
4586 File: make.info, Node: Substitution Refs, Next: Computed Names, Prev: Advanced, Up: Advanced
4588 6.3.1 Substitution References
4589 -----------------------------
4591 A "substitution reference" substitutes the value of a variable with
4592 alterations that you specify. It has the form '$(VAR:A=B)' (or
4593 '${VAR:A=B}') and its meaning is to take the value of the variable VAR,
4594 replace every A at the end of a word with B in that value, and
4595 substitute the resulting string.
4597 When we say "at the end of a word", we mean that A must appear either
4598 followed by whitespace or at the end of the value in order to be
4599 replaced; other occurrences of A in the value are unaltered. For
4602 foo := a.o b.o l.a c.o
4605 sets 'bar' to 'a.c b.c l.a c.c'. *Note Setting Variables: Setting.
4607 A substitution reference is shorthand for the 'patsubst' expansion
4608 function (*note Functions for String Substitution and Analysis: Text
4609 Functions.): '$(VAR:A=B)' is equivalent to '$(patsubst %A,%B,VAR)'. We
4610 provide substitution references as well as 'patsubst' for compatibility
4611 with other implementations of 'make'.
4613 Another type of substitution reference lets you use the full power of
4614 the 'patsubst' function. It has the same form '$(VAR:A=B)' described
4615 above, except that now A must contain a single '%' character. This case
4616 is equivalent to '$(patsubst A,B,$(VAR))'. *Note Functions for String
4617 Substitution and Analysis: Text Functions, for a description of the
4618 'patsubst' function.
4622 foo := a.o b.o l.a c.o
4623 bar := $(foo:%.o=%.c)
4625 sets 'bar' to 'a.c b.c l.a c.c'.
4628 File: make.info, Node: Computed Names, Prev: Substitution Refs, Up: Advanced
4630 6.3.2 Computed Variable Names
4631 -----------------------------
4633 Computed variable names are a complicated concept needed only for
4634 sophisticated makefile programming. For most purposes you need not
4635 consider them, except to know that making a variable with a dollar sign
4636 in its name might have strange results. However, if you are the type
4637 that wants to understand everything, or you are actually interested in
4638 what they do, read on.
4640 Variables may be referenced inside the name of a variable. This is
4641 called a "computed variable name" or a "nested variable reference". For
4648 defines 'a' as 'z': the '$(x)' inside '$($(x))' expands to 'y', so
4649 '$($(x))' expands to '$(y)' which in turn expands to 'z'. Here the name
4650 of the variable to reference is not stated explicitly; it is computed by
4651 expansion of '$(x)'. The reference '$(x)' here is nested within the
4652 outer variable reference.
4654 The previous example shows two levels of nesting, but any number of
4655 levels is possible. For example, here are three levels:
4662 Here the innermost '$(x)' expands to 'y', so '$($(x))' expands to '$(y)'
4663 which in turn expands to 'z'; now we have '$(z)', which becomes 'u'.
4665 References to recursively-expanded variables within a variable name
4666 are re-expanded in the usual fashion. For example:
4673 defines 'a' as 'Hello': '$($(x))' becomes '$($(y))' which becomes '$(z)'
4674 which becomes 'Hello'.
4676 Nested variable references can also contain modified references and
4677 function invocations (*note Functions for Transforming Text:
4678 Functions.), just like any other reference. For example, using the
4679 'subst' function (*note Functions for String Substitution and Analysis:
4684 y = $(subst 1,2,$(x))
4688 eventually defines 'a' as 'Hello'. It is doubtful that anyone would
4689 ever want to write a nested reference as convoluted as this one, but it
4690 works: '$($($(z)))' expands to '$($(y))' which becomes '$($(subst
4691 1,2,$(x)))'. This gets the value 'variable1' from 'x' and changes it by
4692 substitution to 'variable2', so that the entire string becomes
4693 '$(variable2)', a simple variable reference whose value is 'Hello'.
4695 A computed variable name need not consist entirely of a single
4696 variable reference. It can contain several variable references, as well
4697 as some invariant text. For example,
4702 a_files := filea fileb
4703 1_files := file1 file2
4705 ifeq "$(use_a)" "yes"
4711 ifeq "$(use_dirs)" "yes"
4717 dirs := $($(a1)_$(df))
4719 will give 'dirs' the same value as 'a_dirs', '1_dirs', 'a_files' or
4720 '1_files' depending on the settings of 'use_a' and 'use_dirs'.
4722 Computed variable names can also be used in substitution references:
4724 a_objects := a.o b.o c.o
4725 1_objects := 1.o 2.o 3.o
4727 sources := $($(a1)_objects:.o=.c)
4729 defines 'sources' as either 'a.c b.c c.c' or '1.c 2.c 3.c', depending on
4732 The only restriction on this sort of use of nested variable
4733 references is that they cannot specify part of the name of a function to
4734 be called. This is because the test for a recognized function name is
4735 done before the expansion of nested references. For example,
4745 foo := $($(func) $(bar))
4747 attempts to give 'foo' the value of the variable 'sort a d b g q c' or
4748 'strip a d b g q c', rather than giving 'a d b g q c' as the argument to
4749 either the 'sort' or the 'strip' function. This restriction could be
4750 removed in the future if that change is shown to be a good idea.
4752 You can also use computed variable names in the left-hand side of a
4753 variable assignment, or in a 'define' directive, as in:
4756 $(dir)_sources := $(wildcard $(dir)/*.c)
4757 define $(dir)_print =
4758 lpr $($(dir)_sources)
4761 This example defines the variables 'dir', 'foo_sources', and
4764 Note that "nested variable references" are quite different from
4765 "recursively expanded variables" (*note The Two Flavors of Variables:
4766 Flavors.), though both are used together in complex ways when doing
4767 makefile programming.
4770 File: make.info, Node: Values, Next: Setting, Prev: Advanced, Up: Using Variables
4772 6.4 How Variables Get Their Values
4773 ==================================
4775 Variables can get values in several different ways:
4777 * You can specify an overriding value when you run 'make'. *Note
4778 Overriding Variables: Overriding.
4780 * You can specify a value in the makefile, either with an assignment
4781 (*note Setting Variables: Setting.) or with a verbatim definition
4782 (*note Defining Multi-Line Variables: Multi-Line.).
4784 * Variables in the environment become 'make' variables. *Note
4785 Variables from the Environment: Environment.
4787 * Several "automatic" variables are given new values for each rule.
4788 Each of these has a single conventional use. *Note Automatic
4791 * Several variables have constant initial values. *Note Variables
4792 Used by Implicit Rules: Implicit Variables.
4795 File: make.info, Node: Setting, Next: Appending, Prev: Values, Up: Using Variables
4797 6.5 Setting Variables
4798 =====================
4800 To set a variable from the makefile, write a line starting with the
4801 variable name followed by '=', ':=', or '::='. Whatever follows the
4802 '=', ':=', or '::=' on the line becomes the value. For example,
4804 objects = main.o foo.o bar.o utils.o
4806 defines a variable named 'objects'. Whitespace around the variable name
4807 and immediately after the '=' is ignored.
4809 Variables defined with '=' are "recursively expanded" variables.
4810 Variables defined with ':=' or '::=' are "simply expanded" variables;
4811 these definitions can contain variable references which will be expanded
4812 before the definition is made. *Note The Two Flavors of Variables:
4815 The variable name may contain function and variable references, which
4816 are expanded when the line is read to find the actual variable name to
4819 There is no limit on the length of the value of a variable except the
4820 amount of memory on the computer. You can split the value of a variable
4821 into multiple physical lines for readability (*note Splitting Long
4822 Lines: Splitting Lines.).
4824 Most variable names are considered to have the empty string as a
4825 value if you have never set them. Several variables have built-in
4826 initial values that are not empty, but you can set them in the usual
4827 ways (*note Variables Used by Implicit Rules: Implicit Variables.).
4828 Several special variables are set automatically to a new value for each
4829 rule; these are called the "automatic" variables (*note Automatic
4832 If you'd like a variable to be set to a value only if it's not
4833 already set, then you can use the shorthand operator '?=' instead of
4834 '='. These two settings of the variable 'FOO' are identical (*note The
4835 'origin' Function: Origin Function.):
4841 ifeq ($(origin FOO), undefined)
4845 The shell assignment operator '!=' can be used to execute a shell
4846 script and set a variable to its output. This operator first evaluates
4847 the right-hand side, then passes that result to the shell for execution.
4848 If the result of the execution ends in a newline, that one newline is
4849 removed; all other newlines are replaced by spaces. The resulting
4850 string is then placed into the named recursively-expanded variable. For
4853 hash != printf '\043'
4854 file_list != find . -name '*.c'
4856 If the result of the execution could produce a '$', and you don't
4857 intend what follows that to be interpreted as a make variable or
4858 function reference, then you must replace every '$' with '$$' as part of
4859 the execution. Alternatively, you can set a simply expanded variable to
4860 the result of running a program using the 'shell' function call. *Note
4861 The 'shell' Function: Shell Function. For example:
4863 hash := $(shell printf '\043')
4864 var := $(shell find . -name "*.c")
4866 As with the 'shell' function, the exit status of the just-invoked
4867 shell script is stored in the '.SHELLSTATUS' variable.
4870 File: make.info, Node: Appending, Next: Override Directive, Prev: Setting, Up: Using Variables
4872 6.6 Appending More Text to Variables
4873 ====================================
4875 Often it is useful to add more text to the value of a variable already
4876 defined. You do this with a line containing '+=', like this:
4878 objects += another.o
4880 This takes the value of the variable 'objects', and adds the text
4881 'another.o' to it (preceded by a single space, if it has a value
4884 objects = main.o foo.o bar.o utils.o
4885 objects += another.o
4887 sets 'objects' to 'main.o foo.o bar.o utils.o another.o'.
4889 Using '+=' is similar to:
4891 objects = main.o foo.o bar.o utils.o
4892 objects := $(objects) another.o
4894 but differs in ways that become important when you use more complex
4897 When the variable in question has not been defined before, '+=' acts
4898 just like normal '=': it defines a recursively-expanded variable.
4899 However, when there _is_ a previous definition, exactly what '+=' does
4900 depends on what flavor of variable you defined originally. *Note The
4901 Two Flavors of Variables: Flavors, for an explanation of the two flavors
4904 When you add to a variable's value with '+=', 'make' acts essentially
4905 as if you had included the extra text in the initial definition of the
4906 variable. If you defined it first with ':=' or '::=', making it a
4907 simply-expanded variable, '+=' adds to that simply-expanded definition,
4908 and expands the new text before appending it to the old value just as
4909 ':=' does (see *note Setting Variables: Setting, for a full explanation
4910 of ':=' or '::='). In fact,
4915 is exactly equivalent to:
4918 variable := $(variable) more
4920 On the other hand, when you use '+=' with a variable that you defined
4921 first to be recursively-expanded using plain '=', 'make' does something
4922 a bit different. Recall that when you define a recursively-expanded
4923 variable, 'make' does not expand the value you set for variable and
4924 function references immediately. Instead it stores the text verbatim,
4925 and saves these variable and function references to be expanded later,
4926 when you refer to the new variable (*note The Two Flavors of Variables:
4927 Flavors.). When you use '+=' on a recursively-expanded variable, it is
4928 this unexpanded text to which 'make' appends the new text you specify.
4933 is roughly equivalent to:
4936 variable = $(temp) more
4938 except that of course it never defines a variable called 'temp'. The
4939 importance of this comes when the variable's old value contains variable
4940 references. Take this common example:
4942 CFLAGS = $(includes) -O
4944 CFLAGS += -pg # enable profiling
4946 The first line defines the 'CFLAGS' variable with a reference to another
4947 variable, 'includes'. ('CFLAGS' is used by the rules for C compilation;
4948 *note Catalogue of Built-In Rules: Catalogue of Rules.) Using '=' for
4949 the definition makes 'CFLAGS' a recursively-expanded variable, meaning
4950 '$(includes) -O' is _not_ expanded when 'make' processes the definition
4951 of 'CFLAGS'. Thus, 'includes' need not be defined yet for its value to
4952 take effect. It only has to be defined before any reference to
4953 'CFLAGS'. If we tried to append to the value of 'CFLAGS' without using
4954 '+=', we might do it like this:
4956 CFLAGS := $(CFLAGS) -pg # enable profiling
4958 This is pretty close, but not quite what we want. Using ':=' redefines
4959 'CFLAGS' as a simply-expanded variable; this means 'make' expands the
4960 text '$(CFLAGS) -pg' before setting the variable. If 'includes' is not
4961 yet defined, we get ' -O -pg', and a later definition of 'includes' will
4962 have no effect. Conversely, by using '+=' we set 'CFLAGS' to the
4963 _unexpanded_ value '$(includes) -O -pg'. Thus we preserve the reference
4964 to 'includes', so if that variable gets defined at any later point, a
4965 reference like '$(CFLAGS)' still uses its value.
4968 File: make.info, Node: Override Directive, Next: Multi-Line, Prev: Appending, Up: Using Variables
4970 6.7 The 'override' Directive
4971 ============================
4973 If a variable has been set with a command argument (*note Overriding
4974 Variables: Overriding.), then ordinary assignments in the makefile are
4975 ignored. If you want to set the variable in the makefile even though it
4976 was set with a command argument, you can use an 'override' directive,
4977 which is a line that looks like this:
4979 override VARIABLE = VALUE
4983 override VARIABLE := VALUE
4985 To append more text to a variable defined on the command line, use:
4987 override VARIABLE += MORE TEXT
4989 *Note Appending More Text to Variables: Appending.
4991 Variable assignments marked with the 'override' flag have a higher
4992 priority than all other assignments, except another 'override'.
4993 Subsequent assignments or appends to this variable which are not marked
4994 'override' will be ignored.
4996 The 'override' directive was not invented for escalation in the war
4997 between makefiles and command arguments. It was invented so you can
4998 alter and add to values that the user specifies with command arguments.
5000 For example, suppose you always want the '-g' switch when you run the
5001 C compiler, but you would like to allow the user to specify the other
5002 switches with a command argument just as usual. You could use this
5003 'override' directive:
5005 override CFLAGS += -g
5007 You can also use 'override' directives with 'define' directives.
5008 This is done as you might expect:
5010 override define foo =
5014 *Note Defining Multi-Line Variables: Multi-Line.
5017 File: make.info, Node: Multi-Line, Next: Undefine Directive, Prev: Override Directive, Up: Using Variables
5019 6.8 Defining Multi-Line Variables
5020 =================================
5022 Another way to set the value of a variable is to use the 'define'
5023 directive. This directive has an unusual syntax which allows newline
5024 characters to be included in the value, which is convenient for defining
5025 both canned sequences of commands (*note Defining Canned Recipes: Canned
5026 Recipes.), and also sections of makefile syntax to use with 'eval'
5027 (*note Eval Function::).
5029 The 'define' directive is followed on the same line by the name of
5030 the variable being defined and an (optional) assignment operator, and
5031 nothing more. The value to give the variable appears on the following
5032 lines. The end of the value is marked by a line containing just the
5035 Aside from this difference in syntax, 'define' works just like any
5036 other variable definition. The variable name may contain function and
5037 variable references, which are expanded when the directive is read to
5038 find the actual variable name to use.
5040 The final newline before the 'endef' is not included in the value; if
5041 you want your value to contain a trailing newline you must include a
5042 blank line. For example in order to define a variable that contains a
5043 newline character you must use _two_ empty lines, not one:
5050 You may omit the variable assignment operator if you prefer. If
5051 omitted, 'make' assumes it to be '=' and creates a recursively-expanded
5052 variable (*note The Two Flavors of Variables: Flavors.). When using a
5053 '+=' operator, the value is appended to the previous value as with any
5054 other append operation: with a single space separating the old and new
5057 You may nest 'define' directives: 'make' will keep track of nested
5058 directives and report an error if they are not all properly closed with
5059 'endef'. Note that lines beginning with the recipe prefix character are
5060 considered part of a recipe, so any 'define' or 'endef' strings
5061 appearing on such a line will not be considered 'make' directives.
5068 When used in a recipe, the previous example is functionally
5071 two-lines = echo foo; echo $(bar)
5073 since two commands separated by semicolon behave much like two separate
5074 shell commands. However, note that using two separate lines means
5075 'make' will invoke the shell twice, running an independent sub-shell for
5076 each line. *Note Recipe Execution: Execution.
5078 If you want variable definitions made with 'define' to take
5079 precedence over command-line variable definitions, you can use the
5080 'override' directive together with 'define':
5082 override define two-lines =
5087 *Note The 'override' Directive: Override Directive.
5090 File: make.info, Node: Undefine Directive, Next: Environment, Prev: Multi-Line, Up: Using Variables
5092 6.9 Undefining Variables
5093 ========================
5095 If you want to clear a variable, setting its value to empty is usually
5096 sufficient. Expanding such a variable will yield the same result (empty
5097 string) regardless of whether it was set or not. However, if you are
5098 using the 'flavor' (*note Flavor Function::) and 'origin' (*note Origin
5099 Function::) functions, there is a difference between a variable that was
5100 never set and a variable with an empty value. In such situations you
5101 may want to use the 'undefine' directive to make a variable appear as if
5102 it was never set. For example:
5110 $(info $(origin foo))
5111 $(info $(flavor bar))
5113 This example will print "undefined" for both variables.
5115 If you want to undefine a command-line variable definition, you can
5116 use the 'override' directive together with 'undefine', similar to how
5117 this is done for variable definitions:
5119 override undefine CFLAGS
5122 File: make.info, Node: Environment, Next: Target-specific, Prev: Undefine Directive, Up: Using Variables
5124 6.10 Variables from the Environment
5125 ===================================
5127 Variables in 'make' can come from the environment in which 'make' is
5128 run. Every environment variable that 'make' sees when it starts up is
5129 transformed into a 'make' variable with the same name and value.
5130 However, an explicit assignment in the makefile, or with a command
5131 argument, overrides the environment. (If the '-e' flag is specified,
5132 then values from the environment override assignments in the makefile.
5133 *Note Summary of Options: Options Summary. But this is not recommended
5136 Thus, by setting the variable 'CFLAGS' in your environment, you can
5137 cause all C compilations in most makefiles to use the compiler switches
5138 you prefer. This is safe for variables with standard or conventional
5139 meanings because you know that no makefile will use them for other
5140 things. (Note this is not totally reliable; some makefiles set 'CFLAGS'
5141 explicitly and therefore are not affected by the value in the
5144 When 'make' runs a recipe, variables defined in the makefile are
5145 placed into the environment of each shell. This allows you to pass
5146 values to sub-'make' invocations (*note Recursive Use of 'make':
5147 Recursion.). By default, only variables that came from the environment
5148 or the command line are passed to recursive invocations. You can use
5149 the 'export' directive to pass other variables. *Note Communicating
5150 Variables to a Sub-'make': Variables/Recursion, for full details.
5152 Other use of variables from the environment is not recommended. It
5153 is not wise for makefiles to depend for their functioning on environment
5154 variables set up outside their control, since this would cause different
5155 users to get different results from the same makefile. This is against
5156 the whole purpose of most makefiles.
5158 Such problems would be especially likely with the variable 'SHELL',
5159 which is normally present in the environment to specify the user's
5160 choice of interactive shell. It would be very undesirable for this
5161 choice to affect 'make'; so, 'make' handles the 'SHELL' environment
5162 variable in a special way; see *note Choosing the Shell::.
5165 File: make.info, Node: Target-specific, Next: Pattern-specific, Prev: Environment, Up: Using Variables
5167 6.11 Target-specific Variable Values
5168 ====================================
5170 Variable values in 'make' are usually global; that is, they are the same
5171 regardless of where they are evaluated (unless they're reset, of
5172 course). One exception to that is automatic variables (*note Automatic
5175 The other exception is "target-specific variable values". This
5176 feature allows you to define different values for the same variable,
5177 based on the target that 'make' is currently building. As with
5178 automatic variables, these values are only available within the context
5179 of a target's recipe (and in other target-specific assignments).
5181 Set a target-specific variable value like this:
5183 TARGET ... : VARIABLE-ASSIGNMENT
5185 Target-specific variable assignments can be prefixed with any or all
5186 of the special keywords 'export', 'override', or 'private'; these apply
5187 their normal behavior to this instance of the variable only.
5189 Multiple TARGET values create a target-specific variable value for
5190 each member of the target list individually.
5192 The VARIABLE-ASSIGNMENT can be any valid form of assignment;
5193 recursive ('='), simple (':=' or '::='), appending ('+='), or
5194 conditional ('?='). All variables that appear within the
5195 VARIABLE-ASSIGNMENT are evaluated within the context of the target:
5196 thus, any previously-defined target-specific variable values will be in
5197 effect. Note that this variable is actually distinct from any "global"
5198 value: the two variables do not have to have the same flavor (recursive
5201 Target-specific variables have the same priority as any other
5202 makefile variable. Variables provided on the command line (and in the
5203 environment if the '-e' option is in force) will take precedence.
5204 Specifying the 'override' directive will allow the target-specific
5205 variable value to be preferred.
5207 There is one more special feature of target-specific variables: when
5208 you define a target-specific variable that variable value is also in
5209 effect for all prerequisites of this target, and all their
5210 prerequisites, etc. (unless those prerequisites override that variable
5211 with their own target-specific variable value). So, for example, a
5212 statement like this:
5215 prog : prog.o foo.o bar.o
5217 will set 'CFLAGS' to '-g' in the recipe for 'prog', but it will also set
5218 'CFLAGS' to '-g' in the recipes that create 'prog.o', 'foo.o', and
5219 'bar.o', and any recipes which create their prerequisites.
5221 Be aware that a given prerequisite will only be built once per
5222 invocation of make, at most. If the same file is a prerequisite of
5223 multiple targets, and each of those targets has a different value for
5224 the same target-specific variable, then the first target to be built
5225 will cause that prerequisite to be built and the prerequisite will
5226 inherit the target-specific value from the first target. It will ignore
5227 the target-specific values from any other targets.
5230 File: make.info, Node: Pattern-specific, Next: Suppressing Inheritance, Prev: Target-specific, Up: Using Variables
5232 6.12 Pattern-specific Variable Values
5233 =====================================
5235 In addition to target-specific variable values (*note Target-specific
5236 Variable Values: Target-specific.), GNU 'make' supports pattern-specific
5237 variable values. In this form, the variable is defined for any target
5238 that matches the pattern specified.
5240 Set a pattern-specific variable value like this:
5242 PATTERN ... : VARIABLE-ASSIGNMENT
5243 where PATTERN is a %-pattern. As with target-specific variable
5244 values, multiple PATTERN values create a pattern-specific variable value
5245 for each pattern individually. The VARIABLE-ASSIGNMENT can be any valid
5246 form of assignment. Any command line variable setting will take
5247 precedence, unless 'override' is specified.
5253 will assign 'CFLAGS' the value of '-O' for all targets matching the
5256 If a target matches more than one pattern, the matching
5257 pattern-specific variables with longer stems are interpreted first.
5258 This results in more specific variables taking precedence over the more
5259 generic ones, for example:
5262 $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
5264 lib/%.o: CFLAGS := -fPIC -g
5267 all: foo.o lib/bar.o
5269 In this example the first definition of the 'CFLAGS' variable will be
5270 used to update 'lib/bar.o' even though the second one also applies to
5271 this target. Pattern-specific variables which result in the same stem
5272 length are considered in the order in which they were defined in the
5275 Pattern-specific variables are searched after any target-specific
5276 variables defined explicitly for that target, and before target-specific
5277 variables defined for the parent target.
5280 File: make.info, Node: Suppressing Inheritance, Next: Special Variables, Prev: Pattern-specific, Up: Using Variables
5282 6.13 Suppressing Inheritance
5283 ============================
5285 As described in previous sections, 'make' variables are inherited by
5286 prerequisites. This capability allows you to modify the behavior of a
5287 prerequisite based on which targets caused it to be rebuilt. For
5288 example, you might set a target-specific variable on a 'debug' target,
5289 then running 'make debug' will cause that variable to be inherited by
5290 all prerequisites of 'debug', while just running 'make all' (for
5291 example) would not have that assignment.
5293 Sometimes, however, you may not want a variable to be inherited. For
5294 these situations, 'make' provides the 'private' modifier. Although this
5295 modifier can be used with any variable assignment, it makes the most
5296 sense with target- and pattern-specific variables. Any variable marked
5297 'private' will be visible to its local target but will not be inherited
5298 by prerequisites of that target. A global variable marked 'private'
5299 will be visible in the global scope but will not be inherited by any
5300 target, and hence will not be visible in any recipe.
5302 As an example, consider this makefile:
5305 prog: private EXTRA_CFLAGS = -L/usr/local/lib
5308 Due to the 'private' modifier, 'a.o' and 'b.o' will not inherit the
5309 'EXTRA_CFLAGS' variable assignment from the 'prog' target.
5312 File: make.info, Node: Special Variables, Prev: Suppressing Inheritance, Up: Using Variables
5314 6.14 Other Special Variables
5315 ============================
5317 GNU 'make' supports some variables that have special properties.
5320 Contains the name of each makefile that is parsed by 'make', in the
5321 order in which it was parsed. The name is appended just before
5322 'make' begins to parse the makefile. Thus, if the first thing a
5323 makefile does is examine the last word in this variable, it will be
5324 the name of the current makefile. Once the current makefile has
5325 used 'include', however, the last word will be the just-included
5328 If a makefile named 'Makefile' has this content:
5330 name1 := $(lastword $(MAKEFILE_LIST))
5334 name2 := $(lastword $(MAKEFILE_LIST))
5337 @echo name1 = $(name1)
5338 @echo name2 = $(name2)
5340 then you would expect to see this output:
5346 Sets the default goal to be used if no targets were specified on
5347 the command line (*note Arguments to Specify the Goals: Goals.).
5348 The '.DEFAULT_GOAL' variable allows you to discover the current
5349 default goal, restart the default goal selection algorithm by
5350 clearing its value, or to explicitly set the default goal. The
5351 following example illustrates these cases:
5353 # Query the default goal.
5354 ifeq ($(.DEFAULT_GOAL),)
5355 $(warning no default goal is set)
5361 $(warning default goal is $(.DEFAULT_GOAL))
5363 # Reset the default goal.
5369 $(warning default goal is $(.DEFAULT_GOAL))
5372 .DEFAULT_GOAL := foo
5374 This makefile prints:
5376 no default goal is set
5381 Note that assigning more than one target name to '.DEFAULT_GOAL' is
5382 invalid and will result in an error.
5385 This variable is set only if this instance of 'make' has restarted
5386 (*note How Makefiles Are Remade: Remaking Makefiles.): it will
5387 contain the number of times this instance has restarted. Note this
5388 is not the same as recursion (counted by the 'MAKELEVEL' variable).
5389 You should not set, modify, or export this variable.
5393 When 'make' starts it will check whether stdout and stderr will
5394 show their output on a terminal. If so, it will set 'MAKE_TERMOUT'
5395 and 'MAKE_TERMERR', respectively, to the name of the terminal
5396 device (or 'true' if this cannot be determined). If set these
5397 variables will be marked for export. These variables will not be
5398 changed by 'make' and they will not be modified if already set.
5400 These values can be used (particularly in combination with output
5401 synchronization (*note Output During Parallel Execution: Parallel
5402 Output.) to determine whether 'make' itself is writing to a
5403 terminal; they can be tested to decide whether to force recipe
5404 commands to generate colorized output for example.
5406 If you invoke a sub-'make' and redirect its stdout or stderr it is
5407 your responsibility to reset or unexport these variables as well,
5408 if your makefiles rely on them.
5411 The first character of the value of this variable is used as the
5412 character make assumes is introducing a recipe line. If the
5413 variable is empty (as it is by default) that character is the
5414 standard tab character. For example, this is a valid makefile:
5418 > @echo Hello, world
5420 The value of '.RECIPEPREFIX' can be changed multiple times; once
5421 set it stays in effect for all rules parsed until it is modified.
5424 Expands to a list of the _names_ of all global variables defined so
5425 far. This includes variables which have empty values, as well as
5426 built-in variables (*note Variables Used by Implicit Rules:
5427 Implicit Variables.), but does not include any variables which are
5428 only defined in a target-specific context. Note that any value you
5429 assign to this variable will be ignored; it will always return its
5433 Expands to a list of special features supported by this version of
5434 'make'. Possible values include, but are not limited to:
5437 Supports 'ar' (archive) files using special file name syntax.
5438 *Note Using 'make' to Update Archive Files: Archives.
5441 Supports the '-L' ('--check-symlink-times') flag. *Note
5442 Summary of Options: Options Summary.
5445 Supports "else if" non-nested conditionals. *Note Syntax of
5446 Conditionals: Conditional Syntax.
5449 Supports "job server" enhanced parallel builds. *Note
5450 Parallel Execution: Parallel.
5453 Supports the '.ONESHELL' special target. *Note Using One
5457 Supports order-only prerequisites. *Note Types of
5458 Prerequisites: Prerequisite Types.
5461 Supports secondary expansion of prerequisite lists.
5464 Uses the "shortest stem" method of choosing which pattern, of
5465 multiple applicable options, will be used. *Note How Patterns
5466 Match: Pattern Match.
5469 Supports target-specific and pattern-specific variable
5470 assignments. *Note Target-specific Variable Values:
5474 Supports the 'undefine' directive. *Note Undefine
5478 Has GNU Guile available as an embedded extension language.
5479 *Note GNU Guile Integration: Guile Integration.
5482 Supports dynamically loadable objects for creating custom
5483 extensions. *Note Loading Dynamic Objects: Loading Objects.
5486 Expands to a list of directories that 'make' searches for included
5487 makefiles (*note Including Other Makefiles: Include.).
5490 Each word in this variable is a new prerequisite which is added to
5491 targets for which it is set. These prerequisites differ from
5492 normal prerequisites in that they do not appear in any of the
5493 automatic variables (*note Automatic Variables::). This allows
5494 prerequisites to be defined which do not impact the recipe.
5496 Consider a rule to link a program:
5498 myprog: myprog.o file1.o file2.o
5499 $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
5501 Now suppose you want to enhance this makefile to ensure that
5502 updates to the compiler cause the program to be re-linked. You can
5503 add the compiler as a prerequisite, but you must ensure that it's
5504 not passed as an argument to link command. You'll need something
5507 myprog: myprog.o file1.o file2.o $(CC)
5508 $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(filter-out $(CC),$^) $(LDLIBS)
5510 Then consider having multiple extra prerequisites: they would all
5511 have to be filtered out. Using '.EXTRA_PREREQS' and
5512 target-specific variables provides a simpler solution:
5514 myprog: myprog.o file1.o file2.o
5515 $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
5516 myprog: .EXTRA_PREREQS = $(CC)
5518 This feature can also be useful if you want to add prerequisites to
5519 a makefile you cannot easily modify: you can create a new file such
5522 myprog: .EXTRA_PREREQS = $(CC)
5524 then invoke 'make -f extra.mk -f Makefile'.
5526 Setting '.EXTRA_PREREQS' globally will cause those prerequisites to
5527 be added to all targets (which did not themselves override it with
5528 a target-specific value). Note 'make' is smart enough not to add a
5529 prerequisite listed in '.EXTRA_PREREQS' as a prerequisite to
5533 File: make.info, Node: Conditionals, Next: Functions, Prev: Using Variables, Up: Top
5535 7 Conditional Parts of Makefiles
5536 ********************************
5538 A "conditional" directive causes part of a makefile to be obeyed or
5539 ignored depending on the values of variables. Conditionals can compare
5540 the value of one variable to another, or the value of a variable to a
5541 constant string. Conditionals control what 'make' actually "sees" in
5542 the makefile, so they _cannot_ be used to control recipes at the time of
5547 * Conditional Example:: Example of a conditional
5548 * Conditional Syntax:: The syntax of conditionals.
5549 * Testing Flags:: Conditionals that test flags.
5552 File: make.info, Node: Conditional Example, Next: Conditional Syntax, Prev: Conditionals, Up: Conditionals
5554 7.1 Example of a Conditional
5555 ============================
5557 The following example of a conditional tells 'make' to use one set of
5558 libraries if the 'CC' variable is 'gcc', and a different set of
5559 libraries otherwise. It works by controlling which of two recipe lines
5560 will be used for the rule. The result is that 'CC=gcc' as an argument
5561 to 'make' changes not only which compiler is used but also which
5562 libraries are linked.
5564 libs_for_gcc = -lgnu
5569 $(CC) -o foo $(objects) $(libs_for_gcc)
5571 $(CC) -o foo $(objects) $(normal_libs)
5574 This conditional uses three directives: one 'ifeq', one 'else' and
5577 The 'ifeq' directive begins the conditional, and specifies the
5578 condition. It contains two arguments, separated by a comma and
5579 surrounded by parentheses. Variable substitution is performed on both
5580 arguments and then they are compared. The lines of the makefile
5581 following the 'ifeq' are obeyed if the two arguments match; otherwise
5584 The 'else' directive causes the following lines to be obeyed if the
5585 previous conditional failed. In the example above, this means that the
5586 second alternative linking command is used whenever the first
5587 alternative is not used. It is optional to have an 'else' in a
5590 The 'endif' directive ends the conditional. Every conditional must
5591 end with an 'endif'. Unconditional makefile text follows.
5593 As this example illustrates, conditionals work at the textual level:
5594 the lines of the conditional are treated as part of the makefile, or
5595 ignored, according to the condition. This is why the larger syntactic
5596 units of the makefile, such as rules, may cross the beginning or the end
5599 When the variable 'CC' has the value 'gcc', the above example has
5603 $(CC) -o foo $(objects) $(libs_for_gcc)
5605 When the variable 'CC' has any other value, the effect is this:
5608 $(CC) -o foo $(objects) $(normal_libs)
5610 Equivalent results can be obtained in another way by conditionalizing
5611 a variable assignment and then using the variable unconditionally:
5613 libs_for_gcc = -lgnu
5617 libs=$(libs_for_gcc)
5623 $(CC) -o foo $(objects) $(libs)
5626 File: make.info, Node: Conditional Syntax, Next: Testing Flags, Prev: Conditional Example, Up: Conditionals
5628 7.2 Syntax of Conditionals
5629 ==========================
5631 The syntax of a simple conditional with no 'else' is as follows:
5633 CONDITIONAL-DIRECTIVE
5637 The TEXT-IF-TRUE may be any lines of text, to be considered as part of
5638 the makefile if the condition is true. If the condition is false, no
5639 text is used instead.
5641 The syntax of a complex conditional is as follows:
5643 CONDITIONAL-DIRECTIVE
5651 CONDITIONAL-DIRECTIVE-ONE
5653 else CONDITIONAL-DIRECTIVE-TWO
5656 TEXT-IF-ONE-AND-TWO-ARE-FALSE
5659 There can be as many "'else' CONDITIONAL-DIRECTIVE" clauses as
5660 necessary. Once a given condition is true, TEXT-IF-TRUE is used and no
5661 other clause is used; if no condition is true then TEXT-IF-FALSE is
5662 used. The TEXT-IF-TRUE and TEXT-IF-FALSE can be any number of lines of
5665 The syntax of the CONDITIONAL-DIRECTIVE is the same whether the
5666 conditional is simple or complex; after an 'else' or not. There are
5667 four different directives that test different conditions. Here is a
5671 'ifeq 'ARG1' 'ARG2''
5672 'ifeq "ARG1" "ARG2"'
5673 'ifeq "ARG1" 'ARG2''
5674 'ifeq 'ARG1' "ARG2"'
5675 Expand all variable references in ARG1 and ARG2 and compare them.
5676 If they are identical, the TEXT-IF-TRUE is effective; otherwise,
5677 the TEXT-IF-FALSE, if any, is effective.
5679 Often you want to test if a variable has a non-empty value. When
5680 the value results from complex expansions of variables and
5681 functions, expansions you would consider empty may actually contain
5682 whitespace characters and thus are not seen as empty. However, you
5683 can use the 'strip' function (*note Text Functions::) to avoid
5684 interpreting whitespace as a non-empty value. For example:
5686 ifeq ($(strip $(foo)),)
5690 will evaluate TEXT-IF-EMPTY even if the expansion of '$(foo)'
5691 contains whitespace characters.
5693 'ifneq (ARG1, ARG2)'
5694 'ifneq 'ARG1' 'ARG2''
5695 'ifneq "ARG1" "ARG2"'
5696 'ifneq "ARG1" 'ARG2''
5697 'ifneq 'ARG1' "ARG2"'
5698 Expand all variable references in ARG1 and ARG2 and compare them.
5699 If they are different, the TEXT-IF-TRUE is effective; otherwise,
5700 the TEXT-IF-FALSE, if any, is effective.
5702 'ifdef VARIABLE-NAME'
5703 The 'ifdef' form takes the _name_ of a variable as its argument,
5704 not a reference to a variable. If the value of that variable has a
5705 non-empty value, the TEXT-IF-TRUE is effective; otherwise, the
5706 TEXT-IF-FALSE, if any, is effective. Variables that have never
5707 been defined have an empty value. The text VARIABLE-NAME is
5708 expanded, so it could be a variable or function that expands to the
5709 name of a variable. For example:
5717 The variable reference '$(foo)' is expanded, yielding 'bar', which
5718 is considered to be the name of a variable. The variable 'bar' is
5719 not expanded, but its value is examined to determine if it is
5722 Note that 'ifdef' only tests whether a variable has a value. It
5723 does not expand the variable to see if that value is nonempty.
5724 Consequently, tests using 'ifdef' return true for all definitions
5725 except those like 'foo ='. To test for an empty value, use
5726 'ifeq ($(foo),)'. For example,
5736 sets 'frobozz' to 'yes', while:
5745 sets 'frobozz' to 'no'.
5747 'ifndef VARIABLE-NAME'
5748 If the variable VARIABLE-NAME has an empty value, the TEXT-IF-TRUE
5749 is effective; otherwise, the TEXT-IF-FALSE, if any, is effective.
5750 The rules for expansion and testing of VARIABLE-NAME are identical
5751 to the 'ifdef' directive.
5753 Extra spaces are allowed and ignored at the beginning of the
5754 conditional directive line, but a tab is not allowed. (If the line
5755 begins with a tab, it will be considered part of a recipe for a rule.)
5756 Aside from this, extra spaces or tabs may be inserted with no effect
5757 anywhere except within the directive name or within an argument. A
5758 comment starting with '#' may appear at the end of the line.
5760 The other two directives that play a part in a conditional are 'else'
5761 and 'endif'. Each of these directives is written as one word, with no
5762 arguments. Extra spaces are allowed and ignored at the beginning of the
5763 line, and spaces or tabs at the end. A comment starting with '#' may
5764 appear at the end of the line.
5766 Conditionals affect which lines of the makefile 'make' uses. If the
5767 condition is true, 'make' reads the lines of the TEXT-IF-TRUE as part of
5768 the makefile; if the condition is false, 'make' ignores those lines
5769 completely. It follows that syntactic units of the makefile, such as
5770 rules, may safely be split across the beginning or the end of the
5773 'make' evaluates conditionals when it reads a makefile.
5774 Consequently, you cannot use automatic variables in the tests of
5775 conditionals because they are not defined until recipes are run (*note
5776 Automatic Variables::).
5778 To prevent intolerable confusion, it is not permitted to start a
5779 conditional in one makefile and end it in another. However, you may
5780 write an 'include' directive within a conditional, provided you do not
5781 attempt to terminate the conditional inside the included file.
5784 File: make.info, Node: Testing Flags, Prev: Conditional Syntax, Up: Conditionals
5786 7.3 Conditionals that Test Flags
5787 ================================
5789 You can write a conditional that tests 'make' command flags such as '-t'
5790 by using the variable 'MAKEFLAGS' together with the 'findstring'
5791 function (*note Functions for String Substitution and Analysis: Text
5792 Functions.). This is useful when 'touch' is not enough to make a file
5795 The 'findstring' function determines whether one string appears as a
5796 substring of another. If you want to test for the '-t' flag, use 't' as
5797 the first string and the value of 'MAKEFLAGS' as the other.
5799 For example, here is how to arrange to use 'ranlib -t' to finish
5800 marking an archive file up to date:
5803 ifneq (,$(findstring t,$(MAKEFLAGS)))
5805 +ranlib -t archive.a
5810 The '+' prefix marks those recipe lines as "recursive" so that they will
5811 be executed despite use of the '-t' flag. *Note Recursive Use of
5815 File: make.info, Node: Functions, Next: Running, Prev: Conditionals, Up: Top
5817 8 Functions for Transforming Text
5818 *********************************
5820 "Functions" allow you to do text processing in the makefile to compute
5821 the files to operate on or the commands to use in recipes. You use a
5822 function in a "function call", where you give the name of the function
5823 and some text (the "arguments") for the function to operate on. The
5824 result of the function's processing is substituted into the makefile at
5825 the point of the call, just as a variable might be substituted.
5829 * Syntax of Functions:: How to write a function call.
5830 * Text Functions:: General-purpose text manipulation functions.
5831 * File Name Functions:: Functions for manipulating file names.
5832 * Conditional Functions:: Functions that implement conditions.
5833 * Foreach Function:: Repeat some text with controlled variation.
5834 * File Function:: Write text to a file.
5835 * Call Function:: Expand a user-defined function.
5836 * Value Function:: Return the un-expanded value of a variable.
5837 * Eval Function:: Evaluate the arguments as makefile syntax.
5838 * Origin Function:: Find where a variable got its value.
5839 * Flavor Function:: Find out the flavor of a variable.
5840 * Make Control Functions:: Functions that control how make runs.
5841 * Shell Function:: Substitute the output of a shell command.
5842 * Guile Function:: Use GNU Guile embedded scripting language.
5845 File: make.info, Node: Syntax of Functions, Next: Text Functions, Prev: Functions, Up: Functions
5847 8.1 Function Call Syntax
5848 ========================
5850 A function call resembles a variable reference. It can appear anywhere
5851 a variable reference can appear, and it is expanded using the same rules
5852 as variable references. A function call looks like this:
5854 $(FUNCTION ARGUMENTS)
5858 ${FUNCTION ARGUMENTS}
5860 Here FUNCTION is a function name; one of a short list of names that
5861 are part of 'make'. You can also essentially create your own functions
5862 by using the 'call' built-in function.
5864 The ARGUMENTS are the arguments of the function. They are separated
5865 from the function name by one or more spaces or tabs, and if there is
5866 more than one argument, then they are separated by commas. Such
5867 whitespace and commas are not part of an argument's value. The
5868 delimiters which you use to surround the function call, whether
5869 parentheses or braces, can appear in an argument only in matching pairs;
5870 the other kind of delimiters may appear singly. If the arguments
5871 themselves contain other function calls or variable references, it is
5872 wisest to use the same kind of delimiters for all the references; write
5873 '$(subst a,b,$(x))', not '$(subst a,b,${x})'. This is because it is
5874 clearer, and because only one type of delimiter is matched to find the
5875 end of the reference.
5877 The text written for each argument is processed by substitution of
5878 variables and function calls to produce the argument value, which is the
5879 text on which the function acts. The substitution is done in the order
5880 in which the arguments appear.
5882 Commas and unmatched parentheses or braces cannot appear in the text
5883 of an argument as written; leading spaces cannot appear in the text of
5884 the first argument as written. These characters can be put into the
5885 argument value by variable substitution. First define variables 'comma'
5886 and 'space' whose values are isolated comma and space characters, then
5887 substitute these variables where such characters are wanted, like this:
5891 space:= $(empty) $(empty)
5893 bar:= $(subst $(space),$(comma),$(foo))
5894 # bar is now 'a,b,c'.
5896 Here the 'subst' function replaces each space with a comma, through the
5897 value of 'foo', and substitutes the result.
5900 File: make.info, Node: Text Functions, Next: File Name Functions, Prev: Syntax of Functions, Up: Functions
5902 8.2 Functions for String Substitution and Analysis
5903 ==================================================
5905 Here are some functions that operate on strings:
5907 '$(subst FROM,TO,TEXT)'
5908 Performs a textual replacement on the text TEXT: each occurrence of
5909 FROM is replaced by TO. The result is substituted for the function
5912 $(subst ee,EE,feet on the street)
5914 produces the value 'fEEt on the strEEt'.
5916 '$(patsubst PATTERN,REPLACEMENT,TEXT)'
5917 Finds whitespace-separated words in TEXT that match PATTERN and
5918 replaces them with REPLACEMENT. Here PATTERN may contain a '%'
5919 which acts as a wildcard, matching any number of any characters
5920 within a word. If REPLACEMENT also contains a '%', the '%' is
5921 replaced by the text that matched the '%' in PATTERN. Only the
5922 first '%' in the PATTERN and REPLACEMENT is treated this way; any
5923 subsequent '%' is unchanged.
5925 '%' characters in 'patsubst' function invocations can be quoted
5926 with preceding backslashes ('\'). Backslashes that would otherwise
5927 quote '%' characters can be quoted with more backslashes.
5928 Backslashes that quote '%' characters or other backslashes are
5929 removed from the pattern before it is compared file names or has a
5930 stem substituted into it. Backslashes that are not in danger of
5931 quoting '%' characters go unmolested. For example, the pattern
5932 'the\%weird\\%pattern\\' has 'the%weird\' preceding the operative
5933 '%' character, and 'pattern\\' following it. The final two
5934 backslashes are left alone because they cannot affect any '%'
5937 Whitespace between words is folded into single space characters;
5938 leading and trailing whitespace is discarded.
5942 $(patsubst %.c,%.o,x.c.c bar.c)
5944 produces the value 'x.c.o bar.o'.
5946 Substitution references (*note Substitution References:
5947 Substitution Refs.) are a simpler way to get the effect of the
5948 'patsubst' function:
5950 $(VAR:PATTERN=REPLACEMENT)
5954 $(patsubst PATTERN,REPLACEMENT,$(VAR))
5956 The second shorthand simplifies one of the most common uses of
5957 'patsubst': replacing the suffix at the end of file names.
5959 $(VAR:SUFFIX=REPLACEMENT)
5963 $(patsubst %SUFFIX,%REPLACEMENT,$(VAR))
5965 For example, you might have a list of object files:
5967 objects = foo.o bar.o baz.o
5969 To get the list of corresponding source files, you could simply
5974 instead of using the general form:
5976 $(patsubst %.o,%.c,$(objects))
5979 Removes leading and trailing whitespace from STRING and replaces
5980 each internal sequence of one or more whitespace characters with a
5981 single space. Thus, '$(strip a b c )' results in 'a b c'.
5983 The function 'strip' can be very useful when used in conjunction
5984 with conditionals. When comparing something with the empty string
5985 '' using 'ifeq' or 'ifneq', you usually want a string of just
5986 whitespace to match the empty string (*note Conditionals::).
5988 Thus, the following may fail to have the desired results:
5991 ifneq "$(needs_made)" ""
5994 all:;@echo 'Nothing to make!'
5997 Replacing the variable reference '$(needs_made)' with the function
5998 call '$(strip $(needs_made))' in the 'ifneq' directive would make
6001 '$(findstring FIND,IN)'
6002 Searches IN for an occurrence of FIND. If it occurs, the value is
6003 FIND; otherwise, the value is empty. You can use this function in
6004 a conditional to test for the presence of a specific substring in a
6005 given string. Thus, the two examples,
6007 $(findstring a,a b c)
6010 produce the values 'a' and '' (the empty string), respectively.
6011 *Note Testing Flags::, for a practical application of 'findstring'.
6013 '$(filter PATTERN...,TEXT)'
6014 Returns all whitespace-separated words in TEXT that _do_ match any
6015 of the PATTERN words, removing any words that _do not_ match. The
6016 patterns are written using '%', just like the patterns used in the
6017 'patsubst' function above.
6019 The 'filter' function can be used to separate out different types
6020 of strings (such as file names) in a variable. For example:
6022 sources := foo.c bar.c baz.s ugh.h
6024 cc $(filter %.c %.s,$(sources)) -o foo
6026 says that 'foo' depends of 'foo.c', 'bar.c', 'baz.s' and 'ugh.h'
6027 but only 'foo.c', 'bar.c' and 'baz.s' should be specified in the
6028 command to the compiler.
6030 '$(filter-out PATTERN...,TEXT)'
6031 Returns all whitespace-separated words in TEXT that _do not_ match
6032 any of the PATTERN words, removing the words that _do_ match one or
6033 more. This is the exact opposite of the 'filter' function.
6037 objects=main1.o foo.o main2.o bar.o
6038 mains=main1.o main2.o
6040 the following generates a list which contains all the object files
6043 $(filter-out $(mains),$(objects))
6046 Sorts the words of LIST in lexical order, removing duplicate words.
6047 The output is a list of words separated by single spaces. Thus,
6049 $(sort foo bar lose)
6051 returns the value 'bar foo lose'.
6053 Incidentally, since 'sort' removes duplicate words, you can use it
6054 for this purpose even if you don't care about the sort order.
6057 Returns the Nth word of TEXT. The legitimate values of N start
6058 from 1. If N is bigger than the number of words in TEXT, the value
6059 is empty. For example,
6061 $(word 2, foo bar baz)
6065 '$(wordlist S,E,TEXT)'
6066 Returns the list of words in TEXT starting with word S and ending
6067 with word E (inclusive). The legitimate values of S start from 1;
6068 E may start from 0. If S is bigger than the number of words in
6069 TEXT, the value is empty. If E is bigger than the number of words
6070 in TEXT, words up to the end of TEXT are returned. If S is greater
6071 than E, nothing is returned. For example,
6073 $(wordlist 2, 3, foo bar baz)
6078 Returns the number of words in TEXT. Thus, the last word of TEXT
6079 is '$(word $(words TEXT),TEXT)'.
6081 '$(firstword NAMES...)'
6082 The argument NAMES is regarded as a series of names, separated by
6083 whitespace. The value is the first name in the series. The rest
6084 of the names are ignored.
6088 $(firstword foo bar)
6090 produces the result 'foo'. Although '$(firstword TEXT)' is the
6091 same as '$(word 1,TEXT)', the 'firstword' function is retained for
6094 '$(lastword NAMES...)'
6095 The argument NAMES is regarded as a series of names, separated by
6096 whitespace. The value is the last name in the series.
6102 produces the result 'bar'. Although '$(lastword TEXT)' is the same
6103 as '$(word $(words TEXT),TEXT)', the 'lastword' function was added
6104 for its simplicity and better performance.
6106 Here is a realistic example of the use of 'subst' and 'patsubst'.
6107 Suppose that a makefile uses the 'VPATH' variable to specify a list of
6108 directories that 'make' should search for prerequisite files (*note
6109 'VPATH' Search Path for All Prerequisites: General Search.). This
6110 example shows how to tell the C compiler to search for header files in
6111 the same list of directories.
6113 The value of 'VPATH' is a list of directories separated by colons,
6114 such as 'src:../headers'. First, the 'subst' function is used to change
6115 the colons to spaces:
6117 $(subst :, ,$(VPATH))
6119 This produces 'src ../headers'. Then 'patsubst' is used to turn each
6120 directory name into a '-I' flag. These can be added to the value of the
6121 variable 'CFLAGS', which is passed automatically to the C compiler, like
6124 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
6126 The effect is to append the text '-Isrc -I../headers' to the previously
6127 given value of 'CFLAGS'. The 'override' directive is used so that the
6128 new value is assigned even if the previous value of 'CFLAGS' was
6129 specified with a command argument (*note The 'override' Directive:
6130 Override Directive.).
6133 File: make.info, Node: File Name Functions, Next: Conditional Functions, Prev: Text Functions, Up: Functions
6135 8.3 Functions for File Names
6136 ============================
6138 Several of the built-in expansion functions relate specifically to
6139 taking apart file names or lists of file names.
6141 Each of the following functions performs a specific transformation on
6142 a file name. The argument of the function is regarded as a series of
6143 file names, separated by whitespace. (Leading and trailing whitespace
6144 is ignored.) Each file name in the series is transformed in the same
6145 way and the results are concatenated with single spaces between them.
6148 Extracts the directory-part of each file name in NAMES. The
6149 directory-part of the file name is everything up through (and
6150 including) the last slash in it. If the file name contains no
6151 slash, the directory part is the string './'. For example,
6153 $(dir src/foo.c hacks)
6155 produces the result 'src/ ./'.
6157 '$(notdir NAMES...)'
6158 Extracts all but the directory-part of each file name in NAMES. If
6159 the file name contains no slash, it is left unchanged. Otherwise,
6160 everything through the last slash is removed from it.
6162 A file name that ends with a slash becomes an empty string. This
6163 is unfortunate, because it means that the result does not always
6164 have the same number of whitespace-separated file names as the
6165 argument had; but we do not see any other valid alternative.
6169 $(notdir src/foo.c hacks)
6171 produces the result 'foo.c hacks'.
6173 '$(suffix NAMES...)'
6174 Extracts the suffix of each file name in NAMES. If the file name
6175 contains a period, the suffix is everything starting with the last
6176 period. Otherwise, the suffix is the empty string. This
6177 frequently means that the result will be empty when NAMES is not,
6178 and if NAMES contains multiple file names, the result may contain
6183 $(suffix src/foo.c src-1.0/bar.c hacks)
6185 produces the result '.c .c'.
6187 '$(basename NAMES...)'
6188 Extracts all but the suffix of each file name in NAMES. If the
6189 file name contains a period, the basename is everything starting up
6190 to (and not including) the last period. Periods in the directory
6191 part are ignored. If there is no period, the basename is the
6192 entire file name. For example,
6194 $(basename src/foo.c src-1.0/bar hacks)
6196 produces the result 'src/foo src-1.0/bar hacks'.
6198 '$(addsuffix SUFFIX,NAMES...)'
6199 The argument NAMES is regarded as a series of names, separated by
6200 whitespace; SUFFIX is used as a unit. The value of SUFFIX is
6201 appended to the end of each individual name and the resulting
6202 larger names are concatenated with single spaces between them. For
6205 $(addsuffix .c,foo bar)
6207 produces the result 'foo.c bar.c'.
6209 '$(addprefix PREFIX,NAMES...)'
6210 The argument NAMES is regarded as a series of names, separated by
6211 whitespace; PREFIX is used as a unit. The value of PREFIX is
6212 prepended to the front of each individual name and the resulting
6213 larger names are concatenated with single spaces between them. For
6216 $(addprefix src/,foo bar)
6218 produces the result 'src/foo src/bar'.
6220 '$(join LIST1,LIST2)'
6221 Concatenates the two arguments word by word: the two first words
6222 (one from each argument) concatenated form the first word of the
6223 result, the two second words form the second word of the result,
6224 and so on. So the Nth word of the result comes from the Nth word
6225 of each argument. If one argument has more words that the other,
6226 the extra words are copied unchanged into the result.
6228 For example, '$(join a b,.c .o)' produces 'a.c b.o'.
6230 Whitespace between the words in the lists is not preserved; it is
6231 replaced with a single space.
6233 This function can merge the results of the 'dir' and 'notdir'
6234 functions, to produce the original list of files which was given to
6235 those two functions.
6237 '$(wildcard PATTERN)'
6238 The argument PATTERN is a file name pattern, typically containing
6239 wildcard characters (as in shell file name patterns). The result
6240 of 'wildcard' is a space-separated list of the names of existing
6241 files that match the pattern. *Note Using Wildcard Characters in
6242 File Names: Wildcards.
6244 '$(realpath NAMES...)'
6245 For each file name in NAMES return the canonical absolute name. A
6246 canonical name does not contain any '.' or '..' components, nor any
6247 repeated path separators ('/') or symlinks. In case of a failure
6248 the empty string is returned. Consult the 'realpath(3)'
6249 documentation for a list of possible failure causes.
6251 '$(abspath NAMES...)'
6252 For each file name in NAMES return an absolute name that does not
6253 contain any '.' or '..' components, nor any repeated path
6254 separators ('/'). Note that, in contrast to 'realpath' function,
6255 'abspath' does not resolve symlinks and does not require the file
6256 names to refer to an existing file or directory. Use the
6257 'wildcard' function to test for existence.
6260 File: make.info, Node: Conditional Functions, Next: Foreach Function, Prev: File Name Functions, Up: Functions
6262 8.4 Functions for Conditionals
6263 ==============================
6265 There are three functions that provide conditional expansion. A key
6266 aspect of these functions is that not all of the arguments are expanded
6267 initially. Only those arguments which need to be expanded, will be
6270 '$(if CONDITION,THEN-PART[,ELSE-PART])'
6271 The 'if' function provides support for conditional expansion in a
6272 functional context (as opposed to the GNU 'make' makefile
6273 conditionals such as 'ifeq' (*note Syntax of Conditionals:
6274 Conditional Syntax.)).
6276 The first argument, CONDITION, first has all preceding and trailing
6277 whitespace stripped, then is expanded. If it expands to any
6278 non-empty string, then the condition is considered to be true. If
6279 it expands to an empty string, the condition is considered to be
6282 If the condition is true then the second argument, THEN-PART, is
6283 evaluated and this is used as the result of the evaluation of the
6284 entire 'if' function.
6286 If the condition is false then the third argument, ELSE-PART, is
6287 evaluated and this is the result of the 'if' function. If there is
6288 no third argument, the 'if' function evaluates to nothing (the
6291 Note that only one of the THEN-PART or the ELSE-PART will be
6292 evaluated, never both. Thus, either can contain side-effects (such
6293 as 'shell' function calls, etc.)
6295 '$(or CONDITION1[,CONDITION2[,CONDITION3...]])'
6296 The 'or' function provides a "short-circuiting" OR operation. Each
6297 argument is expanded, in order. If an argument expands to a
6298 non-empty string the processing stops and the result of the
6299 expansion is that string. If, after all arguments are expanded,
6300 all of them are false (empty), then the result of the expansion is
6303 '$(and CONDITION1[,CONDITION2[,CONDITION3...]])'
6304 The 'and' function provides a "short-circuiting" AND operation.
6305 Each argument is expanded, in order. If an argument expands to an
6306 empty string the processing stops and the result of the expansion
6307 is the empty string. If all arguments expand to a non-empty string
6308 then the result of the expansion is the expansion of the last
6312 File: make.info, Node: Foreach Function, Next: File Function, Prev: Conditional Functions, Up: Functions
6314 8.5 The 'foreach' Function
6315 ==========================
6317 The 'foreach' function is very different from other functions. It
6318 causes one piece of text to be used repeatedly, each time with a
6319 different substitution performed on it. It resembles the 'for' command
6320 in the shell 'sh' and the 'foreach' command in the C-shell 'csh'.
6322 The syntax of the 'foreach' function is:
6324 $(foreach VAR,LIST,TEXT)
6326 The first two arguments, VAR and LIST, are expanded before anything else
6327 is done; note that the last argument, TEXT, is *not* expanded at the
6328 same time. Then for each word of the expanded value of LIST, the
6329 variable named by the expanded value of VAR is set to that word, and
6330 TEXT is expanded. Presumably TEXT contains references to that variable,
6331 so its expansion will be different each time.
6333 The result is that TEXT is expanded as many times as there are
6334 whitespace-separated words in LIST. The multiple expansions of TEXT are
6335 concatenated, with spaces between them, to make the result of 'foreach'.
6337 This simple example sets the variable 'files' to the list of all
6338 files in the directories in the list 'dirs':
6341 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
6343 Here TEXT is '$(wildcard $(dir)/*)'. The first repetition finds the
6344 value 'a' for 'dir', so it produces the same result as '$(wildcard
6345 a/*)'; the second repetition produces the result of '$(wildcard b/*)';
6346 and the third, that of '$(wildcard c/*)'.
6348 This example has the same result (except for setting 'dirs') as the
6351 files := $(wildcard a/* b/* c/* d/*)
6353 When TEXT is complicated, you can improve readability by giving it a
6354 name, with an additional variable:
6356 find_files = $(wildcard $(dir)/*)
6358 files := $(foreach dir,$(dirs),$(find_files))
6360 Here we use the variable 'find_files' this way. We use plain '=' to
6361 define a recursively-expanding variable, so that its value contains an
6362 actual function call to be re-expanded under the control of 'foreach'; a
6363 simply-expanded variable would not do, since 'wildcard' would be called
6364 only once at the time of defining 'find_files'.
6366 The 'foreach' function has no permanent effect on the variable VAR;
6367 its value and flavor after the 'foreach' function call are the same as
6368 they were beforehand. The other values which are taken from LIST are in
6369 effect only temporarily, during the execution of 'foreach'. The
6370 variable VAR is a simply-expanded variable during the execution of
6371 'foreach'. If VAR was undefined before the 'foreach' function call, it
6372 is undefined after the call. *Note The Two Flavors of Variables:
6375 You must take care when using complex variable expressions that
6376 result in variable names because many strange things are valid variable
6377 names, but are probably not what you intended. For example,
6379 files := $(foreach Esta-escrito-en-espanol!,b c ch,$(find_files))
6381 might be useful if the value of 'find_files' references the variable
6382 whose name is 'Esta-escrito-en-espanol!' (es un nombre bastante largo,
6383 no?), but it is more likely to be a mistake.
6386 File: make.info, Node: File Function, Next: Call Function, Prev: Foreach Function, Up: Functions
6388 8.6 The 'file' Function
6389 =======================
6391 The 'file' function allows the makefile to write to or read from a file.
6392 Two modes of writing are supported: overwrite, where the text is written
6393 to the beginning of the file and any existing content is lost, and
6394 append, where the text is written to the end of the file, preserving the
6395 existing content. In both cases the file is created if it does not
6396 exist. It is a fatal error if the file cannot be opened for writing, or
6397 if the write operation fails. The 'file' function expands to the empty
6398 string when writing to a file.
6400 When reading from a file, the 'file' function expands to the verbatim
6401 contents of the file, except that the final newline (if there is one)
6402 will be stripped. Attempting to read from a non-existent file expands
6403 to the empty string.
6405 The syntax of the 'file' function is:
6407 $(file OP FILENAME[,TEXT])
6409 When the 'file' function is evaluated all its arguments are expanded
6410 first, then the file indicated by FILENAME will be opened in the mode
6413 The operator OP can be '>' to indicate the file will be overwritten
6414 with new content, '>>' to indicate the current contents of the file will
6415 be appended to, or '<' to indicate the contents of the file will be read
6416 in. The FILENAME specifies the file to be written to or read from.
6417 There may optionally be whitespace between the operator and the file
6420 When reading files, it is an error to provide a TEXT value.
6422 When writing files, TEXT will be written to the file. If TEXT does
6423 not already end in a newline a final newline will be written (even if
6424 TEXT is the empty string). If the TEXT argument is not given at all,
6425 nothing will be written.
6427 For example, the 'file' function can be useful if your build system
6428 has a limited command line size and your recipe runs a command that can
6429 accept arguments from a file as well. Many commands use the convention
6430 that an argument prefixed with an '@' specifies a file containing more
6431 arguments. Then you might write your recipe in this way:
6435 $(CMD) $(CMDFLAGS) @$@.in
6438 If the command required each argument to be on a separate line of the
6439 input file, you might write your recipe like this:
6442 $(file >$@.in) $(foreach O,$^,$(file >>$@.in,$O))
6443 $(CMD) $(CMDFLAGS) @$@.in
6447 File: make.info, Node: Call Function, Next: Value Function, Prev: File Function, Up: Functions
6449 8.7 The 'call' Function
6450 =======================
6452 The 'call' function is unique in that it can be used to create new
6453 parameterized functions. You can write a complex expression as the
6454 value of a variable, then use 'call' to expand it with different values.
6456 The syntax of the 'call' function is:
6458 $(call VARIABLE,PARAM,PARAM,...)
6460 When 'make' expands this function, it assigns each PARAM to temporary
6461 variables '$(1)', '$(2)', etc. The variable '$(0)' will contain
6462 VARIABLE. There is no maximum number of parameter arguments. There is
6463 no minimum, either, but it doesn't make sense to use 'call' with no
6466 Then VARIABLE is expanded as a 'make' variable in the context of
6467 these temporary assignments. Thus, any reference to '$(1)' in the value
6468 of VARIABLE will resolve to the first PARAM in the invocation of 'call'.
6470 Note that VARIABLE is the _name_ of a variable, not a _reference_ to
6471 that variable. Therefore you would not normally use a '$' or
6472 parentheses when writing it. (You can, however, use a variable
6473 reference in the name if you want the name not to be a constant.)
6475 If VARIABLE is the name of a built-in function, the built-in function
6476 is always invoked (even if a 'make' variable by that name also exists).
6478 The 'call' function expands the PARAM arguments before assigning them
6479 to temporary variables. This means that VARIABLE values containing
6480 references to built-in functions that have special expansion rules, like
6481 'foreach' or 'if', may not work as you expect.
6483 Some examples may make this clearer.
6485 This macro simply reverses its arguments:
6489 foo = $(call reverse,a,b)
6491 Here FOO will contain 'b a'.
6493 This one is slightly more interesting: it defines a macro to search
6494 for the first instance of a program in 'PATH':
6496 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
6498 LS := $(call pathsearch,ls)
6500 Now the variable LS contains '/bin/ls' or similar.
6502 The 'call' function can be nested. Each recursive invocation gets
6503 its own local values for '$(1)', etc. that mask the values of
6504 higher-level 'call'. For example, here is an implementation of a "map"
6507 map = $(foreach a,$(2),$(call $(1),$(a)))
6509 Now you can MAP a function that normally takes only one argument,
6510 such as 'origin', to multiple values in one step:
6512 o = $(call map,origin,o map MAKE)
6514 and end up with O containing something like 'file file default'.
6516 A final caution: be careful when adding whitespace to the arguments
6517 to 'call'. As with other functions, any whitespace contained in the
6518 second and subsequent arguments is kept; this can cause strange effects.
6519 It's generally safest to remove all extraneous whitespace when providing
6520 parameters to 'call'.
6523 File: make.info, Node: Value Function, Next: Eval Function, Prev: Call Function, Up: Functions
6525 8.8 The 'value' Function
6526 ========================
6528 The 'value' function provides a way for you to use the value of a
6529 variable _without_ having it expanded. Please note that this does not
6530 undo expansions which have already occurred; for example if you create a
6531 simply expanded variable its value is expanded during the definition; in
6532 that case the 'value' function will return the same result as using the
6535 The syntax of the 'value' function is:
6539 Note that VARIABLE is the _name_ of a variable, not a _reference_ to
6540 that variable. Therefore you would not normally use a '$' or
6541 parentheses when writing it. (You can, however, use a variable
6542 reference in the name if you want the name not to be a constant.)
6544 The result of this function is a string containing the value of
6545 VARIABLE, without any expansion occurring. For example, in this
6554 The first output line would be 'ATH', since the "$P" would be expanded
6555 as a 'make' variable, while the second output line would be the current
6556 value of your '$PATH' environment variable, since the 'value' function
6557 avoided the expansion.
6559 The 'value' function is most often used in conjunction with the
6560 'eval' function (*note Eval Function::).
6563 File: make.info, Node: Eval Function, Next: Origin Function, Prev: Value Function, Up: Functions
6565 8.9 The 'eval' Function
6566 =======================
6568 The 'eval' function is very special: it allows you to define new
6569 makefile constructs that are not constant; which are the result of
6570 evaluating other variables and functions. The argument to the 'eval'
6571 function is expanded, then the results of that expansion are parsed as
6572 makefile syntax. The expanded results can define new 'make' variables,
6573 targets, implicit or explicit rules, etc.
6575 The result of the 'eval' function is always the empty string; thus,
6576 it can be placed virtually anywhere in a makefile without causing syntax
6579 It's important to realize that the 'eval' argument is expanded
6580 _twice_; first by the 'eval' function, then the results of that
6581 expansion are expanded again when they are parsed as makefile syntax.
6582 This means you may need to provide extra levels of escaping for "$"
6583 characters when using 'eval'. The 'value' function (*note Value
6584 Function::) can sometimes be useful in these situations, to circumvent
6585 unwanted expansions.
6587 Here is an example of how 'eval' can be used; this example combines a
6588 number of concepts and other functions. Although it might seem overly
6589 complex to use 'eval' in this example, rather than just writing out the
6590 rules, consider two things: first, the template definition (in
6591 'PROGRAM_template') could need to be much more complex than it is here;
6592 and second, you might put the complex, "generic" part of this example
6593 into another makefile, then include it in all the individual makefiles.
6594 Now your individual makefiles are quite straightforward.
6596 PROGRAMS = server client
6598 server_OBJS = server.o server_priv.o server_access.o
6599 server_LIBS = priv protocol
6601 client_OBJS = client.o client_api.o client_mem.o
6602 client_LIBS = protocol
6604 # Everything after this is generic
6609 define PROGRAM_template =
6610 $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
6611 ALL_OBJS += $$($(1)_OBJS)
6614 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
6617 $(LINK.o) $^ $(LDLIBS) -o $@
6620 rm -f $(ALL_OBJS) $(PROGRAMS)
6623 File: make.info, Node: Origin Function, Next: Flavor Function, Prev: Eval Function, Up: Functions
6625 8.10 The 'origin' Function
6626 ==========================
6628 The 'origin' function is unlike most other functions in that it does not
6629 operate on the values of variables; it tells you something _about_ a
6630 variable. Specifically, it tells you where it came from.
6632 The syntax of the 'origin' function is:
6636 Note that VARIABLE is the _name_ of a variable to inquire about, not
6637 a _reference_ to that variable. Therefore you would not normally use a
6638 '$' or parentheses when writing it. (You can, however, use a variable
6639 reference in the name if you want the name not to be a constant.)
6641 The result of this function is a string telling you how the variable
6642 VARIABLE was defined:
6646 if VARIABLE was never defined.
6650 if VARIABLE has a default definition, as is usual with 'CC' and so
6651 on. *Note Variables Used by Implicit Rules: Implicit Variables.
6652 Note that if you have redefined a default variable, the 'origin'
6653 function will return the origin of the later definition.
6657 if VARIABLE was inherited from the environment provided to 'make'.
6659 'environment override'
6661 if VARIABLE was inherited from the environment provided to 'make',
6662 and is overriding a setting for VARIABLE in the makefile as a
6663 result of the '-e' option (*note Summary of Options: Options
6668 if VARIABLE was defined in a makefile.
6672 if VARIABLE was defined on the command line.
6676 if VARIABLE was defined with an 'override' directive in a makefile
6677 (*note The 'override' Directive: Override Directive.).
6681 if VARIABLE is an automatic variable defined for the execution of
6682 the recipe for each rule (*note Automatic Variables::).
6684 This information is primarily useful (other than for your curiosity)
6685 to determine if you want to believe the value of a variable. For
6686 example, suppose you have a makefile 'foo' that includes another
6687 makefile 'bar'. You want a variable 'bletch' to be defined in 'bar' if
6688 you run the command 'make -f bar', even if the environment contains a
6689 definition of 'bletch'. However, if 'foo' defined 'bletch' before
6690 including 'bar', you do not want to override that definition. This
6691 could be done by using an 'override' directive in 'foo', giving that
6692 definition precedence over the later definition in 'bar'; unfortunately,
6693 the 'override' directive would also override any command line
6694 definitions. So, 'bar' could include:
6697 ifeq "$(origin bletch)" "environment"
6698 bletch = barf, gag, etc.
6702 If 'bletch' has been defined from the environment, this will redefine
6705 If you want to override a previous definition of 'bletch' if it came
6706 from the environment, even under '-e', you could instead write:
6708 ifneq "$(findstring environment,$(origin bletch))" ""
6709 bletch = barf, gag, etc.
6712 Here the redefinition takes place if '$(origin bletch)' returns
6713 either 'environment' or 'environment override'. *Note Functions for
6714 String Substitution and Analysis: Text Functions.
6717 File: make.info, Node: Flavor Function, Next: Make Control Functions, Prev: Origin Function, Up: Functions
6719 8.11 The 'flavor' Function
6720 ==========================
6722 The 'flavor' function, like the 'origin' function, does not operate on
6723 the values of variables but rather it tells you something _about_ a
6724 variable. Specifically, it tells you the flavor of a variable (*note
6725 The Two Flavors of Variables: Flavors.).
6727 The syntax of the 'flavor' function is:
6731 Note that VARIABLE is the _name_ of a variable to inquire about, not
6732 a _reference_ to that variable. Therefore you would not normally use a
6733 '$' or parentheses when writing it. (You can, however, use a variable
6734 reference in the name if you want the name not to be a constant.)
6736 The result of this function is a string that identifies the flavor of
6737 the variable VARIABLE:
6741 if VARIABLE was never defined.
6745 if VARIABLE is a recursively expanded variable.
6749 if VARIABLE is a simply expanded variable.
6752 File: make.info, Node: Make Control Functions, Next: Shell Function, Prev: Flavor Function, Up: Functions
6754 8.12 Functions That Control Make
6755 ================================
6757 These functions control the way make runs. Generally, they are used to
6758 provide information to the user of the makefile or to cause make to stop
6759 if some sort of environmental error is detected.
6762 Generates a fatal error where the message is TEXT. Note that the
6763 error is generated whenever this function is evaluated. So, if you
6764 put it inside a recipe or on the right side of a recursive variable
6765 assignment, it won't be evaluated until later. The TEXT will be
6766 expanded before the error is generated.
6771 $(error error is $(ERROR1))
6774 will generate a fatal error during the read of the makefile if the
6775 'make' variable 'ERROR1' is defined. Or,
6777 ERR = $(error found an error!)
6782 will generate a fatal error while 'make' is running, if the 'err'
6785 '$(warning TEXT...)'
6786 This function works similarly to the 'error' function, above,
6787 except that 'make' doesn't exit. Instead, TEXT is expanded and the
6788 resulting message is displayed, but processing of the makefile
6791 The result of the expansion of this function is the empty string.
6794 This function does nothing more than print its (expanded)
6795 argument(s) to standard output. No makefile name or line number is
6796 added. The result of the expansion of this function is the empty
6800 File: make.info, Node: Shell Function, Next: Guile Function, Prev: Make Control Functions, Up: Functions
6802 8.13 The 'shell' Function
6803 =========================
6805 The 'shell' function is unlike any other function other than the
6806 'wildcard' function (*note The Function 'wildcard': Wildcard Function.)
6807 in that it communicates with the world outside of 'make'.
6809 The 'shell' function performs the same function that backquotes ('`')
6810 perform in most shells: it does "command expansion". This means that it
6811 takes as an argument a shell command and evaluates to the output of the
6812 command. The only processing 'make' does on the result is to convert
6813 each newline (or carriage-return / newline pair) to a single space. If
6814 there is a trailing (carriage-return and) newline it will simply be
6817 The commands run by calls to the 'shell' function are run when the
6818 function calls are expanded (*note How 'make' Reads a Makefile: Reading
6819 Makefiles.). Because this function involves spawning a new shell, you
6820 should carefully consider the performance implications of using the
6821 'shell' function within recursively expanded variables vs. simply
6822 expanded variables (*note The Two Flavors of Variables: Flavors.).
6824 After the 'shell' function or '!=' assignment operator is used, its
6825 exit status is placed in the '.SHELLSTATUS' variable.
6827 Here are some examples of the use of the 'shell' function:
6829 contents := $(shell cat foo)
6831 sets 'contents' to the contents of the file 'foo', with a space (rather
6832 than a newline) separating each line.
6834 files := $(shell echo *.c)
6836 sets 'files' to the expansion of '*.c'. Unless 'make' is using a very
6837 strange shell, this has the same result as '$(wildcard *.c)' (as long as
6838 at least one '.c' file exists).
6841 File: make.info, Node: Guile Function, Prev: Shell Function, Up: Functions
6843 8.14 The 'guile' Function
6844 =========================
6846 If GNU 'make' is built with support for GNU Guile as an embedded
6847 extension language then the 'guile' function will be available. The
6848 'guile' function takes one argument which is first expanded by 'make' in
6849 the normal fashion, then passed to the GNU Guile evaluator. The result
6850 of the evaluator is converted into a string and used as the expansion of
6851 the 'guile' function in the makefile. See *note GNU Guile Integration:
6852 Guile Integration. for details on writing extensions to 'make' in Guile.
6854 You can determine whether GNU Guile support is available by checking
6855 the '.FEATURES' variable for the word GUILE.
6858 File: make.info, Node: Running, Next: Implicit Rules, Prev: Functions, Up: Top
6863 A makefile that says how to recompile a program can be used in more than
6864 one way. The simplest use is to recompile every file that is out of
6865 date. Usually, makefiles are written so that if you run 'make' with no
6866 arguments, it does just that.
6868 But you might want to update only some of the files; you might want
6869 to use a different compiler or different compiler options; you might
6870 want just to find out which files are out of date without changing them.
6872 By giving arguments when you run 'make', you can do any of these
6873 things and many others.
6875 The exit status of 'make' is always one of three values:
6877 The exit status is zero if 'make' is successful.
6879 The exit status is two if 'make' encounters any errors. It will
6880 print messages describing the particular errors.
6882 The exit status is one if you use the '-q' flag and 'make'
6883 determines that some target is not already up to date. *Note
6884 Instead of Executing Recipes: Instead of Execution.
6888 * Makefile Arguments:: How to specify which makefile to use.
6889 * Goals:: How to use goal arguments to specify which
6890 parts of the makefile to use.
6891 * Instead of Execution:: How to use mode flags to specify what
6892 kind of thing to do with the recipes
6893 in the makefile other than simply
6895 * Avoiding Compilation:: How to avoid recompiling certain files.
6896 * Overriding:: How to override a variable to specify
6897 an alternate compiler and other things.
6898 * Testing:: How to proceed past some errors, to
6900 * Options Summary:: Summary of Options
6903 File: make.info, Node: Makefile Arguments, Next: Goals, Prev: Running, Up: Running
6905 9.1 Arguments to Specify the Makefile
6906 =====================================
6908 The way to specify the name of the makefile is with the '-f' or '--file'
6909 option ('--makefile' also works). For example, '-f altmake' says to use
6910 the file 'altmake' as the makefile.
6912 If you use the '-f' flag several times and follow each '-f' with an
6913 argument, all the specified files are used jointly as makefiles.
6915 If you do not use the '-f' or '--file' flag, the default is to try
6916 'GNUmakefile', 'makefile', and 'Makefile', in that order, and use the
6917 first of these three which exists or can be made (*note Writing
6918 Makefiles: Makefiles.).
6921 File: make.info, Node: Goals, Next: Instead of Execution, Prev: Makefile Arguments, Up: Running
6923 9.2 Arguments to Specify the Goals
6924 ==================================
6926 The "goals" are the targets that 'make' should strive ultimately to
6927 update. Other targets are updated as well if they appear as
6928 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
6930 By default, the goal is the first target in the makefile (not
6931 counting targets that start with a period). Therefore, makefiles are
6932 usually written so that the first target is for compiling the entire
6933 program or programs they describe. If the first rule in the makefile
6934 has several targets, only the first target in the rule becomes the
6935 default goal, not the whole list. You can manage the selection of the
6936 default goal from within your makefile using the '.DEFAULT_GOAL'
6937 variable (*note Other Special Variables: Special Variables.).
6939 You can also specify a different goal or goals with command line
6940 arguments to 'make'. Use the name of the goal as an argument. If you
6941 specify several goals, 'make' processes each of them in turn, in the
6942 order you name them.
6944 Any target in the makefile may be specified as a goal (unless it
6945 starts with '-' or contains an '=', in which case it will be parsed as a
6946 switch or variable definition, respectively). Even targets not in the
6947 makefile may be specified, if 'make' can find implicit rules that say
6950 'Make' will set the special variable 'MAKECMDGOALS' to the list of
6951 goals you specified on the command line. If no goals were given on the
6952 command line, this variable is empty. Note that this variable should be
6953 used only in special circumstances.
6955 An example of appropriate use is to avoid including '.d' files during
6956 'clean' rules (*note Automatic Prerequisites::), so 'make' won't create
6957 them only to immediately remove them again:
6959 sources = foo.c bar.c
6961 ifneq ($(MAKECMDGOALS),clean)
6962 include $(sources:.c=.d)
6965 One use of specifying a goal is if you want to compile only a part of
6966 the program, or only one of several programs. Specify as a goal each
6967 file that you wish to remake. For example, consider a directory
6968 containing several programs, with a makefile that starts like this:
6971 all: size nm ld ar as
6973 If you are working on the program 'size', you might want to say
6974 'make size' so that only the files of that program are recompiled.
6976 Another use of specifying a goal is to make files that are not
6977 normally made. For example, there may be a file of debugging output, or
6978 a version of the program that is compiled specially for testing, which
6979 has a rule in the makefile but is not a prerequisite of the default
6982 Another use of specifying a goal is to run the recipe associated with
6983 a phony target (*note Phony Targets::) or empty target (*note Empty
6984 Target Files to Record Events: Empty Targets.). Many makefiles contain
6985 a phony target named 'clean' which deletes everything except source
6986 files. Naturally, this is done only if you request it explicitly with
6987 'make clean'. Following is a list of typical phony and empty target
6988 names. *Note Standard Targets::, for a detailed list of all the
6989 standard target names which GNU software packages use.
6992 Make all the top-level targets the makefile knows about.
6995 Delete all files that are normally created by running 'make'.
6998 Like 'clean', but may refrain from deleting a few files that people
6999 normally don't want to recompile. For example, the 'mostlyclean'
7000 target for GCC does not delete 'libgcc.a', because recompiling it
7001 is rarely necessary and takes a lot of time.
7006 Any of these targets might be defined to delete _more_ files than
7007 'clean' does. For example, this would delete configuration files
7008 or links that you would normally create as preparation for
7009 compilation, even if the makefile itself cannot create these files.
7012 Copy the executable file into a directory that users typically
7013 search for commands; copy any auxiliary files that the executable
7014 uses into the directories where it will look for them.
7017 Print listings of the source files that have changed.
7020 Create a tar file of the source files.
7023 Create a shell archive (shar file) of the source files.
7026 Create a distribution file of the source files. This might be a
7027 tar file, or a shar file, or a compressed version of one of the
7028 above, or even more than one of the above.
7031 Update a tags table for this program.
7035 Perform self tests on the program this makefile builds.
7038 File: make.info, Node: Instead of Execution, Next: Avoiding Compilation, Prev: Goals, Up: Running
7040 9.3 Instead of Executing Recipes
7041 ================================
7043 The makefile tells 'make' how to tell whether a target is up to date,
7044 and how to update each target. But updating the targets is not always
7045 what you want. Certain options specify other activities for 'make'.
7052 "No-op". Causes 'make' to print the recipes that are needed to
7053 make the targets up to date, but not actually execute them. Note
7054 that some recipes are still executed, even with this flag (*note
7055 How the 'MAKE' Variable Works: MAKE Variable.). Also any recipes
7056 needed to update included makefiles are still executed (*note How
7057 Makefiles Are Remade: Remaking Makefiles.).
7062 "Touch". Marks targets as up to date without actually changing
7063 them. In other words, 'make' pretends to update the targets but
7064 does not really change their contents; instead only their modified
7070 "Question". Silently check whether the targets are up to date, but
7071 do not execute recipes; the exit code shows whether any updates are
7079 "What if". Each '-W' flag is followed by a file name. The given
7080 files' modification times are recorded by 'make' as being the
7081 present time, although the actual modification times remain the
7082 same. You can use the '-W' flag in conjunction with the '-n' flag
7083 to see what would happen if you were to modify specific files.
7085 With the '-n' flag, 'make' prints the recipe that it would normally
7086 execute but usually does not execute it.
7088 With the '-t' flag, 'make' ignores the recipes in the rules and uses
7089 (in effect) the command 'touch' for each target that needs to be remade.
7090 The 'touch' command is also printed, unless '-s' or '.SILENT' is used.
7091 For speed, 'make' does not actually invoke the program 'touch'. It does
7094 With the '-q' flag, 'make' prints nothing and executes no recipes,
7095 but the exit status code it returns is zero if and only if the targets
7096 to be considered are already up to date. If the exit status is one,
7097 then some updating needs to be done. If 'make' encounters an error, the
7098 exit status is two, so you can distinguish an error from a target that
7101 It is an error to use more than one of these three flags in the same
7102 invocation of 'make'.
7104 The '-n', '-t', and '-q' options do not affect recipe lines that
7105 begin with '+' characters or contain the strings '$(MAKE)' or '${MAKE}'.
7106 Note that only the line containing the '+' character or the strings
7107 '$(MAKE)' or '${MAKE}' is run regardless of these options. Other lines
7108 in the same rule are not run unless they too begin with '+' or contain
7109 '$(MAKE)' or '${MAKE}' (*Note How the 'MAKE' Variable Works: MAKE
7112 The '-t' flag prevents phony targets (*note Phony Targets::) from
7113 being updated, unless there are recipe lines beginning with '+' or
7114 containing '$(MAKE)' or '${MAKE}'.
7116 The '-W' flag provides two features:
7118 * If you also use the '-n' or '-q' flag, you can see what 'make'
7119 would do if you were to modify some files.
7121 * Without the '-n' or '-q' flag, when 'make' is actually executing
7122 recipes, the '-W' flag can direct 'make' to act as if some files
7123 had been modified, without actually running the recipes for those
7126 Note that the options '-p' and '-v' allow you to obtain other
7127 information about 'make' or about the makefiles in use (*note Summary of
7128 Options: Options Summary.).
7131 File: make.info, Node: Avoiding Compilation, Next: Overriding, Prev: Instead of Execution, Up: Running
7133 9.4 Avoiding Recompilation of Some Files
7134 ========================================
7136 Sometimes you may have changed a source file but you do not want to
7137 recompile all the files that depend on it. For example, suppose you add
7138 a macro or a declaration to a header file that many other files depend
7139 on. Being conservative, 'make' assumes that any change in the header
7140 file requires recompilation of all dependent files, but you know that
7141 they do not need to be recompiled and you would rather not waste the
7142 time waiting for them to compile.
7144 If you anticipate the problem before changing the header file, you
7145 can use the '-t' flag. This flag tells 'make' not to run the recipes in
7146 the rules, but rather to mark the target up to date by changing its
7147 last-modification date. You would follow this procedure:
7149 1. Use the command 'make' to recompile the source files that really
7150 need recompilation, ensuring that the object files are up-to-date
7153 2. Make the changes in the header files.
7155 3. Use the command 'make -t' to mark all the object files as up to
7156 date. The next time you run 'make', the changes in the header
7157 files will not cause any recompilation.
7159 If you have already changed the header file at a time when some files
7160 do need recompilation, it is too late to do this. Instead, you can use
7161 the '-o FILE' flag, which marks a specified file as "old" (*note Summary
7162 of Options: Options Summary.). This means that the file itself will not
7163 be remade, and nothing else will be remade on its account. Follow this
7166 1. Recompile the source files that need compilation for reasons
7167 independent of the particular header file, with 'make -o
7168 HEADERFILE'. If several header files are involved, use a separate
7169 '-o' option for each header file.
7171 2. Touch all the object files with 'make -t'.
7174 File: make.info, Node: Overriding, Next: Testing, Prev: Avoiding Compilation, Up: Running
7176 9.5 Overriding Variables
7177 ========================
7179 An argument that contains '=' specifies the value of a variable: 'V=X'
7180 sets the value of the variable V to X. If you specify a value in this
7181 way, all ordinary assignments of the same variable in the makefile are
7182 ignored; we say they have been "overridden" by the command line
7185 The most common way to use this facility is to pass extra flags to
7186 compilers. For example, in a properly written makefile, the variable
7187 'CFLAGS' is included in each recipe that runs the C compiler, so a file
7188 'foo.c' would be compiled something like this:
7190 cc -c $(CFLAGS) foo.c
7192 Thus, whatever value you set for 'CFLAGS' affects each compilation
7193 that occurs. The makefile probably specifies the usual value for
7194 'CFLAGS', like this:
7198 Each time you run 'make', you can override this value if you wish.
7199 For example, if you say 'make CFLAGS='-g -O'', each C compilation will
7200 be done with 'cc -c -g -O'. (This also illustrates how you can use
7201 quoting in the shell to enclose spaces and other special characters in
7202 the value of a variable when you override it.)
7204 The variable 'CFLAGS' is only one of many standard variables that
7205 exist just so that you can change them this way. *Note Variables Used
7206 by Implicit Rules: Implicit Variables, for a complete list.
7208 You can also program the makefile to look at additional variables of
7209 your own, giving the user the ability to control other aspects of how
7210 the makefile works by changing the variables.
7212 When you override a variable with a command line argument, you can
7213 define either a recursively-expanded variable or a simply-expanded
7214 variable. The examples shown above make a recursively-expanded
7215 variable; to make a simply-expanded variable, write ':=' or '::='
7216 instead of '='. But, unless you want to include a variable reference or
7217 function call in the _value_ that you specify, it makes no difference
7218 which kind of variable you create.
7220 There is one way that the makefile can change a variable that you
7221 have overridden. This is to use the 'override' directive, which is a
7222 line that looks like this: 'override VARIABLE = VALUE' (*note The
7223 'override' Directive: Override Directive.).