Create a new internal interface for defining new make functions.
[make.git] / doc / make.texi
blob7f7b46f5d32f56a15ff492410bf8ef62505b893f
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.76 2012/01/16 02:44:04 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 * Call Function::               Expand a user-defined function.
269 * Value Function::              Return the un-expanded value of a variable.
270 * Eval Function::               Evaluate the arguments as makefile syntax.
271 * Origin Function::             Find where a variable got its value.
272 * Flavor Function::             Find out the flavor of a variable.
273 * Make Control Functions::      Functions that control how make runs.
274 * Shell Function::              Substitute the output of a shell command.
275 * Guile Function::              Call the GNU Guile embedded scripting language.
277 The @code{guile} Function
279 * Guile Types::                 Converting Guile types to @code{make} strings.
280 * Guile Interface::             Invoking @code{make} functions from Guile.
281 * Guile Example::               Example using Guile in @code{make}.
283 How to Run @code{make}
285 * Makefile Arguments::          How to specify which makefile to use.
286 * Goals::                       How to use goal arguments to specify which
287                                   parts of the makefile to use.
288 * Instead of Execution::        How to use mode flags to specify what
289                                   kind of thing to do with the recipes
290                                   in the makefile other than simply
291                                   execute them.
292 * Avoiding Compilation::        How to avoid recompiling certain files.
293 * Overriding::                  How to override a variable to specify
294                                   an alternate compiler and other things.
295 * Testing::                     How to proceed past some errors, to
296                                   test compilation.
297 * Options Summary::             Summary of Options
299 Using Implicit Rules
301 * Using Implicit::              How to use an existing implicit rule
302                                   to get the recipes for updating a file.
303 * Catalogue of Rules::          A list of built-in implicit rules.
304 * Implicit Variables::          How to change what predefined rules do.
305 * Chained Rules::               How to use a chain of implicit rules.
306 * Pattern Rules::               How to define new implicit rules.
307 * Last Resort::                 How to define a recipe for rules which
308                                   cannot find any.
309 * Suffix Rules::                The old-fashioned style of implicit rule.
310 * Implicit Rule Search::        The precise algorithm for applying
311                                   implicit rules.
313 Defining and Redefining Pattern Rules
315 * Pattern Intro::               An introduction to pattern rules.
316 * Pattern Examples::            Examples of pattern rules.
317 * Automatic Variables::         How to use automatic variables in the
318                                   recipe of implicit rules.
319 * Pattern Match::               How patterns match.
320 * Match-Anything Rules::        Precautions you should take prior to
321                                   defining rules that can match any
322                                   target file whatever.
323 * Canceling Rules::             How to override or cancel built-in rules.
325 Using @code{make} to Update Archive Files
327 * Archive Members::             Archive members as targets.
328 * Archive Update::              The implicit rule for archive member targets.
329 * Archive Pitfalls::            Dangers to watch out for when using archives.
330 * Archive Suffix Rules::        You can write a special kind of suffix rule
331                                   for updating archives.
333 Implicit Rule for Archive Member Targets
335 * Archive Symbols::             How to update archive symbol directories.
337 @end detailmenu
338 @end menu
340 @node Overview, Introduction, Top, Top
341 @comment  node-name,  next,  previous,  up
342 @chapter Overview of @code{make}
344 The @code{make} utility automatically determines which pieces of a large
345 program need to be recompiled, and issues commands to recompile them.
346 This manual describes GNU @code{make}, which was implemented by Richard
347 Stallman and Roland McGrath.  Development since Version 3.76 has been
348 handled by Paul D. Smith.
350 GNU @code{make} conforms to section 6.2 of @cite{IEEE Standard
351 1003.2-1992} (POSIX.2).
352 @cindex POSIX
353 @cindex IEEE Standard 1003.2
354 @cindex standards conformance
356 Our examples show C programs, since they are most common, but you can use
357 @code{make} with any programming language whose compiler can be run with a
358 shell command.  Indeed, @code{make} is not limited to programs.  You can
359 use it to describe any task where some files must be updated automatically
360 from others whenever the others change.
362 @menu
363 * Preparing::                   Preparing and running @code{make}.
364 * Reading::                     On reading this text.
365 * Bugs::                        Problems and bugs.
366 @end menu
368 @node Preparing, Reading, Overview, Overview
369 @ifnottex
370 @heading Preparing and Running Make
371 @end ifnottex
373 To prepare to use @code{make}, you must write a file called
374 the @dfn{makefile} that describes the relationships among files
375 in your program and provides commands for updating each file.
376 In a program, typically, the executable file is updated from object
377 files, which are in turn made by compiling source files.@refill
379 Once a suitable makefile exists, each time you change some source files,
380 this simple shell command:
382 @example
383 make
384 @end example
386 @noindent
387 suffices to perform all necessary recompilations.  The @code{make} program
388 uses the makefile data base and the last-modification times of the files to
389 decide which of the files need to be updated.  For each of those files, it
390 issues the recipes recorded in the data base.
392 You can provide command line arguments to @code{make} to control which
393 files should be recompiled, or how.  @xref{Running, ,How to Run
394 @code{make}}.
396 @node Reading, Bugs, Preparing, Overview
397 @section How to Read This Manual
399 If you are new to @code{make}, or are looking for a general
400 introduction, read the first few sections of each chapter, skipping the
401 later sections.  In each chapter, the first few sections contain
402 introductory or general information and the later sections contain
403 specialized or technical information.
404 @ifnottex
405 The exception is the second chapter, @ref{Introduction, ,An
406 Introduction to Makefiles}, all of which is introductory.
407 @end ifnottex
408 @iftex
409 The exception is @ref{Introduction, ,An Introduction to Makefiles},
410 all of which is introductory.
411 @end iftex
413 If you are familiar with other @code{make} programs, see @ref{Features,
414 ,Features of GNU @code{make}}, which lists the enhancements GNU
415 @code{make} has, and @ref{Missing, ,Incompatibilities and Missing
416 Features}, which explains the few things GNU @code{make} lacks that
417 others have.
419 For a quick summary, see @ref{Options Summary}, @ref{Quick Reference},
420 and @ref{Special Targets}.
422 @node Bugs,  , Reading, Overview
423 @section Problems and Bugs
424 @cindex reporting bugs
425 @cindex bugs, reporting
426 @cindex problems and bugs, reporting
428 If you have problems with GNU @code{make} or think you've found a bug,
429 please report it to the developers; we cannot promise to do anything but
430 we might well want to fix it.
432 Before reporting a bug, make sure you've actually found a real bug.
433 Carefully reread the documentation and see if it really says you can do
434 what you're trying to do.  If it's not clear whether you should be able
435 to do something or not, report that too; it's a bug in the
436 documentation!
438 Before reporting a bug or trying to fix it yourself, try to isolate it
439 to the smallest possible makefile that reproduces the problem.  Then
440 send us the makefile and the exact results @code{make} gave you,
441 including any error or warning messages.  Please don't paraphrase
442 these messages: it's best to cut and paste them into your report.
443 When generating this small makefile, be sure to not use any non-free
444 or unusual tools in your recipes: you can almost always emulate what
445 such a tool would do with simple shell commands.  Finally, be sure to
446 explain what you expected to occur; this will help us decide whether
447 the problem was really in the documentation.
449 Once you have a precise problem you can report it in one of two ways.
450 Either send electronic mail to:
452 @example
453     bug-make@@gnu.org
454 @end example
456 @noindent
457 or use our Web-based project management tool, at:
459 @example
460     http://savannah.gnu.org/projects/make/
461 @end example
463 @noindent
464 In addition to the information above, please be careful to include the
465 version number of @code{make} you are using.  You can get this
466 information with the command @samp{make --version}.  Be sure also to
467 include the type of machine and operating system you are using.  One
468 way to obtain this information is by looking at the final lines of
469 output from the command @samp{make --help}.
471 @node Introduction, Makefiles, Overview, Top
472 @comment  node-name,  next,  previous,  up
473 @chapter An Introduction to Makefiles
475 You need a file called a @dfn{makefile} to tell @code{make} what to do.
476 Most often, the makefile tells @code{make} how to compile and link a
477 program.
478 @cindex makefile
480 In this chapter, we will discuss a simple makefile that describes how to
481 compile and link a text editor which consists of eight C source files
482 and three header files.  The makefile can also tell @code{make} how to
483 run miscellaneous commands when explicitly asked (for example, to remove
484 certain files as a clean-up operation).  To see a more complex example
485 of a makefile, see @ref{Complex Makefile}.
487 When @code{make} recompiles the editor, each changed C source file
488 must be recompiled.  If a header file has changed, each C source file
489 that includes the header file must be recompiled to be safe.  Each
490 compilation produces an object file corresponding to the source file.
491 Finally, if any source file has been recompiled, all the object files,
492 whether newly made or saved from previous compilations, must be linked
493 together to produce the new executable editor.
494 @cindex recompilation
495 @cindex editor
497 @menu
498 * Rule Introduction::           What a rule looks like.
499 * Simple Makefile::             A simple makefile.
500 * How Make Works::              How @code{make} processes this makefile.
501 * Variables Simplify::          Variables make makefiles simpler.
502 * make Deduces::                Letting @code{make} deduce the recipes.
503 * Combine By Prerequisite::     Another style of makefile.
504 * Cleanup::                     Rules for cleaning the directory.
505 @end menu
507 @node Rule Introduction, Simple Makefile, Introduction, Introduction
508 @comment  node-name,  next,  previous,  up
509 @section What a Rule Looks Like
510 @cindex rule, introduction to
511 @cindex makefile rule parts
512 @cindex parts of makefile rule
514 A simple makefile consists of ``rules'' with the following shape:
516 @cindex targets, introduction to
517 @cindex prerequisites, introduction to
518 @cindex recipes, introduction to
519 @example
520 @group
521 @var{target} @dots{} : @var{prerequisites} @dots{}
522         @var{recipe}
523         @dots{}
524         @dots{}
525 @end group
526 @end example
528 A @dfn{target} is usually the name of a file that is generated by a
529 program; examples of targets are executable or object files.  A target
530 can also be the name of an action to carry out, such as @samp{clean}
531 (@pxref{Phony Targets}).
533 A @dfn{prerequisite} is a file that is used as input to create the
534 target.  A target often depends on several files.
536 @cindex tabs in rules
537 A @dfn{recipe} is an action that @code{make} carries out.  A recipe
538 may have more than one command, either on the same line or each on its
539 own line.  @strong{Please note:} you need to put a tab character at
540 the beginning of every recipe line!  This is an obscurity that catches
541 the unwary.  If you prefer to prefix your recipes with a character
542 other than tab, you can set the @code{.RECIPEPREFIX} variable to an
543 alternate character (@pxref{Special Variables}).
545 Usually a recipe is in a rule with prerequisites and serves to create a
546 target file if any of the prerequisites change.  However, the rule that
547 specifies a recipe for the target need not have prerequisites.  For
548 example, the rule containing the delete command associated with the
549 target @samp{clean} does not have prerequisites.
551 A @dfn{rule}, then, explains how and when to remake certain files
552 which are the targets of the particular rule.  @code{make} carries out
553 the recipe on the prerequisites to create or update the target.  A
554 rule can also explain how and when to carry out an action.
555 @xref{Rules, , Writing Rules}.
557 A makefile may contain other text besides rules, but a simple makefile
558 need only contain rules.  Rules may look somewhat more complicated
559 than shown in this template, but all fit the pattern more or less.
561 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
562 @section A Simple Makefile
563 @cindex simple makefile
564 @cindex makefile, simple
566 Here is a straightforward makefile that describes the way an
567 executable file called @code{edit} depends on eight object files
568 which, in turn, depend on eight C source and three header files.
570 In this example, all the C files include @file{defs.h}, but only those
571 defining editing commands include @file{command.h}, and only low
572 level files that change the editor buffer include @file{buffer.h}.
574 @example
575 @group
576 edit : main.o kbd.o command.o display.o \
577        insert.o search.o files.o utils.o
578         cc -o edit main.o kbd.o command.o display.o \
579                    insert.o search.o files.o utils.o
581 main.o : main.c defs.h
582         cc -c main.c
583 kbd.o : kbd.c defs.h command.h
584         cc -c kbd.c
585 command.o : command.c defs.h command.h
586         cc -c command.c
587 display.o : display.c defs.h buffer.h
588         cc -c display.c
589 insert.o : insert.c defs.h buffer.h
590         cc -c insert.c
591 search.o : search.c defs.h buffer.h
592         cc -c search.c
593 files.o : files.c defs.h buffer.h command.h
594         cc -c files.c
595 utils.o : utils.c defs.h
596         cc -c utils.c
597 clean :
598         rm edit main.o kbd.o command.o display.o \
599            insert.o search.o files.o utils.o
600 @end group
601 @end example
603 @noindent
604 We split each long line into two lines using backslash-newline; this is
605 like using one long line, but is easier to read.
606 @cindex continuation lines
607 @cindex @code{\} (backslash), for continuation lines
608 @cindex backslash (@code{\}), for continuation lines
609 @cindex quoting newline, in makefile
610 @cindex newline, quoting, in makefile
612 To use this makefile to create the executable file called @file{edit},
613 type:
615 @example
616 make
617 @end example
619 To use this makefile to delete the executable file and all the object
620 files from the directory, type:
622 @example
623 make clean
624 @end example
626 In the example makefile, the targets include the executable file
627 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
628 prerequisites are files such as @samp{main.c} and @samp{defs.h}.
629 In fact, each @samp{.o} file is both a target and a prerequisite.
630 Recipes include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
632 When a target is a file, it needs to be recompiled or relinked if any
633 of its prerequisites change.  In addition, any prerequisites that are
634 themselves automatically generated should be updated first.  In this
635 example, @file{edit} depends on each of the eight object files; the
636 object file @file{main.o} depends on the source file @file{main.c} and
637 on the header file @file{defs.h}.
639 A recipe may follow each line that contains a target and
640 prerequisites.  These recipes say how to update the target file.  A
641 tab character (or whatever character is specified by the
642 @code{.RECIPEPREFIX} variable; @pxref{Special Variables}) must come at
643 the beginning of every line in the recipe to distinguish recipes from
644 other lines in the makefile.  (Bear in mind that @code{make} does not
645 know anything about how the recipes work.  It is up to you to supply
646 recipes that will update the target file properly.  All @code{make}
647 does is execute the recipe you have specified when the target file
648 needs to be updated.)@refill
649 @cindex recipe
651 The target @samp{clean} is not a file, but merely the name of an
652 action.  Since you normally do not want to carry out the actions in
653 this rule, @samp{clean} is not a prerequisite of any other rule.
654 Consequently, @code{make} never does anything with it unless you tell
655 it specifically.  Note that this rule not only is not a prerequisite,
656 it also does not have any prerequisites, so the only purpose of the
657 rule is to run the specified recipe.  Targets that do not refer to
658 files but are just actions are called @dfn{phony targets}.
659 @xref{Phony Targets}, for information about this kind of target.
660 @xref{Errors, , Errors in Recipes}, to see how to cause @code{make}
661 to ignore errors from @code{rm} or any other command.
662 @cindex @code{clean} target
663 @cindex @code{rm} (shell command)
665 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
666 @comment  node-name,  next,  previous,  up
667 @section How @code{make} Processes a Makefile
668 @cindex processing a makefile
669 @cindex makefile, how @code{make} processes
671 By default, @code{make} starts with the first target (not targets whose
672 names start with @samp{.}).  This is called the @dfn{default goal}.
673 (@dfn{Goals} are the targets that @code{make} strives ultimately to
674 update.    You can override this behavior using the command line
675 (@pxref{Goals, , Arguments to Specify the Goals}) or with the
676 @code{.DEFAULT_GOAL} special variable (@pxref{Special Variables, ,
677 Other Special Variables}).
678 @cindex default goal
679 @cindex goal, default
680 @cindex goal
682 In the simple example of the previous section, the default goal is to
683 update the executable program @file{edit}; therefore, we put that rule
684 first.
686 Thus, when you give the command:
688 @example
689 make
690 @end example
692 @noindent
693 @code{make} reads the makefile in the current directory and begins by
694 processing the first rule.  In the example, this rule is for relinking
695 @file{edit}; but before @code{make} can fully process this rule, it
696 must process the rules for the files that @file{edit} depends on,
697 which in this case are the object files.  Each of these files is
698 processed according to its own rule.  These rules say to update each
699 @samp{.o} file by compiling its source file.  The recompilation must
700 be done if the source file, or any of the header files named as
701 prerequisites, is more recent than the object file, or if the object
702 file does not exist.
704 The other rules are processed because their targets appear as
705 prerequisites of the goal.  If some other rule is not depended on by the
706 goal (or anything it depends on, etc.), that rule is not processed,
707 unless you tell @code{make} to do so (with a command such as
708 @w{@code{make clean}}).
710 Before recompiling an object file, @code{make} considers updating its
711 prerequisites, the source file and header files.  This makefile does not
712 specify anything to be done for them---the @samp{.c} and @samp{.h} files
713 are not the targets of any rules---so @code{make} does nothing for these
714 files.  But @code{make} would update automatically generated C programs,
715 such as those made by Bison or Yacc, by their own rules at this time.
717 After recompiling whichever object files need it, @code{make} decides
718 whether to relink @file{edit}.  This must be done if the file
719 @file{edit} does not exist, or if any of the object files are newer than
720 it.  If an object file was just recompiled, it is now newer than
721 @file{edit}, so @file{edit} is relinked.
722 @cindex relinking
724 Thus, if we change the file @file{insert.c} and run @code{make},
725 @code{make} will compile that file to update @file{insert.o}, and then
726 link @file{edit}.  If we change the file @file{command.h} and run
727 @code{make}, @code{make} will recompile the object files @file{kbd.o},
728 @file{command.o} and @file{files.o} and then link the file @file{edit}.
730 @node Variables Simplify, make Deduces, How Make Works, Introduction
731 @section Variables Make Makefiles Simpler
732 @cindex variables
733 @cindex simplifying with variables
735 In our example, we had to list all the object files twice in the rule for
736 @file{edit} (repeated here):
738 @example
739 @group
740 edit : main.o kbd.o command.o display.o \
741               insert.o search.o files.o utils.o
742         cc -o edit main.o kbd.o command.o display.o \
743                    insert.o search.o files.o utils.o
744 @end group
745 @end example
747 @cindex @code{objects}
748 Such duplication is error-prone; if a new object file is added to the
749 system, we might add it to one list and forget the other.  We can eliminate
750 the risk and simplify the makefile by using a variable.  @dfn{Variables}
751 allow a text string to be defined once and substituted in multiple places
752 later (@pxref{Using Variables, ,How to Use Variables}).
754 @cindex @code{OBJECTS}
755 @cindex @code{objs}
756 @cindex @code{OBJS}
757 @cindex @code{obj}
758 @cindex @code{OBJ}
759 It is standard practice for every makefile to have a variable named
760 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
761 or @code{OBJ} which is a list of all object file names.  We would
762 define such a variable @code{objects} with a line like this in the
763 makefile:@refill
765 @example
766 @group
767 objects = main.o kbd.o command.o display.o \
768           insert.o search.o files.o utils.o
769 @end group
770 @end example
772 @noindent
773 Then, each place we want to put a list of the object file names, we can
774 substitute the variable's value by writing @samp{$(objects)}
775 (@pxref{Using Variables, ,How to Use Variables}).
777 Here is how the complete simple makefile looks when you use a variable
778 for the object files:
780 @example
781 @group
782 objects = main.o kbd.o command.o display.o \
783           insert.o search.o files.o utils.o
785 edit : $(objects)
786         cc -o edit $(objects)
787 main.o : main.c defs.h
788         cc -c main.c
789 kbd.o : kbd.c defs.h command.h
790         cc -c kbd.c
791 command.o : command.c defs.h command.h
792         cc -c command.c
793 display.o : display.c defs.h buffer.h
794         cc -c display.c
795 insert.o : insert.c defs.h buffer.h
796         cc -c insert.c
797 search.o : search.c defs.h buffer.h
798         cc -c search.c
799 files.o : files.c defs.h buffer.h command.h
800         cc -c files.c
801 utils.o : utils.c defs.h
802         cc -c utils.c
803 clean :
804         rm edit $(objects)
805 @end group
806 @end example
808 @node make Deduces, Combine By Prerequisite, Variables Simplify, Introduction
809 @section Letting @code{make} Deduce the Recipes
810 @cindex deducing recipes (implicit rules)
811 @cindex implicit rule, introduction to
812 @cindex rule, implicit, introduction to
814 It is not necessary to spell out the recipes for compiling the individual
815 C source files, because @code{make} can figure them out: it has an
816 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
817 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
818 use the recipe @samp{cc -c main.c -o main.o} to compile @file{main.c} into
819 @file{main.o}.  We can therefore omit the recipes from the rules for the
820 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.@refill
822 When a @samp{.c} file is used automatically in this way, it is also
823 automatically added to the list of prerequisites.  We can therefore omit
824 the @samp{.c} files from the prerequisites, provided we omit the recipe.
826 Here is the entire example, with both of these changes, and a variable
827 @code{objects} as suggested above:
829 @example
830 @group
831 objects = main.o kbd.o command.o display.o \
832           insert.o search.o files.o utils.o
834 edit : $(objects)
835         cc -o edit $(objects)
837 main.o : defs.h
838 kbd.o : defs.h command.h
839 command.o : defs.h command.h
840 display.o : defs.h buffer.h
841 insert.o : defs.h buffer.h
842 search.o : defs.h buffer.h
843 files.o : defs.h buffer.h command.h
844 utils.o : defs.h
846 .PHONY : clean
847 clean :
848         rm edit $(objects)
849 @end group
850 @end example
852 @noindent
853 This is how we would write the makefile in actual practice.  (The
854 complications associated with @samp{clean} are described elsewhere.
855 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Recipes}.)
857 Because implicit rules are so convenient, they are important.  You
858 will see them used frequently.@refill
860 @node Combine By Prerequisite, Cleanup, make Deduces, Introduction
861 @section Another Style of Makefile
862 @cindex combining rules by prerequisite
864 When the objects of a makefile are created only by implicit rules, an
865 alternative style of makefile is possible.  In this style of makefile,
866 you group entries by their prerequisites instead of by their targets.
867 Here is what one looks like:
869 @example
870 @group
871 objects = main.o kbd.o command.o display.o \
872           insert.o search.o files.o utils.o
874 edit : $(objects)
875         cc -o edit $(objects)
877 $(objects) : defs.h
878 kbd.o command.o files.o : command.h
879 display.o insert.o search.o files.o : buffer.h
880 @end group
881 @end example
883 @noindent
884 Here @file{defs.h} is given as a prerequisite of all the object files;
885 @file{command.h} and @file{buffer.h} are prerequisites of the specific
886 object files listed for them.
888 Whether this is better is a matter of taste: it is more compact, but some
889 people dislike it because they find it clearer to put all the information
890 about each target in one place.
892 @node Cleanup,  , Combine By Prerequisite, Introduction
893 @section Rules for Cleaning the Directory
894 @cindex cleaning up
895 @cindex removing, to clean up
897 Compiling a program is not the only thing you might want to write rules
898 for.  Makefiles commonly tell how to do a few other things besides
899 compiling a program: for example, how to delete all the object files
900 and executables so that the directory is @samp{clean}.
902 @cindex @code{clean} target
903 Here is how we
904 could write a @code{make} rule for cleaning our example editor:
906 @example
907 @group
908 clean:
909         rm edit $(objects)
910 @end group
911 @end example
913 In practice, we might want to write the rule in a somewhat more
914 complicated manner to handle unanticipated situations.  We would do this:
916 @example
917 @group
918 .PHONY : clean
919 clean :
920         -rm edit $(objects)
921 @end group
922 @end example
924 @noindent
925 This prevents @code{make} from getting confused by an actual file
926 called @file{clean} and causes it to continue in spite of errors from
927 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
928 Recipes}.)
930 @noindent
931 A rule such as this should not be placed at the beginning of the
932 makefile, because we do not want it to run by default!  Thus, in the
933 example makefile, we want the rule for @code{edit}, which recompiles
934 the editor, to remain the default goal.
936 Since @code{clean} is not a prerequisite of @code{edit}, this rule will not
937 run at all if we give the command @samp{make} with no arguments.  In
938 order to make the rule run, we have to type @samp{make clean}.
939 @xref{Running, ,How to Run @code{make}}.
941 @node Makefiles, Rules, Introduction, Top
942 @chapter Writing Makefiles
944 @cindex makefile, how to write
945 The information that tells @code{make} how to recompile a system comes from
946 reading a data base called the @dfn{makefile}.
948 @menu
949 * Makefile Contents::           What makefiles contain.
950 * Makefile Names::              How to name your makefile.
951 * Include::                     How one makefile can use another makefile.
952 * MAKEFILES Variable::          The environment can specify extra makefiles.
953 * Remaking Makefiles::          How makefiles get remade.
954 * Overriding Makefiles::        How to override part of one makefile
955                                   with another makefile.
956 * Reading Makefiles::           How makefiles are parsed.
957 * Secondary Expansion::         How and when secondary expansion is performed.
958 @end menu
960 @node Makefile Contents, Makefile Names, Makefiles, Makefiles
961 @section What Makefiles Contain
963 Makefiles contain five kinds of things: @dfn{explicit rules},
964 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
965 and @dfn{comments}.  Rules, variables, and directives are described at
966 length in later chapters.@refill
968 @itemize @bullet
969 @cindex rule, explicit, definition of
970 @cindex explicit rule, definition of
971 @item
972 An @dfn{explicit rule} says when and how to remake one or more files,
973 called the rule's @dfn{targets}.  It lists the other files that the
974 targets depend on, called the @dfn{prerequisites} of the target, and
975 may also give a recipe to use to create or update the targets.
976 @xref{Rules, ,Writing Rules}.
978 @cindex rule, implicit, definition of
979 @cindex implicit rule, definition of
980 @item
981 An @dfn{implicit rule} says when and how to remake a class of files
982 based on their names.  It describes how a target may depend on a file
983 with a name similar to the target and gives a recipe to create or
984 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
986 @cindex variable definition
987 @item
988 A @dfn{variable definition} is a line that specifies a text string
989 value for a variable that can be substituted into the text later.  The
990 simple makefile example shows a variable definition for @code{objects}
991 as a list of all object files (@pxref{Variables Simplify, , Variables
992 Make Makefiles Simpler}).
994 @cindex directive
995 @item
996 A @dfn{directive} is an instruction for @code{make} to do something
997 special while reading the makefile.  These include:
999 @itemize @bullet
1000 @item
1001 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
1003 @item
1004 Deciding (based on the values of variables) whether to use or
1005 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
1007 @item
1008 Defining a variable from a verbatim string containing multiple lines
1009 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).
1010 @end itemize
1012 @cindex comments, in makefile
1013 @cindex @code{#} (comments), in makefile
1014 @item
1015 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the
1016 rest of the line are ignored, except that a trailing backslash not
1017 escaped by another backslash will continue the comment across multiple
1018 lines.  A line containing just a comment (with perhaps spaces before
1019 it) is effectively blank, and is ignored.  If you want a literal
1020 @code{#}, escape it with a backslash (e.g., @code{\#}).  Comments may
1021 appear on any line in the makefile, although they are treated
1022 specially in certain situations.
1024 You cannot use comments within variable references or function calls:
1025 any instance of @code{#} will be treated literally (rather than as the
1026 start of a comment) inside a variable reference or function call.
1028 Comments within a recipe are passed to the shell, just as with any
1029 other recipe text.  The shell decides how to interpret it: whether or
1030 not this is a comment is up to the shell.
1032 Within a @code{define} directive, comments are not ignored during the
1033 definition of the variable, but rather kept intact in the value of the
1034 variable.  When the variable is expanded they will either be treated
1035 as @code{make} comments or as recipe text, depending on the context in
1036 which the variable is evaluated.
1037 @end itemize
1039 @node Makefile Names, Include, Makefile Contents, Makefiles
1040 @section What Name to Give Your Makefile
1041 @cindex makefile name
1042 @cindex name of makefile
1043 @cindex default makefile name
1044 @cindex file name of makefile
1046 @c following paragraph rewritten to avoid overfull hbox
1047 By default, when @code{make} looks for the makefile, it tries the
1048 following names, in order: @file{GNUmakefile}, @file{makefile}
1049 and @file{Makefile}.@refill
1050 @findex Makefile
1051 @findex GNUmakefile
1052 @findex makefile
1054 @cindex @code{README}
1055 Normally you should call your makefile either @file{makefile} or
1056 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1057 prominently near the beginning of a directory listing, right near other
1058 important files such as @file{README}.)  The first name checked,
1059 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1060 use this name if you have a makefile that is specific to GNU
1061 @code{make}, and will not be understood by other versions of
1062 @code{make}.  Other @code{make} programs look for @file{makefile} and
1063 @file{Makefile}, but not @file{GNUmakefile}.
1065 If @code{make} finds none of these names, it does not use any makefile.
1066 Then you must specify a goal with a command argument, and @code{make}
1067 will attempt to figure out how to remake it using only its built-in
1068 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1070 @cindex @code{-f}
1071 @cindex @code{--file}
1072 @cindex @code{--makefile}
1073 If you want to use a nonstandard name for your makefile, you can specify
1074 the makefile name with the @samp{-f} or @samp{--file} option.  The
1075 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1076 @code{make} to read the file @var{name} as the makefile.  If you use
1077 more than one @samp{-f} or @samp{--file} option, you can specify several
1078 makefiles.  All the makefiles are effectively concatenated in the order
1079 specified.  The default makefile names @file{GNUmakefile},
1080 @file{makefile} and @file{Makefile} are not checked automatically if you
1081 specify @samp{-f} or @samp{--file}.@refill
1082 @cindex specifying makefile name
1083 @cindex makefile name, how to specify
1084 @cindex name of makefile, how to specify
1085 @cindex file name of makefile, how to specify
1087 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1088 @section Including Other Makefiles
1089 @cindex including other makefiles
1090 @cindex makefile, including
1092 @findex include
1093 The @code{include} directive tells @code{make} to suspend reading the
1094 current makefile and read one or more other makefiles before continuing.
1095 The directive is a line in the makefile that looks like this:
1097 @example
1098 include @var{filenames}@dots{}
1099 @end example
1101 @noindent
1102 @var{filenames} can contain shell file name patterns.  If
1103 @var{filenames} is empty, nothing is included and no error is printed.
1104 @cindex shell file name pattern (in @code{include})
1105 @cindex shell wildcards (in @code{include})
1106 @cindex wildcard, in @code{include}
1108 Extra spaces are allowed and ignored at the beginning of the line, but
1109 the first character must not be a tab (or the value of
1110 @code{.RECIPEPREFIX})---if the line begins with a tab, it will be
1111 considered a recipe line.  Whitespace is required between
1112 @code{include} and the file names, and between file names; extra
1113 whitespace is ignored there and at the end of the directive.  A
1114 comment starting with @samp{#} is allowed at the end of the line.  If
1115 the file names contain any variable or function references, they are
1116 expanded.  @xref{Using Variables, ,How to Use Variables}.
1118 For example, if you have three @file{.mk} files, @file{a.mk},
1119 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1120 @code{bish bash}, then the following expression
1122 @example
1123 include foo *.mk $(bar)
1124 @end example
1126 is equivalent to
1128 @example
1129 include foo a.mk b.mk c.mk bish bash
1130 @end example
1132 When @code{make} processes an @code{include} directive, it suspends
1133 reading of the containing makefile and reads from each listed file in
1134 turn.  When that is finished, @code{make} resumes reading the
1135 makefile in which the directive appears.
1137 One occasion for using @code{include} directives is when several programs,
1138 handled by individual makefiles in various directories, need to use a
1139 common set of variable definitions
1140 (@pxref{Setting, ,Setting Variables}) or pattern rules
1141 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1143 Another such occasion is when you want to generate prerequisites from
1144 source files automatically; the prerequisites can be put in a file that
1145 is included by the main makefile.  This practice is generally cleaner
1146 than that of somehow appending the prerequisites to the end of the main
1147 makefile as has been traditionally done with other versions of
1148 @code{make}.  @xref{Automatic Prerequisites}.
1149 @cindex prerequisites, automatic generation
1150 @cindex automatic generation of prerequisites
1151 @cindex generating prerequisites automatically
1153 @cindex @code{-I}
1154 @cindex @code{--include-dir}
1155 @cindex included makefiles, default directories
1156 @cindex default directories for included makefiles
1157 @findex /usr/gnu/include
1158 @findex /usr/local/include
1159 @findex /usr/include
1160 If the specified name does not start with a slash, and the file is not
1161 found in the current directory, several other directories are searched.
1162 First, any directories you have specified with the @samp{-I} or
1163 @samp{--include-dir} option are searched
1164 (@pxref{Options Summary, ,Summary of Options}).
1165 Then the following directories (if they exist)
1166 are searched, in this order:
1167 @file{@var{prefix}/include} (normally @file{/usr/local/include}
1168 @footnote{GNU Make compiled for MS-DOS and MS-Windows behaves as if
1169 @var{prefix} has been defined to be the root of the DJGPP tree
1170 hierarchy.})
1171 @file{/usr/gnu/include},
1172 @file{/usr/local/include}, @file{/usr/include}.
1174 If an included makefile cannot be found in any of these directories, a
1175 warning message is generated, but it is not an immediately fatal error;
1176 processing of the makefile containing the @code{include} continues.
1177 Once it has finished reading makefiles, @code{make} will try to remake
1178 any that are out of date or don't exist.
1179 @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
1180 Only after it has tried to find a way to remake a makefile and failed,
1181 will @code{make} diagnose the missing makefile as a fatal error.
1183 If you want @code{make} to simply ignore a makefile which does not exist
1184 or cannot be remade, with no error message, use the @w{@code{-include}}
1185 directive instead of @code{include}, like this:
1187 @example
1188 -include @var{filenames}@dots{}
1189 @end example
1191 This acts like @code{include} in every way except that there is no
1192 error (not even a warning) if any of the @var{filenames} (or any
1193 prerequisites of any of the @var{filenames}) do not exist or cannot be
1194 remade.
1196 For compatibility with some other @code{make} implementations,
1197 @code{sinclude} is another name for @w{@code{-include}}.
1199 @node MAKEFILES Variable, Remaking Makefiles, Include, Makefiles
1200 @section The Variable @code{MAKEFILES}
1201 @cindex makefile, and @code{MAKEFILES} variable
1202 @cindex including (@code{MAKEFILES} variable)
1204 @vindex MAKEFILES
1205 If the environment variable @code{MAKEFILES} is defined, @code{make}
1206 considers its value as a list of names (separated by whitespace) of
1207 additional makefiles to be read before the others.  This works much
1208 like the @code{include} directive: various directories are searched
1209 for those files (@pxref{Include, ,Including Other Makefiles}).  In
1210 addition, the default goal is never taken from one of these makefiles
1211 (or any makefile included by them) and it is not an error if the files
1212 listed in @code{MAKEFILES} are not found.@refill
1214 @cindex recursion, and @code{MAKEFILES} variable
1215 The main use of @code{MAKEFILES} is in communication between recursive
1216 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1217 @code{make}}).  It usually is not desirable to set the environment
1218 variable before a top-level invocation of @code{make}, because it is
1219 usually better not to mess with a makefile from outside.  However, if
1220 you are running @code{make} without a specific makefile, a makefile in
1221 @code{MAKEFILES} can do useful things to help the built-in implicit
1222 rules work better, such as defining search paths (@pxref{Directory Search}).
1224 Some users are tempted to set @code{MAKEFILES} in the environment
1225 automatically on login, and program makefiles to expect this to be done.
1226 This is a very bad idea, because such makefiles will fail to work if run by
1227 anyone else.  It is much better to write explicit @code{include} directives
1228 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1230 @node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
1231 @section How Makefiles Are Remade
1233 @cindex updating makefiles
1234 @cindex remaking makefiles
1235 @cindex makefile, remaking of
1236 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1237 files.  If a makefile can be remade from other files, you probably want
1238 @code{make} to get an up-to-date version of the makefile to read in.
1240 To this end, after reading in all makefiles, @code{make} will consider
1241 each as a goal target and attempt to update it.  If a makefile has a
1242 rule which says how to update it (found either in that very makefile or
1243 in another one) or if an implicit rule applies to it (@pxref{Implicit
1244 Rules, ,Using Implicit Rules}), it will be updated if necessary.  After
1245 all makefiles have been checked, if any have actually been changed,
1246 @code{make} starts with a clean slate and reads all the makefiles over
1247 again.  (It will also attempt to update each of them over again, but
1248 normally this will not change them again, since they are already up to
1249 date.)@refill
1251 If you know that one or more of your makefiles cannot be remade and
1252 you want to keep @code{make} from performing an implicit rule search
1253 on them, perhaps for efficiency reasons, you can use any normal method
1254 of preventing implicit rule look-up to do so.  For example, you can
1255 write an explicit rule with the makefile as the target, and an empty
1256 recipe (@pxref{Empty Recipes, ,Using Empty Recipes}).
1258 If the makefiles specify a double-colon rule to remake a file with
1259 a recipe but no prerequisites, that file will always be remade
1260 (@pxref{Double-Colon}).  In the case of makefiles, a makefile that has a
1261 double-colon rule with a recipe but no prerequisites will be remade every
1262 time @code{make} is run, and then again after @code{make} starts over
1263 and reads the makefiles in again.  This would cause an infinite loop:
1264 @code{make} would constantly remake the makefile, and never do anything
1265 else.  So, to avoid this, @code{make} will @strong{not} attempt to
1266 remake makefiles which are specified as targets of a double-colon rule
1267 with a recipe but no prerequisites.@refill
1269 If you do not specify any makefiles to be read with @samp{-f} or
1270 @samp{--file} options, @code{make} will try the default makefile names;
1271 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1272 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1273 @code{make} is not certain that these makefiles should exist.  However,
1274 if a default makefile does not exist but can be created by running
1275 @code{make} rules, you probably want the rules to be run so that the
1276 makefile can be used.
1278 Therefore, if none of the default makefiles exists, @code{make} will try
1279 to make each of them in the same order in which they are searched for
1280 (@pxref{Makefile Names, ,What Name to Give Your Makefile})
1281 until it succeeds in making one, or it runs out of names to try.  Note
1282 that it is not an error if @code{make} cannot find or make any makefile;
1283 a makefile is not always necessary.@refill
1285 When you use the @samp{-t} or @samp{--touch} option
1286 (@pxref{Instead of Execution, ,Instead of Executing Recipes}),
1287 you would not want to use an out-of-date makefile to decide which
1288 targets to touch.  So the @samp{-t} option has no effect on updating
1289 makefiles; they are really updated even if @samp{-t} is specified.
1290 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1291 @samp{--just-print}) do not prevent updating of makefiles, because an
1292 out-of-date makefile would result in the wrong output for other targets.
1293 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1294 and then print the recipe to update @file{foo} and its prerequisites
1295 without running it.  The recipe printed for @file{foo} will be the one
1296 specified in the updated contents of @file{mfile}.
1298 However, on occasion you might actually wish to prevent updating of even
1299 the makefiles.  You can do this by specifying the makefiles as goals in
1300 the command line as well as specifying them as makefiles.  When the
1301 makefile name is specified explicitly as a goal, the options @samp{-t}
1302 and so on do apply to them.
1304 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1305 @file{mfile}, print the recipe needed to update it without actually
1306 running it, and then print the recipe needed to update @file{foo}
1307 without running that.  The recipe for @file{foo} will be the one
1308 specified by the existing contents of @file{mfile}.
1310 @node Overriding Makefiles, Reading Makefiles, Remaking Makefiles, Makefiles
1311 @section Overriding Part of Another Makefile
1313 @cindex overriding makefiles
1314 @cindex makefile, overriding
1315 Sometimes it is useful to have a makefile that is mostly just like
1316 another makefile.  You can often use the @samp{include} directive to
1317 include one in the other, and add more targets or variable definitions.
1318 However, it is invalid for two makefiles to give different recipes for
1319 the same target.  But there is another way.
1321 @cindex match-anything rule, used to override
1322 In the containing makefile (the one that wants to include the other),
1323 you can use a match-anything pattern rule to say that to remake any
1324 target that cannot be made from the information in the containing
1325 makefile, @code{make} should look in another makefile.
1326 @xref{Pattern Rules}, for more information on pattern rules.
1328 For example, if you have a makefile called @file{Makefile} that says how
1329 to make the target @samp{foo} (and other targets), you can write a
1330 makefile called @file{GNUmakefile} that contains:
1332 @example
1333 foo:
1334         frobnicate > foo
1336 %: force
1337         @@$(MAKE) -f Makefile $@@
1338 force: ;
1339 @end example
1341 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1342 read it, and see that to make @file{foo}, it needs to run the recipe
1343 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1344 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1345 recipe from the pattern rule: @samp{make -f Makefile bar}.  If
1346 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1347 will apply the rule.  And likewise for any other target that
1348 @file{GNUmakefile} does not say how to make.
1350 The way this works is that the pattern rule has a pattern of just
1351 @samp{%}, so it matches any target whatever.  The rule specifies a
1352 prerequisite @file{force}, to guarantee that the recipe will be run even
1353 if the target file already exists.  We give the @file{force} target an
1354 empty recipe to prevent @code{make} from searching for an implicit rule to
1355 build it---otherwise it would apply the same match-anything rule to
1356 @file{force} itself and create a prerequisite loop!
1358 @node Reading Makefiles,  Secondary Expansion, Overriding Makefiles, Makefiles
1359 @section How @code{make} Reads a Makefile
1360 @cindex reading makefiles
1361 @cindex makefile, parsing
1363 GNU @code{make} does its work in two distinct phases.  During the first
1364 phase it reads all the makefiles, included makefiles, etc. and
1365 internalizes all the variables and their values, implicit and explicit
1366 rules, and constructs a dependency graph of all the targets and their
1367 prerequisites.  During the second phase, @code{make} uses these internal
1368 structures to determine what targets will need to be rebuilt and to
1369 invoke the rules necessary to do so.
1371 It's important to understand this two-phase approach because it has a
1372 direct impact on how variable and function expansion happens; this is
1373 often a source of some confusion when writing makefiles.  Here we will
1374 present a summary of the phases in which expansion happens for different
1375 constructs within the makefile.  We say that expansion is
1376 @dfn{immediate} if it happens during the first phase: in this case
1377 @code{make} will expand any variables or functions in that section of a
1378 construct as the makefile is parsed.  We say that expansion is
1379 @dfn{deferred} if expansion is not performed immediately.  Expansion of
1380 a deferred construct is not performed until either the construct appears
1381 later in an immediate context, or until the second phase.
1383 You may not be familiar with some of these constructs yet.  You can
1384 reference this section as you become familiar with them, in later
1385 chapters.
1387 @subheading Variable Assignment
1388 @cindex +=, expansion
1389 @cindex =, expansion
1390 @cindex ?=, expansion
1391 @cindex +=, expansion
1392 @cindex !=, expansion
1393 @cindex define, expansion
1395 Variable definitions are parsed as follows:
1397 @example
1398 @var{immediate} = @var{deferred}
1399 @var{immediate} ?= @var{deferred}
1400 @var{immediate} := @var{immediate}
1401 @var{immediate} += @var{deferred} or @var{immediate}
1402 @var{immediate} != @var{immediate}
1404 define @var{immediate}
1405   @var{deferred}
1406 endef
1408 define @var{immediate} =
1409   @var{deferred}
1410 endef
1412 define @var{immediate} ?=
1413   @var{deferred}
1414 endef
1416 define @var{immediate} :=
1417   @var{immediate}
1418 endef
1420 define @var{immediate} +=
1421   @var{deferred} or @var{immediate}
1422 endef
1424 define @var{immediate} !=
1425   @var{immediate}
1426 endef
1427 @end example
1429 For the append operator, @samp{+=}, the right-hand side is considered
1430 immediate if the variable was previously set as a simple variable
1431 (@samp{:=}), and deferred otherwise.
1433 For the shell assignment operator, @samp{!=}, the right-hand side is
1434 evaluated immediately and handed to the shell.  The result is stored in the
1435 variable named on the left, and that variable becomes a simple variable
1436 (and will thus be re-evaluated on each reference).
1438 @subheading Conditional Directives
1439 @cindex ifdef, expansion
1440 @cindex ifeq, expansion
1441 @cindex ifndef, expansion
1442 @cindex ifneq, expansion
1444 Conditional directives are parsed immediately.  This means, for
1445 example, that automatic variables cannot be used in conditional
1446 directives, as automatic variables are not set until the recipe for
1447 that rule is invoked.  If you need to use automatic variables in a
1448 conditional directive you @emph{must} move the condition into the
1449 recipe and use shell conditional syntax instead.
1451 @subheading Rule Definition
1452 @cindex target, expansion
1453 @cindex prerequisite, expansion
1454 @cindex implicit rule, expansion
1455 @cindex pattern rule, expansion
1456 @cindex explicit rule, expansion
1458 A rule is always expanded the same way, regardless of the form:
1460 @example
1461 @var{immediate} : @var{immediate} ; @var{deferred}
1462         @var{deferred}
1463 @end example
1465 That is, the target and prerequisite sections are expanded immediately,
1466 and the recipe used to construct the target is always deferred.  This
1467 general rule is true for explicit rules, pattern rules, suffix rules,
1468 static pattern rules, and simple prerequisite definitions.
1470 @node Secondary Expansion, , Reading Makefiles, Makefiles
1471 @section Secondary Expansion
1472 @cindex secondary expansion
1473 @cindex expansion, secondary
1475 @findex .SECONDEXPANSION
1476 In the previous section we learned that GNU @code{make} works in two
1477 distinct phases: a read-in phase and a target-update phase
1478 (@pxref{Reading Makefiles, , How @code{make} Reads a Makefile}).  GNU
1479 make also has the ability to enable a @emph{second expansion} of the
1480 prerequisites (only) for some or all targets defined in the makefile.
1481 In order for this second expansion to occur, the special target
1482 @code{.SECONDEXPANSION} must be defined before the first prerequisite
1483 list that makes use of this feature.
1485 If that special target is defined then in between the two phases
1486 mentioned above, right at the end of the read-in phase, all the
1487 prerequisites of the targets defined after the special target are
1488 expanded a @emph{second time}.  In most circumstances this secondary
1489 expansion will have no effect, since all variable and function
1490 references will have been expanded during the initial parsing of the
1491 makefiles.  In order to take advantage of the secondary expansion
1492 phase of the parser, then, it's necessary to @emph{escape} the
1493 variable or function reference in the makefile.  In this case the
1494 first expansion merely un-escapes the reference but doesn't expand it,
1495 and expansion is left to the secondary expansion phase.  For example,
1496 consider this makefile:
1498 @example
1499 .SECONDEXPANSION:
1500 ONEVAR = onefile
1501 TWOVAR = twofile
1502 myfile: $(ONEVAR) $$(TWOVAR)
1503 @end example
1505 After the first expansion phase the prerequisites list of the
1506 @file{myfile} target will be @code{onefile} and @code{$(TWOVAR)}; the
1507 first (unescaped) variable reference to @var{ONEVAR} is expanded,
1508 while the second (escaped) variable reference is simply unescaped,
1509 without being recognized as a variable reference.  Now during the
1510 secondary expansion the first word is expanded again but since it
1511 contains no variable or function references it remains the value
1512 @file{onefile}, while the second word is now a normal reference to the
1513 variable @var{TWOVAR}, which is expanded to the value @file{twofile}.
1514 The final result is that there are two prerequisites, @file{onefile}
1515 and @file{twofile}.
1517 Obviously, this is not a very interesting case since the same result
1518 could more easily have been achieved simply by having both variables
1519 appear, unescaped, in the prerequisites list.  One difference becomes
1520 apparent if the variables are reset; consider this example:
1522 @example
1523 .SECONDEXPANSION:
1524 AVAR = top
1525 onefile: $(AVAR)
1526 twofile: $$(AVAR)
1527 AVAR = bottom
1528 @end example
1530 Here the prerequisite of @file{onefile} will be expanded immediately,
1531 and resolve to the value @file{top}, while the prerequisite of
1532 @file{twofile} will not be full expanded until the secondary expansion
1533 and yield a value of @file{bottom}.
1535 This is marginally more exciting, but the true power of this feature
1536 only becomes apparent when you discover that secondary expansions
1537 always take place within the scope of the automatic variables for that
1538 target.  This means that you can use variables such as @code{$@@},
1539 @code{$*}, etc. during the second expansion and they will have their
1540 expected values, just as in the recipe.  All you have to do is defer
1541 the expansion by escaping the @code{$}.  Also, secondary expansion
1542 occurs for both explicit and implicit (pattern) rules.  Knowing this,
1543 the possible uses for this feature increase dramatically.  For
1544 example:
1546 @example
1547 .SECONDEXPANSION:
1548 main_OBJS := main.o try.o test.o
1549 lib_OBJS := lib.o api.o
1551 main lib: $$($$@@_OBJS)
1552 @end example
1554 Here, after the initial expansion the prerequisites of both the
1555 @file{main} and @file{lib} targets will be @code{$($@@_OBJS)}.  During
1556 the secondary expansion, the @code{$@@} variable is set to the name of
1557 the target and so the expansion for the @file{main} target will yield
1558 @code{$(main_OBJS)}, or @code{main.o try.o test.o}, while the
1559 secondary expansion for the @file{lib} target will yield
1560 @code{$(lib_OBJS)}, or @code{lib.o api.o}.
1562 You can also mix in functions here, as long as they are properly escaped:
1564 @example
1565 main_SRCS := main.c try.c test.c
1566 lib_SRCS := lib.c api.c
1568 .SECONDEXPANSION:
1569 main lib: $$(patsubst %.c,%.o,$$($$@@_SRCS))
1570 @end example
1572 This version allows users to specify source files rather than object
1573 files, but gives the same resulting prerequisites list as the previous
1574 example.
1576 Evaluation of automatic variables during the secondary expansion
1577 phase, especially of the target name variable @code{$$@@}, behaves
1578 similarly to evaluation within recipes.  However, there are some
1579 subtle differences and ``corner cases'' which come into play for the
1580 different types of rule definitions that @code{make} understands.  The
1581 subtleties of using the different automatic variables are described
1582 below.
1584 @subheading Secondary Expansion of Explicit Rules
1585 @cindex secondary expansion and explicit rules
1586 @cindex explicit rules, secondary expansion of
1588 During the secondary expansion of explicit rules, @code{$$@@} and
1589 @code{$$%} evaluate, respectively, to the file name of the target and,
1590 when the target is an archive member, the target member name.  The
1591 @code{$$<} variable evaluates to the first prerequisite in the first
1592 rule for this target.  @code{$$^} and @code{$$+} evaluate to the list
1593 of all prerequisites of rules @emph{that have already appeared} for
1594 the same target (@code{$$+} with repetitions and @code{$$^}
1595 without).  The following example will help illustrate these behaviors:
1597 @example
1598 .SECONDEXPANSION:
1600 foo: foo.1 bar.1 $$< $$^ $$+    # line #1
1602 foo: foo.2 bar.2 $$< $$^ $$+    # line #2
1604 foo: foo.3 bar.3 $$< $$^ $$+    # line #3
1605 @end example
1607 In the first prerequisite list, all three variables (@code{$$<},
1608 @code{$$^}, and @code{$$+}) expand to the empty string.  In the
1609 second, they will have values @code{foo.1}, @code{foo.1 bar.1}, and
1610 @code{foo.1 bar.1} respectively.  In the third they will have values
1611 @code{foo.1}, @code{foo.1 bar.1 foo.2 bar.2}, and @code{foo.1 bar.1
1612 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1} respectively.
1614 Rules undergo secondary expansion in makefile order, except that
1615 the rule with the recipe is always evaluated last.
1617 The variables @code{$$?} and @code{$$*} are not available and expand
1618 to the empty string.
1620 @subheading Secondary Expansion of Static Pattern Rules
1621 @cindex secondary expansion and static pattern rules
1622 @cindex static pattern rules, secondary expansion of
1624 Rules for secondary expansion of static pattern rules are identical to
1625 those for explicit rules, above, with one exception: for static
1626 pattern rules the @code{$$*} variable is set to the pattern stem.  As
1627 with explicit rules, @code{$$?} is not available and expands to the
1628 empty string.
1630 @subheading Secondary Expansion of Implicit Rules
1631 @cindex secondary expansion and implicit rules
1632 @cindex implicit rules, secondary expansion of
1634 As @code{make} searches for an implicit rule, it substitutes the stem
1635 and then performs secondary expansion for every rule with a matching
1636 target pattern.  The value of the automatic variables is derived in
1637 the same fashion as for static pattern rules.  As an example:
1639 @example
1640 .SECONDEXPANSION:
1642 foo: bar
1644 foo foz: fo%: bo%
1646 %oo: $$< $$^ $$+ $$*
1647 @end example
1649 When the implicit rule is tried for target @file{foo}, @code{$$<}
1650 expands to @file{bar}, @code{$$^} expands to @file{bar boo},
1651 @code{$$+} also expands to @file{bar boo}, and @code{$$*} expands to
1652 @file{f}.
1654 Note that the directory prefix (D), as described in @ref{Implicit Rule
1655 Search, ,Implicit Rule Search Algorithm}, is appended (after
1656 expansion) to all the patterns in the prerequisites list.  As an
1657 example:@refill
1659 @example
1660 .SECONDEXPANSION:
1662 /tmp/foo.o:
1664 %.o: $$(addsuffix /%.c,foo bar) foo.h
1665         @@echo $^
1666 @end example
1668 The prerequisite list printed, after the secondary expansion and
1669 directory prefix reconstruction, will be @file{/tmp/foo/foo.c
1670 /tmp/bar/foo.c foo.h}.  If you are not interested in this
1671 reconstruction, you can use @code{$$*} instead of @code{%} in the
1672 prerequisites list.
1674 @node Rules, Recipes, Makefiles, Top
1675 @chapter Writing Rules
1676 @cindex writing rules
1677 @cindex rule, how to write
1678 @cindex target
1679 @cindex prerequisite
1681 A @dfn{rule} appears in the makefile and says when and how to remake
1682 certain files, called the rule's @dfn{targets} (most often only one per rule).
1683 It lists the other files that are the @dfn{prerequisites} of the target, and
1684 the @dfn{recipe} to use to create or update the target.
1686 @cindex default goal
1687 @cindex goal, default
1688 The order of rules is not significant, except for determining the
1689 @dfn{default goal}: the target for @code{make} to consider, if you do
1690 not otherwise specify one.  The default goal is the target of the first
1691 rule in the first makefile.  If the first rule has multiple targets,
1692 only the first target is taken as the default.  There are two
1693 exceptions: a target starting with a period is not a default unless it
1694 contains one or more slashes, @samp{/}, as well; and, a target that
1695 defines a pattern rule has no effect on the default goal.
1696 (@xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.)
1698 Therefore, we usually write the makefile so that the first rule is the
1699 one for compiling the entire program or all the programs described by
1700 the makefile (often with a target called @samp{all}).
1701 @xref{Goals, ,Arguments to Specify the Goals}.
1703 @menu
1704 * Rule Example::                An example explained.
1705 * Rule Syntax::                 General syntax explained.
1706 * Prerequisite Types::          There are two types of prerequisites.
1707 * Wildcards::                   Using wildcard characters such as `*'.
1708 * Directory Search::            Searching other directories for source files.
1709 * Phony Targets::               Using a target that is not a real file's name.
1710 * Force Targets::               You can use a target without a recipe
1711                                   or prerequisites to mark other targets
1712                                   as phony.
1713 * Empty Targets::               When only the date matters and the
1714                                   files are empty.
1715 * Special Targets::             Targets with special built-in meanings.
1716 * Multiple Targets::            When to make use of several targets in a rule.
1717 * Multiple Rules::              How to use several rules with the same target.
1718 * Static Pattern::              Static pattern rules apply to multiple targets
1719                                   and can vary the prerequisites according to
1720                                   the target name.
1721 * Double-Colon::                How to use a special kind of rule to allow
1722                                   several independent rules for one target.
1723 * Automatic Prerequisites::     How to automatically generate rules giving
1724                                   prerequisites from source files themselves.
1725 @end menu
1727 @ifnottex
1728 @node Rule Example, Rule Syntax, Rules, Rules
1729 @section Rule Example
1731 Here is an example of a rule:
1733 @example
1734 foo.o : foo.c defs.h       # module for twiddling the frobs
1735         cc -c -g foo.c
1736 @end example
1738 Its target is @file{foo.o} and its prerequisites are @file{foo.c} and
1739 @file{defs.h}.  It has one command in the recipe: @samp{cc -c -g foo.c}.
1740 The recipe starts with a tab to identify it as a recipe.
1742 This rule says two things:
1744 @itemize @bullet
1745 @item
1746 How to decide whether @file{foo.o} is out of date: it is out of date
1747 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1748 more recent than it.
1750 @item
1751 How to update the file @file{foo.o}: by running @code{cc} as stated.
1752 The recipe does not explicitly mention @file{defs.h}, but we presume
1753 that @file{foo.c} includes it, and that that is why @file{defs.h} was
1754 added to the prerequisites.
1755 @end itemize
1756 @end ifnottex
1758 @node Rule Syntax, Prerequisite Types, Rule Example, Rules
1759 @section Rule Syntax
1761 @cindex rule syntax
1762 @cindex syntax of rules
1763 In general, a rule looks like this:
1765 @example
1766 @var{targets} : @var{prerequisites}
1767         @var{recipe}
1768         @dots{}
1769 @end example
1771 @noindent
1772 or like this:
1774 @example
1775 @var{targets} : @var{prerequisites} ; @var{recipe}
1776         @var{recipe}
1777         @dots{}
1778 @end example
1780 @cindex targets
1781 @cindex rule targets
1782 The @var{targets} are file names, separated by spaces.  Wildcard
1783 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
1784 in File Names}) and a name of the form @file{@var{a}(@var{m})}
1785 represents member @var{m} in archive file @var{a}
1786 (@pxref{Archive Members, ,Archive Members as Targets}).
1787 Usually there is only one
1788 target per rule, but occasionally there is a reason to have more
1789 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).@refill
1791 @cindex recipes
1792 @cindex tab character (in commands)
1793 The @var{recipe} lines start with a tab character (or the first
1794 character in the value of the @code{.RECIPEPREFIX} variable;
1795 @pxref{Special Variables}).  The first recipe line may appear on the line
1796 after the prerequisites, with a tab character, or may appear on the
1797 same line, with a semicolon.  Either way, the effect is the same.
1798 There are other differences in the syntax of recipes.
1799 @xref{Recipes, ,Writing Recipes in Rules}.
1801 @cindex dollar sign (@code{$}), in rules
1802 @cindex @code{$}, in rules
1803 @cindex rules, and @code{$}
1804 Because dollar signs are used to start @code{make} variable
1805 references, if you really want a dollar sign in a target or
1806 prerequisite you must write two of them, @samp{$$} (@pxref{Using
1807 Variables, ,How to Use Variables}).  If you have enabled secondary
1808 expansion (@pxref{Secondary Expansion}) and you want a literal dollar
1809 sign in the prerequisites list, you must actually write @emph{four}
1810 dollar signs (@samp{$$$$}).
1812 You may split a long line by inserting a backslash followed by a
1813 newline, but this is not required, as @code{make} places no limit on
1814 the length of a line in a makefile.
1816 A rule tells @code{make} two things: when the targets are out of date,
1817 and how to update them when necessary.
1819 @cindex prerequisites
1820 @cindex rule prerequisites
1821 The criterion for being out of date is specified in terms of the
1822 @var{prerequisites}, which consist of file names separated by spaces.
1823 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
1824 A target is out of date if it does not exist or if it is older than any
1825 of the prerequisites (by comparison of last-modification times).  The
1826 idea is that the contents of the target file are computed based on
1827 information in the prerequisites, so if any of the prerequisites changes,
1828 the contents of the existing target file are no longer necessarily
1829 valid.
1831 How to update is specified by a @var{recipe}.  This is one or more
1832 lines to be executed by the shell (normally @samp{sh}), but with some
1833 extra features (@pxref{Recipes, ,Writing Recipes in Rules}).
1835 @node Prerequisite Types, Wildcards, Rule Syntax, Rules
1836 @comment  node-name,  next,  previous,  up
1837 @section Types of Prerequisites
1838 @cindex prerequisite types
1839 @cindex types of prerequisites
1841 @cindex prerequisites, normal
1842 @cindex normal prerequisites
1843 @cindex prerequisites, order-only
1844 @cindex order-only prerequisites
1845 There are actually two different types of prerequisites understood by
1846 GNU @code{make}: normal prerequisites such as described in the
1847 previous section, and @dfn{order-only} prerequisites.  A normal
1848 prerequisite makes two statements: first, it imposes an order in which
1849 recipes will be invoked: the recipes for all prerequisites of a target
1850 will be completed before the recipe for the target is run.  Second, it
1851 imposes a dependency relationship: if any prerequisite is newer than
1852 the target, then the target is considered out-of-date and must be
1853 rebuilt.
1855 Normally, this is exactly what you want: if a target's prerequisite is
1856 updated, then the target should also be updated.
1858 Occasionally, however, you have a situation where you want to impose a
1859 specific ordering on the rules to be invoked @emph{without} forcing
1860 the target to be updated if one of those rules is executed.  In that
1861 case, you want to define @dfn{order-only} prerequisites.  Order-only
1862 prerequisites can be specified by placing a pipe symbol (@code{|})
1863 in the prerequisites list: any prerequisites to the left of the pipe
1864 symbol are normal; any prerequisites to the right are order-only:
1866 @example
1867 @var{targets} : @var{normal-prerequisites} | @var{order-only-prerequisites}
1868 @end example
1870 The normal prerequisites section may of course be empty.  Also, you
1871 may still declare multiple lines of prerequisites for the same target:
1872 they are appended appropriately (normal prerequisites are appended to
1873 the list of normal prerequisites; order-only prerequisites are
1874 appended to the list of order-only prerequisites).  Note that if you
1875 declare the same file to be both a normal and an order-only
1876 prerequisite, the normal prerequisite takes precedence (since they
1877 have a strict superset of the behavior of an order-only prerequisite).
1879 Consider an example where your targets are to be placed in a separate
1880 directory, and that directory might not exist before @code{make} is
1881 run.  In this situation, you want the directory to be created before
1882 any targets are placed into it but, because the timestamps on
1883 directories change whenever a file is added, removed, or renamed, we
1884 certainly don't want to rebuild all the targets whenever the
1885 directory's timestamp changes.  One way to manage this is with
1886 order-only prerequisites: make the directory an order-only
1887 prerequisite on all the targets:
1889 @example
1890 OBJDIR := objdir
1891 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
1893 $(OBJDIR)/%.o : %.c
1894         $(COMPILE.c) $(OUTPUT_OPTION) $<
1896 all: $(OBJS)
1898 $(OBJS): | $(OBJDIR)
1900 $(OBJDIR):
1901         mkdir $(OBJDIR)
1902 @end example
1904 Now the rule to create the @file{objdir} directory will be run, if
1905 needed, before any @samp{.o} is built, but no @samp{.o} will be built
1906 because the @file{objdir} directory timestamp changed.
1908 @node Wildcards, Directory Search, Prerequisite Types, Rules
1909 @section Using Wildcard Characters in File Names
1910 @cindex wildcard
1911 @cindex file name with wildcards
1912 @cindex globbing (wildcards)
1914 @cindex @code{*} (wildcard character)
1915 @cindex @code{?} (wildcard character)
1916 @cindex @code{[@dots{}]} (wildcard characters)
1917 A single file name can specify many files using @dfn{wildcard characters}.
1918 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
1919 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
1920 specifies a list of all the files (in the working directory) whose names
1921 end in @samp{.c}.@refill
1923 @cindex @code{~} (tilde)
1924 @cindex tilde (@code{~})
1925 @cindex home directory
1926 The character @samp{~} at the beginning of a file name also has special
1927 significance.  If alone, or followed by a slash, it represents your home
1928 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
1929 If the @samp{~} is followed by a word, the string represents the home
1930 directory of the user named by that word.  For example @file{~john/bin}
1931 expands to @file{/home/john/bin}.  On systems which don't have a home
1932 directory for each user (such as MS-DOS or MS-Windows), this
1933 functionality can be simulated by setting the environment variable
1934 @var{HOME}.@refill
1936 Wildcard expansion is performed by @code{make} automatically in
1937 targets and in prerequisites.  In recipes, the shell is responsible
1938 for wildcard expansion.  In other contexts, wildcard expansion happens
1939 only if you request it explicitly with the @code{wildcard} function.
1941 The special significance of a wildcard character can be turned off by
1942 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
1943 specific file whose name consists of @samp{foo}, an asterisk, and
1944 @samp{bar}.@refill
1946 @menu
1947 * Wildcard Examples::           Several examples.
1948 * Wildcard Pitfall::            Problems to avoid.
1949 * Wildcard Function::           How to cause wildcard expansion where
1950                                   it does not normally take place.
1951 @end menu
1953 @node Wildcard Examples, Wildcard Pitfall, Wildcards, Wildcards
1954 @subsection Wildcard Examples
1956 Wildcards can be used in the recipe of a rule, where they are expanded
1957 by the shell.  For example, here is a rule to delete all the object files:
1959 @example
1960 @group
1961 clean:
1962         rm -f *.o
1963 @end group
1964 @end example
1965 @cindex @code{rm} (shell command)
1967 Wildcards are also useful in the prerequisites of a rule.  With the
1968 following rule in the makefile, @samp{make print} will print all the
1969 @samp{.c} files that have changed since the last time you printed them:
1971 @example
1972 print: *.c
1973         lpr -p $?
1974         touch print
1975 @end example
1977 @cindex @code{print} target
1978 @cindex @code{lpr} (shell command)
1979 @cindex @code{touch} (shell command)
1980 @noindent
1981 This rule uses @file{print} as an empty target file; see @ref{Empty
1982 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
1983 @samp{$?} is used to print only those files that have changed; see
1984 @ref{Automatic Variables}.)@refill
1986 Wildcard expansion does not happen when you define a variable.  Thus, if
1987 you write this:
1989 @example
1990 objects = *.o
1991 @end example
1993 @noindent
1994 then the value of the variable @code{objects} is the actual string
1995 @samp{*.o}.  However, if you use the value of @code{objects} in a
1996 target or prerequisite, wildcard expansion will take place there.  If
1997 you use the value of @code{objects} in a recipe, the shell may perform
1998 wildcard expansion when the recipe runs.  To set @code{objects} to the
1999 expansion, instead use:
2001 @example
2002 objects := $(wildcard *.o)
2003 @end example
2005 @noindent
2006 @xref{Wildcard Function}.
2008 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
2009 @subsection Pitfalls of Using Wildcards
2010 @cindex wildcard pitfalls
2011 @cindex pitfalls of wildcards
2012 @cindex mistakes with wildcards
2013 @cindex errors with wildcards
2014 @cindex problems with wildcards
2016 Now here is an example of a naive way of using wildcard expansion, that
2017 does not do what you would intend.  Suppose you would like to say that the
2018 executable file @file{foo} is made from all the object files in the
2019 directory, and you write this:
2021 @example
2022 objects = *.o
2024 foo : $(objects)
2025         cc -o foo $(CFLAGS) $(objects)
2026 @end example
2028 @noindent
2029 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
2030 expansion happens in the rule for @file{foo}, so that each @emph{existing}
2031 @samp{.o} file becomes a prerequisite of @file{foo} and will be recompiled if
2032 necessary.
2034 But what if you delete all the @samp{.o} files?  When a wildcard matches
2035 no files, it is left as it is, so then @file{foo} will depend on the
2036 oddly-named file @file{*.o}.  Since no such file is likely to exist,
2037 @code{make} will give you an error saying it cannot figure out how to
2038 make @file{*.o}.  This is not what you want!
2040 Actually it is possible to obtain the desired result with wildcard
2041 expansion, but you need more sophisticated techniques, including the
2042 @code{wildcard} function and string substitution.
2043 @ifnottex
2044 @xref{Wildcard Function, ,The Function @code{wildcard}}.
2045 @end ifnottex
2046 @iftex
2047 These are described in the following section.
2048 @end iftex
2050 @cindex wildcards and MS-DOS/MS-Windows backslashes
2051 @cindex backslashes in pathnames and wildcard expansion
2053 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes to
2054 separate directories in pathnames, like so:
2056 @example
2057   c:\foo\bar\baz.c
2058 @end example
2060 This is equivalent to the Unix-style @file{c:/foo/bar/baz.c} (the
2061 @file{c:} part is the so-called drive letter).  When @code{make} runs on
2062 these systems, it supports backslashes as well as the Unix-style forward
2063 slashes in pathnames.  However, this support does @emph{not} include the
2064 wildcard expansion, where backslash is a quote character.  Therefore,
2065 you @emph{must} use Unix-style slashes in these cases.
2068 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
2069 @subsection The Function @code{wildcard}
2070 @findex wildcard
2072 Wildcard expansion happens automatically in rules.  But wildcard expansion
2073 does not normally take place when a variable is set, or inside the
2074 arguments of a function.  If you want to do wildcard expansion in such
2075 places, you need to use the @code{wildcard} function, like this:
2077 @example
2078 $(wildcard @var{pattern}@dots{})
2079 @end example
2081 @noindent
2082 This string, used anywhere in a makefile, is replaced by a
2083 space-separated list of names of existing files that match one of the
2084 given file name patterns.  If no existing file name matches a pattern,
2085 then that pattern is omitted from the output of the @code{wildcard}
2086 function.  Note that this is different from how unmatched wildcards
2087 behave in rules, where they are used verbatim rather than ignored
2088 (@pxref{Wildcard Pitfall}).
2090 One use of the @code{wildcard} function is to get a list of all the C source
2091 files in a directory, like this:
2093 @example
2094 $(wildcard *.c)
2095 @end example
2097 We can change the list of C source files into a list of object files by
2098 replacing the @samp{.c} suffix with @samp{.o} in the result, like this:
2100 @example
2101 $(patsubst %.c,%.o,$(wildcard *.c))
2102 @end example
2104 @noindent
2105 (Here we have used another function, @code{patsubst}.
2106 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)@refill
2108 Thus, a makefile to compile all C source files in the directory and then
2109 link them together could be written as follows:
2111 @example
2112 objects := $(patsubst %.c,%.o,$(wildcard *.c))
2114 foo : $(objects)
2115         cc -o foo $(objects)
2116 @end example
2118 @noindent
2119 (This takes advantage of the implicit rule for compiling C programs, so
2120 there is no need to write explicit rules for compiling the files.
2121 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
2122 @samp{:=}, which is a variant of @samp{=}.)
2124 @node Directory Search, Phony Targets, Wildcards, Rules
2125 @section Searching Directories for Prerequisites
2126 @vindex VPATH
2127 @findex vpath
2128 @cindex vpath
2129 @cindex search path for prerequisites (@code{VPATH})
2130 @cindex directory search (@code{VPATH})
2132 For large systems, it is often desirable to put sources in a separate
2133 directory from the binaries.  The @dfn{directory search} features of
2134 @code{make} facilitate this by searching several directories
2135 automatically to find a prerequisite.  When you redistribute the files
2136 among directories, you do not need to change the individual rules,
2137 just the search paths.
2139 @menu
2140 * General Search::              Specifying a search path that applies
2141                                   to every prerequisite.
2142 * Selective Search::            Specifying a search path
2143                                   for a specified class of names.
2144 * Search Algorithm::            When and how search paths are applied.
2145 * Recipes/Search::              How to write recipes that work together
2146                                   with search paths.
2147 * Implicit/Search::             How search paths affect implicit rules.
2148 * Libraries/Search::            Directory search for link libraries.
2149 @end menu
2151 @node General Search, Selective Search, Directory Search, Directory Search
2152 @subsection @code{VPATH}: Search Path for All Prerequisites
2153 @vindex VPATH
2155 The value of the @code{make} variable @code{VPATH} specifies a list of
2156 directories that @code{make} should search.  Most often, the
2157 directories are expected to contain prerequisite files that are not in the
2158 current directory; however, @code{make} uses @code{VPATH} as a search
2159 list for both prerequisites and targets of rules.
2161 Thus, if a file that is listed as a target or prerequisite does not exist
2162 in the current directory, @code{make} searches the directories listed in
2163 @code{VPATH} for a file with that name.  If a file is found in one of
2164 them, that file may become the prerequisite (see below).  Rules may then
2165 specify the names of files in the prerequisite list as if they all
2166 existed in the current directory.  @xref{Recipes/Search, ,Writing Recipes with Directory Search}.
2168 In the @code{VPATH} variable, directory names are separated by colons or
2169 blanks.  The order in which directories are listed is the order followed
2170 by @code{make} in its search.  (On MS-DOS and MS-Windows, semi-colons
2171 are used as separators of directory names in @code{VPATH}, since the
2172 colon can be used in the pathname itself, after the drive letter.)
2174 For example,
2176 @example
2177 VPATH = src:../headers
2178 @end example
2180 @noindent
2181 specifies a path containing two directories, @file{src} and
2182 @file{../headers}, which @code{make} searches in that order.
2184 With this value of @code{VPATH}, the following rule,
2186 @example
2187 foo.o : foo.c
2188 @end example
2190 @noindent
2191 is interpreted as if it were written like this:
2193 @example
2194 foo.o : src/foo.c
2195 @end example
2197 @noindent
2198 assuming the file @file{foo.c} does not exist in the current directory but
2199 is found in the directory @file{src}.
2201 @node Selective Search, Search Algorithm, General Search, Directory Search
2202 @subsection The @code{vpath} Directive
2203 @findex vpath
2205 Similar to the @code{VPATH} variable, but more selective, is the
2206 @code{vpath} directive (note lower case), which allows you to specify a
2207 search path for a particular class of file names: those that match a
2208 particular pattern.  Thus you can supply certain search directories for
2209 one class of file names and other directories (or none) for other file
2210 names.
2212 There are three forms of the @code{vpath} directive:
2214 @table @code
2215 @item vpath @var{pattern} @var{directories}
2216 Specify the search path @var{directories} for file names that match
2217 @var{pattern}.
2219 The search path, @var{directories}, is a list of directories to be
2220 searched, separated by colons (semi-colons on MS-DOS and MS-Windows) or
2221 blanks, just like the search path used in the @code{VPATH} variable.
2223 @item vpath @var{pattern}
2224 Clear out the search path associated with @var{pattern}.
2226 @c Extra blank line makes sure this gets two lines.
2227 @item vpath
2229 Clear all search paths previously specified with @code{vpath} directives.
2230 @end table
2232 A @code{vpath} pattern is a string containing a @samp{%} character.  The
2233 string must match the file name of a prerequisite that is being searched
2234 for, the @samp{%} character matching any sequence of zero or more
2235 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
2236 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
2237 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
2238 prerequisite exactly, which is not useful very often.)
2240 @cindex @code{%}, quoting in @code{vpath}
2241 @cindex @code{%}, quoting with @code{\} (backslash)
2242 @cindex @code{\} (backslash), to quote @code{%}
2243 @cindex backslash (@code{\}), to quote @code{%}
2244 @cindex quoting @code{%}, in @code{vpath}
2245 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
2246 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
2247 quote @samp{%} characters can be quoted with more backslashes.
2248 Backslashes that quote @samp{%} characters or other backslashes are
2249 removed from the pattern before it is compared to file names.  Backslashes
2250 that are not in danger of quoting @samp{%} characters go unmolested.@refill
2252 When a prerequisite fails to exist in the current directory, if the
2253 @var{pattern} in a @code{vpath} directive matches the name of the
2254 prerequisite file, then the @var{directories} in that directive are searched
2255 just like (and before) the directories in the @code{VPATH} variable.
2257 For example,
2259 @example
2260 vpath %.h ../headers
2261 @end example
2263 @noindent
2264 tells @code{make} to look for any prerequisite whose name ends in @file{.h}
2265 in the directory @file{../headers} if the file is not found in the current
2266 directory.
2268 If several @code{vpath} patterns match the prerequisite file's name, then
2269 @code{make} processes each matching @code{vpath} directive one by one,
2270 searching all the directories mentioned in each directive.  @code{make}
2271 handles multiple @code{vpath} directives in the order in which they
2272 appear in the makefile; multiple directives with the same pattern are
2273 independent of each other.
2275 @need 750
2276 Thus,
2278 @example
2279 @group
2280 vpath %.c foo
2281 vpath %   blish
2282 vpath %.c bar
2283 @end group
2284 @end example
2286 @noindent
2287 will look for a file ending in @samp{.c} in @file{foo}, then
2288 @file{blish}, then @file{bar}, while
2290 @example
2291 @group
2292 vpath %.c foo:bar
2293 vpath %   blish
2294 @end group
2295 @end example
2297 @noindent
2298 will look for a file ending in @samp{.c} in @file{foo}, then
2299 @file{bar}, then @file{blish}.
2301 @node Search Algorithm, Recipes/Search, Selective Search, Directory Search
2302 @subsection How Directory Searches are Performed
2303 @cindex algorithm for directory search
2304 @cindex directory search algorithm
2306 When a prerequisite is found through directory search, regardless of type
2307 (general or selective), the pathname located may not be the one that
2308 @code{make} actually provides you in the prerequisite list.  Sometimes
2309 the path discovered through directory search is thrown away.
2311 The algorithm @code{make} uses to decide whether to keep or abandon a
2312 path found via directory search is as follows:
2314 @enumerate
2315 @item
2316 If a target file does not exist at the path specified in the makefile,
2317 directory search is performed.
2319 @item
2320 If the directory search is successful, that path is kept and this file
2321 is tentatively stored as the target.
2323 @item
2324 All prerequisites of this target are examined using this same method.
2326 @item
2327 After processing the prerequisites, the target may or may not need to be
2328 rebuilt:
2330 @enumerate a
2331 @item
2332 If the target does @emph{not} need to be rebuilt, the path to the file
2333 found during directory search is used for any prerequisite lists which
2334 contain this target.  In short, if @code{make} doesn't need to rebuild
2335 the target then you use the path found via directory search.
2337 @item
2338 If the target @emph{does} need to be rebuilt (is out-of-date), the
2339 pathname found during directory search is @emph{thrown away}, and the
2340 target is rebuilt using the file name specified in the makefile.  In
2341 short, if @code{make} must rebuild, then the target is rebuilt locally,
2342 not in the directory found via directory search.
2343 @end enumerate
2344 @end enumerate
2346 This algorithm may seem complex, but in practice it is quite often
2347 exactly what you want.
2349 @cindex traditional directory search (GPATH)
2350 @cindex directory search, traditional (GPATH)
2351 Other versions of @code{make} use a simpler algorithm: if the file does
2352 not exist, and it is found via directory search, then that pathname is
2353 always used whether or not the target needs to be built.  Thus, if the
2354 target is rebuilt it is created at the pathname discovered during
2355 directory search.
2357 @vindex GPATH
2358 If, in fact, this is the behavior you want for some or all of your
2359 directories, you can use the @code{GPATH} variable to indicate this to
2360 @code{make}.
2362 @code{GPATH} has the same syntax and format as @code{VPATH} (that is, a
2363 space- or colon-delimited list of pathnames).  If an out-of-date target
2364 is found by directory search in a directory that also appears in
2365 @code{GPATH}, then that pathname is not thrown away.  The target is
2366 rebuilt using the expanded path.
2368 @node Recipes/Search, Implicit/Search, Search Algorithm, Directory Search
2369 @subsection Writing Recipes with Directory Search
2370 @cindex recipes, and directory search
2371 @cindex directory search (@code{VPATH}), and recipes
2373 When a prerequisite is found in another directory through directory search,
2374 this cannot change the recipe of the rule; they will execute as written.
2375 Therefore, you must write the recipe with care so that it will look for
2376 the prerequisite in the directory where @code{make} finds it.
2378 This is done with the @dfn{automatic variables} such as @samp{$^}
2379 (@pxref{Automatic Variables}).
2380 For instance, the value of @samp{$^} is a
2381 list of all the prerequisites of the rule, including the names of
2382 the directories in which they were found, and the value of
2383 @samp{$@@} is the target.  Thus:@refill
2385 @example
2386 foo.o : foo.c
2387         cc -c $(CFLAGS) $^ -o $@@
2388 @end example
2390 @noindent
2391 (The variable @code{CFLAGS} exists so you can specify flags for C
2392 compilation by implicit rules; we use it here for consistency so it will
2393 affect all C compilations uniformly;
2394 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
2396 Often the prerequisites include header files as well, which you do not
2397 want to mention in the recipe.  The automatic variable @samp{$<} is
2398 just the first prerequisite:
2400 @example
2401 VPATH = src:../headers
2402 foo.o : foo.c defs.h hack.h
2403         cc -c $(CFLAGS) $< -o $@@
2404 @end example
2406 @node Implicit/Search, Libraries/Search, Recipes/Search, Directory Search
2407 @subsection Directory Search and Implicit Rules
2408 @cindex @code{VPATH}, and implicit rules
2409 @cindex directory search (@code{VPATH}), and implicit rules
2410 @cindex search path for prerequisites (@code{VPATH}), and implicit rules
2411 @cindex implicit rule, and directory search
2412 @cindex implicit rule, and @code{VPATH}
2413 @cindex rule, implicit, and directory search
2414 @cindex rule, implicit, and @code{VPATH}
2416 The search through the directories specified in @code{VPATH} or with
2417 @code{vpath} also happens during consideration of implicit rules
2418 (@pxref{Implicit Rules, ,Using Implicit Rules}).
2420 For example, when a file @file{foo.o} has no explicit rule, @code{make}
2421 considers implicit rules, such as the built-in rule to compile
2422 @file{foo.c} if that file exists.  If such a file is lacking in the
2423 current directory, the appropriate directories are searched for it.  If
2424 @file{foo.c} exists (or is mentioned in the makefile) in any of the
2425 directories, the implicit rule for C compilation is applied.
2427 The recipes of implicit rules normally use automatic variables as a
2428 matter of necessity; consequently they will use the file names found by
2429 directory search with no extra effort.
2431 @node Libraries/Search,  , Implicit/Search, Directory Search
2432 @subsection Directory Search for Link Libraries
2433 @cindex link libraries, and directory search
2434 @cindex libraries for linking, directory search
2435 @cindex directory search (@code{VPATH}), and link libraries
2436 @cindex @code{VPATH}, and link libraries
2437 @cindex search path for prerequisites (@code{VPATH}), and link libraries
2438 @cindex @code{-l} (library search)
2439 @cindex link libraries, patterns matching
2440 @cindex @code{.LIBPATTERNS}, and link libraries
2441 @vindex .LIBPATTERNS
2443 Directory search applies in a special way to libraries used with the
2444 linker.  This special feature comes into play when you write a prerequisite
2445 whose name is of the form @samp{-l@var{name}}.  (You can tell something
2446 strange is going on here because the prerequisite is normally the name of a
2447 file, and the @emph{file name} of a library generally looks like
2448 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)@refill
2450 When a prerequisite's name has the form @samp{-l@var{name}}, @code{make}
2451 handles it specially by searching for the file @file{lib@var{name}.so},
2452 and, if it is not found, for the file @file{lib@var{name}.a} in the current
2453 directory, in directories specified by matching @code{vpath}
2454 search paths and the @code{VPATH} search path, and then in the
2455 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
2456 (normally @file{/usr/local/lib}, but MS-DOS/MS-Windows versions of
2457 @code{make} behave as if @var{prefix} is defined to be the root of the
2458 DJGPP installation tree).
2460 For example, if there is a @file{/usr/lib/libcurses.a} library on your
2461 system (and no @file{/usr/lib/libcurses.so} file), then
2463 @example
2464 @group
2465 foo : foo.c -lcurses
2466         cc $^ -o $@@
2467 @end group
2468 @end example
2470 @noindent
2471 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
2472 be executed when @file{foo} is older than @file{foo.c} or than
2473 @file{/usr/lib/libcurses.a}.@refill
2475 Although the default set of files to be searched for is
2476 @file{lib@var{name}.so} and @file{lib@var{name}.a}, this is customizable
2477 via the @code{.LIBPATTERNS} variable.  Each word in the value of this
2478 variable is a pattern string.  When a prerequisite like
2479 @samp{-l@var{name}} is seen, @code{make} will replace the percent in
2480 each pattern in the list with @var{name} and perform the above directory
2481 searches using each library file name.
2483 The default value for @code{.LIBPATTERNS} is @samp{lib%.so lib%.a},
2484 which provides the default behavior described above.
2486 You can turn off link library expansion completely by setting this
2487 variable to an empty value.
2489 @node Phony Targets, Force Targets, Directory Search, Rules
2490 @section Phony Targets
2491 @cindex phony targets
2492 @cindex targets, phony
2493 @cindex targets without a file
2495 A phony target is one that is not really the name of a file; rather it
2496 is just a name for a recipe to be executed when you make an explicit
2497 request.  There are two reasons to use a phony target: to avoid a
2498 conflict with a file of the same name, and to improve performance.
2500 If you write a rule whose recipe will not create the target file, the
2501 recipe will be executed every time the target comes up for remaking.
2502 Here is an example:
2504 @example
2505 @group
2506 clean:
2507         rm *.o temp
2508 @end group
2509 @end example
2511 @noindent
2512 Because the @code{rm} command does not create a file named @file{clean},
2513 probably no such file will ever exist.  Therefore, the @code{rm} command
2514 will be executed every time you say @samp{make clean}.
2515 @cindex @code{rm} (shell command)
2517 @findex .PHONY
2518 The phony target will cease to work if anything ever does create a file
2519 named @file{clean} in this directory.  Since it has no prerequisites, the
2520 file @file{clean} would inevitably be considered up to date, and its
2521 recipe would not be executed.  To avoid this problem, you can explicitly
2522 declare the target to be phony, using the special target @code{.PHONY}
2523 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
2525 @example
2526 .PHONY : clean
2527 @end example
2529 @noindent
2530 Once this is done, @samp{make clean} will run the recipe regardless of
2531 whether there is a file named @file{clean}.
2533 Since it knows that phony targets do not name actual files that could be
2534 remade from other files, @code{make} skips the implicit rule search for
2535 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
2536 phony is good for performance, even if you are not worried about the
2537 actual file existing.
2539 Thus, you first write the line that states that @code{clean} is a
2540 phony target, then you write the rule, like this:
2542 @example
2543 @group
2544 .PHONY: clean
2545 clean:
2546         rm *.o temp
2547 @end group
2548 @end example
2550 Another example of the usefulness of phony targets is in conjunction
2551 with recursive invocations of @code{make} (for more information, see
2552 @ref{Recursion, ,Recursive Use of @code{make}}).  In this case the
2553 makefile will often contain a variable which lists a number of
2554 sub-directories to be built.  One way to handle this is with one rule
2555 whose recipe is a shell loop over the sub-directories, like this:
2557 @example
2558 @group
2559 SUBDIRS = foo bar baz
2561 subdirs:
2562         for dir in $(SUBDIRS); do \
2563           $(MAKE) -C $$dir; \
2564         done
2565 @end group
2566 @end example
2568 There are problems with this method, however.  First, any error
2569 detected in a sub-make is ignored by this rule, so it will continue
2570 to build the rest of the directories even when one fails.  This can be
2571 overcome by adding shell commands to note the error and exit, but then
2572 it will do so even if @code{make} is invoked with the @code{-k}
2573 option, which is unfortunate.  Second, and perhaps more importantly,
2574 you cannot take advantage of @code{make}'s ability to build targets in
2575 parallel (@pxref{Parallel, ,Parallel Execution}), since there is only
2576 one rule.
2578 By declaring the sub-directories as phony targets (you must do this as
2579 the sub-directory obviously always exists; otherwise it won't be built)
2580 you can remove these problems:
2582 @example
2583 @group
2584 SUBDIRS = foo bar baz
2586 .PHONY: subdirs $(SUBDIRS)
2588 subdirs: $(SUBDIRS)
2590 $(SUBDIRS):
2591         $(MAKE) -C $@@
2593 foo: baz
2594 @end group
2595 @end example
2597 Here we've also declared that the @file{foo} sub-directory cannot be
2598 built until after the @file{baz} sub-directory is complete; this kind of
2599 relationship declaration is particularly important when attempting
2600 parallel builds.
2602 A phony target should not be a prerequisite of a real target file; if it
2603 is, its recipe will be run every time @code{make} goes to update that
2604 file.  As long as a phony target is never a prerequisite of a real
2605 target, the phony target recipe will be executed only when the phony
2606 target is a specified goal (@pxref{Goals, ,Arguments to Specify the
2607 Goals}).
2609 Phony targets can have prerequisites.  When one directory contains multiple
2610 programs, it is most convenient to describe all of the programs in one
2611 makefile @file{./Makefile}.  Since the target remade by default will be the
2612 first one in the makefile, it is common to make this a phony target named
2613 @samp{all} and give it, as prerequisites, all the individual programs.  For
2614 example:
2616 @example
2617 all : prog1 prog2 prog3
2618 .PHONY : all
2620 prog1 : prog1.o utils.o
2621         cc -o prog1 prog1.o utils.o
2623 prog2 : prog2.o
2624         cc -o prog2 prog2.o
2626 prog3 : prog3.o sort.o utils.o
2627         cc -o prog3 prog3.o sort.o utils.o
2628 @end example
2630 @noindent
2631 Now you can say just @samp{make} to remake all three programs, or
2632 specify as arguments the ones to remake (as in @samp{make prog1
2633 prog3}).  Phoniness is not inherited: the prerequisites of a phony
2634 target are not themselves phony, unless explicitly declared to be so.
2636 When one phony target is a prerequisite of another, it serves as a subroutine
2637 of the other.  For example, here @samp{make cleanall} will delete the
2638 object files, the difference files, and the file @file{program}:
2640 @example
2641 .PHONY: cleanall cleanobj cleandiff
2643 cleanall : cleanobj cleandiff
2644         rm program
2646 cleanobj :
2647         rm *.o
2649 cleandiff :
2650         rm *.diff
2651 @end example
2653 @node Force Targets, Empty Targets, Phony Targets, Rules
2654 @section Rules without Recipes or Prerequisites
2655 @cindex force targets
2656 @cindex targets, force
2657 @cindex @code{FORCE}
2658 @cindex rule, no recipe or prerequisites
2660 If a rule has no prerequisites or recipe, and the target of the rule
2661 is a nonexistent file, then @code{make} imagines this target to have
2662 been updated whenever its rule is run.  This implies that all targets
2663 depending on this one will always have their recipe run.
2665 An example will illustrate this:
2667 @example
2668 @group
2669 clean: FORCE
2670         rm $(objects)
2671 FORCE:
2672 @end group
2673 @end example
2675 Here the target @samp{FORCE} satisfies the special conditions, so the
2676 target @file{clean} that depends on it is forced to run its recipe.
2677 There is nothing special about the name @samp{FORCE}, but that is one
2678 name commonly used this way.
2680 As you can see, using @samp{FORCE} this way has the same results as using
2681 @samp{.PHONY: clean}.
2683 Using @samp{.PHONY} is more explicit and more efficient.  However,
2684 other versions of @code{make} do not support @samp{.PHONY}; thus
2685 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2687 @node Empty Targets, Special Targets, Force Targets, Rules
2688 @section Empty Target Files to Record Events
2689 @cindex empty targets
2690 @cindex targets, empty
2691 @cindex recording events with empty targets
2693 The @dfn{empty target} is a variant of the phony target; it is used to hold
2694 recipes for an action that you request explicitly from time to time.
2695 Unlike a phony target, this target file can really exist; but the file's
2696 contents do not matter, and usually are empty.
2698 The purpose of the empty target file is to record, with its
2699 last-modification time, when the rule's recipe was last executed.  It
2700 does so because one of the commands in the recipe is a @code{touch}
2701 command to update the target file.
2703 The empty target file should have some prerequisites (otherwise it
2704 doesn't make sense).  When you ask to remake the empty target, the
2705 recipe is executed if any prerequisite is more recent than the target;
2706 in other words, if a prerequisite has changed since the last time you
2707 remade the target.  Here is an example:
2709 @example
2710 print: foo.c bar.c
2711         lpr -p $?
2712         touch print
2713 @end example
2714 @cindex @code{print} target
2715 @cindex @code{lpr} (shell command)
2716 @cindex @code{touch} (shell command)
2718 @noindent
2719 With this rule, @samp{make print} will execute the @code{lpr} command if
2720 either source file has changed since the last @samp{make print}.  The
2721 automatic variable @samp{$?} is used to print only those files that have
2722 changed (@pxref{Automatic Variables}).
2724 @node Special Targets, Multiple Targets, Empty Targets, Rules
2725 @section Special Built-in Target Names
2726 @cindex special targets
2727 @cindex built-in special targets
2728 @cindex targets, built-in special
2730 Certain names have special meanings if they appear as targets.
2732 @table @code
2733 @findex .PHONY
2734 @item .PHONY
2736 The prerequisites of the special target @code{.PHONY} are considered to
2737 be phony targets.  When it is time to consider such a target,
2738 @code{make} will run its recipe unconditionally, regardless of
2739 whether a file with that name exists or what its last-modification
2740 time is.  @xref{Phony Targets, ,Phony Targets}.
2742 @findex .SUFFIXES
2743 @item .SUFFIXES
2745 The prerequisites of the special target @code{.SUFFIXES} are the list
2746 of suffixes to be used in checking for suffix rules.
2747 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
2749 @findex .DEFAULT
2750 @item .DEFAULT
2752 The recipe specified for @code{.DEFAULT} is used for any target for
2753 which no rules are found (either explicit rules or implicit rules).
2754 @xref{Last Resort}.  If a @code{.DEFAULT} recipe is specified, every
2755 file mentioned as a prerequisite, but not as a target in a rule, will have
2756 that recipe executed on its behalf.  @xref{Implicit Rule Search,
2757 ,Implicit Rule Search Algorithm}.
2759 @findex .PRECIOUS
2760 @item .PRECIOUS
2761 @cindex precious targets
2762 @cindex preserving with @code{.PRECIOUS}
2764 The targets which @code{.PRECIOUS} depends on are given the following
2765 special treatment: if @code{make} is killed or interrupted during the
2766 execution of their recipes, the target is not deleted.
2767 @xref{Interrupts, ,Interrupting or Killing @code{make}}.  Also, if the
2768 target is an intermediate file, it will not be deleted after it is no
2769 longer needed, as is normally done.  @xref{Chained Rules, ,Chains of
2770 Implicit Rules}.  In this latter respect it overlaps with the
2771 @code{.SECONDARY} special target.
2773 You can also list the target pattern of an implicit rule (such as
2774 @samp{%.o}) as a prerequisite file of the special target @code{.PRECIOUS}
2775 to preserve intermediate files created by rules whose target patterns
2776 match that file's name.
2778 @findex .INTERMEDIATE
2779 @item .INTERMEDIATE
2780 @cindex intermediate targets, explicit
2782 The targets which @code{.INTERMEDIATE} depends on are treated as
2783 intermediate files.  @xref{Chained Rules, ,Chains of Implicit Rules}.
2784 @code{.INTERMEDIATE} with no prerequisites has no effect.
2786 @findex .SECONDARY
2787 @item .SECONDARY
2788 @cindex secondary targets
2789 @cindex preserving with @code{.SECONDARY}
2791 The targets which @code{.SECONDARY} depends on are treated as
2792 intermediate files, except that they are never automatically deleted.
2793 @xref{Chained Rules, ,Chains of Implicit Rules}.
2795 @code{.SECONDARY} with no prerequisites causes all targets to be treated
2796 as secondary (i.e., no target is removed because it is considered
2797 intermediate).
2799 @findex .SECONDEXPANSION
2800 @item .SECONDEXPANSION
2802 If @code{.SECONDEXPANSION} is mentioned as a target anywhere in the
2803 makefile, then all prerequisite lists defined @emph{after} it appears
2804 will be expanded a second time after all makefiles have been read in.
2805 @xref{Secondary Expansion, ,Secondary Expansion}.
2807 @findex .DELETE_ON_ERROR
2808 @item .DELETE_ON_ERROR
2809 @cindex removing targets on failure
2811 If @code{.DELETE_ON_ERROR} is mentioned as a target anywhere in the
2812 makefile, then @code{make} will delete the target of a rule if it has
2813 changed and its recipe exits with a nonzero exit status, just as it
2814 does when it receives a signal.  @xref{Errors, ,Errors in Recipes}.
2816 @findex .IGNORE
2817 @item .IGNORE
2819 If you specify prerequisites for @code{.IGNORE}, then @code{make} will
2820 ignore errors in execution of the recipe for those particular files.
2821 The recipe for @code{.IGNORE} (if any) is ignored.
2823 If mentioned as a target with no prerequisites, @code{.IGNORE} says to
2824 ignore errors in execution of recipes for all files.  This usage of
2825 @samp{.IGNORE} is supported only for historical compatibility.  Since
2826 this affects every recipe in the makefile, it is not very useful; we
2827 recommend you use the more selective ways to ignore errors in specific
2828 recipes.  @xref{Errors, ,Errors in Recipes}.
2830 @findex .LOW_RESOLUTION_TIME
2831 @item .LOW_RESOLUTION_TIME
2833 If you specify prerequisites for @code{.LOW_RESOLUTION_TIME},
2834 @command{make} assumes that these files are created by commands that
2835 generate low resolution time stamps.  The recipe for the
2836 @code{.LOW_RESOLUTION_TIME} target are ignored.
2838 The high resolution file time stamps of many modern file systems
2839 lessen the chance of @command{make} incorrectly concluding that a file
2840 is up to date.  Unfortunately, some hosts do not provide a way to set a
2841 high resolution file time stamp, so commands like @samp{cp -p} that
2842 explicitly set a file's time stamp must discard its sub-second part.
2843 If a file is created by such a command, you should list it as a
2844 prerequisite of @code{.LOW_RESOLUTION_TIME} so that @command{make}
2845 does not mistakenly conclude that the file is out of date.  For
2846 example:
2848 @example
2849 @group
2850 .LOW_RESOLUTION_TIME: dst
2851 dst: src
2852         cp -p src dst
2853 @end group
2854 @end example
2856 Since @samp{cp -p} discards the sub-second part of @file{src}'s time
2857 stamp, @file{dst} is typically slightly older than @file{src} even when
2858 it is up to date.  The @code{.LOW_RESOLUTION_TIME} line causes
2859 @command{make} to consider @file{dst} to be up to date if its time stamp
2860 is at the start of the same second that @file{src}'s time stamp is in.
2862 Due to a limitation of the archive format, archive member time stamps
2863 are always low resolution.  You need not list archive members as
2864 prerequisites of @code{.LOW_RESOLUTION_TIME}, as @command{make} does this
2865 automatically.
2867 @findex .SILENT
2868 @item .SILENT
2870 If you specify prerequisites for @code{.SILENT}, then @code{make} will
2871 not print the recipe used to remake those particular files before
2872 executing them.  The recipe for @code{.SILENT} is ignored.
2874 If mentioned as a target with no prerequisites, @code{.SILENT} says not
2875 to print any recipes before executing them.  This usage of
2876 @samp{.SILENT} is supported only for historical compatibility.  We
2877 recommend you use the more selective ways to silence specific recipes.
2878 @xref{Echoing, ,Recipe Echoing}.  If you want to silence all recipes
2879 for a particular run of @code{make}, use the @samp{-s} or
2880 @w{@samp{--silent}} option (@pxref{Options Summary}).
2882 @findex .EXPORT_ALL_VARIABLES
2883 @item .EXPORT_ALL_VARIABLES
2885 Simply by being mentioned as a target, this tells @code{make} to
2886 export all variables to child processes by default.
2887 @xref{Variables/Recursion, ,Communicating Variables to a
2888 Sub-@code{make}}.
2890 @findex .NOTPARALLEL
2891 @item .NOTPARALLEL
2892 @cindex parallel execution, overriding
2894 If @code{.NOTPARALLEL} is mentioned as a target, then this invocation
2895 of @code{make} will be run serially, even if the @samp{-j} option is
2896 given.  Any recursively invoked @code{make} command will still run
2897 recipes in parallel (unless its makefile also contains this target).
2898 Any prerequisites on this target are ignored.
2900 @findex .ONESHELL
2901 @item .ONESHELL
2902 @cindex recipe execution, single invocation
2904 If @code{.ONESHELL} is mentioned as a target, then when a target is
2905 built all lines of the recipe will be given to a single invocation of
2906 the shell rather than each line being invoked separately
2907 (@pxref{Execution, ,Recipe Execution}).
2909 @findex .POSIX
2910 @item .POSIX
2911 @cindex POSIX-conforming mode, setting
2913 If @code{.POSIX} is mentioned as a target, then the makefile will be
2914 parsed and run in POSIX-conforming mode.  This does @emph{not} mean
2915 that only POSIX-conforming makefiles will be accepted: all advanced
2916 GNU @code{make} features are still available.  Rather, this target
2917 causes @code{make} to behave as required by POSIX in those areas
2918 where @code{make}'s default behavior differs.
2920 In particular, if this target is mentioned then recipes will be
2921 invoked as if the shell had been passed the @code{-e} flag: the first
2922 failing command in a recipe will cause the recipe to fail immediately.
2923 @end table
2925 Any defined implicit rule suffix also counts as a special target if it
2926 appears as a target, and so does the concatenation of two suffixes, such
2927 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
2928 defining implicit rules (but a way still widely used).  In principle, any
2929 target name could be special in this way if you break it in two and add
2930 both pieces to the suffix list.  In practice, suffixes normally begin with
2931 @samp{.}, so these special target names also begin with @samp{.}.
2932 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
2934 @node Multiple Targets, Multiple Rules, Special Targets, Rules
2935 @section Multiple Targets in a Rule
2936 @cindex multiple targets
2937 @cindex several targets in a rule
2938 @cindex targets, multiple
2939 @cindex rule, with multiple targets
2941 A rule with multiple targets is equivalent to writing many rules, each with
2942 one target, and all identical aside from that.  The same recipe applies to
2943 all the targets, but its effect may vary because you can substitute the
2944 actual target name into the recipe using @samp{$@@}.  The rule contributes
2945 the same prerequisites to all the targets also.
2947 This is useful in two cases.
2949 @itemize @bullet
2950 @item
2951 You want just prerequisites, no recipe.  For example:
2953 @example
2954 kbd.o command.o files.o: command.h
2955 @end example
2957 @noindent
2958 gives an additional prerequisite to each of the three object files
2959 mentioned.
2961 @item
2962 Similar recipes work for all the targets.  The recipes do not need
2963 to be absolutely identical, since the automatic variable @samp{$@@}
2964 can be used to substitute the particular target to be remade into the
2965 commands (@pxref{Automatic Variables}).  For example:
2967 @example
2968 @group
2969 bigoutput littleoutput : text.g
2970         generate text.g -$(subst output,,$@@) > $@@
2971 @end group
2972 @end example
2973 @findex subst
2975 @noindent
2976 is equivalent to
2978 @example
2979 bigoutput : text.g
2980         generate text.g -big > bigoutput
2981 littleoutput : text.g
2982         generate text.g -little > littleoutput
2983 @end example
2985 @noindent
2986 Here we assume the hypothetical program @code{generate} makes two
2987 types of output, one if given @samp{-big} and one if given
2988 @samp{-little}.
2989 @xref{Text Functions, ,Functions for String Substitution and Analysis},
2990 for an explanation of the @code{subst} function.
2991 @end itemize
2993 Suppose you would like to vary the prerequisites according to the
2994 target, much as the variable @samp{$@@} allows you to vary the recipe.
2995 You cannot do this with multiple targets in an ordinary rule, but you
2996 can do it with a @dfn{static pattern rule}.  @xref{Static Pattern,
2997 ,Static Pattern Rules}.
2999 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
3000 @section Multiple Rules for One Target
3001 @cindex multiple rules for one target
3002 @cindex several rules for one target
3003 @cindex rule, multiple for one target
3004 @cindex target, multiple rules for one
3006 One file can be the target of several rules.  All the prerequisites
3007 mentioned in all the rules are merged into one list of prerequisites for
3008 the target.  If the target is older than any prerequisite from any rule,
3009 the recipe is executed.
3011 There can only be one recipe to be executed for a file.  If more than
3012 one rule gives a recipe for the same file, @code{make} uses the last
3013 one given and prints an error message.  (As a special case, if the
3014 file's name begins with a dot, no error message is printed.  This odd
3015 behavior is only for compatibility with other implementations of
3016 @code{make}@dots{} you should avoid using it).  Occasionally it is
3017 useful to have the same target invoke multiple recipes which are
3018 defined in different parts of your makefile; you can use
3019 @dfn{double-colon rules} (@pxref{Double-Colon}) for this.
3021 An extra rule with just prerequisites can be used to give a few extra
3022 prerequisites to many files at once.  For example, makefiles often
3023 have a variable, such as @code{objects}, containing a list of all the
3024 compiler output files in the system being made.  An easy way to say
3025 that all of them must be recompiled if @file{config.h} changes is to
3026 write the following:
3028 @example
3029 objects = foo.o bar.o
3030 foo.o : defs.h
3031 bar.o : defs.h test.h
3032 $(objects) : config.h
3033 @end example
3035 This could be inserted or taken out without changing the rules that really
3036 specify how to make the object files, making it a convenient form to use if
3037 you wish to add the additional prerequisite intermittently.
3039 Another wrinkle is that the additional prerequisites could be
3040 specified with a variable that you set with a command line argument to
3041 @code{make} (@pxref{Overriding, ,Overriding Variables}).  For example,
3043 @example
3044 @group
3045 extradeps=
3046 $(objects) : $(extradeps)
3047 @end group
3048 @end example
3050 @noindent
3051 means that the command @samp{make extradeps=foo.h} will consider
3052 @file{foo.h} as a prerequisite of each object file, but plain @samp{make}
3053 will not.
3055 If none of the explicit rules for a target has a recipe, then @code{make}
3056 searches for an applicable implicit rule to find one
3057 @pxref{Implicit Rules, ,Using Implicit Rules}).
3059 @node Static Pattern, Double-Colon, Multiple Rules, Rules
3060 @section Static Pattern Rules
3061 @cindex static pattern rule
3062 @cindex rule, static pattern
3063 @cindex pattern rules, static (not implicit)
3064 @cindex varying prerequisites
3065 @cindex prerequisites, varying (static pattern)
3067 @dfn{Static pattern rules} are rules which specify multiple targets and
3068 construct the prerequisite names for each target based on the target name.
3069 They are more general than ordinary rules with multiple targets because the
3070 targets do not have to have identical prerequisites.  Their prerequisites must
3071 be @emph{analogous}, but not necessarily @emph{identical}.
3073 @menu
3074 * Static Usage::                The syntax of static pattern rules.
3075 * Static versus Implicit::      When are they better than implicit rules?
3076 @end menu
3078 @node Static Usage, Static versus Implicit, Static Pattern, Static Pattern
3079 @subsection Syntax of Static Pattern Rules
3080 @cindex static pattern rule, syntax of
3081 @cindex pattern rules, static, syntax of
3083 Here is the syntax of a static pattern rule:
3085 @example
3086 @var{targets} @dots{}: @var{target-pattern}: @var{prereq-patterns} @dots{}
3087         @var{recipe}
3088         @dots{}
3089 @end example
3091 @noindent
3092 The @var{targets} list specifies the targets that the rule applies to.
3093 The targets can contain wildcard characters, just like the targets of
3094 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
3095 Names}).
3097 @cindex target pattern, static (not implicit)
3098 @cindex stem
3099 The @var{target-pattern} and @var{prereq-patterns} say how to compute the
3100 prerequisites of each target.  Each target is matched against the
3101 @var{target-pattern} to extract a part of the target name, called the
3102 @dfn{stem}.  This stem is substituted into each of the @var{prereq-patterns}
3103 to make the prerequisite names (one from each @var{prereq-pattern}).
3105 Each pattern normally contains the character @samp{%} just once.  When the
3106 @var{target-pattern} matches a target, the @samp{%} can match any part of
3107 the target name; this part is called the @dfn{stem}.  The rest of the
3108 pattern must match exactly.  For example, the target @file{foo.o} matches
3109 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
3110 @file{foo.c} and @file{foo.out} do not match that pattern.@refill
3112 @cindex prerequisite pattern, static (not implicit)
3113 The prerequisite names for each target are made by substituting the stem
3114 for the @samp{%} in each prerequisite pattern.  For example, if one
3115 prerequisite pattern is @file{%.c}, then substitution of the stem
3116 @samp{foo} gives the prerequisite name @file{foo.c}.  It is legitimate
3117 to write a prerequisite pattern that does not contain @samp{%}; then this
3118 prerequisite is the same for all targets.
3120 @cindex @code{%}, quoting in static pattern
3121 @cindex @code{%}, quoting with @code{\} (backslash)
3122 @cindex @code{\} (backslash), to quote @code{%}
3123 @cindex backslash (@code{\}), to quote @code{%}
3124 @cindex quoting @code{%}, in static pattern
3125 @samp{%} characters in pattern rules can be quoted with preceding
3126 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
3127 characters can be quoted with more backslashes.  Backslashes that quote
3128 @samp{%} characters or other backslashes are removed from the pattern
3129 before it is compared to file names or has a stem substituted into it.
3130 Backslashes that are not in danger of quoting @samp{%} characters go
3131 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
3132 @samp{the%weird\} preceding the operative @samp{%} character, and
3133 @samp{pattern\\} following it.  The final two backslashes are left alone
3134 because they cannot affect any @samp{%} character.@refill
3136 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
3137 from the corresponding @file{.c} file:
3139 @example
3140 @group
3141 objects = foo.o bar.o
3143 all: $(objects)
3145 $(objects): %.o: %.c
3146         $(CC) -c $(CFLAGS) $< -o $@@
3147 @end group
3148 @end example
3150 @noindent
3151 Here @samp{$<} is the automatic variable that holds the name of the
3152 prerequisite and @samp{$@@} is the automatic variable that holds the name
3153 of the target; see @ref{Automatic Variables}.
3155 Each target specified must match the target pattern; a warning is issued
3156 for each target that does not.  If you have a list of files, only some of
3157 which will match the pattern, you can use the @code{filter} function to
3158 remove non-matching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
3160 @example
3161 files = foo.elc bar.o lose.o
3163 $(filter %.o,$(files)): %.o: %.c
3164         $(CC) -c $(CFLAGS) $< -o $@@
3165 $(filter %.elc,$(files)): %.elc: %.el
3166         emacs -f batch-byte-compile $<
3167 @end example
3169 @noindent
3170 In this example the result of @samp{$(filter %.o,$(files))} is
3171 @file{bar.o lose.o}, and the first static pattern rule causes each of
3172 these object files to be updated by compiling the corresponding C source
3173 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
3174 @file{foo.elc}, so that file is made from @file{foo.el}.@refill
3176 Another example shows how to use @code{$*} in static pattern rules:
3177 @vindex $*@r{, and static pattern}
3179 @example
3180 @group
3181 bigoutput littleoutput : %output : text.g
3182         generate text.g -$* > $@@
3183 @end group
3184 @end example
3186 @noindent
3187 When the @code{generate} command is run, @code{$*} will expand to the
3188 stem, either @samp{big} or @samp{little}.
3190 @node Static versus Implicit,  , Static Usage, Static Pattern
3191 @subsection Static Pattern Rules versus Implicit Rules
3192 @cindex rule, static pattern versus implicit
3193 @cindex static pattern rule, versus implicit
3195 A static pattern rule has much in common with an implicit rule defined as a
3196 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
3197 Both have a pattern for the target and patterns for constructing the
3198 names of prerequisites.  The difference is in how @code{make} decides
3199 @emph{when} the rule applies.
3201 An implicit rule @emph{can} apply to any target that matches its pattern,
3202 but it @emph{does} apply only when the target has no recipe otherwise
3203 specified, and only when the prerequisites can be found.  If more than one
3204 implicit rule appears applicable, only one applies; the choice depends on
3205 the order of rules.
3207 By contrast, a static pattern rule applies to the precise list of targets
3208 that you specify in the rule.  It cannot apply to any other target and it
3209 invariably does apply to each of the targets specified.  If two conflicting
3210 rules apply, and both have recipes, that's an error.
3212 The static pattern rule can be better than an implicit rule for these
3213 reasons:
3215 @itemize @bullet
3216 @item
3217 You may wish to override the usual implicit rule for a few
3218 files whose names cannot be categorized syntactically but
3219 can be given in an explicit list.
3221 @item
3222 If you cannot be sure of the precise contents of the directories
3223 you are using, you may not be sure which other irrelevant files
3224 might lead @code{make} to use the wrong implicit rule.  The choice
3225 might depend on the order in which the implicit rule search is done.
3226 With static pattern rules, there is no uncertainty: each rule applies
3227 to precisely the targets specified.
3228 @end itemize
3230 @node Double-Colon, Automatic Prerequisites, Static Pattern, Rules
3231 @section Double-Colon Rules
3232 @cindex double-colon rules
3233 @cindex rule, double-colon (@code{::})
3234 @cindex multiple rules for one target (@code{::})
3235 @cindex @code{::} rules (double-colon)
3237 @dfn{Double-colon} rules are explicit rules written with @samp{::}
3238 instead of @samp{:} after the target names.  They are handled
3239 differently from ordinary rules when the same target appears in more
3240 than one rule.  Pattern rules with double-colons have an entirely
3241 different meaning (@pxref{Match-Anything Rules}).
3243 When a target appears in multiple rules, all the rules must be the same
3244 type: all ordinary, or all double-colon.  If they are double-colon, each
3245 of them is independent of the others.  Each double-colon rule's recipe
3246 is executed if the target is older than any prerequisites of that rule.
3247 If there are no prerequisites for that rule, its recipe is always
3248 executed (even if the target already exists).  This can result in
3249 executing none, any, or all of the double-colon rules.
3251 Double-colon rules with the same target are in fact completely separate
3252 from one another.  Each double-colon rule is processed individually, just
3253 as rules with different targets are processed.
3255 The double-colon rules for a target are executed in the order they appear
3256 in the makefile.  However, the cases where double-colon rules really make
3257 sense are those where the order of executing the recipes would not matter.
3259 Double-colon rules are somewhat obscure and not often very useful; they
3260 provide a mechanism for cases in which the method used to update a target
3261 differs depending on which prerequisite files caused the update, and such
3262 cases are rare.
3264 Each double-colon rule should specify a recipe; if it does not, an
3265 implicit rule will be used if one applies.
3266 @xref{Implicit Rules, ,Using Implicit Rules}.
3268 @node Automatic Prerequisites,  , Double-Colon, Rules
3269 @section Generating Prerequisites Automatically
3270 @cindex prerequisites, automatic generation
3271 @cindex automatic generation of prerequisites
3272 @cindex generating prerequisites automatically
3274 In the makefile for a program, many of the rules you need to write often
3275 say only that some object file depends on some header
3276 file.  For example, if @file{main.c} uses @file{defs.h} via an
3277 @code{#include}, you would write:
3279 @example
3280 main.o: defs.h
3281 @end example
3283 @noindent
3284 You need this rule so that @code{make} knows that it must remake
3285 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
3286 large program you would have to write dozens of such rules in your
3287 makefile.  And, you must always be very careful to update the makefile
3288 every time you add or remove an @code{#include}.
3289 @cindex @code{#include}
3291 @cindex @code{-M} (to compiler)
3292 To avoid this hassle, most modern C compilers can write these rules for
3293 you, by looking at the @code{#include} lines in the source files.
3294 Usually this is done with the @samp{-M} option to the compiler.
3295 For example, the command:
3297 @example
3298 cc -M main.c
3299 @end example
3301 @noindent
3302 generates the output:
3304 @example
3305 main.o : main.c defs.h
3306 @end example
3308 @noindent
3309 Thus you no longer have to write all those rules yourself.
3310 The compiler will do it for you.
3312 Note that such a rule constitutes mentioning @file{main.o} in a
3313 makefile, so it can never be considered an intermediate file by
3314 implicit rule search.  This means that @code{make} won't ever remove
3315 the file after using it; @pxref{Chained Rules, ,Chains of Implicit
3316 Rules}.
3318 @cindex @code{make depend}
3319 With old @code{make} programs, it was traditional practice to use this
3320 compiler feature to generate prerequisites on demand with a command like
3321 @samp{make depend}.  That command would create a file @file{depend}
3322 containing all the automatically-generated prerequisites; then the
3323 makefile could use @code{include} to read them in (@pxref{Include}).
3325 In GNU @code{make}, the feature of remaking makefiles makes this
3326 practice obsolete---you need never tell @code{make} explicitly to
3327 regenerate the prerequisites, because it always regenerates any makefile
3328 that is out of date.  @xref{Remaking Makefiles}.
3330 The practice we recommend for automatic prerequisite generation is to have
3331 one makefile corresponding to each source file.  For each source file
3332 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
3333 what files the object file @file{@var{name}.o} depends on.  That way
3334 only the source files that have changed need to be rescanned to produce
3335 the new prerequisites.
3337 Here is the pattern rule to generate a file of prerequisites (i.e., a makefile)
3338 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
3340 @smallexample
3341 @group
3342 %.d: %.c
3343         @@set -e; rm -f $@@; \
3344          $(CC) -M $(CPPFLAGS) $< > $@@.$$$$; \
3345          sed 's,\($*\)\.o[ :]*,\1.o $@@ : ,g' < $@@.$$$$ > $@@; \
3346          rm -f $@@.$$$$
3347 @end group
3348 @end smallexample
3350 @noindent
3351 @xref{Pattern Rules}, for information on defining pattern rules.  The
3352 @samp{-e} flag to the shell causes it to exit immediately if the
3353 @code{$(CC)} command (or any other command) fails (exits with a
3354 nonzero status).
3355 @cindex @code{-e} (shell flag)
3357 @cindex @code{-MM} (to GNU compiler)
3358 With the GNU C compiler, you may wish to use the @samp{-MM} flag instead
3359 of @samp{-M}.  This omits prerequisites on system header files.
3360 @xref{Preprocessor Options, , Options Controlling the Preprocessor,
3361 gcc.info, Using GNU CC}, for details.
3363 @cindex @code{sed} (shell command)
3364 The purpose of the @code{sed} command is to translate (for example):
3366 @example
3367 main.o : main.c defs.h
3368 @end example
3370 @noindent
3371 into:
3373 @example
3374 main.o main.d : main.c defs.h
3375 @end example
3377 @noindent
3378 @cindex @code{.d}
3379 This makes each @samp{.d} file depend on all the source and header files
3380 that the corresponding @samp{.o} file depends on.  @code{make} then
3381 knows it must regenerate the prerequisites whenever any of the source or
3382 header files changes.
3384 Once you've defined the rule to remake the @samp{.d} files,
3385 you then use the @code{include} directive to read them all in.
3386 @xref{Include}.  For example:
3388 @example
3389 @group
3390 sources = foo.c bar.c
3392 include $(sources:.c=.d)
3393 @end group
3394 @end example
3396 @noindent
3397 (This example uses a substitution variable reference to translate the
3398 list of source files @samp{foo.c bar.c} into a list of prerequisite
3399 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
3400 information on substitution references.)  Since the @samp{.d} files are
3401 makefiles like any others, @code{make} will remake them as necessary
3402 with no further work from you.  @xref{Remaking Makefiles}.
3404 Note that the @samp{.d} files contain target definitions; you should
3405 be sure to place the @code{include} directive @emph{after} the first,
3406 default goal in your makefiles or run the risk of having a random
3407 object file become the default goal.
3408 @xref{How Make Works}.
3410 @node Recipes, Using Variables, Rules, Top
3411 @chapter Writing Recipes in Rules
3412 @cindex recipes
3413 @cindex recipes, how to write
3414 @cindex writing recipes
3416 The recipe of a rule consists of one or more shell command lines to
3417 be executed, one at a time, in the order they appear.  Typically, the
3418 result of executing these commands is that the target of the rule is
3419 brought up to date.
3421 Users use many different shell programs, but recipes in makefiles are
3422 always interpreted by @file{/bin/sh} unless the makefile specifies
3423 otherwise.  @xref{Execution, ,Recipe Execution}.
3425 @menu
3426 * Recipe Syntax::               Recipe syntax features and pitfalls.
3427 * Echoing::                     How to control when recipes are echoed.
3428 * Execution::                   How recipes are executed.
3429 * Parallel::                    How recipes can be executed in parallel.
3430 * Errors::                      What happens after a recipe execution error.
3431 * Interrupts::                  What happens when a recipe is interrupted.
3432 * Recursion::                   Invoking @code{make} from makefiles.
3433 * Canned Recipes::              Defining canned recipes.
3434 * Empty Recipes::               Defining useful, do-nothing recipes.
3435 @end menu
3437 @node Recipe Syntax, Echoing, Recipes, Recipes
3438 @section Recipe Syntax
3439 @cindex recipe syntax
3440 @cindex syntax of recipe
3442 Makefiles have the unusual property that there are really two distinct
3443 syntaxes in one file.  Most of the makefile uses @code{make} syntax
3444 (@pxref{Makefiles, ,Writing Makefiles}).  However, recipes are meant
3445 to be interpreted by the shell and so they are written using shell
3446 syntax.  The @code{make} program does not try to understand shell
3447 syntax: it performs only a very few specific translations on the
3448 content of the recipe before handing it to the shell.
3450 Each line in the recipe must start with a tab (or the first character
3451 in the value of the @code{.RECIPEPREFIX} variable; @pxref{Special
3452 Variables}), except that the first recipe line may be attached to the
3453 target-and-prerequisites line with a semicolon in between.  @emph{Any}
3454 line in the makefile that begins with a tab and appears in a ``rule
3455 context'' (that is, after a rule has been started until another rule
3456 or variable definition) will be considered part of a recipe for that
3457 rule.  Blank lines and lines of just comments may appear among the
3458 recipe lines; they are ignored.
3460 Some consequences of these rules include:
3462 @itemize @bullet
3463 @item
3464 A blank line that begins with a tab is not blank: it's an empty
3465 recipe (@pxref{Empty Recipes}).
3467 @cindex comments, in recipes
3468 @cindex recipes, comments in
3469 @cindex @code{#} (comments), in recipes
3470 @item
3471 A comment in a recipe is not a @code{make} comment; it will be
3472 passed to the shell as-is.  Whether the shell treats it as a comment
3473 or not depends on your shell.
3475 @item
3476 A variable definition in a ``rule context'' which is indented by a tab
3477 as the first character on the line, will be considered part of a
3478 recipe, not a @code{make} variable definition, and passed to the
3479 shell.
3481 @item
3482 A conditional expression (@code{ifdef}, @code{ifeq},
3483 etc. @pxref{Conditional Syntax, ,Syntax of Conditionals}) in a ``rule
3484 context'' which is indented by a tab as the first character on the
3485 line, will be considered part of a recipe and be passed to the shell.
3487 @end itemize
3489 @menu
3490 * Splitting Lines::             Breaking long recipe lines for readability.
3491 * Variables in Recipes::        Using @code{make} variables in recipes.
3492 @end menu
3494 @node Splitting Lines, Variables in Recipes, Recipe Syntax, Recipe Syntax
3495 @subsection Splitting Recipe Lines
3496 @cindex recipes, splitting
3497 @cindex splitting recipes
3498 @cindex recipes, backslash (@code{\}) in
3499 @cindex recipes, quoting newlines in
3500 @cindex backslash (@code{\}), in recipes
3501 @cindex @code{\} (backslash), in recipes
3502 @cindex quoting newline, in recipes
3503 @cindex newline, quoting, in recipes
3505 One of the few ways in which @code{make} does interpret recipes is
3506 checking for a backslash just before the newline.  As in normal
3507 makefile syntax, a single logical recipe line can be split into
3508 multiple physical lines in the makefile by placing a backslash before
3509 each newline.  A sequence of lines like this is considered a single
3510 recipe line, and one instance of the shell will be invoked to run it.
3512 However, in contrast to how they are treated in other places in a
3513 makefile, backslash-newline pairs are @emph{not} removed from the
3514 recipe.  Both the backslash and the newline characters are preserved
3515 and passed to the shell.  How the backslash-newline is interpreted
3516 depends on your shell.  If the first character of the next line after
3517 the backslash-newline is the recipe prefix character (a tab by
3518 default; @pxref{Special Variables}), then that character (and only
3519 that character) is removed.  Whitespace is never added to the recipe.
3521 For example, the recipe for the all target in this makefile:
3523 @example
3524 @group
3525 all :
3526         @@echo no\
3527 space
3528         @@echo no\
3529         space
3530         @@echo one \
3531         space
3532         @@echo one\
3533          space
3534 @end group
3535 @end example
3537 @noindent
3538 consists of four separate shell commands where the output is:
3540 @example
3541 @group
3542 nospace
3543 nospace
3544 one space
3545 one space
3546 @end group
3547 @end example
3549 As a more complex example, this makefile:
3551 @example
3552 @group
3553 all : ; @@echo 'hello \
3554         world' ; echo "hello \
3555     world"
3556 @end group
3557 @end example
3559 @noindent
3560 will invoke one shell with a command of:
3562 @example
3563 @group
3564 echo 'hello \
3565 world' ; echo "hello \
3566     world"
3567 @end group
3568 @end example
3570 @noindent
3571 which, according to shell quoting rules, will yield the following output:
3573 @example
3574 @group
3575 hello \
3576 world
3577 hello     world
3578 @end group
3579 @end example
3581 @noindent
3582 Notice how the backslash/newline pair was removed inside the string
3583 quoted with double quotes (@code{"@dots{}"}), but not from the string
3584 quoted with single quotes (@code{'@dots{}'}).  This is the way the
3585 default shell (@file{/bin/sh}) handles backslash/newline pairs.  If
3586 you specify a different shell in your makefiles it may treat them
3587 differently.
3589 Sometimes you want to split a long line inside of single quotes, but
3590 you don't want the backslash-newline to appear in the quoted content.
3591 This is often the case when passing scripts to languages such as Perl,
3592 where extraneous backslashes inside the script can change its meaning
3593 or even be a syntax error.  One simple way of handling this is to
3594 place the quoted string, or even the entire command, into a
3595 @code{make} variable then use the variable in the recipe.  In this
3596 situation the newline quoting rules for makefiles will be used, and
3597 the backslash-newline will be removed.  If we rewrite our example
3598 above using this method:
3600 @example
3601 @group
3602 HELLO = 'hello \
3603 world'
3605 all : ; @@echo $(HELLO)
3606 @end group
3607 @end example
3609 @noindent
3610 we will get output like this:
3612 @example
3613 @group
3614 hello world
3615 @end group
3616 @end example
3618 If you like, you can also use target-specific variables
3619 (@pxref{Target-specific, ,Target-specific Variable Values}) to obtain
3620 a tighter correspondence between the variable and the recipe that
3621 uses it.
3623 @node Variables in Recipes,  , Splitting Lines, Recipe Syntax
3624 @subsection Using Variables in Recipes
3625 @cindex variable references in recipes
3626 @cindex recipes, using variables in
3628 The other way in which @code{make} processes recipes is by expanding
3629 any variable references in them (@pxref{Reference,Basics of Variable
3630 References}).  This occurs after make has finished reading all the
3631 makefiles and the target is determined to be out of date; so, the
3632 recipes for targets which are not rebuilt are never expanded.
3634 Variable and function references in recipes have identical syntax and
3635 semantics to references elsewhere in the makefile.  They also have the
3636 same quoting rules: if you want a dollar sign to appear in your
3637 recipe, you must double it (@samp{$$}).  For shells like the default
3638 shell, that use dollar signs to introduce variables, it's important to
3639 keep clear in your mind whether the variable you want to reference is
3640 a @code{make} variable (use a single dollar sign) or a shell variable
3641 (use two dollar signs).  For example:
3643 @example
3644 @group
3645 LIST = one two three
3646 all:
3647         for i in $(LIST); do \
3648             echo $$i; \
3649         done
3650 @end group
3651 @end example
3653 @noindent
3654 results in the following command being passed to the shell:
3656 @example
3657 @group
3658 for i in one two three; do \
3659     echo $i; \
3660 done
3661 @end group
3662 @end example
3664 @noindent
3665 which generates the expected result:
3667 @example
3668 @group
3671 three
3672 @end group
3673 @end example
3675 @node Echoing, Execution, Recipe Syntax, Recipes
3676 @section Recipe Echoing
3677 @cindex echoing of recipes
3678 @cindex silent operation
3679 @cindex @code{@@} (in recipes)
3680 @cindex recipes, echoing
3681 @cindex printing of recipes
3683 Normally @code{make} prints each line of the recipe before it is
3684 executed.  We call this @dfn{echoing} because it gives the appearance
3685 that you are typing the lines yourself.
3687 When a line starts with @samp{@@}, the echoing of that line is suppressed.
3688 The @samp{@@} is discarded before the line is passed to the shell.
3689 Typically you would use this for a command whose only effect is to print
3690 something, such as an @code{echo} command to indicate progress through
3691 the makefile:
3693 @example
3694 @@echo About to make distribution files
3695 @end example
3697 @cindex @code{-n}
3698 @cindex @code{--just-print}
3699 @cindex @code{--dry-run}
3700 @cindex @code{--recon}
3701 When @code{make} is given the flag @samp{-n} or @samp{--just-print} it
3702 only echoes most recipes, without executing them.  @xref{Options
3703 Summary, ,Summary of Options}.  In this case even the recipe lines
3704 starting with @samp{@@} are printed.  This flag is useful for finding
3705 out which recipes @code{make} thinks are necessary without actually
3706 doing them.
3708 @cindex @code{-s}
3709 @cindex @code{--silent}
3710 @cindex @code{--quiet}
3711 @findex .SILENT
3712 The @samp{-s} or @samp{--silent}
3713 flag to @code{make} prevents all echoing, as if all recipes
3714 started with @samp{@@}.  A rule in the makefile for the special target
3715 @code{.SILENT} without prerequisites has the same effect
3716 (@pxref{Special Targets, ,Special Built-in Target Names}).
3717 @code{.SILENT} is essentially obsolete since @samp{@@} is more flexible.@refill
3719 @node Execution, Parallel, Echoing, Recipes
3720 @section Recipe Execution
3721 @cindex recipe, execution
3722 @cindex execution, of recipes
3723 @vindex @code{SHELL} @r{(recipe execution)}
3725 When it is time to execute recipes to update a target, they are
3726 executed by invoking a new sub-shell for each line of the recipe,
3727 unless the @code{.ONESHELL} special target is in effect
3728 (@pxref{One Shell, ,Using One Shell})  (In practice, @code{make} may
3729 take shortcuts that do not affect the results.)
3731 @cindex @code{cd} (shell command)
3732 @cindex shell variables, setting in recipes
3733 @cindex recipes setting shell variables
3734 @strong{Please note:} this implies that setting shell variables and
3735 invoking shell commands such as @code{cd} that set a context local to
3736 each process will not affect the following lines in the recipe.@footnote{On
3737 MS-DOS, the value of current working directory is @strong{global}, so
3738 changing it @emph{will} affect the following recipe lines on those
3739 systems.}  If you want to use @code{cd} to affect the next statement,
3740 put both statements in a single recipe line.  Then @code{make} will
3741 invoke one shell to run the entire line, and the shell will execute
3742 the statements in sequence.  For example:
3744 @example
3745 foo : bar/lose
3746         cd $(@@D) && gobble $(@@F) > ../$@@
3747 @end example
3749 @noindent
3750 Here we use the shell AND operator (@code{&&}) so that if the
3751 @code{cd} command fails, the script will fail without trying to invoke
3752 the @code{gobble} command in the wrong directory, which could cause
3753 problems (in this case it would certainly cause @file{../foo} to be
3754 truncated, at least).
3756 @menu
3757 * One Shell::                   One shell for all lines in a recipe.
3758 * Choosing the Shell::          How @code{make} chooses the shell used
3759                                   to run recipes.
3760 @end menu
3762 @node One Shell, Choosing the Shell, Execution, Execution
3763 @subsection Using One Shell
3764 @cindex recipe lines, single shell
3765 @cindex @code{.ONESHELL}, use of
3766 @findex .ONESHELL
3768 Sometimes you would prefer that all the lines in the recipe be passed
3769 to a single invocation of the shell.  There are generally two
3770 situations where this is useful: first, it can improve performance in
3771 makefiles where recipes consist of many command lines, by avoiding
3772 extra processes.  Second, you might want newlines to be included in
3773 your recipe command (for example perhaps you are using a very
3774 different interpreter as your @code{SHELL}).  If the @code{.ONESHELL}
3775 special target appears anywhere in the makefile then @emph{all}
3776 recipe lines for each target will be provided to a single invocation
3777 of the shell.  Newlines between recipe lines will be preserved.  For
3778 example:
3780 @example
3781 .ONESHELL:
3782 foo : bar/lose
3783         cd $(@@D)
3784         gobble $(@@F) > ../$@@
3785 @end example
3787 @noindent
3788 would now work as expected even though the commands are on different
3789 recipe lines.
3791 If @code{.ONESHELL} is provided, then only the first line of the
3792 recipe will be checked for the special prefix characters (@samp{@@},
3793 @samp{-}, and @samp{+}).  Subsequent lines will include the special
3794 characters in the recipe line when the @code{SHELL} is invoked.  If
3795 you want your recipe to start with one of these special characters
3796 you'll need to arrange for them to not be the first characters on the
3797 first line, perhaps by adding a comment or similar.  For example, this
3798 would be a syntax error in Perl because the first @samp{@@} is removed
3799 by make:
3801 @example
3802 .ONESHELL:
3803 SHELL = /usr/bin/perl
3804 .SHELLFLAGS = -e
3805 show :
3806         @@f = qw(a b c);
3807         print "@@f\n";
3808 @end example
3810 @noindent
3811 However, either of these alternatives would work properly:
3813 @example
3814 .ONESHELL:
3815 SHELL = /usr/bin/perl
3816 .SHELLFLAGS = -e
3817 show :
3818         # Make sure "@@" is not the first character on the first line
3819         @@f = qw(a b c);
3820         print "@@f\n";
3821 @end example
3823 @noindent
3826 @example
3827 .ONESHELL:
3828 SHELL = /usr/bin/perl
3829 .SHELLFLAGS = -e
3830 show :
3831         my @@f = qw(a b c);
3832         print "@@f\n";
3833 @end example
3835 As a special feature, if @code{SHELL} is determined to be a
3836 POSIX-style shell, the special prefix characters in ``internal''
3837 recipe lines will @emph{removed} before the recipe is processed.  This
3838 feature is intended to allow existing makefiles to add the
3839 @code{.ONESHELL} special target and still run properly without
3840 extensive modifications.  Since the special prefix characters are not
3841 legal at the beginning of a line in a POSIX shell script this is not a
3842 loss in functionality.  For example, this works as expected:
3844 @example
3845 .ONESHELL:
3846 foo : bar/lose
3847         @@cd $(@@D)
3848         @@gobble $(@@F) > ../$@@
3849 @end example
3851 Even with this special feature, however, makefiles with
3852 @code{.ONESHELL} will behave differently in ways that could be
3853 noticeable.  For example, normally if any line in the recipe fails,
3854 that causes the rule to fail and no more recipe lines are processed.
3855 Under @code{.ONESHELL} a failure of any but the final recipe line will
3856 not be noticed by @code{make}.  You can modify @code{.SHELLFLAGS} to
3857 add the @code{-e} option to the shell which will cause any failure
3858 anywhere in the command line to cause the shell to fail, but this
3859 could itself cause your recipe to behave differently.  Ultimately you
3860 may need to harden your recipe lines to allow them to work with
3861 @code{.ONESHELL}.
3863 @node Choosing the Shell,  , One Shell, Execution
3864 @subsection Choosing the Shell
3865 @cindex shell, choosing the
3866 @cindex @code{SHELL}, value of
3867 @cindex @code{.SHELLFLAGS}, value of
3869 @vindex SHELL
3870 @vindex .SHELLFLAGS
3871 The program used as the shell is taken from the variable @code{SHELL}.
3872 If this variable is not set in your makefile, the program
3873 @file{/bin/sh} is used as the shell.  The argument(s) passed to the
3874 shell are taken from the variable @code{.SHELLFLAGS}.  The default
3875 value of @code{.SHELLFLAGS} is @code{-c} normally, or @code{-ec} in
3876 POSIX-conforming mode.
3878 @cindex environment, @code{SHELL} in
3879 Unlike most variables, the variable @code{SHELL} is never set from the
3880 environment.  This is because the @code{SHELL} environment variable is
3881 used to specify your personal choice of shell program for interactive
3882 use.  It would be very bad for personal choices like this to affect the
3883 functioning of makefiles.  @xref{Environment, ,Variables from the
3884 Environment}.
3886 Furthermore, when you do set @code{SHELL} in your makefile that value
3887 is @emph{not} exported in the environment to recipe lines that
3888 @code{make} invokes.  Instead, the value inherited from the user's
3889 environment, if any, is exported.  You can override this behavior by
3890 explicitly exporting @code{SHELL} (@pxref{Variables/Recursion,
3891 ,Communicating Variables to a Sub-@code{make}}), forcing it to be
3892 passed in the environment to recipe lines.
3894 @vindex @code{MAKESHELL} @r{(MS-DOS alternative to @code{SHELL})}
3895 However, on MS-DOS and MS-Windows the value of @code{SHELL} in the
3896 environment @strong{is} used, since on those systems most users do not
3897 set this variable, and therefore it is most likely set specifically to
3898 be used by @code{make}.  On MS-DOS, if the setting of @code{SHELL} is
3899 not suitable for @code{make}, you can set the variable
3900 @code{MAKESHELL} to the shell that @code{make} should use; if set it
3901 will be used as the shell instead of the value of @code{SHELL}.
3903 @subsubheading Choosing a Shell in DOS and Windows
3904 @cindex shell, in DOS and Windows
3905 @cindex DOS, choosing a shell in
3906 @cindex Windows, choosing a shell in
3908 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3909 other systems.
3911 @vindex COMSPEC
3912 On MS-DOS, if @code{SHELL} is not set, the value of the variable
3913 @code{COMSPEC} (which is always set) is used instead.
3915 @cindex @code{SHELL}, MS-DOS specifics
3916 The processing of lines that set the variable @code{SHELL} in Makefiles
3917 is different on MS-DOS.  The stock shell, @file{command.com}, is
3918 ridiculously limited in its functionality and many users of @code{make}
3919 tend to install a replacement shell.  Therefore, on MS-DOS, @code{make}
3920 examines the value of @code{SHELL}, and changes its behavior based on
3921 whether it points to a Unix-style or DOS-style shell.  This allows
3922 reasonable functionality even if @code{SHELL} points to
3923 @file{command.com}.
3925 If @code{SHELL} points to a Unix-style shell, @code{make} on MS-DOS
3926 additionally checks whether that shell can indeed be found; if not, it
3927 ignores the line that sets @code{SHELL}.  In MS-DOS, GNU @code{make}
3928 searches for the shell in the following places:
3930 @enumerate
3931 @item
3932 In the precise place pointed to by the value of @code{SHELL}.  For
3933 example, if the makefile specifies @samp{SHELL = /bin/sh}, @code{make}
3934 will look in the directory @file{/bin} on the current drive.
3936 @item
3937 In the current directory.
3939 @item
3940 In each of the directories in the @code{PATH} variable, in order.
3942 @end enumerate
3944 In every directory it examines, @code{make} will first look for the
3945 specific file (@file{sh} in the example above).  If this is not found,
3946 it will also look in that directory for that file with one of the known
3947 extensions which identify executable files.  For example @file{.exe},
3948 @file{.com}, @file{.bat}, @file{.btm}, @file{.sh}, and some others.
3950 If any of these attempts is successful, the value of @code{SHELL} will
3951 be set to the full pathname of the shell as found.  However, if none of
3952 these is found, the value of @code{SHELL} will not be changed, and thus
3953 the line that sets it will be effectively ignored.  This is so
3954 @code{make} will only support features specific to a Unix-style shell if
3955 such a shell is actually installed on the system where @code{make} runs.
3957 Note that this extended search for the shell is limited to the cases
3958 where @code{SHELL} is set from the Makefile; if it is set in the
3959 environment or command line, you are expected to set it to the full
3960 pathname of the shell, exactly as things are on Unix.
3962 The effect of the above DOS-specific processing is that a Makefile that
3963 contains @samp{SHELL = /bin/sh} (as many Unix makefiles do), will work
3964 on MS-DOS unaltered if you have e.g.@: @file{sh.exe} installed in some
3965 directory along your @code{PATH}.
3967 @vindex SHELL
3968 @vindex .SHELLFLAGS
3970 @node Parallel, Errors, Execution, Recipes
3971 @section Parallel Execution
3972 @cindex recipes, execution in parallel
3973 @cindex parallel execution
3974 @cindex execution, in parallel
3975 @cindex job slots
3976 @cindex @code{-j}
3977 @cindex @code{--jobs}
3979 GNU @code{make} knows how to execute several recipes at once.
3980 Normally, @code{make} will execute only one recipe at a time, waiting
3981 for it to finish before executing the next.  However, the @samp{-j} or
3982 @samp{--jobs} option tells @code{make} to execute many recipes
3983 simultaneously.  You can inhibit parallelism in a particular makefile
3984 with the @code{.NOTPARALLEL} pseudo-target (@pxref{Special
3985 Targets,Special Built-in Target Names}).@refill
3987 On MS-DOS, the @samp{-j} option has no effect, since that system doesn't
3988 support multi-processing.
3990 If the @samp{-j} option is followed by an integer, this is the number of
3991 recipes to execute at once; this is called the number of @dfn{job slots}.
3992 If there is nothing looking like an integer after the @samp{-j} option,
3993 there is no limit on the number of job slots.  The default number of job
3994 slots is one, which means serial execution (one thing at a time).
3996 One unpleasant consequence of running several recipes simultaneously is
3997 that output generated by the recipes appears whenever each recipe
3998 sends it, so messages from different recipes may be interspersed.
4000 Another problem is that two processes cannot both take input from the
4001 same device; so to make sure that only one recipe tries to take input
4002 from the terminal at once, @code{make} will invalidate the standard
4003 input streams of all but one running recipe.  This means that
4004 attempting to read from standard input will usually be a fatal error (a
4005 @samp{Broken pipe} signal) for most child processes if there are
4006 several.
4007 @cindex broken pipe
4008 @cindex standard input
4010 It is unpredictable which recipe will have a valid standard input stream
4011 (which will come from the terminal, or wherever you redirect the standard
4012 input of @code{make}).  The first recipe run will always get it first, and
4013 the first recipe started after that one finishes will get it next, and so
4016 We will change how this aspect of @code{make} works if we find a better
4017 alternative.  In the mean time, you should not rely on any recipe using
4018 standard input at all if you are using the parallel execution feature; but
4019 if you are not using this feature, then standard input works normally in
4020 all recipes.
4022 Finally, handling recursive @code{make} invocations raises issues.  For
4023 more information on this, see
4024 @ref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
4026 If a recipe fails (is killed by a signal or exits with a nonzero
4027 status), and errors are not ignored for that recipe
4028 (@pxref{Errors, ,Errors in Recipes}),
4029 the remaining recipe lines to remake the same target will not be run.
4030 If a recipe fails and the @samp{-k} or @samp{--keep-going}
4031 option was not given
4032 (@pxref{Options Summary, ,Summary of Options}),
4033 @code{make} aborts execution.  If make
4034 terminates for any reason (including a signal) with child processes
4035 running, it waits for them to finish before actually exiting.@refill
4037 @cindex load average
4038 @cindex limiting jobs based on load
4039 @cindex jobs, limiting based on load
4040 @cindex @code{-l} (load average)
4041 @cindex @code{--max-load}
4042 @cindex @code{--load-average}
4043 When the system is heavily loaded, you will probably want to run fewer jobs
4044 than when it is lightly loaded.  You can use the @samp{-l} option to tell
4045 @code{make} to limit the number of jobs to run at once, based on the load
4046 average.  The @samp{-l} or @samp{--max-load}
4047 option is followed by a floating-point number.  For
4048 example,
4050 @example
4051 -l 2.5
4052 @end example
4054 @noindent
4055 will not let @code{make} start more than one job if the load average is
4056 above 2.5.  The @samp{-l} option with no following number removes the
4057 load limit, if one was given with a previous @samp{-l} option.@refill
4059 More precisely, when @code{make} goes to start up a job, and it already has
4060 at least one job running, it checks the current load average; if it is not
4061 lower than the limit given with @samp{-l}, @code{make} waits until the load
4062 average goes below that limit, or until all the other jobs finish.
4064 By default, there is no load limit.
4066 @node Errors, Interrupts, Parallel, Recipes
4067 @section Errors in Recipes
4068 @cindex errors (in recipes)
4069 @cindex recipes, errors in
4070 @cindex exit status (errors)
4072 After each shell invocation returns, @code{make} looks at its exit
4073 status.  If the shell completed successfully (the exit status is
4074 zero), the next line in the recipe is executed in a new shell; after
4075 the last line is finished, the rule is finished.
4077 If there is an error (the exit status is nonzero), @code{make} gives up on
4078 the current rule, and perhaps on all rules.
4080 Sometimes the failure of a certain recipe line does not indicate a problem.
4081 For example, you may use the @code{mkdir} command to ensure that a
4082 directory exists.  If the directory already exists, @code{mkdir} will
4083 report an error, but you probably want @code{make} to continue regardless.
4085 @cindex @code{-} (in recipes)
4086 To ignore errors in a recipe line, write a @samp{-} at the beginning
4087 of the line's text (after the initial tab).  The @samp{-} is discarded
4088 before the line is passed to the shell for execution.
4090 For example,
4092 @example
4093 @group
4094 clean:
4095         -rm -f *.o
4096 @end group
4097 @end example
4098 @cindex @code{rm} (shell command)
4100 @noindent
4101 This causes @code{make} to continue even if @code{rm} is unable to
4102 remove a file.
4104 @cindex @code{-i}
4105 @cindex @code{--ignore-errors}
4106 @findex .IGNORE
4107 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
4108 flag, errors are ignored in all recipes of all rules.  A rule in the
4109 makefile for the special target @code{.IGNORE} has the same effect, if
4110 there are no prerequisites.  These ways of ignoring errors are obsolete
4111 because @samp{-} is more flexible.
4113 When errors are to be ignored, because of either a @samp{-} or the
4114 @samp{-i} flag, @code{make} treats an error return just like success,
4115 except that it prints out a message that tells you the status code
4116 the shell exited with, and says that the error has been ignored.
4118 When an error happens that @code{make} has not been told to ignore,
4119 it implies that the current target cannot be correctly remade, and neither
4120 can any other that depends on it either directly or indirectly.  No further
4121 recipes will be executed for these targets, since their preconditions
4122 have not been achieved.
4125 @cindex @code{-k}
4126 @cindex @code{--keep-going}
4127 Normally @code{make} gives up immediately in this circumstance, returning a
4128 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
4129 flag is specified, @code{make}
4130 continues to consider the other prerequisites of the pending targets,
4131 remaking them if necessary, before it gives up and returns nonzero status.
4132 For example, after an error in compiling one object file, @samp{make -k}
4133 will continue compiling other object files even though it already knows
4134 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
4136 The usual behavior assumes that your purpose is to get the specified
4137 targets up to date; once @code{make} learns that this is impossible, it
4138 might as well report the failure immediately.  The @samp{-k} option says
4139 that the real purpose is to test as many of the changes made in the
4140 program as possible, perhaps to find several independent problems so
4141 that you can correct them all before the next attempt to compile.  This
4142 is why Emacs' @code{compile} command passes the @samp{-k} flag by
4143 default.
4144 @cindex Emacs (@code{M-x compile})
4146 @findex .DELETE_ON_ERROR
4147 @cindex deletion of target files
4148 @cindex removal of target files
4149 @cindex target, deleting on error
4150 Usually when a recipe line fails, if it has changed the target file at all,
4151 the file is corrupted and cannot be used---or at least it is not
4152 completely updated.  Yet the file's time stamp says that it is now up to
4153 date, so the next time @code{make} runs, it will not try to update that
4154 file.  The situation is just the same as when the shell is killed by a
4155 signal; @pxref{Interrupts}.  So generally the right thing to do is to
4156 delete the target file if the recipe fails after beginning to change
4157 the file.  @code{make} will do this if @code{.DELETE_ON_ERROR} appears
4158 as a target.  This is almost always what you want @code{make} to do, but
4159 it is not historical practice; so for compatibility, you must explicitly
4160 request it.
4162 @node Interrupts, Recursion, Errors, Recipes
4163 @section Interrupting or Killing @code{make}
4164 @cindex interrupt
4165 @cindex signal
4166 @cindex deletion of target files
4167 @cindex removal of target files
4168 @cindex target, deleting on interrupt
4169 @cindex killing (interruption)
4171 If @code{make} gets a fatal signal while a shell is executing, it may
4172 delete the target file that the recipe was supposed to update.  This is
4173 done if the target file's last-modification time has changed since
4174 @code{make} first checked it.
4176 The purpose of deleting the target is to make sure that it is remade from
4177 scratch when @code{make} is next run.  Why is this?  Suppose you type
4178 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
4179 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
4180 in an incomplete file whose last-modification time is newer than the source
4181 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
4182 and deletes this incomplete file.  If @code{make} did not do this, the next
4183 invocation of @code{make} would think that @file{foo.o} did not require
4184 updating---resulting in a strange error message from the linker when it
4185 tries to link an object file half of which is missing.
4187 @findex .PRECIOUS
4188 You can prevent the deletion of a target file in this way by making the
4189 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
4190 @code{make} checks to see whether it appears on the prerequisites of
4191 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
4192 if a signal happens.  Some reasons why you might do this are that the
4193 target is updated in some atomic fashion, or exists only to record a
4194 modification-time (its contents do not matter), or must exist at all
4195 times to prevent other sorts of trouble.
4197 @node Recursion, Canned Recipes, Interrupts, Recipes
4198 @section Recursive Use of @code{make}
4199 @cindex recursion
4200 @cindex subdirectories, recursion for
4202 Recursive use of @code{make} means using @code{make} as a command in a
4203 makefile.  This technique is useful when you want separate makefiles for
4204 various subsystems that compose a larger system.  For example, suppose you
4205 have a sub-directory @file{subdir} which has its own makefile, and you would
4206 like the containing directory's makefile to run @code{make} on the
4207 sub-directory.  You can do it by writing this:
4209 @example
4210 subsystem:
4211         cd subdir && $(MAKE)
4212 @end example
4214 @noindent
4215 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
4217 @example
4218 subsystem:
4219         $(MAKE) -C subdir
4220 @end example
4221 @cindex @code{-C}
4222 @cindex @code{--directory}
4224 You can write recursive @code{make} commands just by copying this example,
4225 but there are many things to know about how they work and why, and about
4226 how the sub-@code{make} relates to the top-level @code{make}.  You may
4227 also find it useful to declare targets that invoke recursive
4228 @code{make} commands as @samp{.PHONY} (for more discussion on when
4229 this is useful, see @ref{Phony Targets}).
4231 @vindex @code{CURDIR}
4232 For your convenience, when GNU @code{make} starts (after it has
4233 processed any @code{-C} options) it sets the variable @code{CURDIR} to
4234 the pathname of the current working directory.  This value is never
4235 touched by @code{make} again: in particular note that if you include
4236 files from other directories the value of @code{CURDIR} does not
4237 change.  The value has the same precedence it would have if it were
4238 set in the makefile (by default, an environment variable @code{CURDIR}
4239 will not override this value).  Note that setting this variable has no
4240 impact on the operation of @code{make} (it does not cause @code{make}
4241 to change its working directory, for example).
4243 @menu
4244 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
4245 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
4246 * Options/Recursion::           How to communicate options to a sub-@code{make}.
4247 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
4248                                   helps debug use of recursive @code{make} commands.
4249 @end menu
4251 @node MAKE Variable, Variables/Recursion, Recursion, Recursion
4252 @subsection How the @code{MAKE} Variable Works
4253 @vindex MAKE
4254 @cindex recursion, and @code{MAKE} variable
4256 Recursive @code{make} commands should always use the variable @code{MAKE},
4257 not the explicit command name @samp{make}, as shown here:
4259 @example
4260 @group
4261 subsystem:
4262         cd subdir && $(MAKE)
4263 @end group
4264 @end example
4266 The value of this variable is the file name with which @code{make} was
4267 invoked.  If this file name was @file{/bin/make}, then the recipe executed
4268 is @samp{cd subdir && /bin/make}.  If you use a special version of
4269 @code{make} to run the top-level makefile, the same special version will be
4270 executed for recursive invocations.
4271 @cindex @code{cd} (shell command)
4273 @cindex +, and recipes
4274 As a special feature, using the variable @code{MAKE} in the recipe of
4275 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
4276 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
4277 Using the @code{MAKE} variable has the same effect as using a @samp{+}
4278 character at the beginning of the recipe line.  @xref{Instead of
4279 Execution, ,Instead of Executing the Recipes}.  This special feature
4280 is only enabled if the @code{MAKE} variable appears directly in the
4281 recipe: it does not apply if the @code{MAKE} variable is referenced
4282 through expansion of another variable.  In the latter case you must
4283 use the @samp{+} token to get these special effects.@refill
4285 Consider the command @samp{make -t} in the above example.  (The
4286 @samp{-t} option marks targets as up to date without actually running
4287 any recipes; see @ref{Instead of Execution}.)  Following the usual
4288 definition of @samp{-t}, a @samp{make -t} command in the example would
4289 create a file named @file{subsystem} and do nothing else.  What you
4290 really want it to do is run @samp{@w{cd subdir &&} @w{make -t}}; but
4291 that would require executing the recipe, and @samp{-t} says not to
4292 execute recipes.@refill
4293 @cindex @code{-t}, and recursion
4294 @cindex recursion, and @code{-t}
4295 @cindex @code{--touch}, and recursion
4297 The special feature makes this do what you want: whenever a recipe
4298 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
4299 @samp{-n} and @samp{-q} do not apply to that line.  Recipe lines
4300 containing @code{MAKE} are executed normally despite the presence of a
4301 flag that causes most recipes not to be run.  The usual
4302 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
4303 (@pxref{Options/Recursion, ,Communicating Options to a
4304 Sub-@code{make}}), so your request to touch the files, or print the
4305 recipes, is propagated to the subsystem.@refill
4307 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
4308 @subsection Communicating Variables to a Sub-@code{make}
4309 @cindex sub-@code{make}
4310 @cindex environment, and recursion
4311 @cindex exporting variables
4312 @cindex variables, environment
4313 @cindex variables, exporting
4314 @cindex recursion, and environment
4315 @cindex recursion, and variables
4317 Variable values of the top-level @code{make} can be passed to the
4318 sub-@code{make} through the environment by explicit request.  These
4319 variables are defined in the sub-@code{make} as defaults, but they do
4320 not override variables defined in the makefile used by
4321 the sub-@code{make} unless you use the @samp{-e} switch (@pxref{Options
4322 Summary, ,Summary of Options}).@refill
4324 To pass down, or @dfn{export}, a variable, @code{make} adds the
4325 variable and its value to the environment for running each line of the
4326 recipe.  The sub-@code{make}, in turn, uses the environment to
4327 initialize its table of variable values.  @xref{Environment,
4328 ,Variables from the Environment}.
4330 Except by explicit request, @code{make} exports a variable only if it
4331 is either defined in the environment initially or set on the command
4332 line, and if its name consists only of letters, numbers, and underscores.
4333 Some shells cannot cope with environment variable names consisting of
4334 characters other than letters, numbers, and underscores.
4336 @cindex SHELL, exported value
4337 The value of the @code{make} variable @code{SHELL} is not exported.
4338 Instead, the value of the @code{SHELL} variable from the invoking
4339 environment is passed to the sub-@code{make}.  You can force
4340 @code{make} to export its value for @code{SHELL} by using the
4341 @code{export} directive, described below.  @xref{Choosing the Shell}.
4343 The special variable @code{MAKEFLAGS} is always exported (unless you
4344 unexport it).  @code{MAKEFILES} is exported if you set it to anything.
4346 @code{make} automatically passes down variable values that were defined
4347 on the command line, by putting them in the @code{MAKEFLAGS} variable.
4348 @iftex
4349 See the next section.
4350 @end iftex
4351 @ifnottex
4352 @xref{Options/Recursion}.
4353 @end ifnottex
4355 Variables are @emph{not} normally passed down if they were created by
4356 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
4357 Implicit Rules}).  The sub-@code{make} will define these for
4358 itself.@refill
4360 @findex export
4361 If you want to export specific variables to a sub-@code{make}, use the
4362 @code{export} directive, like this:
4364 @example
4365 export @var{variable} @dots{}
4366 @end example
4368 @noindent
4369 @findex unexport
4370 If you want to @emph{prevent} a variable from being exported, use the
4371 @code{unexport} directive, like this:
4373 @example
4374 unexport @var{variable} @dots{}
4375 @end example
4377 @noindent
4378 In both of these forms, the arguments to @code{export} and
4379 @code{unexport} are expanded, and so could be variables or functions
4380 which expand to a (list of) variable names to be (un)exported.
4382 As a convenience, you can define a variable and export it at the same
4383 time by doing:
4385 @example
4386 export @var{variable} = value
4387 @end example
4389 @noindent
4390 has the same result as:
4392 @example
4393 @var{variable} = value
4394 export @var{variable}
4395 @end example
4397 @noindent
4400 @example
4401 export @var{variable} := value
4402 @end example
4404 @noindent
4405 has the same result as:
4407 @example
4408 @var{variable} := value
4409 export @var{variable}
4410 @end example
4412 Likewise,
4414 @example
4415 export @var{variable} += value
4416 @end example
4418 @noindent
4419 is just like:
4421 @example
4422 @var{variable} += value
4423 export @var{variable}
4424 @end example
4426 @noindent
4427 @xref{Appending, ,Appending More Text to Variables}.
4429 You may notice that the @code{export} and @code{unexport} directives
4430 work in @code{make} in the same way they work in the shell, @code{sh}.
4432 If you want all variables to be exported by default, you can use
4433 @code{export} by itself:
4435 @example
4436 export
4437 @end example
4439 @noindent
4440 This tells @code{make} that variables which are not explicitly mentioned
4441 in an @code{export} or @code{unexport} directive should be exported.
4442 Any variable given in an @code{unexport} directive will still @emph{not}
4443 be exported.  If you use @code{export} by itself to export variables by
4444 default, variables whose names contain characters other than
4445 alphanumerics and underscores will not be exported unless specifically
4446 mentioned in an @code{export} directive.@refill
4448 @findex .EXPORT_ALL_VARIABLES
4449 The behavior elicited by an @code{export} directive by itself was the
4450 default in older versions of GNU @code{make}.  If your makefiles depend
4451 on this behavior and you want to be compatible with old versions of
4452 @code{make}, you can write a rule for the special target
4453 @code{.EXPORT_ALL_VARIABLES} instead of using the @code{export} directive.
4454 This will be ignored by old @code{make}s, while the @code{export}
4455 directive will cause a syntax error.@refill
4456 @cindex compatibility in exporting
4458 Likewise, you can use @code{unexport} by itself to tell @code{make}
4459 @emph{not} to export variables by default.  Since this is the default
4460 behavior, you would only need to do this if @code{export} had been used
4461 by itself earlier (in an included makefile, perhaps).  You
4462 @strong{cannot} use @code{export} and @code{unexport} by themselves to
4463 have variables exported for some recipes and not for others.  The last
4464 @code{export} or @code{unexport} directive that appears by itself
4465 determines the behavior for the entire run of @code{make}.@refill
4467 @vindex MAKELEVEL
4468 @cindex recursion, level of
4469 As a special feature, the variable @code{MAKELEVEL} is changed when it
4470 is passed down from level to level.  This variable's value is a string
4471 which is the depth of the level as a decimal number.  The value is
4472 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
4473 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
4474 happens when @code{make} sets up the environment for a recipe.@refill
4476 The main use of @code{MAKELEVEL} is to test it in a conditional
4477 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
4478 way you can write a makefile that behaves one way if run recursively and
4479 another way if run directly by you.@refill
4481 @vindex MAKEFILES
4482 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
4483 commands to use additional makefiles.  The value of @code{MAKEFILES} is
4484 a whitespace-separated list of file names.  This variable, if defined in
4485 the outer-level makefile, is passed down through the environment; then
4486 it serves as a list of extra makefiles for the sub-@code{make} to read
4487 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
4488 Variable @code{MAKEFILES}}.@refill
4490 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
4491 @subsection Communicating Options to a Sub-@code{make}
4492 @cindex options, and recursion
4493 @cindex recursion, and options
4495 @vindex MAKEFLAGS
4496 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
4497 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
4498 set up automatically by @code{make} to contain the flag letters that
4499 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
4500 @code{MAKEFLAGS} gets the value @samp{ks}.@refill
4502 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
4503 in its environment.  In response, it takes the flags from that value and
4504 processes them as if they had been given as arguments.
4505 @xref{Options Summary, ,Summary of Options}.
4507 @cindex command line variable definitions, and recursion
4508 @cindex variables, command line, and recursion
4509 @cindex recursion, and command line variable definitions
4510 Likewise variables defined on the command line are passed to the
4511 sub-@code{make} through @code{MAKEFLAGS}.  Words in the value of
4512 @code{MAKEFLAGS} that contain @samp{=}, @code{make} treats as variable
4513 definitions just as if they appeared on the command line.
4514 @xref{Overriding, ,Overriding Variables}.
4516 @cindex @code{-C}, and recursion
4517 @cindex @code{-f}, and recursion
4518 @cindex @code{-o}, and recursion
4519 @cindex @code{-W}, and recursion
4520 @cindex @code{--directory}, and recursion
4521 @cindex @code{--file}, and recursion
4522 @cindex @code{--old-file}, and recursion
4523 @cindex @code{--assume-old}, and recursion
4524 @cindex @code{--assume-new}, and recursion
4525 @cindex @code{--new-file}, and recursion
4526 @cindex recursion, and @code{-C}
4527 @cindex recursion, and @code{-f}
4528 @cindex recursion, and @code{-o}
4529 @cindex recursion, and @code{-W}
4530 The options @samp{-C}, @samp{-f}, @samp{-o}, and @samp{-W} are not put
4531 into @code{MAKEFLAGS}; these options are not passed down.@refill
4533 @cindex @code{-j}, and recursion
4534 @cindex @code{--jobs}, and recursion
4535 @cindex recursion, and @code{-j}
4536 @cindex job slots, and recursion
4537 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
4538 If you set it to some numeric value @samp{N} and your operating system
4539 supports it (most any UNIX system will; others typically won't), the
4540 parent @code{make} and all the sub-@code{make}s will communicate to
4541 ensure that there are only @samp{N} jobs running at the same time
4542 between them all.  Note that any job that is marked recursive
4543 (@pxref{Instead of Execution, ,Instead of Executing Recipes})
4544 doesn't count against the total jobs (otherwise we could get @samp{N}
4545 sub-@code{make}s running and have no slots left over for any real work!)
4547 If your operating system doesn't support the above communication, then
4548 @samp{-j 1} is always put into @code{MAKEFLAGS} instead of the value you
4549 specified.  This is because if the @w{@samp{-j}} option were passed down
4550 to sub-@code{make}s, you would get many more jobs running in parallel
4551 than you asked for.  If you give @samp{-j} with no numeric argument,
4552 meaning to run as many jobs as possible in parallel, this is passed
4553 down, since multiple infinities are no more than one.@refill
4555 If you do not want to pass the other flags down, you must change the
4556 value of @code{MAKEFLAGS}, like this:
4558 @example
4559 subsystem:
4560         cd subdir && $(MAKE) MAKEFLAGS=
4561 @end example
4563 @vindex MAKEOVERRIDES
4564 The command line variable definitions really appear in the variable
4565 @code{MAKEOVERRIDES}, and @code{MAKEFLAGS} contains a reference to this
4566 variable.  If you do want to pass flags down normally, but don't want to
4567 pass down the command line variable definitions, you can reset
4568 @code{MAKEOVERRIDES} to empty, like this:
4570 @example
4571 MAKEOVERRIDES =
4572 @end example
4574 @noindent
4575 @cindex Arg list too long
4576 @cindex E2BIG
4577 This is not usually useful to do.  However, some systems have a small
4578 fixed limit on the size of the environment, and putting so much
4579 information into the value of @code{MAKEFLAGS} can exceed it.  If you
4580 see the error message @samp{Arg list too long}, this may be the problem.
4581 @findex .POSIX
4582 @cindex POSIX.2
4583 (For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
4584 not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
4585 in the makefile.  You probably do not care about this.)
4587 @vindex MFLAGS
4588 A similar variable @code{MFLAGS} exists also, for historical
4589 compatibility.  It has the same value as @code{MAKEFLAGS} except that it
4590 does not contain the command line variable definitions, and it always
4591 begins with a hyphen unless it is empty (@code{MAKEFLAGS} begins with a
4592 hyphen only when it begins with an option that has no single-letter
4593 version, such as @samp{--warn-undefined-variables}).  @code{MFLAGS} was
4594 traditionally used explicitly in the recursive @code{make} command, like
4595 this:
4597 @example
4598 subsystem:
4599         cd subdir && $(MAKE) $(MFLAGS)
4600 @end example
4602 @noindent
4603 but now @code{MAKEFLAGS} makes this usage redundant.  If you want your
4604 makefiles to be compatible with old @code{make} programs, use this
4605 technique; it will work fine with more modern @code{make} versions too.
4607 @cindex setting options from environment
4608 @cindex options, setting from environment
4609 @cindex setting options in makefiles
4610 @cindex options, setting in makefiles
4611 The @code{MAKEFLAGS} variable can also be useful if you want to have
4612 certain options, such as @samp{-k} (@pxref{Options Summary, ,Summary of
4613 Options}), set each time you run @code{make}.  You simply put a value for
4614 @code{MAKEFLAGS} in your environment.  You can also set @code{MAKEFLAGS} in
4615 a makefile, to specify additional flags that should also be in effect for
4616 that makefile.  (Note that you cannot use @code{MFLAGS} this way.  That
4617 variable is set only for compatibility; @code{make} does not interpret a
4618 value you set for it in any way.)
4620 When @code{make} interprets the value of @code{MAKEFLAGS} (either from the
4621 environment or from a makefile), it first prepends a hyphen if the value
4622 does not already begin with one.  Then it chops the value into words
4623 separated by blanks, and parses these words as if they were options given
4624 on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
4625 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
4626 is no error for an invalid option).
4628 If you do put @code{MAKEFLAGS} in your environment, you should be sure not
4629 to include any options that will drastically affect the actions of
4630 @code{make} and undermine the purpose of makefiles and of @code{make}
4631 itself.  For instance, the @samp{-t}, @samp{-n}, and @samp{-q} options, if
4632 put in one of these variables, could have disastrous consequences and would
4633 certainly have at least surprising and probably annoying effects.@refill
4635 @node -w Option,  , Options/Recursion, Recursion
4636 @subsection The @samp{--print-directory} Option
4637 @cindex directories, printing them
4638 @cindex printing directories
4639 @cindex recursion, and printing directories
4641 If you use several levels of recursive @code{make} invocations, the
4642 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
4643 lot easier to understand by showing each directory as @code{make}
4644 starts processing it and as @code{make} finishes processing it.  For
4645 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
4646 @code{make} will print a line of the form:@refill
4648 @example
4649 make: Entering directory `/u/gnu/make'.
4650 @end example
4652 @noindent
4653 before doing anything else, and a line of the form:
4655 @example
4656 make: Leaving directory `/u/gnu/make'.
4657 @end example
4659 @noindent
4660 when processing is completed.
4662 @cindex @code{-C}, and @code{-w}
4663 @cindex @code{--directory}, and @code{--print-directory}
4664 @cindex recursion, and @code{-w}
4665 @cindex @code{-w}, and @code{-C}
4666 @cindex @code{-w}, and recursion
4667 @cindex @code{--print-directory}, and @code{--directory}
4668 @cindex @code{--print-directory}, and recursion
4669 @cindex @code{--no-print-directory}
4670 @cindex @code{--print-directory}, disabling
4671 @cindex @code{-w}, disabling
4672 Normally, you do not need to specify this option because @samp{make}
4673 does it for you: @samp{-w} is turned on automatically when you use the
4674 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
4675 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
4676 be silent, or if you use @samp{--no-print-directory} to explicitly
4677 disable it.
4679 @node Canned Recipes, Empty Recipes, Recursion, Recipes
4680 @section Defining Canned Recipes
4681 @cindex canned recipes
4682 @cindex recipes, canned
4683 @cindex sequences of commands
4684 @cindex commands, sequences of
4686 When the same sequence of commands is useful in making various
4687 targets, you can define it as a canned sequence with the @code{define}
4688 directive, and refer to the canned sequence from the recipes for those
4689 targets.  The canned sequence is actually a variable, so the name must
4690 not conflict with other variable names.
4692 Here is an example of defining a canned recipe:
4694 @example
4695 define run-yacc =
4696 yacc $(firstword $^)
4697 mv y.tab.c $@@
4698 endef
4699 @end example
4700 @cindex @code{yacc}
4702 @noindent
4703 Here @code{run-yacc} is the name of the variable being defined;
4704 @code{endef} marks the end of the definition; the lines in between are the
4705 commands.  The @code{define} directive does not expand variable references
4706 and function calls in the canned sequence; the @samp{$} characters,
4707 parentheses, variable names, and so on, all become part of the value of the
4708 variable you are defining.
4709 @xref{Multi-Line, ,Defining Multi-Line Variables},
4710 for a complete explanation of @code{define}.
4712 The first command in this example runs Yacc on the first prerequisite of
4713 whichever rule uses the canned sequence.  The output file from Yacc is
4714 always named @file{y.tab.c}.  The second command moves the output to the
4715 rule's target file name.
4717 To use the canned sequence, substitute the variable into the recipe of a
4718 rule.  You can substitute it like any other variable
4719 (@pxref{Reference, ,Basics of Variable References}).
4720 Because variables defined by @code{define} are recursively expanded
4721 variables, all the variable references you wrote inside the @code{define}
4722 are expanded now.  For example:
4724 @example
4725 foo.c : foo.y
4726         $(run-yacc)
4727 @end example
4729 @noindent
4730 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
4731 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.@refill
4733 This is a realistic example, but this particular one is not needed in
4734 practice because @code{make} has an implicit rule to figure out these
4735 commands based on the file names involved
4736 (@pxref{Implicit Rules, ,Using Implicit Rules}).
4738 @cindex @@, and @code{define}
4739 @cindex -, and @code{define}
4740 @cindex +, and @code{define}
4741 In recipe execution, each line of a canned sequence is treated just as
4742 if the line appeared on its own in the rule, preceded by a tab.  In
4743 particular, @code{make} invokes a separate sub-shell for each line.  You
4744 can use the special prefix characters that affect command lines
4745 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
4746 @xref{Recipes, ,Writing Recipes in Rules}.
4747 For example, using this canned sequence:
4749 @example
4750 define frobnicate =
4751 @@echo "frobnicating target $@@"
4752 frob-step-1 $< -o $@@-step-1
4753 frob-step-2 $@@-step-1 -o $@@
4754 endef
4755 @end example
4757 @noindent
4758 @code{make} will not echo the first line, the @code{echo} command.
4759 But it @emph{will} echo the following two recipe lines.
4761 On the other hand, prefix characters on the recipe line that refers to
4762 a canned sequence apply to every line in the sequence.  So the rule:
4764 @example
4765 frob.out: frob.in
4766         @@$(frobnicate)
4767 @end example
4769 @noindent
4770 does not echo @emph{any} recipe lines.
4771 (@xref{Echoing, ,Recipe Echoing}, for a full explanation of @samp{@@}.)
4773 @node Empty Recipes,  , Canned Recipes, Recipes
4774 @section Using Empty Recipes
4775 @cindex empty recipes
4776 @cindex recipes, empty
4778 It is sometimes useful to define recipes which do nothing.  This is done
4779 simply by giving a recipe that consists of nothing but whitespace.  For
4780 example:
4782 @example
4783 target: ;
4784 @end example
4786 @noindent
4787 defines an empty recipe for @file{target}.  You could also use a line
4788 beginning with a recipe prefix character to define an empty recipe,
4789 but this would be confusing because such a line looks empty.
4791 @findex .DEFAULT@r{, and empty recipes}
4792 You may be wondering why you would want to define a recipe that
4793 does nothing.  The only reason this is useful is to prevent a target
4794 from getting implicit recipes (from implicit rules or the
4795 @code{.DEFAULT} special target; @pxref{Implicit Rules} and
4796 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
4798 @c !!! another reason is for canonical stamp files:
4799 @ignore
4800 @example
4801 foo: stamp-foo ;
4802 stamp-foo: foo.in
4803         create foo frm foo.in
4804         touch $@
4805 @end example
4806 @end ignore
4808 You may be inclined to define empty recipes for targets that are
4809 not actual files, but only exist so that their prerequisites can be
4810 remade.  However, this is not the best way to do that, because the
4811 prerequisites may not be remade properly if the target file actually does exist.
4812 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
4814 @node Using Variables, Conditionals, Recipes, Top
4815 @chapter How to Use Variables
4816 @cindex variable
4817 @cindex value
4818 @cindex recursive variable expansion
4819 @cindex simple variable expansion
4821 A @dfn{variable} is a name defined in a makefile to represent a string
4822 of text, called the variable's @dfn{value}.  These values are
4823 substituted by explicit request into targets, prerequisites, recipes,
4824 and other parts of the makefile.  (In some other versions of @code{make},
4825 variables are called @dfn{macros}.)
4826 @cindex macro
4828 Variables and functions in all parts of a makefile are expanded when
4829 read, except for in recipes, the right-hand sides of variable
4830 definitions using @samp{=}, and the bodies of variable definitions
4831 using the @code{define} directive.@refill
4833 Variables can represent lists of file names, options to pass to compilers,
4834 programs to run, directories to look in for source files, directories to
4835 write output in, or anything else you can imagine.
4837 A variable name may be any sequence of characters not containing
4838 @samp{:}, @samp{#}, @samp{=}, or whitespace.  However, variable names
4839 containing characters other than letters, numbers, and underscores
4840 should be considered carefully, as in some shells they cannot be
4841 passed through the environment to a sub-@code{make}
4842 (@pxref{Variables/Recursion, ,Communicating Variables to a
4843 Sub-@code{make}}).  Variable names beginning with @samp{.} and an
4844 uppercase letter may be given special meaning in future versions of
4845 @code{make}.
4847 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
4848 and @samp{Foo} all refer to different variables.
4850 It is traditional to use upper case letters in variable names, but we
4851 recommend using lower case letters for variable names that serve internal
4852 purposes in the makefile, and reserving upper case for parameters that
4853 control implicit rules or for parameters that the user should override with
4854 command options (@pxref{Overriding, ,Overriding Variables}).
4856 A few variables have names that are a single punctuation character or
4857 just a few characters.  These are the @dfn{automatic variables}, and
4858 they have particular specialized uses.  @xref{Automatic Variables}.
4860 @menu
4861 * Reference::                   How to use the value of a variable.
4862 * Flavors::                     Variables come in two flavors.
4863 * Advanced::                    Advanced features for referencing a variable.
4864 * Values::                      All the ways variables get their values.
4865 * Setting::                     How to set a variable in the makefile.
4866 * Appending::                   How to append more text to the old value
4867                                   of a variable.
4868 * Override Directive::          How to set a variable in the makefile even if
4869                                   the user has set it with a command argument.
4870 * Multi-Line::                  An alternate way to set a variable
4871                                   to a multi-line string.
4872 * Undefine Directive::          How to undefine a variable so that it appears
4873                                   as if it was never set.
4874 * Environment::                 Variable values can come from the environment.
4875 * Target-specific::             Variable values can be defined on a per-target
4876                                   basis.
4877 * Pattern-specific::            Target-specific variable values can be applied
4878                                   to a group of targets that match a pattern.
4879 * Suppressing Inheritance::     Suppress inheritance of variables.
4880 * Special Variables::           Variables with special meaning or behavior.
4881 @end menu
4883 @node Reference, Flavors, Using Variables, Using Variables
4884 @section Basics of Variable References
4885 @cindex variables, how to reference
4886 @cindex reference to variables
4887 @cindex @code{$}, in variable reference
4888 @cindex dollar sign (@code{$}), in variable reference
4890 To substitute a variable's value, write a dollar sign followed by the name
4891 of the variable in parentheses or braces: either @samp{$(foo)} or
4892 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
4893 special significance of @samp{$} is why you must write @samp{$$} to have
4894 the effect of a single dollar sign in a file name or recipe.
4896 Variable references can be used in any context: targets, prerequisites,
4897 recipes, most directives, and new variable values.  Here is an
4898 example of a common case, where a variable holds the names of all the
4899 object files in a program:
4901 @example
4902 @group
4903 objects = program.o foo.o utils.o
4904 program : $(objects)
4905         cc -o program $(objects)
4907 $(objects) : defs.h
4908 @end group
4909 @end example
4911 Variable references work by strict textual substitution.  Thus, the rule
4913 @example
4914 @group
4915 foo = c
4916 prog.o : prog.$(foo)
4917         $(foo)$(foo) -$(foo) prog.$(foo)
4918 @end group
4919 @end example
4921 @noindent
4922 could be used to compile a C program @file{prog.c}.  Since spaces before
4923 the variable value are ignored in variable assignments, the value of
4924 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
4925 this way!)
4927 A dollar sign followed by a character other than a dollar sign,
4928 open-parenthesis or open-brace treats that single character as the
4929 variable name.  Thus, you could reference the variable @code{x} with
4930 @samp{$x}.  However, this practice is strongly discouraged, except in
4931 the case of the automatic variables (@pxref{Automatic Variables}).
4933 @node Flavors, Advanced, Reference, Using Variables
4934 @section The Two Flavors of Variables
4935 @cindex flavors of variables
4936 @cindex recursive variable expansion
4937 @cindex variables, flavors
4938 @cindex recursively expanded variables
4939 @cindex variables, recursively expanded
4941 There are two ways that a variable in GNU @code{make} can have a value;
4942 we call them the two @dfn{flavors} of variables.  The two flavors are
4943 distinguished in how they are defined and in what they do when expanded.
4945 @cindex =
4946 The first flavor of variable is a @dfn{recursively expanded} variable.
4947 Variables of this sort are defined by lines using @samp{=}
4948 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
4949 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).  The value you specify
4950 is installed verbatim; if it contains references to other variables,
4951 these references are expanded whenever this variable is substituted (in
4952 the course of expanding some other string).  When this happens, it is
4953 called @dfn{recursive expansion}.@refill
4955 For example,
4957 @example
4958 foo = $(bar)
4959 bar = $(ugh)
4960 ugh = Huh?
4962 all:;echo $(foo)
4963 @end example
4965 @noindent
4966 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
4967 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
4969 This flavor of variable is the only sort supported by other versions of
4970 @code{make}.  It has its advantages and its disadvantages.  An advantage
4971 (most would say) is that:
4973 @example
4974 CFLAGS = $(include_dirs) -O
4975 include_dirs = -Ifoo -Ibar
4976 @end example
4978 @noindent
4979 will do what was intended: when @samp{CFLAGS} is expanded in a recipe,
4980 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
4981 cannot append something on the end of a variable, as in
4983 @example
4984 CFLAGS = $(CFLAGS) -O
4985 @end example
4987 @noindent
4988 because it will cause an infinite loop in the variable expansion.
4989 (Actually @code{make} detects the infinite loop and reports an error.)
4990 @cindex loops in variable expansion
4991 @cindex variables, loops in expansion
4993 Another disadvantage is that any functions
4994 (@pxref{Functions, ,Functions for Transforming Text})
4995 referenced in the definition will be executed every time the variable is
4996 expanded.  This makes @code{make} run slower; worse, it causes the
4997 @code{wildcard} and @code{shell} functions to give unpredictable results
4998 because you cannot easily control when they are called, or even how many
4999 times.
5001 To avoid all the problems and inconveniences of recursively expanded
5002 variables, there is another flavor: simply expanded variables.
5004 @cindex simply expanded variables
5005 @cindex variables, simply expanded
5006 @cindex :=
5007 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
5008 (@pxref{Setting, ,Setting Variables}).
5009 The value of a simply expanded variable is scanned
5010 once and for all, expanding any references to other variables and
5011 functions, when the variable is defined.  The actual value of the simply
5012 expanded variable is the result of expanding the text that you write.
5013 It does not contain any references to other variables; it contains their
5014 values @emph{as of the time this variable was defined}.  Therefore,
5016 @example
5017 x := foo
5018 y := $(x) bar
5019 x := later
5020 @end example
5022 @noindent
5023 is equivalent to
5025 @example
5026 y := foo bar
5027 x := later
5028 @end example
5030 When a simply expanded variable is referenced, its value is substituted
5031 verbatim.
5033 Here is a somewhat more complicated example, illustrating the use of
5034 @samp{:=} in conjunction with the @code{shell} function.
5035 (@xref{Shell Function, , The @code{shell} Function}.)  This example
5036 also shows use of the variable @code{MAKELEVEL}, which is changed
5037 when it is passed down from level to level.
5038 (@xref{Variables/Recursion, , Communicating Variables to a
5039 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
5041 @vindex MAKELEVEL
5042 @vindex MAKE
5043 @example
5044 @group
5045 ifeq (0,$@{MAKELEVEL@})
5046 whoami    := $(shell whoami)
5047 host-type := $(shell arch)
5048 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
5049 endif
5050 @end group
5051 @end example
5053 @noindent
5054 An advantage of this use of @samp{:=} is that a typical
5055 `descend into a directory' recipe then looks like this:
5057 @example
5058 @group
5059 $@{subdirs@}:
5060         $@{MAKE@} -C $@@ all
5061 @end group
5062 @end example
5064 Simply expanded variables generally make complicated makefile programming
5065 more predictable because they work like variables in most programming
5066 languages.  They allow you to redefine a variable using its own value (or
5067 its value processed in some way by one of the expansion functions) and to
5068 use the expansion functions much more efficiently
5069 (@pxref{Functions, ,Functions for Transforming Text}).
5071 @cindex spaces, in variable values
5072 @cindex whitespace, in variable values
5073 @cindex variables, spaces in values
5074 You can also use them to introduce controlled leading whitespace into
5075 variable values.  Leading whitespace characters are discarded from your
5076 input before substitution of variable references and function calls;
5077 this means you can include leading spaces in a variable value by
5078 protecting them with variable references, like this:
5080 @example
5081 nullstring :=
5082 space := $(nullstring) # end of the line
5083 @end example
5085 @noindent
5086 Here the value of the variable @code{space} is precisely one space.  The
5087 comment @w{@samp{# end of the line}} is included here just for clarity.
5088 Since trailing space characters are @emph{not} stripped from variable
5089 values, just a space at the end of the line would have the same effect
5090 (but be rather hard to read).  If you put whitespace at the end of a
5091 variable value, it is a good idea to put a comment like that at the end
5092 of the line to make your intent clear.  Conversely, if you do @emph{not}
5093 want any whitespace characters at the end of your variable value, you
5094 must remember not to put a random comment on the end of the line after
5095 some whitespace, such as this:
5097 @example
5098 dir := /foo/bar    # directory to put the frobs in
5099 @end example
5101 @noindent
5102 Here the value of the variable @code{dir} is @w{@samp{/foo/bar    }}
5103 (with four trailing spaces), which was probably not the intention.
5104 (Imagine something like @w{@samp{$(dir)/file}} with this definition!)
5106 @cindex conditional variable assignment
5107 @cindex variables, conditional assignment
5108 @cindex ?=
5109 There is another assignment operator for variables, @samp{?=}.  This
5110 is called a conditional variable assignment operator, because it only
5111 has an effect if the variable is not yet defined.  This statement:
5113 @example
5114 FOO ?= bar
5115 @end example
5117 @noindent
5118 is exactly equivalent to this
5119 (@pxref{Origin Function, ,The @code{origin} Function}):
5121 @example
5122 ifeq ($(origin FOO), undefined)
5123   FOO = bar
5124 endif
5125 @end example
5127 Note that a variable set to an empty value is still defined, so
5128 @samp{?=} will not set that variable.
5130 @node Advanced, Values, Flavors, Using Variables
5131 @section Advanced Features for Reference to Variables
5132 @cindex reference to variables
5134 This section describes some advanced features you can use to reference
5135 variables in more flexible ways.
5137 @menu
5138 * Substitution Refs::           Referencing a variable with
5139                                   substitutions on the value.
5140 * Computed Names::              Computing the name of the variable to refer to.
5141 @end menu
5143 @node Substitution Refs, Computed Names, Advanced, Advanced
5144 @subsection Substitution References
5145 @cindex modified variable reference
5146 @cindex substitution variable reference
5147 @cindex variables, modified reference
5148 @cindex variables, substitution reference
5150 @cindex variables, substituting suffix in
5151 @cindex suffix, substituting in variables
5152 A @dfn{substitution reference} substitutes the value of a variable with
5153 alterations that you specify.  It has the form
5154 @samp{$(@var{var}:@var{a}=@var{b})} (or
5155 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
5156 of the variable @var{var}, replace every @var{a} at the end of a word with
5157 @var{b} in that value, and substitute the resulting string.
5159 When we say ``at the end of a word'', we mean that @var{a} must appear
5160 either followed by whitespace or at the end of the value in order to be
5161 replaced; other occurrences of @var{a} in the value are unaltered.  For
5162 example:@refill
5164 @example
5165 foo := a.o b.o c.o
5166 bar := $(foo:.o=.c)
5167 @end example
5169 @noindent
5170 sets @samp{bar} to @samp{a.c b.c c.c}.  @xref{Setting, ,Setting Variables}.
5172 A substitution reference is actually an abbreviation for use of the
5173 @code{patsubst} expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}).  We provide
5174 substitution references as well as @code{patsubst} for compatibility with
5175 other implementations of @code{make}.
5177 @findex patsubst
5178 Another type of substitution reference lets you use the full power of
5179 the @code{patsubst} function.  It has the same form
5180 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
5181 @var{a} must contain a single @samp{%} character.  This case is
5182 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
5183 @xref{Text Functions, ,Functions for String Substitution and Analysis},
5184 for a description of the @code{patsubst} function.@refill
5186 @example
5187 @group
5188 @exdent For example:
5190 foo := a.o b.o c.o
5191 bar := $(foo:%.o=%.c)
5192 @end group
5193 @end example
5195 @noindent
5196 sets @samp{bar} to @samp{a.c b.c c.c}.
5198 @node Computed Names,  , Substitution Refs, Advanced
5199 @subsection Computed Variable Names
5200 @cindex nested variable reference
5201 @cindex computed variable name
5202 @cindex variables, computed names
5203 @cindex variables, nested references
5204 @cindex variables, @samp{$} in name
5205 @cindex @code{$}, in variable name
5206 @cindex dollar sign (@code{$}), in variable name
5208 Computed variable names are a complicated concept needed only for
5209 sophisticated makefile programming.  For most purposes you need not
5210 consider them, except to know that making a variable with a dollar sign
5211 in its name might have strange results.  However, if you are the type
5212 that wants to understand everything, or you are actually interested in
5213 what they do, read on.
5215 Variables may be referenced inside the name of a variable.  This is
5216 called a @dfn{computed variable name} or a @dfn{nested variable
5217 reference}.  For example,
5219 @example
5220 x = y
5221 y = z
5222 a := $($(x))
5223 @end example
5225 @noindent
5226 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
5227 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
5228 to @samp{z}.  Here the name of the variable to reference is not stated
5229 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
5230 @samp{$(x)} here is nested within the outer variable reference.
5232 The previous example shows two levels of nesting, but any number of levels
5233 is possible.  For example, here are three levels:
5235 @example
5236 x = y
5237 y = z
5238 z = u
5239 a := $($($(x)))
5240 @end example
5242 @noindent
5243 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
5244 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
5245 @samp{$(z)}, which becomes @samp{u}.
5247 References to recursively-expanded variables within a variable name are
5248 re-expanded in the usual fashion.  For example:
5250 @example
5251 x = $(y)
5252 y = z
5253 z = Hello
5254 a := $($(x))
5255 @end example
5257 @noindent
5258 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
5259 which becomes @samp{$(z)} which becomes @samp{Hello}.
5261 Nested variable references can also contain modified references and
5262 function invocations (@pxref{Functions, ,Functions for Transforming Text}),
5263 just like any other reference.
5264 For example, using the @code{subst} function
5265 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
5267 @example
5268 @group
5269 x = variable1
5270 variable2 := Hello
5271 y = $(subst 1,2,$(x))
5272 z = y
5273 a := $($($(z)))
5274 @end group
5275 @end example
5277 @noindent
5278 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
5279 would ever want to write a nested reference as convoluted as this one, but
5280 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
5281 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
5282 @code{x} and changes it by substitution to @samp{variable2}, so that the
5283 entire string becomes @samp{$(variable2)}, a simple variable reference
5284 whose value is @samp{Hello}.@refill
5286 A computed variable name need not consist entirely of a single variable
5287 reference.  It can contain several variable references, as well as some
5288 invariant text.  For example,
5290 @example
5291 @group
5292 a_dirs := dira dirb
5293 1_dirs := dir1 dir2
5294 @end group
5296 @group
5297 a_files := filea fileb
5298 1_files := file1 file2
5299 @end group
5301 @group
5302 ifeq "$(use_a)" "yes"
5303 a1 := a
5304 else
5305 a1 := 1
5306 endif
5307 @end group
5309 @group
5310 ifeq "$(use_dirs)" "yes"
5311 df := dirs
5312 else
5313 df := files
5314 endif
5316 dirs := $($(a1)_$(df))
5317 @end group
5318 @end example
5320 @noindent
5321 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
5322 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
5323 and @code{use_dirs}.@refill
5325 Computed variable names can also be used in substitution references:
5327 @example
5328 @group
5329 a_objects := a.o b.o c.o
5330 1_objects := 1.o 2.o 3.o
5332 sources := $($(a1)_objects:.o=.c)
5333 @end group
5334 @end example
5336 @noindent
5337 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
5338 depending on the value of @code{a1}.
5340 The only restriction on this sort of use of nested variable references
5341 is that they cannot specify part of the name of a function to be called.
5342 This is because the test for a recognized function name is done before
5343 the expansion of nested references.  For example,
5345 @example
5346 @group
5347 ifdef do_sort
5348 func := sort
5349 else
5350 func := strip
5351 endif
5352 @end group
5354 @group
5355 bar := a d b g q c
5356 @end group
5358 @group
5359 foo := $($(func) $(bar))
5360 @end group
5361 @end example
5363 @noindent
5364 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
5365 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
5366 as the argument to either the @code{sort} or the @code{strip} function.
5367 This restriction could be removed in the future if that change is shown
5368 to be a good idea.
5370 You can also use computed variable names in the left-hand side of a
5371 variable assignment, or in a @code{define} directive, as in:
5373 @example
5374 dir = foo
5375 $(dir)_sources := $(wildcard $(dir)/*.c)
5376 define $(dir)_print =
5377 lpr $($(dir)_sources)
5378 endef
5379 @end example
5381 @noindent
5382 This example defines the variables @samp{dir}, @samp{foo_sources}, and
5383 @samp{foo_print}.
5385 Note that @dfn{nested variable references} are quite different from
5386 @dfn{recursively expanded variables}
5387 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
5388 used together in complex ways when doing makefile programming.@refill
5390 @node Values, Setting, Advanced, Using Variables
5391 @section How Variables Get Their Values
5392 @cindex variables, how they get their values
5393 @cindex value, how a variable gets it
5395 Variables can get values in several different ways:
5397 @itemize @bullet
5398 @item
5399 You can specify an overriding value when you run @code{make}.
5400 @xref{Overriding, ,Overriding Variables}.
5402 @item
5403 You can specify a value in the makefile, either
5404 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
5405 verbatim definition (@pxref{Multi-Line, ,Defining Multi-Line Variables}).@refill
5407 @item
5408 Variables in the environment become @code{make} variables.
5409 @xref{Environment, ,Variables from the Environment}.
5411 @item
5412 Several @dfn{automatic} variables are given new values for each rule.
5413 Each of these has a single conventional use.
5414 @xref{Automatic Variables}.
5416 @item
5417 Several variables have constant initial values.
5418 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
5419 @end itemize
5421 @node Setting, Appending, Values, Using Variables
5422 @section Setting Variables
5423 @cindex setting variables
5424 @cindex variables, setting
5425 @cindex =
5426 @cindex :=
5427 @cindex ?=
5428 @cindex !=
5430 To set a variable from the makefile, write a line starting with the
5431 variable name followed by @samp{=} or @samp{:=}.  Whatever follows the
5432 @samp{=} or @samp{:=} on the line becomes the value.  For example,
5434 @example
5435 objects = main.o foo.o bar.o utils.o
5436 @end example
5438 @noindent
5439 defines a variable named @code{objects}.  Whitespace around the variable
5440 name and immediately after the @samp{=} is ignored.
5442 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
5443 Variables defined with @samp{:=} are @dfn{simply expanded} variables; these
5444 definitions can contain variable references which will be expanded before
5445 the definition is made.  @xref{Flavors, ,The Two Flavors of Variables}.
5447 The variable name may contain function and variable references, which
5448 are expanded when the line is read to find the actual variable name to use.
5450 There is no limit on the length of the value of a variable except the
5451 amount of memory on the computer.  When a variable definition is long,
5452 it is a good idea to break it into several lines by inserting
5453 backslash-newline at convenient places in the definition.  This will
5454 make the makefile easier to read.  Every backslash-newline, along with
5455 any leading whitespace on the following line, will be replaced by a
5456 single space in the value of the variable.
5458 Most variable names are considered to have the empty string as a value if
5459 you have never set them.  Several variables have built-in initial values
5460 that are not empty, but you can set them in the usual ways
5461 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).
5462 Several special variables are set
5463 automatically to a new value for each rule; these are called the
5464 @dfn{automatic} variables (@pxref{Automatic Variables}).
5466 If you'd like a variable to be set to a value only if it's not already
5467 set, then you can use the shorthand operator @samp{?=} instead of
5468 @samp{=}.  These two settings of the variable @samp{FOO} are identical
5469 (@pxref{Origin Function, ,The @code{origin} Function}):
5471 @example
5472 FOO ?= bar
5473 @end example
5475 @noindent
5478 @example
5479 ifeq ($(origin FOO), undefined)
5480 FOO = bar
5481 endif
5482 @end example
5484 The shell assignment operator @samp{!=} can be used to execute a
5485 program and set a variable to its output.  This operator first
5486 evaluates the right-hand side, then passes that result to the shell
5487 for execution.  If the result of the execution ends in a newline, that
5488 one newline is removed; all other newlines are replaced by spaces.
5489 The resulting string is then placed into the named
5490 recursively-expanded variable.  For example:
5492 @example
5493 hash != printf '\043'
5494 file_list != find . -name '*.c'
5495 @end example
5497 If the result of the execution could produce a @code{$}, and you don't
5498 intend what follows that to be interpreted as a make variable or
5499 function reference, then you must replace every @code{$} with
5500 @code{$$} as part of the execution.  Alternatively, you can set a
5501 simply expanded variable to the result of running a program using the
5502 @code{shell} function call.  @xref{Shell Function, , The @code{shell}
5503 Function}.  For example:
5505 @example
5506 hash := $(shell printf '\043')
5507 var := $(shell find . -name "*.c")
5508 @end example
5511 @node Appending, Override Directive, Setting, Using Variables
5512 @section Appending More Text to Variables
5513 @cindex +=
5514 @cindex appending to variables
5515 @cindex variables, appending to
5517 Often it is useful to add more text to the value of a variable already defined.
5518 You do this with a line containing @samp{+=}, like this:
5520 @example
5521 objects += another.o
5522 @end example
5524 @noindent
5525 This takes the value of the variable @code{objects}, and adds the text
5526 @samp{another.o} to it (preceded by a single space).  Thus:
5528 @example
5529 objects = main.o foo.o bar.o utils.o
5530 objects += another.o
5531 @end example
5533 @noindent
5534 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
5536 Using @samp{+=} is similar to:
5538 @example
5539 objects = main.o foo.o bar.o utils.o
5540 objects := $(objects) another.o
5541 @end example
5543 @noindent
5544 but differs in ways that become important when you use more complex values.
5546 When the variable in question has not been defined before, @samp{+=}
5547 acts just like normal @samp{=}: it defines a recursively-expanded
5548 variable.  However, when there @emph{is} a previous definition, exactly
5549 what @samp{+=} does depends on what flavor of variable you defined
5550 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
5551 explanation of the two flavors of variables.
5553 When you add to a variable's value with @samp{+=}, @code{make} acts
5554 essentially as if you had included the extra text in the initial
5555 definition of the variable.  If you defined it first with @samp{:=},
5556 making it a simply-expanded variable, @samp{+=} adds to that
5557 simply-expanded definition, and expands the new text before appending it
5558 to the old value just as @samp{:=} does
5559 (see @ref{Setting, ,Setting Variables}, for a full explanation of @samp{:=}).
5560 In fact,
5562 @example
5563 variable := value
5564 variable += more
5565 @end example
5567 @noindent
5568 is exactly equivalent to:
5570 @noindent
5571 @example
5572 variable := value
5573 variable := $(variable) more
5574 @end example
5576 On the other hand, when you use @samp{+=} with a variable that you defined
5577 first to be recursively-expanded using plain @samp{=}, @code{make} does
5578 something a bit different.  Recall that when you define a
5579 recursively-expanded variable, @code{make} does not expand the value you set
5580 for variable and function references immediately.  Instead it stores the text
5581 verbatim, and saves these variable and function references to be expanded
5582 later, when you refer to the new variable (@pxref{Flavors, ,The Two Flavors
5583 of Variables}).  When you use @samp{+=} on a recursively-expanded variable,
5584 it is this unexpanded text to which @code{make} appends the new text you
5585 specify.
5587 @example
5588 @group
5589 variable = value
5590 variable += more
5591 @end group
5592 @end example
5594 @noindent
5595 is roughly equivalent to:
5597 @example
5598 @group
5599 temp = value
5600 variable = $(temp) more
5601 @end group
5602 @end example
5604 @noindent
5605 except that of course it never defines a variable called @code{temp}.
5606 The importance of this comes when the variable's old value contains
5607 variable references.  Take this common example:
5609 @example
5610 CFLAGS = $(includes) -O
5611 @dots{}
5612 CFLAGS += -pg # enable profiling
5613 @end example
5615 @noindent
5616 The first line defines the @code{CFLAGS} variable with a reference to another
5617 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
5618 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
5619 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
5620 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
5621 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
5622 need not be defined yet for its value to take effect.  It only has to be
5623 defined before any reference to @code{CFLAGS}.  If we tried to append to the
5624 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
5626 @example
5627 CFLAGS := $(CFLAGS) -pg # enable profiling
5628 @end example
5630 @noindent
5631 This is pretty close, but not quite what we want.  Using @samp{:=}
5632 redefines @code{CFLAGS} as a simply-expanded variable; this means
5633 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
5634 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
5635 -pg}}, and a later definition of @code{includes} will have no effect.
5636 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
5637 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
5638 the reference to @code{includes}, so if that variable gets defined at
5639 any later point, a reference like @samp{$(CFLAGS)} still uses its
5640 value.
5642 @node Override Directive, Multi-Line, Appending, Using Variables
5643 @section The @code{override} Directive
5644 @findex override
5645 @cindex overriding with @code{override}
5646 @cindex variables, overriding
5648 If a variable has been set with a command argument
5649 (@pxref{Overriding, ,Overriding Variables}),
5650 then ordinary assignments in the makefile are ignored.  If you want to set
5651 the variable in the makefile even though it was set with a command
5652 argument, you can use an @code{override} directive, which is a line that
5653 looks like this:@refill
5655 @example
5656 override @var{variable} = @var{value}
5657 @end example
5659 @noindent
5662 @example
5663 override @var{variable} := @var{value}
5664 @end example
5666 To append more text to a variable defined on the command line, use:
5668 @example
5669 override @var{variable} += @var{more text}
5670 @end example
5672 @noindent
5673 @xref{Appending, ,Appending More Text to Variables}.
5675 Variable assignments marked with the @code{override} flag have a
5676 higher priority than all other assignments, except another
5677 @code{override}.  Subsequent assignments or appends to this variable
5678 which are not marked @code{override} will be ignored.
5680 The @code{override} directive was not invented for escalation in the war
5681 between makefiles and command arguments.  It was invented so you can alter
5682 and add to values that the user specifies with command arguments.
5684 For example, suppose you always want the @samp{-g} switch when you run the
5685 C compiler, but you would like to allow the user to specify the other
5686 switches with a command argument just as usual.  You could use this
5687 @code{override} directive:
5689 @example
5690 override CFLAGS += -g
5691 @end example
5693 You can also use @code{override} directives with @code{define} directives.
5694 This is done as you might expect:
5696 @example
5697 override define foo =
5699 endef
5700 @end example
5702 @noindent
5703 @iftex
5704 See the next section for information about @code{define}.
5705 @end iftex
5706 @ifnottex
5707 @xref{Multi-Line, ,Defining Multi-Line Variables}.
5708 @end ifnottex
5710 @node Multi-Line, Undefine Directive, Override Directive, Using Variables
5711 @section Defining Multi-Line Variables
5712 @findex define
5713 @findex endef
5714 @cindex multi-line variable definition
5715 @cindex variables, multi-line
5716 @cindex verbatim variable definition
5717 @cindex defining variables verbatim
5718 @cindex variables, defining verbatim
5720 Another way to set the value of a variable is to use the @code{define}
5721 directive.  This directive has an unusual syntax which allows newline
5722 characters to be included in the value, which is convenient for
5723 defining both canned sequences of commands (@pxref{Canned Recipes,
5724 ,Defining Canned Recipes}), and also sections of makefile syntax to
5725 use with @code{eval} (@pxref{Eval Function}).@refill
5727 The @code{define} directive is followed on the same line by the name
5728 of the variable being defined and an (optional) assignment operator,
5729 and nothing more.  The value to give the variable appears on the
5730 following lines.  The end of the value is marked by a line containing
5731 just the word @code{endef}.  Aside from this difference in syntax,
5732 @code{define} works just like any other variable definition.  The
5733 variable name may contain function and variable references, which are
5734 expanded when the directive is read to find the actual variable name
5735 to use.
5737 You may omit the variable assignment operator if you prefer.  If
5738 omitted, @code{make} assumes it to be @samp{=} and creates a
5739 recursively-expanded variable (@pxref{Flavors, ,The Two Flavors of Variables}).
5740 When using a @samp{+=} operator, the value is appended to the previous
5741 value as with any other append operation: with a single space
5742 separating the old and new values.
5744 You may nest @code{define} directives: @code{make} will keep track of
5745 nested directives and report an error if they are not all properly
5746 closed with @code{endef}.  Note that lines beginning with the recipe
5747 prefix character are considered part of a recipe, so any @code{define}
5748 or @code{endef} strings appearing on such a line will not be
5749 considered @code{make} directives.
5751 @example
5752 define two-lines =
5753 echo foo
5754 echo $(bar)
5755 endef
5756 @end example
5758 The value in an ordinary assignment cannot contain a newline; but the
5759 newlines that separate the lines of the value in a @code{define} become
5760 part of the variable's value (except for the final newline which precedes
5761 the @code{endef} and is not considered part of the value).@refill
5763 @need 800
5764 When used in a recipe, the previous example is functionally equivalent
5765 to this:
5767 @example
5768 two-lines = echo foo; echo $(bar)
5769 @end example
5771 @noindent
5772 since two commands separated by semicolon behave much like two separate
5773 shell commands.  However, note that using two separate lines means
5774 @code{make} will invoke the shell twice, running an independent sub-shell
5775 for each line.  @xref{Execution, ,Recipe Execution}.
5777 If you want variable definitions made with @code{define} to take
5778 precedence over command-line variable definitions, you can use the
5779 @code{override} directive together with @code{define}:
5781 @example
5782 override define two-lines =
5784 $(bar)
5785 endef
5786 @end example
5788 @noindent
5789 @xref{Override Directive, ,The @code{override} Directive}.
5791 @node Undefine Directive, Environment, Multi-Line, Using Variables
5792 @section Undefining Variables
5793 @findex undefine
5794 @cindex undefining variable
5796 If you want to clear a variable, setting its value to empty is usually
5797 sufficient. Expanding such a variable will yield the same result (empty
5798 string) regardless of whether it was set or not. However, if you are
5799 using the @code{flavor} (@pxref{Flavor Function}) and
5800 @code{origin} (@pxref{Origin Function}) functions, there is a difference
5801 between a variable that was never set and a variable with an empty value.
5802 In such situations you may want to use the @code{undefine} directive to
5803 make a variable appear as if it was never set. For example:
5805 @example
5806 foo := foo
5807 bar = bar
5809 undefine foo
5810 undefine bar
5812 $(info $(origin foo))
5813 $(info $(flavor bar))
5814 @end example
5816 This example will print ``undefined'' for both variables.
5818 If you want to undefine a command-line variable definition, you can use
5819 the @code{override} directive together with @code{undefine}, similar to
5820 how this is done for variable definitions:
5822 @example
5823 override undefine CFLAGS
5824 @end example
5826 @node Environment, Target-specific, Undefine Directive, Using Variables
5827 @section Variables from the Environment
5829 @cindex variables, environment
5830 @cindex environment
5831 Variables in @code{make} can come from the environment in which
5832 @code{make} is run.  Every environment variable that @code{make} sees
5833 when it starts up is transformed into a @code{make} variable with the
5834 same name and value.  However, an explicit assignment in the makefile,
5835 or with a command argument, overrides the environment.  (If the
5836 @samp{-e} flag is specified, then values from the environment override
5837 assignments in the makefile.  @xref{Options Summary, ,Summary of
5838 Options}.  But this is not recommended practice.)
5840 Thus, by setting the variable @code{CFLAGS} in your environment, you can
5841 cause all C compilations in most makefiles to use the compiler switches you
5842 prefer.  This is safe for variables with standard or conventional meanings
5843 because you know that no makefile will use them for other things.  (Note
5844 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
5845 and therefore are not affected by the value in the environment.)
5847 When @code{make} runs a recipe, variables defined in the
5848 makefile are placed into the environment of each shell.  This allows
5849 you to pass values to sub-@code{make} invocations (@pxref{Recursion,
5850 ,Recursive Use of @code{make}}).  By default, only variables that came
5851 from the environment or the command line are passed to recursive
5852 invocations.  You can use the @code{export} directive to pass other
5853 variables.  @xref{Variables/Recursion, , Communicating Variables to a
5854 Sub-@code{make}}, for full details.
5856 Other use of variables from the environment is not recommended.  It is not
5857 wise for makefiles to depend for their functioning on environment variables
5858 set up outside their control, since this would cause different users to get
5859 different results from the same makefile.  This is against the whole
5860 purpose of most makefiles.
5862 @cindex SHELL, import from environment
5863 Such problems would be especially likely with the variable
5864 @code{SHELL}, which is normally present in the environment to specify
5865 the user's choice of interactive shell.  It would be very undesirable
5866 for this choice to affect @code{make}; so, @code{make} handles the
5867 @code{SHELL} environment variable in a special way; see @ref{Choosing
5868 the Shell}.@refill
5870 @node Target-specific, Pattern-specific, Environment, Using Variables
5871 @section Target-specific Variable Values
5872 @cindex target-specific variables
5873 @cindex variables, target-specific
5875 Variable values in @code{make} are usually global; that is, they are the
5876 same regardless of where they are evaluated (unless they're reset, of
5877 course).  One exception to that is automatic variables
5878 (@pxref{Automatic Variables}).
5880 The other exception is @dfn{target-specific variable values}.  This
5881 feature allows you to define different values for the same variable,
5882 based on the target that @code{make} is currently building.  As with
5883 automatic variables, these values are only available within the context
5884 of a target's recipe (and in other target-specific assignments).
5886 Set a target-specific variable value like this:
5888 @example
5889 @var{target} @dots{} : @var{variable-assignment}
5890 @end example
5892 Target-specific variable assignments can be prefixed with any or all of the
5893 special keywords @code{export}, @code{override}, or @code{private};
5894 these apply their normal behavior to this instance of the variable only.
5896 Multiple @var{target} values create a target-specific variable value for
5897 each member of the target list individually.
5899 The @var{variable-assignment} can be any valid form of assignment;
5900 recursive (@samp{=}), simple (@samp{:=}), appending (@samp{+=}), or
5901 conditional (@samp{?=}).  All variables that appear within the
5902 @var{variable-assignment} are evaluated within the context of the
5903 target: thus, any previously-defined target-specific variable values
5904 will be in effect.  Note that this variable is actually distinct from
5905 any ``global'' value: the two variables do not have to have the same
5906 flavor (recursive vs.@: simple).
5908 Target-specific variables have the same priority as any other makefile
5909 variable.  Variables provided on the command line (and in the
5910 environment if the @samp{-e} option is in force) will take precedence.
5911 Specifying the @code{override} directive will allow the target-specific
5912 variable value to be preferred.
5914 There is one more special feature of target-specific variables: when
5915 you define a target-specific variable that variable value is also in
5916 effect for all prerequisites of this target, and all their
5917 prerequisites, etc.@: (unless those prerequisites override that variable
5918 with their own target-specific variable value).  So, for example, a
5919 statement like this:
5921 @example
5922 prog : CFLAGS = -g
5923 prog : prog.o foo.o bar.o
5924 @end example
5926 @noindent
5927 will set @code{CFLAGS} to @samp{-g} in the recipe for @file{prog}, but
5928 it will also set @code{CFLAGS} to @samp{-g} in the recipes that create
5929 @file{prog.o}, @file{foo.o}, and @file{bar.o}, and any recipes which
5930 create their prerequisites.
5932 Be aware that a given prerequisite will only be built once per
5933 invocation of make, at most.  If the same file is a prerequisite of
5934 multiple targets, and each of those targets has a different value for
5935 the same target-specific variable, then the first target to be built
5936 will cause that prerequisite to be built and the prerequisite will
5937 inherit the target-specific value from the first target.  It will
5938 ignore the target-specific values from any other targets.
5940 @node Pattern-specific, Suppressing Inheritance, Target-specific, Using Variables
5941 @section Pattern-specific Variable Values
5942 @cindex pattern-specific variables
5943 @cindex variables, pattern-specific
5945 In addition to target-specific variable values
5946 (@pxref{Target-specific, ,Target-specific Variable Values}), GNU
5947 @code{make} supports pattern-specific variable values.  In this form,
5948 the variable is defined for any target that matches the pattern
5949 specified.
5951 Set a pattern-specific variable value like this:
5953 @example
5954 @var{pattern} @dots{} : @var{variable-assignment}
5955 @end example
5956 where @var{pattern} is a %-pattern.  As with target-specific variable
5957 values, multiple @var{pattern} values create a pattern-specific variable
5958 value for each pattern individually.  The @var{variable-assignment} can
5959 be any valid form of assignment.  Any command line variable setting will
5960 take precedence, unless @code{override} is specified.
5962 For example:
5964 @example
5965 %.o : CFLAGS = -O
5966 @end example
5968 @noindent
5969 will assign @code{CFLAGS} the value of @samp{-O} for all targets
5970 matching the pattern @code{%.o}.
5972 If a target matches more than one pattern, the matching pattern-specific
5973 variables with longer stems are interpreted first. This results in more
5974 specific variables taking precedence over the more generic ones, for
5975 example:
5977 @example
5978 %.o: %.c
5979         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
5981 lib/%.o: CFLAGS := -fPIC -g
5982 %.o: CFLAGS := -g
5984 all: foo.o lib/bar.o
5985 @end example
5987 In this example the first definition of the @code{CFLAGS} variable
5988 will be used to update @file{lib/bar.o} even though the second one
5989 also applies to this target. Pattern-specific variables which result
5990 in the same stem length are considered in the order in which they
5991 were defined in the makefile.
5993 Pattern-specific variables are searched after any target-specific
5994 variables defined explicitly for that target, and before target-specific
5995 variables defined for the parent target.
5997 @node Suppressing Inheritance, Special Variables, Pattern-specific, Using Variables
5998 @section Suppressing Inheritance
5999 @findex private
6000 @cindex suppressing inheritance
6001 @cindex inheritance, suppressing
6003 As described in previous sections, @code{make} variables are inherited
6004 by prerequisites.  This capability allows you to modify the behavior
6005 of a prerequisite based on which targets caused it to be rebuilt.  For
6006 example, you might set a target-specific variable on a @code{debug}
6007 target, then running @samp{make debug} will cause that variable to be
6008 inherited by all prerequisites of @code{debug}, while just running
6009 @samp{make all} (for example) would not have that assignment.
6011 Sometimes, however, you may not want a variable to be inherited.  For
6012 these situations, @code{make} provides the @code{private} modifier.
6013 Although this modifier can be used with any variable assignment, it
6014 makes the most sense with target- and pattern-specific variables.  Any
6015 variable marked @code{private} will be visible to its local target but
6016 will not be inherited by prerequisites of that target.  A global
6017 variable marked @code{private} will be visible in the global scope but
6018 will not be inherited by any target, and hence will not be visible
6019 in any recipe.
6021 As an example, consider this makefile:
6022 @example
6023 EXTRA_CFLAGS =
6025 prog: private EXTRA_CFLAGS = -L/usr/local/lib
6026 prog: a.o b.o
6027 @end example
6029 Due to the @code{private} modifier, @code{a.o} and @code{b.o} will not
6030 inherit the @code{EXTRA_CFLAGS} variable assignment from the
6031 @code{prog} target.
6033 @node Special Variables,  , Suppressing Inheritance, Using Variables
6034 @comment  node-name,  next,  previous,  up
6035 @section Other Special Variables
6036 @cindex makefiles, and special variables
6037 @cindex special variables
6039 GNU @code{make} supports some variables that have special properties.
6041 @table @code
6043 @vindex MAKEFILE_LIST @r{(list of parsed makefiles)}
6044 @cindex makefiles, and @code{MAKEFILE_LIST} variable
6045 @cindex including (@code{MAKEFILE_LIST} variable)
6046 @item MAKEFILE_LIST
6047 Contains the name of each makefile that is parsed by @code{make}, in
6048 the order in which it was parsed.  The name is appended just
6049 before @code{make} begins to parse the makefile.  Thus, if the first
6050 thing a makefile does is examine the last word in this variable, it
6051 will be the name of the current makefile.  Once the current makefile
6052 has used @code{include}, however, the last word will be the
6053 just-included makefile.
6055 If a makefile named @code{Makefile} has this content:
6057 @example
6058 @group
6059 name1 := $(lastword $(MAKEFILE_LIST))
6061 include inc.mk
6063 name2 := $(lastword $(MAKEFILE_LIST))
6065 all:
6066         @@echo name1 = $(name1)
6067         @@echo name2 = $(name2)
6068 @end group
6069 @end example
6071 @noindent
6072 then you would expect to see this output:
6074 @example
6075 @group
6076 name1 = Makefile
6077 name2 = inc.mk
6078 @end group
6079 @end example
6081 @vindex .DEFAULT_GOAL @r{(define default goal)}
6082 @item .DEFAULT_GOAL
6083 Sets the default goal to be used if no targets were specified on the
6084 command line (@pxref{Goals, , Arguments to Specify the Goals}).  The
6085 @code{.DEFAULT_GOAL} variable allows you to discover the current
6086 default goal, restart the default goal selection algorithm by clearing
6087 its value, or to explicitly set the default goal.  The following
6088 example illustrates these cases:
6090 @example
6091 @group
6092 # Query the default goal.
6093 ifeq ($(.DEFAULT_GOAL),)
6094   $(warning no default goal is set)
6095 endif
6097 .PHONY: foo
6098 foo: ; @@echo $@@
6100 $(warning default goal is $(.DEFAULT_GOAL))
6102 # Reset the default goal.
6103 .DEFAULT_GOAL :=
6105 .PHONY: bar
6106 bar: ; @@echo $@@
6108 $(warning default goal is $(.DEFAULT_GOAL))
6110 # Set our own.
6111 .DEFAULT_GOAL := foo
6112 @end group
6113 @end example
6115 This makefile prints:
6117 @example
6118 @group
6119 no default goal is set
6120 default goal is foo
6121 default goal is bar
6123 @end group
6124 @end example
6126 Note that assigning more than one target name to @code{.DEFAULT_GOAL} is
6127 invalid and will result in an error.
6129 @vindex MAKE_RESTARTS @r{(number of times @code{make} has restarted)}
6130 @item MAKE_RESTARTS
6131 This variable is set only if this instance of @code{make} has
6132 restarted (@pxref{Remaking Makefiles, , How Makefiles Are Remade}): it
6133 will contain the number of times this instance has restarted.  Note
6134 this is not the same as recursion (counted by the @code{MAKELEVEL}
6135 variable).  You should not set, modify, or export this variable.
6137 @vindex .RECIPEPREFIX @r{(change the recipe prefix character)}
6138 @item .RECIPEPREFIX
6139 The first character of the value of this variable is used as the
6140 character make assumes is introducing a recipe line.  If the variable
6141 is empty (as it is by default) that character is the standard tab
6142 character.  For example, this is a valid makefile:
6144 @example
6145 @group
6146 .RECIPEPREFIX = >
6147 all:
6148 > @@echo Hello, world
6149 @end group
6150 @end example
6152 The value of @code{.RECIPEPREFIX} can be changed multiple times; once set
6153 it stays in effect for all rules parsed until it is modified.
6155 @vindex .VARIABLES @r{(list of variables)}
6156 @item .VARIABLES
6157 Expands to a list of the @emph{names} of all global variables defined
6158 so far.  This includes variables which have empty values, as well as
6159 built-in variables (@pxref{Implicit Variables, , Variables Used by
6160 Implicit Rules}), but does not include any variables which are only
6161 defined in a target-specific context.  Note that any value you assign
6162 to this variable will be ignored; it will always return its special
6163 value.
6165 @c @vindex .TARGETS @r{(list of targets)}
6166 @c @item .TARGETS
6167 @c The second special variable is @code{.TARGETS}.  When expanded, the
6168 @c value consists of a list of all targets defined in all makefiles read
6169 @c up until that point.  Note it's not enough for a file to be simply
6170 @c mentioned in the makefile to be listed in this variable, even if it
6171 @c would match an implicit rule and become an ``implicit target''.  The
6172 @c file must appear as a target, on the left-hand side of a ``:'', to be
6173 @c considered a target for the purposes of this variable.
6175 @vindex .FEATURES @r{(list of supported features)}
6176 @item .FEATURES
6177 Expands to a list of special features supported by this version of
6178 @code{make}.  Possible values include, but are not limited to:
6180 @table @samp
6182 @item archives
6183 Supports @code{ar} (archive) files using special file name syntax.
6184 @xref{Archives, ,Using @code{make} to Update Archive Files}.
6186 @item check-symlink
6187 Supports the @code{-L} (@code{--check-symlink-times}) flag.
6188 @xref{Options Summary, ,Summary of Options}.
6190 @item else-if
6191 Supports ``else if'' non-nested conditionals.  @xref{Conditional
6192 Syntax, ,Syntax of Conditionals}.
6194 @item jobserver
6195 Supports ``job server'' enhanced parallel builds.  @xref{Parallel,
6196 ,Parallel Execution}.
6198 @item oneshell
6199 Supports the @code{.ONESHELL} special target.  @xref{One Shell, ,Using
6200 One Shell}.
6202 @item order-only
6203 Supports order-only prerequisites.  @xref{Prerequisite Types, ,Types
6204 of Prerequisites}.
6206 @item second-expansion
6207 Supports secondary expansion of prerequisite lists.
6209 @item shortest-stem
6210 Uses the ``shortest stem'' method of choosing which pattern, of
6211 multiple applicable options, will be used.  @xref{Pattern Match, ,How
6212 Patterns Match}.
6214 @item target-specific
6215 Supports target-specific and pattern-specific variable assignments.
6216 @xref{Target-specific, ,Target-specific Variable Values}.
6218 @item undefine
6219 Supports the @code{undefine} directive.  @xref{Undefine Directive}.
6221 @item guile
6222 Has GNU Guile available as an embedded extension language.
6223 @xref{Guile Function}.
6225 @end table
6227 @vindex .INCLUDE_DIRS @r{(list of include directories)}
6228 @item .INCLUDE_DIRS
6229 Expands to a list of directories that @code{make} searches for
6230 included makefiles (@pxref{Include, , Including Other Makefiles}).
6232 @end table
6234 @node Conditionals, Functions, Using Variables, Top
6235 @chapter Conditional Parts of Makefiles
6237 @cindex conditionals
6238 A @dfn{conditional} directive causes part of a makefile to be obeyed
6239 or ignored depending on the values of variables.  Conditionals can
6240 compare the value of one variable to another, or the value of a
6241 variable to a constant string.  Conditionals control what @code{make}
6242 actually ``sees'' in the makefile, so they @emph{cannot} be used to
6243 control recipes at the time of execution.@refill
6245 @menu
6246 * Conditional Example::         Example of a conditional
6247 * Conditional Syntax::          The syntax of conditionals.
6248 * Testing Flags::               Conditionals that test flags.
6249 @end menu
6251 @node Conditional Example, Conditional Syntax, Conditionals, Conditionals
6252 @section Example of a Conditional
6254 The following example of a conditional tells @code{make} to use one
6255 set of libraries if the @code{CC} variable is @samp{gcc}, and a
6256 different set of libraries otherwise.  It works by controlling which
6257 of two recipe lines will be used for the rule.  The result is that
6258 @samp{CC=gcc} as an argument to @code{make} changes not only which
6259 compiler is used but also which libraries are linked.
6261 @example
6262 libs_for_gcc = -lgnu
6263 normal_libs =
6265 foo: $(objects)
6266 ifeq ($(CC),gcc)
6267         $(CC) -o foo $(objects) $(libs_for_gcc)
6268 else
6269         $(CC) -o foo $(objects) $(normal_libs)
6270 endif
6271 @end example
6273 This conditional uses three directives: one @code{ifeq}, one @code{else}
6274 and one @code{endif}.
6276 The @code{ifeq} directive begins the conditional, and specifies the
6277 condition.  It contains two arguments, separated by a comma and surrounded
6278 by parentheses.  Variable substitution is performed on both arguments and
6279 then they are compared.  The lines of the makefile following the
6280 @code{ifeq} are obeyed if the two arguments match; otherwise they are
6281 ignored.
6283 The @code{else} directive causes the following lines to be obeyed if the
6284 previous conditional failed.  In the example above, this means that the
6285 second alternative linking command is used whenever the first alternative
6286 is not used.  It is optional to have an @code{else} in a conditional.
6288 The @code{endif} directive ends the conditional.  Every conditional must
6289 end with an @code{endif}.  Unconditional makefile text follows.
6291 As this example illustrates, conditionals work at the textual level:
6292 the lines of the conditional are treated as part of the makefile, or
6293 ignored, according to the condition.  This is why the larger syntactic
6294 units of the makefile, such as rules, may cross the beginning or the
6295 end of the conditional.
6297 When the variable @code{CC} has the value @samp{gcc}, the above example has
6298 this effect:
6300 @example
6301 foo: $(objects)
6302         $(CC) -o foo $(objects) $(libs_for_gcc)
6303 @end example
6305 @noindent
6306 When the variable @code{CC} has any other value, the effect is this:
6308 @example
6309 foo: $(objects)
6310         $(CC) -o foo $(objects) $(normal_libs)
6311 @end example
6313 Equivalent results can be obtained in another way by conditionalizing a
6314 variable assignment and then using the variable unconditionally:
6316 @example
6317 libs_for_gcc = -lgnu
6318 normal_libs =
6320 ifeq ($(CC),gcc)
6321   libs=$(libs_for_gcc)
6322 else
6323   libs=$(normal_libs)
6324 endif
6326 foo: $(objects)
6327         $(CC) -o foo $(objects) $(libs)
6328 @end example
6330 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
6331 @section Syntax of Conditionals
6332 @findex ifdef
6333 @findex ifeq
6334 @findex ifndef
6335 @findex ifneq
6336 @findex else
6337 @findex endif
6339 The syntax of a simple conditional with no @code{else} is as follows:
6341 @example
6342 @var{conditional-directive}
6343 @var{text-if-true}
6344 endif
6345 @end example
6347 @noindent
6348 The @var{text-if-true} may be any lines of text, to be considered as part
6349 of the makefile if the condition is true.  If the condition is false, no
6350 text is used instead.
6352 The syntax of a complex conditional is as follows:
6354 @example
6355 @var{conditional-directive}
6356 @var{text-if-true}
6357 else
6358 @var{text-if-false}
6359 endif
6360 @end example
6364 @example
6365 @var{conditional-directive}
6366 @var{text-if-one-is-true}
6367 else @var{conditional-directive}
6368 @var{text-if-true}
6369 else
6370 @var{text-if-false}
6371 endif
6372 @end example
6374 @noindent
6375 There can be as many ``@code{else} @var{conditional-directive}''
6376 clauses as necessary.  Once a given condition is true,
6377 @var{text-if-true} is used and no other clause is used; if no
6378 condition is true then @var{text-if-false} is used.  The
6379 @var{text-if-true} and @var{text-if-false} can be any number of lines
6380 of text.
6382 The syntax of the @var{conditional-directive} is the same whether the
6383 conditional is simple or complex; after an @code{else} or not.  There
6384 are four different directives that test different conditions.  Here is
6385 a table of them:
6387 @table @code
6388 @item ifeq (@var{arg1}, @var{arg2})
6389 @itemx 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 Expand all variable references in @var{arg1} and @var{arg2} and
6394 compare them.  If they are identical, the @var{text-if-true} is
6395 effective; otherwise, the @var{text-if-false}, if any, is effective.
6397 Often you want to test if a variable has a non-empty value.  When the
6398 value results from complex expansions of variables and functions,
6399 expansions you would consider empty may actually contain whitespace
6400 characters and thus are not seen as empty.  However, you can use the
6401 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
6402 whitespace as a non-empty value.  For example:
6404 @example
6405 @group
6406 ifeq ($(strip $(foo)),)
6407 @var{text-if-empty}
6408 endif
6409 @end group
6410 @end example
6412 @noindent
6413 will evaluate @var{text-if-empty} even if the expansion of
6414 @code{$(foo)} contains whitespace characters.
6416 @item ifneq (@var{arg1}, @var{arg2})
6417 @itemx 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 Expand all variable references in @var{arg1} and @var{arg2} and
6422 compare them.  If they are different, the @var{text-if-true} is
6423 effective; otherwise, the @var{text-if-false}, if any, is effective.
6425 @item ifdef @var{variable-name}
6426 The @code{ifdef} form takes the @emph{name} of a variable as its
6427 argument, not a reference to a variable.  The value of that variable
6428 has a non-empty value, the @var{text-if-true} is effective; otherwise,
6429 the @var{text-if-false}, if any, is effective.  Variables that have
6430 never been defined have an empty value.  The text @var{variable-name}
6431 is expanded, so it could be a variable or function that expands
6432 to the name of a variable.  For example:
6434 @example
6435 bar = true
6436 foo = bar
6437 ifdef $(foo)
6438 frobozz = yes
6439 endif
6440 @end example
6442 The variable reference @code{$(foo)} is expanded, yielding @code{bar},
6443 which is considered to be the name of a variable.  The variable
6444 @code{bar} is not expanded, but its value is examined to determine if
6445 it is non-empty.
6447 Note that @code{ifdef} only tests whether a variable has a value.  It
6448 does not expand the variable to see if that value is nonempty.
6449 Consequently, tests using @code{ifdef} return true for all definitions
6450 except those like @code{foo =}.  To test for an empty value, use
6451 @w{@code{ifeq ($(foo),)}}.  For example,
6453 @example
6454 bar =
6455 foo = $(bar)
6456 ifdef foo
6457 frobozz = yes
6458 else
6459 frobozz = no
6460 endif
6461 @end example
6463 @noindent
6464 sets @samp{frobozz} to @samp{yes}, while:
6466 @example
6467 foo =
6468 ifdef foo
6469 frobozz = yes
6470 else
6471 frobozz = no
6472 endif
6473 @end example
6475 @noindent
6476 sets @samp{frobozz} to @samp{no}.
6478 @item ifndef @var{variable-name}
6479 If the variable @var{variable-name} has an empty value, the
6480 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
6481 if any, is effective.  The rules for expansion and testing of
6482 @var{variable-name} are identical to the @code{ifdef} directive.
6483 @end table
6485 Extra spaces are allowed and ignored at the beginning of the
6486 conditional directive line, but a tab is not allowed.  (If the line
6487 begins with a tab, it will be considered part of a recipe for a rule.)
6488 Aside from this, extra spaces or tabs may be inserted with no effect
6489 anywhere except within the directive name or within an argument.  A
6490 comment starting with @samp{#} may appear at the end of the line.
6492 The other two directives that play a part in a conditional are @code{else}
6493 and @code{endif}.  Each of these directives is written as one word, with no
6494 arguments.  Extra spaces are allowed and ignored at the beginning of the
6495 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
6496 appear at the end of the line.
6498 Conditionals affect which lines of the makefile @code{make} uses.  If
6499 the condition is true, @code{make} reads the lines of the
6500 @var{text-if-true} as part of the makefile; if the condition is false,
6501 @code{make} ignores those lines completely.  It follows that syntactic
6502 units of the makefile, such as rules, may safely be split across the
6503 beginning or the end of the conditional.@refill
6505 @code{make} evaluates conditionals when it reads a makefile.
6506 Consequently, you cannot use automatic variables in the tests of
6507 conditionals because they are not defined until recipes are run
6508 (@pxref{Automatic Variables}).
6510 To prevent intolerable confusion, it is not permitted to start a
6511 conditional in one makefile and end it in another.  However, you may
6512 write an @code{include} directive within a conditional, provided you do
6513 not attempt to terminate the conditional inside the included file.
6515 @node Testing Flags,  , Conditional Syntax, Conditionals
6516 @section Conditionals that Test Flags
6518 You can write a conditional that tests @code{make} command flags such as
6519 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
6520 @code{findstring} function
6521 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
6522 This is useful when @code{touch} is not enough to make a file appear up
6523 to date.
6525 The @code{findstring} function determines whether one string appears as a
6526 substring of another.  If you want to test for the @samp{-t} flag,
6527 use @samp{t} as the first string and the value of @code{MAKEFLAGS} as
6528 the other.
6530 For example, here is how to arrange to use @samp{ranlib -t} to finish
6531 marking an archive file up to date:
6533 @example
6534 archive.a: @dots{}
6535 ifneq (,$(findstring t,$(MAKEFLAGS)))
6536         +touch archive.a
6537         +ranlib -t archive.a
6538 else
6539         ranlib archive.a
6540 endif
6541 @end example
6543 @noindent
6544 The @samp{+} prefix marks those recipe lines as ``recursive'' so that
6545 they will be executed despite use of the @samp{-t} flag.
6546 @xref{Recursion, ,Recursive Use of @code{make}}.
6548 @node Functions, Running, Conditionals, Top
6549 @chapter Functions for Transforming Text
6550 @cindex functions
6552 @dfn{Functions} allow you to do text processing in the makefile to
6553 compute the files to operate on or the commands to use in recipes.
6554 You use a function in a @dfn{function call}, where you give the name
6555 of the function and some text (the @dfn{arguments}) for the function
6556 to operate on.  The result of the function's processing is substituted
6557 into the makefile at the point of the call, just as a variable might
6558 be substituted.
6560 @menu
6561 * Syntax of Functions::         How to write a function call.
6562 * Text Functions::              General-purpose text manipulation functions.
6563 * File Name Functions::         Functions for manipulating file names.
6564 * Conditional Functions::       Functions that implement conditions.
6565 * Foreach Function::            Repeat some text with controlled variation.
6566 * Call Function::               Expand a user-defined function.
6567 * Value Function::              Return the un-expanded value of a variable.
6568 * Eval Function::               Evaluate the arguments as makefile syntax.
6569 * Origin Function::             Find where a variable got its value.
6570 * Flavor Function::             Find out the flavor of a variable.
6571 * Make Control Functions::      Functions that control how make runs.
6572 * Shell Function::              Substitute the output of a shell command.
6573 * Guile Function::              Call the GNU Guile embedded scripting language.
6574 @end menu
6576 @node Syntax of Functions, Text Functions, Functions, Functions
6577 @section Function Call Syntax
6578 @cindex @code{$}, in function call
6579 @cindex dollar sign (@code{$}), in function call
6580 @cindex arguments of functions
6581 @cindex functions, syntax of
6583 A function call resembles a variable reference.  It can appear
6584 anywhere a variable reference can appear, and it is expanded using the
6585 same rules as variable references.  A function call looks like this:
6587 @example
6588 $(@var{function} @var{arguments})
6589 @end example
6591 @noindent
6592 or like this:
6594 @example
6595 $@{@var{function} @var{arguments}@}
6596 @end example
6598 Here @var{function} is a function name; one of a short list of names
6599 that are part of @code{make}.  You can also essentially create your own
6600 functions by using the @code{call} built-in function.
6602 The @var{arguments} are the arguments of the function.  They are
6603 separated from the function name by one or more spaces or tabs, and if
6604 there is more than one argument, then they are separated by commas.
6605 Such whitespace and commas are not part of an argument's value.  The
6606 delimiters which you use to surround the function call, whether
6607 parentheses or braces, can appear in an argument only in matching pairs;
6608 the other kind of delimiters may appear singly.  If the arguments
6609 themselves contain other function calls or variable references, it is
6610 wisest to use the same kind of delimiters for all the references; write
6611 @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst a,b,$@{x@})}}.  This
6612 is because it is clearer, and because only one type of delimiter is
6613 matched to find the end of the reference.
6615 The text written for each argument is processed by substitution of
6616 variables and function calls to produce the argument value, which
6617 is the text on which the function acts.  The substitution is done in the
6618 order in which the arguments appear.
6620 Commas and unmatched parentheses or braces cannot appear in the text of an
6621 argument as written; leading spaces cannot appear in the text of the first
6622 argument as written.  These characters can be put into the argument value
6623 by variable substitution.  First define variables @code{comma} and
6624 @code{space} whose values are isolated comma and space characters, then
6625 substitute these variables where such characters are wanted, like this:
6627 @example
6628 @group
6629 comma:= ,
6630 empty:=
6631 space:= $(empty) $(empty)
6632 foo:= a b c
6633 bar:= $(subst $(space),$(comma),$(foo))
6634 # @r{bar is now `a,b,c'.}
6635 @end group
6636 @end example
6638 @noindent
6639 Here the @code{subst} function replaces each space with a comma, through
6640 the value of @code{foo}, and substitutes the result.
6642 @node Text Functions, File Name Functions, Syntax of Functions, Functions
6643 @section Functions for String Substitution and Analysis
6644 @cindex functions, for text
6646 Here are some functions that operate on strings:
6648 @table @code
6649 @item $(subst @var{from},@var{to},@var{text})
6650 @findex subst
6651 Performs a textual replacement on the text @var{text}: each occurrence
6652 of @var{from} is replaced by @var{to}.  The result is substituted for
6653 the function call.  For example,
6655 @example
6656 $(subst ee,EE,feet on the street)
6657 @end example
6659 substitutes the string @samp{fEEt on the strEEt}.
6661 @item $(patsubst @var{pattern},@var{replacement},@var{text})
6662 @findex patsubst
6663 Finds whitespace-separated words in @var{text} that match
6664 @var{pattern} and replaces them with @var{replacement}.  Here
6665 @var{pattern} may contain a @samp{%} which acts as a wildcard,
6666 matching any number of any characters within a word.  If
6667 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
6668 by the text that matched the @samp{%} in @var{pattern}.  Only the first
6669 @samp{%} in the @var{pattern} and @var{replacement} is treated this
6670 way; any subsequent @samp{%} is unchanged.@refill
6672 @cindex @code{%}, quoting in @code{patsubst}
6673 @cindex @code{%}, quoting with @code{\} (backslash)
6674 @cindex @code{\} (backslash), to quote @code{%}
6675 @cindex backslash (@code{\}), to quote @code{%}
6676 @cindex quoting @code{%}, in @code{patsubst}
6677 @samp{%} characters in @code{patsubst} function invocations can be
6678 quoted with preceding backslashes (@samp{\}).  Backslashes that would
6679 otherwise quote @samp{%} characters can be quoted with more backslashes.
6680 Backslashes that quote @samp{%} characters or other backslashes are
6681 removed from the pattern before it is compared file names or has a stem
6682 substituted into it.  Backslashes that are not in danger of quoting
6683 @samp{%} characters go unmolested.  For example, the pattern
6684 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
6685 operative @samp{%} character, and @samp{pattern\\} following it.  The
6686 final two backslashes are left alone because they cannot affect any
6687 @samp{%} character.@refill
6689 Whitespace between words is folded into single space characters;
6690 leading and trailing whitespace is discarded.
6692 For example,
6694 @example
6695 $(patsubst %.c,%.o,x.c.c bar.c)
6696 @end example
6698 @noindent
6699 produces the value @samp{x.c.o bar.o}.
6701 Substitution references (@pxref{Substitution Refs, ,Substitution
6702 References}) are a simpler way to get the effect of the @code{patsubst}
6703 function:
6705 @example
6706 $(@var{var}:@var{pattern}=@var{replacement})
6707 @end example
6709 @noindent
6710 is equivalent to
6712 @example
6713 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
6714 @end example
6716 The second shorthand simplifies one of the most common uses of
6717 @code{patsubst}: replacing the suffix at the end of file names.
6719 @example
6720 $(@var{var}:@var{suffix}=@var{replacement})
6721 @end example
6723 @noindent
6724 is equivalent to
6726 @example
6727 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
6728 @end example
6730 @noindent
6731 For example, you might have a list of object files:
6733 @example
6734 objects = foo.o bar.o baz.o
6735 @end example
6737 @noindent
6738 To get the list of corresponding source files, you could simply write:
6740 @example
6741 $(objects:.o=.c)
6742 @end example
6744 @noindent
6745 instead of using the general form:
6747 @example
6748 $(patsubst %.o,%.c,$(objects))
6749 @end example
6751 @item $(strip @var{string})
6752 @cindex stripping whitespace
6753 @cindex whitespace, stripping
6754 @cindex spaces, stripping
6755 @findex strip
6756 Removes leading and trailing whitespace from @var{string} and replaces
6757 each internal sequence of one or more whitespace characters with a
6758 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
6760 The function @code{strip} can be very useful when used in conjunction
6761 with conditionals.  When comparing something with the empty string
6762 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
6763 just whitespace to match the empty string (@pxref{Conditionals}).
6765 Thus, the following may fail to have the desired results:
6767 @example
6768 .PHONY: all
6769 ifneq   "$(needs_made)" ""
6770 all: $(needs_made)
6771 else
6772 all:;@@echo 'Nothing to make!'
6773 endif
6774 @end example
6776 @noindent
6777 Replacing the variable reference @w{@samp{$(needs_made)}} with the
6778 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
6779 directive would make it more robust.@refill
6781 @item $(findstring @var{find},@var{in})
6782 @findex findstring
6783 @cindex searching for strings
6784 @cindex finding strings
6785 @cindex strings, searching for
6786 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
6787 value is @var{find}; otherwise, the value is empty.  You can use this
6788 function in a conditional to test for the presence of a specific
6789 substring in a given string.  Thus, the two examples,
6791 @example
6792 $(findstring a,a b c)
6793 $(findstring a,b c)
6794 @end example
6796 @noindent
6797 produce the values @samp{a} and @samp{} (the empty string),
6798 respectively.  @xref{Testing Flags}, for a practical application of
6799 @code{findstring}.@refill
6801 @need 750
6802 @findex filter
6803 @cindex filtering words
6804 @cindex words, filtering
6805 @item $(filter @var{pattern}@dots{},@var{text})
6806 Returns all whitespace-separated words in @var{text} that @emph{do} match
6807 any of the @var{pattern} words, removing any words that @emph{do not}
6808 match.  The patterns are written using @samp{%}, just like the patterns
6809 used in the @code{patsubst} function above.@refill
6811 The @code{filter} function can be used to separate out different types
6812 of strings (such as file names) in a variable.  For example:
6814 @example
6815 sources := foo.c bar.c baz.s ugh.h
6816 foo: $(sources)
6817         cc $(filter %.c %.s,$(sources)) -o foo
6818 @end example
6820 @noindent
6821 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
6822 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
6823 @file{baz.s} should be specified in the command to the
6824 compiler.@refill
6826 @item $(filter-out @var{pattern}@dots{},@var{text})
6827 @findex filter-out
6828 @cindex filtering out words
6829 @cindex words, filtering out
6830 Returns all whitespace-separated words in @var{text} that @emph{do not}
6831 match any of the @var{pattern} words, removing the words that @emph{do}
6832 match one or more.  This is the exact opposite of the @code{filter}
6833 function.@refill
6835 For example, given:
6837 @example
6838 @group
6839 objects=main1.o foo.o main2.o bar.o
6840 mains=main1.o main2.o
6841 @end group
6842 @end example
6844 @noindent
6845 the following generates a list which contains all the object files not
6846 in @samp{mains}:
6848 @example
6849 $(filter-out $(mains),$(objects))
6850 @end example
6852 @need 1500
6853 @findex sort
6854 @cindex sorting words
6855 @item $(sort @var{list})
6856 Sorts the words of @var{list} in lexical order, removing duplicate
6857 words.  The output is a list of words separated by single spaces.
6858 Thus,
6860 @example
6861 $(sort foo bar lose)
6862 @end example
6864 @noindent
6865 returns the value @samp{bar foo lose}.
6867 @cindex removing duplicate words
6868 @cindex duplicate words, removing
6869 @cindex words, removing duplicates
6870 Incidentally, since @code{sort} removes duplicate words, you can use
6871 it for this purpose even if you don't care about the sort order.
6873 @item $(word @var{n},@var{text})
6874 @findex word
6875 @cindex word, selecting a
6876 @cindex selecting a word
6877 Returns the @var{n}th word of @var{text}.  The legitimate values of
6878 @var{n} start from 1.  If @var{n} is bigger than the number of words
6879 in @var{text}, the value is empty.  For example,
6881 @example
6882 $(word 2, foo bar baz)
6883 @end example
6885 @noindent
6886 returns @samp{bar}.
6888 @item $(wordlist @var{s},@var{e},@var{text})
6889 @findex wordlist
6890 @cindex words, selecting lists of
6891 @cindex selecting word lists
6892 Returns the list of words in @var{text} starting with word @var{s} and
6893 ending with word @var{e} (inclusive).  The legitimate values of @var{s}
6894 start from 1; @var{e} may start from 0.  If @var{s} is bigger than the
6895 number of words in @var{text}, the value is empty.  If @var{e} is
6896 bigger than the number of words in @var{text}, words up to the end of
6897 @var{text} are returned.  If @var{s} is greater than @var{e}, nothing
6898 is returned.  For example,
6900 @example
6901 $(wordlist 2, 3, foo bar baz)
6902 @end example
6904 @noindent
6905 returns @samp{bar baz}.
6907 @c Following item phrased to prevent overfull hbox.  --RJC 17 Jul 92
6908 @item $(words @var{text})
6909 @findex words
6910 @cindex words, finding number
6911 Returns the number of words in @var{text}.
6912 Thus, the last word of @var{text} is
6913 @w{@code{$(word $(words @var{text}),@var{text})}}.@refill
6915 @item $(firstword @var{names}@dots{})
6916 @findex firstword
6917 @cindex words, extracting first
6918 The argument @var{names} is regarded as a series of names, separated
6919 by whitespace.  The value is the first name in the series.  The rest
6920 of the names are ignored.
6922 For example,
6924 @example
6925 $(firstword foo bar)
6926 @end example
6928 @noindent
6929 produces the result @samp{foo}.  Although @code{$(firstword
6930 @var{text})} is the same as @code{$(word 1,@var{text})}, the
6931 @code{firstword} function is retained for its simplicity.@refill
6934 @item $(lastword @var{names}@dots{})
6935 @findex lastword
6936 @cindex words, extracting last
6937 The argument @var{names} is regarded as a series of names, separated
6938 by whitespace.  The value is the last name in the series.
6940 For example,
6942 @example
6943 $(lastword foo bar)
6944 @end example
6946 @noindent
6947 produces the result @samp{bar}.  Although @code{$(lastword
6948 @var{text})} is the same as @code{$(word $(words @var{text}),@var{text})},
6949 the @code{lastword} function was added for its simplicity and better
6950 performance.@refill
6951 @end table
6954 Here is a realistic example of the use of @code{subst} and
6955 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
6956 to specify a list of directories that @code{make} should search for
6957 prerequisite files
6958 (@pxref{General Search, , @code{VPATH} Search Path for All Prerequisites}).
6959 This example shows how to
6960 tell the C compiler to search for header files in the same list of
6961 directories.@refill
6963 The value of @code{VPATH} is a list of directories separated by colons,
6964 such as @samp{src:../headers}.  First, the @code{subst} function is used to
6965 change the colons to spaces:
6967 @example
6968 $(subst :, ,$(VPATH))
6969 @end example
6971 @noindent
6972 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
6973 each directory name into a @samp{-I} flag.  These can be added to the
6974 value of the variable @code{CFLAGS}, which is passed automatically to the C
6975 compiler, like this:
6977 @example
6978 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
6979 @end example
6981 @noindent
6982 The effect is to append the text @samp{-Isrc -I../headers} to the
6983 previously given value of @code{CFLAGS}.  The @code{override} directive is
6984 used so that the new value is assigned even if the previous value of
6985 @code{CFLAGS} was specified with a command argument (@pxref{Override
6986 Directive, , The @code{override} Directive}).
6988 @node File Name Functions, Conditional Functions, Text Functions, Functions
6989 @section Functions for File Names
6990 @cindex functions, for file names
6991 @cindex file name functions
6993 Several of the built-in expansion functions relate specifically to
6994 taking apart file names or lists of file names.
6996 Each of the following functions performs a specific transformation on a
6997 file name.  The argument of the function is regarded as a series of file
6998 names, separated by whitespace.  (Leading and trailing whitespace is
6999 ignored.)  Each file name in the series is transformed in the same way and
7000 the results are concatenated with single spaces between them.
7002 @table @code
7003 @item $(dir @var{names}@dots{})
7004 @findex dir
7005 @cindex directory part
7006 @cindex file name, directory part
7007 Extracts the directory-part of each file name in @var{names}.  The
7008 directory-part of the file name is everything up through (and
7009 including) the last slash in it.  If the file name contains no slash,
7010 the directory part is the string @samp{./}.  For example,
7012 @example
7013 $(dir src/foo.c hacks)
7014 @end example
7016 @noindent
7017 produces the result @samp{src/ ./}.
7019 @item $(notdir @var{names}@dots{})
7020 @findex notdir
7021 @cindex file name, nondirectory part
7022 @cindex nondirectory part
7023 Extracts all but the directory-part of each file name in @var{names}.
7024 If the file name contains no slash, it is left unchanged.  Otherwise,
7025 everything through the last slash is removed from it.
7027 A file name that ends with a slash becomes an empty string.  This is
7028 unfortunate, because it means that the result does not always have the
7029 same number of whitespace-separated file names as the argument had;
7030 but we do not see any other valid alternative.
7032 For example,
7034 @example
7035 $(notdir src/foo.c hacks)
7036 @end example
7038 @noindent
7039 produces the result @samp{foo.c hacks}.
7041 @item $(suffix @var{names}@dots{})
7042 @findex suffix
7043 @cindex suffix, function to find
7044 @cindex file name suffix
7045 Extracts the suffix of each file name in @var{names}.  If the file name
7046 contains a period, the suffix is everything starting with the last
7047 period.  Otherwise, the suffix is the empty string.  This frequently
7048 means that the result will be empty when @var{names} is not, and if
7049 @var{names} contains multiple file names, the result may contain fewer
7050 file names.
7052 For example,
7054 @example
7055 $(suffix src/foo.c src-1.0/bar.c hacks)
7056 @end example
7058 @noindent
7059 produces the result @samp{.c .c}.
7061 @item $(basename @var{names}@dots{})
7062 @findex basename
7063 @cindex basename
7064 @cindex file name, basename of
7065 Extracts all but the suffix of each file name in @var{names}.  If the
7066 file name contains a period, the basename is everything starting up to
7067 (and not including) the last period.  Periods in the directory part are
7068 ignored.  If there is no period, the basename is the entire file name.
7069 For example,
7071 @example
7072 $(basename src/foo.c src-1.0/bar hacks)
7073 @end example
7075 @noindent
7076 produces the result @samp{src/foo src-1.0/bar hacks}.
7078 @c plural convention with dots (be consistent)
7079 @item $(addsuffix @var{suffix},@var{names}@dots{})
7080 @findex addsuffix
7081 @cindex suffix, adding
7082 @cindex file name suffix, adding
7083 The argument @var{names} is regarded as a series of names, separated
7084 by whitespace; @var{suffix} is used as a unit.  The value of
7085 @var{suffix} is appended to the end of each individual name and the
7086 resulting larger names are concatenated with single spaces between
7087 them.  For example,
7089 @example
7090 $(addsuffix .c,foo bar)
7091 @end example
7093 @noindent
7094 produces the result @samp{foo.c bar.c}.
7096 @item $(addprefix @var{prefix},@var{names}@dots{})
7097 @findex addprefix
7098 @cindex prefix, adding
7099 @cindex file name prefix, adding
7100 The argument @var{names} is regarded as a series of names, separated
7101 by whitespace; @var{prefix} is used as a unit.  The value of
7102 @var{prefix} is prepended to the front of each individual name and the
7103 resulting larger names are concatenated with single spaces between
7104 them.  For example,
7106 @example
7107 $(addprefix src/,foo bar)
7108 @end example
7110 @noindent
7111 produces the result @samp{src/foo src/bar}.
7113 @item $(join @var{list1},@var{list2})
7114 @findex join
7115 @cindex joining lists of words
7116 @cindex words, joining lists
7117 Concatenates the two arguments word by word: the two first words (one
7118 from each argument) concatenated form the first word of the result, the
7119 two second words form the second word of the result, and so on.  So the
7120 @var{n}th word of the result comes from the @var{n}th word of each
7121 argument.  If one argument has more words that the other, the extra
7122 words are copied unchanged into the result.
7124 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
7126 Whitespace between the words in the lists is not preserved; it is
7127 replaced with a single space.
7129 This function can merge the results of the @code{dir} and
7130 @code{notdir} functions, to produce the original list of files which
7131 was given to those two functions.@refill
7133 @item $(wildcard @var{pattern})
7134 @findex wildcard
7135 @cindex wildcard, function
7136 The argument @var{pattern} is a file name pattern, typically containing
7137 wildcard characters (as in shell file name patterns).  The result of
7138 @code{wildcard} is a space-separated list of the names of existing files
7139 that match the pattern.
7140 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
7142 @item $(realpath @var{names}@dots{})
7143 @findex realpath
7144 @cindex realpath
7145 @cindex file name, realpath of
7146 For each file name in @var{names} return the canonical absolute name.
7147 A canonical name does not contain any @code{.} or @code{..} components,
7148 nor any repeated path separators (@code{/}) or symlinks.  In case of a
7149 failure the empty string is returned.  Consult the @code{realpath(3)}
7150 documentation for a list of possible failure causes.
7152 @item $(abspath @var{names}@dots{})
7153 @findex abspath
7154 @cindex abspath
7155 @cindex file name, abspath of
7156 For each file name in @var{names} return an absolute name that does
7157 not contain any @code{.} or @code{..} components, nor any repeated path
7158 separators (@code{/}).  Note that, in contrast to @code{realpath}
7159 function, @code{abspath} does not resolve symlinks and does not require
7160 the file names to refer to an existing file or directory.  Use the
7161 @code{wildcard} function to test for existence.
7162 @end table
7164 @node Conditional Functions, Foreach Function, File Name Functions, Functions
7165 @section Functions for Conditionals
7166 @findex if
7167 @cindex conditional expansion
7168 There are three functions that provide conditional expansion.  A key
7169 aspect of these functions is that not all of the arguments are
7170 expanded initially.  Only those arguments which need to be expanded,
7171 will be expanded.
7173 @table @code
7174 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
7175 @findex if
7176 The @code{if} function provides support for conditional expansion in a
7177 functional context (as opposed to the GNU @code{make} makefile
7178 conditionals such as @code{ifeq} (@pxref{Conditional Syntax, ,Syntax of
7179 Conditionals}).
7181 The first argument, @var{condition}, first has all preceding and
7182 trailing whitespace stripped, then is expanded.  If it expands to any
7183 non-empty string, then the condition is considered to be true.  If it
7184 expands to an empty string, the condition is considered to be false.
7186 If the condition is true then the second argument, @var{then-part}, is
7187 evaluated and this is used as the result of the evaluation of the entire
7188 @code{if} function.
7190 If the condition is false then the third argument, @var{else-part}, is
7191 evaluated and this is the result of the @code{if} function.  If there is
7192 no third argument, the @code{if} function evaluates to nothing (the
7193 empty string).
7195 Note that only one of the @var{then-part} or the @var{else-part} will be
7196 evaluated, never both.  Thus, either can contain side-effects (such as
7197 @code{shell} function calls, etc.)
7199 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
7200 @findex or
7201 The @code{or} function provides a ``short-circuiting'' OR operation.
7202 Each argument is expanded, in order.  If an argument expands to a
7203 non-empty string the processing stops and the result of the expansion
7204 is that string.  If, after all arguments are expanded, all of them are
7205 false (empty), then the result of the expansion is the empty string.
7207 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
7208 @findex and
7209 The @code{and} function provides a ``short-circuiting'' AND operation.
7210 Each argument is expanded, in order.  If an argument expands to an
7211 empty string the processing stops and the result of the expansion is
7212 the empty string.  If all arguments expand to a non-empty string then
7213 the result of the expansion is the expansion of the last argument.
7215 @end table
7217 @node Foreach Function, Call Function, Conditional Functions, Functions
7218 @section The @code{foreach} Function
7219 @findex foreach
7220 @cindex words, iterating over
7222 The @code{foreach} function is very different from other functions.  It
7223 causes one piece of text to be used repeatedly, each time with a different
7224 substitution performed on it.  It resembles the @code{for} command in the
7225 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
7227 The syntax of the @code{foreach} function is:
7229 @example
7230 $(foreach @var{var},@var{list},@var{text})
7231 @end example
7233 @noindent
7234 The first two arguments, @var{var} and @var{list}, are expanded before
7235 anything else is done; note that the last argument, @var{text}, is
7236 @strong{not} expanded at the same time.  Then for each word of the expanded
7237 value of @var{list}, the variable named by the expanded value of @var{var}
7238 is set to that word, and @var{text} is expanded.  Presumably @var{text}
7239 contains references to that variable, so its expansion will be different
7240 each time.
7242 The result is that @var{text} is expanded as many times as there are
7243 whitespace-separated words in @var{list}.  The multiple expansions of
7244 @var{text} are concatenated, with spaces between them, to make the result
7245 of @code{foreach}.
7247 This simple example sets the variable @samp{files} to the list of all files
7248 in the directories in the list @samp{dirs}:
7250 @example
7251 dirs := a b c d
7252 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
7253 @end example
7255 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
7256 finds the value @samp{a} for @code{dir}, so it produces the same result
7257 as @samp{$(wildcard a/*)}; the second repetition produces the result
7258 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
7260 This example has the same result (except for setting @samp{dirs}) as
7261 the following example:
7263 @example
7264 files := $(wildcard a/* b/* c/* d/*)
7265 @end example
7267 When @var{text} is complicated, you can improve readability by giving it
7268 a name, with an additional variable:
7270 @example
7271 find_files = $(wildcard $(dir)/*)
7272 dirs := a b c d
7273 files := $(foreach dir,$(dirs),$(find_files))
7274 @end example
7276 @noindent
7277 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
7278 to define a recursively-expanding variable, so that its value contains an
7279 actual function call to be re-expanded under the control of @code{foreach};
7280 a simply-expanded variable would not do, since @code{wildcard} would be
7281 called only once at the time of defining @code{find_files}.
7283 The @code{foreach} function has no permanent effect on the variable
7284 @var{var}; its value and flavor after the @code{foreach} function call are
7285 the same as they were beforehand.  The other values which are taken from
7286 @var{list} are in effect only temporarily, during the execution of
7287 @code{foreach}.  The variable @var{var} is a simply-expanded variable
7288 during the execution of @code{foreach}.  If @var{var} was undefined
7289 before the @code{foreach} function call, it is undefined after the call.
7290 @xref{Flavors, ,The Two Flavors of Variables}.@refill
7292 You must take care when using complex variable expressions that result in
7293 variable names because many strange things are valid variable names, but
7294 are probably not what you intended.  For example,
7296 @smallexample
7297 files := $(foreach Esta-escrito-en-espanol!,b c ch,$(find_files))
7298 @end smallexample
7300 @noindent
7301 might be useful if the value of @code{find_files} references the variable
7302 whose name is @samp{Esta-escrito-en-espanol!} (es un nombre bastante largo,
7303 no?), but it is more likely to be a mistake.
7305 @node Call Function, Value Function, Foreach Function, Functions
7306 @section The @code{call} Function
7307 @findex call
7308 @cindex functions, user defined
7309 @cindex user defined functions
7311 The @code{call} function is unique in that it can be used to create new
7312 parameterized functions.  You can write a complex expression as the
7313 value of a variable, then use @code{call} to expand it with different
7314 values.
7316 The syntax of the @code{call} function is:
7318 @example
7319 $(call @var{variable},@var{param},@var{param},@dots{})
7320 @end example
7322 When @code{make} expands this function, it assigns each @var{param} to
7323 temporary variables @code{$(1)}, @code{$(2)}, etc.  The variable
7324 @code{$(0)} will contain @var{variable}.  There is no maximum number of
7325 parameter arguments.  There is no minimum, either, but it doesn't make
7326 sense to use @code{call} with no parameters.
7328 Then @var{variable} is expanded as a @code{make} variable in the context
7329 of these temporary assignments.  Thus, any reference to @code{$(1)} in
7330 the value of @var{variable} will resolve to the first @var{param} in the
7331 invocation of @code{call}.
7333 Note that @var{variable} is the @emph{name} of a variable, not a
7334 @emph{reference} to that variable.  Therefore you would not normally use
7335 a @samp{$} or parentheses when writing it.  (You can, however, use a
7336 variable reference in the name if you want the name not to be a
7337 constant.)
7339 If @var{variable} is the name of a built-in function, the built-in function
7340 is always invoked (even if a @code{make} variable by that name also
7341 exists).
7343 The @code{call} function expands the @var{param} arguments before
7344 assigning them to temporary variables.  This means that @var{variable}
7345 values containing references to built-in functions that have special
7346 expansion rules, like @code{foreach} or @code{if}, may not work as you
7347 expect.
7349 Some examples may make this clearer.
7351 This macro simply reverses its arguments:
7353 @smallexample
7354 reverse = $(2) $(1)
7356 foo = $(call reverse,a,b)
7357 @end smallexample
7359 @noindent
7360 Here @var{foo} will contain @samp{b a}.
7362 This one is slightly more interesting: it defines a macro to search for
7363 the first instance of a program in @code{PATH}:
7365 @smallexample
7366 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
7368 LS := $(call pathsearch,ls)
7369 @end smallexample
7371 @noindent
7372 Now the variable LS contains @code{/bin/ls} or similar.
7374 The @code{call} function can be nested.  Each recursive invocation gets
7375 its own local values for @code{$(1)}, etc.@: that mask the values of
7376 higher-level @code{call}.  For example, here is an implementation of a
7377 @dfn{map} function:
7379 @smallexample
7380 map = $(foreach a,$(2),$(call $(1),$(a)))
7381 @end smallexample
7383 Now you can @var{map} a function that normally takes only one argument,
7384 such as @code{origin}, to multiple values in one step:
7386 @smallexample
7387 o = $(call map,origin,o map MAKE)
7388 @end smallexample
7390 and end up with @var{o} containing something like @samp{file file default}.
7392 A final caution: be careful when adding whitespace to the arguments to
7393 @code{call}.  As with other functions, any whitespace contained in the
7394 second and subsequent arguments is kept; this can cause strange
7395 effects.  It's generally safest to remove all extraneous whitespace when
7396 providing parameters to @code{call}.
7398 @node Value Function, Eval Function, Call Function, Functions
7399 @comment  node-name,  next,  previous,  up
7400 @section The @code{value} Function
7401 @findex value
7402 @cindex variables, unexpanded value
7404 The @code{value} function provides a way for you to use the value of a
7405 variable @emph{without} having it expanded.  Please note that this
7406 does not undo expansions which have already occurred; for example if
7407 you create a simply expanded variable its value is expanded during the
7408 definition; in that case the @code{value} function will return the
7409 same result as using the variable directly.
7411 The syntax of the @code{value} function is:
7413 @example
7414 $(value @var{variable})
7415 @end example
7417 Note that @var{variable} is the @emph{name} of a variable, not a
7418 @emph{reference} to that variable.  Therefore you would not normally
7419 use a @samp{$} or parentheses when writing it.  (You can, however, use
7420 a variable reference in the name if you want the name not to be a
7421 constant.)
7423 The result of this function is a string containing the value of
7424 @var{variable}, without any expansion occurring.  For example, in this
7425 makefile:
7427 @example
7428 @group
7429 FOO = $PATH
7431 all:
7432         @@echo $(FOO)
7433         @@echo $(value FOO)
7434 @end group
7435 @end example
7437 @noindent
7438 The first output line would be @code{ATH}, since the ``$P'' would be
7439 expanded as a @code{make} variable, while the second output line would
7440 be the current value of your @code{$PATH} environment variable, since
7441 the @code{value} function avoided the expansion.
7443 The @code{value} function is most often used in conjunction with the
7444 @code{eval} function (@pxref{Eval Function}).
7446 @node Eval Function, Origin Function, Value Function, Functions
7447 @comment  node-name,  next,  previous,  up
7448 @section The @code{eval} Function
7449 @findex eval
7450 @cindex evaluating makefile syntax
7451 @cindex makefile syntax, evaluating
7453 The @code{eval} function is very special: it allows you to define new
7454 makefile constructs that are not constant; which are the result of
7455 evaluating other variables and functions.  The argument to the
7456 @code{eval} function is expanded, then the results of that expansion
7457 are parsed as makefile syntax.  The expanded results can define new
7458 @code{make} variables, targets, implicit or explicit rules, etc.
7460 The result of the @code{eval} function is always the empty string;
7461 thus, it can be placed virtually anywhere in a makefile without
7462 causing syntax errors.
7464 It's important to realize that the @code{eval} argument is expanded
7465 @emph{twice}; first by the @code{eval} function, then the results of
7466 that expansion are expanded again when they are parsed as makefile
7467 syntax.  This means you may need to provide extra levels of escaping
7468 for ``$'' characters when using @code{eval}.  The @code{value}
7469 function (@pxref{Value Function}) can sometimes be useful in these
7470 situations, to circumvent unwanted expansions.
7472 Here is an example of how @code{eval} can be used; this example
7473 combines a number of concepts and other functions.  Although it might
7474 seem overly complex to use @code{eval} in this example, rather than
7475 just writing out the rules, consider two things: first, the template
7476 definition (in @code{PROGRAM_template}) could need to be much more
7477 complex than it is here; and second, you might put the complex,
7478 ``generic'' part of this example into another makefile, then include
7479 it in all the individual makefiles.  Now your individual makefiles are
7480 quite straightforward.
7482 @example
7483 @group
7484 PROGRAMS    = server client
7486 server_OBJS = server.o server_priv.o server_access.o
7487 server_LIBS = priv protocol
7489 client_OBJS = client.o client_api.o client_mem.o
7490 client_LIBS = protocol
7492 # Everything after this is generic
7494 .PHONY: all
7495 all: $(PROGRAMS)
7497 define PROGRAM_template =
7498  $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
7499  ALL_OBJS   += $$($(1)_OBJS)
7500 endef
7502 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
7504 $(PROGRAMS):
7505         $(LINK.o) $^ $(LDLIBS) -o $@@
7507 clean:
7508         rm -f $(ALL_OBJS) $(PROGRAMS)
7509 @end group
7510 @end example
7512 @node Origin Function, Flavor Function, Eval Function, Functions
7513 @section The @code{origin} Function
7514 @findex origin
7515 @cindex variables, origin of
7516 @cindex origin of variable
7518 The @code{origin} function is unlike most other functions in that it does
7519 not operate on the values of variables; it tells you something @emph{about}
7520 a variable.  Specifically, it tells you where it came from.
7522 The syntax of the @code{origin} function is:
7524 @example
7525 $(origin @var{variable})
7526 @end example
7528 Note that @var{variable} is the @emph{name} of a variable to inquire about,
7529 not a @emph{reference} to that variable.  Therefore you would not normally
7530 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7531 variable reference in the name if you want the name not to be a constant.)
7533 The result of this function is a string telling you how the variable
7534 @var{variable} was defined:
7536 @table @samp
7537 @item undefined
7539 if @var{variable} was never defined.
7541 @item default
7543 if @var{variable} has a default definition, as is usual with @code{CC}
7544 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
7545 Note that if you have redefined a default variable, the @code{origin}
7546 function will return the origin of the later definition.
7548 @item environment
7550 if @var{variable} was inherited from the environment provided to
7551 @code{make}.
7553 @item environment override
7555 if @var{variable} was inherited from the environment provided to
7556 @code{make}, and is overriding a setting for @var{variable} in the
7557 makefile as a result of the @w{@samp{-e}} option (@pxref{Options
7558 Summary, ,Summary of Options}).@refill
7560 @item file
7562 if @var{variable} was defined in a makefile.
7564 @item command line
7566 if @var{variable} was defined on the command line.
7568 @item override
7570 if @var{variable} was defined with an @code{override} directive in a
7571 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
7573 @item automatic
7575 if @var{variable} is an automatic variable defined for the execution
7576 of the recipe for each rule (@pxref{Automatic Variables}).
7577 @end table
7579 This information is primarily useful (other than for your curiosity) to
7580 determine if you want to believe the value of a variable.  For example,
7581 suppose you have a makefile @file{foo} that includes another makefile
7582 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
7583 if you run the command @w{@samp{make -f bar}}, even if the environment contains
7584 a definition of @code{bletch}.  However, if @file{foo} defined
7585 @code{bletch} before including @file{bar}, you do not want to override that
7586 definition.  This could be done by using an @code{override} directive in
7587 @file{foo}, giving that definition precedence over the later definition in
7588 @file{bar}; unfortunately, the @code{override} directive would also
7589 override any command line definitions.  So, @file{bar} could
7590 include:@refill
7592 @example
7593 @group
7594 ifdef bletch
7595 ifeq "$(origin bletch)" "environment"
7596 bletch = barf, gag, etc.
7597 endif
7598 endif
7599 @end group
7600 @end example
7602 @noindent
7603 If @code{bletch} has been defined from the environment, this will redefine
7606 If you want to override a previous definition of @code{bletch} if it came
7607 from the environment, even under @samp{-e}, you could instead write:
7609 @example
7610 @group
7611 ifneq "$(findstring environment,$(origin bletch))" ""
7612 bletch = barf, gag, etc.
7613 endif
7614 @end group
7615 @end example
7617 Here the redefinition takes place if @samp{$(origin bletch)} returns either
7618 @samp{environment} or @samp{environment override}.
7619 @xref{Text Functions, , Functions for String Substitution and Analysis}.
7621 @node Flavor Function, Make Control Functions, Origin Function, Functions
7622 @section The @code{flavor} Function
7623 @findex flavor
7624 @cindex variables, flavor of
7625 @cindex flavor of variable
7627 The @code{flavor} function, like the @code{origin} function, does not
7628 operate on the values of variables but rather it tells you something
7629 @emph{about} a variable.  Specifically, it tells you the flavor of a
7630 variable (@pxref{Flavors, ,The Two Flavors of Variables}).
7632 The syntax of the @code{flavor} function is:
7634 @example
7635 $(flavor @var{variable})
7636 @end example
7638 Note that @var{variable} is the @emph{name} of a variable to inquire about,
7639 not a @emph{reference} to that variable.  Therefore you would not normally
7640 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7641 variable reference in the name if you want the name not to be a constant.)
7643 The result of this function is a string that identifies the flavor of the
7644 variable @var{variable}:
7646 @table @samp
7647 @item undefined
7649 if @var{variable} was never defined.
7651 @item recursive
7653 if @var{variable} is a recursively expanded variable.
7655 @item simple
7657 if @var{variable} is a simply expanded variable.
7659 @end table
7661 @node Make Control Functions, Shell Function, Flavor Function, Functions
7662 @section Functions That Control Make
7663 @cindex functions, for controlling make
7664 @cindex controlling make
7666 These functions control the way make runs.  Generally, they are used to
7667 provide information to the user of the makefile or to cause make to stop
7668 if some sort of environmental error is detected.
7670 @table @code
7671 @item $(error @var{text}@dots{})
7672 @findex error
7673 @cindex error, stopping on
7674 @cindex stopping make
7675 Generates a fatal error where the message is @var{text}.  Note that
7676 the error is generated whenever this function is evaluated.  So, if
7677 you put it inside a recipe or on the right side of a recursive
7678 variable assignment, it won't be evaluated until later.  The
7679 @var{text} will be expanded before the error is generated.
7681 For example,
7683 @example
7684 ifdef ERROR1
7685 $(error error is $(ERROR1))
7686 endif
7687 @end example
7689 @noindent
7690 will generate a fatal error during the read of the makefile if the
7691 @code{make} variable @code{ERROR1} is defined.  Or,
7693 @example
7694 ERR = $(error found an error!)
7696 .PHONY: err
7697 err: ; $(ERR)
7698 @end example
7700 @noindent
7701 will generate a fatal error while @code{make} is running, if the
7702 @code{err} target is invoked.
7704 @item $(warning @var{text}@dots{})
7705 @findex warning
7706 @cindex warnings, printing
7707 @cindex printing user warnings
7708 This function works similarly to the @code{error} function, above,
7709 except that @code{make} doesn't exit.  Instead, @var{text} is expanded
7710 and the resulting message is displayed, but processing of the makefile
7711 continues.
7713 The result of the expansion of this function is the empty string.
7715 @item $(info @var{text}@dots{})
7716 @findex info
7717 @cindex printing messages
7718 This function does nothing more than print its (expanded) argument(s)
7719 to standard output.  No makefile name or line number is added.  The
7720 result of the expansion of this function is the empty string.
7721 @end table
7723 @node Shell Function, Guile Function, Make Control Functions, Functions
7724 @section The @code{shell} Function
7725 @findex shell
7726 @cindex command expansion
7727 @cindex backquotes
7728 @cindex shell command, function for
7730 The @code{shell} function is unlike any other function other than the
7731 @code{wildcard} function
7732 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
7733 communicates with the world outside of @code{make}.
7735 The @code{shell} function performs the same function that backquotes
7736 (@samp{`}) perform in most shells: it does @dfn{command expansion}.
7737 This means that it takes as an argument a shell command and evaluates
7738 to the output of the command.  The only processing @code{make} does on
7739 the result is to convert each newline (or carriage-return / newline
7740 pair) to a single space.  If there is a trailing (carriage-return
7741 and) newline it will simply be removed.@refill
7743 The commands run by calls to the @code{shell} function are run when the
7744 function calls are expanded (@pxref{Reading Makefiles, , How
7745 @code{make} Reads a Makefile}).  Because this function involves
7746 spawning a new shell, you should carefully consider the performance
7747 implications of using the @code{shell} function within recursively
7748 expanded variables vs.@: simply expanded variables (@pxref{Flavors, ,The
7749 Two Flavors of Variables}).
7751 Here are some examples of the use of the @code{shell} function:
7753 @example
7754 contents := $(shell cat foo)
7755 @end example
7757 @noindent
7758 sets @code{contents} to the contents of the file @file{foo}, with a space
7759 (rather than a newline) separating each line.
7761 @example
7762 files := $(shell echo *.c)
7763 @end example
7765 @noindent
7766 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
7767 using a very strange shell, this has the same result as
7768 @w{@samp{$(wildcard *.c)}} (as long as at least one @samp{.c} file
7769 exists).@refill
7771 @node Guile Function,  , Shell Function, Functions
7772 @section The @code{guile} Function
7773 @findex guile
7774 @cindex Guile
7776 GNU make may be built with support for GNU Guile as an embedded
7777 extension language.  You can check the @code{.FEATURES} variable for
7778 the word @samp{guile} to determine if your version of GNU make
7779 provides this capability.
7781 GNU Guile implements the Scheme language.  A review of GNU Guile and
7782 the Scheme language and its features is beyond the scope of this
7783 manual: see the documentation for GNU Guile and Scheme.
7785 If GNU Guile is available as an extension language, there will be one
7786 new @code{make} function available: @code{guile}.  The @code{guile}
7787 function takes one argument which is first expanded by @code{make} in
7788 the normal fashion, then passed to the GNU Guile evaluator.  The
7789 result of the evaluator is converted into a string and used as the
7790 expansion of the @code{guile} function in the makefile.
7792 Similarly, there are Guile procedures exposed by @code{make} for use
7793 in Guile scripts.
7795 @menu
7796 * Guile Types::                 Converting Guile types to @code{make} strings.
7797 * Guile Interface::             Invoking @code{make} functions from Guile.
7798 * Guile Example::               Example using Guile in @code{make}.
7799 @end menu
7801 @node Guile Types, Guile Interface, Guile Function, Guile Function
7802 @subsection Conversion of Guile Types
7803 @cindex convert guile types
7804 @cindex guile, conversion of types
7805 @cindex types, conversion of
7807 There is only one ``data type'' in @code{make}: a string.  GNU Guile,
7808 on the other hand, provides a rich variety of different data types.
7809 An important aspect of the interface between @code{make} and GNU Guile
7810 is the conversion of Guile data types into @code{make} strings.
7812 This conversion is relevant in two places: when a makefile invokes the
7813 @code{guile} function to evaluate a Guile expression, the result of
7814 that evaluation must be converted into a make string so it can be
7815 further evaluated by @code{make}.  And secondly, when a Guile script
7816 invokes one of the procedures exported by @code{make} the argument
7817 provided to the procedure must be converted into a string.
7819 The conversion of Guile types into @code{make} strings is as below:
7821 @table @code
7822 @item #f
7823 False is converted into the empty string: in @code{make} conditionals
7824 the empty string is considered false.
7826 @item #t
7827 True is converted to the string @samp{#t}: in @code{make} conditionals
7828 any non-empty string is considered true.
7830 @item symbol
7831 @item number
7832 A symbol or number is converted into the string representation of that
7833 symbol or number.
7835 @item character
7836 A printable character is converted to the same character.
7838 @item string
7839 A string containing only printable characters is converted to the same
7840 string.
7842 @item list
7843 A list is converted recursively according to the above rules.  This
7844 implies that any structured list will be flattened (that is, a result
7845 of @samp{'(a b (c d) e)} will be converted to the @code{make} string
7846 @samp{a b c d e}).
7848 @item other
7849 Any other Guile type results in an error.  In future versions of
7850 @code{make}, other Guile types may be converted.
7852 @end table
7854 The translation of @samp{#f} (to the empty string) and @samp{#t} (to
7855 the non-empty string @samp{#t}) is designed to allow you to use Guile
7856 boolean results directly as @code{make} boolean conditions.  For
7857 example:
7859 @example
7860 $(if $(guile (access? "myfile" R_OK)),$(info myfile exists))
7861 @end example
7863 As a consequence of these conversion rules you must consider the
7864 result of your Guile script, as that result will be converted into a
7865 string and parsed by @code{make}.  If there is no natural result for
7866 the script (that is, the script exists solely for its side-effects),
7867 you should add @samp{#f} as the final expression in order to avoid
7868 syntax errors in your makefile.
7870 @node Guile Interface, Guile Example, Guile Types, Guile Function
7871 @subsection Interfaces from Guile to @code{make}
7872 @cindex make interface to guile
7873 @cindex make procedures in guile
7875 In addition to the @code{guile} function available in makefiles,
7876 @code{make} exposes some procedures for use in your Guile scripts.  At
7877 startup @code{make} creates a new Guile module, @code{gnu make}, and
7878 exports these procedures as public interfaces from that module:
7880 @table @code
7881 @item gmk-expand
7882 This procedure takes a single argument which is converted into a
7883 string.  The string is expanded by @code{make} using normal
7884 @code{make} expansion rules.  The result of the expansion is converted
7885 into a Guile string and provided as the result of the procedure.
7887 @item gmk-eval
7888 This procedure takes a single argument which is converted into a
7889 string.  The string is evaluated by @code{make} as if it were a
7890 makefile.  This is the same capability available via the @code{eval}
7891 function (@pxref{Eval Function}).  The result of the @code{gmk-eval}
7892 procedure is always the empty string.
7894 @item gmk-var
7895 This procedure takes a single argument which is converted into a
7896 string.  The string is assumed to be the name of a @code{make}
7897 variable, which is then expanded.  The expansion is converted into a
7898 string and provided as the result of the procedure.
7900 @end table
7902 @node Guile Example,  , Guile Interface, Guile Function
7903 @subsection Example Using Guile in @code{make}
7904 @cindex Guile example
7905 @cindex example using Guile
7907 Here is a very simple example using GNU Guile to manage writing to a
7908 file.  These Guile procedures simply open a file, allow writing to the
7909 file (one string per line), and close the file.  Note that because we
7910 cannot store complex values such as Guile ports in @code{make}
7911 variables, we'll keep the port as a global variable in the Guile
7912 interpreter.
7914 You can create Guile functions easily using @code{define}/@code{endef}
7915 to create a Guile script, then use the @code{guile} function to
7916 internalize it:
7918 @example
7919 @group
7920 define GUILEIO
7921 ;; A simple Guile IO library for GNU make
7923 (define MKPORT #f)
7925 (define (mkopen name mode)
7926   (set! MKPORT (open-file name mode))
7927   #f)
7929 (define (mkwrite s)
7930   (display s MKPORT)
7931   (newline MKPORT)
7932   #f)
7934 (define (mkclose)
7935   (close-port MKPORT)
7936   #f)
7939 endef
7941 # Internalize the Guile IO functions
7942 $(guile $(GUILEIO))
7943 @end group
7944 @end example
7946 If you have a significant amount of Guile support code, you might
7947 consider keeping it in a different file (e.g., @file{guileio.scm}) and
7948 then loading it in your makefile using the @code{guile} function:
7950 @example
7951 $(guile (load "guileio.scm"))
7952 @end example
7954 An advantage to this method is that when editing @file{guileio.scm},
7955 your editor will understand that this file contains Scheme syntax
7956 rather than makefile syntax.
7958 Now you can use these Guile functions to create files.  Suppose you
7959 need to operate on a very large list, which cannot fit on the command
7960 line, but the utility you're using accepts the list as input as well:
7962 @example
7963 @group
7964 prog: $(PREREQS)
7965         @@$(guile (mkopen "tmp.out" "w")) \
7966          $(foreach X,$^,$(guile (mkwrite "$(X)"))) \
7967          $(guile (mkclose))
7968         $(LINK) < tmp.out
7969 @end group
7970 @end example
7972 A more comprehensive suite of file manipulation procedures is possible
7973 of course.  You could, for example, maintain multiple output files at
7974 the same time by choosing a symbol for each one and using it as the
7975 key to a hash table, where the value is a port, then returning the
7976 symbol to be stored in a @code{make} variable.
7979 @node Running, Implicit Rules, Functions, Top
7980 @chapter How to Run @code{make}
7982 A makefile that says how to recompile a program can be used in more
7983 than one way.  The simplest use is to recompile every file that is out
7984 of date.  Usually, makefiles are written so that if you run
7985 @code{make} with no arguments, it does just that.
7987 But you might want to update only some of the files; you might want to use
7988 a different compiler or different compiler options; you might want just to
7989 find out which files are out of date without changing them.
7991 By giving arguments when you run @code{make}, you can do any of these
7992 things and many others.
7994 @cindex exit status of make
7995 The exit status of @code{make} is always one of three values:
7996 @table @code
7997 @item 0
7998 The exit status is zero if @code{make} is successful.
7999 @item 2
8000 The exit status is two if @code{make} encounters any errors.
8001 It will print messages describing the particular errors.
8002 @item 1
8003 The exit status is one if you use the @samp{-q} flag and @code{make}
8004 determines that some target is not already up to date.
8005 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8006 @end table
8008 @menu
8009 * Makefile Arguments::          How to specify which makefile to use.
8010 * Goals::                       How to use goal arguments to specify which
8011                                   parts of the makefile to use.
8012 * Instead of Execution::        How to use mode flags to specify what
8013                                   kind of thing to do with the recipes
8014                                   in the makefile other than simply
8015                                   execute them.
8016 * Avoiding Compilation::        How to avoid recompiling certain files.
8017 * Overriding::                  How to override a variable to specify
8018                                   an alternate compiler and other things.
8019 * Testing::                     How to proceed past some errors, to
8020                                   test compilation.
8021 * Options Summary::             Summary of Options
8022 @end menu
8024 @node Makefile Arguments, Goals, Running, Running
8025 @section Arguments to Specify the Makefile
8026 @cindex @code{--file}
8027 @cindex @code{--makefile}
8028 @cindex @code{-f}
8030 The way to specify the name of the makefile is with the @samp{-f} or
8031 @samp{--file} option (@samp{--makefile} also works).  For example,
8032 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
8034 If you use the @samp{-f} flag several times and follow each @samp{-f}
8035 with an argument, all the specified files are used jointly as
8036 makefiles.
8038 If you do not use the @samp{-f} or @samp{--file} flag, the default is
8039 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
8040 that order, and use the first of these three which exists or can be made
8041 (@pxref{Makefiles, ,Writing Makefiles}).@refill
8043 @node Goals, Instead of Execution, Makefile Arguments, Running
8044 @section Arguments to Specify the Goals
8045 @cindex goal, how to specify
8047 The @dfn{goals} are the targets that @code{make} should strive ultimately
8048 to update.  Other targets are updated as well if they appear as
8049 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
8051 By default, the goal is the first target in the makefile (not counting
8052 targets that start with a period).  Therefore, makefiles are usually
8053 written so that the first target is for compiling the entire program or
8054 programs they describe.  If the first rule in the makefile has several
8055 targets, only the first target in the rule becomes the default goal, not
8056 the whole list.  You can manage the selection of the default goal from
8057 within your makefile using the @code{.DEFAULT_GOAL} variable
8058 (@pxref{Special Variables, , Other Special Variables}).
8060 You can also specify a different goal or goals with command line
8061 arguments to @code{make}.  Use the name of the goal as an argument.
8062 If you specify several goals, @code{make} processes each of them in
8063 turn, in the order you name them.
8065 Any target in the makefile may be specified as a goal (unless it
8066 starts with @samp{-} or contains an @samp{=}, in which case it will be
8067 parsed as a switch or variable definition, respectively).  Even
8068 targets not in the makefile may be specified, if @code{make} can find
8069 implicit rules that say how to make them.
8071 @vindex MAKECMDGOALS
8072 @code{Make} will set the special variable @code{MAKECMDGOALS} to the
8073 list of goals you specified on the command line.  If no goals were given
8074 on the command line, this variable is empty.  Note that this variable
8075 should be used only in special circumstances.
8077 An example of appropriate use is to avoid including @file{.d} files
8078 during @code{clean} rules (@pxref{Automatic Prerequisites}), so
8079 @code{make} won't create them only to immediately remove them
8080 again:@refill
8082 @example
8083 @group
8084 sources = foo.c bar.c
8086 ifneq ($(MAKECMDGOALS),clean)
8087 include $(sources:.c=.d)
8088 endif
8089 @end group
8090 @end example
8092 One use of specifying a goal is if you want to compile only a part of
8093 the program, or only one of several programs.  Specify as a goal each
8094 file that you wish to remake.  For example, consider a directory containing
8095 several programs, with a makefile that starts like this:
8097 @example
8098 .PHONY: all
8099 all: size nm ld ar as
8100 @end example
8102 If you are working on the program @code{size}, you might want to say
8103 @w{@samp{make size}} so that only the files of that program are recompiled.
8105 Another use of specifying a goal is to make files that are not normally
8106 made.  For example, there may be a file of debugging output, or a
8107 version of the program that is compiled specially for testing, which has
8108 a rule in the makefile but is not a prerequisite of the default goal.
8110 Another use of specifying a goal is to run the recipe associated with
8111 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
8112 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
8113 a phony target named @file{clean} which deletes everything except source
8114 files.  Naturally, this is done only if you request it explicitly with
8115 @w{@samp{make clean}}.  Following is a list of typical phony and empty
8116 target names.  @xref{Standard Targets}, for a detailed list of all the
8117 standard target names which GNU software packages use.
8119 @table @file
8120 @item all
8121 @cindex @code{all} @r{(standard target)}
8122 Make all the top-level targets the makefile knows about.
8124 @item clean
8125 @cindex @code{clean} @r{(standard target)}
8126 Delete all files that are normally created by running @code{make}.
8128 @item mostlyclean
8129 @cindex @code{mostlyclean} @r{(standard target)}
8130 Like @samp{clean}, but may refrain from deleting a few files that people
8131 normally don't want to recompile.  For example, the @samp{mostlyclean}
8132 target for GCC does not delete @file{libgcc.a}, because recompiling it
8133 is rarely necessary and takes a lot of time.
8135 @item distclean
8136 @cindex @code{distclean} @r{(standard target)}
8137 @itemx realclean
8138 @cindex @code{realclean} @r{(standard target)}
8139 @itemx clobber
8140 @cindex @code{clobber} @r{(standard target)}
8141 Any of these targets might be defined to delete @emph{more} files than
8142 @samp{clean} does.  For example, this would delete configuration files
8143 or links that you would normally create as preparation for compilation,
8144 even if the makefile itself cannot create these files.
8146 @item install
8147 @cindex @code{install} @r{(standard target)}
8148 Copy the executable file into a directory that users typically search
8149 for commands; copy any auxiliary files that the executable uses into
8150 the directories where it will look for them.
8152 @item print
8153 @cindex @code{print} @r{(standard target)}
8154 Print listings of the source files that have changed.
8156 @item tar
8157 @cindex @code{tar} @r{(standard target)}
8158 Create a tar file of the source files.
8160 @item shar
8161 @cindex @code{shar} @r{(standard target)}
8162 Create a shell archive (shar file) of the source files.
8164 @item dist
8165 @cindex @code{dist} @r{(standard target)}
8166 Create a distribution file of the source files.  This might
8167 be a tar file, or a shar file, or a compressed version of one of the
8168 above, or even more than one of the above.
8170 @item TAGS
8171 @cindex @code{TAGS} @r{(standard target)}
8172 Update a tags table for this program.
8174 @item check
8175 @cindex @code{check} @r{(standard target)}
8176 @itemx test
8177 @cindex @code{test} @r{(standard target)}
8178 Perform self tests on the program this makefile builds.
8179 @end table
8181 @node Instead of Execution, Avoiding Compilation, Goals, Running
8182 @section Instead of Executing Recipes
8183 @cindex execution, instead of
8184 @cindex recipes, instead of executing
8186 The makefile tells @code{make} how to tell whether a target is up to date,
8187 and how to update each target.  But updating the targets is not always
8188 what you want.  Certain options specify other activities for @code{make}.
8190 @comment Extra blank lines make it print better.
8191 @table @samp
8192 @item -n
8193 @itemx --just-print
8194 @itemx --dry-run
8195 @itemx --recon
8196 @cindex @code{--just-print}
8197 @cindex @code{--dry-run}
8198 @cindex @code{--recon}
8199 @cindex @code{-n}
8201 ``No-op''.  Causes @code{make} to print the recipes that are needed to
8202 make the targets up to date, but not actually execute them.  Note that
8203 some recipes are still executed, even with this flag (@pxref{MAKE
8204 Variable, ,How the @code{MAKE} Variable Works}).  Also any recipes
8205 needed to update included makefiles are still executed
8206 (@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).
8208 @item -t
8209 @itemx --touch
8210 @cindex @code{--touch}
8211 @cindex touching files
8212 @cindex target, touching
8213 @cindex @code{-t}
8215 ``Touch''.  Marks targets as up to date without actually changing
8216 them.  In other words, @code{make} pretends to update the targets but
8217 does not really change their contents; instead only their modified
8218 times are updated.
8220 @item -q
8221 @itemx --question
8222 @cindex @code{--question}
8223 @cindex @code{-q}
8224 @cindex question mode
8226 ``Question''.  Silently check whether the targets are up to date, but
8227 do not execute recipes; the exit code shows whether any updates are
8228 needed.
8230 @item -W @var{file}
8231 @itemx --what-if=@var{file}
8232 @itemx --assume-new=@var{file}
8233 @itemx --new-file=@var{file}
8234 @cindex @code{--what-if}
8235 @cindex @code{-W}
8236 @cindex @code{--assume-new}
8237 @cindex @code{--new-file}
8238 @cindex what if
8239 @cindex files, assuming new
8241 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
8242 files' modification times are recorded by @code{make} as being the present
8243 time, although the actual modification times remain the same.
8244 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
8245 to see what would happen if you were to modify specific files.@refill
8246 @end table
8248 With the @samp{-n} flag, @code{make} prints the recipe that it would
8249 normally execute but usually does not execute it.
8251 With the @samp{-t} flag, @code{make} ignores the recipes in the rules
8252 and uses (in effect) the command @code{touch} for each target that needs to
8253 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
8254 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
8255 the program @code{touch}.  It does the work directly.
8257 With the @samp{-q} flag, @code{make} prints nothing and executes no
8258 recipes, but the exit status code it returns is zero if and only if the
8259 targets to be considered are already up to date.  If the exit status is
8260 one, then some updating needs to be done.  If @code{make} encounters an
8261 error, the exit status is two, so you can distinguish an error from a
8262 target that is not up to date.
8264 It is an error to use more than one of these three flags in the same
8265 invocation of @code{make}.
8267 @cindex +, and recipe execution
8268 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect recipe
8269 lines that begin with @samp{+} characters or contain the strings
8270 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
8271 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
8272 is run regardless of these options.  Other lines in the same rule are
8273 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
8274 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
8276 @cindex phony targets and recipe execution
8277 The @samp{-t} flag prevents phony targets (@pxref{Phony Targets}) from
8278 being updated, unless there are recipe lines beginning with @samp{+}
8279 or containing @samp{$(MAKE)} or @samp{$@{MAKE@}}.
8281 The @samp{-W} flag provides two features:
8283 @itemize @bullet
8284 @item
8285 If you also use the @samp{-n} or @samp{-q} flag, you can see what
8286 @code{make} would do if you were to modify some files.
8288 @item
8289 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
8290 executing recipes, the @samp{-W} flag can direct @code{make} to act as
8291 if some files had been modified, without actually running the recipes
8292 for those files.@refill
8293 @end itemize
8295 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
8296 information about @code{make} or about the makefiles in use
8297 (@pxref{Options Summary, ,Summary of Options}).@refill
8299 @node Avoiding Compilation, Overriding, Instead of Execution, Running
8300 @section Avoiding Recompilation of Some Files
8301 @cindex @code{-o}
8302 @cindex @code{--old-file}
8303 @cindex @code{--assume-old}
8304 @cindex files, assuming old
8305 @cindex files, avoiding recompilation of
8306 @cindex recompilation, avoiding
8308 Sometimes you may have changed a source file but you do not want to
8309 recompile all the files that depend on it.  For example, suppose you add
8310 a macro or a declaration to a header file that many other files depend
8311 on.  Being conservative, @code{make} assumes that any change in the
8312 header file requires recompilation of all dependent files, but you know
8313 that they do not need to be recompiled and you would rather not waste
8314 the time waiting for them to compile.
8316 If you anticipate the problem before changing the header file, you can
8317 use the @samp{-t} flag.  This flag tells @code{make} not to run the
8318 recipes in the rules, but rather to mark the target up to date by
8319 changing its last-modification date.  You would follow this procedure:
8321 @enumerate
8322 @item
8323 Use the command @samp{make} to recompile the source files that really
8324 need recompilation, ensuring that the object files are up-to-date
8325 before you begin.
8327 @item
8328 Make the changes in the header files.
8330 @item
8331 Use the command @samp{make -t} to mark all the object files as
8332 up to date.  The next time you run @code{make}, the changes in the
8333 header files will not cause any recompilation.
8334 @end enumerate
8336 If you have already changed the header file at a time when some files
8337 do need recompilation, it is too late to do this.  Instead, you can
8338 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
8339 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
8340 that the file itself will not be remade, and nothing else will be
8341 remade on its account.  Follow this procedure:
8343 @enumerate
8344 @item
8345 Recompile the source files that need compilation for reasons independent
8346 of the particular header file, with @samp{make -o @var{headerfile}}.
8347 If several header files are involved, use a separate @samp{-o} option
8348 for each header file.
8350 @item
8351 Touch all the object files with @samp{make -t}.
8352 @end enumerate
8354 @node Overriding, Testing, Avoiding Compilation, Running
8355 @section Overriding Variables
8356 @cindex overriding variables with arguments
8357 @cindex variables, overriding with arguments
8358 @cindex command line variables
8359 @cindex variables, command line
8361 An argument that contains @samp{=} specifies the value of a variable:
8362 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
8363 If you specify a value in this way, all ordinary assignments of the same
8364 variable in the makefile are ignored; we say they have been
8365 @dfn{overridden} by the command line argument.
8367 The most common way to use this facility is to pass extra flags to
8368 compilers.  For example, in a properly written makefile, the variable
8369 @code{CFLAGS} is included in each recipe that runs the C compiler, so a
8370 file @file{foo.c} would be compiled something like this:
8372 @example
8373 cc -c $(CFLAGS) foo.c
8374 @end example
8376 Thus, whatever value you set for @code{CFLAGS} affects each compilation
8377 that occurs.  The makefile probably specifies the usual value for
8378 @code{CFLAGS}, like this:
8380 @example
8381 CFLAGS=-g
8382 @end example
8384 Each time you run @code{make}, you can override this value if you
8385 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
8386 compilation will be done with @samp{cc -c -g -O}.  (This also
8387 illustrates how you can use quoting in the shell to enclose spaces and
8388 other special characters in the value of a variable when you override
8389 it.)
8391 The variable @code{CFLAGS} is only one of many standard variables that
8392 exist just so that you can change them this way.  @xref{Implicit
8393 Variables, , Variables Used by Implicit Rules}, for a complete list.
8395 You can also program the makefile to look at additional variables of your
8396 own, giving the user the ability to control other aspects of how the
8397 makefile works by changing the variables.
8399 When you override a variable with a command line argument, you can
8400 define either a recursively-expanded variable or a simply-expanded
8401 variable.  The examples shown above make a recursively-expanded
8402 variable; to make a simply-expanded variable, write @samp{:=} instead
8403 of @samp{=}.  But, unless you want to include a variable reference or
8404 function call in the @emph{value} that you specify, it makes no
8405 difference which kind of variable you create.
8407 There is one way that the makefile can change a variable that you have
8408 overridden.  This is to use the @code{override} directive, which is a line
8409 that looks like this: @samp{override @var{variable} = @var{value}}
8410 (@pxref{Override Directive, ,The @code{override} Directive}).
8412 @node Testing, Options Summary, Overriding, Running
8413 @section Testing the Compilation of a Program
8414 @cindex testing compilation
8415 @cindex compilation, testing
8417 Normally, when an error happens in executing a shell command, @code{make}
8418 gives up immediately, returning a nonzero status.  No further recipes are
8419 executed for any target.  The error implies that the goal cannot be
8420 correctly remade, and @code{make} reports this as soon as it knows.
8422 When you are compiling a program that you have just changed, this is not
8423 what you want.  Instead, you would rather that @code{make} try compiling
8424 every file that can be tried, to show you as many compilation errors
8425 as possible.
8427 @cindex @code{-k}
8428 @cindex @code{--keep-going}
8429 On these occasions, you should use the @samp{-k} or
8430 @samp{--keep-going} flag.  This tells @code{make} to continue to
8431 consider the other prerequisites of the pending targets, remaking them
8432 if necessary, before it gives up and returns nonzero status.  For
8433 example, after an error in compiling one object file, @samp{make -k}
8434 will continue compiling other object files even though it already
8435 knows that linking them will be impossible.  In addition to continuing
8436 after failed shell commands, @samp{make -k} will continue as much as
8437 possible after discovering that it does not know how to make a target
8438 or prerequisite file.  This will always cause an error message, but
8439 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
8440 ,Summary of Options}).@refill
8442 The usual behavior of @code{make} assumes that your purpose is to get the
8443 goals up to date; once @code{make} learns that this is impossible, it might
8444 as well report the failure immediately.  The @samp{-k} flag says that the
8445 real purpose is to test as much as possible of the changes made in the
8446 program, perhaps to find several independent problems so that you can
8447 correct them all before the next attempt to compile.  This is why Emacs'
8448 @kbd{M-x compile} command passes the @samp{-k} flag by default.
8450 @node Options Summary,  , Testing, Running
8451 @section Summary of Options
8452 @cindex options
8453 @cindex flags
8454 @cindex switches
8456 Here is a table of all the options @code{make} understands:
8458 @table @samp
8459 @item -b
8460 @cindex @code{-b}
8461 @itemx -m
8462 @cindex @code{-m}
8463 These options are ignored for compatibility with other versions of @code{make}.
8465 @item -B
8466 @cindex @code{-B}
8467 @itemx --always-make
8468 @cindex @code{--always-make}
8469 Consider all targets out-of-date.  GNU @code{make} proceeds to
8470 consider targets and their prerequisites using the normal algorithms;
8471 however, all targets so considered are always remade regardless of the
8472 status of their prerequisites.  To avoid infinite recursion, if
8473 @code{MAKE_RESTARTS} (@pxref{Special Variables, , Other Special
8474 Variables}) is set to a number greater than 0 this option is disabled
8475 when considering whether to remake makefiles (@pxref{Remaking
8476 Makefiles, , How Makefiles Are Remade}).
8478 @item -C @var{dir}
8479 @cindex @code{-C}
8480 @itemx --directory=@var{dir}
8481 @cindex @code{--directory}
8482 Change to directory @var{dir} before reading the makefiles.  If multiple
8483 @samp{-C} options are specified, each is interpreted relative to the
8484 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
8485 This is typically used with recursive invocations of @code{make}
8486 (@pxref{Recursion, ,Recursive Use of @code{make}}).
8488 @item -d
8489 @cindex @code{-d}
8490 @c Extra blank line here makes the table look better.
8492 Print debugging information in addition to normal processing.  The
8493 debugging information says which files are being considered for
8494 remaking, which file-times are being compared and with what results,
8495 which files actually need to be remade, which implicit rules are
8496 considered and which are applied---everything interesting about how
8497 @code{make} decides what to do.  The @code{-d} option is equivalent to
8498 @samp{--debug=a} (see below).
8500 @item --debug[=@var{options}]
8501 @cindex @code{--debug}
8502 @c Extra blank line here makes the table look better.
8504 Print debugging information in addition to normal processing.  Various
8505 levels and types of output can be chosen.  With no arguments, print the
8506 ``basic'' level of debugging.  Possible arguments are below; only the
8507 first character is considered, and values must be comma- or
8508 space-separated.
8510 @table @code
8511 @item a (@i{all})
8512 All types of debugging output are enabled.  This is equivalent to using
8513 @samp{-d}.
8515 @item b (@i{basic})
8516 Basic debugging prints each target that was found to be out-of-date, and
8517 whether the build was successful or not.
8519 @item v (@i{verbose})
8520 A level above @samp{basic}; includes messages about which makefiles were
8521 parsed, prerequisites that did not need to be rebuilt, etc.  This option
8522 also enables @samp{basic} messages.
8524 @item i (@i{implicit})
8525 Prints messages describing the implicit rule searches for each target.
8526 This option also enables @samp{basic} messages.
8528 @item j (@i{jobs})
8529 Prints messages giving details on the invocation of specific sub-commands.
8531 @item m (@i{makefile})
8532 By default, the above messages are not enabled while trying to remake
8533 the makefiles.  This option enables messages while rebuilding makefiles,
8534 too.  Note that the @samp{all} option does enable this option.  This
8535 option also enables @samp{basic} messages.
8536 @end table
8538 @item -e
8539 @cindex @code{-e}
8540 @itemx --environment-overrides
8541 @cindex @code{--environment-overrides}
8542 Give variables taken from the environment precedence
8543 over variables from makefiles.
8544 @xref{Environment, ,Variables from the Environment}.
8546 @item --eval=@var{string}
8547 @cindex @code{--eval}
8548 @c Extra blank line here makes the table look better.
8550 Evaluate @var{string} as makefile syntax.  This is a command-line
8551 version of the @code{eval} function (@pxref{Eval Function}).  The
8552 evaluation is performed after the default rules and variables have
8553 been defined, but before any makefiles are read.
8555 @item -f @var{file}
8556 @cindex @code{-f}
8557 @itemx --file=@var{file}
8558 @cindex @code{--file}
8559 @itemx --makefile=@var{file}
8560 @cindex @code{--makefile}
8561 Read the file named @var{file} as a makefile.
8562 @xref{Makefiles, ,Writing Makefiles}.
8564 @item -h
8565 @cindex @code{-h}
8566 @itemx --help
8567 @cindex @code{--help}
8568 @c Extra blank line here makes the table look better.
8570 Remind you of the options that @code{make} understands and then exit.
8572 @item -i
8573 @cindex @code{-i}
8574 @itemx --ignore-errors
8575 @cindex @code{--ignore-errors}
8576 Ignore all errors in recipes executed to remake files.
8577 @xref{Errors, ,Errors in Recipes}.
8579 @item -I @var{dir}
8580 @cindex @code{-I}
8581 @itemx --include-dir=@var{dir}
8582 @cindex @code{--include-dir}
8583 Specifies a directory @var{dir} to search for included makefiles.
8584 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
8585 options are used to specify several directories, the directories are
8586 searched in the order specified.
8588 @item -j [@var{jobs}]
8589 @cindex @code{-j}
8590 @itemx --jobs[=@var{jobs}]
8591 @cindex @code{--jobs}
8592 Specifies the number of recipes (jobs) to run simultaneously.  With no
8593 argument, @code{make} runs as many recipes simultaneously as possible.
8594 If there is more than one @samp{-j} option, the last one is effective.
8595 @xref{Parallel, ,Parallel Execution}, for more information on how
8596 recipes are run.  Note that this option is ignored on MS-DOS.
8598 @item -k
8599 @cindex @code{-k}
8600 @itemx --keep-going
8601 @cindex @code{--keep-going}
8602 Continue as much as possible after an error.  While the target that
8603 failed, and those that depend on it, cannot be remade, the other
8604 prerequisites of these targets can be processed all the same.
8605 @xref{Testing, ,Testing the Compilation of a Program}.
8607 @item -l [@var{load}]
8608 @cindex @code{-l}
8609 @itemx --load-average[=@var{load}]
8610 @cindex @code{--load-average}
8611 @itemx --max-load[=@var{load}]
8612 @cindex @code{--max-load}
8613 Specifies that no new recipes should be started if there are other
8614 recipes running and the load average is at least @var{load} (a
8615 floating-point number).  With no argument, removes a previous load
8616 limit.  @xref{Parallel, ,Parallel Execution}.
8618 @item -L
8619 @cindex @code{-L}
8620 @itemx --check-symlink-times
8621 @cindex @code{--check-symlink-times}
8622 On systems that support symbolic links, this option causes @code{make}
8623 to consider the timestamps on any symbolic links in addition to the
8624 timestamp on the file referenced by those links.  When this option is
8625 provided, the most recent timestamp among the file and the symbolic
8626 links is taken as the modification time for this target file.
8628 @item -n
8629 @cindex @code{-n}
8630 @itemx --just-print
8631 @cindex @code{--just-print}
8632 @itemx --dry-run
8633 @cindex @code{--dry-run}
8634 @itemx --recon
8635 @cindex @code{--recon}
8636 @c Extra blank line here makes the table look better.
8638 Print the recipe that would be executed, but do not execute it (except
8639 in certain circumstances).
8640 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8642 @item -o @var{file}
8643 @cindex @code{-o}
8644 @itemx --old-file=@var{file}
8645 @cindex @code{--old-file}
8646 @itemx --assume-old=@var{file}
8647 @cindex @code{--assume-old}
8648 Do not remake the file @var{file} even if it is older than its
8649 prerequisites, and do not remake anything on account of changes in
8650 @var{file}.  Essentially the file is treated as very old and its rules
8651 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
8652 Some Files}.@refill
8654 @item -p
8655 @cindex @code{-p}
8656 @itemx --print-data-base
8657 @cindex @code{--print-data-base}
8658 @cindex data base of @code{make} rules
8659 @cindex predefined rules and variables, printing
8660 Print the data base (rules and variable values) that results from
8661 reading the makefiles; then execute as usual or as otherwise
8662 specified.  This also prints the version information given by the
8663 @samp{-v} switch (see below).  To print the data base without trying
8664 to remake any files, use @w{@samp{make -qp}}.  To print the data base
8665 of predefined rules and variables, use @w{@samp{make -p -f /dev/null}}.
8666 The data base output contains file name and line number information for
8667 recipe and variable definitions, so it can be a useful debugging tool
8668 in complex environments.
8670 @item -q
8671 @cindex @code{-q}
8672 @itemx --question
8673 @cindex @code{--question}
8674 ``Question mode''.  Do not run any recipes, or print anything; just
8675 return an exit status that is zero if the specified targets are already
8676 up to date, one if any remaking is required, or two if an error is
8677 encountered.  @xref{Instead of Execution, ,Instead of Executing
8678 Recipes}.@refill
8680 @item -r
8681 @cindex @code{-r}
8682 @itemx --no-builtin-rules
8683 @cindex @code{--no-builtin-rules}
8684 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
8685 ,Using Implicit Rules}).  You can still define your own by writing
8686 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
8687 Rules}).  The @samp{-r} option also clears out the default list of
8688 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
8689 Rules}).  But you can still define your own suffixes with a rule for
8690 @code{.SUFFIXES}, and then define your own suffix rules.  Note that only
8691 @emph{rules} are affected by the @code{-r} option; default variables
8692 remain in effect (@pxref{Implicit Variables, ,Variables Used by Implicit
8693 Rules}); see the @samp{-R} option below.
8695 @item -R
8696 @cindex @code{-R}
8697 @itemx --no-builtin-variables
8698 @cindex @code{--no-builtin-variables}
8699 Eliminate use of the built-in rule-specific variables (@pxref{Implicit
8700 Variables, ,Variables Used by Implicit Rules}).  You can still define
8701 your own, of course.  The @samp{-R} option also automatically enables
8702 the @samp{-r} option (see above), since it doesn't make sense to have
8703 implicit rules without any definitions for the variables that they use.
8705 @item -s
8706 @cindex @code{-s}
8707 @itemx --silent
8708 @cindex @code{--silent}
8709 @itemx --quiet
8710 @cindex @code{--quiet}
8711 @c Extra blank line here makes the table look better.
8713 Silent operation; do not print the recipes as they are executed.
8714 @xref{Echoing, ,Recipe Echoing}.
8716 @item -S
8717 @cindex @code{-S}
8718 @itemx --no-keep-going
8719 @cindex @code{--no-keep-going}
8720 @itemx --stop
8721 @cindex @code{--stop}
8722 @c Extra blank line here makes the table look better.
8724 Cancel the effect of the @samp{-k} option.  This is never necessary
8725 except in a recursive @code{make} where @samp{-k} might be inherited
8726 from the top-level @code{make} via @code{MAKEFLAGS}
8727 (@pxref{Recursion, ,Recursive Use of @code{make}})
8728 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.@refill
8730 @item -t
8731 @cindex @code{-t}
8732 @itemx --touch
8733 @cindex @code{--touch}
8734 @c Extra blank line here makes the table look better.
8736 Touch files (mark them up to date without really changing them)
8737 instead of running their recipes.  This is used to pretend that the
8738 recipes were done, in order to fool future invocations of
8739 @code{make}.  @xref{Instead of Execution, ,Instead of Executing Recipes}.
8741 @item --trace
8742 @cindex @code{--trace}
8743 @c Extra blank line here makes the table look better.
8745 Print the entire recipe to be executed, even for recipes that are
8746 normally silent (due to @code{.SILENT} or @samp{@@}).  Also print the
8747 makefile name and line number where the recipe was defined.
8749 @item -v
8750 @cindex @code{-v}
8751 @itemx --version
8752 @cindex @code{--version}
8753 Print the version of the @code{make} program plus a copyright, a list
8754 of authors, and a notice that there is no warranty; then exit.
8756 @item -w
8757 @cindex @code{-w}
8758 @itemx --print-directory
8759 @cindex @code{--print-directory}
8760 Print a message containing the working directory both before and after
8761 executing the makefile.  This may be useful for tracking down errors
8762 from complicated nests of recursive @code{make} commands.
8763 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
8764 rarely need to specify this option since @samp{make} does it for you;
8765 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
8767 @itemx --no-print-directory
8768 @cindex @code{--no-print-directory}
8769 Disable printing of the working directory under @code{-w}.
8770 This option is useful when @code{-w} is turned on automatically,
8771 but you do not want to see the extra messages.
8772 @xref{-w Option, ,The @samp{--print-directory} Option}.
8774 @item -W @var{file}
8775 @cindex @code{-W}
8776 @itemx --what-if=@var{file}
8777 @cindex @code{--what-if}
8778 @itemx --new-file=@var{file}
8779 @cindex @code{--new-file}
8780 @itemx --assume-new=@var{file}
8781 @cindex @code{--assume-new}
8782 Pretend that the target @var{file} has just been modified.  When used
8783 with the @samp{-n} flag, this shows you what would happen if you were
8784 to modify that file.  Without @samp{-n}, it is almost the same as
8785 running a @code{touch} command on the given file before running
8786 @code{make}, except that the modification time is changed only in the
8787 imagination of @code{make}.
8788 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8790 @item --warn-undefined-variables
8791 @cindex @code{--warn-undefined-variables}
8792 @cindex variables, warning for undefined
8793 @cindex undefined variables, warning message
8794 Issue a warning message whenever @code{make} sees a reference to an
8795 undefined variable.  This can be helpful when you are trying to debug
8796 makefiles which use variables in complex ways.
8797 @end table
8799 @node Implicit Rules, Archives, Running, Top
8800 @chapter Using Implicit Rules
8801 @cindex implicit rule
8802 @cindex rule, implicit
8804 Certain standard ways of remaking target files are used very often.  For
8805 example, one customary way to make an object file is from a C source file
8806 using the C compiler, @code{cc}.
8808 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
8809 that you do not have to specify them in detail when you want to use
8810 them.  For example, there is an implicit rule for C compilation.  File
8811 names determine which implicit rules are run.  For example, C
8812 compilation typically takes a @file{.c} file and makes a @file{.o} file.
8813 So @code{make} applies the implicit rule for C compilation when it sees
8814 this combination of file name endings.@refill
8816 A chain of implicit rules can apply in sequence; for example, @code{make}
8817 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
8818 @iftex
8819 @xref{Chained Rules, ,Chains of Implicit Rules}.
8820 @end iftex
8822 The built-in implicit rules use several variables in their recipes so
8823 that, by changing the values of the variables, you can change the way the
8824 implicit rule works.  For example, the variable @code{CFLAGS} controls the
8825 flags given to the C compiler by the implicit rule for C compilation.
8826 @iftex
8827 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
8828 @end iftex
8830 You can define your own implicit rules by writing @dfn{pattern rules}.
8831 @iftex
8832 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
8833 @end iftex
8835 @dfn{Suffix rules} are a more limited way to define implicit rules.
8836 Pattern rules are more general and clearer, but suffix rules are
8837 retained for compatibility.
8838 @iftex
8839 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
8840 @end iftex
8842 @menu
8843 * Using Implicit::              How to use an existing implicit rule
8844                                   to get the recipes for updating a file.
8845 * Catalogue of Rules::          A list of built-in implicit rules.
8846 * Implicit Variables::          How to change what predefined rules do.
8847 * Chained Rules::               How to use a chain of implicit rules.
8848 * Pattern Rules::               How to define new implicit rules.
8849 * Last Resort::                 How to define a recipe for rules which
8850                                   cannot find any.
8851 * Suffix Rules::                The old-fashioned style of implicit rule.
8852 * Implicit Rule Search::        The precise algorithm for applying
8853                                   implicit rules.
8854 @end menu
8856 @node Using Implicit, Catalogue of Rules, Implicit Rules, Implicit Rules
8857 @section Using Implicit Rules
8858 @cindex implicit rule, how to use
8859 @cindex rule, implicit, how to use
8861 To allow @code{make} to find a customary method for updating a target
8862 file, all you have to do is refrain from specifying recipes yourself.
8863 Either write a rule with no recipe, or don't write a rule at all.
8864 Then @code{make} will figure out which implicit rule to use based on
8865 which kind of source file exists or can be made.
8867 For example, suppose the makefile looks like this:
8869 @example
8870 foo : foo.o bar.o
8871         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
8872 @end example
8874 @noindent
8875 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
8876 will automatically look for an implicit rule that tells how to update it.
8877 This happens whether or not the file @file{foo.o} currently exists.
8879 If an implicit rule is found, it can supply both a recipe and one or
8880 more prerequisites (the source files).  You would want to write a rule
8881 for @file{foo.o} with no recipe if you need to specify additional
8882 prerequisites, such as header files, that the implicit rule cannot
8883 supply.
8885 Each implicit rule has a target pattern and prerequisite patterns.  There may
8886 be many implicit rules with the same target pattern.  For example, numerous
8887 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
8888 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
8889 that actually applies is the one whose prerequisites exist or can be made.
8890 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
8891 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
8892 compiler; and so on.
8894 Of course, when you write the makefile, you know which implicit rule you
8895 want @code{make} to use, and you know it will choose that one because you
8896 know which possible prerequisite files are supposed to exist.
8897 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
8898 for a catalogue of all the predefined implicit rules.
8900 Above, we said an implicit rule applies if the required prerequisites ``exist
8901 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
8902 the makefile as a target or a prerequisite, or if an implicit rule can be
8903 recursively found for how to make it.  When an implicit prerequisite is the
8904 result of another implicit rule, we say that @dfn{chaining} is occurring.
8905 @xref{Chained Rules, ,Chains of Implicit Rules}.
8907 In general, @code{make} searches for an implicit rule for each target, and
8908 for each double-colon rule, that has no recipe.  A file that is mentioned
8909 only as a prerequisite is considered a target whose rule specifies nothing,
8910 so implicit rule search happens for it.  @xref{Implicit Rule Search, ,Implicit Rule Search Algorithm}, for the
8911 details of how the search is done.
8913 Note that explicit prerequisites do not influence implicit rule search.
8914 For example, consider this explicit rule:
8916 @example
8917 foo.o: foo.p
8918 @end example
8920 @noindent
8921 The prerequisite on @file{foo.p} does not necessarily mean that
8922 @code{make} will remake @file{foo.o} according to the implicit rule to
8923 make an object file, a @file{.o} file, from a Pascal source file, a
8924 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
8925 rule to make an object file from a C source file is used instead,
8926 because it appears before the Pascal rule in the list of predefined
8927 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
8928 Rules}).
8930 If you do not want an implicit rule to be used for a target that has no
8931 recipe, you can give that target an empty recipe by writing a semicolon
8932 (@pxref{Empty Recipes, ,Defining Empty Recipes}).
8934 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
8935 @section Catalogue of Implicit Rules
8936 @cindex implicit rule, predefined
8937 @cindex rule, implicit, predefined
8939 Here is a catalogue of predefined implicit rules which are always
8940 available unless the makefile explicitly overrides or cancels them.
8941 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
8942 canceling or overriding an implicit rule.  The @samp{-r} or
8943 @samp{--no-builtin-rules} option cancels all predefined rules.
8945 This manual only documents the default rules available on POSIX-based
8946 operating systems.  Other operating systems, such as VMS, Windows,
8947 OS/2, etc. may have different sets of default rules.  To see the full
8948 list of default rules and variables available in your version of GNU
8949 @code{make}, run @samp{make -p} in a directory with no makefile.
8951 Not all of these rules will always be defined, even when the @samp{-r}
8952 option is not given.  Many of the predefined implicit rules are
8953 implemented in @code{make} as suffix rules, so which ones will be
8954 defined depends on the @dfn{suffix list} (the list of prerequisites of
8955 the special target @code{.SUFFIXES}).  The default suffix list is:
8956 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
8957 @code{.C}, @code{.cpp}, @code{.p}, @code{.f}, @code{.F}, @code{.m},
8958 @code{.r}, @code{.y}, @code{.l}, @code{.ym}, @code{.lm}, @code{.s},
8959 @code{.S}, @code{.mod}, @code{.sym}, @code{.def}, @code{.h},
8960 @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo}, @code{.texi},
8961 @code{.txinfo}, @code{.w}, @code{.ch} @code{.web}, @code{.sh},
8962 @code{.elc}, @code{.el}.  All of the implicit rules described below
8963 whose prerequisites have one of these suffixes are actually suffix
8964 rules.  If you modify the suffix list, the only predefined suffix
8965 rules in effect will be those named by one or two of the suffixes that
8966 are on the list you specify; rules whose suffixes fail to be on the
8967 list are disabled.  @xref{Suffix Rules, ,Old-Fashioned Suffix Rules},
8968 for full details on suffix rules.
8970 @table @asis
8971 @item Compiling C programs
8972 @cindex C, rule to compile
8973 @pindex cc
8974 @pindex gcc
8975 @pindex .o
8976 @pindex .c
8977 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
8978 a recipe of the form @samp{$(CC) $(CPPFLAGS) $(CFLAGS) -c}.@refill
8980 @item Compiling C++ programs
8981 @cindex C++, rule to compile
8982 @pindex g++
8983 @pindex .cc
8984 @pindex .cpp
8985 @pindex .C
8986 @file{@var{n}.o} is made automatically from @file{@var{n}.cc},
8987 @file{@var{n}.cpp}, or @file{@var{n}.C} with a recipe of the form
8988 @samp{$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c}.  We encourage you to use the
8989 suffix @samp{.cc} for C++ source files instead of @samp{.C}.@refill
8991 @item Compiling Pascal programs
8992 @cindex Pascal, rule to compile
8993 @pindex pc
8994 @pindex .p
8995 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
8996 with the recipe @samp{$(PC) $(PFLAGS) -c}.@refill
8998 @item Compiling Fortran and Ratfor programs
8999 @cindex Fortran, rule to compile
9000 @cindex Ratfor, rule to compile
9001 @pindex f77
9002 @pindex .f
9003 @pindex .r
9004 @pindex .F
9005 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
9006 @file{@var{n}.F} or @file{@var{n}.f} by running the
9007 Fortran compiler.  The precise recipe used is as follows:@refill
9009 @table @samp
9010 @item .f
9011 @samp{$(FC) $(FFLAGS) -c}.
9012 @item .F
9013 @samp{$(FC) $(FFLAGS) $(CPPFLAGS) -c}.
9014 @item .r
9015 @samp{$(FC) $(FFLAGS) $(RFLAGS) -c}.
9016 @end table
9018 @item Preprocessing Fortran and Ratfor programs
9019 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
9020 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
9021 Ratfor or preprocessable Fortran program into a strict Fortran
9022 program.  The precise recipe used is as follows:@refill
9024 @table @samp
9025 @item .F
9026 @samp{$(FC) $(CPPFLAGS) $(FFLAGS) -F}.
9027 @item .r
9028 @samp{$(FC) $(FFLAGS) $(RFLAGS) -F}.
9029 @end table
9031 @item Compiling Modula-2 programs
9032 @cindex Modula-2, rule to compile
9033 @pindex m2c
9034 @pindex .sym
9035 @pindex .def
9036 @pindex .mod
9037 @file{@var{n}.sym} is made from @file{@var{n}.def} with a recipe
9038 of the form @samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}.  @file{@var{n}.o}
9039 is made from @file{@var{n}.mod}; the form is:
9040 @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.@refill
9042 @need 1200
9043 @item Assembling and preprocessing assembler programs
9044 @cindex assembly, rule to compile
9045 @pindex as
9046 @pindex .s
9047 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
9048 running the assembler, @code{as}.  The precise recipe is
9049 @samp{$(AS) $(ASFLAGS)}.@refill
9051 @pindex .S
9052 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
9053 running the C preprocessor, @code{cpp}.  The precise recipe is
9054 @w{@samp{$(CPP) $(CPPFLAGS)}}.
9056 @item Linking a single object file
9057 @cindex linking, predefined rule for
9058 @pindex ld
9059 @pindex .o
9060 @file{@var{n}} is made automatically from @file{@var{n}.o} by running
9061 the linker (usually called @code{ld}) via the C compiler.  The precise
9062 recipe used is @w{@samp{$(CC) $(LDFLAGS) @var{n}.o $(LOADLIBES) $(LDLIBS)}}.
9064 This rule does the right thing for a simple program with only one
9065 source file.  It will also do the right thing if there are multiple
9066 object files (presumably coming from various other source files), one
9067 of which has a name matching that of the executable file.  Thus,
9069 @example
9070 x: y.o z.o
9071 @end example
9073 @noindent
9074 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
9076 @example
9077 @group
9078 cc -c x.c -o x.o
9079 cc -c y.c -o y.o
9080 cc -c z.c -o z.o
9081 cc x.o y.o z.o -o x
9082 rm -f x.o
9083 rm -f y.o
9084 rm -f z.o
9085 @end group
9086 @end example
9088 @noindent
9089 In more complicated cases, such as when there is no object file whose
9090 name derives from the executable file name, you must write an explicit
9091 recipe for linking.
9093 Each kind of file automatically made into @samp{.o} object files will
9094 be automatically linked by using the compiler (@samp{$(CC)},
9095 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
9096 assemble @samp{.s} files) without the @samp{-c} option.  This could be
9097 done by using the @samp{.o} object files as intermediates, but it is
9098 faster to do the compiling and linking in one step, so that's how it's
9099 done.@refill
9101 @item Yacc for C programs
9102 @pindex yacc
9103 @cindex Yacc, rule to run
9104 @pindex .y
9105 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
9106 running Yacc with the recipe @samp{$(YACC) $(YFLAGS)}.
9108 @item Lex for C programs
9109 @pindex lex
9110 @cindex Lex, rule to run
9111 @pindex .l
9112 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
9113 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
9115 @item Lex for Ratfor programs
9116 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
9117 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
9119 The convention of using the same suffix @samp{.l} for all Lex files
9120 regardless of whether they produce C code or Ratfor code makes it
9121 impossible for @code{make} to determine automatically which of the two
9122 languages you are using in any particular case.  If @code{make} is
9123 called upon to remake an object file from a @samp{.l} file, it must
9124 guess which compiler to use.  It will guess the C compiler, because
9125 that is more common.  If you are using Ratfor, make sure @code{make}
9126 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
9127 are using Ratfor exclusively, with no C files, remove @samp{.c} from
9128 the list of implicit rule suffixes with:@refill
9130 @example
9131 @group
9132 .SUFFIXES:
9133 .SUFFIXES: .o .r .f .l @dots{}
9134 @end group
9135 @end example
9137 @item Making Lint Libraries from C, Yacc, or Lex programs
9138 @pindex lint
9139 @cindex @code{lint}, rule to run
9140 @pindex .ln
9141 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
9142 The precise recipe is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.
9143 The same recipe is used on the C code produced from
9144 @file{@var{n}.y} or @file{@var{n}.l}.@refill
9146 @item @TeX{} and Web
9147 @cindex @TeX{}, rule to run
9148 @cindex Web, rule to run
9149 @pindex tex
9150 @pindex cweave
9151 @pindex weave
9152 @pindex tangle
9153 @pindex ctangle
9154 @pindex .dvi
9155 @pindex .tex
9156 @pindex .web
9157 @pindex .w
9158 @pindex .ch
9159 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the recipe
9160 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
9161 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
9162 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
9163 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
9164 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
9165 or can be made) with @samp{$(CTANGLE)}.@refill
9167 @item Texinfo and Info
9168 @cindex Texinfo, rule to format
9169 @cindex Info, rule to format
9170 @pindex texi2dvi
9171 @pindex makeinfo
9172 @pindex .texinfo
9173 @pindex .info
9174 @pindex .texi
9175 @pindex .txinfo
9176 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo},
9177 @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with the recipe
9178 @w{@samp{$(TEXI2DVI) $(TEXI2DVI_FLAGS)}}.  @file{@var{n}.info} is made from
9179 @file{@var{n}.texinfo}, @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with
9180 the recipe @w{@samp{$(MAKEINFO) $(MAKEINFO_FLAGS)}}.
9182 @item RCS
9183 @cindex RCS, rule to extract from
9184 @pindex co
9185 @pindex ,v @r{(RCS file extension)}
9186 Any file @file{@var{n}} is extracted if necessary from an RCS file
9187 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
9188 recipe used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
9189 extracted from RCS if it already exists, even if the RCS file is
9190 newer.  The rules for RCS are terminal
9191 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
9192 so RCS files cannot be generated from another source; they must
9193 actually exist.@refill
9195 @item SCCS
9196 @cindex SCCS, rule to extract from
9197 @pindex get
9198 @pindex s. @r{(SCCS file prefix)}
9199 Any file @file{@var{n}} is extracted if necessary from an SCCS file
9200 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
9201 recipe used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
9202 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
9203 so SCCS files cannot be generated from another source; they must
9204 actually exist.@refill
9206 @pindex .sh
9207 For the benefit of SCCS, a file @file{@var{n}} is copied from
9208 @file{@var{n}.sh} and made executable (by everyone).  This is for
9209 shell scripts that are checked into SCCS.  Since RCS preserves the
9210 execution permission of a file, you do not need to use this feature
9211 with RCS.@refill
9213 We recommend that you avoid using of SCCS.  RCS is widely held to be
9214 superior, and is also free.  By choosing free software in place of
9215 comparable (or inferior) proprietary software, you support the free
9216 software movement.
9217 @end table
9219 Usually, you want to change only the variables listed in the table
9220 above, which are documented in the following section.
9222 However, the recipes in built-in implicit rules actually use
9223 variables such as @code{COMPILE.c}, @code{LINK.p}, and
9224 @code{PREPROCESS.S}, whose values contain the recipes listed above.
9226 @code{make} follows the convention that the rule to compile a
9227 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
9228 Similarly, the rule to produce an executable from a @file{.@var{x}}
9229 file uses @code{LINK.@var{x}}; and the rule to preprocess a
9230 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
9232 @vindex OUTPUT_OPTION
9233 Every rule that produces an object file uses the variable
9234 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
9235 contain @samp{-o $@@}, or to be empty, depending on a compile-time
9236 option.  You need the @samp{-o} option to ensure that the output goes
9237 into the right file when the source file is in a different directory,
9238 as when using @code{VPATH} (@pxref{Directory Search}).  However,
9239 compilers on some systems do not accept a @samp{-o} switch for object
9240 files.  If you use such a system, and use @code{VPATH}, some
9241 compilations will put their output in the wrong place.
9242 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
9243 the value @w{@samp{; mv $*.o $@@}}.
9245 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
9246 @section Variables Used by Implicit Rules
9247 @cindex flags for compilers
9249 The recipes in built-in implicit rules make liberal use of certain
9250 predefined variables.  You can alter the values of these variables in
9251 the makefile, with arguments to @code{make}, or in the environment to
9252 alter how the implicit rules work without redefining the rules
9253 themselves.  You can cancel all variables used by implicit rules with
9254 the @samp{-R} or @samp{--no-builtin-variables} option.
9256 For example, the recipe used to compile a C source file actually says
9257 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
9258 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
9259 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
9260 used for all C compilations performed by the implicit rule.  By redefining
9261 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
9262 each compilation.  @emph{All} implicit rules that do C compilation use
9263 @samp{$(CC)} to get the program name for the compiler and @emph{all}
9264 include @samp{$(CFLAGS)} among the arguments given to the compiler.@refill
9266 The variables used in implicit rules fall into two classes: those that are
9267 names of programs (like @code{CC}) and those that contain arguments for the
9268 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
9269 some command arguments, but it must start with an actual executable program
9270 name.)  If a variable value contains more than one argument, separate them
9271 with spaces.
9273 The following tables describe of some of the more commonly-used predefined
9274 variables.  This list is not exhaustive, and the default values shown here may
9275 not be what @code{make} selects for your environment.  To see the
9276 complete list of predefined variables for your instance of GNU @code{make} you
9277 can run @samp{make -p} in a directory with no makefiles.
9279 Here is a table of some of the more common variables used as names of
9280 programs in built-in rules:
9282 @table @code
9283 @item AR
9284 @vindex AR
9285 Archive-maintaining program; default @samp{ar}.
9286 @pindex ar
9288 @item AS
9289 @vindex AS
9290 Program for compiling assembly files; default @samp{as}.
9291 @pindex as
9293 @item CC
9294 @vindex CC
9295 Program for compiling C programs; default @samp{cc}.
9296 @pindex cc
9298 @item CXX
9299 @vindex CXX
9300 Program for compiling C++ programs; default @samp{g++}.
9301 @pindex g++
9303 @item CPP
9304 @vindex CPP
9305 Program for running the C preprocessor, with results to standard output;
9306 default @samp{$(CC) -E}.
9308 @item FC
9309 @vindex FC
9310 Program for compiling or preprocessing Fortran and Ratfor programs;
9311 default @samp{f77}.
9312 @pindex f77
9314 @item M2C
9315 @vindex M2C
9316 Program to use to compile Modula-2 source code; default @samp{m2c}.
9317 @pindex m2c
9319 @item PC
9320 @vindex PC
9321 Program for compiling Pascal programs; default @samp{pc}.
9322 @pindex pc
9324 @item CO
9325 @vindex CO
9326 Program for extracting a file from RCS; default @samp{co}.
9327 @pindex co
9329 @item GET
9330 @vindex GET
9331 Program for extracting a file from SCCS; default @samp{get}.
9332 @pindex get
9334 @item LEX
9335 @vindex LEX
9336 Program to use to turn Lex grammars into source code; default @samp{lex}.
9337 @pindex lex
9339 @item YACC
9340 @vindex YACC
9341 Program to use to turn Yacc grammars into source code; default @samp{yacc}.
9342 @pindex yacc
9344 @item LINT
9345 @vindex LINT
9346 Program to use to run lint on source code; default @samp{lint}.
9347 @pindex lint
9349 @item MAKEINFO
9350 @vindex MAKEINFO
9351 Program to convert a Texinfo source file into an Info file; default
9352 @samp{makeinfo}.
9353 @pindex makeinfo
9355 @item TEX
9356 @vindex TEX
9357 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
9358 default @samp{tex}.
9359 @pindex tex
9361 @item TEXI2DVI
9362 @vindex TEXI2DVI
9363 Program to make @TeX{} @sc{dvi} files from Texinfo source;
9364 default @samp{texi2dvi}.
9365 @pindex texi2dvi
9367 @item WEAVE
9368 @vindex WEAVE
9369 Program to translate Web into @TeX{}; default @samp{weave}.
9370 @pindex weave
9372 @item CWEAVE
9373 @vindex CWEAVE
9374 Program to translate C Web into @TeX{}; default @samp{cweave}.
9375 @pindex cweave
9377 @item TANGLE
9378 @vindex TANGLE
9379 Program to translate Web into Pascal; default @samp{tangle}.
9380 @pindex tangle
9382 @item CTANGLE
9383 @vindex CTANGLE
9384 Program to translate C Web into C; default @samp{ctangle}.
9385 @pindex ctangle
9387 @item RM
9388 @vindex RM
9389 Command to remove a file; default @samp{rm -f}.
9390 @pindex rm
9391 @end table
9393 Here is a table of variables whose values are additional arguments for the
9394 programs above.  The default values for all of these is the empty
9395 string, unless otherwise noted.
9397 @table @code
9398 @item ARFLAGS
9399 @vindex ARFLAGS
9400 Flags to give the archive-maintaining program; default @samp{rv}.
9402 @item ASFLAGS
9403 @vindex ASFLAGS
9404 Extra flags to give to the assembler (when explicitly
9405 invoked on a @samp{.s} or @samp{.S} file).
9407 @item CFLAGS
9408 @vindex CFLAGS
9409 Extra flags to give to the C compiler.
9411 @item CXXFLAGS
9412 @vindex CXXFLAGS
9413 Extra flags to give to the C++ compiler.
9415 @item COFLAGS
9416 @vindex COFLAGS
9417 Extra flags to give to the RCS @code{co} program.
9419 @item CPPFLAGS
9420 @vindex CPPFLAGS
9421 Extra flags to give to the C preprocessor and programs
9422 that use it (the C and Fortran compilers).
9424 @item FFLAGS
9425 @vindex FFLAGS
9426 Extra flags to give to the Fortran compiler.
9428 @item GFLAGS
9429 @vindex GFLAGS
9430 Extra flags to give to the SCCS @code{get} program.
9432 @item LDFLAGS
9433 @vindex LDFLAGS
9434 Extra flags to give to compilers when they are supposed to invoke the linker,
9435 @samp{ld}.
9437 @item LDLIBS
9438 @vindex LDLIBS
9439 @vindex LOADLIBES
9440 Library flags or names given to compilers when they are supposed to
9441 invoke the linker, @samp{ld}.  @code{LOADLIBES} is a deprecated (but
9442 still supported) alternative to @code{LDLIBS}.
9444 @item LFLAGS
9445 @vindex LFLAGS
9446 Extra flags to give to Lex.
9448 @item YFLAGS
9449 @vindex YFLAGS
9450 Extra flags to give to Yacc.
9452 @item PFLAGS
9453 @vindex PFLAGS
9454 Extra flags to give to the Pascal compiler.
9456 @item RFLAGS
9457 @vindex RFLAGS
9458 Extra flags to give to the Fortran compiler for Ratfor programs.
9460 @item LINTFLAGS
9461 @vindex LINTFLAGS
9462 Extra flags to give to lint.
9463 @end table
9465 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
9466 @section Chains of Implicit Rules
9468 @cindex chains of rules
9469 @cindex rule, implicit, chains of
9470 Sometimes a file can be made by a sequence of implicit rules.  For example,
9471 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
9472 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
9474 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
9475 special searching is required: @code{make} finds that the object file can
9476 be made by C compilation from @file{@var{n}.c}; later on, when considering
9477 how to make @file{@var{n}.c}, the rule for running Yacc is
9478 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
9479 updated.@refill
9481 @cindex intermediate files
9482 @cindex files, intermediate
9483 However, even if @file{@var{n}.c} does not exist and is not mentioned,
9484 @code{make} knows how to envision it as the missing link between
9485 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
9486 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
9487 intermediate file, it is entered in the data base as if it had been
9488 mentioned in the makefile, along with the implicit rule that says how to
9489 create it.@refill
9491 Intermediate files are remade using their rules just like all other
9492 files.  But intermediate files are treated differently in two ways.
9494 The first difference is what happens if the intermediate file does not
9495 exist.  If an ordinary file @var{b} does not exist, and @code{make}
9496 considers a target that depends on @var{b}, it invariably creates
9497 @var{b} and then updates the target from @var{b}.  But if @var{b} is an
9498 intermediate file, then @code{make} can leave well enough alone.  It
9499 won't bother updating @var{b}, or the ultimate target, unless some
9500 prerequisite of @var{b} is newer than that target or there is some other
9501 reason to update that target.
9503 The second difference is that if @code{make} @emph{does} create @var{b}
9504 in order to update something else, it deletes @var{b} later on after it
9505 is no longer needed.  Therefore, an intermediate file which did not
9506 exist before @code{make} also does not exist after @code{make}.
9507 @code{make} reports the deletion to you by printing a @samp{rm -f}
9508 command showing which file it is deleting.
9510 Ordinarily, a file cannot be intermediate if it is mentioned in the
9511 makefile as a target or prerequisite.  However, you can explicitly mark a
9512 file as intermediate by listing it as a prerequisite of the special target
9513 @code{.INTERMEDIATE}.  This takes effect even if the file is mentioned
9514 explicitly in some other way.
9516 @cindex intermediate files, preserving
9517 @cindex preserving intermediate files
9518 @cindex secondary files
9519 You can prevent automatic deletion of an intermediate file by marking it
9520 as a @dfn{secondary} file.  To do this, list it as a prerequisite of the
9521 special target @code{.SECONDARY}.  When a file is secondary, @code{make}
9522 will not create the file merely because it does not already exist, but
9523 @code{make} does not automatically delete the file.  Marking a file as
9524 secondary also marks it as intermediate.
9526 You can list the target pattern of an implicit rule (such as @samp{%.o})
9527 as a prerequisite of the special target @code{.PRECIOUS} to preserve
9528 intermediate files made by implicit rules whose target patterns match
9529 that file's name; see @ref{Interrupts}.@refill
9530 @cindex preserving with @code{.PRECIOUS}
9531 @cindex @code{.PRECIOUS} intermediate files
9533 A chain can involve more than two implicit rules.  For example, it is
9534 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
9535 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
9536 intermediate files that are deleted at the end.@refill
9538 No single implicit rule can appear more than once in a chain.  This means
9539 that @code{make} will not even consider such a ridiculous thing as making
9540 @file{foo} from @file{foo.o.o} by running the linker twice.  This
9541 constraint has the added benefit of preventing any infinite loop in the
9542 search for an implicit rule chain.
9544 There are some special implicit rules to optimize certain cases that would
9545 otherwise be handled by rule chains.  For example, making @file{foo} from
9546 @file{foo.c} could be handled by compiling and linking with separate
9547 chained rules, using @file{foo.o} as an intermediate file.  But what
9548 actually happens is that a special rule for this case does the compilation
9549 and linking with a single @code{cc} command.  The optimized rule is used in
9550 preference to the step-by-step chain because it comes earlier in the
9551 ordering of rules.
9553 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
9554 @section Defining and Redefining Pattern Rules
9556 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
9557 rule looks like an ordinary rule, except that its target contains the
9558 character @samp{%} (exactly one of them).  The target is considered a
9559 pattern for matching file names; the @samp{%} can match any nonempty
9560 substring, while other characters match only themselves.  The prerequisites
9561 likewise use @samp{%} to show how their names relate to the target name.
9563 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
9564 @file{@var{stem}.o} from another file @file{@var{stem}.c}.@refill
9566 Note that expansion using @samp{%} in pattern rules occurs
9567 @strong{after} any variable or function expansions, which take place
9568 when the makefile is read.  @xref{Using Variables, , How to Use
9569 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
9571 @menu
9572 * Pattern Intro::               An introduction to pattern rules.
9573 * Pattern Examples::            Examples of pattern rules.
9574 * Automatic Variables::         How to use automatic variables in the
9575                                   recipe of implicit rules.
9576 * Pattern Match::               How patterns match.
9577 * Match-Anything Rules::        Precautions you should take prior to
9578                                   defining rules that can match any
9579                                   target file whatever.
9580 * Canceling Rules::             How to override or cancel built-in rules.
9581 @end menu
9583 @node Pattern Intro, Pattern Examples, Pattern Rules, Pattern Rules
9584 @subsection Introduction to Pattern Rules
9585 @cindex pattern rule
9586 @cindex rule, pattern
9588 A pattern rule contains the character @samp{%} (exactly one of them)
9589 in the target; otherwise, it looks exactly like an ordinary rule.  The
9590 target is a pattern for matching file names; the @samp{%} matches any
9591 nonempty substring, while other characters match only themselves.
9592 @cindex target pattern, implicit
9593 @cindex @code{%}, in pattern rules
9595 For example, @samp{%.c} as a pattern matches any file name that ends in
9596 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
9597 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
9598 (There must be at least one character to match the @samp{%}.)  The substring
9599 that the @samp{%} matches is called the @dfn{stem}.@refill
9601 @samp{%} in a prerequisite of a pattern rule stands for the same stem
9602 that was matched by the @samp{%} in the target.  In order for the
9603 pattern rule to apply, its target pattern must match the file name
9604 under consideration and all of its prerequisites (after pattern
9605 substitution) must name files that exist or can be made.  These files
9606 become prerequisites of the target.
9607 @cindex prerequisite pattern, implicit
9609 Thus, a rule of the form
9611 @example
9612 %.o : %.c ; @var{recipe}@dots{}
9613 @end example
9615 @noindent
9616 specifies how to make a file @file{@var{n}.o}, with another file
9617 @file{@var{n}.c} as its prerequisite, provided that @file{@var{n}.c}
9618 exists or can be made.
9620 There may also be prerequisites that do not use @samp{%}; such a prerequisite
9621 attaches to every file made by this pattern rule.  These unvarying
9622 prerequisites are useful occasionally.
9624 A pattern rule need not have any prerequisites that contain @samp{%}, or
9625 in fact any prerequisites at all.  Such a rule is effectively a general
9626 wildcard.  It provides a way to make any file that matches the target
9627 pattern.  @xref{Last Resort}.
9629 More than one pattern rule may match a target.  In this case
9630 @code{make} will choose the ``best fit'' rule.  @xref{Pattern Match,
9631 ,How Patterns Match}.
9633 @c !!! The end of of this paragraph should be rewritten.  --bob
9634 Pattern rules may have more than one target.  Unlike normal rules,
9635 this does not act as many different rules with the same prerequisites
9636 and recipe.  If a pattern rule has multiple targets, @code{make} knows
9637 that the rule's recipe is responsible for making all of the targets.
9638 The recipe is executed only once to make all the targets.  When
9639 searching for a pattern rule to match a target, the target patterns of
9640 a rule other than the one that matches the target in need of a rule
9641 are incidental: @code{make} worries only about giving a recipe and
9642 prerequisites to the file presently in question.  However, when this
9643 file's recipe is run, the other targets are marked as having been
9644 updated themselves.
9645 @cindex multiple targets, in pattern rule
9646 @cindex target, multiple in pattern rule
9648 @node Pattern Examples, Automatic Variables, Pattern Intro, Pattern Rules
9649 @subsection Pattern Rule Examples
9651 Here are some examples of pattern rules actually predefined in
9652 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
9653 files:@refill
9655 @example
9656 %.o : %.c
9657         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
9658 @end example
9660 @noindent
9661 defines a rule that can make any file @file{@var{x}.o} from
9662 @file{@var{x}.c}.  The recipe uses the automatic variables @samp{$@@} and
9663 @samp{$<} to substitute the names of the target file and the source file
9664 in each case where the rule applies (@pxref{Automatic Variables}).@refill
9666 Here is a second built-in rule:
9668 @example
9669 % :: RCS/%,v
9670         $(CO) $(COFLAGS) $<
9671 @end example
9673 @noindent
9674 defines a rule that can make any file @file{@var{x}} whatsoever from a
9675 corresponding file @file{@var{x},v} in the sub-directory @file{RCS}.  Since
9676 the target is @samp{%}, this rule will apply to any file whatever, provided
9677 the appropriate prerequisite file exists.  The double colon makes the rule
9678 @dfn{terminal}, which means that its prerequisite may not be an intermediate
9679 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).@refill
9681 @need 500
9682 This pattern rule has two targets:
9684 @example
9685 @group
9686 %.tab.c %.tab.h: %.y
9687         bison -d $<
9688 @end group
9689 @end example
9691 @noindent
9692 @c The following paragraph is rewritten to avoid overfull hboxes
9693 This tells @code{make} that the recipe @samp{bison -d @var{x}.y} will
9694 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
9695 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
9696 and the file @file{scan.o} depends on the file @file{parse.tab.h},
9697 when @file{parse.y} is changed, the recipe @samp{bison -d parse.y}
9698 will be executed only once, and the prerequisites of both
9699 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
9700 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
9701 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
9702 linked from @file{parse.tab.o}, @file{scan.o}, and its other
9703 prerequisites, and it will execute happily ever after.)@refill
9705 @node Automatic Variables, Pattern Match, Pattern Examples, Pattern Rules
9706 @subsection Automatic Variables
9707 @cindex automatic variables
9708 @cindex variables, automatic
9709 @cindex variables, and implicit rule
9711 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
9712 @samp{.o} file: how do you write the @samp{cc} command so that it operates
9713 on the right source file name?  You cannot write the name in the recipe,
9714 because the name is different each time the implicit rule is applied.
9716 What you do is use a special feature of @code{make}, the @dfn{automatic
9717 variables}.  These variables have values computed afresh for each rule that
9718 is executed, based on the target and prerequisites of the rule.  In this
9719 example, you would use @samp{$@@} for the object file name and @samp{$<}
9720 for the source file name.
9722 @cindex automatic variables in prerequisites
9723 @cindex prerequisites, and automatic variables
9724 It's very important that you recognize the limited scope in which
9725 automatic variable values are available: they only have values within
9726 the recipe.  In particular, you cannot use them anywhere
9727 within the target list of a rule; they have no value there and will
9728 expand to the empty string.  Also, they cannot be accessed directly
9729 within the prerequisite list of a rule.  A common mistake is
9730 attempting to use @code{$@@} within the prerequisites list; this will
9731 not work.  However, there is a special feature of GNU @code{make},
9732 secondary expansion (@pxref{Secondary Expansion}), which will allow
9733 automatic variable values to be used in prerequisite lists.
9735 Here is a table of automatic variables:
9737 @table @code
9738 @vindex $@@
9739 @vindex @@ @r{(automatic variable)}
9740 @item $@@
9741 The file name of the target of the rule.  If the target is an archive
9742 member, then @samp{$@@} is the name of the archive file.  In a pattern
9743 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
9744 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
9745 rule's recipe to be run.
9747 @vindex $%
9748 @vindex % @r{(automatic variable)}
9749 @item $%
9750 The target member name, when the target is an archive member.
9751 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
9752 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
9753 empty when the target is not an archive member.
9755 @vindex $<
9756 @vindex < @r{(automatic variable)}
9757 @item $<
9758 The name of the first prerequisite.  If the target got its recipe from
9759 an implicit rule, this will be the first prerequisite added by the
9760 implicit rule (@pxref{Implicit Rules}).
9762 @vindex $?
9763 @vindex ? @r{(automatic variable)}
9764 @item $?
9765 The names of all the prerequisites that are newer than the target, with
9766 spaces between them.  For prerequisites which are archive members, only
9767 the named member is used (@pxref{Archives}).
9768 @cindex prerequisites, list of changed
9769 @cindex list of changed prerequisites
9771 @vindex $^
9772 @vindex ^ @r{(automatic variable)}
9773 @item $^
9774 The names of all the prerequisites, with spaces between them.  For
9775 prerequisites which are archive members, only the named member is used
9776 (@pxref{Archives}).  A target has only one prerequisite on each other file
9777 it depends on, no matter how many times each file is listed as a
9778 prerequisite.  So if you list a prerequisite more than once for a target,
9779 the value of @code{$^} contains just one copy of the name.  This list
9780 does @strong{not} contain any of the order-only prerequisites; for those
9781 see the @samp{$|} variable, below.
9782 @cindex prerequisites, list of all
9783 @cindex list of all prerequisites
9785 @vindex $+
9786 @vindex + @r{(automatic variable)}
9787 @item $+
9788 This is like @samp{$^}, but prerequisites listed more than once are
9789 duplicated in the order they were listed in the makefile.  This is
9790 primarily useful for use in linking commands where it is meaningful to
9791 repeat library file names in a particular order.
9793 @vindex $|
9794 @vindex | @r{(automatic variable)}
9795 @item $|
9796 The names of all the order-only prerequisites, with spaces between
9797 them.
9799 @vindex $*
9800 @vindex * @r{(automatic variable)}
9801 @item $*
9802 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
9803 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
9804 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
9805 useful for constructing names of related files.@refill
9806 @cindex stem, variable for
9808 In a static pattern rule, the stem is part of the file name that matched
9809 the @samp{%} in the target pattern.
9811 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
9812 in that way.  Instead, if the target name ends with a recognized suffix
9813 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
9814 the target name minus the suffix.  For example, if the target name is
9815 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
9816 suffix.  GNU @code{make} does this bizarre thing only for compatibility
9817 with other implementations of @code{make}.  You should generally avoid
9818 using @samp{$*} except in implicit rules or static pattern rules.@refill
9820 If the target name in an explicit rule does not end with a recognized
9821 suffix, @samp{$*} is set to the empty string for that rule.
9822 @end table
9824 @samp{$?} is useful even in explicit rules when you wish to operate on only
9825 the prerequisites that have changed.  For example, suppose that an archive
9826 named @file{lib} is supposed to contain copies of several object files.
9827 This rule copies just the changed object files into the archive:
9829 @example
9830 @group
9831 lib: foo.o bar.o lose.o win.o
9832         ar r lib $?
9833 @end group
9834 @end example
9836 Of the variables listed above, four have values that are single file
9837 names, and three have values that are lists of file names.  These seven
9838 have variants that get just the file's directory name or just the file
9839 name within the directory.  The variant variables' names are formed by
9840 appending @samp{D} or @samp{F}, respectively.  These variants are
9841 semi-obsolete in GNU @code{make} since the functions @code{dir} and
9842 @code{notdir} can be used to get a similar effect (@pxref{File Name
9843 Functions, , Functions for File Names}).  Note, however, that the
9844 @samp{D} variants all omit the trailing slash which always appears in
9845 the output of the @code{dir} function.  Here is a table of the variants:
9847 @table @samp
9848 @vindex $(@@D)
9849 @vindex @@D @r{(automatic variable)}
9850 @item $(@@D)
9851 The directory part of the file name of the target, with the trailing
9852 slash removed.  If the value of @samp{$@@} is @file{dir/foo.o} then
9853 @samp{$(@@D)} is @file{dir}.  This value is @file{.} if @samp{$@@} does
9854 not contain a slash.
9856 @vindex $(@@F)
9857 @vindex @@F @r{(automatic variable)}
9858 @item $(@@F)
9859 The file-within-directory part of the file name of the target.  If the
9860 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
9861 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
9863 @vindex $(*D)
9864 @vindex *D @r{(automatic variable)}
9865 @item $(*D)
9866 @vindex $(*F)
9867 @vindex *F @r{(automatic variable)}
9868 @itemx $(*F)
9869 The directory part and the file-within-directory
9870 part of the stem; @file{dir} and @file{foo} in this example.
9872 @vindex $(%D)
9873 @vindex %D @r{(automatic variable)}
9874 @item $(%D)
9875 @vindex $(%F)
9876 @vindex %F @r{(automatic variable)}
9877 @itemx $(%F)
9878 The directory part and the file-within-directory part of the target
9879 archive member name.  This makes sense only for archive member targets
9880 of the form @file{@var{archive}(@var{member})} and is useful only when
9881 @var{member} may contain a directory name.  (@xref{Archive Members,
9882 ,Archive Members as Targets}.)
9884 @vindex $(<D)
9885 @vindex <D @r{(automatic variable)}
9886 @item $(<D)
9887 @vindex $(<F)
9888 @vindex <F @r{(automatic variable)}
9889 @itemx $(<F)
9890 The directory part and the file-within-directory
9891 part of the first prerequisite.
9893 @vindex $(^D)
9894 @vindex ^D @r{(automatic variable)}
9895 @item $(^D)
9896 @vindex $(^F)
9897 @vindex ^F @r{(automatic variable)}
9898 @itemx $(^F)
9899 Lists of the directory parts and the file-within-directory
9900 parts of all prerequisites.
9902 @vindex $(+D)
9903 @vindex +D @r{(automatic variable)}
9904 @item $(+D)
9905 @vindex $(+F)
9906 @vindex +F @r{(automatic variable)}
9907 @itemx $(+F)
9908 Lists of the directory parts and the file-within-directory
9909 parts of all prerequisites, including multiple instances of duplicated
9910 prerequisites.
9912 @vindex $(?D)
9913 @vindex ?D @r{(automatic variable)}
9914 @item $(?D)
9915 @vindex $(?F)
9916 @vindex ?F @r{(automatic variable)}
9917 @itemx $(?F)
9918 Lists of the directory parts and the file-within-directory parts of
9919 all prerequisites that are newer than the target.
9920 @end table
9922 Note that we use a special stylistic convention when we talk about these
9923 automatic variables; we write ``the value of @samp{$<}'', rather than
9924 @w{``the variable @code{<}''} as we would write for ordinary variables
9925 such as @code{objects} and @code{CFLAGS}.  We think this convention
9926 looks more natural in this special case.  Please do not assume it has a
9927 deep significance; @samp{$<} refers to the variable named @code{<} just
9928 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
9929 You could just as well use @samp{$(<)} in place of @samp{$<}.
9931 @node Pattern Match, Match-Anything Rules, Automatic Variables, Pattern Rules
9932 @subsection How Patterns Match
9934 @cindex stem
9935 A target pattern is composed of a @samp{%} between a prefix and a suffix,
9936 either or both of which may be empty.  The pattern matches a file name only
9937 if the file name starts with the prefix and ends with the suffix, without
9938 overlap.  The text between the prefix and the suffix is called the
9939 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
9940 @file{test.o}, the stem is @samp{test}.  The pattern rule prerequisites are
9941 turned into actual file names by substituting the stem for the character
9942 @samp{%}.  Thus, if in the same example one of the prerequisites is written
9943 as @samp{%.c}, it expands to @samp{test.c}.@refill
9945 When the target pattern does not contain a slash (and it usually does
9946 not), directory names in the file names are removed from the file name
9947 before it is compared with the target prefix and suffix.  After the
9948 comparison of the file name to the target pattern, the directory
9949 names, along with the slash that ends them, are added on to the
9950 prerequisite file names generated from the pattern rule's prerequisite
9951 patterns and the file name.  The directories are ignored only for the
9952 purpose of finding an implicit rule to use, not in the application of
9953 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
9954 with @samp{src/a} as the stem.  When prerequisites are turned into file
9955 names, the directories from the stem are added at the front, while the
9956 rest of the stem is substituted for the @samp{%}.  The stem
9957 @samp{src/a} with a prerequisite pattern @samp{c%r} gives the file name
9958 @file{src/car}.@refill
9960 @cindex pattern rules, order of
9961 @cindex order of pattern rules
9962 A pattern rule can be used to build a given file only if there is a
9963 target pattern that matches the file name, @emph{and} all
9964 prerequisites in that rule either exist or can be built.  The rules
9965 you write take precedence over those that are built in. Note however,
9966 that a rule whose prerequisites actually exist or are mentioned always
9967 takes priority over a rule with prerequisites that must be made by
9968 chaining other implicit rules.
9970 @cindex stem, shortest
9971 It is possible that more than one pattern rule will meet these
9972 criteria.  In that case, @code{make} will choose the rule with the
9973 shortest stem (that is, the pattern that matches most specifically).
9974 If more than one pattern rule has the shortest stem, @code{make} will
9975 choose the first one found in the makefile.
9977 This algorithm results in more specific rules being preferred over
9978 more generic ones; for example:
9980 @example
9981 %.o: %.c
9982         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
9984 %.o : %.f
9985         $(COMPILE.F) $(OUTPUT_OPTION) $<
9987 lib/%.o: lib/%.c
9988         $(CC) -fPIC -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
9989 @end example
9991 Given these rules and asked to build @file{bar.o} where both
9992 @file{bar.c} and @file{bar.f} exist, @code{make} will choose the first
9993 rule and compile @file{bar.c} into @file{bar.o}.  In the same
9994 situation where @file{bar.c} does not exist, then @code{make} will
9995 choose the second rule and compile @file{bar.f} into @file{bar.o}.
9997 If @code{make} is asked to build @file{lib/bar.o} and both
9998 @file{lib/bar.c} and @file{lib/bar.f} exist, then the third rule will
9999 be chosen since the stem for this rule (@samp{bar}) is shorter than
10000 the stem for the first rule (@samp{lib/bar}).  If @file{lib/bar.c}
10001 does not exist then the third rule is not eligible and the second rule
10002 will be used, even though the stem is longer.
10004 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
10005 @subsection Match-Anything Pattern Rules
10007 @cindex match-anything rule
10008 @cindex terminal rule
10009 When a pattern rule's target is just @samp{%}, it matches any file name
10010 whatever.  We call these rules @dfn{match-anything} rules.  They are very
10011 useful, but it can take a lot of time for @code{make} to think about them,
10012 because it must consider every such rule for each file name listed either
10013 as a target or as a prerequisite.
10015 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
10016 would have to consider making it by linking an object file @file{foo.c.o},
10017 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
10018 Pascal compilation-and-linking from @file{foo.c.p}, and many other
10019 possibilities.
10021 We know these possibilities are ridiculous since @file{foo.c} is a C source
10022 file, not an executable.  If @code{make} did consider these possibilities,
10023 it would ultimately reject them, because files such as @file{foo.c.o} and
10024 @file{foo.c.p} would not exist.  But these possibilities are so
10025 numerous that @code{make} would run very slowly if it had to consider
10026 them.@refill
10028 To gain speed, we have put various constraints on the way @code{make}
10029 considers match-anything rules.  There are two different constraints that
10030 can be applied, and each time you define a match-anything rule you must
10031 choose one or the other for that rule.
10033 One choice is to mark the match-anything rule as @dfn{terminal} by defining
10034 it with a double colon.  When a rule is terminal, it does not apply unless
10035 its prerequisites actually exist.  Prerequisites that could be made with
10036 other implicit rules are not good enough.  In other words, no further
10037 chaining is allowed beyond a terminal rule.
10039 For example, the built-in implicit rules for extracting sources from RCS
10040 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
10041 not exist, @code{make} will not even consider trying to make it as an
10042 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
10043 RCS and SCCS files are generally ultimate source files, which should not be
10044 remade from any other files; therefore, @code{make} can save time by not
10045 looking for ways to remake them.@refill
10047 If you do not mark the match-anything rule as terminal, then it is
10048 non-terminal.  A non-terminal match-anything rule cannot apply to a file name
10049 that indicates a specific type of data.  A file name indicates a specific
10050 type of data if some non-match-anything implicit rule target matches it.
10052 For example, the file name @file{foo.c} matches the target for the pattern
10053 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
10054 rule is actually applicable (which happens only if there is a file
10055 @file{foo.y}), the fact that its target matches is enough to prevent
10056 consideration of any non-terminal match-anything rules for the file
10057 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
10058 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
10059 @file{foo.c.p}, etc.@refill
10061 The motivation for this constraint is that non-terminal match-anything
10062 rules are used for making files containing specific types of data (such as
10063 executable files) and a file name with a recognized suffix indicates some
10064 other specific type of data (such as a C source file).
10066 Special built-in dummy pattern rules are provided solely to recognize
10067 certain file names so that non-terminal match-anything rules will not be
10068 considered.  These dummy rules have no prerequisites and no recipes, and
10069 they are ignored for all other purposes.  For example, the built-in
10070 implicit rule
10072 @example
10073 %.p :
10074 @end example
10076 @noindent
10077 exists to make sure that Pascal source files such as @file{foo.p} match a
10078 specific target pattern and thereby prevent time from being wasted looking
10079 for @file{foo.p.o} or @file{foo.p.c}.
10081 Dummy pattern rules such as the one for @samp{%.p} are made for every
10082 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
10084 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
10085 @subsection Canceling Implicit Rules
10087 You can override a built-in implicit rule (or one you have defined
10088 yourself) by defining a new pattern rule with the same target and
10089 prerequisites, but a different recipe.  When the new rule is defined, the
10090 built-in one is replaced.  The new rule's position in the sequence of
10091 implicit rules is determined by where you write the new rule.
10093 You can cancel a built-in implicit rule by defining a pattern rule with the
10094 same target and prerequisites, but no recipe.  For example, the following
10095 would cancel the rule that runs the assembler:
10097 @example
10098 %.o : %.s
10099 @end example
10101 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
10102 @section Defining Last-Resort Default Rules
10103 @cindex last-resort default rules
10104 @cindex default rules, last-resort
10106 You can define a last-resort implicit rule by writing a terminal
10107 match-anything pattern rule with no prerequisites (@pxref{Match-Anything
10108 Rules}).  This is just like any other pattern rule; the only thing
10109 special about it is that it will match any target.  So such a rule's
10110 recipe is used for all targets and prerequisites that have no recipe
10111 of their own and for which no other implicit rule applies.
10113 For example, when testing a makefile, you might not care if the source
10114 files contain real data, only that they exist.  Then you might do this:
10116 @example
10118         touch $@@
10119 @end example
10121 @noindent
10122 to cause all the source files needed (as prerequisites) to be created
10123 automatically.
10125 @findex .DEFAULT
10126 You can instead define a recipe to be used for targets for which there
10127 are no rules at all, even ones which don't specify recipes.  You do
10128 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
10129 recipe is used for all prerequisites which do not appear as targets in
10130 any explicit rule, and for which no implicit rule applies.  Naturally,
10131 there is no @code{.DEFAULT} rule unless you write one.
10133 If you use @code{.DEFAULT} with no recipe or prerequisites:
10135 @example
10136 .DEFAULT:
10137 @end example
10139 @noindent
10140 the recipe previously stored for @code{.DEFAULT} is cleared.  Then
10141 @code{make} acts as if you had never defined @code{.DEFAULT} at all.
10143 If you do not want a target to get the recipe from a match-anything
10144 pattern rule or @code{.DEFAULT}, but you also do not want any recipe
10145 to be run for the target, you can give it an empty recipe
10146 (@pxref{Empty Recipes, ,Defining Empty Recipes}).@refill
10148 You can use a last-resort rule to override part of another makefile.
10149 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
10151 @node Suffix Rules, Implicit Rule Search, Last Resort, Implicit Rules
10152 @section Old-Fashioned Suffix Rules
10153 @cindex old-fashioned suffix rules
10154 @cindex suffix rule
10156 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
10157 @code{make}.  Suffix rules are obsolete because pattern rules are more
10158 general and clearer.  They are supported in GNU @code{make} for
10159 compatibility with old makefiles.  They come in two kinds:
10160 @dfn{double-suffix} and @dfn{single-suffix}.@refill
10162 A double-suffix rule is defined by a pair of suffixes: the target suffix
10163 and the source suffix.  It matches any file whose name ends with the
10164 target suffix.  The corresponding implicit prerequisite is made by
10165 replacing the target suffix with the source suffix in the file name.  A
10166 two-suffix rule whose target and source suffixes are @samp{.o} and
10167 @samp{.c} is equivalent to the pattern rule @samp{%.o : %.c}.
10169 A single-suffix rule is defined by a single suffix, which is the source
10170 suffix.  It matches any file name, and the corresponding implicit
10171 prerequisite name is made by appending the source suffix.  A single-suffix
10172 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
10173 @samp{% : %.c}.
10175 Suffix rule definitions are recognized by comparing each rule's target
10176 against a defined list of known suffixes.  When @code{make} sees a rule
10177 whose target is a known suffix, this rule is considered a single-suffix
10178 rule.  When @code{make} sees a rule whose target is two known suffixes
10179 concatenated, this rule is taken as a double-suffix rule.
10181 For example, @samp{.c} and @samp{.o} are both on the default list of
10182 known suffixes.  Therefore, if you define a rule whose target is
10183 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
10184 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
10185 way to define the rule for compiling a C source file:@refill
10187 @example
10188 .c.o:
10189         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10190 @end example
10192 Suffix rules cannot have any prerequisites of their own.  If they have any,
10193 they are treated as normal files with funny names, not as suffix rules.
10194 Thus, the rule:
10196 @example
10197 .c.o: foo.h
10198         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10199 @end example
10201 @noindent
10202 tells how to make the file @file{.c.o} from the prerequisite file
10203 @file{foo.h}, and is not at all like the pattern rule:
10205 @example
10206 %.o: %.c foo.h
10207         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10208 @end example
10210 @noindent
10211 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
10212 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
10214 Suffix rules with no recipe are also meaningless.  They do not remove
10215 previous rules as do pattern rules with no recipe (@pxref{Canceling
10216 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or
10217 pair of suffixes concatenated as a target in the data base.@refill
10219 @findex .SUFFIXES
10220 The known suffixes are simply the names of the prerequisites of the special
10221 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
10222 for @code{.SUFFIXES} that adds more prerequisites, as in:
10224 @example
10225 .SUFFIXES: .hack .win
10226 @end example
10228 @noindent
10229 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
10231 If you wish to eliminate the default known suffixes instead of just adding
10232 to them, write a rule for @code{.SUFFIXES} with no prerequisites.  By
10233 special dispensation, this eliminates all existing prerequisites of
10234 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
10235 want.  For example,
10237 @example
10238 @group
10239 .SUFFIXES:            # @r{Delete the default suffixes}
10240 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
10241 @end group
10242 @end example
10244 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
10245 list of suffixes to be empty.
10247 @vindex SUFFIXES
10248 The variable @code{SUFFIXES} is defined to the default list of suffixes
10249 before @code{make} reads any makefiles.  You can change the list of suffixes
10250 with a rule for the special target @code{.SUFFIXES}, but that does not alter
10251 this variable.
10253 @node Implicit Rule Search,  , Suffix Rules, Implicit Rules
10254 @section Implicit Rule Search Algorithm
10255 @cindex implicit rule, search algorithm
10256 @cindex search algorithm, implicit rule
10258 Here is the procedure @code{make} uses for searching for an implicit rule
10259 for a target @var{t}.  This procedure is followed for each double-colon
10260 rule with no recipe, for each target of ordinary rules none of which have
10261 a recipe, and for each prerequisite that is not the target of any rule.  It
10262 is also followed recursively for prerequisites that come from implicit
10263 rules, in the search for a chain of rules.
10265 Suffix rules are not mentioned in this algorithm because suffix rules are
10266 converted to equivalent pattern rules once the makefiles have been read in.
10268 For an archive member target of the form
10269 @samp{@var{archive}(@var{member})}, the following algorithm is run
10270 twice, first using the entire target name @var{t}, and second using
10271 @samp{(@var{member})} as the target @var{t} if the first run found no
10272 rule.@refill
10274 @enumerate
10275 @item
10276 Split @var{t} into a directory part, called @var{d}, and the rest,
10277 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
10278 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.@refill
10280 @item
10281 Make a list of all the pattern rules one of whose targets matches
10282 @var{t} or @var{n}.  If the target pattern contains a slash, it is
10283 matched against @var{t}; otherwise, against @var{n}.
10285 @item
10286 If any rule in that list is @emph{not} a match-anything rule, then
10287 remove all non-terminal match-anything rules from the list.
10289 @item
10290 Remove from the list all rules with no recipe.
10292 @item
10293 For each pattern rule in the list:
10295 @enumerate a
10296 @item
10297 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
10298 matched by the @samp{%} in the target pattern.@refill
10300 @item
10301 Compute the prerequisite names by substituting @var{s} for @samp{%}; if
10302 the target pattern does not contain a slash, append @var{d} to
10303 the front of each prerequisite name.@refill
10305 @item
10306 Test whether all the prerequisites exist or ought to exist.  (If a
10307 file name is mentioned in the makefile as a target or as an explicit
10308 prerequisite, then we say it ought to exist.)
10310 If all prerequisites exist or ought to exist, or there are no prerequisites,
10311 then this rule applies.
10312 @end enumerate
10314 @item
10315 If no pattern rule has been found so far, try harder.
10316 For each pattern rule in the list:
10318 @enumerate a
10319 @item
10320 If the rule is terminal, ignore it and go on to the next rule.
10322 @item
10323 Compute the prerequisite names as before.
10325 @item
10326 Test whether all the prerequisites exist or ought to exist.
10328 @item
10329 For each prerequisite that does not exist, follow this algorithm
10330 recursively to see if the prerequisite can be made by an implicit
10331 rule.
10333 @item
10334 If all prerequisites exist, ought to exist, or can be
10335 made by implicit rules, then this rule applies.
10336 @end enumerate
10338 @item
10339 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
10340 applies.  In that case, give @var{t} the same recipe that
10341 @code{.DEFAULT} has.  Otherwise, there is no recipe for @var{t}.
10342 @end enumerate
10344 Once a rule that applies has been found, for each target pattern of
10345 the rule other than the one that matched @var{t} or @var{n}, the
10346 @samp{%} in the pattern is replaced with @var{s} and the resultant
10347 file name is stored until the recipe to remake the target file @var{t}
10348 is executed.  After the recipe is executed, each of these stored file
10349 names are entered into the data base and marked as having been updated
10350 and having the same update status as the file @var{t}.
10352 When the recipe of a pattern rule is executed for @var{t}, the
10353 automatic variables are set corresponding to the target and
10354 prerequisites.  @xref{Automatic Variables}.
10356 @node Archives, Features, Implicit Rules, Top
10357 @chapter Using @code{make} to Update Archive Files
10358 @cindex archive
10360 @dfn{Archive files} are files containing named sub-files called
10361 @dfn{members}; they are maintained with the program @code{ar} and their
10362 main use is as subroutine libraries for linking.
10364 @menu
10365 * Archive Members::             Archive members as targets.
10366 * Archive Update::              The implicit rule for archive member targets.
10367 * Archive Pitfalls::            Dangers to watch out for when using archives.
10368 * Archive Suffix Rules::        You can write a special kind of suffix rule
10369                                   for updating archives.
10370 @end menu
10372 @node Archive Members, Archive Update, Archives, Archives
10373 @section Archive Members as Targets
10374 @cindex archive member targets
10376 An individual member of an archive file can be used as a target or
10377 prerequisite in @code{make}.  You specify the member named @var{member} in
10378 archive file @var{archive} as follows:
10380 @example
10381 @var{archive}(@var{member})
10382 @end example
10384 @noindent
10385 This construct is available only in targets and prerequisites, not in
10386 recipes!  Most programs that you might use in recipes do not support
10387 this syntax and cannot act directly on archive members.  Only
10388 @code{ar} and other programs specifically designed to operate on
10389 archives can do so.  Therefore, valid recipes to update an archive
10390 member target probably must use @code{ar}.  For example, this rule
10391 says to create a member @file{hack.o} in archive @file{foolib} by
10392 copying the file @file{hack.o}:
10394 @example
10395 foolib(hack.o) : hack.o
10396         ar cr foolib hack.o
10397 @end example
10399 In fact, nearly all archive member targets are updated in just this way
10400 and there is an implicit rule to do it for you.  @strong{Please note:} The
10401 @samp{c} flag to @code{ar} is required if the archive file does not
10402 already exist.
10404 To specify several members in the same archive, you can write all the
10405 member names together between the parentheses.  For example:
10407 @example
10408 foolib(hack.o kludge.o)
10409 @end example
10411 @noindent
10412 is equivalent to:
10414 @example
10415 foolib(hack.o) foolib(kludge.o)
10416 @end example
10418 @cindex wildcard, in archive member
10419 You can also use shell-style wildcards in an archive member reference.
10420 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
10421 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
10422 @file{foolib} archive whose names end in @samp{.o}; perhaps
10423 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
10425 @node Archive Update, Archive Pitfalls, Archive Members, Archives
10426 @section Implicit Rule for Archive Member Targets
10428 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
10429 member named @var{m} in the archive file @var{a}.
10431 When @code{make} looks for an implicit rule for such a target, as a special
10432 feature it considers implicit rules that match @file{(@var{m})}, as well as
10433 those that match the actual target @file{@var{a}(@var{m})}.
10435 This causes one special rule whose target is @file{(%)} to match.  This
10436 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
10437 into the archive.  For example, it will update the archive member target
10438 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
10439 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
10441 When this rule is chained with others, the result is very powerful.
10442 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
10443 @samp{(} and @samp{)} from being interpreted specially by the shell) in
10444 the presence of a file @file{bar.c} is enough to cause the following
10445 recipe to be run, even without a makefile:
10447 @example
10448 cc -c bar.c -o bar.o
10449 ar r foo.a bar.o
10450 rm -f bar.o
10451 @end example
10453 @noindent
10454 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
10455 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
10457 Implicit rules such as this one are written using the automatic variable
10458 @samp{$%}.  @xref{Automatic Variables}.
10460 An archive member name in an archive cannot contain a directory name, but
10461 it may be useful in a makefile to pretend that it does.  If you write an
10462 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
10463 automatic updating with this recipe:
10465 @example
10466 ar r foo.a dir/file.o
10467 @end example
10469 @noindent
10470 which has the effect of copying the file @file{dir/file.o} into a member
10471 named @file{file.o}.  In connection with such usage, the automatic variables
10472 @code{%D} and @code{%F} may be useful.
10474 @menu
10475 * Archive Symbols::             How to update archive symbol directories.
10476 @end menu
10478 @node Archive Symbols,  , Archive Update, Archive Update
10479 @subsection Updating Archive Symbol Directories
10480 @cindex @code{__.SYMDEF}
10481 @cindex updating archive symbol directories
10482 @cindex archive symbol directory updating
10483 @cindex symbol directories, updating archive
10484 @cindex directories, updating archive symbol
10486 An archive file that is used as a library usually contains a special member
10487 named @file{__.SYMDEF} that contains a directory of the external symbol
10488 names defined by all the other members.  After you update any other
10489 members, you need to update @file{__.SYMDEF} so that it will summarize the
10490 other members properly.  This is done by running the @code{ranlib} program:
10492 @example
10493 ranlib @var{archivefile}
10494 @end example
10496 Normally you would put this command in the rule for the archive file,
10497 and make all the members of the archive file prerequisites of that rule.
10498 For example,
10500 @example
10501 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
10502         ranlib libfoo.a
10503 @end example
10505 @noindent
10506 The effect of this is to update archive members @file{x.o}, @file{y.o},
10507 etc., and then update the symbol directory member @file{__.SYMDEF} by
10508 running @code{ranlib}.  The rules for updating the members are not shown
10509 here; most likely you can omit them and use the implicit rule which copies
10510 files into the archive, as described in the preceding section.
10512 This is not necessary when using the GNU @code{ar} program, which
10513 updates the @file{__.SYMDEF} member automatically.
10515 @node Archive Pitfalls, Archive Suffix Rules, Archive Update, Archives
10516 @section Dangers When Using Archives
10517 @cindex archive, and parallel execution
10518 @cindex parallel execution, and archive update
10519 @cindex archive, and @code{-j}
10520 @cindex @code{-j}, and archive update
10522 It is important to be careful when using parallel execution (the
10523 @code{-j} switch; @pxref{Parallel, ,Parallel Execution}) and archives.
10524 If multiple @code{ar} commands run at the same time on the same archive
10525 file, they will not know about each other and can corrupt the file.
10527 Possibly a future version of @code{make} will provide a mechanism to
10528 circumvent this problem by serializing all recipes that operate on the
10529 same archive file.  But for the time being, you must either write your
10530 makefiles to avoid this problem in some other way, or not use @code{-j}.
10532 @node Archive Suffix Rules,  , Archive Pitfalls, Archives
10533 @section Suffix Rules for Archive Files
10534 @cindex suffix rule, for archive
10535 @cindex archive, suffix rule for
10536 @cindex library archive, suffix rule for
10537 @cindex @code{.a} (archives)
10539 You can write a special kind of suffix rule for dealing with archive
10540 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
10541 Archive suffix rules are obsolete in GNU @code{make}, because pattern
10542 rules for archives are a more general mechanism (@pxref{Archive
10543 Update}).  But they are retained for compatibility with other
10544 @code{make}s.
10546 To write a suffix rule for archives, you simply write a suffix rule
10547 using the target suffix @samp{.a} (the usual suffix for archive files).
10548 For example, here is the old-fashioned suffix rule to update a library
10549 archive from C source files:
10551 @example
10552 @group
10553 .c.a:
10554         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
10555         $(AR) r $@@ $*.o
10556         $(RM) $*.o
10557 @end group
10558 @end example
10560 @noindent
10561 This works just as if you had written the pattern rule:
10563 @example
10564 @group
10565 (%.o): %.c
10566         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
10567         $(AR) r $@@ $*.o
10568         $(RM) $*.o
10569 @end group
10570 @end example
10572 In fact, this is just what @code{make} does when it sees a suffix rule
10573 with @samp{.a} as the target suffix.  Any double-suffix rule
10574 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
10575 pattern @samp{(%.o)} and a prerequisite pattern of @samp{%.@var{x}}.
10577 Since you might want to use @samp{.a} as the suffix for some other kind
10578 of file, @code{make} also converts archive suffix rules to pattern rules
10579 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
10580 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
10581 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
10583 @node Features, Missing, Archives, Top
10584 @chapter Features of GNU @code{make}
10585 @cindex features of GNU @code{make}
10586 @cindex portability
10587 @cindex compatibility
10589 Here is a summary of the features of GNU @code{make}, for comparison
10590 with and credit to other versions of @code{make}.  We consider the
10591 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
10592 concerned with writing portable makefiles, you should not use the
10593 features of @code{make} listed here, nor the ones in @ref{Missing}.
10595 Many features come from the version of @code{make} in System V.
10597 @itemize @bullet
10598 @item
10599 The @code{VPATH} variable and its special meaning.
10600 @xref{Directory Search, , Searching Directories for Prerequisites}.
10601 This feature exists in System V @code{make}, but is undocumented.
10602 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
10603 @code{VPATH} feature).@refill
10605 @item
10606 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
10607 Allowing multiple files to be included with a single directive is a GNU
10608 extension.
10610 @item
10611 Variables are read from and communicated via the environment.
10612 @xref{Environment, ,Variables from the Environment}.
10614 @item
10615 Options passed through the variable @code{MAKEFLAGS} to recursive
10616 invocations of @code{make}.
10617 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
10619 @item
10620 The automatic variable @code{$%} is set to the member name
10621 in an archive reference.  @xref{Automatic Variables}.
10623 @item
10624 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
10625 and @code{$?} have corresponding forms like @code{$(@@F)} and
10626 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
10627 extension.  @xref{Automatic Variables}.@refill
10629 @item
10630 Substitution variable references.
10631 @xref{Reference, ,Basics of Variable References}.
10633 @item
10634 The command line options @samp{-b} and @samp{-m}, accepted and
10635 ignored.  In System V @code{make}, these options actually do something.
10637 @item
10638 Execution of recursive commands to run @code{make} via the variable
10639 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
10640 @xref{Recursion, ,Recursive Use of @code{make}}.
10642 @item
10643 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
10644 Rules}.  This feature is obsolete in GNU @code{make}, because the
10645 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
10646 Implicit Rules}) allows one pattern rule for installing members in an
10647 archive (@pxref{Archive Update}) to be sufficient.
10649 @item
10650 The arrangement of lines and backslash-newline combinations in
10651 recipes is retained when the recipes are printed, so they appear as
10652 they do in the makefile, except for the stripping of initial
10653 whitespace.
10654 @end itemize
10656 The following features were inspired by various other versions of
10657 @code{make}.  In some cases it is unclear exactly which versions inspired
10658 which others.
10660 @itemize @bullet
10661 @item
10662 Pattern rules using @samp{%}.
10663 This has been implemented in several versions of @code{make}.
10664 We're not sure who invented it first, but it's been spread around a bit.
10665 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.@refill
10667 @item
10668 Rule chaining and implicit intermediate files.
10669 This was implemented by Stu Feldman in his version of @code{make}
10670 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
10671 AT&T Bell Labs in his @code{mk} program (where he terms it
10672 ``transitive closure'').  We do not really know if
10673 we got this from either of them or thought it up ourselves at the
10674 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
10676 @item
10677 The automatic variable @code{$^} containing a list of all prerequisites
10678 of the current target.  We did not invent this, but we have no idea who
10679 did.  @xref{Automatic Variables}.  The automatic variable
10680 @code{$+} is a simple extension of @code{$^}.
10682 @item
10683 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
10684 invented by Andrew Hume in @code{mk}.
10685 @xref{Instead of Execution, ,Instead of Executing Recipes}.
10687 @item
10688 The concept of doing several things at once (parallelism) exists in
10689 many incarnations of @code{make} and similar programs, though not in the
10690 System V or BSD implementations.  @xref{Execution, ,Recipe Execution}.
10692 @item
10693 Modified variable references using pattern substitution come from
10694 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
10695 This functionality was provided in GNU @code{make} by the
10696 @code{patsubst} function before the alternate syntax was implemented
10697 for compatibility with SunOS 4.  It is not altogether clear who
10698 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
10699 4 was released.@refill
10701 @item
10702 The special significance of @samp{+} characters preceding recipe lines
10703 (@pxref{Instead of Execution, ,Instead of Executing Recipes}) is
10704 mandated by @cite{IEEE Standard 1003.2-1992} (POSIX.2).
10706 @item
10707 The @samp{+=} syntax to append to the value of a variable comes from SunOS
10708 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
10710 @item
10711 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
10712 multiple members in a single archive file comes from SunOS 4 @code{make}.
10713 @xref{Archive Members}.
10715 @item
10716 The @code{-include} directive to include makefiles with no error for a
10717 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
10718 @code{make} does not allow multiple makefiles to be specified in one
10719 @code{-include} directive.)  The same feature appears with the name
10720 @code{sinclude} in SGI @code{make} and perhaps others.
10722 @item
10723 The @code{!=} shell assignment operator exists in many BSD of
10724 @code{make} and is purposefully implemented here to behave identically
10725 to those implementations.
10726 @end itemize
10728 The remaining features are inventions new in GNU @code{make}:
10730 @itemize @bullet
10731 @item
10732 Use the @samp{-v} or @samp{--version} option to print version and
10733 copyright information.
10735 @item
10736 Use the @samp{-h} or @samp{--help} option to summarize the options to
10737 @code{make}.
10739 @item
10740 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
10742 @item
10743 Pass command line variable assignments automatically through the
10744 variable @code{MAKE} to recursive @code{make} invocations.
10745 @xref{Recursion, ,Recursive Use of @code{make}}.
10747 @item
10748 Use the @samp{-C} or @samp{--directory} command option to change
10749 directory.  @xref{Options Summary, ,Summary of Options}.
10751 @item
10752 Make verbatim variable definitions with @code{define}.
10753 @xref{Multi-Line, ,Defining Multi-Line Variables}.
10755 @item
10756 Declare phony targets with the special target @code{.PHONY}.
10758 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
10759 different syntax in his @code{mk} program.  This seems to be a case of
10760 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
10762 @item
10763 Manipulate text by calling functions.
10764 @xref{Functions, ,Functions for Transforming Text}.
10766 @item
10767 Use the @samp{-o} or @samp{--old-file}
10768 option to pretend a file's modification-time is old.
10769 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
10771 @item
10772 Conditional execution.
10774 This feature has been implemented numerous times in various versions
10775 of @code{make}; it seems a natural extension derived from the features
10776 of the C preprocessor and similar macro languages and is not a
10777 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
10779 @item
10780 Specify a search path for included makefiles.
10781 @xref{Include, ,Including Other Makefiles}.
10783 @item
10784 Specify extra makefiles to read with an environment variable.
10785 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
10787 @item
10788 Strip leading sequences of @samp{./} from file names, so that
10789 @file{./@var{file}} and @file{@var{file}} are considered to be the
10790 same file.@refill
10792 @item
10793 Use a special search method for library prerequisites written in the
10794 form @samp{-l@var{name}}.
10795 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
10797 @item
10798 Allow suffixes for suffix rules
10799 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
10800 characters.  In other versions of @code{make}, they must begin with
10801 @samp{.} and not contain any @samp{/} characters.
10803 @item
10804 Keep track of the current level of @code{make} recursion using the
10805 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
10807 @item
10808 Provide any goals given on the command line in the variable
10809 @code{MAKECMDGOALS}.  @xref{Goals, ,Arguments to Specify the Goals}.
10811 @item
10812 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
10814 @item
10815 Provide selective @code{vpath} search.
10816 @xref{Directory Search, ,Searching Directories for Prerequisites}.
10818 @item
10819 Provide computed variable references.
10820 @xref{Reference, ,Basics of Variable References}.
10822 @item
10823 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
10824 System V @code{make} has a very, very limited form of this
10825 functionality in that it will check out SCCS files for makefiles.
10827 @item
10828 Various new built-in implicit rules.
10829 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
10831 @item
10832 The built-in variable @samp{MAKE_VERSION} gives the version number of
10833 @code{make}.
10834 @vindex MAKE_VERSION
10835 @end itemize
10837 @node Missing, Makefile Conventions, Features, Top
10838 @chapter Incompatibilities and Missing Features
10839 @cindex incompatibilities
10840 @cindex missing features
10841 @cindex features, missing
10843 The @code{make} programs in various other systems support a few features
10844 that are not implemented in GNU @code{make}.  The POSIX.2 standard
10845 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
10846 require any of these features.@refill
10848 @itemize @bullet
10849 @item
10850 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
10851 of archive file @var{file}.  The member is chosen, not by name, but by
10852 being an object file which defines the linker symbol @var{entry}.@refill
10854 This feature was not put into GNU @code{make} because of the
10855 non-modularity of putting knowledge into @code{make} of the internal
10856 format of archive file symbol tables.
10857 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
10859 @item
10860 Suffixes (used in suffix rules) that end with the character @samp{~}
10861 have a special meaning to System V @code{make};
10862 they refer to the SCCS file that corresponds
10863 to the file one would get without the @samp{~}.  For example, the
10864 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
10865 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
10866 series of such suffix rules is required.
10867 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
10869 In GNU @code{make}, this entire series of cases is handled by two
10870 pattern rules for extraction from SCCS, in combination with the
10871 general feature of rule chaining.
10872 @xref{Chained Rules, ,Chains of Implicit Rules}.
10874 @item
10875 In System V and 4.3 BSD @code{make}, files found by @code{VPATH}
10876 search (@pxref{Directory Search, ,Searching Directories for
10877 Prerequisites}) have their names changed inside recipes.  We feel it
10878 is much cleaner to always use automatic variables and thus make this
10879 feature obsolete.@refill
10881 @item
10882 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
10883 the prerequisites of a rule has the amazingly strange ``feature'' of
10884 expanding to the full name of the @emph{target of that rule}.  We cannot
10885 imagine what went on in the minds of Unix @code{make} developers to do
10886 this; it is utterly inconsistent with the normal definition of @code{$*}.
10887 @vindex * @r{(automatic variable), unsupported bizarre usage}
10889 @item
10890 In some Unix @code{make}s, implicit rule search (@pxref{Implicit
10891 Rules, ,Using Implicit Rules}) is apparently done for @emph{all}
10892 targets, not just those without recipes.  This means you can
10893 do:@refill
10895 @example
10896 @group
10897 foo.o:
10898         cc -c foo.c
10899 @end group
10900 @end example
10902 @noindent
10903 and Unix @code{make} will intuit that @file{foo.o} depends on
10904 @file{foo.c}.@refill
10906 We feel that such usage is broken.  The prerequisite properties of
10907 @code{make} are well-defined (for GNU @code{make}, at least),
10908 and doing such a thing simply does not fit the model.@refill
10910 @item
10911 GNU @code{make} does not include any built-in implicit rules for
10912 compiling or preprocessing EFL programs.  If we hear of anyone who is
10913 using EFL, we will gladly add them.
10915 @item
10916 It appears that in SVR4 @code{make}, a suffix rule can be specified
10917 with no recipe, and it is treated as if it had an empty recipe
10918 (@pxref{Empty Recipes}).  For example:
10920 @example
10921 .c.a:
10922 @end example
10924 @noindent
10925 will override the built-in @file{.c.a} suffix rule.
10927 We feel that it is cleaner for a rule without a recipe to always simply
10928 add to the prerequisite list for the target.  The above example can be
10929 easily rewritten to get the desired behavior in GNU @code{make}:
10931 @example
10932 .c.a: ;
10933 @end example
10935 @item
10936 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
10937 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
10938 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
10939 program it runs returns a nonzero status.  We feel it is cleaner to
10940 write each line of the recipe to stand on its own and not require this
10941 special treatment.
10942 @end itemize
10944 @comment The makefile standards are in a separate file that is also
10945 @comment included by standards.texi.
10946 @include make-stds.texi
10948 @node Quick Reference, Error Messages, Makefile Conventions, Top
10949 @appendix Quick Reference
10951 This appendix summarizes the directives, text manipulation functions,
10952 and special variables which GNU @code{make} understands.
10953 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
10954 and @ref{Options Summary, ,Summary of Options},
10955 for other summaries.
10957 Here is a summary of the directives GNU @code{make} recognizes:
10959 @table @code
10960 @item define @var{variable}
10961 @itemx define @var{variable} =
10962 @itemx define @var{variable} :=
10963 @itemx define @var{variable} +=
10964 @itemx define @var{variable} ?=
10965 @itemx endef
10966 Define multi-line variables.@*
10967 @xref{Multi-Line}.
10969 @item undefine @var{variable}
10970 Undefining variables.@*
10971 @xref{Undefine Directive}.
10973 @item ifdef @var{variable}
10974 @itemx ifndef @var{variable}
10975 @itemx ifeq (@var{a},@var{b})
10976 @itemx ifeq "@var{a}" "@var{b}"
10977 @itemx ifeq '@var{a}' '@var{b}'
10978 @itemx ifneq (@var{a},@var{b})
10979 @itemx ifneq "@var{a}" "@var{b}"
10980 @itemx ifneq '@var{a}' '@var{b}'
10981 @itemx else
10982 @itemx endif
10983 Conditionally evaluate part of the makefile.@*
10984 @xref{Conditionals}.
10986 @item include @var{file}
10987 @itemx -include @var{file}
10988 @itemx sinclude @var{file}
10989 Include another makefile.@*
10990 @xref{Include, ,Including Other Makefiles}.
10992 @item override @var{variable-assignment}
10993 Define a variable, overriding any previous definition, even one from
10994 the command line.@*
10995 @xref{Override Directive, ,The @code{override} Directive}.
10997 @item export
10998 Tell @code{make} to export all variables to child processes by default.@*
10999 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
11001 @item export @var{variable}
11002 @itemx export @var{variable-assignment}
11003 @itemx unexport @var{variable}
11004 Tell @code{make} whether or not to export a particular variable to child
11005 processes.@*
11006 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
11008 @item private @var{variable-assignment}
11009 Do not allow this variable assignment to be inherited by prerequisites.@*
11010 @xref{Suppressing Inheritance}.
11012 @item vpath @var{pattern} @var{path}
11013 Specify a search path for files matching a @samp{%} pattern.@*
11014 @xref{Selective Search, , The @code{vpath} Directive}.
11016 @item vpath @var{pattern}
11017 Remove all search paths previously specified for @var{pattern}.
11019 @item vpath
11020 Remove all search paths previously specified in any @code{vpath}
11021 directive.
11022 @end table
11024 Here is a summary of the built-in functions (@pxref{Functions}):
11026 @table @code
11027 @item $(subst @var{from},@var{to},@var{text})
11028 Replace @var{from} with @var{to} in @var{text}.@*
11029 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11031 @item $(patsubst @var{pattern},@var{replacement},@var{text})
11032 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
11033 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11035 @item $(strip @var{string})
11036 Remove excess whitespace characters from @var{string}.@*
11037 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11039 @item $(findstring @var{find},@var{text})
11040 Locate @var{find} in @var{text}.@*
11041 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11043 @item $(filter @var{pattern}@dots{},@var{text})
11044 Select words in @var{text} that match one of the @var{pattern} words.@*
11045 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11047 @item $(filter-out @var{pattern}@dots{},@var{text})
11048 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
11049 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11051 @item $(sort @var{list})
11052 Sort the words in @var{list} lexicographically, removing duplicates.@*
11053 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11055 @item $(word @var{n},@var{text})
11056 Extract the @var{n}th word (one-origin) of @var{text}.@*
11057 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11059 @item $(words @var{text})
11060 Count the number of words in @var{text}.@*
11061 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11063 @item $(wordlist @var{s},@var{e},@var{text})
11064 Returns the list of words in @var{text} from @var{s} to @var{e}.@*
11065 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11067 @item $(firstword @var{names}@dots{})
11068 Extract the first word of @var{names}.@*
11069 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11071 @item $(lastword @var{names}@dots{})
11072 Extract the last word of @var{names}.@*
11073 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11075 @item $(dir @var{names}@dots{})
11076 Extract the directory part of each file name.@*
11077 @xref{File Name Functions, ,Functions for File Names}.
11079 @item $(notdir @var{names}@dots{})
11080 Extract the non-directory part of each file name.@*
11081 @xref{File Name Functions, ,Functions for File Names}.
11083 @item $(suffix @var{names}@dots{})
11084 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
11085 @xref{File Name Functions, ,Functions for File Names}.
11087 @item $(basename @var{names}@dots{})
11088 Extract the base name (name without suffix) of each file name.@*
11089 @xref{File Name Functions, ,Functions for File Names}.
11091 @item $(addsuffix @var{suffix},@var{names}@dots{})
11092 Append @var{suffix} to each word in @var{names}.@*
11093 @xref{File Name Functions, ,Functions for File Names}.
11095 @item $(addprefix @var{prefix},@var{names}@dots{})
11096 Prepend @var{prefix} to each word in @var{names}.@*
11097 @xref{File Name Functions, ,Functions for File Names}.
11099 @item $(join @var{list1},@var{list2})
11100 Join two parallel lists of words.@*
11101 @xref{File Name Functions, ,Functions for File Names}.
11103 @item $(wildcard @var{pattern}@dots{})
11104 Find file names matching a shell file name pattern (@emph{not} a
11105 @samp{%} pattern).@*
11106 @xref{Wildcard Function, ,The Function @code{wildcard}}.
11108 @item $(realpath @var{names}@dots{})
11109 For each file name in @var{names}, expand to an absolute name that
11110 does not contain any @code{.}, @code{..}, nor symlinks.@*
11111 @xref{File Name Functions, ,Functions for File Names}.
11113 @item $(abspath @var{names}@dots{})
11114 For each file name in @var{names}, expand to an absolute name that
11115 does not contain any @code{.} or @code{..} components, but preserves
11116 symlinks.@*
11117 @xref{File Name Functions, ,Functions for File Names}.
11119 @item $(error @var{text}@dots{})
11120 When this function is evaluated, @code{make} generates a fatal error
11121 with the message @var{text}.@*
11122 @xref{Make Control Functions, ,Functions That Control Make}.
11124 @item $(warning @var{text}@dots{})
11125 When this function is evaluated, @code{make} generates a warning with
11126 the message @var{text}.@*
11127 @xref{Make Control Functions, ,Functions That Control Make}.
11129 @item $(shell @var{command})
11130 Execute a shell command and return its output.@*
11131 @xref{Shell Function, , The @code{shell} Function}.
11133 @item $(origin @var{variable})
11134 Return a string describing how the @code{make} variable @var{variable} was
11135 defined.@*
11136 @xref{Origin Function, , The @code{origin} Function}.
11138 @item $(flavor @var{variable})
11139 Return a string describing the flavor of the @code{make} variable
11140 @var{variable}.@*
11141 @xref{Flavor Function, , The @code{flavor} Function}.
11143 @item $(foreach @var{var},@var{words},@var{text})
11144 Evaluate @var{text} with @var{var} bound to each word in @var{words},
11145 and concatenate the results.@*
11146 @xref{Foreach Function, ,The @code{foreach} Function}.
11148 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
11149 Evaluate the condition @var{condition}; if it's non-empty substitute
11150 the expansion of the @var{then-part} otherwise substitute the
11151 expansion of the @var{else-part}.@*
11152 @xref{Conditional Functions, ,Functions for Conditionals}.
11154 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
11155 Evaluate each condition @var{conditionN} one at a time; substitute the
11156 first non-empty expansion.  If all expansions are empty, substitute
11157 the empty string.@*
11158 @xref{Conditional Functions, ,Functions for Conditionals}.
11160 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
11161 Evaluate each condition @var{conditionN} one at a time; if any
11162 expansion results in the empty string substitute the empty string.  If
11163 all expansions result in a non-empty string, substitute the expansion
11164 of the last @var{condition}.@*
11165 @xref{Conditional Functions, ,Functions for Conditionals}.
11167 @item $(call @var{var},@var{param},@dots{})
11168 Evaluate the variable @var{var} replacing any references to @code{$(1)},
11169 @code{$(2)} with the first, second, etc.@: @var{param} values.@*
11170 @xref{Call Function, ,The @code{call} Function}.
11172 @item $(eval @var{text})
11173 Evaluate @var{text} then read the results as makefile commands.
11174 Expands to the empty string.@*
11175 @xref{Eval Function, ,The @code{eval} Function}.
11177 @item $(value @var{var})
11178 Evaluates to the contents of the variable @var{var}, with no expansion
11179 performed on it.@*
11180 @xref{Value Function, ,The @code{value} Function}.
11181 @end table
11183 Here is a summary of the automatic variables.
11184 @xref{Automatic Variables},
11185 for full information.
11187 @table @code
11188 @item $@@
11189 The file name of the target.
11191 @item $%
11192 The target member name, when the target is an archive member.
11194 @item $<
11195 The name of the first prerequisite.
11197 @item $?
11198 The names of all the prerequisites that are
11199 newer than the target, with spaces between them.
11200 For prerequisites which are archive members, only
11201 the named member is used (@pxref{Archives}).
11203 @item $^
11204 @itemx $+
11205 The names of all the prerequisites, with spaces between them.  For
11206 prerequisites which are archive members, only the named member is used
11207 (@pxref{Archives}).  The value of @code{$^} omits duplicate
11208 prerequisites, while @code{$+} retains them and preserves their order.
11210 @item $*
11211 The stem with which an implicit rule matches
11212 (@pxref{Pattern Match, ,How Patterns Match}).
11214 @item $(@@D)
11215 @itemx $(@@F)
11216 The directory part and the file-within-directory part of @code{$@@}.
11218 @item $(*D)
11219 @itemx $(*F)
11220 The directory part and the file-within-directory part of @code{$*}.
11222 @item $(%D)
11223 @itemx $(%F)
11224 The directory part and the file-within-directory part of @code{$%}.
11226 @item $(<D)
11227 @itemx $(<F)
11228 The directory part and the file-within-directory part of @code{$<}.
11230 @item $(^D)
11231 @itemx $(^F)
11232 The directory part and the file-within-directory part of @code{$^}.
11234 @item $(+D)
11235 @itemx $(+F)
11236 The directory part and the file-within-directory part of @code{$+}.
11238 @item $(?D)
11239 @itemx $(?F)
11240 The directory part and the file-within-directory part of @code{$?}.
11241 @end table
11243 These variables are used specially by GNU @code{make}:
11245 @table @code
11246 @item MAKEFILES
11248 Makefiles to be read on every invocation of @code{make}.@*
11249 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
11251 @item VPATH
11253 Directory search path for files not found in the current directory.@*
11254 @xref{General Search, , @code{VPATH} Search Path for All Prerequisites}.
11256 @item SHELL
11258 The name of the system default command interpreter, usually @file{/bin/sh}.
11259 You can set @code{SHELL} in the makefile to change the shell used to run
11260 recipes.  @xref{Execution, ,Recipe Execution}.  The @code{SHELL}
11261 variable is handled specially when importing from and exporting to the
11262 environment.  @xref{Choosing the Shell}.
11264 @item MAKESHELL
11266 On MS-DOS only, the name of the command interpreter that is to be used
11267 by @code{make}.  This value takes precedence over the value of
11268 @code{SHELL}.  @xref{Execution, ,MAKESHELL variable}.
11270 @item MAKE
11272 The name with which @code{make} was invoked.  Using this variable in
11273 recipes has special meaning.  @xref{MAKE Variable, ,How the
11274 @code{MAKE} Variable Works}.
11276 @item MAKELEVEL
11278 The number of levels of recursion (sub-@code{make}s).@*
11279 @xref{Variables/Recursion}.
11281 @item MAKEFLAGS
11283 The flags given to @code{make}.  You can set this in the environment or
11284 a makefile to set flags.@*
11285 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
11287 It is @emph{never} appropriate to use @code{MAKEFLAGS} directly in a
11288 recipe line: its contents may not be quoted correctly for use in the
11289 shell.  Always allow recursive @code{make}'s to obtain these values
11290 through the environment from its parent.
11292 @item MAKECMDGOALS
11294 The targets given to @code{make} on the command line.  Setting this
11295 variable has no effect on the operation of @code{make}.@*
11296 @xref{Goals, ,Arguments to Specify the Goals}.
11298 @item CURDIR
11300 Set to the pathname of the current working directory (after all
11301 @code{-C} options are processed, if any).  Setting this variable has no
11302 effect on the operation of @code{make}.@*
11303 @xref{Recursion, ,Recursive Use of @code{make}}.
11305 @item SUFFIXES
11307 The default list of suffixes before @code{make} reads any makefiles.
11309 @item .LIBPATTERNS
11310 Defines the naming of the libraries @code{make} searches for, and their
11311 order.@*
11312 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
11313 @end table
11315 @node Error Messages, Complex Makefile, Quick Reference, Top
11316 @comment  node-name,  next,  previous,  up
11317 @appendix Errors Generated by Make
11319 Here is a list of the more common errors you might see generated by
11320 @code{make}, and some information about what they mean and how to fix
11321 them.
11323 Sometimes @code{make} errors are not fatal, especially in the presence
11324 of a @code{-} prefix on a recipe line, or the @code{-k} command line
11325 option.  Errors that are fatal are prefixed with the string
11326 @code{***}.
11328 Error messages are all either prefixed with the name of the program
11329 (usually @samp{make}), or, if the error is found in a makefile, the name
11330 of the file and line number containing the problem.
11332 In the table below, these common prefixes are left off.
11334 @table @samp
11336 @item [@var{foo}] Error @var{NN}
11337 @itemx [@var{foo}] @var{signal description}
11338 These errors are not really @code{make} errors at all.  They mean that a
11339 program that @code{make} invoked as part of a recipe returned a
11340 non-0 error code (@samp{Error @var{NN}}), which @code{make} interprets
11341 as failure, or it exited in some other abnormal fashion (with a
11342 signal of some type).  @xref{Errors, ,Errors in Recipes}.
11344 If no @code{***} is attached to the message, then the sub-process failed
11345 but the rule in the makefile was prefixed with the @code{-} special
11346 character, so @code{make} ignored the error.
11348 @item missing separator.  Stop.
11349 @itemx missing separator (did you mean TAB instead of 8 spaces?).  Stop.
11350 This means that @code{make} could not understand much of anything
11351 about the makefile line it just read.  GNU @code{make} looks for
11352 various separators (@code{:}, @code{=}, recipe prefix characters,
11353 etc.) to indicate what kind of line it's parsing.  This message means
11354 it couldn't find a valid one.
11356 One of the most common reasons for this message is that you (or
11357 perhaps your oh-so-helpful editor, as is the case with many MS-Windows
11358 editors) have attempted to indent your recipe lines with spaces
11359 instead of a tab character.  In this case, @code{make} will use the
11360 second form of the error above.  Remember that every line in the
11361 recipe must begin with a tab character (unless you set
11362 @code{.RECIPEPREFIX}; @pxref{Special Variables}).  Eight spaces do not
11363 count.  @xref{Rule Syntax}.
11365 @item recipe commences before first target.  Stop.
11366 @itemx missing rule before recipe.  Stop.
11367 This means the first thing in the makefile seems to be part of a
11368 recipe: it begins with a recipe prefix character and doesn't appear to
11369 be a legal @code{make} directive (such as a variable assignment).
11370 Recipes must always be associated with a target.
11372 The second form is generated if the line has a semicolon as the first
11373 non-whitespace character; @code{make} interprets this to mean you left
11374 out the "target: prerequisite" section of a rule.  @xref{Rule Syntax}.
11376 @item No rule to make target `@var{xxx}'.
11377 @itemx No rule to make target `@var{xxx}', needed by `@var{yyy}'.
11378 This means that @code{make} decided it needed to build a target, but
11379 then couldn't find any instructions in the makefile on how to do that,
11380 either explicit or implicit (including in the default rules database).
11382 If you want that file to be built, you will need to add a rule to your
11383 makefile describing how that target can be built.  Other possible
11384 sources of this problem are typos in the makefile (if that file name is
11385 wrong) or a corrupted source tree (if that file is not supposed to be
11386 built, but rather only a prerequisite).
11388 @item No targets specified and no makefile found.  Stop.
11389 @itemx No targets.  Stop.
11390 The former means that you didn't provide any targets to be built on the
11391 command line, and @code{make} couldn't find any makefiles to read in.
11392 The latter means that some makefile was found, but it didn't contain any
11393 default goal and none was given on the command line.  GNU @code{make}
11394 has nothing to do in these situations.
11395 @xref{Makefile Arguments, ,Arguments to Specify the Makefile}.@refill
11397 @item Makefile `@var{xxx}' was not found.
11398 @itemx Included makefile `@var{xxx}' was not found.
11399 A makefile specified on the command line (first form) or included
11400 (second form) was not found.
11402 @item warning: overriding recipe for target `@var{xxx}'
11403 @itemx warning: ignoring old recipe for target `@var{xxx}'
11404 GNU @code{make} allows only one recipe to be specified per target
11405 (except for double-colon rules).  If you give a recipe for a target
11406 which already has been defined to have one, this warning is issued and
11407 the second recipe will overwrite the first.  @xref{Multiple Rules,
11408 ,Multiple Rules for One Target}.
11410 @item Circular @var{xxx} <- @var{yyy} dependency dropped.
11411 This means that @code{make} detected a loop in the dependency graph:
11412 after tracing the prerequisite @var{yyy} of target @var{xxx}, and its
11413 prerequisites, etc., one of them depended on @var{xxx} again.
11415 @item Recursive variable `@var{xxx}' references itself (eventually).  Stop.
11416 This means you've defined a normal (recursive) @code{make} variable
11417 @var{xxx} that, when it's expanded, will refer to itself (@var{xxx}).
11418 This is not allowed; either use simply-expanded variables (@code{:=}) or
11419 use the append operator (@code{+=}).  @xref{Using Variables, ,How to Use
11420 Variables}.
11422 @item Unterminated variable reference.  Stop.
11423 This means you forgot to provide the proper closing parenthesis
11424 or brace in your variable or function reference.
11426 @item insufficient arguments to function `@var{xxx}'.  Stop.
11427 This means you haven't provided the requisite number of arguments for
11428 this function.  See the documentation of the function for a description
11429 of its arguments.  @xref{Functions, ,Functions for Transforming Text}.
11431 @item missing target pattern.  Stop.
11432 @itemx multiple target patterns.  Stop.
11433 @itemx target pattern contains no `%'.  Stop.
11434 @itemx mixed implicit and static pattern rules.  Stop.
11435 These are generated for malformed static pattern rules.  The first means
11436 there's no pattern in the target section of the rule; the second means
11437 there are multiple patterns in the target section; the third means
11438 the target doesn't contain a pattern character (@code{%}); and the
11439 fourth means that all three parts of the static pattern rule contain
11440 pattern characters (@code{%})--only the first two parts should.
11441 @xref{Static Usage, ,Syntax of Static Pattern Rules}.
11443 @item warning: -jN forced in submake: disabling jobserver mode.
11444 This warning and the next are generated if @code{make} detects error
11445 conditions related to parallel processing on systems where
11446 sub-@code{make}s can communicate (@pxref{Options/Recursion,
11447 ,Communicating Options to a Sub-@code{make}}).  This warning is
11448 generated if a recursive invocation of a @code{make} process is forced
11449 to have @samp{-j@var{N}} in its argument list (where @var{N} is greater
11450 than one).  This could happen, for example, if you set the @code{MAKE}
11451 environment variable to @samp{make -j2}.  In this case, the
11452 sub-@code{make} doesn't communicate with other @code{make} processes and
11453 will simply pretend it has two jobs of its own.
11455 @item warning: jobserver unavailable: using -j1.  Add `+' to parent make rule.
11456 In order for @code{make} processes to communicate, the parent will pass
11457 information to the child.  Since this could result in problems if the
11458 child process isn't actually a @code{make}, the parent will only do this
11459 if it thinks the child is a @code{make}.  The parent uses the normal
11460 algorithms to determine this (@pxref{MAKE Variable, ,How the @code{MAKE}
11461 Variable Works}).  If the makefile is constructed such that the parent
11462 doesn't know the child is a @code{make} process, then the child will
11463 receive only part of the information necessary.  In this case, the child
11464 will generate this warning message and proceed with its build in a
11465 sequential manner.
11467 @end table
11469 @node Complex Makefile, GNU Free Documentation License, Error Messages, Top
11470 @appendix Complex Makefile Example
11472 Here is the makefile for the GNU @code{tar} program.  This is a
11473 moderately complex makefile.  The first line uses a @code{#!} setting
11474 to allow the makefile to be executed directly.
11476 Because it is the first target, the default goal is @samp{all}.  An
11477 interesting feature of this makefile is that @file{testpad.h} is a
11478 source file automatically created by the @code{testpad} program,
11479 itself compiled from @file{testpad.c}.
11481 If you type @samp{make} or @samp{make all}, then @code{make} creates
11482 the @file{tar} executable, the @file{rmt} daemon that provides
11483 remote tape access, and the @file{tar.info} Info file.
11485 If you type @samp{make install}, then @code{make} not only creates
11486 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
11487 them.
11489 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
11490 files, and the @file{tar}, @file{rmt}, @file{testpad},
11491 @file{testpad.h}, and @file{core} files.
11493 If you type @samp{make distclean}, then @code{make} not only removes
11494 the same files as does @samp{make clean} but also the
11495 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
11496 (Although it is not evident, this makefile (and
11497 @file{config.status}) is generated by the user with the
11498 @code{configure} program, which is provided in the @code{tar}
11499 distribution, but is not shown here.)
11501 If you type @samp{make realclean}, then @code{make} removes the same
11502 files as does @samp{make distclean} and also removes the Info files
11503 generated from @file{tar.texinfo}.
11505 In addition, there are targets @code{shar} and @code{dist} that create
11506 distribution kits.
11508 @example
11509 @group
11510 #!/usr/bin/make -f
11511 # Generated automatically from Makefile.in by configure.
11512 # Un*x Makefile for GNU tar program.
11513 # Copyright (C) 1991 Free Software Foundation, Inc.
11514 @end group
11516 @group
11517 # This program is free software; you can redistribute
11518 # it and/or modify it under the terms of the GNU
11519 # General Public License @dots{}
11520 @dots{}
11521 @dots{}
11522 @end group
11524 SHELL = /bin/sh
11526 #### Start of system configuration section. ####
11528 srcdir = .
11530 @group
11531 # If you use gcc, you should either run the
11532 # fixincludes script that comes with it or else use
11533 # gcc with the -traditional option.  Otherwise ioctl
11534 # calls will be compiled incorrectly on some systems.
11535 CC = gcc -O
11536 YACC = bison -y
11537 INSTALL = /usr/local/bin/install -c
11538 INSTALLDATA = /usr/local/bin/install -c -m 644
11539 @end group
11541 # Things you might add to DEFS:
11542 # -DSTDC_HEADERS        If you have ANSI C headers and
11543 #                       libraries.
11544 # -DPOSIX               If you have POSIX.1 headers and
11545 #                       libraries.
11546 # -DBSD42               If you have sys/dir.h (unless
11547 #                       you use -DPOSIX), sys/file.h,
11548 #                       and st_blocks in `struct stat'.
11549 # -DUSG                 If you have System V/ANSI C
11550 #                       string and memory functions
11551 #                       and headers, sys/sysmacros.h,
11552 #                       fcntl.h, getcwd, no valloc,
11553 #                       and ndir.h (unless
11554 #                       you use -DDIRENT).
11555 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not
11556 #                       include memory.h.
11557 # -DDIRENT              If USG and you have dirent.h
11558 #                       instead of ndir.h.
11559 # -DSIGTYPE=int         If your signal handlers
11560 #                       return int, not void.
11561 # -DNO_MTIO             If you lack sys/mtio.h
11562 #                       (magtape ioctls).
11563 # -DNO_REMOTE           If you do not have a remote shell
11564 #                       or rexec.
11565 # -DUSE_REXEC           To use rexec for remote tape
11566 #                       operations instead of
11567 #                       forking rsh or remsh.
11568 # -DVPRINTF_MISSING     If you lack vprintf function
11569 #                       (but have _doprnt).
11570 # -DDOPRNT_MISSING      If you lack _doprnt function.
11571 #                       Also need to define
11572 #                       -DVPRINTF_MISSING.
11573 # -DFTIME_MISSING       If you lack ftime system call.
11574 # -DSTRSTR_MISSING      If you lack strstr function.
11575 # -DVALLOC_MISSING      If you lack valloc function.
11576 # -DMKDIR_MISSING       If you lack mkdir and
11577 #                       rmdir system calls.
11578 # -DRENAME_MISSING      If you lack rename system call.
11579 # -DFTRUNCATE_MISSING   If you lack ftruncate
11580 #                       system call.
11581 # -DV7                  On Version 7 Unix (not
11582 #                       tested in a long time).
11583 # -DEMUL_OPEN3          If you lack a 3-argument version
11584 #                       of open, and want to emulate it
11585 #                       with system calls you do have.
11586 # -DNO_OPEN3            If you lack the 3-argument open
11587 #                       and want to disable the tar -k
11588 #                       option instead of emulating open.
11589 # -DXENIX               If you have sys/inode.h
11590 #                       and need it 94 to be included.
11592 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
11593         -DVPRINTF_MISSING -DBSD42
11594 # Set this to rtapelib.o unless you defined NO_REMOTE,
11595 # in which case make it empty.
11596 RTAPELIB = rtapelib.o
11597 LIBS =
11598 DEF_AR_FILE = /dev/rmt8
11599 DEFBLOCKING = 20
11601 @group
11602 CDEBUG = -g
11603 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
11604         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
11605         -DDEFBLOCKING=$(DEFBLOCKING)
11606 LDFLAGS = -g
11607 @end group
11609 @group
11610 prefix = /usr/local
11611 # Prefix for each installed program,
11612 # normally empty or `g'.
11613 binprefix =
11615 # The directory to install tar in.
11616 bindir = $(prefix)/bin
11618 # The directory to install the info files in.
11619 infodir = $(prefix)/info
11620 @end group
11622 #### End of system configuration section. ####
11624 @group
11625 SRCS_C  = tar.c create.c extract.c buffer.c   \
11626           getoldopt.c update.c gnu.c mangle.c \
11627           version.c list.c names.c diffarch.c \
11628           port.c wildmat.c getopt.c getopt1.c \
11629           regex.c
11630 SRCS_Y  = getdate.y
11631 SRCS    = $(SRCS_C) $(SRCS_Y)
11632 OBJS    = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB)
11633 @end group
11634 @group
11635 AUX =   README COPYING ChangeLog Makefile.in  \
11636         makefile.pc configure configure.in \
11637         tar.texinfo tar.info* texinfo.tex \
11638         tar.h port.h open3.h getopt.h regex.h \
11639         rmt.h rmt.c rtapelib.c alloca.c \
11640         msd_dir.h msd_dir.c tcexparg.c \
11641         level-0 level-1 backup-specs testpad.c
11642 @end group
11644 .PHONY: all
11645 all:    tar rmt tar.info
11647 @group
11648 tar:    $(OBJS)
11649         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
11650 @end group
11652 @group
11653 rmt:    rmt.c
11654         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
11655 @end group
11657 @group
11658 tar.info: tar.texinfo
11659         makeinfo tar.texinfo
11660 @end group
11662 @group
11663 .PHONY: install
11664 install: all
11665         $(INSTALL) tar $(bindir)/$(binprefix)tar
11666         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
11667         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
11668 @end group
11670 @group
11671 $(OBJS): tar.h port.h testpad.h
11672 regex.o buffer.o tar.o: regex.h
11673 # getdate.y has 8 shift/reduce conflicts.
11674 @end group
11676 @group
11677 testpad.h: testpad
11678         ./testpad
11679 @end group
11681 @group
11682 testpad: testpad.o
11683         $(CC) -o $@@ testpad.o
11684 @end group
11686 @group
11687 TAGS:   $(SRCS)
11688         etags $(SRCS)
11689 @end group
11691 @group
11692 .PHONY: clean
11693 clean:
11694         rm -f *.o tar rmt testpad testpad.h core
11695 @end group
11697 @group
11698 .PHONY: distclean
11699 distclean: clean
11700         rm -f TAGS Makefile config.status
11701 @end group
11703 @group
11704 .PHONY: realclean
11705 realclean: distclean
11706         rm -f tar.info*
11707 @end group
11709 @group
11710 .PHONY: shar
11711 shar: $(SRCS) $(AUX)
11712         shar $(SRCS) $(AUX) | compress \
11713           > tar-`sed -e '/version_string/!d' \
11714                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11715                      -e q
11716                      version.c`.shar.Z
11717 @end group
11719 @group
11720 .PHONY: dist
11721 dist: $(SRCS) $(AUX)
11722         echo tar-`sed \
11723              -e '/version_string/!d' \
11724              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11725              -e q
11726              version.c` > .fname
11727         -rm -rf `cat .fname`
11728         mkdir `cat .fname`
11729         ln $(SRCS) $(AUX) `cat .fname`
11730         tar chZf `cat .fname`.tar.Z `cat .fname`
11731         -rm -rf `cat .fname` .fname
11732 @end group
11734 @group
11735 tar.zoo: $(SRCS) $(AUX)
11736         -rm -rf tmp.dir
11737         -mkdir tmp.dir
11738         -rm tar.zoo
11739         for X in $(SRCS) $(AUX) ; do \
11740             echo $$X ; \
11741             sed 's/$$/^M/' $$X \
11742             > tmp.dir/$$X ; done
11743         cd tmp.dir ; zoo aM ../tar.zoo *
11744         -rm -rf tmp.dir
11745 @end group
11746 @end example
11748 @node GNU Free Documentation License, Concept Index, Complex Makefile, Top
11749 @appendixsec GNU Free Documentation License
11750 @cindex FDL, GNU Free Documentation License
11751 @include fdl.texi
11753 @node Concept Index, Name Index, GNU Free Documentation License, Top
11754 @unnumbered Index of Concepts
11756 @printindex cp
11758 @node Name Index,  , Concept Index, Top
11759 @unnumbered Index of Functions, Variables, & Directives
11761 @printindex fn
11763 @bye