Create a new function $(file ...)
[make.git] / doc / make.texi
blobdfc84654e18f902455baa9e1b1c97ca05f295f48
1 \input texinfo                @c -*- Texinfo -*-
2 @c %**start of header
3 @setfilename make.info
5 @include version.texi
6 @set EDITION 0.72
7 @set RCSID $Id: make.texi,v 1.77 2012/01/29 18:12:22 psmith Exp $
9 @settitle GNU @code{make}
10 @setchapternewpage odd
11 @c Combine the variable and function indices:
12 @syncodeindex vr fn
13 @c Combine the program and concept indices:
14 @syncodeindex pg cp
15 @c FSF publishers: format makebook.texi instead of using this file directly.
16 @c ISBN confirmed by Jasimin Huang <jasimin@fsf.org> on 25 Mar 2009
17 @set ISBN 1-882114-83-3
18 @c %**end of header
20 @copying
21 This file documents the GNU @code{make} utility, which determines
22 automatically which pieces of a large program need to be recompiled,
23 and issues the commands to recompile them.
25 This is Edition @value{EDITION}, last updated @value{UPDATED},
26 of @cite{The GNU Make Manual}, for GNU @code{make} version @value{VERSION}.
28 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
29 1996, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007,
30 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
32 @quotation
33 Permission is granted to copy, distribute and/or modify this document
34 under the terms of the GNU Free Documentation License, Version 1.3 or
35 any later version published by the Free Software Foundation; with no
36 Invariant Sections, with the Front-Cover Texts being ``A GNU Manual,''
37 and with the Back-Cover Texts as in (a) below.  A copy of the
38 license is included in the section entitled ``GNU Free Documentation
39 License.''
41 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
42 modify this GNU manual.  Buying copies from the FSF supports it in
43 developing GNU and promoting software freedom.''
44 @end quotation
45 @end copying
47 @c finalout
49 @c ISPELL CHECK: done, 10 June 1993 --roland
50 @c ISPELL CHECK: done, 2000-06-25 --Martin Buchholz
53 @dircategory Software development
54 @direntry
55 * Make: (make).            Remake files automatically.
56 @end direntry
58 @iftex
59 @shorttitlepage GNU Make
60 @end iftex
61 @titlepage
62 @title GNU Make
63 @subtitle A Program for Directing Recompilation
64 @subtitle GNU @code{make} Version @value{VERSION}
65 @subtitle @value{UPDATED-MONTH}
66 @author Richard M. Stallman, Roland McGrath, Paul D. Smith
67 @page
68 @vskip 0pt plus 1filll
69 @insertcopying
70 @sp 2
71 Published by the Free Software Foundation @*
72 51 Franklin St. -- Fifth Floor @*
73 Boston, MA 02110-1301 USA @*
74 ISBN @value{ISBN} @*
75 @sp 2
76 Cover art by Etienne Suvasa.
77 @end titlepage
79 @summarycontents
80 @contents
82 @ifnottex
83 @node Top, Overview, (dir), (dir)
84 @top GNU @code{make}
86 @insertcopying
87 @end ifnottex
89 @menu
90 * Overview::                    Overview of @code{make}.
91 * Introduction::                An introduction to @code{make}.
92 * Makefiles::                   Makefiles tell @code{make} what to do.
93 * Rules::                       Rules describe when a file must be remade.
94 * Recipes::                     Recipes say how to remake a file.
95 * Using Variables::             You can use variables to avoid repetition.
96 * Conditionals::                Use or ignore parts of the makefile based
97                                   on the values of variables.
98 * Functions::                   Many powerful ways to manipulate text.
99 * Invoking make: Running.       How to invoke @code{make} on the command line.
100 * Implicit Rules::              Use implicit rules to treat many files alike,
101                                   based on their file names.
102 * Archives::                    How @code{make} can update library archives.
103 * Features::                    Features GNU @code{make} has over other @code{make}s.
104 * Missing::                     What GNU @code{make} lacks from other @code{make}s.
105 * Makefile Conventions::        Conventions for writing makefiles for
106                                   GNU programs.
107 * Quick Reference::             A quick reference for experienced users.
108 * Error Messages::              A list of common errors generated by @code{make}.
109 * Complex Makefile::            A real example of a straightforward,
110                                   but nontrivial, makefile.
112 * GNU Free Documentation License::  License for copying this manual.
113 * Concept Index::               Index of Concepts.
114 * Name Index::                  Index of Functions, Variables, & Directives.
116 @detailmenu
117  --- The Detailed Node Listing ---
119 Overview of @code{make}
121 * Preparing::                   Preparing and running @code{make}.
122 * Reading::                     On reading this text.
123 * Bugs::                        Problems and bugs.
125 An Introduction to Makefiles
127 * Rule Introduction::           What a rule looks like.
128 * Simple Makefile::             A simple makefile.
129 * How Make Works::              How @code{make} processes this makefile.
130 * Variables Simplify::          Variables make makefiles simpler.
131 * make Deduces::                Letting @code{make} deduce the recipes.
132 * Combine By Prerequisite::     Another style of makefile.
133 * Cleanup::                     Rules for cleaning the directory.
135 Writing Makefiles
137 * Makefile Contents::           What makefiles contain.
138 * Makefile Names::              How to name your makefile.
139 * Include::                     How one makefile can use another makefile.
140 * MAKEFILES Variable::          The environment can specify extra makefiles.
141 * Remaking Makefiles::          How makefiles get remade.
142 * Overriding Makefiles::        How to override part of one makefile
143                                   with another makefile.
144 * Reading Makefiles::           How makefiles are parsed.
145 * Secondary Expansion::         How and when secondary expansion is performed.
147 Writing Rules
149 * Rule Example::                An example explained.
150 * Rule Syntax::                 General syntax explained.
151 * Prerequisite Types::          There are two types of prerequisites.
152 * Wildcards::                   Using wildcard characters such as `*'.
153 * Directory Search::            Searching other directories for source files.
154 * Phony Targets::               Using a target that is not a real file's name.
155 * Force Targets::               You can use a target without a recipe
156                                   or prerequisites to mark other targets
157                                   as phony.
158 * Empty Targets::               When only the date matters and the
159                                   files are empty.
160 * Special Targets::             Targets with special built-in meanings.
161 * Multiple Targets::            When to make use of several targets in a rule.
162 * Multiple Rules::              How to use several rules with the same target.
163 * Static Pattern::              Static pattern rules apply to multiple targets
164                                   and can vary the prerequisites according to
165                                   the target name.
166 * Double-Colon::                How to use a special kind of rule to allow
167                                   several independent rules for one target.
168 * Automatic Prerequisites::     How to automatically generate rules giving
169                                   prerequisites from source files themselves.
171 Using Wildcard Characters in File Names
173 * Wildcard Examples::           Several examples.
174 * Wildcard Pitfall::            Problems to avoid.
175 * Wildcard Function::           How to cause wildcard expansion where
176                                   it does not normally take place.
178 Searching Directories for Prerequisites
180 * General Search::              Specifying a search path that applies
181                                   to every prerequisite.
182 * Selective Search::            Specifying a search path
183                                   for a specified class of names.
184 * Search Algorithm::            When and how search paths are applied.
185 * Recipes/Search::              How to write recipes that work together
186                                   with search paths.
187 * Implicit/Search::             How search paths affect implicit rules.
188 * Libraries/Search::            Directory search for link libraries.
190 Static Pattern Rules
192 * Static Usage::                The syntax of static pattern rules.
193 * Static versus Implicit::      When are they better than implicit rules?
195 Writing Recipes in Rules
197 * Recipe Syntax::               Recipe syntax features and pitfalls.
198 * Echoing::                     How to control when recipes are echoed.
199 * Execution::                   How recipes are executed.
200 * Parallel::                    How recipes can be executed in parallel.
201 * Errors::                      What happens after a recipe execution error.
202 * Interrupts::                  What happens when a recipe is interrupted.
203 * Recursion::                   Invoking @code{make} from makefiles.
204 * Canned Recipes::              Defining canned recipes.
205 * Empty Recipes::               Defining useful, do-nothing recipes.
207 Recipe Syntax
209 * Splitting Lines::             Breaking long recipe lines for readability.
210 * Variables in Recipes::        Using @code{make} variables in recipes.
212 Recipe Execution
214 * One Shell::                   One shell for all lines in a recipe.
215 * Choosing the Shell::          How @code{make} chooses the shell used
216                                   to run recipes.
218 Recursive Use of @code{make}
220 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
221 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
222 * Options/Recursion::           How to communicate options to a sub-@code{make}.
223 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
224                                   helps debug use of recursive @code{make} commands.
226 How to Use Variables
228 * Reference::                   How to use the value of a variable.
229 * Flavors::                     Variables come in two flavors.
230 * Advanced::                    Advanced features for referencing a variable.
231 * Values::                      All the ways variables get their values.
232 * Setting::                     How to set a variable in the makefile.
233 * Appending::                   How to append more text to the old value
234                                   of a variable.
235 * Override Directive::          How to set a variable in the makefile even if
236                                   the user has set it with a command argument.
237 * Multi-Line::                  An alternate way to set a variable
238                                   to a multi-line string.
239 * Undefine Directive::          How to undefine a variable so that it appears
240                                   as if it was never set.
241 * Environment::                 Variable values can come from the environment.
242 * Target-specific::             Variable values can be defined on a per-target
243                                   basis.
244 * Pattern-specific::            Target-specific variable values can be applied
245                                   to a group of targets that match a pattern.
246 * Suppressing Inheritance::     Suppress inheritance of variables.
247 * Special Variables::           Variables with special meaning or behavior.
249 Advanced Features for Reference to Variables
251 * Substitution Refs::           Referencing a variable with
252                                   substitutions on the value.
253 * Computed Names::              Computing the name of the variable to refer to.
255 Conditional Parts of Makefiles
257 * Conditional Example::         Example of a conditional
258 * Conditional Syntax::          The syntax of conditionals.
259 * Testing Flags::               Conditionals that test flags.
261 Functions for Transforming Text
263 * Syntax of Functions::         How to write a function call.
264 * Text Functions::              General-purpose text manipulation functions.
265 * File Name Functions::         Functions for manipulating file names.
266 * Conditional Functions::       Functions that implement conditions.
267 * Foreach Function::            Repeat some text with controlled variation.
268 * File Function::               Write text to a file.
269 * Call Function::               Expand a user-defined function.
270 * Value Function::              Return the un-expanded value of a variable.
271 * Eval Function::               Evaluate the arguments as makefile syntax.
272 * Origin Function::             Find where a variable got its value.
273 * Flavor Function::             Find out the flavor of a variable.
274 * Make Control Functions::      Functions that control how make runs.
275 * Shell Function::              Substitute the output of a shell command.
276 * Guile Function::              Call the GNU Guile embedded scripting language.
278 The @code{guile} Function
280 * Guile Types::                 Converting Guile types to @code{make} strings.
281 * Guile Interface::             Invoking @code{make} functions from Guile.
282 * Guile Example::               Example using Guile in @code{make}.
284 How to Run @code{make}
286 * Makefile Arguments::          How to specify which makefile to use.
287 * Goals::                       How to use goal arguments to specify which
288                                   parts of the makefile to use.
289 * Instead of Execution::        How to use mode flags to specify what
290                                   kind of thing to do with the recipes
291                                   in the makefile other than simply
292                                   execute them.
293 * Avoiding Compilation::        How to avoid recompiling certain files.
294 * Overriding::                  How to override a variable to specify
295                                   an alternate compiler and other things.
296 * Testing::                     How to proceed past some errors, to
297                                   test compilation.
298 * Options Summary::             Summary of Options
300 Using Implicit Rules
302 * Using Implicit::              How to use an existing implicit rule
303                                   to get the recipes for updating a file.
304 * Catalogue of Rules::          A list of built-in implicit rules.
305 * Implicit Variables::          How to change what predefined rules do.
306 * Chained Rules::               How to use a chain of implicit rules.
307 * Pattern Rules::               How to define new implicit rules.
308 * Last Resort::                 How to define a recipe for rules which
309                                   cannot find any.
310 * Suffix Rules::                The old-fashioned style of implicit rule.
311 * Implicit Rule Search::        The precise algorithm for applying
312                                   implicit rules.
314 Defining and Redefining Pattern Rules
316 * Pattern Intro::               An introduction to pattern rules.
317 * Pattern Examples::            Examples of pattern rules.
318 * Automatic Variables::         How to use automatic variables in the
319                                   recipe of implicit rules.
320 * Pattern Match::               How patterns match.
321 * Match-Anything Rules::        Precautions you should take prior to
322                                   defining rules that can match any
323                                   target file whatever.
324 * Canceling Rules::             How to override or cancel built-in rules.
326 Using @code{make} to Update Archive Files
328 * Archive Members::             Archive members as targets.
329 * Archive Update::              The implicit rule for archive member targets.
330 * Archive Pitfalls::            Dangers to watch out for when using archives.
331 * Archive Suffix Rules::        You can write a special kind of suffix rule
332                                   for updating archives.
334 Implicit Rule for Archive Member Targets
336 * Archive Symbols::             How to update archive symbol directories.
338 @end detailmenu
339 @end menu
341 @node Overview, Introduction, Top, Top
342 @comment  node-name,  next,  previous,  up
343 @chapter Overview of @code{make}
345 The @code{make} utility automatically determines which pieces of a large
346 program need to be recompiled, and issues commands to recompile them.
347 This manual describes GNU @code{make}, which was implemented by Richard
348 Stallman and Roland McGrath.  Development since Version 3.76 has been
349 handled by Paul D. Smith.
351 GNU @code{make} conforms to section 6.2 of @cite{IEEE Standard
352 1003.2-1992} (POSIX.2).
353 @cindex POSIX
354 @cindex IEEE Standard 1003.2
355 @cindex standards conformance
357 Our examples show C programs, since they are most common, but you can use
358 @code{make} with any programming language whose compiler can be run with a
359 shell command.  Indeed, @code{make} is not limited to programs.  You can
360 use it to describe any task where some files must be updated automatically
361 from others whenever the others change.
363 @menu
364 * Preparing::                   Preparing and running @code{make}.
365 * Reading::                     On reading this text.
366 * Bugs::                        Problems and bugs.
367 @end menu
369 @node Preparing, Reading, Overview, Overview
370 @ifnottex
371 @heading Preparing and Running Make
372 @end ifnottex
374 To prepare to use @code{make}, you must write a file called
375 the @dfn{makefile} that describes the relationships among files
376 in your program and provides commands for updating each file.
377 In a program, typically, the executable file is updated from object
378 files, which are in turn made by compiling source files.@refill
380 Once a suitable makefile exists, each time you change some source files,
381 this simple shell command:
383 @example
384 make
385 @end example
387 @noindent
388 suffices to perform all necessary recompilations.  The @code{make} program
389 uses the makefile data base and the last-modification times of the files to
390 decide which of the files need to be updated.  For each of those files, it
391 issues the recipes recorded in the data base.
393 You can provide command line arguments to @code{make} to control which
394 files should be recompiled, or how.  @xref{Running, ,How to Run
395 @code{make}}.
397 @node Reading, Bugs, Preparing, Overview
398 @section How to Read This Manual
400 If you are new to @code{make}, or are looking for a general
401 introduction, read the first few sections of each chapter, skipping the
402 later sections.  In each chapter, the first few sections contain
403 introductory or general information and the later sections contain
404 specialized or technical information.
405 @ifnottex
406 The exception is the second chapter, @ref{Introduction, ,An
407 Introduction to Makefiles}, all of which is introductory.
408 @end ifnottex
409 @iftex
410 The exception is @ref{Introduction, ,An Introduction to Makefiles},
411 all of which is introductory.
412 @end iftex
414 If you are familiar with other @code{make} programs, see @ref{Features,
415 ,Features of GNU @code{make}}, which lists the enhancements GNU
416 @code{make} has, and @ref{Missing, ,Incompatibilities and Missing
417 Features}, which explains the few things GNU @code{make} lacks that
418 others have.
420 For a quick summary, see @ref{Options Summary}, @ref{Quick Reference},
421 and @ref{Special Targets}.
423 @node Bugs,  , Reading, Overview
424 @section Problems and Bugs
425 @cindex reporting bugs
426 @cindex bugs, reporting
427 @cindex problems and bugs, reporting
429 If you have problems with GNU @code{make} or think you've found a bug,
430 please report it to the developers; we cannot promise to do anything but
431 we might well want to fix it.
433 Before reporting a bug, make sure you've actually found a real bug.
434 Carefully reread the documentation and see if it really says you can do
435 what you're trying to do.  If it's not clear whether you should be able
436 to do something or not, report that too; it's a bug in the
437 documentation!
439 Before reporting a bug or trying to fix it yourself, try to isolate it
440 to the smallest possible makefile that reproduces the problem.  Then
441 send us the makefile and the exact results @code{make} gave you,
442 including any error or warning messages.  Please don't paraphrase
443 these messages: it's best to cut and paste them into your report.
444 When generating this small makefile, be sure to not use any non-free
445 or unusual tools in your recipes: you can almost always emulate what
446 such a tool would do with simple shell commands.  Finally, be sure to
447 explain what you expected to occur; this will help us decide whether
448 the problem was really in the documentation.
450 Once you have a precise problem you can report it in one of two ways.
451 Either send electronic mail to:
453 @example
454     bug-make@@gnu.org
455 @end example
457 @noindent
458 or use our Web-based project management tool, at:
460 @example
461     http://savannah.gnu.org/projects/make/
462 @end example
464 @noindent
465 In addition to the information above, please be careful to include the
466 version number of @code{make} you are using.  You can get this
467 information with the command @samp{make --version}.  Be sure also to
468 include the type of machine and operating system you are using.  One
469 way to obtain this information is by looking at the final lines of
470 output from the command @samp{make --help}.
472 @node Introduction, Makefiles, Overview, Top
473 @comment  node-name,  next,  previous,  up
474 @chapter An Introduction to Makefiles
476 You need a file called a @dfn{makefile} to tell @code{make} what to do.
477 Most often, the makefile tells @code{make} how to compile and link a
478 program.
479 @cindex makefile
481 In this chapter, we will discuss a simple makefile that describes how to
482 compile and link a text editor which consists of eight C source files
483 and three header files.  The makefile can also tell @code{make} how to
484 run miscellaneous commands when explicitly asked (for example, to remove
485 certain files as a clean-up operation).  To see a more complex example
486 of a makefile, see @ref{Complex Makefile}.
488 When @code{make} recompiles the editor, each changed C source file
489 must be recompiled.  If a header file has changed, each C source file
490 that includes the header file must be recompiled to be safe.  Each
491 compilation produces an object file corresponding to the source file.
492 Finally, if any source file has been recompiled, all the object files,
493 whether newly made or saved from previous compilations, must be linked
494 together to produce the new executable editor.
495 @cindex recompilation
496 @cindex editor
498 @menu
499 * Rule Introduction::           What a rule looks like.
500 * Simple Makefile::             A simple makefile.
501 * How Make Works::              How @code{make} processes this makefile.
502 * Variables Simplify::          Variables make makefiles simpler.
503 * make Deduces::                Letting @code{make} deduce the recipes.
504 * Combine By Prerequisite::     Another style of makefile.
505 * Cleanup::                     Rules for cleaning the directory.
506 @end menu
508 @node Rule Introduction, Simple Makefile, Introduction, Introduction
509 @comment  node-name,  next,  previous,  up
510 @section What a Rule Looks Like
511 @cindex rule, introduction to
512 @cindex makefile rule parts
513 @cindex parts of makefile rule
515 A simple makefile consists of ``rules'' with the following shape:
517 @cindex targets, introduction to
518 @cindex prerequisites, introduction to
519 @cindex recipes, introduction to
520 @example
521 @group
522 @var{target} @dots{} : @var{prerequisites} @dots{}
523         @var{recipe}
524         @dots{}
525         @dots{}
526 @end group
527 @end example
529 A @dfn{target} is usually the name of a file that is generated by a
530 program; examples of targets are executable or object files.  A target
531 can also be the name of an action to carry out, such as @samp{clean}
532 (@pxref{Phony Targets}).
534 A @dfn{prerequisite} is a file that is used as input to create the
535 target.  A target often depends on several files.
537 @cindex tabs in rules
538 A @dfn{recipe} is an action that @code{make} carries out.  A recipe
539 may have more than one command, either on the same line or each on its
540 own line.  @strong{Please note:} you need to put a tab character at
541 the beginning of every recipe line!  This is an obscurity that catches
542 the unwary.  If you prefer to prefix your recipes with a character
543 other than tab, you can set the @code{.RECIPEPREFIX} variable to an
544 alternate character (@pxref{Special Variables}).
546 Usually a recipe is in a rule with prerequisites and serves to create a
547 target file if any of the prerequisites change.  However, the rule that
548 specifies a recipe for the target need not have prerequisites.  For
549 example, the rule containing the delete command associated with the
550 target @samp{clean} does not have prerequisites.
552 A @dfn{rule}, then, explains how and when to remake certain files
553 which are the targets of the particular rule.  @code{make} carries out
554 the recipe on the prerequisites to create or update the target.  A
555 rule can also explain how and when to carry out an action.
556 @xref{Rules, , Writing Rules}.
558 A makefile may contain other text besides rules, but a simple makefile
559 need only contain rules.  Rules may look somewhat more complicated
560 than shown in this template, but all fit the pattern more or less.
562 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
563 @section A Simple Makefile
564 @cindex simple makefile
565 @cindex makefile, simple
567 Here is a straightforward makefile that describes the way an
568 executable file called @code{edit} depends on eight object files
569 which, in turn, depend on eight C source and three header files.
571 In this example, all the C files include @file{defs.h}, but only those
572 defining editing commands include @file{command.h}, and only low
573 level files that change the editor buffer include @file{buffer.h}.
575 @example
576 @group
577 edit : main.o kbd.o command.o display.o \
578        insert.o search.o files.o utils.o
579         cc -o edit main.o kbd.o command.o display.o \
580                    insert.o search.o files.o utils.o
582 main.o : main.c defs.h
583         cc -c main.c
584 kbd.o : kbd.c defs.h command.h
585         cc -c kbd.c
586 command.o : command.c defs.h command.h
587         cc -c command.c
588 display.o : display.c defs.h buffer.h
589         cc -c display.c
590 insert.o : insert.c defs.h buffer.h
591         cc -c insert.c
592 search.o : search.c defs.h buffer.h
593         cc -c search.c
594 files.o : files.c defs.h buffer.h command.h
595         cc -c files.c
596 utils.o : utils.c defs.h
597         cc -c utils.c
598 clean :
599         rm edit main.o kbd.o command.o display.o \
600            insert.o search.o files.o utils.o
601 @end group
602 @end example
604 @noindent
605 We split each long line into two lines using backslash-newline; this is
606 like using one long line, but is easier to read.
607 @cindex continuation lines
608 @cindex @code{\} (backslash), for continuation lines
609 @cindex backslash (@code{\}), for continuation lines
610 @cindex quoting newline, in makefile
611 @cindex newline, quoting, in makefile
613 To use this makefile to create the executable file called @file{edit},
614 type:
616 @example
617 make
618 @end example
620 To use this makefile to delete the executable file and all the object
621 files from the directory, type:
623 @example
624 make clean
625 @end example
627 In the example makefile, the targets include the executable file
628 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
629 prerequisites are files such as @samp{main.c} and @samp{defs.h}.
630 In fact, each @samp{.o} file is both a target and a prerequisite.
631 Recipes include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
633 When a target is a file, it needs to be recompiled or relinked if any
634 of its prerequisites change.  In addition, any prerequisites that are
635 themselves automatically generated should be updated first.  In this
636 example, @file{edit} depends on each of the eight object files; the
637 object file @file{main.o} depends on the source file @file{main.c} and
638 on the header file @file{defs.h}.
640 A recipe may follow each line that contains a target and
641 prerequisites.  These recipes say how to update the target file.  A
642 tab character (or whatever character is specified by the
643 @code{.RECIPEPREFIX} variable; @pxref{Special Variables}) must come at
644 the beginning of every line in the recipe to distinguish recipes from
645 other lines in the makefile.  (Bear in mind that @code{make} does not
646 know anything about how the recipes work.  It is up to you to supply
647 recipes that will update the target file properly.  All @code{make}
648 does is execute the recipe you have specified when the target file
649 needs to be updated.)@refill
650 @cindex recipe
652 The target @samp{clean} is not a file, but merely the name of an
653 action.  Since you normally do not want to carry out the actions in
654 this rule, @samp{clean} is not a prerequisite of any other rule.
655 Consequently, @code{make} never does anything with it unless you tell
656 it specifically.  Note that this rule not only is not a prerequisite,
657 it also does not have any prerequisites, so the only purpose of the
658 rule is to run the specified recipe.  Targets that do not refer to
659 files but are just actions are called @dfn{phony targets}.
660 @xref{Phony Targets}, for information about this kind of target.
661 @xref{Errors, , Errors in Recipes}, to see how to cause @code{make}
662 to ignore errors from @code{rm} or any other command.
663 @cindex @code{clean} target
664 @cindex @code{rm} (shell command)
666 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
667 @comment  node-name,  next,  previous,  up
668 @section How @code{make} Processes a Makefile
669 @cindex processing a makefile
670 @cindex makefile, how @code{make} processes
672 By default, @code{make} starts with the first target (not targets whose
673 names start with @samp{.}).  This is called the @dfn{default goal}.
674 (@dfn{Goals} are the targets that @code{make} strives ultimately to
675 update.    You can override this behavior using the command line
676 (@pxref{Goals, , Arguments to Specify the Goals}) or with the
677 @code{.DEFAULT_GOAL} special variable (@pxref{Special Variables, ,
678 Other Special Variables}).
679 @cindex default goal
680 @cindex goal, default
681 @cindex goal
683 In the simple example of the previous section, the default goal is to
684 update the executable program @file{edit}; therefore, we put that rule
685 first.
687 Thus, when you give the command:
689 @example
690 make
691 @end example
693 @noindent
694 @code{make} reads the makefile in the current directory and begins by
695 processing the first rule.  In the example, this rule is for relinking
696 @file{edit}; but before @code{make} can fully process this rule, it
697 must process the rules for the files that @file{edit} depends on,
698 which in this case are the object files.  Each of these files is
699 processed according to its own rule.  These rules say to update each
700 @samp{.o} file by compiling its source file.  The recompilation must
701 be done if the source file, or any of the header files named as
702 prerequisites, is more recent than the object file, or if the object
703 file does not exist.
705 The other rules are processed because their targets appear as
706 prerequisites of the goal.  If some other rule is not depended on by the
707 goal (or anything it depends on, etc.), that rule is not processed,
708 unless you tell @code{make} to do so (with a command such as
709 @w{@code{make clean}}).
711 Before recompiling an object file, @code{make} considers updating its
712 prerequisites, the source file and header files.  This makefile does not
713 specify anything to be done for them---the @samp{.c} and @samp{.h} files
714 are not the targets of any rules---so @code{make} does nothing for these
715 files.  But @code{make} would update automatically generated C programs,
716 such as those made by Bison or Yacc, by their own rules at this time.
718 After recompiling whichever object files need it, @code{make} decides
719 whether to relink @file{edit}.  This must be done if the file
720 @file{edit} does not exist, or if any of the object files are newer than
721 it.  If an object file was just recompiled, it is now newer than
722 @file{edit}, so @file{edit} is relinked.
723 @cindex relinking
725 Thus, if we change the file @file{insert.c} and run @code{make},
726 @code{make} will compile that file to update @file{insert.o}, and then
727 link @file{edit}.  If we change the file @file{command.h} and run
728 @code{make}, @code{make} will recompile the object files @file{kbd.o},
729 @file{command.o} and @file{files.o} and then link the file @file{edit}.
731 @node Variables Simplify, make Deduces, How Make Works, Introduction
732 @section Variables Make Makefiles Simpler
733 @cindex variables
734 @cindex simplifying with variables
736 In our example, we had to list all the object files twice in the rule for
737 @file{edit} (repeated here):
739 @example
740 @group
741 edit : main.o kbd.o command.o display.o \
742               insert.o search.o files.o utils.o
743         cc -o edit main.o kbd.o command.o display.o \
744                    insert.o search.o files.o utils.o
745 @end group
746 @end example
748 @cindex @code{objects}
749 Such duplication is error-prone; if a new object file is added to the
750 system, we might add it to one list and forget the other.  We can eliminate
751 the risk and simplify the makefile by using a variable.  @dfn{Variables}
752 allow a text string to be defined once and substituted in multiple places
753 later (@pxref{Using Variables, ,How to Use Variables}).
755 @cindex @code{OBJECTS}
756 @cindex @code{objs}
757 @cindex @code{OBJS}
758 @cindex @code{obj}
759 @cindex @code{OBJ}
760 It is standard practice for every makefile to have a variable named
761 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
762 or @code{OBJ} which is a list of all object file names.  We would
763 define such a variable @code{objects} with a line like this in the
764 makefile:@refill
766 @example
767 @group
768 objects = main.o kbd.o command.o display.o \
769           insert.o search.o files.o utils.o
770 @end group
771 @end example
773 @noindent
774 Then, each place we want to put a list of the object file names, we can
775 substitute the variable's value by writing @samp{$(objects)}
776 (@pxref{Using Variables, ,How to Use Variables}).
778 Here is how the complete simple makefile looks when you use a variable
779 for the object files:
781 @example
782 @group
783 objects = main.o kbd.o command.o display.o \
784           insert.o search.o files.o utils.o
786 edit : $(objects)
787         cc -o edit $(objects)
788 main.o : main.c defs.h
789         cc -c main.c
790 kbd.o : kbd.c defs.h command.h
791         cc -c kbd.c
792 command.o : command.c defs.h command.h
793         cc -c command.c
794 display.o : display.c defs.h buffer.h
795         cc -c display.c
796 insert.o : insert.c defs.h buffer.h
797         cc -c insert.c
798 search.o : search.c defs.h buffer.h
799         cc -c search.c
800 files.o : files.c defs.h buffer.h command.h
801         cc -c files.c
802 utils.o : utils.c defs.h
803         cc -c utils.c
804 clean :
805         rm edit $(objects)
806 @end group
807 @end example
809 @node make Deduces, Combine By Prerequisite, Variables Simplify, Introduction
810 @section Letting @code{make} Deduce the Recipes
811 @cindex deducing recipes (implicit rules)
812 @cindex implicit rule, introduction to
813 @cindex rule, implicit, introduction to
815 It is not necessary to spell out the recipes for compiling the individual
816 C source files, because @code{make} can figure them out: it has an
817 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
818 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
819 use the recipe @samp{cc -c main.c -o main.o} to compile @file{main.c} into
820 @file{main.o}.  We can therefore omit the recipes from the rules for the
821 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.@refill
823 When a @samp{.c} file is used automatically in this way, it is also
824 automatically added to the list of prerequisites.  We can therefore omit
825 the @samp{.c} files from the prerequisites, provided we omit the recipe.
827 Here is the entire example, with both of these changes, and a variable
828 @code{objects} as suggested above:
830 @example
831 @group
832 objects = main.o kbd.o command.o display.o \
833           insert.o search.o files.o utils.o
835 edit : $(objects)
836         cc -o edit $(objects)
838 main.o : defs.h
839 kbd.o : defs.h command.h
840 command.o : defs.h command.h
841 display.o : defs.h buffer.h
842 insert.o : defs.h buffer.h
843 search.o : defs.h buffer.h
844 files.o : defs.h buffer.h command.h
845 utils.o : defs.h
847 .PHONY : clean
848 clean :
849         rm edit $(objects)
850 @end group
851 @end example
853 @noindent
854 This is how we would write the makefile in actual practice.  (The
855 complications associated with @samp{clean} are described elsewhere.
856 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Recipes}.)
858 Because implicit rules are so convenient, they are important.  You
859 will see them used frequently.@refill
861 @node Combine By Prerequisite, Cleanup, make Deduces, Introduction
862 @section Another Style of Makefile
863 @cindex combining rules by prerequisite
865 When the objects of a makefile are created only by implicit rules, an
866 alternative style of makefile is possible.  In this style of makefile,
867 you group entries by their prerequisites instead of by their targets.
868 Here is what one looks like:
870 @example
871 @group
872 objects = main.o kbd.o command.o display.o \
873           insert.o search.o files.o utils.o
875 edit : $(objects)
876         cc -o edit $(objects)
878 $(objects) : defs.h
879 kbd.o command.o files.o : command.h
880 display.o insert.o search.o files.o : buffer.h
881 @end group
882 @end example
884 @noindent
885 Here @file{defs.h} is given as a prerequisite of all the object files;
886 @file{command.h} and @file{buffer.h} are prerequisites of the specific
887 object files listed for them.
889 Whether this is better is a matter of taste: it is more compact, but some
890 people dislike it because they find it clearer to put all the information
891 about each target in one place.
893 @node Cleanup,  , Combine By Prerequisite, Introduction
894 @section Rules for Cleaning the Directory
895 @cindex cleaning up
896 @cindex removing, to clean up
898 Compiling a program is not the only thing you might want to write rules
899 for.  Makefiles commonly tell how to do a few other things besides
900 compiling a program: for example, how to delete all the object files
901 and executables so that the directory is @samp{clean}.
903 @cindex @code{clean} target
904 Here is how we
905 could write a @code{make} rule for cleaning our example editor:
907 @example
908 @group
909 clean:
910         rm edit $(objects)
911 @end group
912 @end example
914 In practice, we might want to write the rule in a somewhat more
915 complicated manner to handle unanticipated situations.  We would do this:
917 @example
918 @group
919 .PHONY : clean
920 clean :
921         -rm edit $(objects)
922 @end group
923 @end example
925 @noindent
926 This prevents @code{make} from getting confused by an actual file
927 called @file{clean} and causes it to continue in spite of errors from
928 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
929 Recipes}.)
931 @noindent
932 A rule such as this should not be placed at the beginning of the
933 makefile, because we do not want it to run by default!  Thus, in the
934 example makefile, we want the rule for @code{edit}, which recompiles
935 the editor, to remain the default goal.
937 Since @code{clean} is not a prerequisite of @code{edit}, this rule will not
938 run at all if we give the command @samp{make} with no arguments.  In
939 order to make the rule run, we have to type @samp{make clean}.
940 @xref{Running, ,How to Run @code{make}}.
942 @node Makefiles, Rules, Introduction, Top
943 @chapter Writing Makefiles
945 @cindex makefile, how to write
946 The information that tells @code{make} how to recompile a system comes from
947 reading a data base called the @dfn{makefile}.
949 @menu
950 * Makefile Contents::           What makefiles contain.
951 * Makefile Names::              How to name your makefile.
952 * Include::                     How one makefile can use another makefile.
953 * MAKEFILES Variable::          The environment can specify extra makefiles.
954 * Remaking Makefiles::          How makefiles get remade.
955 * Overriding Makefiles::        How to override part of one makefile
956                                   with another makefile.
957 * Reading Makefiles::           How makefiles are parsed.
958 * Secondary Expansion::         How and when secondary expansion is performed.
959 @end menu
961 @node Makefile Contents, Makefile Names, Makefiles, Makefiles
962 @section What Makefiles Contain
964 Makefiles contain five kinds of things: @dfn{explicit rules},
965 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
966 and @dfn{comments}.  Rules, variables, and directives are described at
967 length in later chapters.@refill
969 @itemize @bullet
970 @cindex rule, explicit, definition of
971 @cindex explicit rule, definition of
972 @item
973 An @dfn{explicit rule} says when and how to remake one or more files,
974 called the rule's @dfn{targets}.  It lists the other files that the
975 targets depend on, called the @dfn{prerequisites} of the target, and
976 may also give a recipe to use to create or update the targets.
977 @xref{Rules, ,Writing Rules}.
979 @cindex rule, implicit, definition of
980 @cindex implicit rule, definition of
981 @item
982 An @dfn{implicit rule} says when and how to remake a class of files
983 based on their names.  It describes how a target may depend on a file
984 with a name similar to the target and gives a recipe to create or
985 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
987 @cindex variable definition
988 @item
989 A @dfn{variable definition} is a line that specifies a text string
990 value for a variable that can be substituted into the text later.  The
991 simple makefile example shows a variable definition for @code{objects}
992 as a list of all object files (@pxref{Variables Simplify, , Variables
993 Make Makefiles Simpler}).
995 @cindex directive
996 @item
997 A @dfn{directive} is an instruction for @code{make} to do something
998 special while reading the makefile.  These include:
1000 @itemize @bullet
1001 @item
1002 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
1004 @item
1005 Deciding (based on the values of variables) whether to use or
1006 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
1008 @item
1009 Defining a variable from a verbatim string containing multiple lines
1010 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).
1011 @end itemize
1013 @cindex comments, in makefile
1014 @cindex @code{#} (comments), in makefile
1015 @item
1016 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the
1017 rest of the line are ignored, except that a trailing backslash not
1018 escaped by another backslash will continue the comment across multiple
1019 lines.  A line containing just a comment (with perhaps spaces before
1020 it) is effectively blank, and is ignored.  If you want a literal
1021 @code{#}, escape it with a backslash (e.g., @code{\#}).  Comments may
1022 appear on any line in the makefile, although they are treated
1023 specially in certain situations.
1025 You cannot use comments within variable references or function calls:
1026 any instance of @code{#} will be treated literally (rather than as the
1027 start of a comment) inside a variable reference or function call.
1029 Comments within a recipe are passed to the shell, just as with any
1030 other recipe text.  The shell decides how to interpret it: whether or
1031 not this is a comment is up to the shell.
1033 Within a @code{define} directive, comments are not ignored during the
1034 definition of the variable, but rather kept intact in the value of the
1035 variable.  When the variable is expanded they will either be treated
1036 as @code{make} comments or as recipe text, depending on the context in
1037 which the variable is evaluated.
1038 @end itemize
1040 @node Makefile Names, Include, Makefile Contents, Makefiles
1041 @section What Name to Give Your Makefile
1042 @cindex makefile name
1043 @cindex name of makefile
1044 @cindex default makefile name
1045 @cindex file name of makefile
1047 @c following paragraph rewritten to avoid overfull hbox
1048 By default, when @code{make} looks for the makefile, it tries the
1049 following names, in order: @file{GNUmakefile}, @file{makefile}
1050 and @file{Makefile}.@refill
1051 @findex Makefile
1052 @findex GNUmakefile
1053 @findex makefile
1055 @cindex @code{README}
1056 Normally you should call your makefile either @file{makefile} or
1057 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1058 prominently near the beginning of a directory listing, right near other
1059 important files such as @file{README}.)  The first name checked,
1060 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1061 use this name if you have a makefile that is specific to GNU
1062 @code{make}, and will not be understood by other versions of
1063 @code{make}.  Other @code{make} programs look for @file{makefile} and
1064 @file{Makefile}, but not @file{GNUmakefile}.
1066 If @code{make} finds none of these names, it does not use any makefile.
1067 Then you must specify a goal with a command argument, and @code{make}
1068 will attempt to figure out how to remake it using only its built-in
1069 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1071 @cindex @code{-f}
1072 @cindex @code{--file}
1073 @cindex @code{--makefile}
1074 If you want to use a nonstandard name for your makefile, you can specify
1075 the makefile name with the @samp{-f} or @samp{--file} option.  The
1076 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1077 @code{make} to read the file @var{name} as the makefile.  If you use
1078 more than one @samp{-f} or @samp{--file} option, you can specify several
1079 makefiles.  All the makefiles are effectively concatenated in the order
1080 specified.  The default makefile names @file{GNUmakefile},
1081 @file{makefile} and @file{Makefile} are not checked automatically if you
1082 specify @samp{-f} or @samp{--file}.@refill
1083 @cindex specifying makefile name
1084 @cindex makefile name, how to specify
1085 @cindex name of makefile, how to specify
1086 @cindex file name of makefile, how to specify
1088 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1089 @section Including Other Makefiles
1090 @cindex including other makefiles
1091 @cindex makefile, including
1093 @findex include
1094 The @code{include} directive tells @code{make} to suspend reading the
1095 current makefile and read one or more other makefiles before continuing.
1096 The directive is a line in the makefile that looks like this:
1098 @example
1099 include @var{filenames}@dots{}
1100 @end example
1102 @noindent
1103 @var{filenames} can contain shell file name patterns.  If
1104 @var{filenames} is empty, nothing is included and no error is printed.
1105 @cindex shell file name pattern (in @code{include})
1106 @cindex shell wildcards (in @code{include})
1107 @cindex wildcard, in @code{include}
1109 Extra spaces are allowed and ignored at the beginning of the line, but
1110 the first character must not be a tab (or the value of
1111 @code{.RECIPEPREFIX})---if the line begins with a tab, it will be
1112 considered a recipe line.  Whitespace is required between
1113 @code{include} and the file names, and between file names; extra
1114 whitespace is ignored there and at the end of the directive.  A
1115 comment starting with @samp{#} is allowed at the end of the line.  If
1116 the file names contain any variable or function references, they are
1117 expanded.  @xref{Using Variables, ,How to Use Variables}.
1119 For example, if you have three @file{.mk} files, @file{a.mk},
1120 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1121 @code{bish bash}, then the following expression
1123 @example
1124 include foo *.mk $(bar)
1125 @end example
1127 is equivalent to
1129 @example
1130 include foo a.mk b.mk c.mk bish bash
1131 @end example
1133 When @code{make} processes an @code{include} directive, it suspends
1134 reading of the containing makefile and reads from each listed file in
1135 turn.  When that is finished, @code{make} resumes reading the
1136 makefile in which the directive appears.
1138 One occasion for using @code{include} directives is when several programs,
1139 handled by individual makefiles in various directories, need to use a
1140 common set of variable definitions
1141 (@pxref{Setting, ,Setting Variables}) or pattern rules
1142 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1144 Another such occasion is when you want to generate prerequisites from
1145 source files automatically; the prerequisites can be put in a file that
1146 is included by the main makefile.  This practice is generally cleaner
1147 than that of somehow appending the prerequisites to the end of the main
1148 makefile as has been traditionally done with other versions of
1149 @code{make}.  @xref{Automatic Prerequisites}.
1150 @cindex prerequisites, automatic generation
1151 @cindex automatic generation of prerequisites
1152 @cindex generating prerequisites automatically
1154 @cindex @code{-I}
1155 @cindex @code{--include-dir}
1156 @cindex included makefiles, default directories
1157 @cindex default directories for included makefiles
1158 @findex /usr/gnu/include
1159 @findex /usr/local/include
1160 @findex /usr/include
1161 If the specified name does not start with a slash, and the file is not
1162 found in the current directory, several other directories are searched.
1163 First, any directories you have specified with the @samp{-I} or
1164 @samp{--include-dir} option are searched
1165 (@pxref{Options Summary, ,Summary of Options}).
1166 Then the following directories (if they exist)
1167 are searched, in this order:
1168 @file{@var{prefix}/include} (normally @file{/usr/local/include}
1169 @footnote{GNU Make compiled for MS-DOS and MS-Windows behaves as if
1170 @var{prefix} has been defined to be the root of the DJGPP tree
1171 hierarchy.})
1172 @file{/usr/gnu/include},
1173 @file{/usr/local/include}, @file{/usr/include}.
1175 If an included makefile cannot be found in any of these directories, a
1176 warning message is generated, but it is not an immediately fatal error;
1177 processing of the makefile containing the @code{include} continues.
1178 Once it has finished reading makefiles, @code{make} will try to remake
1179 any that are out of date or don't exist.
1180 @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
1181 Only after it has tried to find a way to remake a makefile and failed,
1182 will @code{make} diagnose the missing makefile as a fatal error.
1184 If you want @code{make} to simply ignore a makefile which does not exist
1185 or cannot be remade, with no error message, use the @w{@code{-include}}
1186 directive instead of @code{include}, like this:
1188 @example
1189 -include @var{filenames}@dots{}
1190 @end example
1192 This acts like @code{include} in every way except that there is no
1193 error (not even a warning) if any of the @var{filenames} (or any
1194 prerequisites of any of the @var{filenames}) do not exist or cannot be
1195 remade.
1197 For compatibility with some other @code{make} implementations,
1198 @code{sinclude} is another name for @w{@code{-include}}.
1200 @node MAKEFILES Variable, Remaking Makefiles, Include, Makefiles
1201 @section The Variable @code{MAKEFILES}
1202 @cindex makefile, and @code{MAKEFILES} variable
1203 @cindex including (@code{MAKEFILES} variable)
1205 @vindex MAKEFILES
1206 If the environment variable @code{MAKEFILES} is defined, @code{make}
1207 considers its value as a list of names (separated by whitespace) of
1208 additional makefiles to be read before the others.  This works much
1209 like the @code{include} directive: various directories are searched
1210 for those files (@pxref{Include, ,Including Other Makefiles}).  In
1211 addition, the default goal is never taken from one of these makefiles
1212 (or any makefile included by them) and it is not an error if the files
1213 listed in @code{MAKEFILES} are not found.@refill
1215 @cindex recursion, and @code{MAKEFILES} variable
1216 The main use of @code{MAKEFILES} is in communication between recursive
1217 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1218 @code{make}}).  It usually is not desirable to set the environment
1219 variable before a top-level invocation of @code{make}, because it is
1220 usually better not to mess with a makefile from outside.  However, if
1221 you are running @code{make} without a specific makefile, a makefile in
1222 @code{MAKEFILES} can do useful things to help the built-in implicit
1223 rules work better, such as defining search paths (@pxref{Directory Search}).
1225 Some users are tempted to set @code{MAKEFILES} in the environment
1226 automatically on login, and program makefiles to expect this to be done.
1227 This is a very bad idea, because such makefiles will fail to work if run by
1228 anyone else.  It is much better to write explicit @code{include} directives
1229 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1231 @node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
1232 @section How Makefiles Are Remade
1234 @cindex updating makefiles
1235 @cindex remaking makefiles
1236 @cindex makefile, remaking of
1237 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1238 files.  If a makefile can be remade from other files, you probably want
1239 @code{make} to get an up-to-date version of the makefile to read in.
1241 To this end, after reading in all makefiles, @code{make} will consider
1242 each as a goal target and attempt to update it.  If a makefile has a
1243 rule which says how to update it (found either in that very makefile or
1244 in another one) or if an implicit rule applies to it (@pxref{Implicit
1245 Rules, ,Using Implicit Rules}), it will be updated if necessary.  After
1246 all makefiles have been checked, if any have actually been changed,
1247 @code{make} starts with a clean slate and reads all the makefiles over
1248 again.  (It will also attempt to update each of them over again, but
1249 normally this will not change them again, since they are already up to
1250 date.)@refill
1252 If you know that one or more of your makefiles cannot be remade and
1253 you want to keep @code{make} from performing an implicit rule search
1254 on them, perhaps for efficiency reasons, you can use any normal method
1255 of preventing implicit rule look-up to do so.  For example, you can
1256 write an explicit rule with the makefile as the target, and an empty
1257 recipe (@pxref{Empty Recipes, ,Using Empty Recipes}).
1259 If the makefiles specify a double-colon rule to remake a file with
1260 a recipe but no prerequisites, that file will always be remade
1261 (@pxref{Double-Colon}).  In the case of makefiles, a makefile that has a
1262 double-colon rule with a recipe but no prerequisites will be remade every
1263 time @code{make} is run, and then again after @code{make} starts over
1264 and reads the makefiles in again.  This would cause an infinite loop:
1265 @code{make} would constantly remake the makefile, and never do anything
1266 else.  So, to avoid this, @code{make} will @strong{not} attempt to
1267 remake makefiles which are specified as targets of a double-colon rule
1268 with a recipe but no prerequisites.@refill
1270 If you do not specify any makefiles to be read with @samp{-f} or
1271 @samp{--file} options, @code{make} will try the default makefile names;
1272 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1273 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1274 @code{make} is not certain that these makefiles should exist.  However,
1275 if a default makefile does not exist but can be created by running
1276 @code{make} rules, you probably want the rules to be run so that the
1277 makefile can be used.
1279 Therefore, if none of the default makefiles exists, @code{make} will try
1280 to make each of them in the same order in which they are searched for
1281 (@pxref{Makefile Names, ,What Name to Give Your Makefile})
1282 until it succeeds in making one, or it runs out of names to try.  Note
1283 that it is not an error if @code{make} cannot find or make any makefile;
1284 a makefile is not always necessary.@refill
1286 When you use the @samp{-t} or @samp{--touch} option
1287 (@pxref{Instead of Execution, ,Instead of Executing Recipes}),
1288 you would not want to use an out-of-date makefile to decide which
1289 targets to touch.  So the @samp{-t} option has no effect on updating
1290 makefiles; they are really updated even if @samp{-t} is specified.
1291 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1292 @samp{--just-print}) do not prevent updating of makefiles, because an
1293 out-of-date makefile would result in the wrong output for other targets.
1294 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1295 and then print the recipe to update @file{foo} and its prerequisites
1296 without running it.  The recipe printed for @file{foo} will be the one
1297 specified in the updated contents of @file{mfile}.
1299 However, on occasion you might actually wish to prevent updating of even
1300 the makefiles.  You can do this by specifying the makefiles as goals in
1301 the command line as well as specifying them as makefiles.  When the
1302 makefile name is specified explicitly as a goal, the options @samp{-t}
1303 and so on do apply to them.
1305 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1306 @file{mfile}, print the recipe needed to update it without actually
1307 running it, and then print the recipe needed to update @file{foo}
1308 without running that.  The recipe for @file{foo} will be the one
1309 specified by the existing contents of @file{mfile}.
1311 @node Overriding Makefiles, Reading Makefiles, Remaking Makefiles, Makefiles
1312 @section Overriding Part of Another Makefile
1314 @cindex overriding makefiles
1315 @cindex makefile, overriding
1316 Sometimes it is useful to have a makefile that is mostly just like
1317 another makefile.  You can often use the @samp{include} directive to
1318 include one in the other, and add more targets or variable definitions.
1319 However, it is invalid for two makefiles to give different recipes for
1320 the same target.  But there is another way.
1322 @cindex match-anything rule, used to override
1323 In the containing makefile (the one that wants to include the other),
1324 you can use a match-anything pattern rule to say that to remake any
1325 target that cannot be made from the information in the containing
1326 makefile, @code{make} should look in another makefile.
1327 @xref{Pattern Rules}, for more information on pattern rules.
1329 For example, if you have a makefile called @file{Makefile} that says how
1330 to make the target @samp{foo} (and other targets), you can write a
1331 makefile called @file{GNUmakefile} that contains:
1333 @example
1334 foo:
1335         frobnicate > foo
1337 %: force
1338         @@$(MAKE) -f Makefile $@@
1339 force: ;
1340 @end example
1342 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1343 read it, and see that to make @file{foo}, it needs to run the recipe
1344 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1345 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1346 recipe from the pattern rule: @samp{make -f Makefile bar}.  If
1347 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1348 will apply the rule.  And likewise for any other target that
1349 @file{GNUmakefile} does not say how to make.
1351 The way this works is that the pattern rule has a pattern of just
1352 @samp{%}, so it matches any target whatever.  The rule specifies a
1353 prerequisite @file{force}, to guarantee that the recipe will be run even
1354 if the target file already exists.  We give the @file{force} target an
1355 empty recipe to prevent @code{make} from searching for an implicit rule to
1356 build it---otherwise it would apply the same match-anything rule to
1357 @file{force} itself and create a prerequisite loop!
1359 @node Reading Makefiles,  Secondary Expansion, Overriding Makefiles, Makefiles
1360 @section How @code{make} Reads a Makefile
1361 @cindex reading makefiles
1362 @cindex makefile, parsing
1364 GNU @code{make} does its work in two distinct phases.  During the first
1365 phase it reads all the makefiles, included makefiles, etc. and
1366 internalizes all the variables and their values, implicit and explicit
1367 rules, and constructs a dependency graph of all the targets and their
1368 prerequisites.  During the second phase, @code{make} uses these internal
1369 structures to determine what targets will need to be rebuilt and to
1370 invoke the rules necessary to do so.
1372 It's important to understand this two-phase approach because it has a
1373 direct impact on how variable and function expansion happens; this is
1374 often a source of some confusion when writing makefiles.  Here we will
1375 present a summary of the phases in which expansion happens for different
1376 constructs within the makefile.  We say that expansion is
1377 @dfn{immediate} if it happens during the first phase: in this case
1378 @code{make} will expand any variables or functions in that section of a
1379 construct as the makefile is parsed.  We say that expansion is
1380 @dfn{deferred} if expansion is not performed immediately.  Expansion of
1381 a deferred construct is not performed until either the construct appears
1382 later in an immediate context, or until the second phase.
1384 You may not be familiar with some of these constructs yet.  You can
1385 reference this section as you become familiar with them, in later
1386 chapters.
1388 @subheading Variable Assignment
1389 @cindex +=, expansion
1390 @cindex =, expansion
1391 @cindex ?=, expansion
1392 @cindex +=, expansion
1393 @cindex !=, expansion
1394 @cindex define, expansion
1396 Variable definitions are parsed as follows:
1398 @example
1399 @var{immediate} = @var{deferred}
1400 @var{immediate} ?= @var{deferred}
1401 @var{immediate} := @var{immediate}
1402 @var{immediate} += @var{deferred} or @var{immediate}
1403 @var{immediate} != @var{immediate}
1405 define @var{immediate}
1406   @var{deferred}
1407 endef
1409 define @var{immediate} =
1410   @var{deferred}
1411 endef
1413 define @var{immediate} ?=
1414   @var{deferred}
1415 endef
1417 define @var{immediate} :=
1418   @var{immediate}
1419 endef
1421 define @var{immediate} +=
1422   @var{deferred} or @var{immediate}
1423 endef
1425 define @var{immediate} !=
1426   @var{immediate}
1427 endef
1428 @end example
1430 For the append operator, @samp{+=}, the right-hand side is considered
1431 immediate if the variable was previously set as a simple variable
1432 (@samp{:=}), and deferred otherwise.
1434 For the shell assignment operator, @samp{!=}, the right-hand side is
1435 evaluated immediately and handed to the shell.  The result is stored in the
1436 variable named on the left, and that variable becomes a simple variable
1437 (and will thus be re-evaluated on each reference).
1439 @subheading Conditional Directives
1440 @cindex ifdef, expansion
1441 @cindex ifeq, expansion
1442 @cindex ifndef, expansion
1443 @cindex ifneq, expansion
1445 Conditional directives are parsed immediately.  This means, for
1446 example, that automatic variables cannot be used in conditional
1447 directives, as automatic variables are not set until the recipe for
1448 that rule is invoked.  If you need to use automatic variables in a
1449 conditional directive you @emph{must} move the condition into the
1450 recipe and use shell conditional syntax instead.
1452 @subheading Rule Definition
1453 @cindex target, expansion
1454 @cindex prerequisite, expansion
1455 @cindex implicit rule, expansion
1456 @cindex pattern rule, expansion
1457 @cindex explicit rule, expansion
1459 A rule is always expanded the same way, regardless of the form:
1461 @example
1462 @var{immediate} : @var{immediate} ; @var{deferred}
1463         @var{deferred}
1464 @end example
1466 That is, the target and prerequisite sections are expanded immediately,
1467 and the recipe used to construct the target is always deferred.  This
1468 general rule is true for explicit rules, pattern rules, suffix rules,
1469 static pattern rules, and simple prerequisite definitions.
1471 @node Secondary Expansion, , Reading Makefiles, Makefiles
1472 @section Secondary Expansion
1473 @cindex secondary expansion
1474 @cindex expansion, secondary
1476 @findex .SECONDEXPANSION
1477 In the previous section we learned that GNU @code{make} works in two
1478 distinct phases: a read-in phase and a target-update phase
1479 (@pxref{Reading Makefiles, , How @code{make} Reads a Makefile}).  GNU
1480 make also has the ability to enable a @emph{second expansion} of the
1481 prerequisites (only) for some or all targets defined in the makefile.
1482 In order for this second expansion to occur, the special target
1483 @code{.SECONDEXPANSION} must be defined before the first prerequisite
1484 list that makes use of this feature.
1486 If that special target is defined then in between the two phases
1487 mentioned above, right at the end of the read-in phase, all the
1488 prerequisites of the targets defined after the special target are
1489 expanded a @emph{second time}.  In most circumstances this secondary
1490 expansion will have no effect, since all variable and function
1491 references will have been expanded during the initial parsing of the
1492 makefiles.  In order to take advantage of the secondary expansion
1493 phase of the parser, then, it's necessary to @emph{escape} the
1494 variable or function reference in the makefile.  In this case the
1495 first expansion merely un-escapes the reference but doesn't expand it,
1496 and expansion is left to the secondary expansion phase.  For example,
1497 consider this makefile:
1499 @example
1500 .SECONDEXPANSION:
1501 ONEVAR = onefile
1502 TWOVAR = twofile
1503 myfile: $(ONEVAR) $$(TWOVAR)
1504 @end example
1506 After the first expansion phase the prerequisites list of the
1507 @file{myfile} target will be @code{onefile} and @code{$(TWOVAR)}; the
1508 first (unescaped) variable reference to @var{ONEVAR} is expanded,
1509 while the second (escaped) variable reference is simply unescaped,
1510 without being recognized as a variable reference.  Now during the
1511 secondary expansion the first word is expanded again but since it
1512 contains no variable or function references it remains the value
1513 @file{onefile}, while the second word is now a normal reference to the
1514 variable @var{TWOVAR}, which is expanded to the value @file{twofile}.
1515 The final result is that there are two prerequisites, @file{onefile}
1516 and @file{twofile}.
1518 Obviously, this is not a very interesting case since the same result
1519 could more easily have been achieved simply by having both variables
1520 appear, unescaped, in the prerequisites list.  One difference becomes
1521 apparent if the variables are reset; consider this example:
1523 @example
1524 .SECONDEXPANSION:
1525 AVAR = top
1526 onefile: $(AVAR)
1527 twofile: $$(AVAR)
1528 AVAR = bottom
1529 @end example
1531 Here the prerequisite of @file{onefile} will be expanded immediately,
1532 and resolve to the value @file{top}, while the prerequisite of
1533 @file{twofile} will not be full expanded until the secondary expansion
1534 and yield a value of @file{bottom}.
1536 This is marginally more exciting, but the true power of this feature
1537 only becomes apparent when you discover that secondary expansions
1538 always take place within the scope of the automatic variables for that
1539 target.  This means that you can use variables such as @code{$@@},
1540 @code{$*}, etc. during the second expansion and they will have their
1541 expected values, just as in the recipe.  All you have to do is defer
1542 the expansion by escaping the @code{$}.  Also, secondary expansion
1543 occurs for both explicit and implicit (pattern) rules.  Knowing this,
1544 the possible uses for this feature increase dramatically.  For
1545 example:
1547 @example
1548 .SECONDEXPANSION:
1549 main_OBJS := main.o try.o test.o
1550 lib_OBJS := lib.o api.o
1552 main lib: $$($$@@_OBJS)
1553 @end example
1555 Here, after the initial expansion the prerequisites of both the
1556 @file{main} and @file{lib} targets will be @code{$($@@_OBJS)}.  During
1557 the secondary expansion, the @code{$@@} variable is set to the name of
1558 the target and so the expansion for the @file{main} target will yield
1559 @code{$(main_OBJS)}, or @code{main.o try.o test.o}, while the
1560 secondary expansion for the @file{lib} target will yield
1561 @code{$(lib_OBJS)}, or @code{lib.o api.o}.
1563 You can also mix in functions here, as long as they are properly escaped:
1565 @example
1566 main_SRCS := main.c try.c test.c
1567 lib_SRCS := lib.c api.c
1569 .SECONDEXPANSION:
1570 main lib: $$(patsubst %.c,%.o,$$($$@@_SRCS))
1571 @end example
1573 This version allows users to specify source files rather than object
1574 files, but gives the same resulting prerequisites list as the previous
1575 example.
1577 Evaluation of automatic variables during the secondary expansion
1578 phase, especially of the target name variable @code{$$@@}, behaves
1579 similarly to evaluation within recipes.  However, there are some
1580 subtle differences and ``corner cases'' which come into play for the
1581 different types of rule definitions that @code{make} understands.  The
1582 subtleties of using the different automatic variables are described
1583 below.
1585 @subheading Secondary Expansion of Explicit Rules
1586 @cindex secondary expansion and explicit rules
1587 @cindex explicit rules, secondary expansion of
1589 During the secondary expansion of explicit rules, @code{$$@@} and
1590 @code{$$%} evaluate, respectively, to the file name of the target and,
1591 when the target is an archive member, the target member name.  The
1592 @code{$$<} variable evaluates to the first prerequisite in the first
1593 rule for this target.  @code{$$^} and @code{$$+} evaluate to the list
1594 of all prerequisites of rules @emph{that have already appeared} for
1595 the same target (@code{$$+} with repetitions and @code{$$^}
1596 without).  The following example will help illustrate these behaviors:
1598 @example
1599 .SECONDEXPANSION:
1601 foo: foo.1 bar.1 $$< $$^ $$+    # line #1
1603 foo: foo.2 bar.2 $$< $$^ $$+    # line #2
1605 foo: foo.3 bar.3 $$< $$^ $$+    # line #3
1606 @end example
1608 In the first prerequisite list, all three variables (@code{$$<},
1609 @code{$$^}, and @code{$$+}) expand to the empty string.  In the
1610 second, they will have values @code{foo.1}, @code{foo.1 bar.1}, and
1611 @code{foo.1 bar.1} respectively.  In the third they will have values
1612 @code{foo.1}, @code{foo.1 bar.1 foo.2 bar.2}, and @code{foo.1 bar.1
1613 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1} respectively.
1615 Rules undergo secondary expansion in makefile order, except that
1616 the rule with the recipe is always evaluated last.
1618 The variables @code{$$?} and @code{$$*} are not available and expand
1619 to the empty string.
1621 @subheading Secondary Expansion of Static Pattern Rules
1622 @cindex secondary expansion and static pattern rules
1623 @cindex static pattern rules, secondary expansion of
1625 Rules for secondary expansion of static pattern rules are identical to
1626 those for explicit rules, above, with one exception: for static
1627 pattern rules the @code{$$*} variable is set to the pattern stem.  As
1628 with explicit rules, @code{$$?} is not available and expands to the
1629 empty string.
1631 @subheading Secondary Expansion of Implicit Rules
1632 @cindex secondary expansion and implicit rules
1633 @cindex implicit rules, secondary expansion of
1635 As @code{make} searches for an implicit rule, it substitutes the stem
1636 and then performs secondary expansion for every rule with a matching
1637 target pattern.  The value of the automatic variables is derived in
1638 the same fashion as for static pattern rules.  As an example:
1640 @example
1641 .SECONDEXPANSION:
1643 foo: bar
1645 foo foz: fo%: bo%
1647 %oo: $$< $$^ $$+ $$*
1648 @end example
1650 When the implicit rule is tried for target @file{foo}, @code{$$<}
1651 expands to @file{bar}, @code{$$^} expands to @file{bar boo},
1652 @code{$$+} also expands to @file{bar boo}, and @code{$$*} expands to
1653 @file{f}.
1655 Note that the directory prefix (D), as described in @ref{Implicit Rule
1656 Search, ,Implicit Rule Search Algorithm}, is appended (after
1657 expansion) to all the patterns in the prerequisites list.  As an
1658 example:@refill
1660 @example
1661 .SECONDEXPANSION:
1663 /tmp/foo.o:
1665 %.o: $$(addsuffix /%.c,foo bar) foo.h
1666         @@echo $^
1667 @end example
1669 The prerequisite list printed, after the secondary expansion and
1670 directory prefix reconstruction, will be @file{/tmp/foo/foo.c
1671 /tmp/bar/foo.c foo.h}.  If you are not interested in this
1672 reconstruction, you can use @code{$$*} instead of @code{%} in the
1673 prerequisites list.
1675 @node Rules, Recipes, Makefiles, Top
1676 @chapter Writing Rules
1677 @cindex writing rules
1678 @cindex rule, how to write
1679 @cindex target
1680 @cindex prerequisite
1682 A @dfn{rule} appears in the makefile and says when and how to remake
1683 certain files, called the rule's @dfn{targets} (most often only one per rule).
1684 It lists the other files that are the @dfn{prerequisites} of the target, and
1685 the @dfn{recipe} to use to create or update the target.
1687 @cindex default goal
1688 @cindex goal, default
1689 The order of rules is not significant, except for determining the
1690 @dfn{default goal}: the target for @code{make} to consider, if you do
1691 not otherwise specify one.  The default goal is the target of the first
1692 rule in the first makefile.  If the first rule has multiple targets,
1693 only the first target is taken as the default.  There are two
1694 exceptions: a target starting with a period is not a default unless it
1695 contains one or more slashes, @samp{/}, as well; and, a target that
1696 defines a pattern rule has no effect on the default goal.
1697 (@xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.)
1699 Therefore, we usually write the makefile so that the first rule is the
1700 one for compiling the entire program or all the programs described by
1701 the makefile (often with a target called @samp{all}).
1702 @xref{Goals, ,Arguments to Specify the Goals}.
1704 @menu
1705 * Rule Example::                An example explained.
1706 * Rule Syntax::                 General syntax explained.
1707 * Prerequisite Types::          There are two types of prerequisites.
1708 * Wildcards::                   Using wildcard characters such as `*'.
1709 * Directory Search::            Searching other directories for source files.
1710 * Phony Targets::               Using a target that is not a real file's name.
1711 * Force Targets::               You can use a target without a recipe
1712                                   or prerequisites to mark other targets
1713                                   as phony.
1714 * Empty Targets::               When only the date matters and the
1715                                   files are empty.
1716 * Special Targets::             Targets with special built-in meanings.
1717 * Multiple Targets::            When to make use of several targets in a rule.
1718 * Multiple Rules::              How to use several rules with the same target.
1719 * Static Pattern::              Static pattern rules apply to multiple targets
1720                                   and can vary the prerequisites according to
1721                                   the target name.
1722 * Double-Colon::                How to use a special kind of rule to allow
1723                                   several independent rules for one target.
1724 * Automatic Prerequisites::     How to automatically generate rules giving
1725                                   prerequisites from source files themselves.
1726 @end menu
1728 @ifnottex
1729 @node Rule Example, Rule Syntax, Rules, Rules
1730 @section Rule Example
1732 Here is an example of a rule:
1734 @example
1735 foo.o : foo.c defs.h       # module for twiddling the frobs
1736         cc -c -g foo.c
1737 @end example
1739 Its target is @file{foo.o} and its prerequisites are @file{foo.c} and
1740 @file{defs.h}.  It has one command in the recipe: @samp{cc -c -g foo.c}.
1741 The recipe starts with a tab to identify it as a recipe.
1743 This rule says two things:
1745 @itemize @bullet
1746 @item
1747 How to decide whether @file{foo.o} is out of date: it is out of date
1748 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1749 more recent than it.
1751 @item
1752 How to update the file @file{foo.o}: by running @code{cc} as stated.
1753 The recipe does not explicitly mention @file{defs.h}, but we presume
1754 that @file{foo.c} includes it, and that that is why @file{defs.h} was
1755 added to the prerequisites.
1756 @end itemize
1757 @end ifnottex
1759 @node Rule Syntax, Prerequisite Types, Rule Example, Rules
1760 @section Rule Syntax
1762 @cindex rule syntax
1763 @cindex syntax of rules
1764 In general, a rule looks like this:
1766 @example
1767 @var{targets} : @var{prerequisites}
1768         @var{recipe}
1769         @dots{}
1770 @end example
1772 @noindent
1773 or like this:
1775 @example
1776 @var{targets} : @var{prerequisites} ; @var{recipe}
1777         @var{recipe}
1778         @dots{}
1779 @end example
1781 @cindex targets
1782 @cindex rule targets
1783 The @var{targets} are file names, separated by spaces.  Wildcard
1784 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
1785 in File Names}) and a name of the form @file{@var{a}(@var{m})}
1786 represents member @var{m} in archive file @var{a}
1787 (@pxref{Archive Members, ,Archive Members as Targets}).
1788 Usually there is only one
1789 target per rule, but occasionally there is a reason to have more
1790 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).@refill
1792 @cindex recipes
1793 @cindex tab character (in commands)
1794 The @var{recipe} lines start with a tab character (or the first
1795 character in the value of the @code{.RECIPEPREFIX} variable;
1796 @pxref{Special Variables}).  The first recipe line may appear on the line
1797 after the prerequisites, with a tab character, or may appear on the
1798 same line, with a semicolon.  Either way, the effect is the same.
1799 There are other differences in the syntax of recipes.
1800 @xref{Recipes, ,Writing Recipes in Rules}.
1802 @cindex dollar sign (@code{$}), in rules
1803 @cindex @code{$}, in rules
1804 @cindex rules, and @code{$}
1805 Because dollar signs are used to start @code{make} variable
1806 references, if you really want a dollar sign in a target or
1807 prerequisite you must write two of them, @samp{$$} (@pxref{Using
1808 Variables, ,How to Use Variables}).  If you have enabled secondary
1809 expansion (@pxref{Secondary Expansion}) and you want a literal dollar
1810 sign in the prerequisites list, you must actually write @emph{four}
1811 dollar signs (@samp{$$$$}).
1813 You may split a long line by inserting a backslash followed by a
1814 newline, but this is not required, as @code{make} places no limit on
1815 the length of a line in a makefile.
1817 A rule tells @code{make} two things: when the targets are out of date,
1818 and how to update them when necessary.
1820 @cindex prerequisites
1821 @cindex rule prerequisites
1822 The criterion for being out of date is specified in terms of the
1823 @var{prerequisites}, which consist of file names separated by spaces.
1824 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
1825 A target is out of date if it does not exist or if it is older than any
1826 of the prerequisites (by comparison of last-modification times).  The
1827 idea is that the contents of the target file are computed based on
1828 information in the prerequisites, so if any of the prerequisites changes,
1829 the contents of the existing target file are no longer necessarily
1830 valid.
1832 How to update is specified by a @var{recipe}.  This is one or more
1833 lines to be executed by the shell (normally @samp{sh}), but with some
1834 extra features (@pxref{Recipes, ,Writing Recipes in Rules}).
1836 @node Prerequisite Types, Wildcards, Rule Syntax, Rules
1837 @comment  node-name,  next,  previous,  up
1838 @section Types of Prerequisites
1839 @cindex prerequisite types
1840 @cindex types of prerequisites
1842 @cindex prerequisites, normal
1843 @cindex normal prerequisites
1844 @cindex prerequisites, order-only
1845 @cindex order-only prerequisites
1846 There are actually two different types of prerequisites understood by
1847 GNU @code{make}: normal prerequisites such as described in the
1848 previous section, and @dfn{order-only} prerequisites.  A normal
1849 prerequisite makes two statements: first, it imposes an order in which
1850 recipes will be invoked: the recipes for all prerequisites of a target
1851 will be completed before the recipe for the target is run.  Second, it
1852 imposes a dependency relationship: if any prerequisite is newer than
1853 the target, then the target is considered out-of-date and must be
1854 rebuilt.
1856 Normally, this is exactly what you want: if a target's prerequisite is
1857 updated, then the target should also be updated.
1859 Occasionally, however, you have a situation where you want to impose a
1860 specific ordering on the rules to be invoked @emph{without} forcing
1861 the target to be updated if one of those rules is executed.  In that
1862 case, you want to define @dfn{order-only} prerequisites.  Order-only
1863 prerequisites can be specified by placing a pipe symbol (@code{|})
1864 in the prerequisites list: any prerequisites to the left of the pipe
1865 symbol are normal; any prerequisites to the right are order-only:
1867 @example
1868 @var{targets} : @var{normal-prerequisites} | @var{order-only-prerequisites}
1869 @end example
1871 The normal prerequisites section may of course be empty.  Also, you
1872 may still declare multiple lines of prerequisites for the same target:
1873 they are appended appropriately (normal prerequisites are appended to
1874 the list of normal prerequisites; order-only prerequisites are
1875 appended to the list of order-only prerequisites).  Note that if you
1876 declare the same file to be both a normal and an order-only
1877 prerequisite, the normal prerequisite takes precedence (since they
1878 have a strict superset of the behavior of an order-only prerequisite).
1880 Consider an example where your targets are to be placed in a separate
1881 directory, and that directory might not exist before @code{make} is
1882 run.  In this situation, you want the directory to be created before
1883 any targets are placed into it but, because the timestamps on
1884 directories change whenever a file is added, removed, or renamed, we
1885 certainly don't want to rebuild all the targets whenever the
1886 directory's timestamp changes.  One way to manage this is with
1887 order-only prerequisites: make the directory an order-only
1888 prerequisite on all the targets:
1890 @example
1891 OBJDIR := objdir
1892 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
1894 $(OBJDIR)/%.o : %.c
1895         $(COMPILE.c) $(OUTPUT_OPTION) $<
1897 all: $(OBJS)
1899 $(OBJS): | $(OBJDIR)
1901 $(OBJDIR):
1902         mkdir $(OBJDIR)
1903 @end example
1905 Now the rule to create the @file{objdir} directory will be run, if
1906 needed, before any @samp{.o} is built, but no @samp{.o} will be built
1907 because the @file{objdir} directory timestamp changed.
1909 @node Wildcards, Directory Search, Prerequisite Types, Rules
1910 @section Using Wildcard Characters in File Names
1911 @cindex wildcard
1912 @cindex file name with wildcards
1913 @cindex globbing (wildcards)
1915 @cindex @code{*} (wildcard character)
1916 @cindex @code{?} (wildcard character)
1917 @cindex @code{[@dots{}]} (wildcard characters)
1918 A single file name can specify many files using @dfn{wildcard characters}.
1919 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
1920 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
1921 specifies a list of all the files (in the working directory) whose names
1922 end in @samp{.c}.@refill
1924 @cindex @code{~} (tilde)
1925 @cindex tilde (@code{~})
1926 @cindex home directory
1927 The character @samp{~} at the beginning of a file name also has special
1928 significance.  If alone, or followed by a slash, it represents your home
1929 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
1930 If the @samp{~} is followed by a word, the string represents the home
1931 directory of the user named by that word.  For example @file{~john/bin}
1932 expands to @file{/home/john/bin}.  On systems which don't have a home
1933 directory for each user (such as MS-DOS or MS-Windows), this
1934 functionality can be simulated by setting the environment variable
1935 @var{HOME}.@refill
1937 Wildcard expansion is performed by @code{make} automatically in
1938 targets and in prerequisites.  In recipes, the shell is responsible
1939 for wildcard expansion.  In other contexts, wildcard expansion happens
1940 only if you request it explicitly with the @code{wildcard} function.
1942 The special significance of a wildcard character can be turned off by
1943 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
1944 specific file whose name consists of @samp{foo}, an asterisk, and
1945 @samp{bar}.@refill
1947 @menu
1948 * Wildcard Examples::           Several examples.
1949 * Wildcard Pitfall::            Problems to avoid.
1950 * Wildcard Function::           How to cause wildcard expansion where
1951                                   it does not normally take place.
1952 @end menu
1954 @node Wildcard Examples, Wildcard Pitfall, Wildcards, Wildcards
1955 @subsection Wildcard Examples
1957 Wildcards can be used in the recipe of a rule, where they are expanded
1958 by the shell.  For example, here is a rule to delete all the object files:
1960 @example
1961 @group
1962 clean:
1963         rm -f *.o
1964 @end group
1965 @end example
1966 @cindex @code{rm} (shell command)
1968 Wildcards are also useful in the prerequisites of a rule.  With the
1969 following rule in the makefile, @samp{make print} will print all the
1970 @samp{.c} files that have changed since the last time you printed them:
1972 @example
1973 print: *.c
1974         lpr -p $?
1975         touch print
1976 @end example
1978 @cindex @code{print} target
1979 @cindex @code{lpr} (shell command)
1980 @cindex @code{touch} (shell command)
1981 @noindent
1982 This rule uses @file{print} as an empty target file; see @ref{Empty
1983 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
1984 @samp{$?} is used to print only those files that have changed; see
1985 @ref{Automatic Variables}.)@refill
1987 Wildcard expansion does not happen when you define a variable.  Thus, if
1988 you write this:
1990 @example
1991 objects = *.o
1992 @end example
1994 @noindent
1995 then the value of the variable @code{objects} is the actual string
1996 @samp{*.o}.  However, if you use the value of @code{objects} in a
1997 target or prerequisite, wildcard expansion will take place there.  If
1998 you use the value of @code{objects} in a recipe, the shell may perform
1999 wildcard expansion when the recipe runs.  To set @code{objects} to the
2000 expansion, instead use:
2002 @example
2003 objects := $(wildcard *.o)
2004 @end example
2006 @noindent
2007 @xref{Wildcard Function}.
2009 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
2010 @subsection Pitfalls of Using Wildcards
2011 @cindex wildcard pitfalls
2012 @cindex pitfalls of wildcards
2013 @cindex mistakes with wildcards
2014 @cindex errors with wildcards
2015 @cindex problems with wildcards
2017 Now here is an example of a naive way of using wildcard expansion, that
2018 does not do what you would intend.  Suppose you would like to say that the
2019 executable file @file{foo} is made from all the object files in the
2020 directory, and you write this:
2022 @example
2023 objects = *.o
2025 foo : $(objects)
2026         cc -o foo $(CFLAGS) $(objects)
2027 @end example
2029 @noindent
2030 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
2031 expansion happens in the rule for @file{foo}, so that each @emph{existing}
2032 @samp{.o} file becomes a prerequisite of @file{foo} and will be recompiled if
2033 necessary.
2035 But what if you delete all the @samp{.o} files?  When a wildcard matches
2036 no files, it is left as it is, so then @file{foo} will depend on the
2037 oddly-named file @file{*.o}.  Since no such file is likely to exist,
2038 @code{make} will give you an error saying it cannot figure out how to
2039 make @file{*.o}.  This is not what you want!
2041 Actually it is possible to obtain the desired result with wildcard
2042 expansion, but you need more sophisticated techniques, including the
2043 @code{wildcard} function and string substitution.
2044 @ifnottex
2045 @xref{Wildcard Function, ,The Function @code{wildcard}}.
2046 @end ifnottex
2047 @iftex
2048 These are described in the following section.
2049 @end iftex
2051 @cindex wildcards and MS-DOS/MS-Windows backslashes
2052 @cindex backslashes in pathnames and wildcard expansion
2054 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes to
2055 separate directories in pathnames, like so:
2057 @example
2058   c:\foo\bar\baz.c
2059 @end example
2061 This is equivalent to the Unix-style @file{c:/foo/bar/baz.c} (the
2062 @file{c:} part is the so-called drive letter).  When @code{make} runs on
2063 these systems, it supports backslashes as well as the Unix-style forward
2064 slashes in pathnames.  However, this support does @emph{not} include the
2065 wildcard expansion, where backslash is a quote character.  Therefore,
2066 you @emph{must} use Unix-style slashes in these cases.
2069 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
2070 @subsection The Function @code{wildcard}
2071 @findex wildcard
2073 Wildcard expansion happens automatically in rules.  But wildcard expansion
2074 does not normally take place when a variable is set, or inside the
2075 arguments of a function.  If you want to do wildcard expansion in such
2076 places, you need to use the @code{wildcard} function, like this:
2078 @example
2079 $(wildcard @var{pattern}@dots{})
2080 @end example
2082 @noindent
2083 This string, used anywhere in a makefile, is replaced by a
2084 space-separated list of names of existing files that match one of the
2085 given file name patterns.  If no existing file name matches a pattern,
2086 then that pattern is omitted from the output of the @code{wildcard}
2087 function.  Note that this is different from how unmatched wildcards
2088 behave in rules, where they are used verbatim rather than ignored
2089 (@pxref{Wildcard Pitfall}).
2091 One use of the @code{wildcard} function is to get a list of all the C source
2092 files in a directory, like this:
2094 @example
2095 $(wildcard *.c)
2096 @end example
2098 We can change the list of C source files into a list of object files by
2099 replacing the @samp{.c} suffix with @samp{.o} in the result, like this:
2101 @example
2102 $(patsubst %.c,%.o,$(wildcard *.c))
2103 @end example
2105 @noindent
2106 (Here we have used another function, @code{patsubst}.
2107 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)@refill
2109 Thus, a makefile to compile all C source files in the directory and then
2110 link them together could be written as follows:
2112 @example
2113 objects := $(patsubst %.c,%.o,$(wildcard *.c))
2115 foo : $(objects)
2116         cc -o foo $(objects)
2117 @end example
2119 @noindent
2120 (This takes advantage of the implicit rule for compiling C programs, so
2121 there is no need to write explicit rules for compiling the files.
2122 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
2123 @samp{:=}, which is a variant of @samp{=}.)
2125 @node Directory Search, Phony Targets, Wildcards, Rules
2126 @section Searching Directories for Prerequisites
2127 @vindex VPATH
2128 @findex vpath
2129 @cindex vpath
2130 @cindex search path for prerequisites (@code{VPATH})
2131 @cindex directory search (@code{VPATH})
2133 For large systems, it is often desirable to put sources in a separate
2134 directory from the binaries.  The @dfn{directory search} features of
2135 @code{make} facilitate this by searching several directories
2136 automatically to find a prerequisite.  When you redistribute the files
2137 among directories, you do not need to change the individual rules,
2138 just the search paths.
2140 @menu
2141 * General Search::              Specifying a search path that applies
2142                                   to every prerequisite.
2143 * Selective Search::            Specifying a search path
2144                                   for a specified class of names.
2145 * Search Algorithm::            When and how search paths are applied.
2146 * Recipes/Search::              How to write recipes that work together
2147                                   with search paths.
2148 * Implicit/Search::             How search paths affect implicit rules.
2149 * Libraries/Search::            Directory search for link libraries.
2150 @end menu
2152 @node General Search, Selective Search, Directory Search, Directory Search
2153 @subsection @code{VPATH}: Search Path for All Prerequisites
2154 @vindex VPATH
2156 The value of the @code{make} variable @code{VPATH} specifies a list of
2157 directories that @code{make} should search.  Most often, the
2158 directories are expected to contain prerequisite files that are not in the
2159 current directory; however, @code{make} uses @code{VPATH} as a search
2160 list for both prerequisites and targets of rules.
2162 Thus, if a file that is listed as a target or prerequisite does not exist
2163 in the current directory, @code{make} searches the directories listed in
2164 @code{VPATH} for a file with that name.  If a file is found in one of
2165 them, that file may become the prerequisite (see below).  Rules may then
2166 specify the names of files in the prerequisite list as if they all
2167 existed in the current directory.  @xref{Recipes/Search, ,Writing Recipes with Directory Search}.
2169 In the @code{VPATH} variable, directory names are separated by colons or
2170 blanks.  The order in which directories are listed is the order followed
2171 by @code{make} in its search.  (On MS-DOS and MS-Windows, semi-colons
2172 are used as separators of directory names in @code{VPATH}, since the
2173 colon can be used in the pathname itself, after the drive letter.)
2175 For example,
2177 @example
2178 VPATH = src:../headers
2179 @end example
2181 @noindent
2182 specifies a path containing two directories, @file{src} and
2183 @file{../headers}, which @code{make} searches in that order.
2185 With this value of @code{VPATH}, the following rule,
2187 @example
2188 foo.o : foo.c
2189 @end example
2191 @noindent
2192 is interpreted as if it were written like this:
2194 @example
2195 foo.o : src/foo.c
2196 @end example
2198 @noindent
2199 assuming the file @file{foo.c} does not exist in the current directory but
2200 is found in the directory @file{src}.
2202 @node Selective Search, Search Algorithm, General Search, Directory Search
2203 @subsection The @code{vpath} Directive
2204 @findex vpath
2206 Similar to the @code{VPATH} variable, but more selective, is the
2207 @code{vpath} directive (note lower case), which allows you to specify a
2208 search path for a particular class of file names: those that match a
2209 particular pattern.  Thus you can supply certain search directories for
2210 one class of file names and other directories (or none) for other file
2211 names.
2213 There are three forms of the @code{vpath} directive:
2215 @table @code
2216 @item vpath @var{pattern} @var{directories}
2217 Specify the search path @var{directories} for file names that match
2218 @var{pattern}.
2220 The search path, @var{directories}, is a list of directories to be
2221 searched, separated by colons (semi-colons on MS-DOS and MS-Windows) or
2222 blanks, just like the search path used in the @code{VPATH} variable.
2224 @item vpath @var{pattern}
2225 Clear out the search path associated with @var{pattern}.
2227 @c Extra blank line makes sure this gets two lines.
2228 @item vpath
2230 Clear all search paths previously specified with @code{vpath} directives.
2231 @end table
2233 A @code{vpath} pattern is a string containing a @samp{%} character.  The
2234 string must match the file name of a prerequisite that is being searched
2235 for, the @samp{%} character matching any sequence of zero or more
2236 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
2237 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
2238 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
2239 prerequisite exactly, which is not useful very often.)
2241 @cindex @code{%}, quoting in @code{vpath}
2242 @cindex @code{%}, quoting with @code{\} (backslash)
2243 @cindex @code{\} (backslash), to quote @code{%}
2244 @cindex backslash (@code{\}), to quote @code{%}
2245 @cindex quoting @code{%}, in @code{vpath}
2246 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
2247 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
2248 quote @samp{%} characters can be quoted with more backslashes.
2249 Backslashes that quote @samp{%} characters or other backslashes are
2250 removed from the pattern before it is compared to file names.  Backslashes
2251 that are not in danger of quoting @samp{%} characters go unmolested.@refill
2253 When a prerequisite fails to exist in the current directory, if the
2254 @var{pattern} in a @code{vpath} directive matches the name of the
2255 prerequisite file, then the @var{directories} in that directive are searched
2256 just like (and before) the directories in the @code{VPATH} variable.
2258 For example,
2260 @example
2261 vpath %.h ../headers
2262 @end example
2264 @noindent
2265 tells @code{make} to look for any prerequisite whose name ends in @file{.h}
2266 in the directory @file{../headers} if the file is not found in the current
2267 directory.
2269 If several @code{vpath} patterns match the prerequisite file's name, then
2270 @code{make} processes each matching @code{vpath} directive one by one,
2271 searching all the directories mentioned in each directive.  @code{make}
2272 handles multiple @code{vpath} directives in the order in which they
2273 appear in the makefile; multiple directives with the same pattern are
2274 independent of each other.
2276 @need 750
2277 Thus,
2279 @example
2280 @group
2281 vpath %.c foo
2282 vpath %   blish
2283 vpath %.c bar
2284 @end group
2285 @end example
2287 @noindent
2288 will look for a file ending in @samp{.c} in @file{foo}, then
2289 @file{blish}, then @file{bar}, while
2291 @example
2292 @group
2293 vpath %.c foo:bar
2294 vpath %   blish
2295 @end group
2296 @end example
2298 @noindent
2299 will look for a file ending in @samp{.c} in @file{foo}, then
2300 @file{bar}, then @file{blish}.
2302 @node Search Algorithm, Recipes/Search, Selective Search, Directory Search
2303 @subsection How Directory Searches are Performed
2304 @cindex algorithm for directory search
2305 @cindex directory search algorithm
2307 When a prerequisite is found through directory search, regardless of type
2308 (general or selective), the pathname located may not be the one that
2309 @code{make} actually provides you in the prerequisite list.  Sometimes
2310 the path discovered through directory search is thrown away.
2312 The algorithm @code{make} uses to decide whether to keep or abandon a
2313 path found via directory search is as follows:
2315 @enumerate
2316 @item
2317 If a target file does not exist at the path specified in the makefile,
2318 directory search is performed.
2320 @item
2321 If the directory search is successful, that path is kept and this file
2322 is tentatively stored as the target.
2324 @item
2325 All prerequisites of this target are examined using this same method.
2327 @item
2328 After processing the prerequisites, the target may or may not need to be
2329 rebuilt:
2331 @enumerate a
2332 @item
2333 If the target does @emph{not} need to be rebuilt, the path to the file
2334 found during directory search is used for any prerequisite lists which
2335 contain this target.  In short, if @code{make} doesn't need to rebuild
2336 the target then you use the path found via directory search.
2338 @item
2339 If the target @emph{does} need to be rebuilt (is out-of-date), the
2340 pathname found during directory search is @emph{thrown away}, and the
2341 target is rebuilt using the file name specified in the makefile.  In
2342 short, if @code{make} must rebuild, then the target is rebuilt locally,
2343 not in the directory found via directory search.
2344 @end enumerate
2345 @end enumerate
2347 This algorithm may seem complex, but in practice it is quite often
2348 exactly what you want.
2350 @cindex traditional directory search (GPATH)
2351 @cindex directory search, traditional (GPATH)
2352 Other versions of @code{make} use a simpler algorithm: if the file does
2353 not exist, and it is found via directory search, then that pathname is
2354 always used whether or not the target needs to be built.  Thus, if the
2355 target is rebuilt it is created at the pathname discovered during
2356 directory search.
2358 @vindex GPATH
2359 If, in fact, this is the behavior you want for some or all of your
2360 directories, you can use the @code{GPATH} variable to indicate this to
2361 @code{make}.
2363 @code{GPATH} has the same syntax and format as @code{VPATH} (that is, a
2364 space- or colon-delimited list of pathnames).  If an out-of-date target
2365 is found by directory search in a directory that also appears in
2366 @code{GPATH}, then that pathname is not thrown away.  The target is
2367 rebuilt using the expanded path.
2369 @node Recipes/Search, Implicit/Search, Search Algorithm, Directory Search
2370 @subsection Writing Recipes with Directory Search
2371 @cindex recipes, and directory search
2372 @cindex directory search (@code{VPATH}), and recipes
2374 When a prerequisite is found in another directory through directory search,
2375 this cannot change the recipe of the rule; they will execute as written.
2376 Therefore, you must write the recipe with care so that it will look for
2377 the prerequisite in the directory where @code{make} finds it.
2379 This is done with the @dfn{automatic variables} such as @samp{$^}
2380 (@pxref{Automatic Variables}).
2381 For instance, the value of @samp{$^} is a
2382 list of all the prerequisites of the rule, including the names of
2383 the directories in which they were found, and the value of
2384 @samp{$@@} is the target.  Thus:@refill
2386 @example
2387 foo.o : foo.c
2388         cc -c $(CFLAGS) $^ -o $@@
2389 @end example
2391 @noindent
2392 (The variable @code{CFLAGS} exists so you can specify flags for C
2393 compilation by implicit rules; we use it here for consistency so it will
2394 affect all C compilations uniformly;
2395 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
2397 Often the prerequisites include header files as well, which you do not
2398 want to mention in the recipe.  The automatic variable @samp{$<} is
2399 just the first prerequisite:
2401 @example
2402 VPATH = src:../headers
2403 foo.o : foo.c defs.h hack.h
2404         cc -c $(CFLAGS) $< -o $@@
2405 @end example
2407 @node Implicit/Search, Libraries/Search, Recipes/Search, Directory Search
2408 @subsection Directory Search and Implicit Rules
2409 @cindex @code{VPATH}, and implicit rules
2410 @cindex directory search (@code{VPATH}), and implicit rules
2411 @cindex search path for prerequisites (@code{VPATH}), and implicit rules
2412 @cindex implicit rule, and directory search
2413 @cindex implicit rule, and @code{VPATH}
2414 @cindex rule, implicit, and directory search
2415 @cindex rule, implicit, and @code{VPATH}
2417 The search through the directories specified in @code{VPATH} or with
2418 @code{vpath} also happens during consideration of implicit rules
2419 (@pxref{Implicit Rules, ,Using Implicit Rules}).
2421 For example, when a file @file{foo.o} has no explicit rule, @code{make}
2422 considers implicit rules, such as the built-in rule to compile
2423 @file{foo.c} if that file exists.  If such a file is lacking in the
2424 current directory, the appropriate directories are searched for it.  If
2425 @file{foo.c} exists (or is mentioned in the makefile) in any of the
2426 directories, the implicit rule for C compilation is applied.
2428 The recipes of implicit rules normally use automatic variables as a
2429 matter of necessity; consequently they will use the file names found by
2430 directory search with no extra effort.
2432 @node Libraries/Search,  , Implicit/Search, Directory Search
2433 @subsection Directory Search for Link Libraries
2434 @cindex link libraries, and directory search
2435 @cindex libraries for linking, directory search
2436 @cindex directory search (@code{VPATH}), and link libraries
2437 @cindex @code{VPATH}, and link libraries
2438 @cindex search path for prerequisites (@code{VPATH}), and link libraries
2439 @cindex @code{-l} (library search)
2440 @cindex link libraries, patterns matching
2441 @cindex @code{.LIBPATTERNS}, and link libraries
2442 @vindex .LIBPATTERNS
2444 Directory search applies in a special way to libraries used with the
2445 linker.  This special feature comes into play when you write a prerequisite
2446 whose name is of the form @samp{-l@var{name}}.  (You can tell something
2447 strange is going on here because the prerequisite is normally the name of a
2448 file, and the @emph{file name} of a library generally looks like
2449 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)@refill
2451 When a prerequisite's name has the form @samp{-l@var{name}}, @code{make}
2452 handles it specially by searching for the file @file{lib@var{name}.so},
2453 and, if it is not found, for the file @file{lib@var{name}.a} in the current
2454 directory, in directories specified by matching @code{vpath}
2455 search paths and the @code{VPATH} search path, and then in the
2456 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
2457 (normally @file{/usr/local/lib}, but MS-DOS/MS-Windows versions of
2458 @code{make} behave as if @var{prefix} is defined to be the root of the
2459 DJGPP installation tree).
2461 For example, if there is a @file{/usr/lib/libcurses.a} library on your
2462 system (and no @file{/usr/lib/libcurses.so} file), then
2464 @example
2465 @group
2466 foo : foo.c -lcurses
2467         cc $^ -o $@@
2468 @end group
2469 @end example
2471 @noindent
2472 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
2473 be executed when @file{foo} is older than @file{foo.c} or than
2474 @file{/usr/lib/libcurses.a}.@refill
2476 Although the default set of files to be searched for is
2477 @file{lib@var{name}.so} and @file{lib@var{name}.a}, this is customizable
2478 via the @code{.LIBPATTERNS} variable.  Each word in the value of this
2479 variable is a pattern string.  When a prerequisite like
2480 @samp{-l@var{name}} is seen, @code{make} will replace the percent in
2481 each pattern in the list with @var{name} and perform the above directory
2482 searches using each library file name.
2484 The default value for @code{.LIBPATTERNS} is @samp{lib%.so lib%.a},
2485 which provides the default behavior described above.
2487 You can turn off link library expansion completely by setting this
2488 variable to an empty value.
2490 @node Phony Targets, Force Targets, Directory Search, Rules
2491 @section Phony Targets
2492 @cindex phony targets
2493 @cindex targets, phony
2494 @cindex targets without a file
2496 A phony target is one that is not really the name of a file; rather it
2497 is just a name for a recipe to be executed when you make an explicit
2498 request.  There are two reasons to use a phony target: to avoid a
2499 conflict with a file of the same name, and to improve performance.
2501 If you write a rule whose recipe will not create the target file, the
2502 recipe will be executed every time the target comes up for remaking.
2503 Here is an example:
2505 @example
2506 @group
2507 clean:
2508         rm *.o temp
2509 @end group
2510 @end example
2512 @noindent
2513 Because the @code{rm} command does not create a file named @file{clean},
2514 probably no such file will ever exist.  Therefore, the @code{rm} command
2515 will be executed every time you say @samp{make clean}.
2516 @cindex @code{rm} (shell command)
2518 @findex .PHONY
2519 The phony target will cease to work if anything ever does create a file
2520 named @file{clean} in this directory.  Since it has no prerequisites, the
2521 file @file{clean} would inevitably be considered up to date, and its
2522 recipe would not be executed.  To avoid this problem, you can explicitly
2523 declare the target to be phony, using the special target @code{.PHONY}
2524 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
2526 @example
2527 .PHONY : clean
2528 @end example
2530 @noindent
2531 Once this is done, @samp{make clean} will run the recipe regardless of
2532 whether there is a file named @file{clean}.
2534 Since it knows that phony targets do not name actual files that could be
2535 remade from other files, @code{make} skips the implicit rule search for
2536 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
2537 phony is good for performance, even if you are not worried about the
2538 actual file existing.
2540 Thus, you first write the line that states that @code{clean} is a
2541 phony target, then you write the rule, like this:
2543 @example
2544 @group
2545 .PHONY: clean
2546 clean:
2547         rm *.o temp
2548 @end group
2549 @end example
2551 Another example of the usefulness of phony targets is in conjunction
2552 with recursive invocations of @code{make} (for more information, see
2553 @ref{Recursion, ,Recursive Use of @code{make}}).  In this case the
2554 makefile will often contain a variable which lists a number of
2555 sub-directories to be built.  One way to handle this is with one rule
2556 whose recipe is a shell loop over the sub-directories, like this:
2558 @example
2559 @group
2560 SUBDIRS = foo bar baz
2562 subdirs:
2563         for dir in $(SUBDIRS); do \
2564           $(MAKE) -C $$dir; \
2565         done
2566 @end group
2567 @end example
2569 There are problems with this method, however.  First, any error
2570 detected in a sub-make is ignored by this rule, so it will continue
2571 to build the rest of the directories even when one fails.  This can be
2572 overcome by adding shell commands to note the error and exit, but then
2573 it will do so even if @code{make} is invoked with the @code{-k}
2574 option, which is unfortunate.  Second, and perhaps more importantly,
2575 you cannot take advantage of @code{make}'s ability to build targets in
2576 parallel (@pxref{Parallel, ,Parallel Execution}), since there is only
2577 one rule.
2579 By declaring the sub-directories as phony targets (you must do this as
2580 the sub-directory obviously always exists; otherwise it won't be built)
2581 you can remove these problems:
2583 @example
2584 @group
2585 SUBDIRS = foo bar baz
2587 .PHONY: subdirs $(SUBDIRS)
2589 subdirs: $(SUBDIRS)
2591 $(SUBDIRS):
2592         $(MAKE) -C $@@
2594 foo: baz
2595 @end group
2596 @end example
2598 Here we've also declared that the @file{foo} sub-directory cannot be
2599 built until after the @file{baz} sub-directory is complete; this kind of
2600 relationship declaration is particularly important when attempting
2601 parallel builds.
2603 A phony target should not be a prerequisite of a real target file; if it
2604 is, its recipe will be run every time @code{make} goes to update that
2605 file.  As long as a phony target is never a prerequisite of a real
2606 target, the phony target recipe will be executed only when the phony
2607 target is a specified goal (@pxref{Goals, ,Arguments to Specify the
2608 Goals}).
2610 Phony targets can have prerequisites.  When one directory contains multiple
2611 programs, it is most convenient to describe all of the programs in one
2612 makefile @file{./Makefile}.  Since the target remade by default will be the
2613 first one in the makefile, it is common to make this a phony target named
2614 @samp{all} and give it, as prerequisites, all the individual programs.  For
2615 example:
2617 @example
2618 all : prog1 prog2 prog3
2619 .PHONY : all
2621 prog1 : prog1.o utils.o
2622         cc -o prog1 prog1.o utils.o
2624 prog2 : prog2.o
2625         cc -o prog2 prog2.o
2627 prog3 : prog3.o sort.o utils.o
2628         cc -o prog3 prog3.o sort.o utils.o
2629 @end example
2631 @noindent
2632 Now you can say just @samp{make} to remake all three programs, or
2633 specify as arguments the ones to remake (as in @samp{make prog1
2634 prog3}).  Phoniness is not inherited: the prerequisites of a phony
2635 target are not themselves phony, unless explicitly declared to be so.
2637 When one phony target is a prerequisite of another, it serves as a subroutine
2638 of the other.  For example, here @samp{make cleanall} will delete the
2639 object files, the difference files, and the file @file{program}:
2641 @example
2642 .PHONY: cleanall cleanobj cleandiff
2644 cleanall : cleanobj cleandiff
2645         rm program
2647 cleanobj :
2648         rm *.o
2650 cleandiff :
2651         rm *.diff
2652 @end example
2654 @node Force Targets, Empty Targets, Phony Targets, Rules
2655 @section Rules without Recipes or Prerequisites
2656 @cindex force targets
2657 @cindex targets, force
2658 @cindex @code{FORCE}
2659 @cindex rule, no recipe or prerequisites
2661 If a rule has no prerequisites or recipe, and the target of the rule
2662 is a nonexistent file, then @code{make} imagines this target to have
2663 been updated whenever its rule is run.  This implies that all targets
2664 depending on this one will always have their recipe run.
2666 An example will illustrate this:
2668 @example
2669 @group
2670 clean: FORCE
2671         rm $(objects)
2672 FORCE:
2673 @end group
2674 @end example
2676 Here the target @samp{FORCE} satisfies the special conditions, so the
2677 target @file{clean} that depends on it is forced to run its recipe.
2678 There is nothing special about the name @samp{FORCE}, but that is one
2679 name commonly used this way.
2681 As you can see, using @samp{FORCE} this way has the same results as using
2682 @samp{.PHONY: clean}.
2684 Using @samp{.PHONY} is more explicit and more efficient.  However,
2685 other versions of @code{make} do not support @samp{.PHONY}; thus
2686 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2688 @node Empty Targets, Special Targets, Force Targets, Rules
2689 @section Empty Target Files to Record Events
2690 @cindex empty targets
2691 @cindex targets, empty
2692 @cindex recording events with empty targets
2694 The @dfn{empty target} is a variant of the phony target; it is used to hold
2695 recipes for an action that you request explicitly from time to time.
2696 Unlike a phony target, this target file can really exist; but the file's
2697 contents do not matter, and usually are empty.
2699 The purpose of the empty target file is to record, with its
2700 last-modification time, when the rule's recipe was last executed.  It
2701 does so because one of the commands in the recipe is a @code{touch}
2702 command to update the target file.
2704 The empty target file should have some prerequisites (otherwise it
2705 doesn't make sense).  When you ask to remake the empty target, the
2706 recipe is executed if any prerequisite is more recent than the target;
2707 in other words, if a prerequisite has changed since the last time you
2708 remade the target.  Here is an example:
2710 @example
2711 print: foo.c bar.c
2712         lpr -p $?
2713         touch print
2714 @end example
2715 @cindex @code{print} target
2716 @cindex @code{lpr} (shell command)
2717 @cindex @code{touch} (shell command)
2719 @noindent
2720 With this rule, @samp{make print} will execute the @code{lpr} command if
2721 either source file has changed since the last @samp{make print}.  The
2722 automatic variable @samp{$?} is used to print only those files that have
2723 changed (@pxref{Automatic Variables}).
2725 @node Special Targets, Multiple Targets, Empty Targets, Rules
2726 @section Special Built-in Target Names
2727 @cindex special targets
2728 @cindex built-in special targets
2729 @cindex targets, built-in special
2731 Certain names have special meanings if they appear as targets.
2733 @table @code
2734 @findex .PHONY
2735 @item .PHONY
2737 The prerequisites of the special target @code{.PHONY} are considered to
2738 be phony targets.  When it is time to consider such a target,
2739 @code{make} will run its recipe unconditionally, regardless of
2740 whether a file with that name exists or what its last-modification
2741 time is.  @xref{Phony Targets, ,Phony Targets}.
2743 @findex .SUFFIXES
2744 @item .SUFFIXES
2746 The prerequisites of the special target @code{.SUFFIXES} are the list
2747 of suffixes to be used in checking for suffix rules.
2748 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
2750 @findex .DEFAULT
2751 @item .DEFAULT
2753 The recipe specified for @code{.DEFAULT} is used for any target for
2754 which no rules are found (either explicit rules or implicit rules).
2755 @xref{Last Resort}.  If a @code{.DEFAULT} recipe is specified, every
2756 file mentioned as a prerequisite, but not as a target in a rule, will have
2757 that recipe executed on its behalf.  @xref{Implicit Rule Search,
2758 ,Implicit Rule Search Algorithm}.
2760 @findex .PRECIOUS
2761 @item .PRECIOUS
2762 @cindex precious targets
2763 @cindex preserving with @code{.PRECIOUS}
2765 The targets which @code{.PRECIOUS} depends on are given the following
2766 special treatment: if @code{make} is killed or interrupted during the
2767 execution of their recipes, the target is not deleted.
2768 @xref{Interrupts, ,Interrupting or Killing @code{make}}.  Also, if the
2769 target is an intermediate file, it will not be deleted after it is no
2770 longer needed, as is normally done.  @xref{Chained Rules, ,Chains of
2771 Implicit Rules}.  In this latter respect it overlaps with the
2772 @code{.SECONDARY} special target.
2774 You can also list the target pattern of an implicit rule (such as
2775 @samp{%.o}) as a prerequisite file of the special target @code{.PRECIOUS}
2776 to preserve intermediate files created by rules whose target patterns
2777 match that file's name.
2779 @findex .INTERMEDIATE
2780 @item .INTERMEDIATE
2781 @cindex intermediate targets, explicit
2783 The targets which @code{.INTERMEDIATE} depends on are treated as
2784 intermediate files.  @xref{Chained Rules, ,Chains of Implicit Rules}.
2785 @code{.INTERMEDIATE} with no prerequisites has no effect.
2787 @findex .SECONDARY
2788 @item .SECONDARY
2789 @cindex secondary targets
2790 @cindex preserving with @code{.SECONDARY}
2792 The targets which @code{.SECONDARY} depends on are treated as
2793 intermediate files, except that they are never automatically deleted.
2794 @xref{Chained Rules, ,Chains of Implicit Rules}.
2796 @code{.SECONDARY} with no prerequisites causes all targets to be treated
2797 as secondary (i.e., no target is removed because it is considered
2798 intermediate).
2800 @findex .SECONDEXPANSION
2801 @item .SECONDEXPANSION
2803 If @code{.SECONDEXPANSION} is mentioned as a target anywhere in the
2804 makefile, then all prerequisite lists defined @emph{after} it appears
2805 will be expanded a second time after all makefiles have been read in.
2806 @xref{Secondary Expansion, ,Secondary Expansion}.
2808 @findex .DELETE_ON_ERROR
2809 @item .DELETE_ON_ERROR
2810 @cindex removing targets on failure
2812 If @code{.DELETE_ON_ERROR} is mentioned as a target anywhere in the
2813 makefile, then @code{make} will delete the target of a rule if it has
2814 changed and its recipe exits with a nonzero exit status, just as it
2815 does when it receives a signal.  @xref{Errors, ,Errors in Recipes}.
2817 @findex .IGNORE
2818 @item .IGNORE
2820 If you specify prerequisites for @code{.IGNORE}, then @code{make} will
2821 ignore errors in execution of the recipe for those particular files.
2822 The recipe for @code{.IGNORE} (if any) is ignored.
2824 If mentioned as a target with no prerequisites, @code{.IGNORE} says to
2825 ignore errors in execution of recipes for all files.  This usage of
2826 @samp{.IGNORE} is supported only for historical compatibility.  Since
2827 this affects every recipe in the makefile, it is not very useful; we
2828 recommend you use the more selective ways to ignore errors in specific
2829 recipes.  @xref{Errors, ,Errors in Recipes}.
2831 @findex .LOW_RESOLUTION_TIME
2832 @item .LOW_RESOLUTION_TIME
2834 If you specify prerequisites for @code{.LOW_RESOLUTION_TIME},
2835 @command{make} assumes that these files are created by commands that
2836 generate low resolution time stamps.  The recipe for the
2837 @code{.LOW_RESOLUTION_TIME} target are ignored.
2839 The high resolution file time stamps of many modern file systems
2840 lessen the chance of @command{make} incorrectly concluding that a file
2841 is up to date.  Unfortunately, some hosts do not provide a way to set a
2842 high resolution file time stamp, so commands like @samp{cp -p} that
2843 explicitly set a file's time stamp must discard its sub-second part.
2844 If a file is created by such a command, you should list it as a
2845 prerequisite of @code{.LOW_RESOLUTION_TIME} so that @command{make}
2846 does not mistakenly conclude that the file is out of date.  For
2847 example:
2849 @example
2850 @group
2851 .LOW_RESOLUTION_TIME: dst
2852 dst: src
2853         cp -p src dst
2854 @end group
2855 @end example
2857 Since @samp{cp -p} discards the sub-second part of @file{src}'s time
2858 stamp, @file{dst} is typically slightly older than @file{src} even when
2859 it is up to date.  The @code{.LOW_RESOLUTION_TIME} line causes
2860 @command{make} to consider @file{dst} to be up to date if its time stamp
2861 is at the start of the same second that @file{src}'s time stamp is in.
2863 Due to a limitation of the archive format, archive member time stamps
2864 are always low resolution.  You need not list archive members as
2865 prerequisites of @code{.LOW_RESOLUTION_TIME}, as @command{make} does this
2866 automatically.
2868 @findex .SILENT
2869 @item .SILENT
2871 If you specify prerequisites for @code{.SILENT}, then @code{make} will
2872 not print the recipe used to remake those particular files before
2873 executing them.  The recipe for @code{.SILENT} is ignored.
2875 If mentioned as a target with no prerequisites, @code{.SILENT} says not
2876 to print any recipes before executing them.  This usage of
2877 @samp{.SILENT} is supported only for historical compatibility.  We
2878 recommend you use the more selective ways to silence specific recipes.
2879 @xref{Echoing, ,Recipe Echoing}.  If you want to silence all recipes
2880 for a particular run of @code{make}, use the @samp{-s} or
2881 @w{@samp{--silent}} option (@pxref{Options Summary}).
2883 @findex .EXPORT_ALL_VARIABLES
2884 @item .EXPORT_ALL_VARIABLES
2886 Simply by being mentioned as a target, this tells @code{make} to
2887 export all variables to child processes by default.
2888 @xref{Variables/Recursion, ,Communicating Variables to a
2889 Sub-@code{make}}.
2891 @findex .NOTPARALLEL
2892 @item .NOTPARALLEL
2893 @cindex parallel execution, overriding
2895 If @code{.NOTPARALLEL} is mentioned as a target, then this invocation
2896 of @code{make} will be run serially, even if the @samp{-j} option is
2897 given.  Any recursively invoked @code{make} command will still run
2898 recipes in parallel (unless its makefile also contains this target).
2899 Any prerequisites on this target are ignored.
2901 @findex .ONESHELL
2902 @item .ONESHELL
2903 @cindex recipe execution, single invocation
2905 If @code{.ONESHELL} is mentioned as a target, then when a target is
2906 built all lines of the recipe will be given to a single invocation of
2907 the shell rather than each line being invoked separately
2908 (@pxref{Execution, ,Recipe Execution}).
2910 @findex .POSIX
2911 @item .POSIX
2912 @cindex POSIX-conforming mode, setting
2914 If @code{.POSIX} is mentioned as a target, then the makefile will be
2915 parsed and run in POSIX-conforming mode.  This does @emph{not} mean
2916 that only POSIX-conforming makefiles will be accepted: all advanced
2917 GNU @code{make} features are still available.  Rather, this target
2918 causes @code{make} to behave as required by POSIX in those areas
2919 where @code{make}'s default behavior differs.
2921 In particular, if this target is mentioned then recipes will be
2922 invoked as if the shell had been passed the @code{-e} flag: the first
2923 failing command in a recipe will cause the recipe to fail immediately.
2924 @end table
2926 Any defined implicit rule suffix also counts as a special target if it
2927 appears as a target, and so does the concatenation of two suffixes, such
2928 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
2929 defining implicit rules (but a way still widely used).  In principle, any
2930 target name could be special in this way if you break it in two and add
2931 both pieces to the suffix list.  In practice, suffixes normally begin with
2932 @samp{.}, so these special target names also begin with @samp{.}.
2933 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
2935 @node Multiple Targets, Multiple Rules, Special Targets, Rules
2936 @section Multiple Targets in a Rule
2937 @cindex multiple targets
2938 @cindex several targets in a rule
2939 @cindex targets, multiple
2940 @cindex rule, with multiple targets
2942 A rule with multiple targets is equivalent to writing many rules, each with
2943 one target, and all identical aside from that.  The same recipe applies to
2944 all the targets, but its effect may vary because you can substitute the
2945 actual target name into the recipe using @samp{$@@}.  The rule contributes
2946 the same prerequisites to all the targets also.
2948 This is useful in two cases.
2950 @itemize @bullet
2951 @item
2952 You want just prerequisites, no recipe.  For example:
2954 @example
2955 kbd.o command.o files.o: command.h
2956 @end example
2958 @noindent
2959 gives an additional prerequisite to each of the three object files
2960 mentioned.
2962 @item
2963 Similar recipes work for all the targets.  The recipes do not need
2964 to be absolutely identical, since the automatic variable @samp{$@@}
2965 can be used to substitute the particular target to be remade into the
2966 commands (@pxref{Automatic Variables}).  For example:
2968 @example
2969 @group
2970 bigoutput littleoutput : text.g
2971         generate text.g -$(subst output,,$@@) > $@@
2972 @end group
2973 @end example
2974 @findex subst
2976 @noindent
2977 is equivalent to
2979 @example
2980 bigoutput : text.g
2981         generate text.g -big > bigoutput
2982 littleoutput : text.g
2983         generate text.g -little > littleoutput
2984 @end example
2986 @noindent
2987 Here we assume the hypothetical program @code{generate} makes two
2988 types of output, one if given @samp{-big} and one if given
2989 @samp{-little}.
2990 @xref{Text Functions, ,Functions for String Substitution and Analysis},
2991 for an explanation of the @code{subst} function.
2992 @end itemize
2994 Suppose you would like to vary the prerequisites according to the
2995 target, much as the variable @samp{$@@} allows you to vary the recipe.
2996 You cannot do this with multiple targets in an ordinary rule, but you
2997 can do it with a @dfn{static pattern rule}.  @xref{Static Pattern,
2998 ,Static Pattern Rules}.
3000 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
3001 @section Multiple Rules for One Target
3002 @cindex multiple rules for one target
3003 @cindex several rules for one target
3004 @cindex rule, multiple for one target
3005 @cindex target, multiple rules for one
3007 One file can be the target of several rules.  All the prerequisites
3008 mentioned in all the rules are merged into one list of prerequisites for
3009 the target.  If the target is older than any prerequisite from any rule,
3010 the recipe is executed.
3012 There can only be one recipe to be executed for a file.  If more than
3013 one rule gives a recipe for the same file, @code{make} uses the last
3014 one given and prints an error message.  (As a special case, if the
3015 file's name begins with a dot, no error message is printed.  This odd
3016 behavior is only for compatibility with other implementations of
3017 @code{make}@dots{} you should avoid using it).  Occasionally it is
3018 useful to have the same target invoke multiple recipes which are
3019 defined in different parts of your makefile; you can use
3020 @dfn{double-colon rules} (@pxref{Double-Colon}) for this.
3022 An extra rule with just prerequisites can be used to give a few extra
3023 prerequisites to many files at once.  For example, makefiles often
3024 have a variable, such as @code{objects}, containing a list of all the
3025 compiler output files in the system being made.  An easy way to say
3026 that all of them must be recompiled if @file{config.h} changes is to
3027 write the following:
3029 @example
3030 objects = foo.o bar.o
3031 foo.o : defs.h
3032 bar.o : defs.h test.h
3033 $(objects) : config.h
3034 @end example
3036 This could be inserted or taken out without changing the rules that really
3037 specify how to make the object files, making it a convenient form to use if
3038 you wish to add the additional prerequisite intermittently.
3040 Another wrinkle is that the additional prerequisites could be
3041 specified with a variable that you set with a command line argument to
3042 @code{make} (@pxref{Overriding, ,Overriding Variables}).  For example,
3044 @example
3045 @group
3046 extradeps=
3047 $(objects) : $(extradeps)
3048 @end group
3049 @end example
3051 @noindent
3052 means that the command @samp{make extradeps=foo.h} will consider
3053 @file{foo.h} as a prerequisite of each object file, but plain @samp{make}
3054 will not.
3056 If none of the explicit rules for a target has a recipe, then @code{make}
3057 searches for an applicable implicit rule to find one
3058 @pxref{Implicit Rules, ,Using Implicit Rules}).
3060 @node Static Pattern, Double-Colon, Multiple Rules, Rules
3061 @section Static Pattern Rules
3062 @cindex static pattern rule
3063 @cindex rule, static pattern
3064 @cindex pattern rules, static (not implicit)
3065 @cindex varying prerequisites
3066 @cindex prerequisites, varying (static pattern)
3068 @dfn{Static pattern rules} are rules which specify multiple targets and
3069 construct the prerequisite names for each target based on the target name.
3070 They are more general than ordinary rules with multiple targets because the
3071 targets do not have to have identical prerequisites.  Their prerequisites must
3072 be @emph{analogous}, but not necessarily @emph{identical}.
3074 @menu
3075 * Static Usage::                The syntax of static pattern rules.
3076 * Static versus Implicit::      When are they better than implicit rules?
3077 @end menu
3079 @node Static Usage, Static versus Implicit, Static Pattern, Static Pattern
3080 @subsection Syntax of Static Pattern Rules
3081 @cindex static pattern rule, syntax of
3082 @cindex pattern rules, static, syntax of
3084 Here is the syntax of a static pattern rule:
3086 @example
3087 @var{targets} @dots{}: @var{target-pattern}: @var{prereq-patterns} @dots{}
3088         @var{recipe}
3089         @dots{}
3090 @end example
3092 @noindent
3093 The @var{targets} list specifies the targets that the rule applies to.
3094 The targets can contain wildcard characters, just like the targets of
3095 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
3096 Names}).
3098 @cindex target pattern, static (not implicit)
3099 @cindex stem
3100 The @var{target-pattern} and @var{prereq-patterns} say how to compute the
3101 prerequisites of each target.  Each target is matched against the
3102 @var{target-pattern} to extract a part of the target name, called the
3103 @dfn{stem}.  This stem is substituted into each of the @var{prereq-patterns}
3104 to make the prerequisite names (one from each @var{prereq-pattern}).
3106 Each pattern normally contains the character @samp{%} just once.  When the
3107 @var{target-pattern} matches a target, the @samp{%} can match any part of
3108 the target name; this part is called the @dfn{stem}.  The rest of the
3109 pattern must match exactly.  For example, the target @file{foo.o} matches
3110 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
3111 @file{foo.c} and @file{foo.out} do not match that pattern.@refill
3113 @cindex prerequisite pattern, static (not implicit)
3114 The prerequisite names for each target are made by substituting the stem
3115 for the @samp{%} in each prerequisite pattern.  For example, if one
3116 prerequisite pattern is @file{%.c}, then substitution of the stem
3117 @samp{foo} gives the prerequisite name @file{foo.c}.  It is legitimate
3118 to write a prerequisite pattern that does not contain @samp{%}; then this
3119 prerequisite is the same for all targets.
3121 @cindex @code{%}, quoting in static pattern
3122 @cindex @code{%}, quoting with @code{\} (backslash)
3123 @cindex @code{\} (backslash), to quote @code{%}
3124 @cindex backslash (@code{\}), to quote @code{%}
3125 @cindex quoting @code{%}, in static pattern
3126 @samp{%} characters in pattern rules can be quoted with preceding
3127 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
3128 characters can be quoted with more backslashes.  Backslashes that quote
3129 @samp{%} characters or other backslashes are removed from the pattern
3130 before it is compared to file names or has a stem substituted into it.
3131 Backslashes that are not in danger of quoting @samp{%} characters go
3132 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
3133 @samp{the%weird\} preceding the operative @samp{%} character, and
3134 @samp{pattern\\} following it.  The final two backslashes are left alone
3135 because they cannot affect any @samp{%} character.@refill
3137 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
3138 from the corresponding @file{.c} file:
3140 @example
3141 @group
3142 objects = foo.o bar.o
3144 all: $(objects)
3146 $(objects): %.o: %.c
3147         $(CC) -c $(CFLAGS) $< -o $@@
3148 @end group
3149 @end example
3151 @noindent
3152 Here @samp{$<} is the automatic variable that holds the name of the
3153 prerequisite and @samp{$@@} is the automatic variable that holds the name
3154 of the target; see @ref{Automatic Variables}.
3156 Each target specified must match the target pattern; a warning is issued
3157 for each target that does not.  If you have a list of files, only some of
3158 which will match the pattern, you can use the @code{filter} function to
3159 remove non-matching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
3161 @example
3162 files = foo.elc bar.o lose.o
3164 $(filter %.o,$(files)): %.o: %.c
3165         $(CC) -c $(CFLAGS) $< -o $@@
3166 $(filter %.elc,$(files)): %.elc: %.el
3167         emacs -f batch-byte-compile $<
3168 @end example
3170 @noindent
3171 In this example the result of @samp{$(filter %.o,$(files))} is
3172 @file{bar.o lose.o}, and the first static pattern rule causes each of
3173 these object files to be updated by compiling the corresponding C source
3174 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
3175 @file{foo.elc}, so that file is made from @file{foo.el}.@refill
3177 Another example shows how to use @code{$*} in static pattern rules:
3178 @vindex $*@r{, and static pattern}
3180 @example
3181 @group
3182 bigoutput littleoutput : %output : text.g
3183         generate text.g -$* > $@@
3184 @end group
3185 @end example
3187 @noindent
3188 When the @code{generate} command is run, @code{$*} will expand to the
3189 stem, either @samp{big} or @samp{little}.
3191 @node Static versus Implicit,  , Static Usage, Static Pattern
3192 @subsection Static Pattern Rules versus Implicit Rules
3193 @cindex rule, static pattern versus implicit
3194 @cindex static pattern rule, versus implicit
3196 A static pattern rule has much in common with an implicit rule defined as a
3197 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
3198 Both have a pattern for the target and patterns for constructing the
3199 names of prerequisites.  The difference is in how @code{make} decides
3200 @emph{when} the rule applies.
3202 An implicit rule @emph{can} apply to any target that matches its pattern,
3203 but it @emph{does} apply only when the target has no recipe otherwise
3204 specified, and only when the prerequisites can be found.  If more than one
3205 implicit rule appears applicable, only one applies; the choice depends on
3206 the order of rules.
3208 By contrast, a static pattern rule applies to the precise list of targets
3209 that you specify in the rule.  It cannot apply to any other target and it
3210 invariably does apply to each of the targets specified.  If two conflicting
3211 rules apply, and both have recipes, that's an error.
3213 The static pattern rule can be better than an implicit rule for these
3214 reasons:
3216 @itemize @bullet
3217 @item
3218 You may wish to override the usual implicit rule for a few
3219 files whose names cannot be categorized syntactically but
3220 can be given in an explicit list.
3222 @item
3223 If you cannot be sure of the precise contents of the directories
3224 you are using, you may not be sure which other irrelevant files
3225 might lead @code{make} to use the wrong implicit rule.  The choice
3226 might depend on the order in which the implicit rule search is done.
3227 With static pattern rules, there is no uncertainty: each rule applies
3228 to precisely the targets specified.
3229 @end itemize
3231 @node Double-Colon, Automatic Prerequisites, Static Pattern, Rules
3232 @section Double-Colon Rules
3233 @cindex double-colon rules
3234 @cindex rule, double-colon (@code{::})
3235 @cindex multiple rules for one target (@code{::})
3236 @cindex @code{::} rules (double-colon)
3238 @dfn{Double-colon} rules are explicit rules written with @samp{::}
3239 instead of @samp{:} after the target names.  They are handled
3240 differently from ordinary rules when the same target appears in more
3241 than one rule.  Pattern rules with double-colons have an entirely
3242 different meaning (@pxref{Match-Anything Rules}).
3244 When a target appears in multiple rules, all the rules must be the same
3245 type: all ordinary, or all double-colon.  If they are double-colon, each
3246 of them is independent of the others.  Each double-colon rule's recipe
3247 is executed if the target is older than any prerequisites of that rule.
3248 If there are no prerequisites for that rule, its recipe is always
3249 executed (even if the target already exists).  This can result in
3250 executing none, any, or all of the double-colon rules.
3252 Double-colon rules with the same target are in fact completely separate
3253 from one another.  Each double-colon rule is processed individually, just
3254 as rules with different targets are processed.
3256 The double-colon rules for a target are executed in the order they appear
3257 in the makefile.  However, the cases where double-colon rules really make
3258 sense are those where the order of executing the recipes would not matter.
3260 Double-colon rules are somewhat obscure and not often very useful; they
3261 provide a mechanism for cases in which the method used to update a target
3262 differs depending on which prerequisite files caused the update, and such
3263 cases are rare.
3265 Each double-colon rule should specify a recipe; if it does not, an
3266 implicit rule will be used if one applies.
3267 @xref{Implicit Rules, ,Using Implicit Rules}.
3269 @node Automatic Prerequisites,  , Double-Colon, Rules
3270 @section Generating Prerequisites Automatically
3271 @cindex prerequisites, automatic generation
3272 @cindex automatic generation of prerequisites
3273 @cindex generating prerequisites automatically
3275 In the makefile for a program, many of the rules you need to write often
3276 say only that some object file depends on some header
3277 file.  For example, if @file{main.c} uses @file{defs.h} via an
3278 @code{#include}, you would write:
3280 @example
3281 main.o: defs.h
3282 @end example
3284 @noindent
3285 You need this rule so that @code{make} knows that it must remake
3286 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
3287 large program you would have to write dozens of such rules in your
3288 makefile.  And, you must always be very careful to update the makefile
3289 every time you add or remove an @code{#include}.
3290 @cindex @code{#include}
3292 @cindex @code{-M} (to compiler)
3293 To avoid this hassle, most modern C compilers can write these rules for
3294 you, by looking at the @code{#include} lines in the source files.
3295 Usually this is done with the @samp{-M} option to the compiler.
3296 For example, the command:
3298 @example
3299 cc -M main.c
3300 @end example
3302 @noindent
3303 generates the output:
3305 @example
3306 main.o : main.c defs.h
3307 @end example
3309 @noindent
3310 Thus you no longer have to write all those rules yourself.
3311 The compiler will do it for you.
3313 Note that such a rule constitutes mentioning @file{main.o} in a
3314 makefile, so it can never be considered an intermediate file by
3315 implicit rule search.  This means that @code{make} won't ever remove
3316 the file after using it; @pxref{Chained Rules, ,Chains of Implicit
3317 Rules}.
3319 @cindex @code{make depend}
3320 With old @code{make} programs, it was traditional practice to use this
3321 compiler feature to generate prerequisites on demand with a command like
3322 @samp{make depend}.  That command would create a file @file{depend}
3323 containing all the automatically-generated prerequisites; then the
3324 makefile could use @code{include} to read them in (@pxref{Include}).
3326 In GNU @code{make}, the feature of remaking makefiles makes this
3327 practice obsolete---you need never tell @code{make} explicitly to
3328 regenerate the prerequisites, because it always regenerates any makefile
3329 that is out of date.  @xref{Remaking Makefiles}.
3331 The practice we recommend for automatic prerequisite generation is to have
3332 one makefile corresponding to each source file.  For each source file
3333 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
3334 what files the object file @file{@var{name}.o} depends on.  That way
3335 only the source files that have changed need to be rescanned to produce
3336 the new prerequisites.
3338 Here is the pattern rule to generate a file of prerequisites (i.e., a makefile)
3339 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
3341 @smallexample
3342 @group
3343 %.d: %.c
3344         @@set -e; rm -f $@@; \
3345          $(CC) -M $(CPPFLAGS) $< > $@@.$$$$; \
3346          sed 's,\($*\)\.o[ :]*,\1.o $@@ : ,g' < $@@.$$$$ > $@@; \
3347          rm -f $@@.$$$$
3348 @end group
3349 @end smallexample
3351 @noindent
3352 @xref{Pattern Rules}, for information on defining pattern rules.  The
3353 @samp{-e} flag to the shell causes it to exit immediately if the
3354 @code{$(CC)} command (or any other command) fails (exits with a
3355 nonzero status).
3356 @cindex @code{-e} (shell flag)
3358 @cindex @code{-MM} (to GNU compiler)
3359 With the GNU C compiler, you may wish to use the @samp{-MM} flag instead
3360 of @samp{-M}.  This omits prerequisites on system header files.
3361 @xref{Preprocessor Options, , Options Controlling the Preprocessor,
3362 gcc.info, Using GNU CC}, for details.
3364 @cindex @code{sed} (shell command)
3365 The purpose of the @code{sed} command is to translate (for example):
3367 @example
3368 main.o : main.c defs.h
3369 @end example
3371 @noindent
3372 into:
3374 @example
3375 main.o main.d : main.c defs.h
3376 @end example
3378 @noindent
3379 @cindex @code{.d}
3380 This makes each @samp{.d} file depend on all the source and header files
3381 that the corresponding @samp{.o} file depends on.  @code{make} then
3382 knows it must regenerate the prerequisites whenever any of the source or
3383 header files changes.
3385 Once you've defined the rule to remake the @samp{.d} files,
3386 you then use the @code{include} directive to read them all in.
3387 @xref{Include}.  For example:
3389 @example
3390 @group
3391 sources = foo.c bar.c
3393 include $(sources:.c=.d)
3394 @end group
3395 @end example
3397 @noindent
3398 (This example uses a substitution variable reference to translate the
3399 list of source files @samp{foo.c bar.c} into a list of prerequisite
3400 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
3401 information on substitution references.)  Since the @samp{.d} files are
3402 makefiles like any others, @code{make} will remake them as necessary
3403 with no further work from you.  @xref{Remaking Makefiles}.
3405 Note that the @samp{.d} files contain target definitions; you should
3406 be sure to place the @code{include} directive @emph{after} the first,
3407 default goal in your makefiles or run the risk of having a random
3408 object file become the default goal.
3409 @xref{How Make Works}.
3411 @node Recipes, Using Variables, Rules, Top
3412 @chapter Writing Recipes in Rules
3413 @cindex recipes
3414 @cindex recipes, how to write
3415 @cindex writing recipes
3417 The recipe of a rule consists of one or more shell command lines to
3418 be executed, one at a time, in the order they appear.  Typically, the
3419 result of executing these commands is that the target of the rule is
3420 brought up to date.
3422 Users use many different shell programs, but recipes in makefiles are
3423 always interpreted by @file{/bin/sh} unless the makefile specifies
3424 otherwise.  @xref{Execution, ,Recipe Execution}.
3426 @menu
3427 * Recipe Syntax::               Recipe syntax features and pitfalls.
3428 * Echoing::                     How to control when recipes are echoed.
3429 * Execution::                   How recipes are executed.
3430 * Parallel::                    How recipes can be executed in parallel.
3431 * Errors::                      What happens after a recipe execution error.
3432 * Interrupts::                  What happens when a recipe is interrupted.
3433 * Recursion::                   Invoking @code{make} from makefiles.
3434 * Canned Recipes::              Defining canned recipes.
3435 * Empty Recipes::               Defining useful, do-nothing recipes.
3436 @end menu
3438 @node Recipe Syntax, Echoing, Recipes, Recipes
3439 @section Recipe Syntax
3440 @cindex recipe syntax
3441 @cindex syntax of recipe
3443 Makefiles have the unusual property that there are really two distinct
3444 syntaxes in one file.  Most of the makefile uses @code{make} syntax
3445 (@pxref{Makefiles, ,Writing Makefiles}).  However, recipes are meant
3446 to be interpreted by the shell and so they are written using shell
3447 syntax.  The @code{make} program does not try to understand shell
3448 syntax: it performs only a very few specific translations on the
3449 content of the recipe before handing it to the shell.
3451 Each line in the recipe must start with a tab (or the first character
3452 in the value of the @code{.RECIPEPREFIX} variable; @pxref{Special
3453 Variables}), except that the first recipe line may be attached to the
3454 target-and-prerequisites line with a semicolon in between.  @emph{Any}
3455 line in the makefile that begins with a tab and appears in a ``rule
3456 context'' (that is, after a rule has been started until another rule
3457 or variable definition) will be considered part of a recipe for that
3458 rule.  Blank lines and lines of just comments may appear among the
3459 recipe lines; they are ignored.
3461 Some consequences of these rules include:
3463 @itemize @bullet
3464 @item
3465 A blank line that begins with a tab is not blank: it's an empty
3466 recipe (@pxref{Empty Recipes}).
3468 @cindex comments, in recipes
3469 @cindex recipes, comments in
3470 @cindex @code{#} (comments), in recipes
3471 @item
3472 A comment in a recipe is not a @code{make} comment; it will be
3473 passed to the shell as-is.  Whether the shell treats it as a comment
3474 or not depends on your shell.
3476 @item
3477 A variable definition in a ``rule context'' which is indented by a tab
3478 as the first character on the line, will be considered part of a
3479 recipe, not a @code{make} variable definition, and passed to the
3480 shell.
3482 @item
3483 A conditional expression (@code{ifdef}, @code{ifeq},
3484 etc. @pxref{Conditional Syntax, ,Syntax of Conditionals}) in a ``rule
3485 context'' which is indented by a tab as the first character on the
3486 line, will be considered part of a recipe and be passed to the shell.
3488 @end itemize
3490 @menu
3491 * Splitting Lines::             Breaking long recipe lines for readability.
3492 * Variables in Recipes::        Using @code{make} variables in recipes.
3493 @end menu
3495 @node Splitting Lines, Variables in Recipes, Recipe Syntax, Recipe Syntax
3496 @subsection Splitting Recipe Lines
3497 @cindex recipes, splitting
3498 @cindex splitting recipes
3499 @cindex recipes, backslash (@code{\}) in
3500 @cindex recipes, quoting newlines in
3501 @cindex backslash (@code{\}), in recipes
3502 @cindex @code{\} (backslash), in recipes
3503 @cindex quoting newline, in recipes
3504 @cindex newline, quoting, in recipes
3506 One of the few ways in which @code{make} does interpret recipes is
3507 checking for a backslash just before the newline.  As in normal
3508 makefile syntax, a single logical recipe line can be split into
3509 multiple physical lines in the makefile by placing a backslash before
3510 each newline.  A sequence of lines like this is considered a single
3511 recipe line, and one instance of the shell will be invoked to run it.
3513 However, in contrast to how they are treated in other places in a
3514 makefile, backslash-newline pairs are @emph{not} removed from the
3515 recipe.  Both the backslash and the newline characters are preserved
3516 and passed to the shell.  How the backslash-newline is interpreted
3517 depends on your shell.  If the first character of the next line after
3518 the backslash-newline is the recipe prefix character (a tab by
3519 default; @pxref{Special Variables}), then that character (and only
3520 that character) is removed.  Whitespace is never added to the recipe.
3522 For example, the recipe for the all target in this makefile:
3524 @example
3525 @group
3526 all :
3527         @@echo no\
3528 space
3529         @@echo no\
3530         space
3531         @@echo one \
3532         space
3533         @@echo one\
3534          space
3535 @end group
3536 @end example
3538 @noindent
3539 consists of four separate shell commands where the output is:
3541 @example
3542 @group
3543 nospace
3544 nospace
3545 one space
3546 one space
3547 @end group
3548 @end example
3550 As a more complex example, this makefile:
3552 @example
3553 @group
3554 all : ; @@echo 'hello \
3555         world' ; echo "hello \
3556     world"
3557 @end group
3558 @end example
3560 @noindent
3561 will invoke one shell with a command of:
3563 @example
3564 @group
3565 echo 'hello \
3566 world' ; echo "hello \
3567     world"
3568 @end group
3569 @end example
3571 @noindent
3572 which, according to shell quoting rules, will yield the following output:
3574 @example
3575 @group
3576 hello \
3577 world
3578 hello     world
3579 @end group
3580 @end example
3582 @noindent
3583 Notice how the backslash/newline pair was removed inside the string
3584 quoted with double quotes (@code{"@dots{}"}), but not from the string
3585 quoted with single quotes (@code{'@dots{}'}).  This is the way the
3586 default shell (@file{/bin/sh}) handles backslash/newline pairs.  If
3587 you specify a different shell in your makefiles it may treat them
3588 differently.
3590 Sometimes you want to split a long line inside of single quotes, but
3591 you don't want the backslash-newline to appear in the quoted content.
3592 This is often the case when passing scripts to languages such as Perl,
3593 where extraneous backslashes inside the script can change its meaning
3594 or even be a syntax error.  One simple way of handling this is to
3595 place the quoted string, or even the entire command, into a
3596 @code{make} variable then use the variable in the recipe.  In this
3597 situation the newline quoting rules for makefiles will be used, and
3598 the backslash-newline will be removed.  If we rewrite our example
3599 above using this method:
3601 @example
3602 @group
3603 HELLO = 'hello \
3604 world'
3606 all : ; @@echo $(HELLO)
3607 @end group
3608 @end example
3610 @noindent
3611 we will get output like this:
3613 @example
3614 @group
3615 hello world
3616 @end group
3617 @end example
3619 If you like, you can also use target-specific variables
3620 (@pxref{Target-specific, ,Target-specific Variable Values}) to obtain
3621 a tighter correspondence between the variable and the recipe that
3622 uses it.
3624 @node Variables in Recipes,  , Splitting Lines, Recipe Syntax
3625 @subsection Using Variables in Recipes
3626 @cindex variable references in recipes
3627 @cindex recipes, using variables in
3629 The other way in which @code{make} processes recipes is by expanding
3630 any variable references in them (@pxref{Reference,Basics of Variable
3631 References}).  This occurs after make has finished reading all the
3632 makefiles and the target is determined to be out of date; so, the
3633 recipes for targets which are not rebuilt are never expanded.
3635 Variable and function references in recipes have identical syntax and
3636 semantics to references elsewhere in the makefile.  They also have the
3637 same quoting rules: if you want a dollar sign to appear in your
3638 recipe, you must double it (@samp{$$}).  For shells like the default
3639 shell, that use dollar signs to introduce variables, it's important to
3640 keep clear in your mind whether the variable you want to reference is
3641 a @code{make} variable (use a single dollar sign) or a shell variable
3642 (use two dollar signs).  For example:
3644 @example
3645 @group
3646 LIST = one two three
3647 all:
3648         for i in $(LIST); do \
3649             echo $$i; \
3650         done
3651 @end group
3652 @end example
3654 @noindent
3655 results in the following command being passed to the shell:
3657 @example
3658 @group
3659 for i in one two three; do \
3660     echo $i; \
3661 done
3662 @end group
3663 @end example
3665 @noindent
3666 which generates the expected result:
3668 @example
3669 @group
3672 three
3673 @end group
3674 @end example
3676 @node Echoing, Execution, Recipe Syntax, Recipes
3677 @section Recipe Echoing
3678 @cindex echoing of recipes
3679 @cindex silent operation
3680 @cindex @code{@@} (in recipes)
3681 @cindex recipes, echoing
3682 @cindex printing of recipes
3684 Normally @code{make} prints each line of the recipe before it is
3685 executed.  We call this @dfn{echoing} because it gives the appearance
3686 that you are typing the lines yourself.
3688 When a line starts with @samp{@@}, the echoing of that line is suppressed.
3689 The @samp{@@} is discarded before the line is passed to the shell.
3690 Typically you would use this for a command whose only effect is to print
3691 something, such as an @code{echo} command to indicate progress through
3692 the makefile:
3694 @example
3695 @@echo About to make distribution files
3696 @end example
3698 @cindex @code{-n}
3699 @cindex @code{--just-print}
3700 @cindex @code{--dry-run}
3701 @cindex @code{--recon}
3702 When @code{make} is given the flag @samp{-n} or @samp{--just-print} it
3703 only echoes most recipes, without executing them.  @xref{Options
3704 Summary, ,Summary of Options}.  In this case even the recipe lines
3705 starting with @samp{@@} are printed.  This flag is useful for finding
3706 out which recipes @code{make} thinks are necessary without actually
3707 doing them.
3709 @cindex @code{-s}
3710 @cindex @code{--silent}
3711 @cindex @code{--quiet}
3712 @findex .SILENT
3713 The @samp{-s} or @samp{--silent}
3714 flag to @code{make} prevents all echoing, as if all recipes
3715 started with @samp{@@}.  A rule in the makefile for the special target
3716 @code{.SILENT} without prerequisites has the same effect
3717 (@pxref{Special Targets, ,Special Built-in Target Names}).
3718 @code{.SILENT} is essentially obsolete since @samp{@@} is more flexible.@refill
3720 @node Execution, Parallel, Echoing, Recipes
3721 @section Recipe Execution
3722 @cindex recipe, execution
3723 @cindex execution, of recipes
3724 @vindex @code{SHELL} @r{(recipe execution)}
3726 When it is time to execute recipes to update a target, they are
3727 executed by invoking a new sub-shell for each line of the recipe,
3728 unless the @code{.ONESHELL} special target is in effect
3729 (@pxref{One Shell, ,Using One Shell})  (In practice, @code{make} may
3730 take shortcuts that do not affect the results.)
3732 @cindex @code{cd} (shell command)
3733 @cindex shell variables, setting in recipes
3734 @cindex recipes setting shell variables
3735 @strong{Please note:} this implies that setting shell variables and
3736 invoking shell commands such as @code{cd} that set a context local to
3737 each process will not affect the following lines in the recipe.@footnote{On
3738 MS-DOS, the value of current working directory is @strong{global}, so
3739 changing it @emph{will} affect the following recipe lines on those
3740 systems.}  If you want to use @code{cd} to affect the next statement,
3741 put both statements in a single recipe line.  Then @code{make} will
3742 invoke one shell to run the entire line, and the shell will execute
3743 the statements in sequence.  For example:
3745 @example
3746 foo : bar/lose
3747         cd $(@@D) && gobble $(@@F) > ../$@@
3748 @end example
3750 @noindent
3751 Here we use the shell AND operator (@code{&&}) so that if the
3752 @code{cd} command fails, the script will fail without trying to invoke
3753 the @code{gobble} command in the wrong directory, which could cause
3754 problems (in this case it would certainly cause @file{../foo} to be
3755 truncated, at least).
3757 @menu
3758 * One Shell::                   One shell for all lines in a recipe.
3759 * Choosing the Shell::          How @code{make} chooses the shell used
3760                                   to run recipes.
3761 @end menu
3763 @node One Shell, Choosing the Shell, Execution, Execution
3764 @subsection Using One Shell
3765 @cindex recipe lines, single shell
3766 @cindex @code{.ONESHELL}, use of
3767 @findex .ONESHELL
3769 Sometimes you would prefer that all the lines in the recipe be passed
3770 to a single invocation of the shell.  There are generally two
3771 situations where this is useful: first, it can improve performance in
3772 makefiles where recipes consist of many command lines, by avoiding
3773 extra processes.  Second, you might want newlines to be included in
3774 your recipe command (for example perhaps you are using a very
3775 different interpreter as your @code{SHELL}).  If the @code{.ONESHELL}
3776 special target appears anywhere in the makefile then @emph{all}
3777 recipe lines for each target will be provided to a single invocation
3778 of the shell.  Newlines between recipe lines will be preserved.  For
3779 example:
3781 @example
3782 .ONESHELL:
3783 foo : bar/lose
3784         cd $(@@D)
3785         gobble $(@@F) > ../$@@
3786 @end example
3788 @noindent
3789 would now work as expected even though the commands are on different
3790 recipe lines.
3792 If @code{.ONESHELL} is provided, then only the first line of the
3793 recipe will be checked for the special prefix characters (@samp{@@},
3794 @samp{-}, and @samp{+}).  Subsequent lines will include the special
3795 characters in the recipe line when the @code{SHELL} is invoked.  If
3796 you want your recipe to start with one of these special characters
3797 you'll need to arrange for them to not be the first characters on the
3798 first line, perhaps by adding a comment or similar.  For example, this
3799 would be a syntax error in Perl because the first @samp{@@} is removed
3800 by make:
3802 @example
3803 .ONESHELL:
3804 SHELL = /usr/bin/perl
3805 .SHELLFLAGS = -e
3806 show :
3807         @@f = qw(a b c);
3808         print "@@f\n";
3809 @end example
3811 @noindent
3812 However, either of these alternatives would work properly:
3814 @example
3815 .ONESHELL:
3816 SHELL = /usr/bin/perl
3817 .SHELLFLAGS = -e
3818 show :
3819         # Make sure "@@" is not the first character on the first line
3820         @@f = qw(a b c);
3821         print "@@f\n";
3822 @end example
3824 @noindent
3827 @example
3828 .ONESHELL:
3829 SHELL = /usr/bin/perl
3830 .SHELLFLAGS = -e
3831 show :
3832         my @@f = qw(a b c);
3833         print "@@f\n";
3834 @end example
3836 As a special feature, if @code{SHELL} is determined to be a
3837 POSIX-style shell, the special prefix characters in ``internal''
3838 recipe lines will @emph{removed} before the recipe is processed.  This
3839 feature is intended to allow existing makefiles to add the
3840 @code{.ONESHELL} special target and still run properly without
3841 extensive modifications.  Since the special prefix characters are not
3842 legal at the beginning of a line in a POSIX shell script this is not a
3843 loss in functionality.  For example, this works as expected:
3845 @example
3846 .ONESHELL:
3847 foo : bar/lose
3848         @@cd $(@@D)
3849         @@gobble $(@@F) > ../$@@
3850 @end example
3852 Even with this special feature, however, makefiles with
3853 @code{.ONESHELL} will behave differently in ways that could be
3854 noticeable.  For example, normally if any line in the recipe fails,
3855 that causes the rule to fail and no more recipe lines are processed.
3856 Under @code{.ONESHELL} a failure of any but the final recipe line will
3857 not be noticed by @code{make}.  You can modify @code{.SHELLFLAGS} to
3858 add the @code{-e} option to the shell which will cause any failure
3859 anywhere in the command line to cause the shell to fail, but this
3860 could itself cause your recipe to behave differently.  Ultimately you
3861 may need to harden your recipe lines to allow them to work with
3862 @code{.ONESHELL}.
3864 @node Choosing the Shell,  , One Shell, Execution
3865 @subsection Choosing the Shell
3866 @cindex shell, choosing the
3867 @cindex @code{SHELL}, value of
3868 @cindex @code{.SHELLFLAGS}, value of
3870 @vindex SHELL
3871 @vindex .SHELLFLAGS
3872 The program used as the shell is taken from the variable @code{SHELL}.
3873 If this variable is not set in your makefile, the program
3874 @file{/bin/sh} is used as the shell.  The argument(s) passed to the
3875 shell are taken from the variable @code{.SHELLFLAGS}.  The default
3876 value of @code{.SHELLFLAGS} is @code{-c} normally, or @code{-ec} in
3877 POSIX-conforming mode.
3879 @cindex environment, @code{SHELL} in
3880 Unlike most variables, the variable @code{SHELL} is never set from the
3881 environment.  This is because the @code{SHELL} environment variable is
3882 used to specify your personal choice of shell program for interactive
3883 use.  It would be very bad for personal choices like this to affect the
3884 functioning of makefiles.  @xref{Environment, ,Variables from the
3885 Environment}.
3887 Furthermore, when you do set @code{SHELL} in your makefile that value
3888 is @emph{not} exported in the environment to recipe lines that
3889 @code{make} invokes.  Instead, the value inherited from the user's
3890 environment, if any, is exported.  You can override this behavior by
3891 explicitly exporting @code{SHELL} (@pxref{Variables/Recursion,
3892 ,Communicating Variables to a Sub-@code{make}}), forcing it to be
3893 passed in the environment to recipe lines.
3895 @vindex @code{MAKESHELL} @r{(MS-DOS alternative to @code{SHELL})}
3896 However, on MS-DOS and MS-Windows the value of @code{SHELL} in the
3897 environment @strong{is} used, since on those systems most users do not
3898 set this variable, and therefore it is most likely set specifically to
3899 be used by @code{make}.  On MS-DOS, if the setting of @code{SHELL} is
3900 not suitable for @code{make}, you can set the variable
3901 @code{MAKESHELL} to the shell that @code{make} should use; if set it
3902 will be used as the shell instead of the value of @code{SHELL}.
3904 @subsubheading Choosing a Shell in DOS and Windows
3905 @cindex shell, in DOS and Windows
3906 @cindex DOS, choosing a shell in
3907 @cindex Windows, choosing a shell in
3909 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3910 other systems.
3912 @vindex COMSPEC
3913 On MS-DOS, if @code{SHELL} is not set, the value of the variable
3914 @code{COMSPEC} (which is always set) is used instead.
3916 @cindex @code{SHELL}, MS-DOS specifics
3917 The processing of lines that set the variable @code{SHELL} in Makefiles
3918 is different on MS-DOS.  The stock shell, @file{command.com}, is
3919 ridiculously limited in its functionality and many users of @code{make}
3920 tend to install a replacement shell.  Therefore, on MS-DOS, @code{make}
3921 examines the value of @code{SHELL}, and changes its behavior based on
3922 whether it points to a Unix-style or DOS-style shell.  This allows
3923 reasonable functionality even if @code{SHELL} points to
3924 @file{command.com}.
3926 If @code{SHELL} points to a Unix-style shell, @code{make} on MS-DOS
3927 additionally checks whether that shell can indeed be found; if not, it
3928 ignores the line that sets @code{SHELL}.  In MS-DOS, GNU @code{make}
3929 searches for the shell in the following places:
3931 @enumerate
3932 @item
3933 In the precise place pointed to by the value of @code{SHELL}.  For
3934 example, if the makefile specifies @samp{SHELL = /bin/sh}, @code{make}
3935 will look in the directory @file{/bin} on the current drive.
3937 @item
3938 In the current directory.
3940 @item
3941 In each of the directories in the @code{PATH} variable, in order.
3943 @end enumerate
3945 In every directory it examines, @code{make} will first look for the
3946 specific file (@file{sh} in the example above).  If this is not found,
3947 it will also look in that directory for that file with one of the known
3948 extensions which identify executable files.  For example @file{.exe},
3949 @file{.com}, @file{.bat}, @file{.btm}, @file{.sh}, and some others.
3951 If any of these attempts is successful, the value of @code{SHELL} will
3952 be set to the full pathname of the shell as found.  However, if none of
3953 these is found, the value of @code{SHELL} will not be changed, and thus
3954 the line that sets it will be effectively ignored.  This is so
3955 @code{make} will only support features specific to a Unix-style shell if
3956 such a shell is actually installed on the system where @code{make} runs.
3958 Note that this extended search for the shell is limited to the cases
3959 where @code{SHELL} is set from the Makefile; if it is set in the
3960 environment or command line, you are expected to set it to the full
3961 pathname of the shell, exactly as things are on Unix.
3963 The effect of the above DOS-specific processing is that a Makefile that
3964 contains @samp{SHELL = /bin/sh} (as many Unix makefiles do), will work
3965 on MS-DOS unaltered if you have e.g.@: @file{sh.exe} installed in some
3966 directory along your @code{PATH}.
3968 @vindex SHELL
3969 @vindex .SHELLFLAGS
3971 @node Parallel, Errors, Execution, Recipes
3972 @section Parallel Execution
3973 @cindex recipes, execution in parallel
3974 @cindex parallel execution
3975 @cindex execution, in parallel
3976 @cindex job slots
3977 @cindex @code{-j}
3978 @cindex @code{--jobs}
3980 GNU @code{make} knows how to execute several recipes at once.
3981 Normally, @code{make} will execute only one recipe at a time, waiting
3982 for it to finish before executing the next.  However, the @samp{-j} or
3983 @samp{--jobs} option tells @code{make} to execute many recipes
3984 simultaneously.  You can inhibit parallelism in a particular makefile
3985 with the @code{.NOTPARALLEL} pseudo-target (@pxref{Special
3986 Targets,Special Built-in Target Names}).@refill
3988 On MS-DOS, the @samp{-j} option has no effect, since that system doesn't
3989 support multi-processing.
3991 If the @samp{-j} option is followed by an integer, this is the number of
3992 recipes to execute at once; this is called the number of @dfn{job slots}.
3993 If there is nothing looking like an integer after the @samp{-j} option,
3994 there is no limit on the number of job slots.  The default number of job
3995 slots is one, which means serial execution (one thing at a time).
3997 One unpleasant consequence of running several recipes simultaneously is
3998 that output generated by the recipes appears whenever each recipe
3999 sends it, so messages from different recipes may be interspersed.
4001 Another problem is that two processes cannot both take input from the
4002 same device; so to make sure that only one recipe tries to take input
4003 from the terminal at once, @code{make} will invalidate the standard
4004 input streams of all but one running recipe.  This means that
4005 attempting to read from standard input will usually be a fatal error (a
4006 @samp{Broken pipe} signal) for most child processes if there are
4007 several.
4008 @cindex broken pipe
4009 @cindex standard input
4011 It is unpredictable which recipe will have a valid standard input stream
4012 (which will come from the terminal, or wherever you redirect the standard
4013 input of @code{make}).  The first recipe run will always get it first, and
4014 the first recipe started after that one finishes will get it next, and so
4017 We will change how this aspect of @code{make} works if we find a better
4018 alternative.  In the mean time, you should not rely on any recipe using
4019 standard input at all if you are using the parallel execution feature; but
4020 if you are not using this feature, then standard input works normally in
4021 all recipes.
4023 Finally, handling recursive @code{make} invocations raises issues.  For
4024 more information on this, see
4025 @ref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
4027 If a recipe fails (is killed by a signal or exits with a nonzero
4028 status), and errors are not ignored for that recipe
4029 (@pxref{Errors, ,Errors in Recipes}),
4030 the remaining recipe lines to remake the same target will not be run.
4031 If a recipe fails and the @samp{-k} or @samp{--keep-going}
4032 option was not given
4033 (@pxref{Options Summary, ,Summary of Options}),
4034 @code{make} aborts execution.  If make
4035 terminates for any reason (including a signal) with child processes
4036 running, it waits for them to finish before actually exiting.@refill
4038 @cindex load average
4039 @cindex limiting jobs based on load
4040 @cindex jobs, limiting based on load
4041 @cindex @code{-l} (load average)
4042 @cindex @code{--max-load}
4043 @cindex @code{--load-average}
4044 When the system is heavily loaded, you will probably want to run fewer jobs
4045 than when it is lightly loaded.  You can use the @samp{-l} option to tell
4046 @code{make} to limit the number of jobs to run at once, based on the load
4047 average.  The @samp{-l} or @samp{--max-load}
4048 option is followed by a floating-point number.  For
4049 example,
4051 @example
4052 -l 2.5
4053 @end example
4055 @noindent
4056 will not let @code{make} start more than one job if the load average is
4057 above 2.5.  The @samp{-l} option with no following number removes the
4058 load limit, if one was given with a previous @samp{-l} option.@refill
4060 More precisely, when @code{make} goes to start up a job, and it already has
4061 at least one job running, it checks the current load average; if it is not
4062 lower than the limit given with @samp{-l}, @code{make} waits until the load
4063 average goes below that limit, or until all the other jobs finish.
4065 By default, there is no load limit.
4067 @node Errors, Interrupts, Parallel, Recipes
4068 @section Errors in Recipes
4069 @cindex errors (in recipes)
4070 @cindex recipes, errors in
4071 @cindex exit status (errors)
4073 After each shell invocation returns, @code{make} looks at its exit
4074 status.  If the shell completed successfully (the exit status is
4075 zero), the next line in the recipe is executed in a new shell; after
4076 the last line is finished, the rule is finished.
4078 If there is an error (the exit status is nonzero), @code{make} gives up on
4079 the current rule, and perhaps on all rules.
4081 Sometimes the failure of a certain recipe line does not indicate a problem.
4082 For example, you may use the @code{mkdir} command to ensure that a
4083 directory exists.  If the directory already exists, @code{mkdir} will
4084 report an error, but you probably want @code{make} to continue regardless.
4086 @cindex @code{-} (in recipes)
4087 To ignore errors in a recipe line, write a @samp{-} at the beginning
4088 of the line's text (after the initial tab).  The @samp{-} is discarded
4089 before the line is passed to the shell for execution.
4091 For example,
4093 @example
4094 @group
4095 clean:
4096         -rm -f *.o
4097 @end group
4098 @end example
4099 @cindex @code{rm} (shell command)
4101 @noindent
4102 This causes @code{make} to continue even if @code{rm} is unable to
4103 remove a file.
4105 @cindex @code{-i}
4106 @cindex @code{--ignore-errors}
4107 @findex .IGNORE
4108 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
4109 flag, errors are ignored in all recipes of all rules.  A rule in the
4110 makefile for the special target @code{.IGNORE} has the same effect, if
4111 there are no prerequisites.  These ways of ignoring errors are obsolete
4112 because @samp{-} is more flexible.
4114 When errors are to be ignored, because of either a @samp{-} or the
4115 @samp{-i} flag, @code{make} treats an error return just like success,
4116 except that it prints out a message that tells you the status code
4117 the shell exited with, and says that the error has been ignored.
4119 When an error happens that @code{make} has not been told to ignore,
4120 it implies that the current target cannot be correctly remade, and neither
4121 can any other that depends on it either directly or indirectly.  No further
4122 recipes will be executed for these targets, since their preconditions
4123 have not been achieved.
4126 @cindex @code{-k}
4127 @cindex @code{--keep-going}
4128 Normally @code{make} gives up immediately in this circumstance, returning a
4129 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
4130 flag is specified, @code{make}
4131 continues to consider the other prerequisites of the pending targets,
4132 remaking them if necessary, before it gives up and returns nonzero status.
4133 For example, after an error in compiling one object file, @samp{make -k}
4134 will continue compiling other object files even though it already knows
4135 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
4137 The usual behavior assumes that your purpose is to get the specified
4138 targets up to date; once @code{make} learns that this is impossible, it
4139 might as well report the failure immediately.  The @samp{-k} option says
4140 that the real purpose is to test as many of the changes made in the
4141 program as possible, perhaps to find several independent problems so
4142 that you can correct them all before the next attempt to compile.  This
4143 is why Emacs' @code{compile} command passes the @samp{-k} flag by
4144 default.
4145 @cindex Emacs (@code{M-x compile})
4147 @findex .DELETE_ON_ERROR
4148 @cindex deletion of target files
4149 @cindex removal of target files
4150 @cindex target, deleting on error
4151 Usually when a recipe line fails, if it has changed the target file at all,
4152 the file is corrupted and cannot be used---or at least it is not
4153 completely updated.  Yet the file's time stamp says that it is now up to
4154 date, so the next time @code{make} runs, it will not try to update that
4155 file.  The situation is just the same as when the shell is killed by a
4156 signal; @pxref{Interrupts}.  So generally the right thing to do is to
4157 delete the target file if the recipe fails after beginning to change
4158 the file.  @code{make} will do this if @code{.DELETE_ON_ERROR} appears
4159 as a target.  This is almost always what you want @code{make} to do, but
4160 it is not historical practice; so for compatibility, you must explicitly
4161 request it.
4163 @node Interrupts, Recursion, Errors, Recipes
4164 @section Interrupting or Killing @code{make}
4165 @cindex interrupt
4166 @cindex signal
4167 @cindex deletion of target files
4168 @cindex removal of target files
4169 @cindex target, deleting on interrupt
4170 @cindex killing (interruption)
4172 If @code{make} gets a fatal signal while a shell is executing, it may
4173 delete the target file that the recipe was supposed to update.  This is
4174 done if the target file's last-modification time has changed since
4175 @code{make} first checked it.
4177 The purpose of deleting the target is to make sure that it is remade from
4178 scratch when @code{make} is next run.  Why is this?  Suppose you type
4179 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
4180 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
4181 in an incomplete file whose last-modification time is newer than the source
4182 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
4183 and deletes this incomplete file.  If @code{make} did not do this, the next
4184 invocation of @code{make} would think that @file{foo.o} did not require
4185 updating---resulting in a strange error message from the linker when it
4186 tries to link an object file half of which is missing.
4188 @findex .PRECIOUS
4189 You can prevent the deletion of a target file in this way by making the
4190 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
4191 @code{make} checks to see whether it appears on the prerequisites of
4192 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
4193 if a signal happens.  Some reasons why you might do this are that the
4194 target is updated in some atomic fashion, or exists only to record a
4195 modification-time (its contents do not matter), or must exist at all
4196 times to prevent other sorts of trouble.
4198 @node Recursion, Canned Recipes, Interrupts, Recipes
4199 @section Recursive Use of @code{make}
4200 @cindex recursion
4201 @cindex subdirectories, recursion for
4203 Recursive use of @code{make} means using @code{make} as a command in a
4204 makefile.  This technique is useful when you want separate makefiles for
4205 various subsystems that compose a larger system.  For example, suppose you
4206 have a sub-directory @file{subdir} which has its own makefile, and you would
4207 like the containing directory's makefile to run @code{make} on the
4208 sub-directory.  You can do it by writing this:
4210 @example
4211 subsystem:
4212         cd subdir && $(MAKE)
4213 @end example
4215 @noindent
4216 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
4218 @example
4219 subsystem:
4220         $(MAKE) -C subdir
4221 @end example
4222 @cindex @code{-C}
4223 @cindex @code{--directory}
4225 You can write recursive @code{make} commands just by copying this example,
4226 but there are many things to know about how they work and why, and about
4227 how the sub-@code{make} relates to the top-level @code{make}.  You may
4228 also find it useful to declare targets that invoke recursive
4229 @code{make} commands as @samp{.PHONY} (for more discussion on when
4230 this is useful, see @ref{Phony Targets}).
4232 @vindex @code{CURDIR}
4233 For your convenience, when GNU @code{make} starts (after it has
4234 processed any @code{-C} options) it sets the variable @code{CURDIR} to
4235 the pathname of the current working directory.  This value is never
4236 touched by @code{make} again: in particular note that if you include
4237 files from other directories the value of @code{CURDIR} does not
4238 change.  The value has the same precedence it would have if it were
4239 set in the makefile (by default, an environment variable @code{CURDIR}
4240 will not override this value).  Note that setting this variable has no
4241 impact on the operation of @code{make} (it does not cause @code{make}
4242 to change its working directory, for example).
4244 @menu
4245 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
4246 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
4247 * Options/Recursion::           How to communicate options to a sub-@code{make}.
4248 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
4249                                   helps debug use of recursive @code{make} commands.
4250 @end menu
4252 @node MAKE Variable, Variables/Recursion, Recursion, Recursion
4253 @subsection How the @code{MAKE} Variable Works
4254 @vindex MAKE
4255 @cindex recursion, and @code{MAKE} variable
4257 Recursive @code{make} commands should always use the variable @code{MAKE},
4258 not the explicit command name @samp{make}, as shown here:
4260 @example
4261 @group
4262 subsystem:
4263         cd subdir && $(MAKE)
4264 @end group
4265 @end example
4267 The value of this variable is the file name with which @code{make} was
4268 invoked.  If this file name was @file{/bin/make}, then the recipe executed
4269 is @samp{cd subdir && /bin/make}.  If you use a special version of
4270 @code{make} to run the top-level makefile, the same special version will be
4271 executed for recursive invocations.
4272 @cindex @code{cd} (shell command)
4274 @cindex +, and recipes
4275 As a special feature, using the variable @code{MAKE} in the recipe of
4276 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
4277 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
4278 Using the @code{MAKE} variable has the same effect as using a @samp{+}
4279 character at the beginning of the recipe line.  @xref{Instead of
4280 Execution, ,Instead of Executing the Recipes}.  This special feature
4281 is only enabled if the @code{MAKE} variable appears directly in the
4282 recipe: it does not apply if the @code{MAKE} variable is referenced
4283 through expansion of another variable.  In the latter case you must
4284 use the @samp{+} token to get these special effects.@refill
4286 Consider the command @samp{make -t} in the above example.  (The
4287 @samp{-t} option marks targets as up to date without actually running
4288 any recipes; see @ref{Instead of Execution}.)  Following the usual
4289 definition of @samp{-t}, a @samp{make -t} command in the example would
4290 create a file named @file{subsystem} and do nothing else.  What you
4291 really want it to do is run @samp{@w{cd subdir &&} @w{make -t}}; but
4292 that would require executing the recipe, and @samp{-t} says not to
4293 execute recipes.@refill
4294 @cindex @code{-t}, and recursion
4295 @cindex recursion, and @code{-t}
4296 @cindex @code{--touch}, and recursion
4298 The special feature makes this do what you want: whenever a recipe
4299 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
4300 @samp{-n} and @samp{-q} do not apply to that line.  Recipe lines
4301 containing @code{MAKE} are executed normally despite the presence of a
4302 flag that causes most recipes not to be run.  The usual
4303 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
4304 (@pxref{Options/Recursion, ,Communicating Options to a
4305 Sub-@code{make}}), so your request to touch the files, or print the
4306 recipes, is propagated to the subsystem.@refill
4308 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
4309 @subsection Communicating Variables to a Sub-@code{make}
4310 @cindex sub-@code{make}
4311 @cindex environment, and recursion
4312 @cindex exporting variables
4313 @cindex variables, environment
4314 @cindex variables, exporting
4315 @cindex recursion, and environment
4316 @cindex recursion, and variables
4318 Variable values of the top-level @code{make} can be passed to the
4319 sub-@code{make} through the environment by explicit request.  These
4320 variables are defined in the sub-@code{make} as defaults, but they do
4321 not override variables defined in the makefile used by
4322 the sub-@code{make} unless you use the @samp{-e} switch (@pxref{Options
4323 Summary, ,Summary of Options}).@refill
4325 To pass down, or @dfn{export}, a variable, @code{make} adds the
4326 variable and its value to the environment for running each line of the
4327 recipe.  The sub-@code{make}, in turn, uses the environment to
4328 initialize its table of variable values.  @xref{Environment,
4329 ,Variables from the Environment}.
4331 Except by explicit request, @code{make} exports a variable only if it
4332 is either defined in the environment initially or set on the command
4333 line, and if its name consists only of letters, numbers, and underscores.
4334 Some shells cannot cope with environment variable names consisting of
4335 characters other than letters, numbers, and underscores.
4337 @cindex SHELL, exported value
4338 The value of the @code{make} variable @code{SHELL} is not exported.
4339 Instead, the value of the @code{SHELL} variable from the invoking
4340 environment is passed to the sub-@code{make}.  You can force
4341 @code{make} to export its value for @code{SHELL} by using the
4342 @code{export} directive, described below.  @xref{Choosing the Shell}.
4344 The special variable @code{MAKEFLAGS} is always exported (unless you
4345 unexport it).  @code{MAKEFILES} is exported if you set it to anything.
4347 @code{make} automatically passes down variable values that were defined
4348 on the command line, by putting them in the @code{MAKEFLAGS} variable.
4349 @iftex
4350 See the next section.
4351 @end iftex
4352 @ifnottex
4353 @xref{Options/Recursion}.
4354 @end ifnottex
4356 Variables are @emph{not} normally passed down if they were created by
4357 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
4358 Implicit Rules}).  The sub-@code{make} will define these for
4359 itself.@refill
4361 @findex export
4362 If you want to export specific variables to a sub-@code{make}, use the
4363 @code{export} directive, like this:
4365 @example
4366 export @var{variable} @dots{}
4367 @end example
4369 @noindent
4370 @findex unexport
4371 If you want to @emph{prevent} a variable from being exported, use the
4372 @code{unexport} directive, like this:
4374 @example
4375 unexport @var{variable} @dots{}
4376 @end example
4378 @noindent
4379 In both of these forms, the arguments to @code{export} and
4380 @code{unexport} are expanded, and so could be variables or functions
4381 which expand to a (list of) variable names to be (un)exported.
4383 As a convenience, you can define a variable and export it at the same
4384 time by doing:
4386 @example
4387 export @var{variable} = value
4388 @end example
4390 @noindent
4391 has the same result as:
4393 @example
4394 @var{variable} = value
4395 export @var{variable}
4396 @end example
4398 @noindent
4401 @example
4402 export @var{variable} := value
4403 @end example
4405 @noindent
4406 has the same result as:
4408 @example
4409 @var{variable} := value
4410 export @var{variable}
4411 @end example
4413 Likewise,
4415 @example
4416 export @var{variable} += value
4417 @end example
4419 @noindent
4420 is just like:
4422 @example
4423 @var{variable} += value
4424 export @var{variable}
4425 @end example
4427 @noindent
4428 @xref{Appending, ,Appending More Text to Variables}.
4430 You may notice that the @code{export} and @code{unexport} directives
4431 work in @code{make} in the same way they work in the shell, @code{sh}.
4433 If you want all variables to be exported by default, you can use
4434 @code{export} by itself:
4436 @example
4437 export
4438 @end example
4440 @noindent
4441 This tells @code{make} that variables which are not explicitly mentioned
4442 in an @code{export} or @code{unexport} directive should be exported.
4443 Any variable given in an @code{unexport} directive will still @emph{not}
4444 be exported.  If you use @code{export} by itself to export variables by
4445 default, variables whose names contain characters other than
4446 alphanumerics and underscores will not be exported unless specifically
4447 mentioned in an @code{export} directive.@refill
4449 @findex .EXPORT_ALL_VARIABLES
4450 The behavior elicited by an @code{export} directive by itself was the
4451 default in older versions of GNU @code{make}.  If your makefiles depend
4452 on this behavior and you want to be compatible with old versions of
4453 @code{make}, you can write a rule for the special target
4454 @code{.EXPORT_ALL_VARIABLES} instead of using the @code{export} directive.
4455 This will be ignored by old @code{make}s, while the @code{export}
4456 directive will cause a syntax error.@refill
4457 @cindex compatibility in exporting
4459 Likewise, you can use @code{unexport} by itself to tell @code{make}
4460 @emph{not} to export variables by default.  Since this is the default
4461 behavior, you would only need to do this if @code{export} had been used
4462 by itself earlier (in an included makefile, perhaps).  You
4463 @strong{cannot} use @code{export} and @code{unexport} by themselves to
4464 have variables exported for some recipes and not for others.  The last
4465 @code{export} or @code{unexport} directive that appears by itself
4466 determines the behavior for the entire run of @code{make}.@refill
4468 @vindex MAKELEVEL
4469 @cindex recursion, level of
4470 As a special feature, the variable @code{MAKELEVEL} is changed when it
4471 is passed down from level to level.  This variable's value is a string
4472 which is the depth of the level as a decimal number.  The value is
4473 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
4474 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
4475 happens when @code{make} sets up the environment for a recipe.@refill
4477 The main use of @code{MAKELEVEL} is to test it in a conditional
4478 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
4479 way you can write a makefile that behaves one way if run recursively and
4480 another way if run directly by you.@refill
4482 @vindex MAKEFILES
4483 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
4484 commands to use additional makefiles.  The value of @code{MAKEFILES} is
4485 a whitespace-separated list of file names.  This variable, if defined in
4486 the outer-level makefile, is passed down through the environment; then
4487 it serves as a list of extra makefiles for the sub-@code{make} to read
4488 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
4489 Variable @code{MAKEFILES}}.@refill
4491 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
4492 @subsection Communicating Options to a Sub-@code{make}
4493 @cindex options, and recursion
4494 @cindex recursion, and options
4496 @vindex MAKEFLAGS
4497 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
4498 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
4499 set up automatically by @code{make} to contain the flag letters that
4500 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
4501 @code{MAKEFLAGS} gets the value @samp{ks}.@refill
4503 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
4504 in its environment.  In response, it takes the flags from that value and
4505 processes them as if they had been given as arguments.
4506 @xref{Options Summary, ,Summary of Options}.
4508 @cindex command line variable definitions, and recursion
4509 @cindex variables, command line, and recursion
4510 @cindex recursion, and command line variable definitions
4511 Likewise variables defined on the command line are passed to the
4512 sub-@code{make} through @code{MAKEFLAGS}.  Words in the value of
4513 @code{MAKEFLAGS} that contain @samp{=}, @code{make} treats as variable
4514 definitions just as if they appeared on the command line.
4515 @xref{Overriding, ,Overriding Variables}.
4517 @cindex @code{-C}, and recursion
4518 @cindex @code{-f}, and recursion
4519 @cindex @code{-o}, and recursion
4520 @cindex @code{-W}, and recursion
4521 @cindex @code{--directory}, and recursion
4522 @cindex @code{--file}, and recursion
4523 @cindex @code{--old-file}, and recursion
4524 @cindex @code{--assume-old}, and recursion
4525 @cindex @code{--assume-new}, and recursion
4526 @cindex @code{--new-file}, and recursion
4527 @cindex recursion, and @code{-C}
4528 @cindex recursion, and @code{-f}
4529 @cindex recursion, and @code{-o}
4530 @cindex recursion, and @code{-W}
4531 The options @samp{-C}, @samp{-f}, @samp{-o}, and @samp{-W} are not put
4532 into @code{MAKEFLAGS}; these options are not passed down.@refill
4534 @cindex @code{-j}, and recursion
4535 @cindex @code{--jobs}, and recursion
4536 @cindex recursion, and @code{-j}
4537 @cindex job slots, and recursion
4538 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
4539 If you set it to some numeric value @samp{N} and your operating system
4540 supports it (most any UNIX system will; others typically won't), the
4541 parent @code{make} and all the sub-@code{make}s will communicate to
4542 ensure that there are only @samp{N} jobs running at the same time
4543 between them all.  Note that any job that is marked recursive
4544 (@pxref{Instead of Execution, ,Instead of Executing Recipes})
4545 doesn't count against the total jobs (otherwise we could get @samp{N}
4546 sub-@code{make}s running and have no slots left over for any real work!)
4548 If your operating system doesn't support the above communication, then
4549 @samp{-j 1} is always put into @code{MAKEFLAGS} instead of the value you
4550 specified.  This is because if the @w{@samp{-j}} option were passed down
4551 to sub-@code{make}s, you would get many more jobs running in parallel
4552 than you asked for.  If you give @samp{-j} with no numeric argument,
4553 meaning to run as many jobs as possible in parallel, this is passed
4554 down, since multiple infinities are no more than one.@refill
4556 If you do not want to pass the other flags down, you must change the
4557 value of @code{MAKEFLAGS}, like this:
4559 @example
4560 subsystem:
4561         cd subdir && $(MAKE) MAKEFLAGS=
4562 @end example
4564 @vindex MAKEOVERRIDES
4565 The command line variable definitions really appear in the variable
4566 @code{MAKEOVERRIDES}, and @code{MAKEFLAGS} contains a reference to this
4567 variable.  If you do want to pass flags down normally, but don't want to
4568 pass down the command line variable definitions, you can reset
4569 @code{MAKEOVERRIDES} to empty, like this:
4571 @example
4572 MAKEOVERRIDES =
4573 @end example
4575 @noindent
4576 @cindex Arg list too long
4577 @cindex E2BIG
4578 This is not usually useful to do.  However, some systems have a small
4579 fixed limit on the size of the environment, and putting so much
4580 information into the value of @code{MAKEFLAGS} can exceed it.  If you
4581 see the error message @samp{Arg list too long}, this may be the problem.
4582 @findex .POSIX
4583 @cindex POSIX.2
4584 (For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
4585 not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
4586 in the makefile.  You probably do not care about this.)
4588 @vindex MFLAGS
4589 A similar variable @code{MFLAGS} exists also, for historical
4590 compatibility.  It has the same value as @code{MAKEFLAGS} except that it
4591 does not contain the command line variable definitions, and it always
4592 begins with a hyphen unless it is empty (@code{MAKEFLAGS} begins with a
4593 hyphen only when it begins with an option that has no single-letter
4594 version, such as @samp{--warn-undefined-variables}).  @code{MFLAGS} was
4595 traditionally used explicitly in the recursive @code{make} command, like
4596 this:
4598 @example
4599 subsystem:
4600         cd subdir && $(MAKE) $(MFLAGS)
4601 @end example
4603 @noindent
4604 but now @code{MAKEFLAGS} makes this usage redundant.  If you want your
4605 makefiles to be compatible with old @code{make} programs, use this
4606 technique; it will work fine with more modern @code{make} versions too.
4608 @cindex setting options from environment
4609 @cindex options, setting from environment
4610 @cindex setting options in makefiles
4611 @cindex options, setting in makefiles
4612 The @code{MAKEFLAGS} variable can also be useful if you want to have
4613 certain options, such as @samp{-k} (@pxref{Options Summary, ,Summary of
4614 Options}), set each time you run @code{make}.  You simply put a value for
4615 @code{MAKEFLAGS} in your environment.  You can also set @code{MAKEFLAGS} in
4616 a makefile, to specify additional flags that should also be in effect for
4617 that makefile.  (Note that you cannot use @code{MFLAGS} this way.  That
4618 variable is set only for compatibility; @code{make} does not interpret a
4619 value you set for it in any way.)
4621 When @code{make} interprets the value of @code{MAKEFLAGS} (either from the
4622 environment or from a makefile), it first prepends a hyphen if the value
4623 does not already begin with one.  Then it chops the value into words
4624 separated by blanks, and parses these words as if they were options given
4625 on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
4626 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
4627 is no error for an invalid option).
4629 If you do put @code{MAKEFLAGS} in your environment, you should be sure not
4630 to include any options that will drastically affect the actions of
4631 @code{make} and undermine the purpose of makefiles and of @code{make}
4632 itself.  For instance, the @samp{-t}, @samp{-n}, and @samp{-q} options, if
4633 put in one of these variables, could have disastrous consequences and would
4634 certainly have at least surprising and probably annoying effects.@refill
4636 @node -w Option,  , Options/Recursion, Recursion
4637 @subsection The @samp{--print-directory} Option
4638 @cindex directories, printing them
4639 @cindex printing directories
4640 @cindex recursion, and printing directories
4642 If you use several levels of recursive @code{make} invocations, the
4643 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
4644 lot easier to understand by showing each directory as @code{make}
4645 starts processing it and as @code{make} finishes processing it.  For
4646 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
4647 @code{make} will print a line of the form:@refill
4649 @example
4650 make: Entering directory `/u/gnu/make'.
4651 @end example
4653 @noindent
4654 before doing anything else, and a line of the form:
4656 @example
4657 make: Leaving directory `/u/gnu/make'.
4658 @end example
4660 @noindent
4661 when processing is completed.
4663 @cindex @code{-C}, and @code{-w}
4664 @cindex @code{--directory}, and @code{--print-directory}
4665 @cindex recursion, and @code{-w}
4666 @cindex @code{-w}, and @code{-C}
4667 @cindex @code{-w}, and recursion
4668 @cindex @code{--print-directory}, and @code{--directory}
4669 @cindex @code{--print-directory}, and recursion
4670 @cindex @code{--no-print-directory}
4671 @cindex @code{--print-directory}, disabling
4672 @cindex @code{-w}, disabling
4673 Normally, you do not need to specify this option because @samp{make}
4674 does it for you: @samp{-w} is turned on automatically when you use the
4675 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
4676 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
4677 be silent, or if you use @samp{--no-print-directory} to explicitly
4678 disable it.
4680 @node Canned Recipes, Empty Recipes, Recursion, Recipes
4681 @section Defining Canned Recipes
4682 @cindex canned recipes
4683 @cindex recipes, canned
4684 @cindex sequences of commands
4685 @cindex commands, sequences of
4687 When the same sequence of commands is useful in making various
4688 targets, you can define it as a canned sequence with the @code{define}
4689 directive, and refer to the canned sequence from the recipes for those
4690 targets.  The canned sequence is actually a variable, so the name must
4691 not conflict with other variable names.
4693 Here is an example of defining a canned recipe:
4695 @example
4696 define run-yacc =
4697 yacc $(firstword $^)
4698 mv y.tab.c $@@
4699 endef
4700 @end example
4701 @cindex @code{yacc}
4703 @noindent
4704 Here @code{run-yacc} is the name of the variable being defined;
4705 @code{endef} marks the end of the definition; the lines in between are the
4706 commands.  The @code{define} directive does not expand variable references
4707 and function calls in the canned sequence; the @samp{$} characters,
4708 parentheses, variable names, and so on, all become part of the value of the
4709 variable you are defining.
4710 @xref{Multi-Line, ,Defining Multi-Line Variables},
4711 for a complete explanation of @code{define}.
4713 The first command in this example runs Yacc on the first prerequisite of
4714 whichever rule uses the canned sequence.  The output file from Yacc is
4715 always named @file{y.tab.c}.  The second command moves the output to the
4716 rule's target file name.
4718 To use the canned sequence, substitute the variable into the recipe of a
4719 rule.  You can substitute it like any other variable
4720 (@pxref{Reference, ,Basics of Variable References}).
4721 Because variables defined by @code{define} are recursively expanded
4722 variables, all the variable references you wrote inside the @code{define}
4723 are expanded now.  For example:
4725 @example
4726 foo.c : foo.y
4727         $(run-yacc)
4728 @end example
4730 @noindent
4731 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
4732 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.@refill
4734 This is a realistic example, but this particular one is not needed in
4735 practice because @code{make} has an implicit rule to figure out these
4736 commands based on the file names involved
4737 (@pxref{Implicit Rules, ,Using Implicit Rules}).
4739 @cindex @@, and @code{define}
4740 @cindex -, and @code{define}
4741 @cindex +, and @code{define}
4742 In recipe execution, each line of a canned sequence is treated just as
4743 if the line appeared on its own in the rule, preceded by a tab.  In
4744 particular, @code{make} invokes a separate sub-shell for each line.  You
4745 can use the special prefix characters that affect command lines
4746 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
4747 @xref{Recipes, ,Writing Recipes in Rules}.
4748 For example, using this canned sequence:
4750 @example
4751 define frobnicate =
4752 @@echo "frobnicating target $@@"
4753 frob-step-1 $< -o $@@-step-1
4754 frob-step-2 $@@-step-1 -o $@@
4755 endef
4756 @end example
4758 @noindent
4759 @code{make} will not echo the first line, the @code{echo} command.
4760 But it @emph{will} echo the following two recipe lines.
4762 On the other hand, prefix characters on the recipe line that refers to
4763 a canned sequence apply to every line in the sequence.  So the rule:
4765 @example
4766 frob.out: frob.in
4767         @@$(frobnicate)
4768 @end example
4770 @noindent
4771 does not echo @emph{any} recipe lines.
4772 (@xref{Echoing, ,Recipe Echoing}, for a full explanation of @samp{@@}.)
4774 @node Empty Recipes,  , Canned Recipes, Recipes
4775 @section Using Empty Recipes
4776 @cindex empty recipes
4777 @cindex recipes, empty
4779 It is sometimes useful to define recipes which do nothing.  This is done
4780 simply by giving a recipe that consists of nothing but whitespace.  For
4781 example:
4783 @example
4784 target: ;
4785 @end example
4787 @noindent
4788 defines an empty recipe for @file{target}.  You could also use a line
4789 beginning with a recipe prefix character to define an empty recipe,
4790 but this would be confusing because such a line looks empty.
4792 @findex .DEFAULT@r{, and empty recipes}
4793 You may be wondering why you would want to define a recipe that
4794 does nothing.  The only reason this is useful is to prevent a target
4795 from getting implicit recipes (from implicit rules or the
4796 @code{.DEFAULT} special target; @pxref{Implicit Rules} and
4797 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
4799 @c !!! another reason is for canonical stamp files:
4800 @ignore
4801 @example
4802 foo: stamp-foo ;
4803 stamp-foo: foo.in
4804         create foo frm foo.in
4805         touch $@
4806 @end example
4807 @end ignore
4809 You may be inclined to define empty recipes for targets that are
4810 not actual files, but only exist so that their prerequisites can be
4811 remade.  However, this is not the best way to do that, because the
4812 prerequisites may not be remade properly if the target file actually does exist.
4813 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
4815 @node Using Variables, Conditionals, Recipes, Top
4816 @chapter How to Use Variables
4817 @cindex variable
4818 @cindex value
4819 @cindex recursive variable expansion
4820 @cindex simple variable expansion
4822 A @dfn{variable} is a name defined in a makefile to represent a string
4823 of text, called the variable's @dfn{value}.  These values are
4824 substituted by explicit request into targets, prerequisites, recipes,
4825 and other parts of the makefile.  (In some other versions of @code{make},
4826 variables are called @dfn{macros}.)
4827 @cindex macro
4829 Variables and functions in all parts of a makefile are expanded when
4830 read, except for in recipes, the right-hand sides of variable
4831 definitions using @samp{=}, and the bodies of variable definitions
4832 using the @code{define} directive.@refill
4834 Variables can represent lists of file names, options to pass to compilers,
4835 programs to run, directories to look in for source files, directories to
4836 write output in, or anything else you can imagine.
4838 A variable name may be any sequence of characters not containing
4839 @samp{:}, @samp{#}, @samp{=}, or whitespace.  However, variable names
4840 containing characters other than letters, numbers, and underscores
4841 should be considered carefully, as in some shells they cannot be
4842 passed through the environment to a sub-@code{make}
4843 (@pxref{Variables/Recursion, ,Communicating Variables to a
4844 Sub-@code{make}}).  Variable names beginning with @samp{.} and an
4845 uppercase letter may be given special meaning in future versions of
4846 @code{make}.
4848 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
4849 and @samp{Foo} all refer to different variables.
4851 It is traditional to use upper case letters in variable names, but we
4852 recommend using lower case letters for variable names that serve internal
4853 purposes in the makefile, and reserving upper case for parameters that
4854 control implicit rules or for parameters that the user should override with
4855 command options (@pxref{Overriding, ,Overriding Variables}).
4857 A few variables have names that are a single punctuation character or
4858 just a few characters.  These are the @dfn{automatic variables}, and
4859 they have particular specialized uses.  @xref{Automatic Variables}.
4861 @menu
4862 * Reference::                   How to use the value of a variable.
4863 * Flavors::                     Variables come in two flavors.
4864 * Advanced::                    Advanced features for referencing a variable.
4865 * Values::                      All the ways variables get their values.
4866 * Setting::                     How to set a variable in the makefile.
4867 * Appending::                   How to append more text to the old value
4868                                   of a variable.
4869 * Override Directive::          How to set a variable in the makefile even if
4870                                   the user has set it with a command argument.
4871 * Multi-Line::                  An alternate way to set a variable
4872                                   to a multi-line string.
4873 * Undefine Directive::          How to undefine a variable so that it appears
4874                                   as if it was never set.
4875 * Environment::                 Variable values can come from the environment.
4876 * Target-specific::             Variable values can be defined on a per-target
4877                                   basis.
4878 * Pattern-specific::            Target-specific variable values can be applied
4879                                   to a group of targets that match a pattern.
4880 * Suppressing Inheritance::     Suppress inheritance of variables.
4881 * Special Variables::           Variables with special meaning or behavior.
4882 @end menu
4884 @node Reference, Flavors, Using Variables, Using Variables
4885 @section Basics of Variable References
4886 @cindex variables, how to reference
4887 @cindex reference to variables
4888 @cindex @code{$}, in variable reference
4889 @cindex dollar sign (@code{$}), in variable reference
4891 To substitute a variable's value, write a dollar sign followed by the name
4892 of the variable in parentheses or braces: either @samp{$(foo)} or
4893 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
4894 special significance of @samp{$} is why you must write @samp{$$} to have
4895 the effect of a single dollar sign in a file name or recipe.
4897 Variable references can be used in any context: targets, prerequisites,
4898 recipes, most directives, and new variable values.  Here is an
4899 example of a common case, where a variable holds the names of all the
4900 object files in a program:
4902 @example
4903 @group
4904 objects = program.o foo.o utils.o
4905 program : $(objects)
4906         cc -o program $(objects)
4908 $(objects) : defs.h
4909 @end group
4910 @end example
4912 Variable references work by strict textual substitution.  Thus, the rule
4914 @example
4915 @group
4916 foo = c
4917 prog.o : prog.$(foo)
4918         $(foo)$(foo) -$(foo) prog.$(foo)
4919 @end group
4920 @end example
4922 @noindent
4923 could be used to compile a C program @file{prog.c}.  Since spaces before
4924 the variable value are ignored in variable assignments, the value of
4925 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
4926 this way!)
4928 A dollar sign followed by a character other than a dollar sign,
4929 open-parenthesis or open-brace treats that single character as the
4930 variable name.  Thus, you could reference the variable @code{x} with
4931 @samp{$x}.  However, this practice is strongly discouraged, except in
4932 the case of the automatic variables (@pxref{Automatic Variables}).
4934 @node Flavors, Advanced, Reference, Using Variables
4935 @section The Two Flavors of Variables
4936 @cindex flavors of variables
4937 @cindex recursive variable expansion
4938 @cindex variables, flavors
4939 @cindex recursively expanded variables
4940 @cindex variables, recursively expanded
4942 There are two ways that a variable in GNU @code{make} can have a value;
4943 we call them the two @dfn{flavors} of variables.  The two flavors are
4944 distinguished in how they are defined and in what they do when expanded.
4946 @cindex =
4947 The first flavor of variable is a @dfn{recursively expanded} variable.
4948 Variables of this sort are defined by lines using @samp{=}
4949 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
4950 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).  The value you specify
4951 is installed verbatim; if it contains references to other variables,
4952 these references are expanded whenever this variable is substituted (in
4953 the course of expanding some other string).  When this happens, it is
4954 called @dfn{recursive expansion}.@refill
4956 For example,
4958 @example
4959 foo = $(bar)
4960 bar = $(ugh)
4961 ugh = Huh?
4963 all:;echo $(foo)
4964 @end example
4966 @noindent
4967 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
4968 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
4970 This flavor of variable is the only sort supported by other versions of
4971 @code{make}.  It has its advantages and its disadvantages.  An advantage
4972 (most would say) is that:
4974 @example
4975 CFLAGS = $(include_dirs) -O
4976 include_dirs = -Ifoo -Ibar
4977 @end example
4979 @noindent
4980 will do what was intended: when @samp{CFLAGS} is expanded in a recipe,
4981 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
4982 cannot append something on the end of a variable, as in
4984 @example
4985 CFLAGS = $(CFLAGS) -O
4986 @end example
4988 @noindent
4989 because it will cause an infinite loop in the variable expansion.
4990 (Actually @code{make} detects the infinite loop and reports an error.)
4991 @cindex loops in variable expansion
4992 @cindex variables, loops in expansion
4994 Another disadvantage is that any functions
4995 (@pxref{Functions, ,Functions for Transforming Text})
4996 referenced in the definition will be executed every time the variable is
4997 expanded.  This makes @code{make} run slower; worse, it causes the
4998 @code{wildcard} and @code{shell} functions to give unpredictable results
4999 because you cannot easily control when they are called, or even how many
5000 times.
5002 To avoid all the problems and inconveniences of recursively expanded
5003 variables, there is another flavor: simply expanded variables.
5005 @cindex simply expanded variables
5006 @cindex variables, simply expanded
5007 @cindex :=
5008 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
5009 (@pxref{Setting, ,Setting Variables}).
5010 The value of a simply expanded variable is scanned
5011 once and for all, expanding any references to other variables and
5012 functions, when the variable is defined.  The actual value of the simply
5013 expanded variable is the result of expanding the text that you write.
5014 It does not contain any references to other variables; it contains their
5015 values @emph{as of the time this variable was defined}.  Therefore,
5017 @example
5018 x := foo
5019 y := $(x) bar
5020 x := later
5021 @end example
5023 @noindent
5024 is equivalent to
5026 @example
5027 y := foo bar
5028 x := later
5029 @end example
5031 When a simply expanded variable is referenced, its value is substituted
5032 verbatim.
5034 Here is a somewhat more complicated example, illustrating the use of
5035 @samp{:=} in conjunction with the @code{shell} function.
5036 (@xref{Shell Function, , The @code{shell} Function}.)  This example
5037 also shows use of the variable @code{MAKELEVEL}, which is changed
5038 when it is passed down from level to level.
5039 (@xref{Variables/Recursion, , Communicating Variables to a
5040 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
5042 @vindex MAKELEVEL
5043 @vindex MAKE
5044 @example
5045 @group
5046 ifeq (0,$@{MAKELEVEL@})
5047 whoami    := $(shell whoami)
5048 host-type := $(shell arch)
5049 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
5050 endif
5051 @end group
5052 @end example
5054 @noindent
5055 An advantage of this use of @samp{:=} is that a typical
5056 `descend into a directory' recipe then looks like this:
5058 @example
5059 @group
5060 $@{subdirs@}:
5061         $@{MAKE@} -C $@@ all
5062 @end group
5063 @end example
5065 Simply expanded variables generally make complicated makefile programming
5066 more predictable because they work like variables in most programming
5067 languages.  They allow you to redefine a variable using its own value (or
5068 its value processed in some way by one of the expansion functions) and to
5069 use the expansion functions much more efficiently
5070 (@pxref{Functions, ,Functions for Transforming Text}).
5072 @cindex spaces, in variable values
5073 @cindex whitespace, in variable values
5074 @cindex variables, spaces in values
5075 You can also use them to introduce controlled leading whitespace into
5076 variable values.  Leading whitespace characters are discarded from your
5077 input before substitution of variable references and function calls;
5078 this means you can include leading spaces in a variable value by
5079 protecting them with variable references, like this:
5081 @example
5082 nullstring :=
5083 space := $(nullstring) # end of the line
5084 @end example
5086 @noindent
5087 Here the value of the variable @code{space} is precisely one space.  The
5088 comment @w{@samp{# end of the line}} is included here just for clarity.
5089 Since trailing space characters are @emph{not} stripped from variable
5090 values, just a space at the end of the line would have the same effect
5091 (but be rather hard to read).  If you put whitespace at the end of a
5092 variable value, it is a good idea to put a comment like that at the end
5093 of the line to make your intent clear.  Conversely, if you do @emph{not}
5094 want any whitespace characters at the end of your variable value, you
5095 must remember not to put a random comment on the end of the line after
5096 some whitespace, such as this:
5098 @example
5099 dir := /foo/bar    # directory to put the frobs in
5100 @end example
5102 @noindent
5103 Here the value of the variable @code{dir} is @w{@samp{/foo/bar    }}
5104 (with four trailing spaces), which was probably not the intention.
5105 (Imagine something like @w{@samp{$(dir)/file}} with this definition!)
5107 @cindex conditional variable assignment
5108 @cindex variables, conditional assignment
5109 @cindex ?=
5110 There is another assignment operator for variables, @samp{?=}.  This
5111 is called a conditional variable assignment operator, because it only
5112 has an effect if the variable is not yet defined.  This statement:
5114 @example
5115 FOO ?= bar
5116 @end example
5118 @noindent
5119 is exactly equivalent to this
5120 (@pxref{Origin Function, ,The @code{origin} Function}):
5122 @example
5123 ifeq ($(origin FOO), undefined)
5124   FOO = bar
5125 endif
5126 @end example
5128 Note that a variable set to an empty value is still defined, so
5129 @samp{?=} will not set that variable.
5131 @node Advanced, Values, Flavors, Using Variables
5132 @section Advanced Features for Reference to Variables
5133 @cindex reference to variables
5135 This section describes some advanced features you can use to reference
5136 variables in more flexible ways.
5138 @menu
5139 * Substitution Refs::           Referencing a variable with
5140                                   substitutions on the value.
5141 * Computed Names::              Computing the name of the variable to refer to.
5142 @end menu
5144 @node Substitution Refs, Computed Names, Advanced, Advanced
5145 @subsection Substitution References
5146 @cindex modified variable reference
5147 @cindex substitution variable reference
5148 @cindex variables, modified reference
5149 @cindex variables, substitution reference
5151 @cindex variables, substituting suffix in
5152 @cindex suffix, substituting in variables
5153 A @dfn{substitution reference} substitutes the value of a variable with
5154 alterations that you specify.  It has the form
5155 @samp{$(@var{var}:@var{a}=@var{b})} (or
5156 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
5157 of the variable @var{var}, replace every @var{a} at the end of a word with
5158 @var{b} in that value, and substitute the resulting string.
5160 When we say ``at the end of a word'', we mean that @var{a} must appear
5161 either followed by whitespace or at the end of the value in order to be
5162 replaced; other occurrences of @var{a} in the value are unaltered.  For
5163 example:@refill
5165 @example
5166 foo := a.o b.o c.o
5167 bar := $(foo:.o=.c)
5168 @end example
5170 @noindent
5171 sets @samp{bar} to @samp{a.c b.c c.c}.  @xref{Setting, ,Setting Variables}.
5173 A substitution reference is actually an abbreviation for use of the
5174 @code{patsubst} expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}).  We provide
5175 substitution references as well as @code{patsubst} for compatibility with
5176 other implementations of @code{make}.
5178 @findex patsubst
5179 Another type of substitution reference lets you use the full power of
5180 the @code{patsubst} function.  It has the same form
5181 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
5182 @var{a} must contain a single @samp{%} character.  This case is
5183 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
5184 @xref{Text Functions, ,Functions for String Substitution and Analysis},
5185 for a description of the @code{patsubst} function.@refill
5187 @example
5188 @group
5189 @exdent For example:
5191 foo := a.o b.o c.o
5192 bar := $(foo:%.o=%.c)
5193 @end group
5194 @end example
5196 @noindent
5197 sets @samp{bar} to @samp{a.c b.c c.c}.
5199 @node Computed Names,  , Substitution Refs, Advanced
5200 @subsection Computed Variable Names
5201 @cindex nested variable reference
5202 @cindex computed variable name
5203 @cindex variables, computed names
5204 @cindex variables, nested references
5205 @cindex variables, @samp{$} in name
5206 @cindex @code{$}, in variable name
5207 @cindex dollar sign (@code{$}), in variable name
5209 Computed variable names are a complicated concept needed only for
5210 sophisticated makefile programming.  For most purposes you need not
5211 consider them, except to know that making a variable with a dollar sign
5212 in its name might have strange results.  However, if you are the type
5213 that wants to understand everything, or you are actually interested in
5214 what they do, read on.
5216 Variables may be referenced inside the name of a variable.  This is
5217 called a @dfn{computed variable name} or a @dfn{nested variable
5218 reference}.  For example,
5220 @example
5221 x = y
5222 y = z
5223 a := $($(x))
5224 @end example
5226 @noindent
5227 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
5228 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
5229 to @samp{z}.  Here the name of the variable to reference is not stated
5230 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
5231 @samp{$(x)} here is nested within the outer variable reference.
5233 The previous example shows two levels of nesting, but any number of levels
5234 is possible.  For example, here are three levels:
5236 @example
5237 x = y
5238 y = z
5239 z = u
5240 a := $($($(x)))
5241 @end example
5243 @noindent
5244 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
5245 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
5246 @samp{$(z)}, which becomes @samp{u}.
5248 References to recursively-expanded variables within a variable name are
5249 re-expanded in the usual fashion.  For example:
5251 @example
5252 x = $(y)
5253 y = z
5254 z = Hello
5255 a := $($(x))
5256 @end example
5258 @noindent
5259 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
5260 which becomes @samp{$(z)} which becomes @samp{Hello}.
5262 Nested variable references can also contain modified references and
5263 function invocations (@pxref{Functions, ,Functions for Transforming Text}),
5264 just like any other reference.
5265 For example, using the @code{subst} function
5266 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
5268 @example
5269 @group
5270 x = variable1
5271 variable2 := Hello
5272 y = $(subst 1,2,$(x))
5273 z = y
5274 a := $($($(z)))
5275 @end group
5276 @end example
5278 @noindent
5279 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
5280 would ever want to write a nested reference as convoluted as this one, but
5281 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
5282 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
5283 @code{x} and changes it by substitution to @samp{variable2}, so that the
5284 entire string becomes @samp{$(variable2)}, a simple variable reference
5285 whose value is @samp{Hello}.@refill
5287 A computed variable name need not consist entirely of a single variable
5288 reference.  It can contain several variable references, as well as some
5289 invariant text.  For example,
5291 @example
5292 @group
5293 a_dirs := dira dirb
5294 1_dirs := dir1 dir2
5295 @end group
5297 @group
5298 a_files := filea fileb
5299 1_files := file1 file2
5300 @end group
5302 @group
5303 ifeq "$(use_a)" "yes"
5304 a1 := a
5305 else
5306 a1 := 1
5307 endif
5308 @end group
5310 @group
5311 ifeq "$(use_dirs)" "yes"
5312 df := dirs
5313 else
5314 df := files
5315 endif
5317 dirs := $($(a1)_$(df))
5318 @end group
5319 @end example
5321 @noindent
5322 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
5323 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
5324 and @code{use_dirs}.@refill
5326 Computed variable names can also be used in substitution references:
5328 @example
5329 @group
5330 a_objects := a.o b.o c.o
5331 1_objects := 1.o 2.o 3.o
5333 sources := $($(a1)_objects:.o=.c)
5334 @end group
5335 @end example
5337 @noindent
5338 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
5339 depending on the value of @code{a1}.
5341 The only restriction on this sort of use of nested variable references
5342 is that they cannot specify part of the name of a function to be called.
5343 This is because the test for a recognized function name is done before
5344 the expansion of nested references.  For example,
5346 @example
5347 @group
5348 ifdef do_sort
5349 func := sort
5350 else
5351 func := strip
5352 endif
5353 @end group
5355 @group
5356 bar := a d b g q c
5357 @end group
5359 @group
5360 foo := $($(func) $(bar))
5361 @end group
5362 @end example
5364 @noindent
5365 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
5366 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
5367 as the argument to either the @code{sort} or the @code{strip} function.
5368 This restriction could be removed in the future if that change is shown
5369 to be a good idea.
5371 You can also use computed variable names in the left-hand side of a
5372 variable assignment, or in a @code{define} directive, as in:
5374 @example
5375 dir = foo
5376 $(dir)_sources := $(wildcard $(dir)/*.c)
5377 define $(dir)_print =
5378 lpr $($(dir)_sources)
5379 endef
5380 @end example
5382 @noindent
5383 This example defines the variables @samp{dir}, @samp{foo_sources}, and
5384 @samp{foo_print}.
5386 Note that @dfn{nested variable references} are quite different from
5387 @dfn{recursively expanded variables}
5388 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
5389 used together in complex ways when doing makefile programming.@refill
5391 @node Values, Setting, Advanced, Using Variables
5392 @section How Variables Get Their Values
5393 @cindex variables, how they get their values
5394 @cindex value, how a variable gets it
5396 Variables can get values in several different ways:
5398 @itemize @bullet
5399 @item
5400 You can specify an overriding value when you run @code{make}.
5401 @xref{Overriding, ,Overriding Variables}.
5403 @item
5404 You can specify a value in the makefile, either
5405 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
5406 verbatim definition (@pxref{Multi-Line, ,Defining Multi-Line Variables}).@refill
5408 @item
5409 Variables in the environment become @code{make} variables.
5410 @xref{Environment, ,Variables from the Environment}.
5412 @item
5413 Several @dfn{automatic} variables are given new values for each rule.
5414 Each of these has a single conventional use.
5415 @xref{Automatic Variables}.
5417 @item
5418 Several variables have constant initial values.
5419 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
5420 @end itemize
5422 @node Setting, Appending, Values, Using Variables
5423 @section Setting Variables
5424 @cindex setting variables
5425 @cindex variables, setting
5426 @cindex =
5427 @cindex :=
5428 @cindex ?=
5429 @cindex !=
5431 To set a variable from the makefile, write a line starting with the
5432 variable name followed by @samp{=} or @samp{:=}.  Whatever follows the
5433 @samp{=} or @samp{:=} on the line becomes the value.  For example,
5435 @example
5436 objects = main.o foo.o bar.o utils.o
5437 @end example
5439 @noindent
5440 defines a variable named @code{objects}.  Whitespace around the variable
5441 name and immediately after the @samp{=} is ignored.
5443 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
5444 Variables defined with @samp{:=} are @dfn{simply expanded} variables; these
5445 definitions can contain variable references which will be expanded before
5446 the definition is made.  @xref{Flavors, ,The Two Flavors of Variables}.
5448 The variable name may contain function and variable references, which
5449 are expanded when the line is read to find the actual variable name to use.
5451 There is no limit on the length of the value of a variable except the
5452 amount of memory on the computer.  When a variable definition is long,
5453 it is a good idea to break it into several lines by inserting
5454 backslash-newline at convenient places in the definition.  This will
5455 make the makefile easier to read.  Every backslash-newline, along with
5456 any leading whitespace on the following line, will be replaced by a
5457 single space in the value of the variable.
5459 Most variable names are considered to have the empty string as a value if
5460 you have never set them.  Several variables have built-in initial values
5461 that are not empty, but you can set them in the usual ways
5462 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).
5463 Several special variables are set
5464 automatically to a new value for each rule; these are called the
5465 @dfn{automatic} variables (@pxref{Automatic Variables}).
5467 If you'd like a variable to be set to a value only if it's not already
5468 set, then you can use the shorthand operator @samp{?=} instead of
5469 @samp{=}.  These two settings of the variable @samp{FOO} are identical
5470 (@pxref{Origin Function, ,The @code{origin} Function}):
5472 @example
5473 FOO ?= bar
5474 @end example
5476 @noindent
5479 @example
5480 ifeq ($(origin FOO), undefined)
5481 FOO = bar
5482 endif
5483 @end example
5485 The shell assignment operator @samp{!=} can be used to execute a
5486 program and set a variable to its output.  This operator first
5487 evaluates the right-hand side, then passes that result to the shell
5488 for execution.  If the result of the execution ends in a newline, that
5489 one newline is removed; all other newlines are replaced by spaces.
5490 The resulting string is then placed into the named
5491 recursively-expanded variable.  For example:
5493 @example
5494 hash != printf '\043'
5495 file_list != find . -name '*.c'
5496 @end example
5498 If the result of the execution could produce a @code{$}, and you don't
5499 intend what follows that to be interpreted as a make variable or
5500 function reference, then you must replace every @code{$} with
5501 @code{$$} as part of the execution.  Alternatively, you can set a
5502 simply expanded variable to the result of running a program using the
5503 @code{shell} function call.  @xref{Shell Function, , The @code{shell}
5504 Function}.  For example:
5506 @example
5507 hash := $(shell printf '\043')
5508 var := $(shell find . -name "*.c")
5509 @end example
5512 @node Appending, Override Directive, Setting, Using Variables
5513 @section Appending More Text to Variables
5514 @cindex +=
5515 @cindex appending to variables
5516 @cindex variables, appending to
5518 Often it is useful to add more text to the value of a variable already defined.
5519 You do this with a line containing @samp{+=}, like this:
5521 @example
5522 objects += another.o
5523 @end example
5525 @noindent
5526 This takes the value of the variable @code{objects}, and adds the text
5527 @samp{another.o} to it (preceded by a single space).  Thus:
5529 @example
5530 objects = main.o foo.o bar.o utils.o
5531 objects += another.o
5532 @end example
5534 @noindent
5535 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
5537 Using @samp{+=} is similar to:
5539 @example
5540 objects = main.o foo.o bar.o utils.o
5541 objects := $(objects) another.o
5542 @end example
5544 @noindent
5545 but differs in ways that become important when you use more complex values.
5547 When the variable in question has not been defined before, @samp{+=}
5548 acts just like normal @samp{=}: it defines a recursively-expanded
5549 variable.  However, when there @emph{is} a previous definition, exactly
5550 what @samp{+=} does depends on what flavor of variable you defined
5551 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
5552 explanation of the two flavors of variables.
5554 When you add to a variable's value with @samp{+=}, @code{make} acts
5555 essentially as if you had included the extra text in the initial
5556 definition of the variable.  If you defined it first with @samp{:=},
5557 making it a simply-expanded variable, @samp{+=} adds to that
5558 simply-expanded definition, and expands the new text before appending it
5559 to the old value just as @samp{:=} does
5560 (see @ref{Setting, ,Setting Variables}, for a full explanation of @samp{:=}).
5561 In fact,
5563 @example
5564 variable := value
5565 variable += more
5566 @end example
5568 @noindent
5569 is exactly equivalent to:
5571 @noindent
5572 @example
5573 variable := value
5574 variable := $(variable) more
5575 @end example
5577 On the other hand, when you use @samp{+=} with a variable that you defined
5578 first to be recursively-expanded using plain @samp{=}, @code{make} does
5579 something a bit different.  Recall that when you define a
5580 recursively-expanded variable, @code{make} does not expand the value you set
5581 for variable and function references immediately.  Instead it stores the text
5582 verbatim, and saves these variable and function references to be expanded
5583 later, when you refer to the new variable (@pxref{Flavors, ,The Two Flavors
5584 of Variables}).  When you use @samp{+=} on a recursively-expanded variable,
5585 it is this unexpanded text to which @code{make} appends the new text you
5586 specify.
5588 @example
5589 @group
5590 variable = value
5591 variable += more
5592 @end group
5593 @end example
5595 @noindent
5596 is roughly equivalent to:
5598 @example
5599 @group
5600 temp = value
5601 variable = $(temp) more
5602 @end group
5603 @end example
5605 @noindent
5606 except that of course it never defines a variable called @code{temp}.
5607 The importance of this comes when the variable's old value contains
5608 variable references.  Take this common example:
5610 @example
5611 CFLAGS = $(includes) -O
5612 @dots{}
5613 CFLAGS += -pg # enable profiling
5614 @end example
5616 @noindent
5617 The first line defines the @code{CFLAGS} variable with a reference to another
5618 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
5619 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
5620 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
5621 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
5622 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
5623 need not be defined yet for its value to take effect.  It only has to be
5624 defined before any reference to @code{CFLAGS}.  If we tried to append to the
5625 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
5627 @example
5628 CFLAGS := $(CFLAGS) -pg # enable profiling
5629 @end example
5631 @noindent
5632 This is pretty close, but not quite what we want.  Using @samp{:=}
5633 redefines @code{CFLAGS} as a simply-expanded variable; this means
5634 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
5635 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
5636 -pg}}, and a later definition of @code{includes} will have no effect.
5637 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
5638 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
5639 the reference to @code{includes}, so if that variable gets defined at
5640 any later point, a reference like @samp{$(CFLAGS)} still uses its
5641 value.
5643 @node Override Directive, Multi-Line, Appending, Using Variables
5644 @section The @code{override} Directive
5645 @findex override
5646 @cindex overriding with @code{override}
5647 @cindex variables, overriding
5649 If a variable has been set with a command argument
5650 (@pxref{Overriding, ,Overriding Variables}),
5651 then ordinary assignments in the makefile are ignored.  If you want to set
5652 the variable in the makefile even though it was set with a command
5653 argument, you can use an @code{override} directive, which is a line that
5654 looks like this:@refill
5656 @example
5657 override @var{variable} = @var{value}
5658 @end example
5660 @noindent
5663 @example
5664 override @var{variable} := @var{value}
5665 @end example
5667 To append more text to a variable defined on the command line, use:
5669 @example
5670 override @var{variable} += @var{more text}
5671 @end example
5673 @noindent
5674 @xref{Appending, ,Appending More Text to Variables}.
5676 Variable assignments marked with the @code{override} flag have a
5677 higher priority than all other assignments, except another
5678 @code{override}.  Subsequent assignments or appends to this variable
5679 which are not marked @code{override} will be ignored.
5681 The @code{override} directive was not invented for escalation in the war
5682 between makefiles and command arguments.  It was invented so you can alter
5683 and add to values that the user specifies with command arguments.
5685 For example, suppose you always want the @samp{-g} switch when you run the
5686 C compiler, but you would like to allow the user to specify the other
5687 switches with a command argument just as usual.  You could use this
5688 @code{override} directive:
5690 @example
5691 override CFLAGS += -g
5692 @end example
5694 You can also use @code{override} directives with @code{define} directives.
5695 This is done as you might expect:
5697 @example
5698 override define foo =
5700 endef
5701 @end example
5703 @noindent
5704 @iftex
5705 See the next section for information about @code{define}.
5706 @end iftex
5707 @ifnottex
5708 @xref{Multi-Line, ,Defining Multi-Line Variables}.
5709 @end ifnottex
5711 @node Multi-Line, Undefine Directive, Override Directive, Using Variables
5712 @section Defining Multi-Line Variables
5713 @findex define
5714 @findex endef
5715 @cindex multi-line variable definition
5716 @cindex variables, multi-line
5717 @cindex verbatim variable definition
5718 @cindex defining variables verbatim
5719 @cindex variables, defining verbatim
5721 Another way to set the value of a variable is to use the @code{define}
5722 directive.  This directive has an unusual syntax which allows newline
5723 characters to be included in the value, which is convenient for
5724 defining both canned sequences of commands (@pxref{Canned Recipes,
5725 ,Defining Canned Recipes}), and also sections of makefile syntax to
5726 use with @code{eval} (@pxref{Eval Function}).@refill
5728 The @code{define} directive is followed on the same line by the name
5729 of the variable being defined and an (optional) assignment operator,
5730 and nothing more.  The value to give the variable appears on the
5731 following lines.  The end of the value is marked by a line containing
5732 just the word @code{endef}.  Aside from this difference in syntax,
5733 @code{define} works just like any other variable definition.  The
5734 variable name may contain function and variable references, which are
5735 expanded when the directive is read to find the actual variable name
5736 to use.
5738 You may omit the variable assignment operator if you prefer.  If
5739 omitted, @code{make} assumes it to be @samp{=} and creates a
5740 recursively-expanded variable (@pxref{Flavors, ,The Two Flavors of Variables}).
5741 When using a @samp{+=} operator, the value is appended to the previous
5742 value as with any other append operation: with a single space
5743 separating the old and new values.
5745 You may nest @code{define} directives: @code{make} will keep track of
5746 nested directives and report an error if they are not all properly
5747 closed with @code{endef}.  Note that lines beginning with the recipe
5748 prefix character are considered part of a recipe, so any @code{define}
5749 or @code{endef} strings appearing on such a line will not be
5750 considered @code{make} directives.
5752 @example
5753 define two-lines =
5754 echo foo
5755 echo $(bar)
5756 endef
5757 @end example
5759 The value in an ordinary assignment cannot contain a newline; but the
5760 newlines that separate the lines of the value in a @code{define} become
5761 part of the variable's value (except for the final newline which precedes
5762 the @code{endef} and is not considered part of the value).@refill
5764 @need 800
5765 When used in a recipe, the previous example is functionally equivalent
5766 to this:
5768 @example
5769 two-lines = echo foo; echo $(bar)
5770 @end example
5772 @noindent
5773 since two commands separated by semicolon behave much like two separate
5774 shell commands.  However, note that using two separate lines means
5775 @code{make} will invoke the shell twice, running an independent sub-shell
5776 for each line.  @xref{Execution, ,Recipe Execution}.
5778 If you want variable definitions made with @code{define} to take
5779 precedence over command-line variable definitions, you can use the
5780 @code{override} directive together with @code{define}:
5782 @example
5783 override define two-lines =
5785 $(bar)
5786 endef
5787 @end example
5789 @noindent
5790 @xref{Override Directive, ,The @code{override} Directive}.
5792 @node Undefine Directive, Environment, Multi-Line, Using Variables
5793 @section Undefining Variables
5794 @findex undefine
5795 @cindex undefining variable
5797 If you want to clear a variable, setting its value to empty is usually
5798 sufficient. Expanding such a variable will yield the same result (empty
5799 string) regardless of whether it was set or not. However, if you are
5800 using the @code{flavor} (@pxref{Flavor Function}) and
5801 @code{origin} (@pxref{Origin Function}) functions, there is a difference
5802 between a variable that was never set and a variable with an empty value.
5803 In such situations you may want to use the @code{undefine} directive to
5804 make a variable appear as if it was never set. For example:
5806 @example
5807 foo := foo
5808 bar = bar
5810 undefine foo
5811 undefine bar
5813 $(info $(origin foo))
5814 $(info $(flavor bar))
5815 @end example
5817 This example will print ``undefined'' for both variables.
5819 If you want to undefine a command-line variable definition, you can use
5820 the @code{override} directive together with @code{undefine}, similar to
5821 how this is done for variable definitions:
5823 @example
5824 override undefine CFLAGS
5825 @end example
5827 @node Environment, Target-specific, Undefine Directive, Using Variables
5828 @section Variables from the Environment
5830 @cindex variables, environment
5831 @cindex environment
5832 Variables in @code{make} can come from the environment in which
5833 @code{make} is run.  Every environment variable that @code{make} sees
5834 when it starts up is transformed into a @code{make} variable with the
5835 same name and value.  However, an explicit assignment in the makefile,
5836 or with a command argument, overrides the environment.  (If the
5837 @samp{-e} flag is specified, then values from the environment override
5838 assignments in the makefile.  @xref{Options Summary, ,Summary of
5839 Options}.  But this is not recommended practice.)
5841 Thus, by setting the variable @code{CFLAGS} in your environment, you can
5842 cause all C compilations in most makefiles to use the compiler switches you
5843 prefer.  This is safe for variables with standard or conventional meanings
5844 because you know that no makefile will use them for other things.  (Note
5845 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
5846 and therefore are not affected by the value in the environment.)
5848 When @code{make} runs a recipe, variables defined in the
5849 makefile are placed into the environment of each shell.  This allows
5850 you to pass values to sub-@code{make} invocations (@pxref{Recursion,
5851 ,Recursive Use of @code{make}}).  By default, only variables that came
5852 from the environment or the command line are passed to recursive
5853 invocations.  You can use the @code{export} directive to pass other
5854 variables.  @xref{Variables/Recursion, , Communicating Variables to a
5855 Sub-@code{make}}, for full details.
5857 Other use of variables from the environment is not recommended.  It is not
5858 wise for makefiles to depend for their functioning on environment variables
5859 set up outside their control, since this would cause different users to get
5860 different results from the same makefile.  This is against the whole
5861 purpose of most makefiles.
5863 @cindex SHELL, import from environment
5864 Such problems would be especially likely with the variable
5865 @code{SHELL}, which is normally present in the environment to specify
5866 the user's choice of interactive shell.  It would be very undesirable
5867 for this choice to affect @code{make}; so, @code{make} handles the
5868 @code{SHELL} environment variable in a special way; see @ref{Choosing
5869 the Shell}.@refill
5871 @node Target-specific, Pattern-specific, Environment, Using Variables
5872 @section Target-specific Variable Values
5873 @cindex target-specific variables
5874 @cindex variables, target-specific
5876 Variable values in @code{make} are usually global; that is, they are the
5877 same regardless of where they are evaluated (unless they're reset, of
5878 course).  One exception to that is automatic variables
5879 (@pxref{Automatic Variables}).
5881 The other exception is @dfn{target-specific variable values}.  This
5882 feature allows you to define different values for the same variable,
5883 based on the target that @code{make} is currently building.  As with
5884 automatic variables, these values are only available within the context
5885 of a target's recipe (and in other target-specific assignments).
5887 Set a target-specific variable value like this:
5889 @example
5890 @var{target} @dots{} : @var{variable-assignment}
5891 @end example
5893 Target-specific variable assignments can be prefixed with any or all of the
5894 special keywords @code{export}, @code{override}, or @code{private};
5895 these apply their normal behavior to this instance of the variable only.
5897 Multiple @var{target} values create a target-specific variable value for
5898 each member of the target list individually.
5900 The @var{variable-assignment} can be any valid form of assignment;
5901 recursive (@samp{=}), simple (@samp{:=}), appending (@samp{+=}), or
5902 conditional (@samp{?=}).  All variables that appear within the
5903 @var{variable-assignment} are evaluated within the context of the
5904 target: thus, any previously-defined target-specific variable values
5905 will be in effect.  Note that this variable is actually distinct from
5906 any ``global'' value: the two variables do not have to have the same
5907 flavor (recursive vs.@: simple).
5909 Target-specific variables have the same priority as any other makefile
5910 variable.  Variables provided on the command line (and in the
5911 environment if the @samp{-e} option is in force) will take precedence.
5912 Specifying the @code{override} directive will allow the target-specific
5913 variable value to be preferred.
5915 There is one more special feature of target-specific variables: when
5916 you define a target-specific variable that variable value is also in
5917 effect for all prerequisites of this target, and all their
5918 prerequisites, etc.@: (unless those prerequisites override that variable
5919 with their own target-specific variable value).  So, for example, a
5920 statement like this:
5922 @example
5923 prog : CFLAGS = -g
5924 prog : prog.o foo.o bar.o
5925 @end example
5927 @noindent
5928 will set @code{CFLAGS} to @samp{-g} in the recipe for @file{prog}, but
5929 it will also set @code{CFLAGS} to @samp{-g} in the recipes that create
5930 @file{prog.o}, @file{foo.o}, and @file{bar.o}, and any recipes which
5931 create their prerequisites.
5933 Be aware that a given prerequisite will only be built once per
5934 invocation of make, at most.  If the same file is a prerequisite of
5935 multiple targets, and each of those targets has a different value for
5936 the same target-specific variable, then the first target to be built
5937 will cause that prerequisite to be built and the prerequisite will
5938 inherit the target-specific value from the first target.  It will
5939 ignore the target-specific values from any other targets.
5941 @node Pattern-specific, Suppressing Inheritance, Target-specific, Using Variables
5942 @section Pattern-specific Variable Values
5943 @cindex pattern-specific variables
5944 @cindex variables, pattern-specific
5946 In addition to target-specific variable values
5947 (@pxref{Target-specific, ,Target-specific Variable Values}), GNU
5948 @code{make} supports pattern-specific variable values.  In this form,
5949 the variable is defined for any target that matches the pattern
5950 specified.
5952 Set a pattern-specific variable value like this:
5954 @example
5955 @var{pattern} @dots{} : @var{variable-assignment}
5956 @end example
5957 where @var{pattern} is a %-pattern.  As with target-specific variable
5958 values, multiple @var{pattern} values create a pattern-specific variable
5959 value for each pattern individually.  The @var{variable-assignment} can
5960 be any valid form of assignment.  Any command line variable setting will
5961 take precedence, unless @code{override} is specified.
5963 For example:
5965 @example
5966 %.o : CFLAGS = -O
5967 @end example
5969 @noindent
5970 will assign @code{CFLAGS} the value of @samp{-O} for all targets
5971 matching the pattern @code{%.o}.
5973 If a target matches more than one pattern, the matching pattern-specific
5974 variables with longer stems are interpreted first. This results in more
5975 specific variables taking precedence over the more generic ones, for
5976 example:
5978 @example
5979 %.o: %.c
5980         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
5982 lib/%.o: CFLAGS := -fPIC -g
5983 %.o: CFLAGS := -g
5985 all: foo.o lib/bar.o
5986 @end example
5988 In this example the first definition of the @code{CFLAGS} variable
5989 will be used to update @file{lib/bar.o} even though the second one
5990 also applies to this target. Pattern-specific variables which result
5991 in the same stem length are considered in the order in which they
5992 were defined in the makefile.
5994 Pattern-specific variables are searched after any target-specific
5995 variables defined explicitly for that target, and before target-specific
5996 variables defined for the parent target.
5998 @node Suppressing Inheritance, Special Variables, Pattern-specific, Using Variables
5999 @section Suppressing Inheritance
6000 @findex private
6001 @cindex suppressing inheritance
6002 @cindex inheritance, suppressing
6004 As described in previous sections, @code{make} variables are inherited
6005 by prerequisites.  This capability allows you to modify the behavior
6006 of a prerequisite based on which targets caused it to be rebuilt.  For
6007 example, you might set a target-specific variable on a @code{debug}
6008 target, then running @samp{make debug} will cause that variable to be
6009 inherited by all prerequisites of @code{debug}, while just running
6010 @samp{make all} (for example) would not have that assignment.
6012 Sometimes, however, you may not want a variable to be inherited.  For
6013 these situations, @code{make} provides the @code{private} modifier.
6014 Although this modifier can be used with any variable assignment, it
6015 makes the most sense with target- and pattern-specific variables.  Any
6016 variable marked @code{private} will be visible to its local target but
6017 will not be inherited by prerequisites of that target.  A global
6018 variable marked @code{private} will be visible in the global scope but
6019 will not be inherited by any target, and hence will not be visible
6020 in any recipe.
6022 As an example, consider this makefile:
6023 @example
6024 EXTRA_CFLAGS =
6026 prog: private EXTRA_CFLAGS = -L/usr/local/lib
6027 prog: a.o b.o
6028 @end example
6030 Due to the @code{private} modifier, @code{a.o} and @code{b.o} will not
6031 inherit the @code{EXTRA_CFLAGS} variable assignment from the
6032 @code{prog} target.
6034 @node Special Variables,  , Suppressing Inheritance, Using Variables
6035 @comment  node-name,  next,  previous,  up
6036 @section Other Special Variables
6037 @cindex makefiles, and special variables
6038 @cindex special variables
6040 GNU @code{make} supports some variables that have special properties.
6042 @table @code
6044 @vindex MAKEFILE_LIST @r{(list of parsed makefiles)}
6045 @cindex makefiles, and @code{MAKEFILE_LIST} variable
6046 @cindex including (@code{MAKEFILE_LIST} variable)
6047 @item MAKEFILE_LIST
6048 Contains the name of each makefile that is parsed by @code{make}, in
6049 the order in which it was parsed.  The name is appended just
6050 before @code{make} begins to parse the makefile.  Thus, if the first
6051 thing a makefile does is examine the last word in this variable, it
6052 will be the name of the current makefile.  Once the current makefile
6053 has used @code{include}, however, the last word will be the
6054 just-included makefile.
6056 If a makefile named @code{Makefile} has this content:
6058 @example
6059 @group
6060 name1 := $(lastword $(MAKEFILE_LIST))
6062 include inc.mk
6064 name2 := $(lastword $(MAKEFILE_LIST))
6066 all:
6067         @@echo name1 = $(name1)
6068         @@echo name2 = $(name2)
6069 @end group
6070 @end example
6072 @noindent
6073 then you would expect to see this output:
6075 @example
6076 @group
6077 name1 = Makefile
6078 name2 = inc.mk
6079 @end group
6080 @end example
6082 @vindex .DEFAULT_GOAL @r{(define default goal)}
6083 @item .DEFAULT_GOAL
6084 Sets the default goal to be used if no targets were specified on the
6085 command line (@pxref{Goals, , Arguments to Specify the Goals}).  The
6086 @code{.DEFAULT_GOAL} variable allows you to discover the current
6087 default goal, restart the default goal selection algorithm by clearing
6088 its value, or to explicitly set the default goal.  The following
6089 example illustrates these cases:
6091 @example
6092 @group
6093 # Query the default goal.
6094 ifeq ($(.DEFAULT_GOAL),)
6095   $(warning no default goal is set)
6096 endif
6098 .PHONY: foo
6099 foo: ; @@echo $@@
6101 $(warning default goal is $(.DEFAULT_GOAL))
6103 # Reset the default goal.
6104 .DEFAULT_GOAL :=
6106 .PHONY: bar
6107 bar: ; @@echo $@@
6109 $(warning default goal is $(.DEFAULT_GOAL))
6111 # Set our own.
6112 .DEFAULT_GOAL := foo
6113 @end group
6114 @end example
6116 This makefile prints:
6118 @example
6119 @group
6120 no default goal is set
6121 default goal is foo
6122 default goal is bar
6124 @end group
6125 @end example
6127 Note that assigning more than one target name to @code{.DEFAULT_GOAL} is
6128 invalid and will result in an error.
6130 @vindex MAKE_RESTARTS @r{(number of times @code{make} has restarted)}
6131 @item MAKE_RESTARTS
6132 This variable is set only if this instance of @code{make} has
6133 restarted (@pxref{Remaking Makefiles, , How Makefiles Are Remade}): it
6134 will contain the number of times this instance has restarted.  Note
6135 this is not the same as recursion (counted by the @code{MAKELEVEL}
6136 variable).  You should not set, modify, or export this variable.
6138 @vindex .RECIPEPREFIX @r{(change the recipe prefix character)}
6139 @item .RECIPEPREFIX
6140 The first character of the value of this variable is used as the
6141 character make assumes is introducing a recipe line.  If the variable
6142 is empty (as it is by default) that character is the standard tab
6143 character.  For example, this is a valid makefile:
6145 @example
6146 @group
6147 .RECIPEPREFIX = >
6148 all:
6149 > @@echo Hello, world
6150 @end group
6151 @end example
6153 The value of @code{.RECIPEPREFIX} can be changed multiple times; once set
6154 it stays in effect for all rules parsed until it is modified.
6156 @vindex .VARIABLES @r{(list of variables)}
6157 @item .VARIABLES
6158 Expands to a list of the @emph{names} of all global variables defined
6159 so far.  This includes variables which have empty values, as well as
6160 built-in variables (@pxref{Implicit Variables, , Variables Used by
6161 Implicit Rules}), but does not include any variables which are only
6162 defined in a target-specific context.  Note that any value you assign
6163 to this variable will be ignored; it will always return its special
6164 value.
6166 @c @vindex .TARGETS @r{(list of targets)}
6167 @c @item .TARGETS
6168 @c The second special variable is @code{.TARGETS}.  When expanded, the
6169 @c value consists of a list of all targets defined in all makefiles read
6170 @c up until that point.  Note it's not enough for a file to be simply
6171 @c mentioned in the makefile to be listed in this variable, even if it
6172 @c would match an implicit rule and become an ``implicit target''.  The
6173 @c file must appear as a target, on the left-hand side of a ``:'', to be
6174 @c considered a target for the purposes of this variable.
6176 @vindex .FEATURES @r{(list of supported features)}
6177 @item .FEATURES
6178 Expands to a list of special features supported by this version of
6179 @code{make}.  Possible values include, but are not limited to:
6181 @table @samp
6183 @item archives
6184 Supports @code{ar} (archive) files using special file name syntax.
6185 @xref{Archives, ,Using @code{make} to Update Archive Files}.
6187 @item check-symlink
6188 Supports the @code{-L} (@code{--check-symlink-times}) flag.
6189 @xref{Options Summary, ,Summary of Options}.
6191 @item else-if
6192 Supports ``else if'' non-nested conditionals.  @xref{Conditional
6193 Syntax, ,Syntax of Conditionals}.
6195 @item jobserver
6196 Supports ``job server'' enhanced parallel builds.  @xref{Parallel,
6197 ,Parallel Execution}.
6199 @item oneshell
6200 Supports the @code{.ONESHELL} special target.  @xref{One Shell, ,Using
6201 One Shell}.
6203 @item order-only
6204 Supports order-only prerequisites.  @xref{Prerequisite Types, ,Types
6205 of Prerequisites}.
6207 @item second-expansion
6208 Supports secondary expansion of prerequisite lists.
6210 @item shortest-stem
6211 Uses the ``shortest stem'' method of choosing which pattern, of
6212 multiple applicable options, will be used.  @xref{Pattern Match, ,How
6213 Patterns Match}.
6215 @item target-specific
6216 Supports target-specific and pattern-specific variable assignments.
6217 @xref{Target-specific, ,Target-specific Variable Values}.
6219 @item undefine
6220 Supports the @code{undefine} directive.  @xref{Undefine Directive}.
6222 @item guile
6223 Has GNU Guile available as an embedded extension language.
6224 @xref{Guile Function}.
6226 @end table
6228 @vindex .INCLUDE_DIRS @r{(list of include directories)}
6229 @item .INCLUDE_DIRS
6230 Expands to a list of directories that @code{make} searches for
6231 included makefiles (@pxref{Include, , Including Other Makefiles}).
6233 @end table
6235 @node Conditionals, Functions, Using Variables, Top
6236 @chapter Conditional Parts of Makefiles
6238 @cindex conditionals
6239 A @dfn{conditional} directive causes part of a makefile to be obeyed
6240 or ignored depending on the values of variables.  Conditionals can
6241 compare the value of one variable to another, or the value of a
6242 variable to a constant string.  Conditionals control what @code{make}
6243 actually ``sees'' in the makefile, so they @emph{cannot} be used to
6244 control recipes at the time of execution.@refill
6246 @menu
6247 * Conditional Example::         Example of a conditional
6248 * Conditional Syntax::          The syntax of conditionals.
6249 * Testing Flags::               Conditionals that test flags.
6250 @end menu
6252 @node Conditional Example, Conditional Syntax, Conditionals, Conditionals
6253 @section Example of a Conditional
6255 The following example of a conditional tells @code{make} to use one
6256 set of libraries if the @code{CC} variable is @samp{gcc}, and a
6257 different set of libraries otherwise.  It works by controlling which
6258 of two recipe lines will be used for the rule.  The result is that
6259 @samp{CC=gcc} as an argument to @code{make} changes not only which
6260 compiler is used but also which libraries are linked.
6262 @example
6263 libs_for_gcc = -lgnu
6264 normal_libs =
6266 foo: $(objects)
6267 ifeq ($(CC),gcc)
6268         $(CC) -o foo $(objects) $(libs_for_gcc)
6269 else
6270         $(CC) -o foo $(objects) $(normal_libs)
6271 endif
6272 @end example
6274 This conditional uses three directives: one @code{ifeq}, one @code{else}
6275 and one @code{endif}.
6277 The @code{ifeq} directive begins the conditional, and specifies the
6278 condition.  It contains two arguments, separated by a comma and surrounded
6279 by parentheses.  Variable substitution is performed on both arguments and
6280 then they are compared.  The lines of the makefile following the
6281 @code{ifeq} are obeyed if the two arguments match; otherwise they are
6282 ignored.
6284 The @code{else} directive causes the following lines to be obeyed if the
6285 previous conditional failed.  In the example above, this means that the
6286 second alternative linking command is used whenever the first alternative
6287 is not used.  It is optional to have an @code{else} in a conditional.
6289 The @code{endif} directive ends the conditional.  Every conditional must
6290 end with an @code{endif}.  Unconditional makefile text follows.
6292 As this example illustrates, conditionals work at the textual level:
6293 the lines of the conditional are treated as part of the makefile, or
6294 ignored, according to the condition.  This is why the larger syntactic
6295 units of the makefile, such as rules, may cross the beginning or the
6296 end of the conditional.
6298 When the variable @code{CC} has the value @samp{gcc}, the above example has
6299 this effect:
6301 @example
6302 foo: $(objects)
6303         $(CC) -o foo $(objects) $(libs_for_gcc)
6304 @end example
6306 @noindent
6307 When the variable @code{CC} has any other value, the effect is this:
6309 @example
6310 foo: $(objects)
6311         $(CC) -o foo $(objects) $(normal_libs)
6312 @end example
6314 Equivalent results can be obtained in another way by conditionalizing a
6315 variable assignment and then using the variable unconditionally:
6317 @example
6318 libs_for_gcc = -lgnu
6319 normal_libs =
6321 ifeq ($(CC),gcc)
6322   libs=$(libs_for_gcc)
6323 else
6324   libs=$(normal_libs)
6325 endif
6327 foo: $(objects)
6328         $(CC) -o foo $(objects) $(libs)
6329 @end example
6331 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
6332 @section Syntax of Conditionals
6333 @findex ifdef
6334 @findex ifeq
6335 @findex ifndef
6336 @findex ifneq
6337 @findex else
6338 @findex endif
6340 The syntax of a simple conditional with no @code{else} is as follows:
6342 @example
6343 @var{conditional-directive}
6344 @var{text-if-true}
6345 endif
6346 @end example
6348 @noindent
6349 The @var{text-if-true} may be any lines of text, to be considered as part
6350 of the makefile if the condition is true.  If the condition is false, no
6351 text is used instead.
6353 The syntax of a complex conditional is as follows:
6355 @example
6356 @var{conditional-directive}
6357 @var{text-if-true}
6358 else
6359 @var{text-if-false}
6360 endif
6361 @end example
6365 @example
6366 @var{conditional-directive}
6367 @var{text-if-one-is-true}
6368 else @var{conditional-directive}
6369 @var{text-if-true}
6370 else
6371 @var{text-if-false}
6372 endif
6373 @end example
6375 @noindent
6376 There can be as many ``@code{else} @var{conditional-directive}''
6377 clauses as necessary.  Once a given condition is true,
6378 @var{text-if-true} is used and no other clause is used; if no
6379 condition is true then @var{text-if-false} is used.  The
6380 @var{text-if-true} and @var{text-if-false} can be any number of lines
6381 of text.
6383 The syntax of the @var{conditional-directive} is the same whether the
6384 conditional is simple or complex; after an @code{else} or not.  There
6385 are four different directives that test different conditions.  Here is
6386 a table of them:
6388 @table @code
6389 @item ifeq (@var{arg1}, @var{arg2})
6390 @itemx ifeq '@var{arg1}' '@var{arg2}'
6391 @itemx ifeq "@var{arg1}" "@var{arg2}"
6392 @itemx ifeq "@var{arg1}" '@var{arg2}'
6393 @itemx ifeq '@var{arg1}' "@var{arg2}"
6394 Expand all variable references in @var{arg1} and @var{arg2} and
6395 compare them.  If they are identical, the @var{text-if-true} is
6396 effective; otherwise, the @var{text-if-false}, if any, is effective.
6398 Often you want to test if a variable has a non-empty value.  When the
6399 value results from complex expansions of variables and functions,
6400 expansions you would consider empty may actually contain whitespace
6401 characters and thus are not seen as empty.  However, you can use the
6402 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
6403 whitespace as a non-empty value.  For example:
6405 @example
6406 @group
6407 ifeq ($(strip $(foo)),)
6408 @var{text-if-empty}
6409 endif
6410 @end group
6411 @end example
6413 @noindent
6414 will evaluate @var{text-if-empty} even if the expansion of
6415 @code{$(foo)} contains whitespace characters.
6417 @item ifneq (@var{arg1}, @var{arg2})
6418 @itemx ifneq '@var{arg1}' '@var{arg2}'
6419 @itemx ifneq "@var{arg1}" "@var{arg2}"
6420 @itemx ifneq "@var{arg1}" '@var{arg2}'
6421 @itemx ifneq '@var{arg1}' "@var{arg2}"
6422 Expand all variable references in @var{arg1} and @var{arg2} and
6423 compare them.  If they are different, the @var{text-if-true} is
6424 effective; otherwise, the @var{text-if-false}, if any, is effective.
6426 @item ifdef @var{variable-name}
6427 The @code{ifdef} form takes the @emph{name} of a variable as its
6428 argument, not a reference to a variable.  The value of that variable
6429 has a non-empty value, the @var{text-if-true} is effective; otherwise,
6430 the @var{text-if-false}, if any, is effective.  Variables that have
6431 never been defined have an empty value.  The text @var{variable-name}
6432 is expanded, so it could be a variable or function that expands
6433 to the name of a variable.  For example:
6435 @example
6436 bar = true
6437 foo = bar
6438 ifdef $(foo)
6439 frobozz = yes
6440 endif
6441 @end example
6443 The variable reference @code{$(foo)} is expanded, yielding @code{bar},
6444 which is considered to be the name of a variable.  The variable
6445 @code{bar} is not expanded, but its value is examined to determine if
6446 it is non-empty.
6448 Note that @code{ifdef} only tests whether a variable has a value.  It
6449 does not expand the variable to see if that value is nonempty.
6450 Consequently, tests using @code{ifdef} return true for all definitions
6451 except those like @code{foo =}.  To test for an empty value, use
6452 @w{@code{ifeq ($(foo),)}}.  For example,
6454 @example
6455 bar =
6456 foo = $(bar)
6457 ifdef foo
6458 frobozz = yes
6459 else
6460 frobozz = no
6461 endif
6462 @end example
6464 @noindent
6465 sets @samp{frobozz} to @samp{yes}, while:
6467 @example
6468 foo =
6469 ifdef foo
6470 frobozz = yes
6471 else
6472 frobozz = no
6473 endif
6474 @end example
6476 @noindent
6477 sets @samp{frobozz} to @samp{no}.
6479 @item ifndef @var{variable-name}
6480 If the variable @var{variable-name} has an empty value, the
6481 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
6482 if any, is effective.  The rules for expansion and testing of
6483 @var{variable-name} are identical to the @code{ifdef} directive.
6484 @end table
6486 Extra spaces are allowed and ignored at the beginning of the
6487 conditional directive line, but a tab is not allowed.  (If the line
6488 begins with a tab, it will be considered part of a recipe for a rule.)
6489 Aside from this, extra spaces or tabs may be inserted with no effect
6490 anywhere except within the directive name or within an argument.  A
6491 comment starting with @samp{#} may appear at the end of the line.
6493 The other two directives that play a part in a conditional are @code{else}
6494 and @code{endif}.  Each of these directives is written as one word, with no
6495 arguments.  Extra spaces are allowed and ignored at the beginning of the
6496 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
6497 appear at the end of the line.
6499 Conditionals affect which lines of the makefile @code{make} uses.  If
6500 the condition is true, @code{make} reads the lines of the
6501 @var{text-if-true} as part of the makefile; if the condition is false,
6502 @code{make} ignores those lines completely.  It follows that syntactic
6503 units of the makefile, such as rules, may safely be split across the
6504 beginning or the end of the conditional.@refill
6506 @code{make} evaluates conditionals when it reads a makefile.
6507 Consequently, you cannot use automatic variables in the tests of
6508 conditionals because they are not defined until recipes are run
6509 (@pxref{Automatic Variables}).
6511 To prevent intolerable confusion, it is not permitted to start a
6512 conditional in one makefile and end it in another.  However, you may
6513 write an @code{include} directive within a conditional, provided you do
6514 not attempt to terminate the conditional inside the included file.
6516 @node Testing Flags,  , Conditional Syntax, Conditionals
6517 @section Conditionals that Test Flags
6519 You can write a conditional that tests @code{make} command flags such as
6520 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
6521 @code{findstring} function
6522 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
6523 This is useful when @code{touch} is not enough to make a file appear up
6524 to date.
6526 The @code{findstring} function determines whether one string appears as a
6527 substring of another.  If you want to test for the @samp{-t} flag,
6528 use @samp{t} as the first string and the value of @code{MAKEFLAGS} as
6529 the other.
6531 For example, here is how to arrange to use @samp{ranlib -t} to finish
6532 marking an archive file up to date:
6534 @example
6535 archive.a: @dots{}
6536 ifneq (,$(findstring t,$(MAKEFLAGS)))
6537         +touch archive.a
6538         +ranlib -t archive.a
6539 else
6540         ranlib archive.a
6541 endif
6542 @end example
6544 @noindent
6545 The @samp{+} prefix marks those recipe lines as ``recursive'' so that
6546 they will be executed despite use of the @samp{-t} flag.
6547 @xref{Recursion, ,Recursive Use of @code{make}}.
6549 @node Functions, Running, Conditionals, Top
6550 @chapter Functions for Transforming Text
6551 @cindex functions
6553 @dfn{Functions} allow you to do text processing in the makefile to
6554 compute the files to operate on or the commands to use in recipes.
6555 You use a function in a @dfn{function call}, where you give the name
6556 of the function and some text (the @dfn{arguments}) for the function
6557 to operate on.  The result of the function's processing is substituted
6558 into the makefile at the point of the call, just as a variable might
6559 be substituted.
6561 @menu
6562 * Syntax of Functions::         How to write a function call.
6563 * Text Functions::              General-purpose text manipulation functions.
6564 * File Name Functions::         Functions for manipulating file names.
6565 * Conditional Functions::       Functions that implement conditions.
6566 * Foreach Function::            Repeat some text with controlled variation.
6567 * File Function::               Write text to a file.
6568 * Call Function::               Expand a user-defined function.
6569 * Value Function::              Return the un-expanded value of a variable.
6570 * Eval Function::               Evaluate the arguments as makefile syntax.
6571 * Origin Function::             Find where a variable got its value.
6572 * Flavor Function::             Find out the flavor of a variable.
6573 * Make Control Functions::      Functions that control how make runs.
6574 * Shell Function::              Substitute the output of a shell command.
6575 * Guile Function::              Call the GNU Guile embedded scripting language.
6576 @end menu
6578 @node Syntax of Functions, Text Functions, Functions, Functions
6579 @section Function Call Syntax
6580 @cindex @code{$}, in function call
6581 @cindex dollar sign (@code{$}), in function call
6582 @cindex arguments of functions
6583 @cindex functions, syntax of
6585 A function call resembles a variable reference.  It can appear
6586 anywhere a variable reference can appear, and it is expanded using the
6587 same rules as variable references.  A function call looks like this:
6589 @example
6590 $(@var{function} @var{arguments})
6591 @end example
6593 @noindent
6594 or like this:
6596 @example
6597 $@{@var{function} @var{arguments}@}
6598 @end example
6600 Here @var{function} is a function name; one of a short list of names
6601 that are part of @code{make}.  You can also essentially create your own
6602 functions by using the @code{call} built-in function.
6604 The @var{arguments} are the arguments of the function.  They are
6605 separated from the function name by one or more spaces or tabs, and if
6606 there is more than one argument, then they are separated by commas.
6607 Such whitespace and commas are not part of an argument's value.  The
6608 delimiters which you use to surround the function call, whether
6609 parentheses or braces, can appear in an argument only in matching pairs;
6610 the other kind of delimiters may appear singly.  If the arguments
6611 themselves contain other function calls or variable references, it is
6612 wisest to use the same kind of delimiters for all the references; write
6613 @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst a,b,$@{x@})}}.  This
6614 is because it is clearer, and because only one type of delimiter is
6615 matched to find the end of the reference.
6617 The text written for each argument is processed by substitution of
6618 variables and function calls to produce the argument value, which
6619 is the text on which the function acts.  The substitution is done in the
6620 order in which the arguments appear.
6622 Commas and unmatched parentheses or braces cannot appear in the text of an
6623 argument as written; leading spaces cannot appear in the text of the first
6624 argument as written.  These characters can be put into the argument value
6625 by variable substitution.  First define variables @code{comma} and
6626 @code{space} whose values are isolated comma and space characters, then
6627 substitute these variables where such characters are wanted, like this:
6629 @example
6630 @group
6631 comma:= ,
6632 empty:=
6633 space:= $(empty) $(empty)
6634 foo:= a b c
6635 bar:= $(subst $(space),$(comma),$(foo))
6636 # @r{bar is now `a,b,c'.}
6637 @end group
6638 @end example
6640 @noindent
6641 Here the @code{subst} function replaces each space with a comma, through
6642 the value of @code{foo}, and substitutes the result.
6644 @node Text Functions, File Name Functions, Syntax of Functions, Functions
6645 @section Functions for String Substitution and Analysis
6646 @cindex functions, for text
6648 Here are some functions that operate on strings:
6650 @table @code
6651 @item $(subst @var{from},@var{to},@var{text})
6652 @findex subst
6653 Performs a textual replacement on the text @var{text}: each occurrence
6654 of @var{from} is replaced by @var{to}.  The result is substituted for
6655 the function call.  For example,
6657 @example
6658 $(subst ee,EE,feet on the street)
6659 @end example
6661 substitutes the string @samp{fEEt on the strEEt}.
6663 @item $(patsubst @var{pattern},@var{replacement},@var{text})
6664 @findex patsubst
6665 Finds whitespace-separated words in @var{text} that match
6666 @var{pattern} and replaces them with @var{replacement}.  Here
6667 @var{pattern} may contain a @samp{%} which acts as a wildcard,
6668 matching any number of any characters within a word.  If
6669 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
6670 by the text that matched the @samp{%} in @var{pattern}.  Only the first
6671 @samp{%} in the @var{pattern} and @var{replacement} is treated this
6672 way; any subsequent @samp{%} is unchanged.@refill
6674 @cindex @code{%}, quoting in @code{patsubst}
6675 @cindex @code{%}, quoting with @code{\} (backslash)
6676 @cindex @code{\} (backslash), to quote @code{%}
6677 @cindex backslash (@code{\}), to quote @code{%}
6678 @cindex quoting @code{%}, in @code{patsubst}
6679 @samp{%} characters in @code{patsubst} function invocations can be
6680 quoted with preceding backslashes (@samp{\}).  Backslashes that would
6681 otherwise quote @samp{%} characters can be quoted with more backslashes.
6682 Backslashes that quote @samp{%} characters or other backslashes are
6683 removed from the pattern before it is compared file names or has a stem
6684 substituted into it.  Backslashes that are not in danger of quoting
6685 @samp{%} characters go unmolested.  For example, the pattern
6686 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
6687 operative @samp{%} character, and @samp{pattern\\} following it.  The
6688 final two backslashes are left alone because they cannot affect any
6689 @samp{%} character.@refill
6691 Whitespace between words is folded into single space characters;
6692 leading and trailing whitespace is discarded.
6694 For example,
6696 @example
6697 $(patsubst %.c,%.o,x.c.c bar.c)
6698 @end example
6700 @noindent
6701 produces the value @samp{x.c.o bar.o}.
6703 Substitution references (@pxref{Substitution Refs, ,Substitution
6704 References}) are a simpler way to get the effect of the @code{patsubst}
6705 function:
6707 @example
6708 $(@var{var}:@var{pattern}=@var{replacement})
6709 @end example
6711 @noindent
6712 is equivalent to
6714 @example
6715 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
6716 @end example
6718 The second shorthand simplifies one of the most common uses of
6719 @code{patsubst}: replacing the suffix at the end of file names.
6721 @example
6722 $(@var{var}:@var{suffix}=@var{replacement})
6723 @end example
6725 @noindent
6726 is equivalent to
6728 @example
6729 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
6730 @end example
6732 @noindent
6733 For example, you might have a list of object files:
6735 @example
6736 objects = foo.o bar.o baz.o
6737 @end example
6739 @noindent
6740 To get the list of corresponding source files, you could simply write:
6742 @example
6743 $(objects:.o=.c)
6744 @end example
6746 @noindent
6747 instead of using the general form:
6749 @example
6750 $(patsubst %.o,%.c,$(objects))
6751 @end example
6753 @item $(strip @var{string})
6754 @cindex stripping whitespace
6755 @cindex whitespace, stripping
6756 @cindex spaces, stripping
6757 @findex strip
6758 Removes leading and trailing whitespace from @var{string} and replaces
6759 each internal sequence of one or more whitespace characters with a
6760 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
6762 The function @code{strip} can be very useful when used in conjunction
6763 with conditionals.  When comparing something with the empty string
6764 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
6765 just whitespace to match the empty string (@pxref{Conditionals}).
6767 Thus, the following may fail to have the desired results:
6769 @example
6770 .PHONY: all
6771 ifneq   "$(needs_made)" ""
6772 all: $(needs_made)
6773 else
6774 all:;@@echo 'Nothing to make!'
6775 endif
6776 @end example
6778 @noindent
6779 Replacing the variable reference @w{@samp{$(needs_made)}} with the
6780 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
6781 directive would make it more robust.@refill
6783 @item $(findstring @var{find},@var{in})
6784 @findex findstring
6785 @cindex searching for strings
6786 @cindex finding strings
6787 @cindex strings, searching for
6788 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
6789 value is @var{find}; otherwise, the value is empty.  You can use this
6790 function in a conditional to test for the presence of a specific
6791 substring in a given string.  Thus, the two examples,
6793 @example
6794 $(findstring a,a b c)
6795 $(findstring a,b c)
6796 @end example
6798 @noindent
6799 produce the values @samp{a} and @samp{} (the empty string),
6800 respectively.  @xref{Testing Flags}, for a practical application of
6801 @code{findstring}.@refill
6803 @need 750
6804 @findex filter
6805 @cindex filtering words
6806 @cindex words, filtering
6807 @item $(filter @var{pattern}@dots{},@var{text})
6808 Returns all whitespace-separated words in @var{text} that @emph{do} match
6809 any of the @var{pattern} words, removing any words that @emph{do not}
6810 match.  The patterns are written using @samp{%}, just like the patterns
6811 used in the @code{patsubst} function above.@refill
6813 The @code{filter} function can be used to separate out different types
6814 of strings (such as file names) in a variable.  For example:
6816 @example
6817 sources := foo.c bar.c baz.s ugh.h
6818 foo: $(sources)
6819         cc $(filter %.c %.s,$(sources)) -o foo
6820 @end example
6822 @noindent
6823 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
6824 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
6825 @file{baz.s} should be specified in the command to the
6826 compiler.@refill
6828 @item $(filter-out @var{pattern}@dots{},@var{text})
6829 @findex filter-out
6830 @cindex filtering out words
6831 @cindex words, filtering out
6832 Returns all whitespace-separated words in @var{text} that @emph{do not}
6833 match any of the @var{pattern} words, removing the words that @emph{do}
6834 match one or more.  This is the exact opposite of the @code{filter}
6835 function.@refill
6837 For example, given:
6839 @example
6840 @group
6841 objects=main1.o foo.o main2.o bar.o
6842 mains=main1.o main2.o
6843 @end group
6844 @end example
6846 @noindent
6847 the following generates a list which contains all the object files not
6848 in @samp{mains}:
6850 @example
6851 $(filter-out $(mains),$(objects))
6852 @end example
6854 @need 1500
6855 @findex sort
6856 @cindex sorting words
6857 @item $(sort @var{list})
6858 Sorts the words of @var{list} in lexical order, removing duplicate
6859 words.  The output is a list of words separated by single spaces.
6860 Thus,
6862 @example
6863 $(sort foo bar lose)
6864 @end example
6866 @noindent
6867 returns the value @samp{bar foo lose}.
6869 @cindex removing duplicate words
6870 @cindex duplicate words, removing
6871 @cindex words, removing duplicates
6872 Incidentally, since @code{sort} removes duplicate words, you can use
6873 it for this purpose even if you don't care about the sort order.
6875 @item $(word @var{n},@var{text})
6876 @findex word
6877 @cindex word, selecting a
6878 @cindex selecting a word
6879 Returns the @var{n}th word of @var{text}.  The legitimate values of
6880 @var{n} start from 1.  If @var{n} is bigger than the number of words
6881 in @var{text}, the value is empty.  For example,
6883 @example
6884 $(word 2, foo bar baz)
6885 @end example
6887 @noindent
6888 returns @samp{bar}.
6890 @item $(wordlist @var{s},@var{e},@var{text})
6891 @findex wordlist
6892 @cindex words, selecting lists of
6893 @cindex selecting word lists
6894 Returns the list of words in @var{text} starting with word @var{s} and
6895 ending with word @var{e} (inclusive).  The legitimate values of @var{s}
6896 start from 1; @var{e} may start from 0.  If @var{s} is bigger than the
6897 number of words in @var{text}, the value is empty.  If @var{e} is
6898 bigger than the number of words in @var{text}, words up to the end of
6899 @var{text} are returned.  If @var{s} is greater than @var{e}, nothing
6900 is returned.  For example,
6902 @example
6903 $(wordlist 2, 3, foo bar baz)
6904 @end example
6906 @noindent
6907 returns @samp{bar baz}.
6909 @c Following item phrased to prevent overfull hbox.  --RJC 17 Jul 92
6910 @item $(words @var{text})
6911 @findex words
6912 @cindex words, finding number
6913 Returns the number of words in @var{text}.
6914 Thus, the last word of @var{text} is
6915 @w{@code{$(word $(words @var{text}),@var{text})}}.@refill
6917 @item $(firstword @var{names}@dots{})
6918 @findex firstword
6919 @cindex words, extracting first
6920 The argument @var{names} is regarded as a series of names, separated
6921 by whitespace.  The value is the first name in the series.  The rest
6922 of the names are ignored.
6924 For example,
6926 @example
6927 $(firstword foo bar)
6928 @end example
6930 @noindent
6931 produces the result @samp{foo}.  Although @code{$(firstword
6932 @var{text})} is the same as @code{$(word 1,@var{text})}, the
6933 @code{firstword} function is retained for its simplicity.@refill
6936 @item $(lastword @var{names}@dots{})
6937 @findex lastword
6938 @cindex words, extracting last
6939 The argument @var{names} is regarded as a series of names, separated
6940 by whitespace.  The value is the last name in the series.
6942 For example,
6944 @example
6945 $(lastword foo bar)
6946 @end example
6948 @noindent
6949 produces the result @samp{bar}.  Although @code{$(lastword
6950 @var{text})} is the same as @code{$(word $(words @var{text}),@var{text})},
6951 the @code{lastword} function was added for its simplicity and better
6952 performance.@refill
6953 @end table
6956 Here is a realistic example of the use of @code{subst} and
6957 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
6958 to specify a list of directories that @code{make} should search for
6959 prerequisite files
6960 (@pxref{General Search, , @code{VPATH} Search Path for All Prerequisites}).
6961 This example shows how to
6962 tell the C compiler to search for header files in the same list of
6963 directories.@refill
6965 The value of @code{VPATH} is a list of directories separated by colons,
6966 such as @samp{src:../headers}.  First, the @code{subst} function is used to
6967 change the colons to spaces:
6969 @example
6970 $(subst :, ,$(VPATH))
6971 @end example
6973 @noindent
6974 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
6975 each directory name into a @samp{-I} flag.  These can be added to the
6976 value of the variable @code{CFLAGS}, which is passed automatically to the C
6977 compiler, like this:
6979 @example
6980 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
6981 @end example
6983 @noindent
6984 The effect is to append the text @samp{-Isrc -I../headers} to the
6985 previously given value of @code{CFLAGS}.  The @code{override} directive is
6986 used so that the new value is assigned even if the previous value of
6987 @code{CFLAGS} was specified with a command argument (@pxref{Override
6988 Directive, , The @code{override} Directive}).
6990 @node File Name Functions, Conditional Functions, Text Functions, Functions
6991 @section Functions for File Names
6992 @cindex functions, for file names
6993 @cindex file name functions
6995 Several of the built-in expansion functions relate specifically to
6996 taking apart file names or lists of file names.
6998 Each of the following functions performs a specific transformation on a
6999 file name.  The argument of the function is regarded as a series of file
7000 names, separated by whitespace.  (Leading and trailing whitespace is
7001 ignored.)  Each file name in the series is transformed in the same way and
7002 the results are concatenated with single spaces between them.
7004 @table @code
7005 @item $(dir @var{names}@dots{})
7006 @findex dir
7007 @cindex directory part
7008 @cindex file name, directory part
7009 Extracts the directory-part of each file name in @var{names}.  The
7010 directory-part of the file name is everything up through (and
7011 including) the last slash in it.  If the file name contains no slash,
7012 the directory part is the string @samp{./}.  For example,
7014 @example
7015 $(dir src/foo.c hacks)
7016 @end example
7018 @noindent
7019 produces the result @samp{src/ ./}.
7021 @item $(notdir @var{names}@dots{})
7022 @findex notdir
7023 @cindex file name, nondirectory part
7024 @cindex nondirectory part
7025 Extracts all but the directory-part of each file name in @var{names}.
7026 If the file name contains no slash, it is left unchanged.  Otherwise,
7027 everything through the last slash is removed from it.
7029 A file name that ends with a slash becomes an empty string.  This is
7030 unfortunate, because it means that the result does not always have the
7031 same number of whitespace-separated file names as the argument had;
7032 but we do not see any other valid alternative.
7034 For example,
7036 @example
7037 $(notdir src/foo.c hacks)
7038 @end example
7040 @noindent
7041 produces the result @samp{foo.c hacks}.
7043 @item $(suffix @var{names}@dots{})
7044 @findex suffix
7045 @cindex suffix, function to find
7046 @cindex file name suffix
7047 Extracts the suffix of each file name in @var{names}.  If the file name
7048 contains a period, the suffix is everything starting with the last
7049 period.  Otherwise, the suffix is the empty string.  This frequently
7050 means that the result will be empty when @var{names} is not, and if
7051 @var{names} contains multiple file names, the result may contain fewer
7052 file names.
7054 For example,
7056 @example
7057 $(suffix src/foo.c src-1.0/bar.c hacks)
7058 @end example
7060 @noindent
7061 produces the result @samp{.c .c}.
7063 @item $(basename @var{names}@dots{})
7064 @findex basename
7065 @cindex basename
7066 @cindex file name, basename of
7067 Extracts all but the suffix of each file name in @var{names}.  If the
7068 file name contains a period, the basename is everything starting up to
7069 (and not including) the last period.  Periods in the directory part are
7070 ignored.  If there is no period, the basename is the entire file name.
7071 For example,
7073 @example
7074 $(basename src/foo.c src-1.0/bar hacks)
7075 @end example
7077 @noindent
7078 produces the result @samp{src/foo src-1.0/bar hacks}.
7080 @c plural convention with dots (be consistent)
7081 @item $(addsuffix @var{suffix},@var{names}@dots{})
7082 @findex addsuffix
7083 @cindex suffix, adding
7084 @cindex file name suffix, adding
7085 The argument @var{names} is regarded as a series of names, separated
7086 by whitespace; @var{suffix} is used as a unit.  The value of
7087 @var{suffix} is appended to the end of each individual name and the
7088 resulting larger names are concatenated with single spaces between
7089 them.  For example,
7091 @example
7092 $(addsuffix .c,foo bar)
7093 @end example
7095 @noindent
7096 produces the result @samp{foo.c bar.c}.
7098 @item $(addprefix @var{prefix},@var{names}@dots{})
7099 @findex addprefix
7100 @cindex prefix, adding
7101 @cindex file name prefix, adding
7102 The argument @var{names} is regarded as a series of names, separated
7103 by whitespace; @var{prefix} is used as a unit.  The value of
7104 @var{prefix} is prepended to the front of each individual name and the
7105 resulting larger names are concatenated with single spaces between
7106 them.  For example,
7108 @example
7109 $(addprefix src/,foo bar)
7110 @end example
7112 @noindent
7113 produces the result @samp{src/foo src/bar}.
7115 @item $(join @var{list1},@var{list2})
7116 @findex join
7117 @cindex joining lists of words
7118 @cindex words, joining lists
7119 Concatenates the two arguments word by word: the two first words (one
7120 from each argument) concatenated form the first word of the result, the
7121 two second words form the second word of the result, and so on.  So the
7122 @var{n}th word of the result comes from the @var{n}th word of each
7123 argument.  If one argument has more words that the other, the extra
7124 words are copied unchanged into the result.
7126 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
7128 Whitespace between the words in the lists is not preserved; it is
7129 replaced with a single space.
7131 This function can merge the results of the @code{dir} and
7132 @code{notdir} functions, to produce the original list of files which
7133 was given to those two functions.@refill
7135 @item $(wildcard @var{pattern})
7136 @findex wildcard
7137 @cindex wildcard, function
7138 The argument @var{pattern} is a file name pattern, typically containing
7139 wildcard characters (as in shell file name patterns).  The result of
7140 @code{wildcard} is a space-separated list of the names of existing files
7141 that match the pattern.
7142 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
7144 @item $(realpath @var{names}@dots{})
7145 @findex realpath
7146 @cindex realpath
7147 @cindex file name, realpath of
7148 For each file name in @var{names} return the canonical absolute name.
7149 A canonical name does not contain any @code{.} or @code{..} components,
7150 nor any repeated path separators (@code{/}) or symlinks.  In case of a
7151 failure the empty string is returned.  Consult the @code{realpath(3)}
7152 documentation for a list of possible failure causes.
7154 @item $(abspath @var{names}@dots{})
7155 @findex abspath
7156 @cindex abspath
7157 @cindex file name, abspath of
7158 For each file name in @var{names} return an absolute name that does
7159 not contain any @code{.} or @code{..} components, nor any repeated path
7160 separators (@code{/}).  Note that, in contrast to @code{realpath}
7161 function, @code{abspath} does not resolve symlinks and does not require
7162 the file names to refer to an existing file or directory.  Use the
7163 @code{wildcard} function to test for existence.
7164 @end table
7166 @node Conditional Functions, Foreach Function, File Name Functions, Functions
7167 @section Functions for Conditionals
7168 @findex if
7169 @cindex conditional expansion
7170 There are three functions that provide conditional expansion.  A key
7171 aspect of these functions is that not all of the arguments are
7172 expanded initially.  Only those arguments which need to be expanded,
7173 will be expanded.
7175 @table @code
7176 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
7177 @findex if
7178 The @code{if} function provides support for conditional expansion in a
7179 functional context (as opposed to the GNU @code{make} makefile
7180 conditionals such as @code{ifeq} (@pxref{Conditional Syntax, ,Syntax of
7181 Conditionals}).
7183 The first argument, @var{condition}, first has all preceding and
7184 trailing whitespace stripped, then is expanded.  If it expands to any
7185 non-empty string, then the condition is considered to be true.  If it
7186 expands to an empty string, the condition is considered to be false.
7188 If the condition is true then the second argument, @var{then-part}, is
7189 evaluated and this is used as the result of the evaluation of the entire
7190 @code{if} function.
7192 If the condition is false then the third argument, @var{else-part}, is
7193 evaluated and this is the result of the @code{if} function.  If there is
7194 no third argument, the @code{if} function evaluates to nothing (the
7195 empty string).
7197 Note that only one of the @var{then-part} or the @var{else-part} will be
7198 evaluated, never both.  Thus, either can contain side-effects (such as
7199 @code{shell} function calls, etc.)
7201 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
7202 @findex or
7203 The @code{or} function provides a ``short-circuiting'' OR operation.
7204 Each argument is expanded, in order.  If an argument expands to a
7205 non-empty string the processing stops and the result of the expansion
7206 is that string.  If, after all arguments are expanded, all of them are
7207 false (empty), then the result of the expansion is the empty string.
7209 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
7210 @findex and
7211 The @code{and} function provides a ``short-circuiting'' AND operation.
7212 Each argument is expanded, in order.  If an argument expands to an
7213 empty string the processing stops and the result of the expansion is
7214 the empty string.  If all arguments expand to a non-empty string then
7215 the result of the expansion is the expansion of the last argument.
7217 @end table
7219 @node Foreach Function, File Function, Conditional Functions, Functions
7220 @section The @code{foreach} Function
7221 @findex foreach
7222 @cindex words, iterating over
7224 The @code{foreach} function is very different from other functions.  It
7225 causes one piece of text to be used repeatedly, each time with a different
7226 substitution performed on it.  It resembles the @code{for} command in the
7227 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
7229 The syntax of the @code{foreach} function is:
7231 @example
7232 $(foreach @var{var},@var{list},@var{text})
7233 @end example
7235 @noindent
7236 The first two arguments, @var{var} and @var{list}, are expanded before
7237 anything else is done; note that the last argument, @var{text}, is
7238 @strong{not} expanded at the same time.  Then for each word of the expanded
7239 value of @var{list}, the variable named by the expanded value of @var{var}
7240 is set to that word, and @var{text} is expanded.  Presumably @var{text}
7241 contains references to that variable, so its expansion will be different
7242 each time.
7244 The result is that @var{text} is expanded as many times as there are
7245 whitespace-separated words in @var{list}.  The multiple expansions of
7246 @var{text} are concatenated, with spaces between them, to make the result
7247 of @code{foreach}.
7249 This simple example sets the variable @samp{files} to the list of all files
7250 in the directories in the list @samp{dirs}:
7252 @example
7253 dirs := a b c d
7254 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
7255 @end example
7257 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
7258 finds the value @samp{a} for @code{dir}, so it produces the same result
7259 as @samp{$(wildcard a/*)}; the second repetition produces the result
7260 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
7262 This example has the same result (except for setting @samp{dirs}) as
7263 the following example:
7265 @example
7266 files := $(wildcard a/* b/* c/* d/*)
7267 @end example
7269 When @var{text} is complicated, you can improve readability by giving it
7270 a name, with an additional variable:
7272 @example
7273 find_files = $(wildcard $(dir)/*)
7274 dirs := a b c d
7275 files := $(foreach dir,$(dirs),$(find_files))
7276 @end example
7278 @noindent
7279 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
7280 to define a recursively-expanding variable, so that its value contains an
7281 actual function call to be re-expanded under the control of @code{foreach};
7282 a simply-expanded variable would not do, since @code{wildcard} would be
7283 called only once at the time of defining @code{find_files}.
7285 The @code{foreach} function has no permanent effect on the variable
7286 @var{var}; its value and flavor after the @code{foreach} function call are
7287 the same as they were beforehand.  The other values which are taken from
7288 @var{list} are in effect only temporarily, during the execution of
7289 @code{foreach}.  The variable @var{var} is a simply-expanded variable
7290 during the execution of @code{foreach}.  If @var{var} was undefined
7291 before the @code{foreach} function call, it is undefined after the call.
7292 @xref{Flavors, ,The Two Flavors of Variables}.@refill
7294 You must take care when using complex variable expressions that result in
7295 variable names because many strange things are valid variable names, but
7296 are probably not what you intended.  For example,
7298 @smallexample
7299 files := $(foreach Esta-escrito-en-espanol!,b c ch,$(find_files))
7300 @end smallexample
7302 @noindent
7303 might be useful if the value of @code{find_files} references the variable
7304 whose name is @samp{Esta-escrito-en-espanol!} (es un nombre bastante largo,
7305 no?), but it is more likely to be a mistake.
7307 @node File Function, Call Function, Foreach Function, Functions
7308 @section The @code{file} Function
7309 @findex file
7310 @cindex writing to a file
7311 @cindex file, writing to
7313 The @code{file} function allows the makefile to write to a file.  Two
7314 modes of writing are supported: overwrite, where the text is written
7315 to the beginning of the file and any existing content is lost, and
7316 append, where the text is written to the end of the file, preserving
7317 the existing content.  In all cases the file is created if it does not
7318 exist.
7320 The syntax of the @code{file} function is:
7322 @example
7323 $(file @var{op} @var{filename},@var{text})
7324 @end example
7326 The operator @var{op} can be either @code{>} which indicates overwrite
7327 mode, or @code{>>} which indicates append mode.  The @var{filename}
7328 indicates the file to be written to.  There may optionally be
7329 whitespace between the operator and the file name.
7331 When the @code{file} function is expanded all its arguments are
7332 expanded first, then the file indicated by @var{filename} will be
7333 opened in the mode described by @var{op}.  Finally @var{text} will be
7334 written to the file.  If @var{text} does not already end in a newline,
7335 a final newline will be written.  The result of evaluating the
7336 @code{file} function is always the empty string.
7338 It is a fatal error if the file cannot be opened for writing, or if
7339 the write operation fails.
7341 For example, the @code{file} function can be useful if your build
7342 system has a limited command line size and your recipe runs a command
7343 that can accept arguments from a file as well.  Many commands use the
7344 convention that an argument prefixed with an @code{@@} specifies a
7345 file containing more arguments.  Then you might write your recipe in
7346 this way:
7348 @example
7349 @group
7350 program: $(OBJECTS)
7351         $(file >$@@.in,$^)
7352         $(CMD) $(CMDFLAGS) @@$@@.in
7353         @@rm $@@.in
7354 @end group
7355 @end example
7357 If the command required each argument to be on a separate line of the
7358 input file, you might write your recipe like this:
7360 @example
7361 @group
7362 program: $(OBJECTS)
7363         $(file >$@@.in,) $(foreach O,$^,$(file >>$@@.in,$O))
7364         $(CMD) $(CMDFLAGS) @@$@@.in
7365         @@rm $@@.in
7366 @end group
7367 @end example
7369 @node Call Function, Value Function, File Function, Functions
7370 @section The @code{call} Function
7371 @findex call
7372 @cindex functions, user defined
7373 @cindex user defined functions
7375 The @code{call} function is unique in that it can be used to create new
7376 parameterized functions.  You can write a complex expression as the
7377 value of a variable, then use @code{call} to expand it with different
7378 values.
7380 The syntax of the @code{call} function is:
7382 @example
7383 $(call @var{variable},@var{param},@var{param},@dots{})
7384 @end example
7386 When @code{make} expands this function, it assigns each @var{param} to
7387 temporary variables @code{$(1)}, @code{$(2)}, etc.  The variable
7388 @code{$(0)} will contain @var{variable}.  There is no maximum number of
7389 parameter arguments.  There is no minimum, either, but it doesn't make
7390 sense to use @code{call} with no parameters.
7392 Then @var{variable} is expanded as a @code{make} variable in the context
7393 of these temporary assignments.  Thus, any reference to @code{$(1)} in
7394 the value of @var{variable} will resolve to the first @var{param} in the
7395 invocation of @code{call}.
7397 Note that @var{variable} is the @emph{name} of a variable, not a
7398 @emph{reference} to that variable.  Therefore you would not normally use
7399 a @samp{$} or parentheses when writing it.  (You can, however, use a
7400 variable reference in the name if you want the name not to be a
7401 constant.)
7403 If @var{variable} is the name of a built-in function, the built-in function
7404 is always invoked (even if a @code{make} variable by that name also
7405 exists).
7407 The @code{call} function expands the @var{param} arguments before
7408 assigning them to temporary variables.  This means that @var{variable}
7409 values containing references to built-in functions that have special
7410 expansion rules, like @code{foreach} or @code{if}, may not work as you
7411 expect.
7413 Some examples may make this clearer.
7415 This macro simply reverses its arguments:
7417 @smallexample
7418 reverse = $(2) $(1)
7420 foo = $(call reverse,a,b)
7421 @end smallexample
7423 @noindent
7424 Here @var{foo} will contain @samp{b a}.
7426 This one is slightly more interesting: it defines a macro to search for
7427 the first instance of a program in @code{PATH}:
7429 @smallexample
7430 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
7432 LS := $(call pathsearch,ls)
7433 @end smallexample
7435 @noindent
7436 Now the variable LS contains @code{/bin/ls} or similar.
7438 The @code{call} function can be nested.  Each recursive invocation gets
7439 its own local values for @code{$(1)}, etc.@: that mask the values of
7440 higher-level @code{call}.  For example, here is an implementation of a
7441 @dfn{map} function:
7443 @smallexample
7444 map = $(foreach a,$(2),$(call $(1),$(a)))
7445 @end smallexample
7447 Now you can @var{map} a function that normally takes only one argument,
7448 such as @code{origin}, to multiple values in one step:
7450 @smallexample
7451 o = $(call map,origin,o map MAKE)
7452 @end smallexample
7454 and end up with @var{o} containing something like @samp{file file default}.
7456 A final caution: be careful when adding whitespace to the arguments to
7457 @code{call}.  As with other functions, any whitespace contained in the
7458 second and subsequent arguments is kept; this can cause strange
7459 effects.  It's generally safest to remove all extraneous whitespace when
7460 providing parameters to @code{call}.
7462 @node Value Function, Eval Function, Call Function, Functions
7463 @comment  node-name,  next,  previous,  up
7464 @section The @code{value} Function
7465 @findex value
7466 @cindex variables, unexpanded value
7468 The @code{value} function provides a way for you to use the value of a
7469 variable @emph{without} having it expanded.  Please note that this
7470 does not undo expansions which have already occurred; for example if
7471 you create a simply expanded variable its value is expanded during the
7472 definition; in that case the @code{value} function will return the
7473 same result as using the variable directly.
7475 The syntax of the @code{value} function is:
7477 @example
7478 $(value @var{variable})
7479 @end example
7481 Note that @var{variable} is the @emph{name} of a variable, not a
7482 @emph{reference} to that variable.  Therefore you would not normally
7483 use a @samp{$} or parentheses when writing it.  (You can, however, use
7484 a variable reference in the name if you want the name not to be a
7485 constant.)
7487 The result of this function is a string containing the value of
7488 @var{variable}, without any expansion occurring.  For example, in this
7489 makefile:
7491 @example
7492 @group
7493 FOO = $PATH
7495 all:
7496         @@echo $(FOO)
7497         @@echo $(value FOO)
7498 @end group
7499 @end example
7501 @noindent
7502 The first output line would be @code{ATH}, since the ``$P'' would be
7503 expanded as a @code{make} variable, while the second output line would
7504 be the current value of your @code{$PATH} environment variable, since
7505 the @code{value} function avoided the expansion.
7507 The @code{value} function is most often used in conjunction with the
7508 @code{eval} function (@pxref{Eval Function}).
7510 @node Eval Function, Origin Function, Value Function, Functions
7511 @comment  node-name,  next,  previous,  up
7512 @section The @code{eval} Function
7513 @findex eval
7514 @cindex evaluating makefile syntax
7515 @cindex makefile syntax, evaluating
7517 The @code{eval} function is very special: it allows you to define new
7518 makefile constructs that are not constant; which are the result of
7519 evaluating other variables and functions.  The argument to the
7520 @code{eval} function is expanded, then the results of that expansion
7521 are parsed as makefile syntax.  The expanded results can define new
7522 @code{make} variables, targets, implicit or explicit rules, etc.
7524 The result of the @code{eval} function is always the empty string;
7525 thus, it can be placed virtually anywhere in a makefile without
7526 causing syntax errors.
7528 It's important to realize that the @code{eval} argument is expanded
7529 @emph{twice}; first by the @code{eval} function, then the results of
7530 that expansion are expanded again when they are parsed as makefile
7531 syntax.  This means you may need to provide extra levels of escaping
7532 for ``$'' characters when using @code{eval}.  The @code{value}
7533 function (@pxref{Value Function}) can sometimes be useful in these
7534 situations, to circumvent unwanted expansions.
7536 Here is an example of how @code{eval} can be used; this example
7537 combines a number of concepts and other functions.  Although it might
7538 seem overly complex to use @code{eval} in this example, rather than
7539 just writing out the rules, consider two things: first, the template
7540 definition (in @code{PROGRAM_template}) could need to be much more
7541 complex than it is here; and second, you might put the complex,
7542 ``generic'' part of this example into another makefile, then include
7543 it in all the individual makefiles.  Now your individual makefiles are
7544 quite straightforward.
7546 @example
7547 @group
7548 PROGRAMS    = server client
7550 server_OBJS = server.o server_priv.o server_access.o
7551 server_LIBS = priv protocol
7553 client_OBJS = client.o client_api.o client_mem.o
7554 client_LIBS = protocol
7556 # Everything after this is generic
7558 .PHONY: all
7559 all: $(PROGRAMS)
7561 define PROGRAM_template =
7562  $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
7563  ALL_OBJS   += $$($(1)_OBJS)
7564 endef
7566 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
7568 $(PROGRAMS):
7569         $(LINK.o) $^ $(LDLIBS) -o $@@
7571 clean:
7572         rm -f $(ALL_OBJS) $(PROGRAMS)
7573 @end group
7574 @end example
7576 @node Origin Function, Flavor Function, Eval Function, Functions
7577 @section The @code{origin} Function
7578 @findex origin
7579 @cindex variables, origin of
7580 @cindex origin of variable
7582 The @code{origin} function is unlike most other functions in that it does
7583 not operate on the values of variables; it tells you something @emph{about}
7584 a variable.  Specifically, it tells you where it came from.
7586 The syntax of the @code{origin} function is:
7588 @example
7589 $(origin @var{variable})
7590 @end example
7592 Note that @var{variable} is the @emph{name} of a variable to inquire about,
7593 not a @emph{reference} to that variable.  Therefore you would not normally
7594 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7595 variable reference in the name if you want the name not to be a constant.)
7597 The result of this function is a string telling you how the variable
7598 @var{variable} was defined:
7600 @table @samp
7601 @item undefined
7603 if @var{variable} was never defined.
7605 @item default
7607 if @var{variable} has a default definition, as is usual with @code{CC}
7608 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
7609 Note that if you have redefined a default variable, the @code{origin}
7610 function will return the origin of the later definition.
7612 @item environment
7614 if @var{variable} was inherited from the environment provided to
7615 @code{make}.
7617 @item environment override
7619 if @var{variable} was inherited from the environment provided to
7620 @code{make}, and is overriding a setting for @var{variable} in the
7621 makefile as a result of the @w{@samp{-e}} option (@pxref{Options
7622 Summary, ,Summary of Options}).@refill
7624 @item file
7626 if @var{variable} was defined in a makefile.
7628 @item command line
7630 if @var{variable} was defined on the command line.
7632 @item override
7634 if @var{variable} was defined with an @code{override} directive in a
7635 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
7637 @item automatic
7639 if @var{variable} is an automatic variable defined for the execution
7640 of the recipe for each rule (@pxref{Automatic Variables}).
7641 @end table
7643 This information is primarily useful (other than for your curiosity) to
7644 determine if you want to believe the value of a variable.  For example,
7645 suppose you have a makefile @file{foo} that includes another makefile
7646 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
7647 if you run the command @w{@samp{make -f bar}}, even if the environment contains
7648 a definition of @code{bletch}.  However, if @file{foo} defined
7649 @code{bletch} before including @file{bar}, you do not want to override that
7650 definition.  This could be done by using an @code{override} directive in
7651 @file{foo}, giving that definition precedence over the later definition in
7652 @file{bar}; unfortunately, the @code{override} directive would also
7653 override any command line definitions.  So, @file{bar} could
7654 include:@refill
7656 @example
7657 @group
7658 ifdef bletch
7659 ifeq "$(origin bletch)" "environment"
7660 bletch = barf, gag, etc.
7661 endif
7662 endif
7663 @end group
7664 @end example
7666 @noindent
7667 If @code{bletch} has been defined from the environment, this will redefine
7670 If you want to override a previous definition of @code{bletch} if it came
7671 from the environment, even under @samp{-e}, you could instead write:
7673 @example
7674 @group
7675 ifneq "$(findstring environment,$(origin bletch))" ""
7676 bletch = barf, gag, etc.
7677 endif
7678 @end group
7679 @end example
7681 Here the redefinition takes place if @samp{$(origin bletch)} returns either
7682 @samp{environment} or @samp{environment override}.
7683 @xref{Text Functions, , Functions for String Substitution and Analysis}.
7685 @node Flavor Function, Make Control Functions, Origin Function, Functions
7686 @section The @code{flavor} Function
7687 @findex flavor
7688 @cindex variables, flavor of
7689 @cindex flavor of variable
7691 The @code{flavor} function, like the @code{origin} function, does not
7692 operate on the values of variables but rather it tells you something
7693 @emph{about} a variable.  Specifically, it tells you the flavor of a
7694 variable (@pxref{Flavors, ,The Two Flavors of Variables}).
7696 The syntax of the @code{flavor} function is:
7698 @example
7699 $(flavor @var{variable})
7700 @end example
7702 Note that @var{variable} is the @emph{name} of a variable to inquire about,
7703 not a @emph{reference} to that variable.  Therefore you would not normally
7704 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7705 variable reference in the name if you want the name not to be a constant.)
7707 The result of this function is a string that identifies the flavor of the
7708 variable @var{variable}:
7710 @table @samp
7711 @item undefined
7713 if @var{variable} was never defined.
7715 @item recursive
7717 if @var{variable} is a recursively expanded variable.
7719 @item simple
7721 if @var{variable} is a simply expanded variable.
7723 @end table
7725 @node Make Control Functions, Shell Function, Flavor Function, Functions
7726 @section Functions That Control Make
7727 @cindex functions, for controlling make
7728 @cindex controlling make
7730 These functions control the way make runs.  Generally, they are used to
7731 provide information to the user of the makefile or to cause make to stop
7732 if some sort of environmental error is detected.
7734 @table @code
7735 @item $(error @var{text}@dots{})
7736 @findex error
7737 @cindex error, stopping on
7738 @cindex stopping make
7739 Generates a fatal error where the message is @var{text}.  Note that
7740 the error is generated whenever this function is evaluated.  So, if
7741 you put it inside a recipe or on the right side of a recursive
7742 variable assignment, it won't be evaluated until later.  The
7743 @var{text} will be expanded before the error is generated.
7745 For example,
7747 @example
7748 ifdef ERROR1
7749 $(error error is $(ERROR1))
7750 endif
7751 @end example
7753 @noindent
7754 will generate a fatal error during the read of the makefile if the
7755 @code{make} variable @code{ERROR1} is defined.  Or,
7757 @example
7758 ERR = $(error found an error!)
7760 .PHONY: err
7761 err: ; $(ERR)
7762 @end example
7764 @noindent
7765 will generate a fatal error while @code{make} is running, if the
7766 @code{err} target is invoked.
7768 @item $(warning @var{text}@dots{})
7769 @findex warning
7770 @cindex warnings, printing
7771 @cindex printing user warnings
7772 This function works similarly to the @code{error} function, above,
7773 except that @code{make} doesn't exit.  Instead, @var{text} is expanded
7774 and the resulting message is displayed, but processing of the makefile
7775 continues.
7777 The result of the expansion of this function is the empty string.
7779 @item $(info @var{text}@dots{})
7780 @findex info
7781 @cindex printing messages
7782 This function does nothing more than print its (expanded) argument(s)
7783 to standard output.  No makefile name or line number is added.  The
7784 result of the expansion of this function is the empty string.
7785 @end table
7787 @node Shell Function, Guile Function, Make Control Functions, Functions
7788 @section The @code{shell} Function
7789 @findex shell
7790 @cindex command expansion
7791 @cindex backquotes
7792 @cindex shell command, function for
7794 The @code{shell} function is unlike any other function other than the
7795 @code{wildcard} function
7796 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
7797 communicates with the world outside of @code{make}.
7799 The @code{shell} function performs the same function that backquotes
7800 (@samp{`}) perform in most shells: it does @dfn{command expansion}.
7801 This means that it takes as an argument a shell command and evaluates
7802 to the output of the command.  The only processing @code{make} does on
7803 the result is to convert each newline (or carriage-return / newline
7804 pair) to a single space.  If there is a trailing (carriage-return
7805 and) newline it will simply be removed.@refill
7807 The commands run by calls to the @code{shell} function are run when the
7808 function calls are expanded (@pxref{Reading Makefiles, , How
7809 @code{make} Reads a Makefile}).  Because this function involves
7810 spawning a new shell, you should carefully consider the performance
7811 implications of using the @code{shell} function within recursively
7812 expanded variables vs.@: simply expanded variables (@pxref{Flavors, ,The
7813 Two Flavors of Variables}).
7815 Here are some examples of the use of the @code{shell} function:
7817 @example
7818 contents := $(shell cat foo)
7819 @end example
7821 @noindent
7822 sets @code{contents} to the contents of the file @file{foo}, with a space
7823 (rather than a newline) separating each line.
7825 @example
7826 files := $(shell echo *.c)
7827 @end example
7829 @noindent
7830 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
7831 using a very strange shell, this has the same result as
7832 @w{@samp{$(wildcard *.c)}} (as long as at least one @samp{.c} file
7833 exists).@refill
7835 @node Guile Function,  , Shell Function, Functions
7836 @section The @code{guile} Function
7837 @findex guile
7838 @cindex Guile
7840 GNU make may be built with support for GNU Guile as an embedded
7841 extension language.  You can check the @code{.FEATURES} variable for
7842 the word @samp{guile} to determine if your version of GNU make
7843 provides this capability.
7845 GNU Guile implements the Scheme language.  A review of GNU Guile and
7846 the Scheme language and its features is beyond the scope of this
7847 manual: see the documentation for GNU Guile and Scheme.
7849 If GNU Guile is available as an extension language, there will be one
7850 new @code{make} function available: @code{guile}.  The @code{guile}
7851 function takes one argument which is first expanded by @code{make} in
7852 the normal fashion, then passed to the GNU Guile evaluator.  The
7853 result of the evaluator is converted into a string and used as the
7854 expansion of the @code{guile} function in the makefile.
7856 Similarly, there are Guile procedures exposed by @code{make} for use
7857 in Guile scripts.
7859 @menu
7860 * Guile Types::                 Converting Guile types to @code{make} strings.
7861 * Guile Interface::             Invoking @code{make} functions from Guile.
7862 * Guile Example::               Example using Guile in @code{make}.
7863 @end menu
7865 @node Guile Types, Guile Interface, Guile Function, Guile Function
7866 @subsection Conversion of Guile Types
7867 @cindex convert guile types
7868 @cindex guile, conversion of types
7869 @cindex types, conversion of
7871 There is only one ``data type'' in @code{make}: a string.  GNU Guile,
7872 on the other hand, provides a rich variety of different data types.
7873 An important aspect of the interface between @code{make} and GNU Guile
7874 is the conversion of Guile data types into @code{make} strings.
7876 This conversion is relevant in two places: when a makefile invokes the
7877 @code{guile} function to evaluate a Guile expression, the result of
7878 that evaluation must be converted into a make string so it can be
7879 further evaluated by @code{make}.  And secondly, when a Guile script
7880 invokes one of the procedures exported by @code{make} the argument
7881 provided to the procedure must be converted into a string.
7883 The conversion of Guile types into @code{make} strings is as below:
7885 @table @code
7886 @item #f
7887 False is converted into the empty string: in @code{make} conditionals
7888 the empty string is considered false.
7890 @item #t
7891 True is converted to the string @samp{#t}: in @code{make} conditionals
7892 any non-empty string is considered true.
7894 @item symbol
7895 @item number
7896 A symbol or number is converted into the string representation of that
7897 symbol or number.
7899 @item character
7900 A printable character is converted to the same character.
7902 @item string
7903 A string containing only printable characters is converted to the same
7904 string.
7906 @item list
7907 A list is converted recursively according to the above rules.  This
7908 implies that any structured list will be flattened (that is, a result
7909 of @samp{'(a b (c d) e)} will be converted to the @code{make} string
7910 @samp{a b c d e}).
7912 @item other
7913 Any other Guile type results in an error.  In future versions of
7914 @code{make}, other Guile types may be converted.
7916 @end table
7918 The translation of @samp{#f} (to the empty string) and @samp{#t} (to
7919 the non-empty string @samp{#t}) is designed to allow you to use Guile
7920 boolean results directly as @code{make} boolean conditions.  For
7921 example:
7923 @example
7924 $(if $(guile (access? "myfile" R_OK)),$(info myfile exists))
7925 @end example
7927 As a consequence of these conversion rules you must consider the
7928 result of your Guile script, as that result will be converted into a
7929 string and parsed by @code{make}.  If there is no natural result for
7930 the script (that is, the script exists solely for its side-effects),
7931 you should add @samp{#f} as the final expression in order to avoid
7932 syntax errors in your makefile.
7934 @node Guile Interface, Guile Example, Guile Types, Guile Function
7935 @subsection Interfaces from Guile to @code{make}
7936 @cindex make interface to guile
7937 @cindex make procedures in guile
7939 In addition to the @code{guile} function available in makefiles,
7940 @code{make} exposes some procedures for use in your Guile scripts.  At
7941 startup @code{make} creates a new Guile module, @code{gnu make}, and
7942 exports these procedures as public interfaces from that module:
7944 @table @code
7945 @item gmk-expand
7946 This procedure takes a single argument which is converted into a
7947 string.  The string is expanded by @code{make} using normal
7948 @code{make} expansion rules.  The result of the expansion is converted
7949 into a Guile string and provided as the result of the procedure.
7951 @item gmk-eval
7952 This procedure takes a single argument which is converted into a
7953 string.  The string is evaluated by @code{make} as if it were a
7954 makefile.  This is the same capability available via the @code{eval}
7955 function (@pxref{Eval Function}).  The result of the @code{gmk-eval}
7956 procedure is always the empty string.
7958 @item gmk-var
7959 This procedure takes a single argument which is converted into a
7960 string.  The string is assumed to be the name of a @code{make}
7961 variable, which is then expanded.  The expansion is converted into a
7962 string and provided as the result of the procedure.
7964 @end table
7966 @node Guile Example,  , Guile Interface, Guile Function
7967 @subsection Example Using Guile in @code{make}
7968 @cindex Guile example
7969 @cindex example using Guile
7971 Here is a very simple example using GNU Guile to manage writing to a
7972 file.  These Guile procedures simply open a file, allow writing to the
7973 file (one string per line), and close the file.  Note that because we
7974 cannot store complex values such as Guile ports in @code{make}
7975 variables, we'll keep the port as a global variable in the Guile
7976 interpreter.
7978 You can create Guile functions easily using @code{define}/@code{endef}
7979 to create a Guile script, then use the @code{guile} function to
7980 internalize it:
7982 @example
7983 @group
7984 define GUILEIO
7985 ;; A simple Guile IO library for GNU make
7987 (define MKPORT #f)
7989 (define (mkopen name mode)
7990   (set! MKPORT (open-file name mode))
7991   #f)
7993 (define (mkwrite s)
7994   (display s MKPORT)
7995   (newline MKPORT)
7996   #f)
7998 (define (mkclose)
7999   (close-port MKPORT)
8000   #f)
8003 endef
8005 # Internalize the Guile IO functions
8006 $(guile $(GUILEIO))
8007 @end group
8008 @end example
8010 If you have a significant amount of Guile support code, you might
8011 consider keeping it in a different file (e.g., @file{guileio.scm}) and
8012 then loading it in your makefile using the @code{guile} function:
8014 @example
8015 $(guile (load "guileio.scm"))
8016 @end example
8018 An advantage to this method is that when editing @file{guileio.scm},
8019 your editor will understand that this file contains Scheme syntax
8020 rather than makefile syntax.
8022 Now you can use these Guile functions to create files.  Suppose you
8023 need to operate on a very large list, which cannot fit on the command
8024 line, but the utility you're using accepts the list as input as well:
8026 @example
8027 @group
8028 prog: $(PREREQS)
8029         @@$(guile (mkopen "tmp.out" "w")) \
8030          $(foreach X,$^,$(guile (mkwrite "$(X)"))) \
8031          $(guile (mkclose))
8032         $(LINK) < tmp.out
8033 @end group
8034 @end example
8036 A more comprehensive suite of file manipulation procedures is possible
8037 of course.  You could, for example, maintain multiple output files at
8038 the same time by choosing a symbol for each one and using it as the
8039 key to a hash table, where the value is a port, then returning the
8040 symbol to be stored in a @code{make} variable.
8043 @node Running, Implicit Rules, Functions, Top
8044 @chapter How to Run @code{make}
8046 A makefile that says how to recompile a program can be used in more
8047 than one way.  The simplest use is to recompile every file that is out
8048 of date.  Usually, makefiles are written so that if you run
8049 @code{make} with no arguments, it does just that.
8051 But you might want to update only some of the files; you might want to use
8052 a different compiler or different compiler options; you might want just to
8053 find out which files are out of date without changing them.
8055 By giving arguments when you run @code{make}, you can do any of these
8056 things and many others.
8058 @cindex exit status of make
8059 The exit status of @code{make} is always one of three values:
8060 @table @code
8061 @item 0
8062 The exit status is zero if @code{make} is successful.
8063 @item 2
8064 The exit status is two if @code{make} encounters any errors.
8065 It will print messages describing the particular errors.
8066 @item 1
8067 The exit status is one if you use the @samp{-q} flag and @code{make}
8068 determines that some target is not already up to date.
8069 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8070 @end table
8072 @menu
8073 * Makefile Arguments::          How to specify which makefile to use.
8074 * Goals::                       How to use goal arguments to specify which
8075                                   parts of the makefile to use.
8076 * Instead of Execution::        How to use mode flags to specify what
8077                                   kind of thing to do with the recipes
8078                                   in the makefile other than simply
8079                                   execute them.
8080 * Avoiding Compilation::        How to avoid recompiling certain files.
8081 * Overriding::                  How to override a variable to specify
8082                                   an alternate compiler and other things.
8083 * Testing::                     How to proceed past some errors, to
8084                                   test compilation.
8085 * Options Summary::             Summary of Options
8086 @end menu
8088 @node Makefile Arguments, Goals, Running, Running
8089 @section Arguments to Specify the Makefile
8090 @cindex @code{--file}
8091 @cindex @code{--makefile}
8092 @cindex @code{-f}
8094 The way to specify the name of the makefile is with the @samp{-f} or
8095 @samp{--file} option (@samp{--makefile} also works).  For example,
8096 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
8098 If you use the @samp{-f} flag several times and follow each @samp{-f}
8099 with an argument, all the specified files are used jointly as
8100 makefiles.
8102 If you do not use the @samp{-f} or @samp{--file} flag, the default is
8103 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
8104 that order, and use the first of these three which exists or can be made
8105 (@pxref{Makefiles, ,Writing Makefiles}).@refill
8107 @node Goals, Instead of Execution, Makefile Arguments, Running
8108 @section Arguments to Specify the Goals
8109 @cindex goal, how to specify
8111 The @dfn{goals} are the targets that @code{make} should strive ultimately
8112 to update.  Other targets are updated as well if they appear as
8113 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
8115 By default, the goal is the first target in the makefile (not counting
8116 targets that start with a period).  Therefore, makefiles are usually
8117 written so that the first target is for compiling the entire program or
8118 programs they describe.  If the first rule in the makefile has several
8119 targets, only the first target in the rule becomes the default goal, not
8120 the whole list.  You can manage the selection of the default goal from
8121 within your makefile using the @code{.DEFAULT_GOAL} variable
8122 (@pxref{Special Variables, , Other Special Variables}).
8124 You can also specify a different goal or goals with command line
8125 arguments to @code{make}.  Use the name of the goal as an argument.
8126 If you specify several goals, @code{make} processes each of them in
8127 turn, in the order you name them.
8129 Any target in the makefile may be specified as a goal (unless it
8130 starts with @samp{-} or contains an @samp{=}, in which case it will be
8131 parsed as a switch or variable definition, respectively).  Even
8132 targets not in the makefile may be specified, if @code{make} can find
8133 implicit rules that say how to make them.
8135 @vindex MAKECMDGOALS
8136 @code{Make} will set the special variable @code{MAKECMDGOALS} to the
8137 list of goals you specified on the command line.  If no goals were given
8138 on the command line, this variable is empty.  Note that this variable
8139 should be used only in special circumstances.
8141 An example of appropriate use is to avoid including @file{.d} files
8142 during @code{clean} rules (@pxref{Automatic Prerequisites}), so
8143 @code{make} won't create them only to immediately remove them
8144 again:@refill
8146 @example
8147 @group
8148 sources = foo.c bar.c
8150 ifneq ($(MAKECMDGOALS),clean)
8151 include $(sources:.c=.d)
8152 endif
8153 @end group
8154 @end example
8156 One use of specifying a goal is if you want to compile only a part of
8157 the program, or only one of several programs.  Specify as a goal each
8158 file that you wish to remake.  For example, consider a directory containing
8159 several programs, with a makefile that starts like this:
8161 @example
8162 .PHONY: all
8163 all: size nm ld ar as
8164 @end example
8166 If you are working on the program @code{size}, you might want to say
8167 @w{@samp{make size}} so that only the files of that program are recompiled.
8169 Another use of specifying a goal is to make files that are not normally
8170 made.  For example, there may be a file of debugging output, or a
8171 version of the program that is compiled specially for testing, which has
8172 a rule in the makefile but is not a prerequisite of the default goal.
8174 Another use of specifying a goal is to run the recipe associated with
8175 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
8176 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
8177 a phony target named @file{clean} which deletes everything except source
8178 files.  Naturally, this is done only if you request it explicitly with
8179 @w{@samp{make clean}}.  Following is a list of typical phony and empty
8180 target names.  @xref{Standard Targets}, for a detailed list of all the
8181 standard target names which GNU software packages use.
8183 @table @file
8184 @item all
8185 @cindex @code{all} @r{(standard target)}
8186 Make all the top-level targets the makefile knows about.
8188 @item clean
8189 @cindex @code{clean} @r{(standard target)}
8190 Delete all files that are normally created by running @code{make}.
8192 @item mostlyclean
8193 @cindex @code{mostlyclean} @r{(standard target)}
8194 Like @samp{clean}, but may refrain from deleting a few files that people
8195 normally don't want to recompile.  For example, the @samp{mostlyclean}
8196 target for GCC does not delete @file{libgcc.a}, because recompiling it
8197 is rarely necessary and takes a lot of time.
8199 @item distclean
8200 @cindex @code{distclean} @r{(standard target)}
8201 @itemx realclean
8202 @cindex @code{realclean} @r{(standard target)}
8203 @itemx clobber
8204 @cindex @code{clobber} @r{(standard target)}
8205 Any of these targets might be defined to delete @emph{more} files than
8206 @samp{clean} does.  For example, this would delete configuration files
8207 or links that you would normally create as preparation for compilation,
8208 even if the makefile itself cannot create these files.
8210 @item install
8211 @cindex @code{install} @r{(standard target)}
8212 Copy the executable file into a directory that users typically search
8213 for commands; copy any auxiliary files that the executable uses into
8214 the directories where it will look for them.
8216 @item print
8217 @cindex @code{print} @r{(standard target)}
8218 Print listings of the source files that have changed.
8220 @item tar
8221 @cindex @code{tar} @r{(standard target)}
8222 Create a tar file of the source files.
8224 @item shar
8225 @cindex @code{shar} @r{(standard target)}
8226 Create a shell archive (shar file) of the source files.
8228 @item dist
8229 @cindex @code{dist} @r{(standard target)}
8230 Create a distribution file of the source files.  This might
8231 be a tar file, or a shar file, or a compressed version of one of the
8232 above, or even more than one of the above.
8234 @item TAGS
8235 @cindex @code{TAGS} @r{(standard target)}
8236 Update a tags table for this program.
8238 @item check
8239 @cindex @code{check} @r{(standard target)}
8240 @itemx test
8241 @cindex @code{test} @r{(standard target)}
8242 Perform self tests on the program this makefile builds.
8243 @end table
8245 @node Instead of Execution, Avoiding Compilation, Goals, Running
8246 @section Instead of Executing Recipes
8247 @cindex execution, instead of
8248 @cindex recipes, instead of executing
8250 The makefile tells @code{make} how to tell whether a target is up to date,
8251 and how to update each target.  But updating the targets is not always
8252 what you want.  Certain options specify other activities for @code{make}.
8254 @comment Extra blank lines make it print better.
8255 @table @samp
8256 @item -n
8257 @itemx --just-print
8258 @itemx --dry-run
8259 @itemx --recon
8260 @cindex @code{--just-print}
8261 @cindex @code{--dry-run}
8262 @cindex @code{--recon}
8263 @cindex @code{-n}
8265 ``No-op''.  Causes @code{make} to print the recipes that are needed to
8266 make the targets up to date, but not actually execute them.  Note that
8267 some recipes are still executed, even with this flag (@pxref{MAKE
8268 Variable, ,How the @code{MAKE} Variable Works}).  Also any recipes
8269 needed to update included makefiles are still executed
8270 (@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).
8272 @item -t
8273 @itemx --touch
8274 @cindex @code{--touch}
8275 @cindex touching files
8276 @cindex target, touching
8277 @cindex @code{-t}
8279 ``Touch''.  Marks targets as up to date without actually changing
8280 them.  In other words, @code{make} pretends to update the targets but
8281 does not really change their contents; instead only their modified
8282 times are updated.
8284 @item -q
8285 @itemx --question
8286 @cindex @code{--question}
8287 @cindex @code{-q}
8288 @cindex question mode
8290 ``Question''.  Silently check whether the targets are up to date, but
8291 do not execute recipes; the exit code shows whether any updates are
8292 needed.
8294 @item -W @var{file}
8295 @itemx --what-if=@var{file}
8296 @itemx --assume-new=@var{file}
8297 @itemx --new-file=@var{file}
8298 @cindex @code{--what-if}
8299 @cindex @code{-W}
8300 @cindex @code{--assume-new}
8301 @cindex @code{--new-file}
8302 @cindex what if
8303 @cindex files, assuming new
8305 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
8306 files' modification times are recorded by @code{make} as being the present
8307 time, although the actual modification times remain the same.
8308 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
8309 to see what would happen if you were to modify specific files.@refill
8310 @end table
8312 With the @samp{-n} flag, @code{make} prints the recipe that it would
8313 normally execute but usually does not execute it.
8315 With the @samp{-t} flag, @code{make} ignores the recipes in the rules
8316 and uses (in effect) the command @code{touch} for each target that needs to
8317 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
8318 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
8319 the program @code{touch}.  It does the work directly.
8321 With the @samp{-q} flag, @code{make} prints nothing and executes no
8322 recipes, but the exit status code it returns is zero if and only if the
8323 targets to be considered are already up to date.  If the exit status is
8324 one, then some updating needs to be done.  If @code{make} encounters an
8325 error, the exit status is two, so you can distinguish an error from a
8326 target that is not up to date.
8328 It is an error to use more than one of these three flags in the same
8329 invocation of @code{make}.
8331 @cindex +, and recipe execution
8332 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect recipe
8333 lines that begin with @samp{+} characters or contain the strings
8334 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
8335 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
8336 is run regardless of these options.  Other lines in the same rule are
8337 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
8338 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
8340 @cindex phony targets and recipe execution
8341 The @samp{-t} flag prevents phony targets (@pxref{Phony Targets}) from
8342 being updated, unless there are recipe lines beginning with @samp{+}
8343 or containing @samp{$(MAKE)} or @samp{$@{MAKE@}}.
8345 The @samp{-W} flag provides two features:
8347 @itemize @bullet
8348 @item
8349 If you also use the @samp{-n} or @samp{-q} flag, you can see what
8350 @code{make} would do if you were to modify some files.
8352 @item
8353 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
8354 executing recipes, the @samp{-W} flag can direct @code{make} to act as
8355 if some files had been modified, without actually running the recipes
8356 for those files.@refill
8357 @end itemize
8359 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
8360 information about @code{make} or about the makefiles in use
8361 (@pxref{Options Summary, ,Summary of Options}).@refill
8363 @node Avoiding Compilation, Overriding, Instead of Execution, Running
8364 @section Avoiding Recompilation of Some Files
8365 @cindex @code{-o}
8366 @cindex @code{--old-file}
8367 @cindex @code{--assume-old}
8368 @cindex files, assuming old
8369 @cindex files, avoiding recompilation of
8370 @cindex recompilation, avoiding
8372 Sometimes you may have changed a source file but you do not want to
8373 recompile all the files that depend on it.  For example, suppose you add
8374 a macro or a declaration to a header file that many other files depend
8375 on.  Being conservative, @code{make} assumes that any change in the
8376 header file requires recompilation of all dependent files, but you know
8377 that they do not need to be recompiled and you would rather not waste
8378 the time waiting for them to compile.
8380 If you anticipate the problem before changing the header file, you can
8381 use the @samp{-t} flag.  This flag tells @code{make} not to run the
8382 recipes in the rules, but rather to mark the target up to date by
8383 changing its last-modification date.  You would follow this procedure:
8385 @enumerate
8386 @item
8387 Use the command @samp{make} to recompile the source files that really
8388 need recompilation, ensuring that the object files are up-to-date
8389 before you begin.
8391 @item
8392 Make the changes in the header files.
8394 @item
8395 Use the command @samp{make -t} to mark all the object files as
8396 up to date.  The next time you run @code{make}, the changes in the
8397 header files will not cause any recompilation.
8398 @end enumerate
8400 If you have already changed the header file at a time when some files
8401 do need recompilation, it is too late to do this.  Instead, you can
8402 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
8403 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
8404 that the file itself will not be remade, and nothing else will be
8405 remade on its account.  Follow this procedure:
8407 @enumerate
8408 @item
8409 Recompile the source files that need compilation for reasons independent
8410 of the particular header file, with @samp{make -o @var{headerfile}}.
8411 If several header files are involved, use a separate @samp{-o} option
8412 for each header file.
8414 @item
8415 Touch all the object files with @samp{make -t}.
8416 @end enumerate
8418 @node Overriding, Testing, Avoiding Compilation, Running
8419 @section Overriding Variables
8420 @cindex overriding variables with arguments
8421 @cindex variables, overriding with arguments
8422 @cindex command line variables
8423 @cindex variables, command line
8425 An argument that contains @samp{=} specifies the value of a variable:
8426 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
8427 If you specify a value in this way, all ordinary assignments of the same
8428 variable in the makefile are ignored; we say they have been
8429 @dfn{overridden} by the command line argument.
8431 The most common way to use this facility is to pass extra flags to
8432 compilers.  For example, in a properly written makefile, the variable
8433 @code{CFLAGS} is included in each recipe that runs the C compiler, so a
8434 file @file{foo.c} would be compiled something like this:
8436 @example
8437 cc -c $(CFLAGS) foo.c
8438 @end example
8440 Thus, whatever value you set for @code{CFLAGS} affects each compilation
8441 that occurs.  The makefile probably specifies the usual value for
8442 @code{CFLAGS}, like this:
8444 @example
8445 CFLAGS=-g
8446 @end example
8448 Each time you run @code{make}, you can override this value if you
8449 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
8450 compilation will be done with @samp{cc -c -g -O}.  (This also
8451 illustrates how you can use quoting in the shell to enclose spaces and
8452 other special characters in the value of a variable when you override
8453 it.)
8455 The variable @code{CFLAGS} is only one of many standard variables that
8456 exist just so that you can change them this way.  @xref{Implicit
8457 Variables, , Variables Used by Implicit Rules}, for a complete list.
8459 You can also program the makefile to look at additional variables of your
8460 own, giving the user the ability to control other aspects of how the
8461 makefile works by changing the variables.
8463 When you override a variable with a command line argument, you can
8464 define either a recursively-expanded variable or a simply-expanded
8465 variable.  The examples shown above make a recursively-expanded
8466 variable; to make a simply-expanded variable, write @samp{:=} instead
8467 of @samp{=}.  But, unless you want to include a variable reference or
8468 function call in the @emph{value} that you specify, it makes no
8469 difference which kind of variable you create.
8471 There is one way that the makefile can change a variable that you have
8472 overridden.  This is to use the @code{override} directive, which is a line
8473 that looks like this: @samp{override @var{variable} = @var{value}}
8474 (@pxref{Override Directive, ,The @code{override} Directive}).
8476 @node Testing, Options Summary, Overriding, Running
8477 @section Testing the Compilation of a Program
8478 @cindex testing compilation
8479 @cindex compilation, testing
8481 Normally, when an error happens in executing a shell command, @code{make}
8482 gives up immediately, returning a nonzero status.  No further recipes are
8483 executed for any target.  The error implies that the goal cannot be
8484 correctly remade, and @code{make} reports this as soon as it knows.
8486 When you are compiling a program that you have just changed, this is not
8487 what you want.  Instead, you would rather that @code{make} try compiling
8488 every file that can be tried, to show you as many compilation errors
8489 as possible.
8491 @cindex @code{-k}
8492 @cindex @code{--keep-going}
8493 On these occasions, you should use the @samp{-k} or
8494 @samp{--keep-going} flag.  This tells @code{make} to continue to
8495 consider the other prerequisites of the pending targets, remaking them
8496 if necessary, before it gives up and returns nonzero status.  For
8497 example, after an error in compiling one object file, @samp{make -k}
8498 will continue compiling other object files even though it already
8499 knows that linking them will be impossible.  In addition to continuing
8500 after failed shell commands, @samp{make -k} will continue as much as
8501 possible after discovering that it does not know how to make a target
8502 or prerequisite file.  This will always cause an error message, but
8503 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
8504 ,Summary of Options}).@refill
8506 The usual behavior of @code{make} assumes that your purpose is to get the
8507 goals up to date; once @code{make} learns that this is impossible, it might
8508 as well report the failure immediately.  The @samp{-k} flag says that the
8509 real purpose is to test as much as possible of the changes made in the
8510 program, perhaps to find several independent problems so that you can
8511 correct them all before the next attempt to compile.  This is why Emacs'
8512 @kbd{M-x compile} command passes the @samp{-k} flag by default.
8514 @node Options Summary,  , Testing, Running
8515 @section Summary of Options
8516 @cindex options
8517 @cindex flags
8518 @cindex switches
8520 Here is a table of all the options @code{make} understands:
8522 @table @samp
8523 @item -b
8524 @cindex @code{-b}
8525 @itemx -m
8526 @cindex @code{-m}
8527 These options are ignored for compatibility with other versions of @code{make}.
8529 @item -B
8530 @cindex @code{-B}
8531 @itemx --always-make
8532 @cindex @code{--always-make}
8533 Consider all targets out-of-date.  GNU @code{make} proceeds to
8534 consider targets and their prerequisites using the normal algorithms;
8535 however, all targets so considered are always remade regardless of the
8536 status of their prerequisites.  To avoid infinite recursion, if
8537 @code{MAKE_RESTARTS} (@pxref{Special Variables, , Other Special
8538 Variables}) is set to a number greater than 0 this option is disabled
8539 when considering whether to remake makefiles (@pxref{Remaking
8540 Makefiles, , How Makefiles Are Remade}).
8542 @item -C @var{dir}
8543 @cindex @code{-C}
8544 @itemx --directory=@var{dir}
8545 @cindex @code{--directory}
8546 Change to directory @var{dir} before reading the makefiles.  If multiple
8547 @samp{-C} options are specified, each is interpreted relative to the
8548 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
8549 This is typically used with recursive invocations of @code{make}
8550 (@pxref{Recursion, ,Recursive Use of @code{make}}).
8552 @item -d
8553 @cindex @code{-d}
8554 @c Extra blank line here makes the table look better.
8556 Print debugging information in addition to normal processing.  The
8557 debugging information says which files are being considered for
8558 remaking, which file-times are being compared and with what results,
8559 which files actually need to be remade, which implicit rules are
8560 considered and which are applied---everything interesting about how
8561 @code{make} decides what to do.  The @code{-d} option is equivalent to
8562 @samp{--debug=a} (see below).
8564 @item --debug[=@var{options}]
8565 @cindex @code{--debug}
8566 @c Extra blank line here makes the table look better.
8568 Print debugging information in addition to normal processing.  Various
8569 levels and types of output can be chosen.  With no arguments, print the
8570 ``basic'' level of debugging.  Possible arguments are below; only the
8571 first character is considered, and values must be comma- or
8572 space-separated.
8574 @table @code
8575 @item a (@i{all})
8576 All types of debugging output are enabled.  This is equivalent to using
8577 @samp{-d}.
8579 @item b (@i{basic})
8580 Basic debugging prints each target that was found to be out-of-date, and
8581 whether the build was successful or not.
8583 @item v (@i{verbose})
8584 A level above @samp{basic}; includes messages about which makefiles were
8585 parsed, prerequisites that did not need to be rebuilt, etc.  This option
8586 also enables @samp{basic} messages.
8588 @item i (@i{implicit})
8589 Prints messages describing the implicit rule searches for each target.
8590 This option also enables @samp{basic} messages.
8592 @item j (@i{jobs})
8593 Prints messages giving details on the invocation of specific sub-commands.
8595 @item m (@i{makefile})
8596 By default, the above messages are not enabled while trying to remake
8597 the makefiles.  This option enables messages while rebuilding makefiles,
8598 too.  Note that the @samp{all} option does enable this option.  This
8599 option also enables @samp{basic} messages.
8600 @end table
8602 @item -e
8603 @cindex @code{-e}
8604 @itemx --environment-overrides
8605 @cindex @code{--environment-overrides}
8606 Give variables taken from the environment precedence
8607 over variables from makefiles.
8608 @xref{Environment, ,Variables from the Environment}.
8610 @item --eval=@var{string}
8611 @cindex @code{--eval}
8612 @c Extra blank line here makes the table look better.
8614 Evaluate @var{string} as makefile syntax.  This is a command-line
8615 version of the @code{eval} function (@pxref{Eval Function}).  The
8616 evaluation is performed after the default rules and variables have
8617 been defined, but before any makefiles are read.
8619 @item -f @var{file}
8620 @cindex @code{-f}
8621 @itemx --file=@var{file}
8622 @cindex @code{--file}
8623 @itemx --makefile=@var{file}
8624 @cindex @code{--makefile}
8625 Read the file named @var{file} as a makefile.
8626 @xref{Makefiles, ,Writing Makefiles}.
8628 @item -h
8629 @cindex @code{-h}
8630 @itemx --help
8631 @cindex @code{--help}
8632 @c Extra blank line here makes the table look better.
8634 Remind you of the options that @code{make} understands and then exit.
8636 @item -i
8637 @cindex @code{-i}
8638 @itemx --ignore-errors
8639 @cindex @code{--ignore-errors}
8640 Ignore all errors in recipes executed to remake files.
8641 @xref{Errors, ,Errors in Recipes}.
8643 @item -I @var{dir}
8644 @cindex @code{-I}
8645 @itemx --include-dir=@var{dir}
8646 @cindex @code{--include-dir}
8647 Specifies a directory @var{dir} to search for included makefiles.
8648 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
8649 options are used to specify several directories, the directories are
8650 searched in the order specified.
8652 @item -j [@var{jobs}]
8653 @cindex @code{-j}
8654 @itemx --jobs[=@var{jobs}]
8655 @cindex @code{--jobs}
8656 Specifies the number of recipes (jobs) to run simultaneously.  With no
8657 argument, @code{make} runs as many recipes simultaneously as possible.
8658 If there is more than one @samp{-j} option, the last one is effective.
8659 @xref{Parallel, ,Parallel Execution}, for more information on how
8660 recipes are run.  Note that this option is ignored on MS-DOS.
8662 @item -k
8663 @cindex @code{-k}
8664 @itemx --keep-going
8665 @cindex @code{--keep-going}
8666 Continue as much as possible after an error.  While the target that
8667 failed, and those that depend on it, cannot be remade, the other
8668 prerequisites of these targets can be processed all the same.
8669 @xref{Testing, ,Testing the Compilation of a Program}.
8671 @item -l [@var{load}]
8672 @cindex @code{-l}
8673 @itemx --load-average[=@var{load}]
8674 @cindex @code{--load-average}
8675 @itemx --max-load[=@var{load}]
8676 @cindex @code{--max-load}
8677 Specifies that no new recipes should be started if there are other
8678 recipes running and the load average is at least @var{load} (a
8679 floating-point number).  With no argument, removes a previous load
8680 limit.  @xref{Parallel, ,Parallel Execution}.
8682 @item -L
8683 @cindex @code{-L}
8684 @itemx --check-symlink-times
8685 @cindex @code{--check-symlink-times}
8686 On systems that support symbolic links, this option causes @code{make}
8687 to consider the timestamps on any symbolic links in addition to the
8688 timestamp on the file referenced by those links.  When this option is
8689 provided, the most recent timestamp among the file and the symbolic
8690 links is taken as the modification time for this target file.
8692 @item -n
8693 @cindex @code{-n}
8694 @itemx --just-print
8695 @cindex @code{--just-print}
8696 @itemx --dry-run
8697 @cindex @code{--dry-run}
8698 @itemx --recon
8699 @cindex @code{--recon}
8700 @c Extra blank line here makes the table look better.
8702 Print the recipe that would be executed, but do not execute it (except
8703 in certain circumstances).
8704 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8706 @item -o @var{file}
8707 @cindex @code{-o}
8708 @itemx --old-file=@var{file}
8709 @cindex @code{--old-file}
8710 @itemx --assume-old=@var{file}
8711 @cindex @code{--assume-old}
8712 Do not remake the file @var{file} even if it is older than its
8713 prerequisites, and do not remake anything on account of changes in
8714 @var{file}.  Essentially the file is treated as very old and its rules
8715 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
8716 Some Files}.@refill
8718 @item -p
8719 @cindex @code{-p}
8720 @itemx --print-data-base
8721 @cindex @code{--print-data-base}
8722 @cindex data base of @code{make} rules
8723 @cindex predefined rules and variables, printing
8724 Print the data base (rules and variable values) that results from
8725 reading the makefiles; then execute as usual or as otherwise
8726 specified.  This also prints the version information given by the
8727 @samp{-v} switch (see below).  To print the data base without trying
8728 to remake any files, use @w{@samp{make -qp}}.  To print the data base
8729 of predefined rules and variables, use @w{@samp{make -p -f /dev/null}}.
8730 The data base output contains file name and line number information for
8731 recipe and variable definitions, so it can be a useful debugging tool
8732 in complex environments.
8734 @item -q
8735 @cindex @code{-q}
8736 @itemx --question
8737 @cindex @code{--question}
8738 ``Question mode''.  Do not run any recipes, or print anything; just
8739 return an exit status that is zero if the specified targets are already
8740 up to date, one if any remaking is required, or two if an error is
8741 encountered.  @xref{Instead of Execution, ,Instead of Executing
8742 Recipes}.@refill
8744 @item -r
8745 @cindex @code{-r}
8746 @itemx --no-builtin-rules
8747 @cindex @code{--no-builtin-rules}
8748 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
8749 ,Using Implicit Rules}).  You can still define your own by writing
8750 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
8751 Rules}).  The @samp{-r} option also clears out the default list of
8752 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
8753 Rules}).  But you can still define your own suffixes with a rule for
8754 @code{.SUFFIXES}, and then define your own suffix rules.  Note that only
8755 @emph{rules} are affected by the @code{-r} option; default variables
8756 remain in effect (@pxref{Implicit Variables, ,Variables Used by Implicit
8757 Rules}); see the @samp{-R} option below.
8759 @item -R
8760 @cindex @code{-R}
8761 @itemx --no-builtin-variables
8762 @cindex @code{--no-builtin-variables}
8763 Eliminate use of the built-in rule-specific variables (@pxref{Implicit
8764 Variables, ,Variables Used by Implicit Rules}).  You can still define
8765 your own, of course.  The @samp{-R} option also automatically enables
8766 the @samp{-r} option (see above), since it doesn't make sense to have
8767 implicit rules without any definitions for the variables that they use.
8769 @item -s
8770 @cindex @code{-s}
8771 @itemx --silent
8772 @cindex @code{--silent}
8773 @itemx --quiet
8774 @cindex @code{--quiet}
8775 @c Extra blank line here makes the table look better.
8777 Silent operation; do not print the recipes as they are executed.
8778 @xref{Echoing, ,Recipe Echoing}.
8780 @item -S
8781 @cindex @code{-S}
8782 @itemx --no-keep-going
8783 @cindex @code{--no-keep-going}
8784 @itemx --stop
8785 @cindex @code{--stop}
8786 @c Extra blank line here makes the table look better.
8788 Cancel the effect of the @samp{-k} option.  This is never necessary
8789 except in a recursive @code{make} where @samp{-k} might be inherited
8790 from the top-level @code{make} via @code{MAKEFLAGS}
8791 (@pxref{Recursion, ,Recursive Use of @code{make}})
8792 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.@refill
8794 @item -t
8795 @cindex @code{-t}
8796 @itemx --touch
8797 @cindex @code{--touch}
8798 @c Extra blank line here makes the table look better.
8800 Touch files (mark them up to date without really changing them)
8801 instead of running their recipes.  This is used to pretend that the
8802 recipes were done, in order to fool future invocations of
8803 @code{make}.  @xref{Instead of Execution, ,Instead of Executing Recipes}.
8805 @item --trace
8806 @cindex @code{--trace}
8807 @c Extra blank line here makes the table look better.
8809 Print the entire recipe to be executed, even for recipes that are
8810 normally silent (due to @code{.SILENT} or @samp{@@}).  Also print the
8811 makefile name and line number where the recipe was defined.
8813 @item -v
8814 @cindex @code{-v}
8815 @itemx --version
8816 @cindex @code{--version}
8817 Print the version of the @code{make} program plus a copyright, a list
8818 of authors, and a notice that there is no warranty; then exit.
8820 @item -w
8821 @cindex @code{-w}
8822 @itemx --print-directory
8823 @cindex @code{--print-directory}
8824 Print a message containing the working directory both before and after
8825 executing the makefile.  This may be useful for tracking down errors
8826 from complicated nests of recursive @code{make} commands.
8827 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
8828 rarely need to specify this option since @samp{make} does it for you;
8829 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
8831 @itemx --no-print-directory
8832 @cindex @code{--no-print-directory}
8833 Disable printing of the working directory under @code{-w}.
8834 This option is useful when @code{-w} is turned on automatically,
8835 but you do not want to see the extra messages.
8836 @xref{-w Option, ,The @samp{--print-directory} Option}.
8838 @item -W @var{file}
8839 @cindex @code{-W}
8840 @itemx --what-if=@var{file}
8841 @cindex @code{--what-if}
8842 @itemx --new-file=@var{file}
8843 @cindex @code{--new-file}
8844 @itemx --assume-new=@var{file}
8845 @cindex @code{--assume-new}
8846 Pretend that the target @var{file} has just been modified.  When used
8847 with the @samp{-n} flag, this shows you what would happen if you were
8848 to modify that file.  Without @samp{-n}, it is almost the same as
8849 running a @code{touch} command on the given file before running
8850 @code{make}, except that the modification time is changed only in the
8851 imagination of @code{make}.
8852 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8854 @item --warn-undefined-variables
8855 @cindex @code{--warn-undefined-variables}
8856 @cindex variables, warning for undefined
8857 @cindex undefined variables, warning message
8858 Issue a warning message whenever @code{make} sees a reference to an
8859 undefined variable.  This can be helpful when you are trying to debug
8860 makefiles which use variables in complex ways.
8861 @end table
8863 @node Implicit Rules, Archives, Running, Top
8864 @chapter Using Implicit Rules
8865 @cindex implicit rule
8866 @cindex rule, implicit
8868 Certain standard ways of remaking target files are used very often.  For
8869 example, one customary way to make an object file is from a C source file
8870 using the C compiler, @code{cc}.
8872 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
8873 that you do not have to specify them in detail when you want to use
8874 them.  For example, there is an implicit rule for C compilation.  File
8875 names determine which implicit rules are run.  For example, C
8876 compilation typically takes a @file{.c} file and makes a @file{.o} file.
8877 So @code{make} applies the implicit rule for C compilation when it sees
8878 this combination of file name endings.@refill
8880 A chain of implicit rules can apply in sequence; for example, @code{make}
8881 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
8882 @iftex
8883 @xref{Chained Rules, ,Chains of Implicit Rules}.
8884 @end iftex
8886 The built-in implicit rules use several variables in their recipes so
8887 that, by changing the values of the variables, you can change the way the
8888 implicit rule works.  For example, the variable @code{CFLAGS} controls the
8889 flags given to the C compiler by the implicit rule for C compilation.
8890 @iftex
8891 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
8892 @end iftex
8894 You can define your own implicit rules by writing @dfn{pattern rules}.
8895 @iftex
8896 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
8897 @end iftex
8899 @dfn{Suffix rules} are a more limited way to define implicit rules.
8900 Pattern rules are more general and clearer, but suffix rules are
8901 retained for compatibility.
8902 @iftex
8903 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
8904 @end iftex
8906 @menu
8907 * Using Implicit::              How to use an existing implicit rule
8908                                   to get the recipes for updating a file.
8909 * Catalogue of Rules::          A list of built-in implicit rules.
8910 * Implicit Variables::          How to change what predefined rules do.
8911 * Chained Rules::               How to use a chain of implicit rules.
8912 * Pattern Rules::               How to define new implicit rules.
8913 * Last Resort::                 How to define a recipe for rules which
8914                                   cannot find any.
8915 * Suffix Rules::                The old-fashioned style of implicit rule.
8916 * Implicit Rule Search::        The precise algorithm for applying
8917                                   implicit rules.
8918 @end menu
8920 @node Using Implicit, Catalogue of Rules, Implicit Rules, Implicit Rules
8921 @section Using Implicit Rules
8922 @cindex implicit rule, how to use
8923 @cindex rule, implicit, how to use
8925 To allow @code{make} to find a customary method for updating a target
8926 file, all you have to do is refrain from specifying recipes yourself.
8927 Either write a rule with no recipe, or don't write a rule at all.
8928 Then @code{make} will figure out which implicit rule to use based on
8929 which kind of source file exists or can be made.
8931 For example, suppose the makefile looks like this:
8933 @example
8934 foo : foo.o bar.o
8935         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
8936 @end example
8938 @noindent
8939 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
8940 will automatically look for an implicit rule that tells how to update it.
8941 This happens whether or not the file @file{foo.o} currently exists.
8943 If an implicit rule is found, it can supply both a recipe and one or
8944 more prerequisites (the source files).  You would want to write a rule
8945 for @file{foo.o} with no recipe if you need to specify additional
8946 prerequisites, such as header files, that the implicit rule cannot
8947 supply.
8949 Each implicit rule has a target pattern and prerequisite patterns.  There may
8950 be many implicit rules with the same target pattern.  For example, numerous
8951 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
8952 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
8953 that actually applies is the one whose prerequisites exist or can be made.
8954 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
8955 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
8956 compiler; and so on.
8958 Of course, when you write the makefile, you know which implicit rule you
8959 want @code{make} to use, and you know it will choose that one because you
8960 know which possible prerequisite files are supposed to exist.
8961 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
8962 for a catalogue of all the predefined implicit rules.
8964 Above, we said an implicit rule applies if the required prerequisites ``exist
8965 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
8966 the makefile as a target or a prerequisite, or if an implicit rule can be
8967 recursively found for how to make it.  When an implicit prerequisite is the
8968 result of another implicit rule, we say that @dfn{chaining} is occurring.
8969 @xref{Chained Rules, ,Chains of Implicit Rules}.
8971 In general, @code{make} searches for an implicit rule for each target, and
8972 for each double-colon rule, that has no recipe.  A file that is mentioned
8973 only as a prerequisite is considered a target whose rule specifies nothing,
8974 so implicit rule search happens for it.  @xref{Implicit Rule Search, ,Implicit Rule Search Algorithm}, for the
8975 details of how the search is done.
8977 Note that explicit prerequisites do not influence implicit rule search.
8978 For example, consider this explicit rule:
8980 @example
8981 foo.o: foo.p
8982 @end example
8984 @noindent
8985 The prerequisite on @file{foo.p} does not necessarily mean that
8986 @code{make} will remake @file{foo.o} according to the implicit rule to
8987 make an object file, a @file{.o} file, from a Pascal source file, a
8988 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
8989 rule to make an object file from a C source file is used instead,
8990 because it appears before the Pascal rule in the list of predefined
8991 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
8992 Rules}).
8994 If you do not want an implicit rule to be used for a target that has no
8995 recipe, you can give that target an empty recipe by writing a semicolon
8996 (@pxref{Empty Recipes, ,Defining Empty Recipes}).
8998 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
8999 @section Catalogue of Implicit Rules
9000 @cindex implicit rule, predefined
9001 @cindex rule, implicit, predefined
9003 Here is a catalogue of predefined implicit rules which are always
9004 available unless the makefile explicitly overrides or cancels them.
9005 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
9006 canceling or overriding an implicit rule.  The @samp{-r} or
9007 @samp{--no-builtin-rules} option cancels all predefined rules.
9009 This manual only documents the default rules available on POSIX-based
9010 operating systems.  Other operating systems, such as VMS, Windows,
9011 OS/2, etc. may have different sets of default rules.  To see the full
9012 list of default rules and variables available in your version of GNU
9013 @code{make}, run @samp{make -p} in a directory with no makefile.
9015 Not all of these rules will always be defined, even when the @samp{-r}
9016 option is not given.  Many of the predefined implicit rules are
9017 implemented in @code{make} as suffix rules, so which ones will be
9018 defined depends on the @dfn{suffix list} (the list of prerequisites of
9019 the special target @code{.SUFFIXES}).  The default suffix list is:
9020 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
9021 @code{.C}, @code{.cpp}, @code{.p}, @code{.f}, @code{.F}, @code{.m},
9022 @code{.r}, @code{.y}, @code{.l}, @code{.ym}, @code{.lm}, @code{.s},
9023 @code{.S}, @code{.mod}, @code{.sym}, @code{.def}, @code{.h},
9024 @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo}, @code{.texi},
9025 @code{.txinfo}, @code{.w}, @code{.ch} @code{.web}, @code{.sh},
9026 @code{.elc}, @code{.el}.  All of the implicit rules described below
9027 whose prerequisites have one of these suffixes are actually suffix
9028 rules.  If you modify the suffix list, the only predefined suffix
9029 rules in effect will be those named by one or two of the suffixes that
9030 are on the list you specify; rules whose suffixes fail to be on the
9031 list are disabled.  @xref{Suffix Rules, ,Old-Fashioned Suffix Rules},
9032 for full details on suffix rules.
9034 @table @asis
9035 @item Compiling C programs
9036 @cindex C, rule to compile
9037 @pindex cc
9038 @pindex gcc
9039 @pindex .o
9040 @pindex .c
9041 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
9042 a recipe of the form @samp{$(CC) $(CPPFLAGS) $(CFLAGS) -c}.@refill
9044 @item Compiling C++ programs
9045 @cindex C++, rule to compile
9046 @pindex g++
9047 @pindex .cc
9048 @pindex .cpp
9049 @pindex .C
9050 @file{@var{n}.o} is made automatically from @file{@var{n}.cc},
9051 @file{@var{n}.cpp}, or @file{@var{n}.C} with a recipe of the form
9052 @samp{$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c}.  We encourage you to use the
9053 suffix @samp{.cc} for C++ source files instead of @samp{.C}.@refill
9055 @item Compiling Pascal programs
9056 @cindex Pascal, rule to compile
9057 @pindex pc
9058 @pindex .p
9059 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
9060 with the recipe @samp{$(PC) $(PFLAGS) -c}.@refill
9062 @item Compiling Fortran and Ratfor programs
9063 @cindex Fortran, rule to compile
9064 @cindex Ratfor, rule to compile
9065 @pindex f77
9066 @pindex .f
9067 @pindex .r
9068 @pindex .F
9069 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
9070 @file{@var{n}.F} or @file{@var{n}.f} by running the
9071 Fortran compiler.  The precise recipe used is as follows:@refill
9073 @table @samp
9074 @item .f
9075 @samp{$(FC) $(FFLAGS) -c}.
9076 @item .F
9077 @samp{$(FC) $(FFLAGS) $(CPPFLAGS) -c}.
9078 @item .r
9079 @samp{$(FC) $(FFLAGS) $(RFLAGS) -c}.
9080 @end table
9082 @item Preprocessing Fortran and Ratfor programs
9083 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
9084 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
9085 Ratfor or preprocessable Fortran program into a strict Fortran
9086 program.  The precise recipe used is as follows:@refill
9088 @table @samp
9089 @item .F
9090 @samp{$(FC) $(CPPFLAGS) $(FFLAGS) -F}.
9091 @item .r
9092 @samp{$(FC) $(FFLAGS) $(RFLAGS) -F}.
9093 @end table
9095 @item Compiling Modula-2 programs
9096 @cindex Modula-2, rule to compile
9097 @pindex m2c
9098 @pindex .sym
9099 @pindex .def
9100 @pindex .mod
9101 @file{@var{n}.sym} is made from @file{@var{n}.def} with a recipe
9102 of the form @samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}.  @file{@var{n}.o}
9103 is made from @file{@var{n}.mod}; the form is:
9104 @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.@refill
9106 @need 1200
9107 @item Assembling and preprocessing assembler programs
9108 @cindex assembly, rule to compile
9109 @pindex as
9110 @pindex .s
9111 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
9112 running the assembler, @code{as}.  The precise recipe is
9113 @samp{$(AS) $(ASFLAGS)}.@refill
9115 @pindex .S
9116 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
9117 running the C preprocessor, @code{cpp}.  The precise recipe is
9118 @w{@samp{$(CPP) $(CPPFLAGS)}}.
9120 @item Linking a single object file
9121 @cindex linking, predefined rule for
9122 @pindex ld
9123 @pindex .o
9124 @file{@var{n}} is made automatically from @file{@var{n}.o} by running
9125 the linker (usually called @code{ld}) via the C compiler.  The precise
9126 recipe used is @w{@samp{$(CC) $(LDFLAGS) @var{n}.o $(LOADLIBES) $(LDLIBS)}}.
9128 This rule does the right thing for a simple program with only one
9129 source file.  It will also do the right thing if there are multiple
9130 object files (presumably coming from various other source files), one
9131 of which has a name matching that of the executable file.  Thus,
9133 @example
9134 x: y.o z.o
9135 @end example
9137 @noindent
9138 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
9140 @example
9141 @group
9142 cc -c x.c -o x.o
9143 cc -c y.c -o y.o
9144 cc -c z.c -o z.o
9145 cc x.o y.o z.o -o x
9146 rm -f x.o
9147 rm -f y.o
9148 rm -f z.o
9149 @end group
9150 @end example
9152 @noindent
9153 In more complicated cases, such as when there is no object file whose
9154 name derives from the executable file name, you must write an explicit
9155 recipe for linking.
9157 Each kind of file automatically made into @samp{.o} object files will
9158 be automatically linked by using the compiler (@samp{$(CC)},
9159 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
9160 assemble @samp{.s} files) without the @samp{-c} option.  This could be
9161 done by using the @samp{.o} object files as intermediates, but it is
9162 faster to do the compiling and linking in one step, so that's how it's
9163 done.@refill
9165 @item Yacc for C programs
9166 @pindex yacc
9167 @cindex Yacc, rule to run
9168 @pindex .y
9169 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
9170 running Yacc with the recipe @samp{$(YACC) $(YFLAGS)}.
9172 @item Lex for C programs
9173 @pindex lex
9174 @cindex Lex, rule to run
9175 @pindex .l
9176 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
9177 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
9179 @item Lex for Ratfor programs
9180 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
9181 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
9183 The convention of using the same suffix @samp{.l} for all Lex files
9184 regardless of whether they produce C code or Ratfor code makes it
9185 impossible for @code{make} to determine automatically which of the two
9186 languages you are using in any particular case.  If @code{make} is
9187 called upon to remake an object file from a @samp{.l} file, it must
9188 guess which compiler to use.  It will guess the C compiler, because
9189 that is more common.  If you are using Ratfor, make sure @code{make}
9190 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
9191 are using Ratfor exclusively, with no C files, remove @samp{.c} from
9192 the list of implicit rule suffixes with:@refill
9194 @example
9195 @group
9196 .SUFFIXES:
9197 .SUFFIXES: .o .r .f .l @dots{}
9198 @end group
9199 @end example
9201 @item Making Lint Libraries from C, Yacc, or Lex programs
9202 @pindex lint
9203 @cindex @code{lint}, rule to run
9204 @pindex .ln
9205 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
9206 The precise recipe is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.
9207 The same recipe is used on the C code produced from
9208 @file{@var{n}.y} or @file{@var{n}.l}.@refill
9210 @item @TeX{} and Web
9211 @cindex @TeX{}, rule to run
9212 @cindex Web, rule to run
9213 @pindex tex
9214 @pindex cweave
9215 @pindex weave
9216 @pindex tangle
9217 @pindex ctangle
9218 @pindex .dvi
9219 @pindex .tex
9220 @pindex .web
9221 @pindex .w
9222 @pindex .ch
9223 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the recipe
9224 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
9225 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
9226 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
9227 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
9228 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
9229 or can be made) with @samp{$(CTANGLE)}.@refill
9231 @item Texinfo and Info
9232 @cindex Texinfo, rule to format
9233 @cindex Info, rule to format
9234 @pindex texi2dvi
9235 @pindex makeinfo
9236 @pindex .texinfo
9237 @pindex .info
9238 @pindex .texi
9239 @pindex .txinfo
9240 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo},
9241 @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with the recipe
9242 @w{@samp{$(TEXI2DVI) $(TEXI2DVI_FLAGS)}}.  @file{@var{n}.info} is made from
9243 @file{@var{n}.texinfo}, @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with
9244 the recipe @w{@samp{$(MAKEINFO) $(MAKEINFO_FLAGS)}}.
9246 @item RCS
9247 @cindex RCS, rule to extract from
9248 @pindex co
9249 @pindex ,v @r{(RCS file extension)}
9250 Any file @file{@var{n}} is extracted if necessary from an RCS file
9251 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
9252 recipe used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
9253 extracted from RCS if it already exists, even if the RCS file is
9254 newer.  The rules for RCS are terminal
9255 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
9256 so RCS files cannot be generated from another source; they must
9257 actually exist.@refill
9259 @item SCCS
9260 @cindex SCCS, rule to extract from
9261 @pindex get
9262 @pindex s. @r{(SCCS file prefix)}
9263 Any file @file{@var{n}} is extracted if necessary from an SCCS file
9264 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
9265 recipe used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
9266 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
9267 so SCCS files cannot be generated from another source; they must
9268 actually exist.@refill
9270 @pindex .sh
9271 For the benefit of SCCS, a file @file{@var{n}} is copied from
9272 @file{@var{n}.sh} and made executable (by everyone).  This is for
9273 shell scripts that are checked into SCCS.  Since RCS preserves the
9274 execution permission of a file, you do not need to use this feature
9275 with RCS.@refill
9277 We recommend that you avoid using of SCCS.  RCS is widely held to be
9278 superior, and is also free.  By choosing free software in place of
9279 comparable (or inferior) proprietary software, you support the free
9280 software movement.
9281 @end table
9283 Usually, you want to change only the variables listed in the table
9284 above, which are documented in the following section.
9286 However, the recipes in built-in implicit rules actually use
9287 variables such as @code{COMPILE.c}, @code{LINK.p}, and
9288 @code{PREPROCESS.S}, whose values contain the recipes listed above.
9290 @code{make} follows the convention that the rule to compile a
9291 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
9292 Similarly, the rule to produce an executable from a @file{.@var{x}}
9293 file uses @code{LINK.@var{x}}; and the rule to preprocess a
9294 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
9296 @vindex OUTPUT_OPTION
9297 Every rule that produces an object file uses the variable
9298 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
9299 contain @samp{-o $@@}, or to be empty, depending on a compile-time
9300 option.  You need the @samp{-o} option to ensure that the output goes
9301 into the right file when the source file is in a different directory,
9302 as when using @code{VPATH} (@pxref{Directory Search}).  However,
9303 compilers on some systems do not accept a @samp{-o} switch for object
9304 files.  If you use such a system, and use @code{VPATH}, some
9305 compilations will put their output in the wrong place.
9306 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
9307 the value @w{@samp{; mv $*.o $@@}}.
9309 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
9310 @section Variables Used by Implicit Rules
9311 @cindex flags for compilers
9313 The recipes in built-in implicit rules make liberal use of certain
9314 predefined variables.  You can alter the values of these variables in
9315 the makefile, with arguments to @code{make}, or in the environment to
9316 alter how the implicit rules work without redefining the rules
9317 themselves.  You can cancel all variables used by implicit rules with
9318 the @samp{-R} or @samp{--no-builtin-variables} option.
9320 For example, the recipe used to compile a C source file actually says
9321 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
9322 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
9323 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
9324 used for all C compilations performed by the implicit rule.  By redefining
9325 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
9326 each compilation.  @emph{All} implicit rules that do C compilation use
9327 @samp{$(CC)} to get the program name for the compiler and @emph{all}
9328 include @samp{$(CFLAGS)} among the arguments given to the compiler.@refill
9330 The variables used in implicit rules fall into two classes: those that are
9331 names of programs (like @code{CC}) and those that contain arguments for the
9332 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
9333 some command arguments, but it must start with an actual executable program
9334 name.)  If a variable value contains more than one argument, separate them
9335 with spaces.
9337 The following tables describe of some of the more commonly-used predefined
9338 variables.  This list is not exhaustive, and the default values shown here may
9339 not be what @code{make} selects for your environment.  To see the
9340 complete list of predefined variables for your instance of GNU @code{make} you
9341 can run @samp{make -p} in a directory with no makefiles.
9343 Here is a table of some of the more common variables used as names of
9344 programs in built-in rules:
9346 @table @code
9347 @item AR
9348 @vindex AR
9349 Archive-maintaining program; default @samp{ar}.
9350 @pindex ar
9352 @item AS
9353 @vindex AS
9354 Program for compiling assembly files; default @samp{as}.
9355 @pindex as
9357 @item CC
9358 @vindex CC
9359 Program for compiling C programs; default @samp{cc}.
9360 @pindex cc
9362 @item CXX
9363 @vindex CXX
9364 Program for compiling C++ programs; default @samp{g++}.
9365 @pindex g++
9367 @item CPP
9368 @vindex CPP
9369 Program for running the C preprocessor, with results to standard output;
9370 default @samp{$(CC) -E}.
9372 @item FC
9373 @vindex FC
9374 Program for compiling or preprocessing Fortran and Ratfor programs;
9375 default @samp{f77}.
9376 @pindex f77
9378 @item M2C
9379 @vindex M2C
9380 Program to use to compile Modula-2 source code; default @samp{m2c}.
9381 @pindex m2c
9383 @item PC
9384 @vindex PC
9385 Program for compiling Pascal programs; default @samp{pc}.
9386 @pindex pc
9388 @item CO
9389 @vindex CO
9390 Program for extracting a file from RCS; default @samp{co}.
9391 @pindex co
9393 @item GET
9394 @vindex GET
9395 Program for extracting a file from SCCS; default @samp{get}.
9396 @pindex get
9398 @item LEX
9399 @vindex LEX
9400 Program to use to turn Lex grammars into source code; default @samp{lex}.
9401 @pindex lex
9403 @item YACC
9404 @vindex YACC
9405 Program to use to turn Yacc grammars into source code; default @samp{yacc}.
9406 @pindex yacc
9408 @item LINT
9409 @vindex LINT
9410 Program to use to run lint on source code; default @samp{lint}.
9411 @pindex lint
9413 @item MAKEINFO
9414 @vindex MAKEINFO
9415 Program to convert a Texinfo source file into an Info file; default
9416 @samp{makeinfo}.
9417 @pindex makeinfo
9419 @item TEX
9420 @vindex TEX
9421 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
9422 default @samp{tex}.
9423 @pindex tex
9425 @item TEXI2DVI
9426 @vindex TEXI2DVI
9427 Program to make @TeX{} @sc{dvi} files from Texinfo source;
9428 default @samp{texi2dvi}.
9429 @pindex texi2dvi
9431 @item WEAVE
9432 @vindex WEAVE
9433 Program to translate Web into @TeX{}; default @samp{weave}.
9434 @pindex weave
9436 @item CWEAVE
9437 @vindex CWEAVE
9438 Program to translate C Web into @TeX{}; default @samp{cweave}.
9439 @pindex cweave
9441 @item TANGLE
9442 @vindex TANGLE
9443 Program to translate Web into Pascal; default @samp{tangle}.
9444 @pindex tangle
9446 @item CTANGLE
9447 @vindex CTANGLE
9448 Program to translate C Web into C; default @samp{ctangle}.
9449 @pindex ctangle
9451 @item RM
9452 @vindex RM
9453 Command to remove a file; default @samp{rm -f}.
9454 @pindex rm
9455 @end table
9457 Here is a table of variables whose values are additional arguments for the
9458 programs above.  The default values for all of these is the empty
9459 string, unless otherwise noted.
9461 @table @code
9462 @item ARFLAGS
9463 @vindex ARFLAGS
9464 Flags to give the archive-maintaining program; default @samp{rv}.
9466 @item ASFLAGS
9467 @vindex ASFLAGS
9468 Extra flags to give to the assembler (when explicitly
9469 invoked on a @samp{.s} or @samp{.S} file).
9471 @item CFLAGS
9472 @vindex CFLAGS
9473 Extra flags to give to the C compiler.
9475 @item CXXFLAGS
9476 @vindex CXXFLAGS
9477 Extra flags to give to the C++ compiler.
9479 @item COFLAGS
9480 @vindex COFLAGS
9481 Extra flags to give to the RCS @code{co} program.
9483 @item CPPFLAGS
9484 @vindex CPPFLAGS
9485 Extra flags to give to the C preprocessor and programs
9486 that use it (the C and Fortran compilers).
9488 @item FFLAGS
9489 @vindex FFLAGS
9490 Extra flags to give to the Fortran compiler.
9492 @item GFLAGS
9493 @vindex GFLAGS
9494 Extra flags to give to the SCCS @code{get} program.
9496 @item LDFLAGS
9497 @vindex LDFLAGS
9498 Extra flags to give to compilers when they are supposed to invoke the linker,
9499 @samp{ld}.
9501 @item LDLIBS
9502 @vindex LDLIBS
9503 @vindex LOADLIBES
9504 Library flags or names given to compilers when they are supposed to
9505 invoke the linker, @samp{ld}.  @code{LOADLIBES} is a deprecated (but
9506 still supported) alternative to @code{LDLIBS}.
9508 @item LFLAGS
9509 @vindex LFLAGS
9510 Extra flags to give to Lex.
9512 @item YFLAGS
9513 @vindex YFLAGS
9514 Extra flags to give to Yacc.
9516 @item PFLAGS
9517 @vindex PFLAGS
9518 Extra flags to give to the Pascal compiler.
9520 @item RFLAGS
9521 @vindex RFLAGS
9522 Extra flags to give to the Fortran compiler for Ratfor programs.
9524 @item LINTFLAGS
9525 @vindex LINTFLAGS
9526 Extra flags to give to lint.
9527 @end table
9529 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
9530 @section Chains of Implicit Rules
9532 @cindex chains of rules
9533 @cindex rule, implicit, chains of
9534 Sometimes a file can be made by a sequence of implicit rules.  For example,
9535 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
9536 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
9538 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
9539 special searching is required: @code{make} finds that the object file can
9540 be made by C compilation from @file{@var{n}.c}; later on, when considering
9541 how to make @file{@var{n}.c}, the rule for running Yacc is
9542 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
9543 updated.@refill
9545 @cindex intermediate files
9546 @cindex files, intermediate
9547 However, even if @file{@var{n}.c} does not exist and is not mentioned,
9548 @code{make} knows how to envision it as the missing link between
9549 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
9550 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
9551 intermediate file, it is entered in the data base as if it had been
9552 mentioned in the makefile, along with the implicit rule that says how to
9553 create it.@refill
9555 Intermediate files are remade using their rules just like all other
9556 files.  But intermediate files are treated differently in two ways.
9558 The first difference is what happens if the intermediate file does not
9559 exist.  If an ordinary file @var{b} does not exist, and @code{make}
9560 considers a target that depends on @var{b}, it invariably creates
9561 @var{b} and then updates the target from @var{b}.  But if @var{b} is an
9562 intermediate file, then @code{make} can leave well enough alone.  It
9563 won't bother updating @var{b}, or the ultimate target, unless some
9564 prerequisite of @var{b} is newer than that target or there is some other
9565 reason to update that target.
9567 The second difference is that if @code{make} @emph{does} create @var{b}
9568 in order to update something else, it deletes @var{b} later on after it
9569 is no longer needed.  Therefore, an intermediate file which did not
9570 exist before @code{make} also does not exist after @code{make}.
9571 @code{make} reports the deletion to you by printing a @samp{rm -f}
9572 command showing which file it is deleting.
9574 Ordinarily, a file cannot be intermediate if it is mentioned in the
9575 makefile as a target or prerequisite.  However, you can explicitly mark a
9576 file as intermediate by listing it as a prerequisite of the special target
9577 @code{.INTERMEDIATE}.  This takes effect even if the file is mentioned
9578 explicitly in some other way.
9580 @cindex intermediate files, preserving
9581 @cindex preserving intermediate files
9582 @cindex secondary files
9583 You can prevent automatic deletion of an intermediate file by marking it
9584 as a @dfn{secondary} file.  To do this, list it as a prerequisite of the
9585 special target @code{.SECONDARY}.  When a file is secondary, @code{make}
9586 will not create the file merely because it does not already exist, but
9587 @code{make} does not automatically delete the file.  Marking a file as
9588 secondary also marks it as intermediate.
9590 You can list the target pattern of an implicit rule (such as @samp{%.o})
9591 as a prerequisite of the special target @code{.PRECIOUS} to preserve
9592 intermediate files made by implicit rules whose target patterns match
9593 that file's name; see @ref{Interrupts}.@refill
9594 @cindex preserving with @code{.PRECIOUS}
9595 @cindex @code{.PRECIOUS} intermediate files
9597 A chain can involve more than two implicit rules.  For example, it is
9598 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
9599 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
9600 intermediate files that are deleted at the end.@refill
9602 No single implicit rule can appear more than once in a chain.  This means
9603 that @code{make} will not even consider such a ridiculous thing as making
9604 @file{foo} from @file{foo.o.o} by running the linker twice.  This
9605 constraint has the added benefit of preventing any infinite loop in the
9606 search for an implicit rule chain.
9608 There are some special implicit rules to optimize certain cases that would
9609 otherwise be handled by rule chains.  For example, making @file{foo} from
9610 @file{foo.c} could be handled by compiling and linking with separate
9611 chained rules, using @file{foo.o} as an intermediate file.  But what
9612 actually happens is that a special rule for this case does the compilation
9613 and linking with a single @code{cc} command.  The optimized rule is used in
9614 preference to the step-by-step chain because it comes earlier in the
9615 ordering of rules.
9617 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
9618 @section Defining and Redefining Pattern Rules
9620 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
9621 rule looks like an ordinary rule, except that its target contains the
9622 character @samp{%} (exactly one of them).  The target is considered a
9623 pattern for matching file names; the @samp{%} can match any nonempty
9624 substring, while other characters match only themselves.  The prerequisites
9625 likewise use @samp{%} to show how their names relate to the target name.
9627 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
9628 @file{@var{stem}.o} from another file @file{@var{stem}.c}.@refill
9630 Note that expansion using @samp{%} in pattern rules occurs
9631 @strong{after} any variable or function expansions, which take place
9632 when the makefile is read.  @xref{Using Variables, , How to Use
9633 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
9635 @menu
9636 * Pattern Intro::               An introduction to pattern rules.
9637 * Pattern Examples::            Examples of pattern rules.
9638 * Automatic Variables::         How to use automatic variables in the
9639                                   recipe of implicit rules.
9640 * Pattern Match::               How patterns match.
9641 * Match-Anything Rules::        Precautions you should take prior to
9642                                   defining rules that can match any
9643                                   target file whatever.
9644 * Canceling Rules::             How to override or cancel built-in rules.
9645 @end menu
9647 @node Pattern Intro, Pattern Examples, Pattern Rules, Pattern Rules
9648 @subsection Introduction to Pattern Rules
9649 @cindex pattern rule
9650 @cindex rule, pattern
9652 A pattern rule contains the character @samp{%} (exactly one of them)
9653 in the target; otherwise, it looks exactly like an ordinary rule.  The
9654 target is a pattern for matching file names; the @samp{%} matches any
9655 nonempty substring, while other characters match only themselves.
9656 @cindex target pattern, implicit
9657 @cindex @code{%}, in pattern rules
9659 For example, @samp{%.c} as a pattern matches any file name that ends in
9660 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
9661 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
9662 (There must be at least one character to match the @samp{%}.)  The substring
9663 that the @samp{%} matches is called the @dfn{stem}.@refill
9665 @samp{%} in a prerequisite of a pattern rule stands for the same stem
9666 that was matched by the @samp{%} in the target.  In order for the
9667 pattern rule to apply, its target pattern must match the file name
9668 under consideration and all of its prerequisites (after pattern
9669 substitution) must name files that exist or can be made.  These files
9670 become prerequisites of the target.
9671 @cindex prerequisite pattern, implicit
9673 Thus, a rule of the form
9675 @example
9676 %.o : %.c ; @var{recipe}@dots{}
9677 @end example
9679 @noindent
9680 specifies how to make a file @file{@var{n}.o}, with another file
9681 @file{@var{n}.c} as its prerequisite, provided that @file{@var{n}.c}
9682 exists or can be made.
9684 There may also be prerequisites that do not use @samp{%}; such a prerequisite
9685 attaches to every file made by this pattern rule.  These unvarying
9686 prerequisites are useful occasionally.
9688 A pattern rule need not have any prerequisites that contain @samp{%}, or
9689 in fact any prerequisites at all.  Such a rule is effectively a general
9690 wildcard.  It provides a way to make any file that matches the target
9691 pattern.  @xref{Last Resort}.
9693 More than one pattern rule may match a target.  In this case
9694 @code{make} will choose the ``best fit'' rule.  @xref{Pattern Match,
9695 ,How Patterns Match}.
9697 @c !!! The end of of this paragraph should be rewritten.  --bob
9698 Pattern rules may have more than one target.  Unlike normal rules,
9699 this does not act as many different rules with the same prerequisites
9700 and recipe.  If a pattern rule has multiple targets, @code{make} knows
9701 that the rule's recipe is responsible for making all of the targets.
9702 The recipe is executed only once to make all the targets.  When
9703 searching for a pattern rule to match a target, the target patterns of
9704 a rule other than the one that matches the target in need of a rule
9705 are incidental: @code{make} worries only about giving a recipe and
9706 prerequisites to the file presently in question.  However, when this
9707 file's recipe is run, the other targets are marked as having been
9708 updated themselves.
9709 @cindex multiple targets, in pattern rule
9710 @cindex target, multiple in pattern rule
9712 @node Pattern Examples, Automatic Variables, Pattern Intro, Pattern Rules
9713 @subsection Pattern Rule Examples
9715 Here are some examples of pattern rules actually predefined in
9716 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
9717 files:@refill
9719 @example
9720 %.o : %.c
9721         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
9722 @end example
9724 @noindent
9725 defines a rule that can make any file @file{@var{x}.o} from
9726 @file{@var{x}.c}.  The recipe uses the automatic variables @samp{$@@} and
9727 @samp{$<} to substitute the names of the target file and the source file
9728 in each case where the rule applies (@pxref{Automatic Variables}).@refill
9730 Here is a second built-in rule:
9732 @example
9733 % :: RCS/%,v
9734         $(CO) $(COFLAGS) $<
9735 @end example
9737 @noindent
9738 defines a rule that can make any file @file{@var{x}} whatsoever from a
9739 corresponding file @file{@var{x},v} in the sub-directory @file{RCS}.  Since
9740 the target is @samp{%}, this rule will apply to any file whatever, provided
9741 the appropriate prerequisite file exists.  The double colon makes the rule
9742 @dfn{terminal}, which means that its prerequisite may not be an intermediate
9743 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).@refill
9745 @need 500
9746 This pattern rule has two targets:
9748 @example
9749 @group
9750 %.tab.c %.tab.h: %.y
9751         bison -d $<
9752 @end group
9753 @end example
9755 @noindent
9756 @c The following paragraph is rewritten to avoid overfull hboxes
9757 This tells @code{make} that the recipe @samp{bison -d @var{x}.y} will
9758 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
9759 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
9760 and the file @file{scan.o} depends on the file @file{parse.tab.h},
9761 when @file{parse.y} is changed, the recipe @samp{bison -d parse.y}
9762 will be executed only once, and the prerequisites of both
9763 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
9764 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
9765 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
9766 linked from @file{parse.tab.o}, @file{scan.o}, and its other
9767 prerequisites, and it will execute happily ever after.)@refill
9769 @node Automatic Variables, Pattern Match, Pattern Examples, Pattern Rules
9770 @subsection Automatic Variables
9771 @cindex automatic variables
9772 @cindex variables, automatic
9773 @cindex variables, and implicit rule
9775 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
9776 @samp{.o} file: how do you write the @samp{cc} command so that it operates
9777 on the right source file name?  You cannot write the name in the recipe,
9778 because the name is different each time the implicit rule is applied.
9780 What you do is use a special feature of @code{make}, the @dfn{automatic
9781 variables}.  These variables have values computed afresh for each rule that
9782 is executed, based on the target and prerequisites of the rule.  In this
9783 example, you would use @samp{$@@} for the object file name and @samp{$<}
9784 for the source file name.
9786 @cindex automatic variables in prerequisites
9787 @cindex prerequisites, and automatic variables
9788 It's very important that you recognize the limited scope in which
9789 automatic variable values are available: they only have values within
9790 the recipe.  In particular, you cannot use them anywhere
9791 within the target list of a rule; they have no value there and will
9792 expand to the empty string.  Also, they cannot be accessed directly
9793 within the prerequisite list of a rule.  A common mistake is
9794 attempting to use @code{$@@} within the prerequisites list; this will
9795 not work.  However, there is a special feature of GNU @code{make},
9796 secondary expansion (@pxref{Secondary Expansion}), which will allow
9797 automatic variable values to be used in prerequisite lists.
9799 Here is a table of automatic variables:
9801 @table @code
9802 @vindex $@@
9803 @vindex @@ @r{(automatic variable)}
9804 @item $@@
9805 The file name of the target of the rule.  If the target is an archive
9806 member, then @samp{$@@} is the name of the archive file.  In a pattern
9807 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
9808 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
9809 rule's recipe to be run.
9811 @vindex $%
9812 @vindex % @r{(automatic variable)}
9813 @item $%
9814 The target member name, when the target is an archive member.
9815 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
9816 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
9817 empty when the target is not an archive member.
9819 @vindex $<
9820 @vindex < @r{(automatic variable)}
9821 @item $<
9822 The name of the first prerequisite.  If the target got its recipe from
9823 an implicit rule, this will be the first prerequisite added by the
9824 implicit rule (@pxref{Implicit Rules}).
9826 @vindex $?
9827 @vindex ? @r{(automatic variable)}
9828 @item $?
9829 The names of all the prerequisites that are newer than the target, with
9830 spaces between them.  For prerequisites which are archive members, only
9831 the named member is used (@pxref{Archives}).
9832 @cindex prerequisites, list of changed
9833 @cindex list of changed prerequisites
9835 @vindex $^
9836 @vindex ^ @r{(automatic variable)}
9837 @item $^
9838 The names of all the prerequisites, with spaces between them.  For
9839 prerequisites which are archive members, only the named member is used
9840 (@pxref{Archives}).  A target has only one prerequisite on each other file
9841 it depends on, no matter how many times each file is listed as a
9842 prerequisite.  So if you list a prerequisite more than once for a target,
9843 the value of @code{$^} contains just one copy of the name.  This list
9844 does @strong{not} contain any of the order-only prerequisites; for those
9845 see the @samp{$|} variable, below.
9846 @cindex prerequisites, list of all
9847 @cindex list of all prerequisites
9849 @vindex $+
9850 @vindex + @r{(automatic variable)}
9851 @item $+
9852 This is like @samp{$^}, but prerequisites listed more than once are
9853 duplicated in the order they were listed in the makefile.  This is
9854 primarily useful for use in linking commands where it is meaningful to
9855 repeat library file names in a particular order.
9857 @vindex $|
9858 @vindex | @r{(automatic variable)}
9859 @item $|
9860 The names of all the order-only prerequisites, with spaces between
9861 them.
9863 @vindex $*
9864 @vindex * @r{(automatic variable)}
9865 @item $*
9866 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
9867 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
9868 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
9869 useful for constructing names of related files.@refill
9870 @cindex stem, variable for
9872 In a static pattern rule, the stem is part of the file name that matched
9873 the @samp{%} in the target pattern.
9875 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
9876 in that way.  Instead, if the target name ends with a recognized suffix
9877 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
9878 the target name minus the suffix.  For example, if the target name is
9879 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
9880 suffix.  GNU @code{make} does this bizarre thing only for compatibility
9881 with other implementations of @code{make}.  You should generally avoid
9882 using @samp{$*} except in implicit rules or static pattern rules.@refill
9884 If the target name in an explicit rule does not end with a recognized
9885 suffix, @samp{$*} is set to the empty string for that rule.
9886 @end table
9888 @samp{$?} is useful even in explicit rules when you wish to operate on only
9889 the prerequisites that have changed.  For example, suppose that an archive
9890 named @file{lib} is supposed to contain copies of several object files.
9891 This rule copies just the changed object files into the archive:
9893 @example
9894 @group
9895 lib: foo.o bar.o lose.o win.o
9896         ar r lib $?
9897 @end group
9898 @end example
9900 Of the variables listed above, four have values that are single file
9901 names, and three have values that are lists of file names.  These seven
9902 have variants that get just the file's directory name or just the file
9903 name within the directory.  The variant variables' names are formed by
9904 appending @samp{D} or @samp{F}, respectively.  These variants are
9905 semi-obsolete in GNU @code{make} since the functions @code{dir} and
9906 @code{notdir} can be used to get a similar effect (@pxref{File Name
9907 Functions, , Functions for File Names}).  Note, however, that the
9908 @samp{D} variants all omit the trailing slash which always appears in
9909 the output of the @code{dir} function.  Here is a table of the variants:
9911 @table @samp
9912 @vindex $(@@D)
9913 @vindex @@D @r{(automatic variable)}
9914 @item $(@@D)
9915 The directory part of the file name of the target, with the trailing
9916 slash removed.  If the value of @samp{$@@} is @file{dir/foo.o} then
9917 @samp{$(@@D)} is @file{dir}.  This value is @file{.} if @samp{$@@} does
9918 not contain a slash.
9920 @vindex $(@@F)
9921 @vindex @@F @r{(automatic variable)}
9922 @item $(@@F)
9923 The file-within-directory part of the file name of the target.  If the
9924 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
9925 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
9927 @vindex $(*D)
9928 @vindex *D @r{(automatic variable)}
9929 @item $(*D)
9930 @vindex $(*F)
9931 @vindex *F @r{(automatic variable)}
9932 @itemx $(*F)
9933 The directory part and the file-within-directory
9934 part of the stem; @file{dir} and @file{foo} in this example.
9936 @vindex $(%D)
9937 @vindex %D @r{(automatic variable)}
9938 @item $(%D)
9939 @vindex $(%F)
9940 @vindex %F @r{(automatic variable)}
9941 @itemx $(%F)
9942 The directory part and the file-within-directory part of the target
9943 archive member name.  This makes sense only for archive member targets
9944 of the form @file{@var{archive}(@var{member})} and is useful only when
9945 @var{member} may contain a directory name.  (@xref{Archive Members,
9946 ,Archive Members as Targets}.)
9948 @vindex $(<D)
9949 @vindex <D @r{(automatic variable)}
9950 @item $(<D)
9951 @vindex $(<F)
9952 @vindex <F @r{(automatic variable)}
9953 @itemx $(<F)
9954 The directory part and the file-within-directory
9955 part of the first prerequisite.
9957 @vindex $(^D)
9958 @vindex ^D @r{(automatic variable)}
9959 @item $(^D)
9960 @vindex $(^F)
9961 @vindex ^F @r{(automatic variable)}
9962 @itemx $(^F)
9963 Lists of the directory parts and the file-within-directory
9964 parts of all prerequisites.
9966 @vindex $(+D)
9967 @vindex +D @r{(automatic variable)}
9968 @item $(+D)
9969 @vindex $(+F)
9970 @vindex +F @r{(automatic variable)}
9971 @itemx $(+F)
9972 Lists of the directory parts and the file-within-directory
9973 parts of all prerequisites, including multiple instances of duplicated
9974 prerequisites.
9976 @vindex $(?D)
9977 @vindex ?D @r{(automatic variable)}
9978 @item $(?D)
9979 @vindex $(?F)
9980 @vindex ?F @r{(automatic variable)}
9981 @itemx $(?F)
9982 Lists of the directory parts and the file-within-directory parts of
9983 all prerequisites that are newer than the target.
9984 @end table
9986 Note that we use a special stylistic convention when we talk about these
9987 automatic variables; we write ``the value of @samp{$<}'', rather than
9988 @w{``the variable @code{<}''} as we would write for ordinary variables
9989 such as @code{objects} and @code{CFLAGS}.  We think this convention
9990 looks more natural in this special case.  Please do not assume it has a
9991 deep significance; @samp{$<} refers to the variable named @code{<} just
9992 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
9993 You could just as well use @samp{$(<)} in place of @samp{$<}.
9995 @node Pattern Match, Match-Anything Rules, Automatic Variables, Pattern Rules
9996 @subsection How Patterns Match
9998 @cindex stem
9999 A target pattern is composed of a @samp{%} between a prefix and a suffix,
10000 either or both of which may be empty.  The pattern matches a file name only
10001 if the file name starts with the prefix and ends with the suffix, without
10002 overlap.  The text between the prefix and the suffix is called the
10003 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
10004 @file{test.o}, the stem is @samp{test}.  The pattern rule prerequisites are
10005 turned into actual file names by substituting the stem for the character
10006 @samp{%}.  Thus, if in the same example one of the prerequisites is written
10007 as @samp{%.c}, it expands to @samp{test.c}.@refill
10009 When the target pattern does not contain a slash (and it usually does
10010 not), directory names in the file names are removed from the file name
10011 before it is compared with the target prefix and suffix.  After the
10012 comparison of the file name to the target pattern, the directory
10013 names, along with the slash that ends them, are added on to the
10014 prerequisite file names generated from the pattern rule's prerequisite
10015 patterns and the file name.  The directories are ignored only for the
10016 purpose of finding an implicit rule to use, not in the application of
10017 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
10018 with @samp{src/a} as the stem.  When prerequisites are turned into file
10019 names, the directories from the stem are added at the front, while the
10020 rest of the stem is substituted for the @samp{%}.  The stem
10021 @samp{src/a} with a prerequisite pattern @samp{c%r} gives the file name
10022 @file{src/car}.@refill
10024 @cindex pattern rules, order of
10025 @cindex order of pattern rules
10026 A pattern rule can be used to build a given file only if there is a
10027 target pattern that matches the file name, @emph{and} all
10028 prerequisites in that rule either exist or can be built.  The rules
10029 you write take precedence over those that are built in. Note however,
10030 that a rule whose prerequisites actually exist or are mentioned always
10031 takes priority over a rule with prerequisites that must be made by
10032 chaining other implicit rules.
10034 @cindex stem, shortest
10035 It is possible that more than one pattern rule will meet these
10036 criteria.  In that case, @code{make} will choose the rule with the
10037 shortest stem (that is, the pattern that matches most specifically).
10038 If more than one pattern rule has the shortest stem, @code{make} will
10039 choose the first one found in the makefile.
10041 This algorithm results in more specific rules being preferred over
10042 more generic ones; for example:
10044 @example
10045 %.o: %.c
10046         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
10048 %.o : %.f
10049         $(COMPILE.F) $(OUTPUT_OPTION) $<
10051 lib/%.o: lib/%.c
10052         $(CC) -fPIC -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
10053 @end example
10055 Given these rules and asked to build @file{bar.o} where both
10056 @file{bar.c} and @file{bar.f} exist, @code{make} will choose the first
10057 rule and compile @file{bar.c} into @file{bar.o}.  In the same
10058 situation where @file{bar.c} does not exist, then @code{make} will
10059 choose the second rule and compile @file{bar.f} into @file{bar.o}.
10061 If @code{make} is asked to build @file{lib/bar.o} and both
10062 @file{lib/bar.c} and @file{lib/bar.f} exist, then the third rule will
10063 be chosen since the stem for this rule (@samp{bar}) is shorter than
10064 the stem for the first rule (@samp{lib/bar}).  If @file{lib/bar.c}
10065 does not exist then the third rule is not eligible and the second rule
10066 will be used, even though the stem is longer.
10068 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
10069 @subsection Match-Anything Pattern Rules
10071 @cindex match-anything rule
10072 @cindex terminal rule
10073 When a pattern rule's target is just @samp{%}, it matches any file name
10074 whatever.  We call these rules @dfn{match-anything} rules.  They are very
10075 useful, but it can take a lot of time for @code{make} to think about them,
10076 because it must consider every such rule for each file name listed either
10077 as a target or as a prerequisite.
10079 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
10080 would have to consider making it by linking an object file @file{foo.c.o},
10081 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
10082 Pascal compilation-and-linking from @file{foo.c.p}, and many other
10083 possibilities.
10085 We know these possibilities are ridiculous since @file{foo.c} is a C source
10086 file, not an executable.  If @code{make} did consider these possibilities,
10087 it would ultimately reject them, because files such as @file{foo.c.o} and
10088 @file{foo.c.p} would not exist.  But these possibilities are so
10089 numerous that @code{make} would run very slowly if it had to consider
10090 them.@refill
10092 To gain speed, we have put various constraints on the way @code{make}
10093 considers match-anything rules.  There are two different constraints that
10094 can be applied, and each time you define a match-anything rule you must
10095 choose one or the other for that rule.
10097 One choice is to mark the match-anything rule as @dfn{terminal} by defining
10098 it with a double colon.  When a rule is terminal, it does not apply unless
10099 its prerequisites actually exist.  Prerequisites that could be made with
10100 other implicit rules are not good enough.  In other words, no further
10101 chaining is allowed beyond a terminal rule.
10103 For example, the built-in implicit rules for extracting sources from RCS
10104 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
10105 not exist, @code{make} will not even consider trying to make it as an
10106 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
10107 RCS and SCCS files are generally ultimate source files, which should not be
10108 remade from any other files; therefore, @code{make} can save time by not
10109 looking for ways to remake them.@refill
10111 If you do not mark the match-anything rule as terminal, then it is
10112 non-terminal.  A non-terminal match-anything rule cannot apply to a file name
10113 that indicates a specific type of data.  A file name indicates a specific
10114 type of data if some non-match-anything implicit rule target matches it.
10116 For example, the file name @file{foo.c} matches the target for the pattern
10117 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
10118 rule is actually applicable (which happens only if there is a file
10119 @file{foo.y}), the fact that its target matches is enough to prevent
10120 consideration of any non-terminal match-anything rules for the file
10121 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
10122 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
10123 @file{foo.c.p}, etc.@refill
10125 The motivation for this constraint is that non-terminal match-anything
10126 rules are used for making files containing specific types of data (such as
10127 executable files) and a file name with a recognized suffix indicates some
10128 other specific type of data (such as a C source file).
10130 Special built-in dummy pattern rules are provided solely to recognize
10131 certain file names so that non-terminal match-anything rules will not be
10132 considered.  These dummy rules have no prerequisites and no recipes, and
10133 they are ignored for all other purposes.  For example, the built-in
10134 implicit rule
10136 @example
10137 %.p :
10138 @end example
10140 @noindent
10141 exists to make sure that Pascal source files such as @file{foo.p} match a
10142 specific target pattern and thereby prevent time from being wasted looking
10143 for @file{foo.p.o} or @file{foo.p.c}.
10145 Dummy pattern rules such as the one for @samp{%.p} are made for every
10146 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
10148 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
10149 @subsection Canceling Implicit Rules
10151 You can override a built-in implicit rule (or one you have defined
10152 yourself) by defining a new pattern rule with the same target and
10153 prerequisites, but a different recipe.  When the new rule is defined, the
10154 built-in one is replaced.  The new rule's position in the sequence of
10155 implicit rules is determined by where you write the new rule.
10157 You can cancel a built-in implicit rule by defining a pattern rule with the
10158 same target and prerequisites, but no recipe.  For example, the following
10159 would cancel the rule that runs the assembler:
10161 @example
10162 %.o : %.s
10163 @end example
10165 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
10166 @section Defining Last-Resort Default Rules
10167 @cindex last-resort default rules
10168 @cindex default rules, last-resort
10170 You can define a last-resort implicit rule by writing a terminal
10171 match-anything pattern rule with no prerequisites (@pxref{Match-Anything
10172 Rules}).  This is just like any other pattern rule; the only thing
10173 special about it is that it will match any target.  So such a rule's
10174 recipe is used for all targets and prerequisites that have no recipe
10175 of their own and for which no other implicit rule applies.
10177 For example, when testing a makefile, you might not care if the source
10178 files contain real data, only that they exist.  Then you might do this:
10180 @example
10182         touch $@@
10183 @end example
10185 @noindent
10186 to cause all the source files needed (as prerequisites) to be created
10187 automatically.
10189 @findex .DEFAULT
10190 You can instead define a recipe to be used for targets for which there
10191 are no rules at all, even ones which don't specify recipes.  You do
10192 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
10193 recipe is used for all prerequisites which do not appear as targets in
10194 any explicit rule, and for which no implicit rule applies.  Naturally,
10195 there is no @code{.DEFAULT} rule unless you write one.
10197 If you use @code{.DEFAULT} with no recipe or prerequisites:
10199 @example
10200 .DEFAULT:
10201 @end example
10203 @noindent
10204 the recipe previously stored for @code{.DEFAULT} is cleared.  Then
10205 @code{make} acts as if you had never defined @code{.DEFAULT} at all.
10207 If you do not want a target to get the recipe from a match-anything
10208 pattern rule or @code{.DEFAULT}, but you also do not want any recipe
10209 to be run for the target, you can give it an empty recipe
10210 (@pxref{Empty Recipes, ,Defining Empty Recipes}).@refill
10212 You can use a last-resort rule to override part of another makefile.
10213 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
10215 @node Suffix Rules, Implicit Rule Search, Last Resort, Implicit Rules
10216 @section Old-Fashioned Suffix Rules
10217 @cindex old-fashioned suffix rules
10218 @cindex suffix rule
10220 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
10221 @code{make}.  Suffix rules are obsolete because pattern rules are more
10222 general and clearer.  They are supported in GNU @code{make} for
10223 compatibility with old makefiles.  They come in two kinds:
10224 @dfn{double-suffix} and @dfn{single-suffix}.@refill
10226 A double-suffix rule is defined by a pair of suffixes: the target suffix
10227 and the source suffix.  It matches any file whose name ends with the
10228 target suffix.  The corresponding implicit prerequisite is made by
10229 replacing the target suffix with the source suffix in the file name.  A
10230 two-suffix rule whose target and source suffixes are @samp{.o} and
10231 @samp{.c} is equivalent to the pattern rule @samp{%.o : %.c}.
10233 A single-suffix rule is defined by a single suffix, which is the source
10234 suffix.  It matches any file name, and the corresponding implicit
10235 prerequisite name is made by appending the source suffix.  A single-suffix
10236 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
10237 @samp{% : %.c}.
10239 Suffix rule definitions are recognized by comparing each rule's target
10240 against a defined list of known suffixes.  When @code{make} sees a rule
10241 whose target is a known suffix, this rule is considered a single-suffix
10242 rule.  When @code{make} sees a rule whose target is two known suffixes
10243 concatenated, this rule is taken as a double-suffix rule.
10245 For example, @samp{.c} and @samp{.o} are both on the default list of
10246 known suffixes.  Therefore, if you define a rule whose target is
10247 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
10248 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
10249 way to define the rule for compiling a C source file:@refill
10251 @example
10252 .c.o:
10253         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10254 @end example
10256 Suffix rules cannot have any prerequisites of their own.  If they have any,
10257 they are treated as normal files with funny names, not as suffix rules.
10258 Thus, the rule:
10260 @example
10261 .c.o: foo.h
10262         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10263 @end example
10265 @noindent
10266 tells how to make the file @file{.c.o} from the prerequisite file
10267 @file{foo.h}, and is not at all like the pattern rule:
10269 @example
10270 %.o: %.c foo.h
10271         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10272 @end example
10274 @noindent
10275 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
10276 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
10278 Suffix rules with no recipe are also meaningless.  They do not remove
10279 previous rules as do pattern rules with no recipe (@pxref{Canceling
10280 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or
10281 pair of suffixes concatenated as a target in the data base.@refill
10283 @findex .SUFFIXES
10284 The known suffixes are simply the names of the prerequisites of the special
10285 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
10286 for @code{.SUFFIXES} that adds more prerequisites, as in:
10288 @example
10289 .SUFFIXES: .hack .win
10290 @end example
10292 @noindent
10293 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
10295 If you wish to eliminate the default known suffixes instead of just adding
10296 to them, write a rule for @code{.SUFFIXES} with no prerequisites.  By
10297 special dispensation, this eliminates all existing prerequisites of
10298 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
10299 want.  For example,
10301 @example
10302 @group
10303 .SUFFIXES:            # @r{Delete the default suffixes}
10304 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
10305 @end group
10306 @end example
10308 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
10309 list of suffixes to be empty.
10311 @vindex SUFFIXES
10312 The variable @code{SUFFIXES} is defined to the default list of suffixes
10313 before @code{make} reads any makefiles.  You can change the list of suffixes
10314 with a rule for the special target @code{.SUFFIXES}, but that does not alter
10315 this variable.
10317 @node Implicit Rule Search,  , Suffix Rules, Implicit Rules
10318 @section Implicit Rule Search Algorithm
10319 @cindex implicit rule, search algorithm
10320 @cindex search algorithm, implicit rule
10322 Here is the procedure @code{make} uses for searching for an implicit rule
10323 for a target @var{t}.  This procedure is followed for each double-colon
10324 rule with no recipe, for each target of ordinary rules none of which have
10325 a recipe, and for each prerequisite that is not the target of any rule.  It
10326 is also followed recursively for prerequisites that come from implicit
10327 rules, in the search for a chain of rules.
10329 Suffix rules are not mentioned in this algorithm because suffix rules are
10330 converted to equivalent pattern rules once the makefiles have been read in.
10332 For an archive member target of the form
10333 @samp{@var{archive}(@var{member})}, the following algorithm is run
10334 twice, first using the entire target name @var{t}, and second using
10335 @samp{(@var{member})} as the target @var{t} if the first run found no
10336 rule.@refill
10338 @enumerate
10339 @item
10340 Split @var{t} into a directory part, called @var{d}, and the rest,
10341 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
10342 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.@refill
10344 @item
10345 Make a list of all the pattern rules one of whose targets matches
10346 @var{t} or @var{n}.  If the target pattern contains a slash, it is
10347 matched against @var{t}; otherwise, against @var{n}.
10349 @item
10350 If any rule in that list is @emph{not} a match-anything rule, then
10351 remove all non-terminal match-anything rules from the list.
10353 @item
10354 Remove from the list all rules with no recipe.
10356 @item
10357 For each pattern rule in the list:
10359 @enumerate a
10360 @item
10361 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
10362 matched by the @samp{%} in the target pattern.@refill
10364 @item
10365 Compute the prerequisite names by substituting @var{s} for @samp{%}; if
10366 the target pattern does not contain a slash, append @var{d} to
10367 the front of each prerequisite name.@refill
10369 @item
10370 Test whether all the prerequisites exist or ought to exist.  (If a
10371 file name is mentioned in the makefile as a target or as an explicit
10372 prerequisite, then we say it ought to exist.)
10374 If all prerequisites exist or ought to exist, or there are no prerequisites,
10375 then this rule applies.
10376 @end enumerate
10378 @item
10379 If no pattern rule has been found so far, try harder.
10380 For each pattern rule in the list:
10382 @enumerate a
10383 @item
10384 If the rule is terminal, ignore it and go on to the next rule.
10386 @item
10387 Compute the prerequisite names as before.
10389 @item
10390 Test whether all the prerequisites exist or ought to exist.
10392 @item
10393 For each prerequisite that does not exist, follow this algorithm
10394 recursively to see if the prerequisite can be made by an implicit
10395 rule.
10397 @item
10398 If all prerequisites exist, ought to exist, or can be
10399 made by implicit rules, then this rule applies.
10400 @end enumerate
10402 @item
10403 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
10404 applies.  In that case, give @var{t} the same recipe that
10405 @code{.DEFAULT} has.  Otherwise, there is no recipe for @var{t}.
10406 @end enumerate
10408 Once a rule that applies has been found, for each target pattern of
10409 the rule other than the one that matched @var{t} or @var{n}, the
10410 @samp{%} in the pattern is replaced with @var{s} and the resultant
10411 file name is stored until the recipe to remake the target file @var{t}
10412 is executed.  After the recipe is executed, each of these stored file
10413 names are entered into the data base and marked as having been updated
10414 and having the same update status as the file @var{t}.
10416 When the recipe of a pattern rule is executed for @var{t}, the
10417 automatic variables are set corresponding to the target and
10418 prerequisites.  @xref{Automatic Variables}.
10420 @node Archives, Features, Implicit Rules, Top
10421 @chapter Using @code{make} to Update Archive Files
10422 @cindex archive
10424 @dfn{Archive files} are files containing named sub-files called
10425 @dfn{members}; they are maintained with the program @code{ar} and their
10426 main use is as subroutine libraries for linking.
10428 @menu
10429 * Archive Members::             Archive members as targets.
10430 * Archive Update::              The implicit rule for archive member targets.
10431 * Archive Pitfalls::            Dangers to watch out for when using archives.
10432 * Archive Suffix Rules::        You can write a special kind of suffix rule
10433                                   for updating archives.
10434 @end menu
10436 @node Archive Members, Archive Update, Archives, Archives
10437 @section Archive Members as Targets
10438 @cindex archive member targets
10440 An individual member of an archive file can be used as a target or
10441 prerequisite in @code{make}.  You specify the member named @var{member} in
10442 archive file @var{archive} as follows:
10444 @example
10445 @var{archive}(@var{member})
10446 @end example
10448 @noindent
10449 This construct is available only in targets and prerequisites, not in
10450 recipes!  Most programs that you might use in recipes do not support
10451 this syntax and cannot act directly on archive members.  Only
10452 @code{ar} and other programs specifically designed to operate on
10453 archives can do so.  Therefore, valid recipes to update an archive
10454 member target probably must use @code{ar}.  For example, this rule
10455 says to create a member @file{hack.o} in archive @file{foolib} by
10456 copying the file @file{hack.o}:
10458 @example
10459 foolib(hack.o) : hack.o
10460         ar cr foolib hack.o
10461 @end example
10463 In fact, nearly all archive member targets are updated in just this way
10464 and there is an implicit rule to do it for you.  @strong{Please note:} The
10465 @samp{c} flag to @code{ar} is required if the archive file does not
10466 already exist.
10468 To specify several members in the same archive, you can write all the
10469 member names together between the parentheses.  For example:
10471 @example
10472 foolib(hack.o kludge.o)
10473 @end example
10475 @noindent
10476 is equivalent to:
10478 @example
10479 foolib(hack.o) foolib(kludge.o)
10480 @end example
10482 @cindex wildcard, in archive member
10483 You can also use shell-style wildcards in an archive member reference.
10484 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
10485 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
10486 @file{foolib} archive whose names end in @samp{.o}; perhaps
10487 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
10489 @node Archive Update, Archive Pitfalls, Archive Members, Archives
10490 @section Implicit Rule for Archive Member Targets
10492 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
10493 member named @var{m} in the archive file @var{a}.
10495 When @code{make} looks for an implicit rule for such a target, as a special
10496 feature it considers implicit rules that match @file{(@var{m})}, as well as
10497 those that match the actual target @file{@var{a}(@var{m})}.
10499 This causes one special rule whose target is @file{(%)} to match.  This
10500 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
10501 into the archive.  For example, it will update the archive member target
10502 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
10503 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
10505 When this rule is chained with others, the result is very powerful.
10506 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
10507 @samp{(} and @samp{)} from being interpreted specially by the shell) in
10508 the presence of a file @file{bar.c} is enough to cause the following
10509 recipe to be run, even without a makefile:
10511 @example
10512 cc -c bar.c -o bar.o
10513 ar r foo.a bar.o
10514 rm -f bar.o
10515 @end example
10517 @noindent
10518 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
10519 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
10521 Implicit rules such as this one are written using the automatic variable
10522 @samp{$%}.  @xref{Automatic Variables}.
10524 An archive member name in an archive cannot contain a directory name, but
10525 it may be useful in a makefile to pretend that it does.  If you write an
10526 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
10527 automatic updating with this recipe:
10529 @example
10530 ar r foo.a dir/file.o
10531 @end example
10533 @noindent
10534 which has the effect of copying the file @file{dir/file.o} into a member
10535 named @file{file.o}.  In connection with such usage, the automatic variables
10536 @code{%D} and @code{%F} may be useful.
10538 @menu
10539 * Archive Symbols::             How to update archive symbol directories.
10540 @end menu
10542 @node Archive Symbols,  , Archive Update, Archive Update
10543 @subsection Updating Archive Symbol Directories
10544 @cindex @code{__.SYMDEF}
10545 @cindex updating archive symbol directories
10546 @cindex archive symbol directory updating
10547 @cindex symbol directories, updating archive
10548 @cindex directories, updating archive symbol
10550 An archive file that is used as a library usually contains a special member
10551 named @file{__.SYMDEF} that contains a directory of the external symbol
10552 names defined by all the other members.  After you update any other
10553 members, you need to update @file{__.SYMDEF} so that it will summarize the
10554 other members properly.  This is done by running the @code{ranlib} program:
10556 @example
10557 ranlib @var{archivefile}
10558 @end example
10560 Normally you would put this command in the rule for the archive file,
10561 and make all the members of the archive file prerequisites of that rule.
10562 For example,
10564 @example
10565 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
10566         ranlib libfoo.a
10567 @end example
10569 @noindent
10570 The effect of this is to update archive members @file{x.o}, @file{y.o},
10571 etc., and then update the symbol directory member @file{__.SYMDEF} by
10572 running @code{ranlib}.  The rules for updating the members are not shown
10573 here; most likely you can omit them and use the implicit rule which copies
10574 files into the archive, as described in the preceding section.
10576 This is not necessary when using the GNU @code{ar} program, which
10577 updates the @file{__.SYMDEF} member automatically.
10579 @node Archive Pitfalls, Archive Suffix Rules, Archive Update, Archives
10580 @section Dangers When Using Archives
10581 @cindex archive, and parallel execution
10582 @cindex parallel execution, and archive update
10583 @cindex archive, and @code{-j}
10584 @cindex @code{-j}, and archive update
10586 It is important to be careful when using parallel execution (the
10587 @code{-j} switch; @pxref{Parallel, ,Parallel Execution}) and archives.
10588 If multiple @code{ar} commands run at the same time on the same archive
10589 file, they will not know about each other and can corrupt the file.
10591 Possibly a future version of @code{make} will provide a mechanism to
10592 circumvent this problem by serializing all recipes that operate on the
10593 same archive file.  But for the time being, you must either write your
10594 makefiles to avoid this problem in some other way, or not use @code{-j}.
10596 @node Archive Suffix Rules,  , Archive Pitfalls, Archives
10597 @section Suffix Rules for Archive Files
10598 @cindex suffix rule, for archive
10599 @cindex archive, suffix rule for
10600 @cindex library archive, suffix rule for
10601 @cindex @code{.a} (archives)
10603 You can write a special kind of suffix rule for dealing with archive
10604 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
10605 Archive suffix rules are obsolete in GNU @code{make}, because pattern
10606 rules for archives are a more general mechanism (@pxref{Archive
10607 Update}).  But they are retained for compatibility with other
10608 @code{make}s.
10610 To write a suffix rule for archives, you simply write a suffix rule
10611 using the target suffix @samp{.a} (the usual suffix for archive files).
10612 For example, here is the old-fashioned suffix rule to update a library
10613 archive from C source files:
10615 @example
10616 @group
10617 .c.a:
10618         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
10619         $(AR) r $@@ $*.o
10620         $(RM) $*.o
10621 @end group
10622 @end example
10624 @noindent
10625 This works just as if you had written the pattern rule:
10627 @example
10628 @group
10629 (%.o): %.c
10630         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
10631         $(AR) r $@@ $*.o
10632         $(RM) $*.o
10633 @end group
10634 @end example
10636 In fact, this is just what @code{make} does when it sees a suffix rule
10637 with @samp{.a} as the target suffix.  Any double-suffix rule
10638 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
10639 pattern @samp{(%.o)} and a prerequisite pattern of @samp{%.@var{x}}.
10641 Since you might want to use @samp{.a} as the suffix for some other kind
10642 of file, @code{make} also converts archive suffix rules to pattern rules
10643 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
10644 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
10645 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
10647 @node Features, Missing, Archives, Top
10648 @chapter Features of GNU @code{make}
10649 @cindex features of GNU @code{make}
10650 @cindex portability
10651 @cindex compatibility
10653 Here is a summary of the features of GNU @code{make}, for comparison
10654 with and credit to other versions of @code{make}.  We consider the
10655 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
10656 concerned with writing portable makefiles, you should not use the
10657 features of @code{make} listed here, nor the ones in @ref{Missing}.
10659 Many features come from the version of @code{make} in System V.
10661 @itemize @bullet
10662 @item
10663 The @code{VPATH} variable and its special meaning.
10664 @xref{Directory Search, , Searching Directories for Prerequisites}.
10665 This feature exists in System V @code{make}, but is undocumented.
10666 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
10667 @code{VPATH} feature).@refill
10669 @item
10670 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
10671 Allowing multiple files to be included with a single directive is a GNU
10672 extension.
10674 @item
10675 Variables are read from and communicated via the environment.
10676 @xref{Environment, ,Variables from the Environment}.
10678 @item
10679 Options passed through the variable @code{MAKEFLAGS} to recursive
10680 invocations of @code{make}.
10681 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
10683 @item
10684 The automatic variable @code{$%} is set to the member name
10685 in an archive reference.  @xref{Automatic Variables}.
10687 @item
10688 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
10689 and @code{$?} have corresponding forms like @code{$(@@F)} and
10690 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
10691 extension.  @xref{Automatic Variables}.@refill
10693 @item
10694 Substitution variable references.
10695 @xref{Reference, ,Basics of Variable References}.
10697 @item
10698 The command line options @samp{-b} and @samp{-m}, accepted and
10699 ignored.  In System V @code{make}, these options actually do something.
10701 @item
10702 Execution of recursive commands to run @code{make} via the variable
10703 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
10704 @xref{Recursion, ,Recursive Use of @code{make}}.
10706 @item
10707 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
10708 Rules}.  This feature is obsolete in GNU @code{make}, because the
10709 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
10710 Implicit Rules}) allows one pattern rule for installing members in an
10711 archive (@pxref{Archive Update}) to be sufficient.
10713 @item
10714 The arrangement of lines and backslash-newline combinations in
10715 recipes is retained when the recipes are printed, so they appear as
10716 they do in the makefile, except for the stripping of initial
10717 whitespace.
10718 @end itemize
10720 The following features were inspired by various other versions of
10721 @code{make}.  In some cases it is unclear exactly which versions inspired
10722 which others.
10724 @itemize @bullet
10725 @item
10726 Pattern rules using @samp{%}.
10727 This has been implemented in several versions of @code{make}.
10728 We're not sure who invented it first, but it's been spread around a bit.
10729 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.@refill
10731 @item
10732 Rule chaining and implicit intermediate files.
10733 This was implemented by Stu Feldman in his version of @code{make}
10734 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
10735 AT&T Bell Labs in his @code{mk} program (where he terms it
10736 ``transitive closure'').  We do not really know if
10737 we got this from either of them or thought it up ourselves at the
10738 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
10740 @item
10741 The automatic variable @code{$^} containing a list of all prerequisites
10742 of the current target.  We did not invent this, but we have no idea who
10743 did.  @xref{Automatic Variables}.  The automatic variable
10744 @code{$+} is a simple extension of @code{$^}.
10746 @item
10747 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
10748 invented by Andrew Hume in @code{mk}.
10749 @xref{Instead of Execution, ,Instead of Executing Recipes}.
10751 @item
10752 The concept of doing several things at once (parallelism) exists in
10753 many incarnations of @code{make} and similar programs, though not in the
10754 System V or BSD implementations.  @xref{Execution, ,Recipe Execution}.
10756 @item
10757 Modified variable references using pattern substitution come from
10758 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
10759 This functionality was provided in GNU @code{make} by the
10760 @code{patsubst} function before the alternate syntax was implemented
10761 for compatibility with SunOS 4.  It is not altogether clear who
10762 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
10763 4 was released.@refill
10765 @item
10766 The special significance of @samp{+} characters preceding recipe lines
10767 (@pxref{Instead of Execution, ,Instead of Executing Recipes}) is
10768 mandated by @cite{IEEE Standard 1003.2-1992} (POSIX.2).
10770 @item
10771 The @samp{+=} syntax to append to the value of a variable comes from SunOS
10772 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
10774 @item
10775 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
10776 multiple members in a single archive file comes from SunOS 4 @code{make}.
10777 @xref{Archive Members}.
10779 @item
10780 The @code{-include} directive to include makefiles with no error for a
10781 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
10782 @code{make} does not allow multiple makefiles to be specified in one
10783 @code{-include} directive.)  The same feature appears with the name
10784 @code{sinclude} in SGI @code{make} and perhaps others.
10786 @item
10787 The @code{!=} shell assignment operator exists in many BSD of
10788 @code{make} and is purposefully implemented here to behave identically
10789 to those implementations.
10790 @end itemize
10792 The remaining features are inventions new in GNU @code{make}:
10794 @itemize @bullet
10795 @item
10796 Use the @samp{-v} or @samp{--version} option to print version and
10797 copyright information.
10799 @item
10800 Use the @samp{-h} or @samp{--help} option to summarize the options to
10801 @code{make}.
10803 @item
10804 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
10806 @item
10807 Pass command line variable assignments automatically through the
10808 variable @code{MAKE} to recursive @code{make} invocations.
10809 @xref{Recursion, ,Recursive Use of @code{make}}.
10811 @item
10812 Use the @samp{-C} or @samp{--directory} command option to change
10813 directory.  @xref{Options Summary, ,Summary of Options}.
10815 @item
10816 Make verbatim variable definitions with @code{define}.
10817 @xref{Multi-Line, ,Defining Multi-Line Variables}.
10819 @item
10820 Declare phony targets with the special target @code{.PHONY}.
10822 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
10823 different syntax in his @code{mk} program.  This seems to be a case of
10824 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
10826 @item
10827 Manipulate text by calling functions.
10828 @xref{Functions, ,Functions for Transforming Text}.
10830 @item
10831 Use the @samp{-o} or @samp{--old-file}
10832 option to pretend a file's modification-time is old.
10833 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
10835 @item
10836 Conditional execution.
10838 This feature has been implemented numerous times in various versions
10839 of @code{make}; it seems a natural extension derived from the features
10840 of the C preprocessor and similar macro languages and is not a
10841 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
10843 @item
10844 Specify a search path for included makefiles.
10845 @xref{Include, ,Including Other Makefiles}.
10847 @item
10848 Specify extra makefiles to read with an environment variable.
10849 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
10851 @item
10852 Strip leading sequences of @samp{./} from file names, so that
10853 @file{./@var{file}} and @file{@var{file}} are considered to be the
10854 same file.@refill
10856 @item
10857 Use a special search method for library prerequisites written in the
10858 form @samp{-l@var{name}}.
10859 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
10861 @item
10862 Allow suffixes for suffix rules
10863 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
10864 characters.  In other versions of @code{make}, they must begin with
10865 @samp{.} and not contain any @samp{/} characters.
10867 @item
10868 Keep track of the current level of @code{make} recursion using the
10869 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
10871 @item
10872 Provide any goals given on the command line in the variable
10873 @code{MAKECMDGOALS}.  @xref{Goals, ,Arguments to Specify the Goals}.
10875 @item
10876 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
10878 @item
10879 Provide selective @code{vpath} search.
10880 @xref{Directory Search, ,Searching Directories for Prerequisites}.
10882 @item
10883 Provide computed variable references.
10884 @xref{Reference, ,Basics of Variable References}.
10886 @item
10887 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
10888 System V @code{make} has a very, very limited form of this
10889 functionality in that it will check out SCCS files for makefiles.
10891 @item
10892 Various new built-in implicit rules.
10893 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
10895 @item
10896 The built-in variable @samp{MAKE_VERSION} gives the version number of
10897 @code{make}.
10898 @vindex MAKE_VERSION
10899 @end itemize
10901 @node Missing, Makefile Conventions, Features, Top
10902 @chapter Incompatibilities and Missing Features
10903 @cindex incompatibilities
10904 @cindex missing features
10905 @cindex features, missing
10907 The @code{make} programs in various other systems support a few features
10908 that are not implemented in GNU @code{make}.  The POSIX.2 standard
10909 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
10910 require any of these features.@refill
10912 @itemize @bullet
10913 @item
10914 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
10915 of archive file @var{file}.  The member is chosen, not by name, but by
10916 being an object file which defines the linker symbol @var{entry}.@refill
10918 This feature was not put into GNU @code{make} because of the
10919 non-modularity of putting knowledge into @code{make} of the internal
10920 format of archive file symbol tables.
10921 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
10923 @item
10924 Suffixes (used in suffix rules) that end with the character @samp{~}
10925 have a special meaning to System V @code{make};
10926 they refer to the SCCS file that corresponds
10927 to the file one would get without the @samp{~}.  For example, the
10928 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
10929 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
10930 series of such suffix rules is required.
10931 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
10933 In GNU @code{make}, this entire series of cases is handled by two
10934 pattern rules for extraction from SCCS, in combination with the
10935 general feature of rule chaining.
10936 @xref{Chained Rules, ,Chains of Implicit Rules}.
10938 @item
10939 In System V and 4.3 BSD @code{make}, files found by @code{VPATH}
10940 search (@pxref{Directory Search, ,Searching Directories for
10941 Prerequisites}) have their names changed inside recipes.  We feel it
10942 is much cleaner to always use automatic variables and thus make this
10943 feature obsolete.@refill
10945 @item
10946 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
10947 the prerequisites of a rule has the amazingly strange ``feature'' of
10948 expanding to the full name of the @emph{target of that rule}.  We cannot
10949 imagine what went on in the minds of Unix @code{make} developers to do
10950 this; it is utterly inconsistent with the normal definition of @code{$*}.
10951 @vindex * @r{(automatic variable), unsupported bizarre usage}
10953 @item
10954 In some Unix @code{make}s, implicit rule search (@pxref{Implicit
10955 Rules, ,Using Implicit Rules}) is apparently done for @emph{all}
10956 targets, not just those without recipes.  This means you can
10957 do:@refill
10959 @example
10960 @group
10961 foo.o:
10962         cc -c foo.c
10963 @end group
10964 @end example
10966 @noindent
10967 and Unix @code{make} will intuit that @file{foo.o} depends on
10968 @file{foo.c}.@refill
10970 We feel that such usage is broken.  The prerequisite properties of
10971 @code{make} are well-defined (for GNU @code{make}, at least),
10972 and doing such a thing simply does not fit the model.@refill
10974 @item
10975 GNU @code{make} does not include any built-in implicit rules for
10976 compiling or preprocessing EFL programs.  If we hear of anyone who is
10977 using EFL, we will gladly add them.
10979 @item
10980 It appears that in SVR4 @code{make}, a suffix rule can be specified
10981 with no recipe, and it is treated as if it had an empty recipe
10982 (@pxref{Empty Recipes}).  For example:
10984 @example
10985 .c.a:
10986 @end example
10988 @noindent
10989 will override the built-in @file{.c.a} suffix rule.
10991 We feel that it is cleaner for a rule without a recipe to always simply
10992 add to the prerequisite list for the target.  The above example can be
10993 easily rewritten to get the desired behavior in GNU @code{make}:
10995 @example
10996 .c.a: ;
10997 @end example
10999 @item
11000 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
11001 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
11002 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
11003 program it runs returns a nonzero status.  We feel it is cleaner to
11004 write each line of the recipe to stand on its own and not require this
11005 special treatment.
11006 @end itemize
11008 @comment The makefile standards are in a separate file that is also
11009 @comment included by standards.texi.
11010 @include make-stds.texi
11012 @node Quick Reference, Error Messages, Makefile Conventions, Top
11013 @appendix Quick Reference
11015 This appendix summarizes the directives, text manipulation functions,
11016 and special variables which GNU @code{make} understands.
11017 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
11018 and @ref{Options Summary, ,Summary of Options},
11019 for other summaries.
11021 Here is a summary of the directives GNU @code{make} recognizes:
11023 @table @code
11024 @item define @var{variable}
11025 @itemx define @var{variable} =
11026 @itemx define @var{variable} :=
11027 @itemx define @var{variable} +=
11028 @itemx define @var{variable} ?=
11029 @itemx endef
11030 Define multi-line variables.@*
11031 @xref{Multi-Line}.
11033 @item undefine @var{variable}
11034 Undefining variables.@*
11035 @xref{Undefine Directive}.
11037 @item ifdef @var{variable}
11038 @itemx ifndef @var{variable}
11039 @itemx ifeq (@var{a},@var{b})
11040 @itemx ifeq "@var{a}" "@var{b}"
11041 @itemx ifeq '@var{a}' '@var{b}'
11042 @itemx ifneq (@var{a},@var{b})
11043 @itemx ifneq "@var{a}" "@var{b}"
11044 @itemx ifneq '@var{a}' '@var{b}'
11045 @itemx else
11046 @itemx endif
11047 Conditionally evaluate part of the makefile.@*
11048 @xref{Conditionals}.
11050 @item include @var{file}
11051 @itemx -include @var{file}
11052 @itemx sinclude @var{file}
11053 Include another makefile.@*
11054 @xref{Include, ,Including Other Makefiles}.
11056 @item override @var{variable-assignment}
11057 Define a variable, overriding any previous definition, even one from
11058 the command line.@*
11059 @xref{Override Directive, ,The @code{override} Directive}.
11061 @item export
11062 Tell @code{make} to export all variables to child processes by default.@*
11063 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
11065 @item export @var{variable}
11066 @itemx export @var{variable-assignment}
11067 @itemx unexport @var{variable}
11068 Tell @code{make} whether or not to export a particular variable to child
11069 processes.@*
11070 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
11072 @item private @var{variable-assignment}
11073 Do not allow this variable assignment to be inherited by prerequisites.@*
11074 @xref{Suppressing Inheritance}.
11076 @item vpath @var{pattern} @var{path}
11077 Specify a search path for files matching a @samp{%} pattern.@*
11078 @xref{Selective Search, , The @code{vpath} Directive}.
11080 @item vpath @var{pattern}
11081 Remove all search paths previously specified for @var{pattern}.
11083 @item vpath
11084 Remove all search paths previously specified in any @code{vpath}
11085 directive.
11086 @end table
11088 Here is a summary of the built-in functions (@pxref{Functions}):
11090 @table @code
11091 @item $(subst @var{from},@var{to},@var{text})
11092 Replace @var{from} with @var{to} in @var{text}.@*
11093 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11095 @item $(patsubst @var{pattern},@var{replacement},@var{text})
11096 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
11097 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11099 @item $(strip @var{string})
11100 Remove excess whitespace characters from @var{string}.@*
11101 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11103 @item $(findstring @var{find},@var{text})
11104 Locate @var{find} in @var{text}.@*
11105 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11107 @item $(filter @var{pattern}@dots{},@var{text})
11108 Select words in @var{text} that match one of the @var{pattern} words.@*
11109 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11111 @item $(filter-out @var{pattern}@dots{},@var{text})
11112 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
11113 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11115 @item $(sort @var{list})
11116 Sort the words in @var{list} lexicographically, removing duplicates.@*
11117 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11119 @item $(word @var{n},@var{text})
11120 Extract the @var{n}th word (one-origin) of @var{text}.@*
11121 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11123 @item $(words @var{text})
11124 Count the number of words in @var{text}.@*
11125 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11127 @item $(wordlist @var{s},@var{e},@var{text})
11128 Returns the list of words in @var{text} from @var{s} to @var{e}.@*
11129 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11131 @item $(firstword @var{names}@dots{})
11132 Extract the first word of @var{names}.@*
11133 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11135 @item $(lastword @var{names}@dots{})
11136 Extract the last word of @var{names}.@*
11137 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11139 @item $(dir @var{names}@dots{})
11140 Extract the directory part of each file name.@*
11141 @xref{File Name Functions, ,Functions for File Names}.
11143 @item $(notdir @var{names}@dots{})
11144 Extract the non-directory part of each file name.@*
11145 @xref{File Name Functions, ,Functions for File Names}.
11147 @item $(suffix @var{names}@dots{})
11148 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
11149 @xref{File Name Functions, ,Functions for File Names}.
11151 @item $(basename @var{names}@dots{})
11152 Extract the base name (name without suffix) of each file name.@*
11153 @xref{File Name Functions, ,Functions for File Names}.
11155 @item $(addsuffix @var{suffix},@var{names}@dots{})
11156 Append @var{suffix} to each word in @var{names}.@*
11157 @xref{File Name Functions, ,Functions for File Names}.
11159 @item $(addprefix @var{prefix},@var{names}@dots{})
11160 Prepend @var{prefix} to each word in @var{names}.@*
11161 @xref{File Name Functions, ,Functions for File Names}.
11163 @item $(join @var{list1},@var{list2})
11164 Join two parallel lists of words.@*
11165 @xref{File Name Functions, ,Functions for File Names}.
11167 @item $(wildcard @var{pattern}@dots{})
11168 Find file names matching a shell file name pattern (@emph{not} a
11169 @samp{%} pattern).@*
11170 @xref{Wildcard Function, ,The Function @code{wildcard}}.
11172 @item $(realpath @var{names}@dots{})
11173 For each file name in @var{names}, expand to an absolute name that
11174 does not contain any @code{.}, @code{..}, nor symlinks.@*
11175 @xref{File Name Functions, ,Functions for File Names}.
11177 @item $(abspath @var{names}@dots{})
11178 For each file name in @var{names}, expand to an absolute name that
11179 does not contain any @code{.} or @code{..} components, but preserves
11180 symlinks.@*
11181 @xref{File Name Functions, ,Functions for File Names}.
11183 @item $(error @var{text}@dots{})
11184 When this function is evaluated, @code{make} generates a fatal error
11185 with the message @var{text}.@*
11186 @xref{Make Control Functions, ,Functions That Control Make}.
11188 @item $(warning @var{text}@dots{})
11189 When this function is evaluated, @code{make} generates a warning with
11190 the message @var{text}.@*
11191 @xref{Make Control Functions, ,Functions That Control Make}.
11193 @item $(shell @var{command})
11194 Execute a shell command and return its output.@*
11195 @xref{Shell Function, , The @code{shell} Function}.
11197 @item $(origin @var{variable})
11198 Return a string describing how the @code{make} variable @var{variable} was
11199 defined.@*
11200 @xref{Origin Function, , The @code{origin} Function}.
11202 @item $(flavor @var{variable})
11203 Return a string describing the flavor of the @code{make} variable
11204 @var{variable}.@*
11205 @xref{Flavor Function, , The @code{flavor} Function}.
11207 @item $(foreach @var{var},@var{words},@var{text})
11208 Evaluate @var{text} with @var{var} bound to each word in @var{words},
11209 and concatenate the results.@*
11210 @xref{Foreach Function, ,The @code{foreach} Function}.
11212 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
11213 Evaluate the condition @var{condition}; if it's non-empty substitute
11214 the expansion of the @var{then-part} otherwise substitute the
11215 expansion of the @var{else-part}.@*
11216 @xref{Conditional Functions, ,Functions for Conditionals}.
11218 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
11219 Evaluate each condition @var{conditionN} one at a time; substitute the
11220 first non-empty expansion.  If all expansions are empty, substitute
11221 the empty string.@*
11222 @xref{Conditional Functions, ,Functions for Conditionals}.
11224 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
11225 Evaluate each condition @var{conditionN} one at a time; if any
11226 expansion results in the empty string substitute the empty string.  If
11227 all expansions result in a non-empty string, substitute the expansion
11228 of the last @var{condition}.@*
11229 @xref{Conditional Functions, ,Functions for Conditionals}.
11231 @item $(call @var{var},@var{param},@dots{})
11232 Evaluate the variable @var{var} replacing any references to @code{$(1)},
11233 @code{$(2)} with the first, second, etc.@: @var{param} values.@*
11234 @xref{Call Function, ,The @code{call} Function}.
11236 @item $(eval @var{text})
11237 Evaluate @var{text} then read the results as makefile commands.
11238 Expands to the empty string.@*
11239 @xref{Eval Function, ,The @code{eval} Function}.
11241 @item $(value @var{var})
11242 Evaluates to the contents of the variable @var{var}, with no expansion
11243 performed on it.@*
11244 @xref{Value Function, ,The @code{value} Function}.
11245 @end table
11247 Here is a summary of the automatic variables.
11248 @xref{Automatic Variables},
11249 for full information.
11251 @table @code
11252 @item $@@
11253 The file name of the target.
11255 @item $%
11256 The target member name, when the target is an archive member.
11258 @item $<
11259 The name of the first prerequisite.
11261 @item $?
11262 The names of all the prerequisites that are
11263 newer than the target, with spaces between them.
11264 For prerequisites which are archive members, only
11265 the named member is used (@pxref{Archives}).
11267 @item $^
11268 @itemx $+
11269 The names of all the prerequisites, with spaces between them.  For
11270 prerequisites which are archive members, only the named member is used
11271 (@pxref{Archives}).  The value of @code{$^} omits duplicate
11272 prerequisites, while @code{$+} retains them and preserves their order.
11274 @item $*
11275 The stem with which an implicit rule matches
11276 (@pxref{Pattern Match, ,How Patterns Match}).
11278 @item $(@@D)
11279 @itemx $(@@F)
11280 The directory part and the file-within-directory part of @code{$@@}.
11282 @item $(*D)
11283 @itemx $(*F)
11284 The directory part and the file-within-directory part of @code{$*}.
11286 @item $(%D)
11287 @itemx $(%F)
11288 The directory part and the file-within-directory part of @code{$%}.
11290 @item $(<D)
11291 @itemx $(<F)
11292 The directory part and the file-within-directory part of @code{$<}.
11294 @item $(^D)
11295 @itemx $(^F)
11296 The directory part and the file-within-directory part of @code{$^}.
11298 @item $(+D)
11299 @itemx $(+F)
11300 The directory part and the file-within-directory part of @code{$+}.
11302 @item $(?D)
11303 @itemx $(?F)
11304 The directory part and the file-within-directory part of @code{$?}.
11305 @end table
11307 These variables are used specially by GNU @code{make}:
11309 @table @code
11310 @item MAKEFILES
11312 Makefiles to be read on every invocation of @code{make}.@*
11313 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
11315 @item VPATH
11317 Directory search path for files not found in the current directory.@*
11318 @xref{General Search, , @code{VPATH} Search Path for All Prerequisites}.
11320 @item SHELL
11322 The name of the system default command interpreter, usually @file{/bin/sh}.
11323 You can set @code{SHELL} in the makefile to change the shell used to run
11324 recipes.  @xref{Execution, ,Recipe Execution}.  The @code{SHELL}
11325 variable is handled specially when importing from and exporting to the
11326 environment.  @xref{Choosing the Shell}.
11328 @item MAKESHELL
11330 On MS-DOS only, the name of the command interpreter that is to be used
11331 by @code{make}.  This value takes precedence over the value of
11332 @code{SHELL}.  @xref{Execution, ,MAKESHELL variable}.
11334 @item MAKE
11336 The name with which @code{make} was invoked.  Using this variable in
11337 recipes has special meaning.  @xref{MAKE Variable, ,How the
11338 @code{MAKE} Variable Works}.
11340 @item MAKELEVEL
11342 The number of levels of recursion (sub-@code{make}s).@*
11343 @xref{Variables/Recursion}.
11345 @item MAKEFLAGS
11347 The flags given to @code{make}.  You can set this in the environment or
11348 a makefile to set flags.@*
11349 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
11351 It is @emph{never} appropriate to use @code{MAKEFLAGS} directly in a
11352 recipe line: its contents may not be quoted correctly for use in the
11353 shell.  Always allow recursive @code{make}'s to obtain these values
11354 through the environment from its parent.
11356 @item MAKECMDGOALS
11358 The targets given to @code{make} on the command line.  Setting this
11359 variable has no effect on the operation of @code{make}.@*
11360 @xref{Goals, ,Arguments to Specify the Goals}.
11362 @item CURDIR
11364 Set to the pathname of the current working directory (after all
11365 @code{-C} options are processed, if any).  Setting this variable has no
11366 effect on the operation of @code{make}.@*
11367 @xref{Recursion, ,Recursive Use of @code{make}}.
11369 @item SUFFIXES
11371 The default list of suffixes before @code{make} reads any makefiles.
11373 @item .LIBPATTERNS
11374 Defines the naming of the libraries @code{make} searches for, and their
11375 order.@*
11376 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
11377 @end table
11379 @node Error Messages, Complex Makefile, Quick Reference, Top
11380 @comment  node-name,  next,  previous,  up
11381 @appendix Errors Generated by Make
11383 Here is a list of the more common errors you might see generated by
11384 @code{make}, and some information about what they mean and how to fix
11385 them.
11387 Sometimes @code{make} errors are not fatal, especially in the presence
11388 of a @code{-} prefix on a recipe line, or the @code{-k} command line
11389 option.  Errors that are fatal are prefixed with the string
11390 @code{***}.
11392 Error messages are all either prefixed with the name of the program
11393 (usually @samp{make}), or, if the error is found in a makefile, the name
11394 of the file and line number containing the problem.
11396 In the table below, these common prefixes are left off.
11398 @table @samp
11400 @item [@var{foo}] Error @var{NN}
11401 @itemx [@var{foo}] @var{signal description}
11402 These errors are not really @code{make} errors at all.  They mean that a
11403 program that @code{make} invoked as part of a recipe returned a
11404 non-0 error code (@samp{Error @var{NN}}), which @code{make} interprets
11405 as failure, or it exited in some other abnormal fashion (with a
11406 signal of some type).  @xref{Errors, ,Errors in Recipes}.
11408 If no @code{***} is attached to the message, then the sub-process failed
11409 but the rule in the makefile was prefixed with the @code{-} special
11410 character, so @code{make} ignored the error.
11412 @item missing separator.  Stop.
11413 @itemx missing separator (did you mean TAB instead of 8 spaces?).  Stop.
11414 This means that @code{make} could not understand much of anything
11415 about the makefile line it just read.  GNU @code{make} looks for
11416 various separators (@code{:}, @code{=}, recipe prefix characters,
11417 etc.) to indicate what kind of line it's parsing.  This message means
11418 it couldn't find a valid one.
11420 One of the most common reasons for this message is that you (or
11421 perhaps your oh-so-helpful editor, as is the case with many MS-Windows
11422 editors) have attempted to indent your recipe lines with spaces
11423 instead of a tab character.  In this case, @code{make} will use the
11424 second form of the error above.  Remember that every line in the
11425 recipe must begin with a tab character (unless you set
11426 @code{.RECIPEPREFIX}; @pxref{Special Variables}).  Eight spaces do not
11427 count.  @xref{Rule Syntax}.
11429 @item recipe commences before first target.  Stop.
11430 @itemx missing rule before recipe.  Stop.
11431 This means the first thing in the makefile seems to be part of a
11432 recipe: it begins with a recipe prefix character and doesn't appear to
11433 be a legal @code{make} directive (such as a variable assignment).
11434 Recipes must always be associated with a target.
11436 The second form is generated if the line has a semicolon as the first
11437 non-whitespace character; @code{make} interprets this to mean you left
11438 out the "target: prerequisite" section of a rule.  @xref{Rule Syntax}.
11440 @item No rule to make target `@var{xxx}'.
11441 @itemx No rule to make target `@var{xxx}', needed by `@var{yyy}'.
11442 This means that @code{make} decided it needed to build a target, but
11443 then couldn't find any instructions in the makefile on how to do that,
11444 either explicit or implicit (including in the default rules database).
11446 If you want that file to be built, you will need to add a rule to your
11447 makefile describing how that target can be built.  Other possible
11448 sources of this problem are typos in the makefile (if that file name is
11449 wrong) or a corrupted source tree (if that file is not supposed to be
11450 built, but rather only a prerequisite).
11452 @item No targets specified and no makefile found.  Stop.
11453 @itemx No targets.  Stop.
11454 The former means that you didn't provide any targets to be built on the
11455 command line, and @code{make} couldn't find any makefiles to read in.
11456 The latter means that some makefile was found, but it didn't contain any
11457 default goal and none was given on the command line.  GNU @code{make}
11458 has nothing to do in these situations.
11459 @xref{Makefile Arguments, ,Arguments to Specify the Makefile}.@refill
11461 @item Makefile `@var{xxx}' was not found.
11462 @itemx Included makefile `@var{xxx}' was not found.
11463 A makefile specified on the command line (first form) or included
11464 (second form) was not found.
11466 @item warning: overriding recipe for target `@var{xxx}'
11467 @itemx warning: ignoring old recipe for target `@var{xxx}'
11468 GNU @code{make} allows only one recipe to be specified per target
11469 (except for double-colon rules).  If you give a recipe for a target
11470 which already has been defined to have one, this warning is issued and
11471 the second recipe will overwrite the first.  @xref{Multiple Rules,
11472 ,Multiple Rules for One Target}.
11474 @item Circular @var{xxx} <- @var{yyy} dependency dropped.
11475 This means that @code{make} detected a loop in the dependency graph:
11476 after tracing the prerequisite @var{yyy} of target @var{xxx}, and its
11477 prerequisites, etc., one of them depended on @var{xxx} again.
11479 @item Recursive variable `@var{xxx}' references itself (eventually).  Stop.
11480 This means you've defined a normal (recursive) @code{make} variable
11481 @var{xxx} that, when it's expanded, will refer to itself (@var{xxx}).
11482 This is not allowed; either use simply-expanded variables (@code{:=}) or
11483 use the append operator (@code{+=}).  @xref{Using Variables, ,How to Use
11484 Variables}.
11486 @item Unterminated variable reference.  Stop.
11487 This means you forgot to provide the proper closing parenthesis
11488 or brace in your variable or function reference.
11490 @item insufficient arguments to function `@var{xxx}'.  Stop.
11491 This means you haven't provided the requisite number of arguments for
11492 this function.  See the documentation of the function for a description
11493 of its arguments.  @xref{Functions, ,Functions for Transforming Text}.
11495 @item missing target pattern.  Stop.
11496 @itemx multiple target patterns.  Stop.
11497 @itemx target pattern contains no `%'.  Stop.
11498 @itemx mixed implicit and static pattern rules.  Stop.
11499 These are generated for malformed static pattern rules.  The first means
11500 there's no pattern in the target section of the rule; the second means
11501 there are multiple patterns in the target section; the third means
11502 the target doesn't contain a pattern character (@code{%}); and the
11503 fourth means that all three parts of the static pattern rule contain
11504 pattern characters (@code{%})--only the first two parts should.
11505 @xref{Static Usage, ,Syntax of Static Pattern Rules}.
11507 @item warning: -jN forced in submake: disabling jobserver mode.
11508 This warning and the next are generated if @code{make} detects error
11509 conditions related to parallel processing on systems where
11510 sub-@code{make}s can communicate (@pxref{Options/Recursion,
11511 ,Communicating Options to a Sub-@code{make}}).  This warning is
11512 generated if a recursive invocation of a @code{make} process is forced
11513 to have @samp{-j@var{N}} in its argument list (where @var{N} is greater
11514 than one).  This could happen, for example, if you set the @code{MAKE}
11515 environment variable to @samp{make -j2}.  In this case, the
11516 sub-@code{make} doesn't communicate with other @code{make} processes and
11517 will simply pretend it has two jobs of its own.
11519 @item warning: jobserver unavailable: using -j1.  Add `+' to parent make rule.
11520 In order for @code{make} processes to communicate, the parent will pass
11521 information to the child.  Since this could result in problems if the
11522 child process isn't actually a @code{make}, the parent will only do this
11523 if it thinks the child is a @code{make}.  The parent uses the normal
11524 algorithms to determine this (@pxref{MAKE Variable, ,How the @code{MAKE}
11525 Variable Works}).  If the makefile is constructed such that the parent
11526 doesn't know the child is a @code{make} process, then the child will
11527 receive only part of the information necessary.  In this case, the child
11528 will generate this warning message and proceed with its build in a
11529 sequential manner.
11531 @end table
11533 @node Complex Makefile, GNU Free Documentation License, Error Messages, Top
11534 @appendix Complex Makefile Example
11536 Here is the makefile for the GNU @code{tar} program.  This is a
11537 moderately complex makefile.  The first line uses a @code{#!} setting
11538 to allow the makefile to be executed directly.
11540 Because it is the first target, the default goal is @samp{all}.  An
11541 interesting feature of this makefile is that @file{testpad.h} is a
11542 source file automatically created by the @code{testpad} program,
11543 itself compiled from @file{testpad.c}.
11545 If you type @samp{make} or @samp{make all}, then @code{make} creates
11546 the @file{tar} executable, the @file{rmt} daemon that provides
11547 remote tape access, and the @file{tar.info} Info file.
11549 If you type @samp{make install}, then @code{make} not only creates
11550 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
11551 them.
11553 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
11554 files, and the @file{tar}, @file{rmt}, @file{testpad},
11555 @file{testpad.h}, and @file{core} files.
11557 If you type @samp{make distclean}, then @code{make} not only removes
11558 the same files as does @samp{make clean} but also the
11559 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
11560 (Although it is not evident, this makefile (and
11561 @file{config.status}) is generated by the user with the
11562 @code{configure} program, which is provided in the @code{tar}
11563 distribution, but is not shown here.)
11565 If you type @samp{make realclean}, then @code{make} removes the same
11566 files as does @samp{make distclean} and also removes the Info files
11567 generated from @file{tar.texinfo}.
11569 In addition, there are targets @code{shar} and @code{dist} that create
11570 distribution kits.
11572 @example
11573 @group
11574 #!/usr/bin/make -f
11575 # Generated automatically from Makefile.in by configure.
11576 # Un*x Makefile for GNU tar program.
11577 # Copyright (C) 1991 Free Software Foundation, Inc.
11578 @end group
11580 @group
11581 # This program is free software; you can redistribute
11582 # it and/or modify it under the terms of the GNU
11583 # General Public License @dots{}
11584 @dots{}
11585 @dots{}
11586 @end group
11588 SHELL = /bin/sh
11590 #### Start of system configuration section. ####
11592 srcdir = .
11594 @group
11595 # If you use gcc, you should either run the
11596 # fixincludes script that comes with it or else use
11597 # gcc with the -traditional option.  Otherwise ioctl
11598 # calls will be compiled incorrectly on some systems.
11599 CC = gcc -O
11600 YACC = bison -y
11601 INSTALL = /usr/local/bin/install -c
11602 INSTALLDATA = /usr/local/bin/install -c -m 644
11603 @end group
11605 # Things you might add to DEFS:
11606 # -DSTDC_HEADERS        If you have ANSI C headers and
11607 #                       libraries.
11608 # -DPOSIX               If you have POSIX.1 headers and
11609 #                       libraries.
11610 # -DBSD42               If you have sys/dir.h (unless
11611 #                       you use -DPOSIX), sys/file.h,
11612 #                       and st_blocks in `struct stat'.
11613 # -DUSG                 If you have System V/ANSI C
11614 #                       string and memory functions
11615 #                       and headers, sys/sysmacros.h,
11616 #                       fcntl.h, getcwd, no valloc,
11617 #                       and ndir.h (unless
11618 #                       you use -DDIRENT).
11619 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not
11620 #                       include memory.h.
11621 # -DDIRENT              If USG and you have dirent.h
11622 #                       instead of ndir.h.
11623 # -DSIGTYPE=int         If your signal handlers
11624 #                       return int, not void.
11625 # -DNO_MTIO             If you lack sys/mtio.h
11626 #                       (magtape ioctls).
11627 # -DNO_REMOTE           If you do not have a remote shell
11628 #                       or rexec.
11629 # -DUSE_REXEC           To use rexec for remote tape
11630 #                       operations instead of
11631 #                       forking rsh or remsh.
11632 # -DVPRINTF_MISSING     If you lack vprintf function
11633 #                       (but have _doprnt).
11634 # -DDOPRNT_MISSING      If you lack _doprnt function.
11635 #                       Also need to define
11636 #                       -DVPRINTF_MISSING.
11637 # -DFTIME_MISSING       If you lack ftime system call.
11638 # -DSTRSTR_MISSING      If you lack strstr function.
11639 # -DVALLOC_MISSING      If you lack valloc function.
11640 # -DMKDIR_MISSING       If you lack mkdir and
11641 #                       rmdir system calls.
11642 # -DRENAME_MISSING      If you lack rename system call.
11643 # -DFTRUNCATE_MISSING   If you lack ftruncate
11644 #                       system call.
11645 # -DV7                  On Version 7 Unix (not
11646 #                       tested in a long time).
11647 # -DEMUL_OPEN3          If you lack a 3-argument version
11648 #                       of open, and want to emulate it
11649 #                       with system calls you do have.
11650 # -DNO_OPEN3            If you lack the 3-argument open
11651 #                       and want to disable the tar -k
11652 #                       option instead of emulating open.
11653 # -DXENIX               If you have sys/inode.h
11654 #                       and need it 94 to be included.
11656 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
11657         -DVPRINTF_MISSING -DBSD42
11658 # Set this to rtapelib.o unless you defined NO_REMOTE,
11659 # in which case make it empty.
11660 RTAPELIB = rtapelib.o
11661 LIBS =
11662 DEF_AR_FILE = /dev/rmt8
11663 DEFBLOCKING = 20
11665 @group
11666 CDEBUG = -g
11667 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
11668         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
11669         -DDEFBLOCKING=$(DEFBLOCKING)
11670 LDFLAGS = -g
11671 @end group
11673 @group
11674 prefix = /usr/local
11675 # Prefix for each installed program,
11676 # normally empty or `g'.
11677 binprefix =
11679 # The directory to install tar in.
11680 bindir = $(prefix)/bin
11682 # The directory to install the info files in.
11683 infodir = $(prefix)/info
11684 @end group
11686 #### End of system configuration section. ####
11688 @group
11689 SRCS_C  = tar.c create.c extract.c buffer.c   \
11690           getoldopt.c update.c gnu.c mangle.c \
11691           version.c list.c names.c diffarch.c \
11692           port.c wildmat.c getopt.c getopt1.c \
11693           regex.c
11694 SRCS_Y  = getdate.y
11695 SRCS    = $(SRCS_C) $(SRCS_Y)
11696 OBJS    = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB)
11697 @end group
11698 @group
11699 AUX =   README COPYING ChangeLog Makefile.in  \
11700         makefile.pc configure configure.in \
11701         tar.texinfo tar.info* texinfo.tex \
11702         tar.h port.h open3.h getopt.h regex.h \
11703         rmt.h rmt.c rtapelib.c alloca.c \
11704         msd_dir.h msd_dir.c tcexparg.c \
11705         level-0 level-1 backup-specs testpad.c
11706 @end group
11708 .PHONY: all
11709 all:    tar rmt tar.info
11711 @group
11712 tar:    $(OBJS)
11713         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
11714 @end group
11716 @group
11717 rmt:    rmt.c
11718         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
11719 @end group
11721 @group
11722 tar.info: tar.texinfo
11723         makeinfo tar.texinfo
11724 @end group
11726 @group
11727 .PHONY: install
11728 install: all
11729         $(INSTALL) tar $(bindir)/$(binprefix)tar
11730         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
11731         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
11732 @end group
11734 @group
11735 $(OBJS): tar.h port.h testpad.h
11736 regex.o buffer.o tar.o: regex.h
11737 # getdate.y has 8 shift/reduce conflicts.
11738 @end group
11740 @group
11741 testpad.h: testpad
11742         ./testpad
11743 @end group
11745 @group
11746 testpad: testpad.o
11747         $(CC) -o $@@ testpad.o
11748 @end group
11750 @group
11751 TAGS:   $(SRCS)
11752         etags $(SRCS)
11753 @end group
11755 @group
11756 .PHONY: clean
11757 clean:
11758         rm -f *.o tar rmt testpad testpad.h core
11759 @end group
11761 @group
11762 .PHONY: distclean
11763 distclean: clean
11764         rm -f TAGS Makefile config.status
11765 @end group
11767 @group
11768 .PHONY: realclean
11769 realclean: distclean
11770         rm -f tar.info*
11771 @end group
11773 @group
11774 .PHONY: shar
11775 shar: $(SRCS) $(AUX)
11776         shar $(SRCS) $(AUX) | compress \
11777           > tar-`sed -e '/version_string/!d' \
11778                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11779                      -e q
11780                      version.c`.shar.Z
11781 @end group
11783 @group
11784 .PHONY: dist
11785 dist: $(SRCS) $(AUX)
11786         echo tar-`sed \
11787              -e '/version_string/!d' \
11788              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11789              -e q
11790              version.c` > .fname
11791         -rm -rf `cat .fname`
11792         mkdir `cat .fname`
11793         ln $(SRCS) $(AUX) `cat .fname`
11794         tar chZf `cat .fname`.tar.Z `cat .fname`
11795         -rm -rf `cat .fname` .fname
11796 @end group
11798 @group
11799 tar.zoo: $(SRCS) $(AUX)
11800         -rm -rf tmp.dir
11801         -mkdir tmp.dir
11802         -rm tar.zoo
11803         for X in $(SRCS) $(AUX) ; do \
11804             echo $$X ; \
11805             sed 's/$$/^M/' $$X \
11806             > tmp.dir/$$X ; done
11807         cd tmp.dir ; zoo aM ../tar.zoo *
11808         -rm -rf tmp.dir
11809 @end group
11810 @end example
11812 @node GNU Free Documentation License, Concept Index, Complex Makefile, Top
11813 @appendixsec GNU Free Documentation License
11814 @cindex FDL, GNU Free Documentation License
11815 @include fdl.texi
11817 @node Concept Index, Name Index, GNU Free Documentation License, Top
11818 @unnumbered Index of Concepts
11820 @printindex cp
11822 @node Name Index,  , Concept Index, Top
11823 @unnumbered Index of Functions, Variables, & Directives
11825 @printindex fn
11827 @bye