Bump to 4.4
[platform/upstream/make.git] / doc / make.texi
1 \input texinfo                @c -*- Texinfo -*-
2 @c %**start of header
3 @setfilename make.info
4
5 @include version.texi
6 @set EDITION 0.76
7
8 @settitle GNU @code{make}
9 @setchapternewpage odd
10 @c Combine the variable and function indices:
11 @syncodeindex vr fn
12 @c Combine the program and concept indices:
13 @syncodeindex pg cp
14 @c FSF publishers: format makebook.texi instead of using this file directly.
15 @c ISBN confirmed by Jasimin Huang <jasimin@fsf.org> on 25 Mar 2009
16 @set ISBN 1-882114-83-3
17 @c %**end of header
18
19 @copying
20 This file documents the GNU @code{make} utility, which determines
21 automatically which pieces of a large program need to be recompiled,
22 and issues the commands to recompile them.
23
24 This is Edition @value{EDITION}, last updated @value{UPDATED},
25 of @cite{The GNU Make Manual}, for GNU @code{make} version @value{VERSION}.
26
27 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
28 1996, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007,
29 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
30 2020, 2021, 2022 Free Software Foundation, Inc.
31
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.''
40
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
46
47 @c finalout
48
49 @c ISPELL CHECK: done, 10 June 1993 --roland
50 @c ISPELL CHECK: done, 2000-06-25 --Martin Buchholz
51
52
53 @dircategory Software development
54 @direntry
55 * Make: (make).            Remake files automatically.
56 @end direntry
57
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
78
79 @summarycontents
80 @contents
81
82 @ifnottex
83 @node Top, Overview, (dir), (dir)
84 @top GNU @code{make}
85
86 @insertcopying
87 @end ifnottex
88
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 * Extending make::              Using extensions to @code{make}.
104 * Integrating make::            Integrating @code{make} with other tools.
105 * Features::                    Features GNU @code{make} has over other @code{make}s.
106 * Missing::                     What GNU @code{make} lacks from other @code{make}s.
107 * Makefile Conventions::        Conventions for writing makefiles for
108                                   GNU programs.
109 * Quick Reference::             A quick reference for experienced users.
110 * Error Messages::              A list of common errors generated by @code{make}.
111 * Complex Makefile::            A real example of a straightforward,
112                                   but nontrivial, makefile.
113
114 * GNU Free Documentation License::  License for copying this manual.
115 * Concept Index::               Index of Concepts.
116 * Name Index::                  Index of Functions, Variables, & Directives.
117
118 @detailmenu
119  --- The Detailed Node Listing ---
120
121 Overview of @code{make}
122
123 * Preparing::                   Preparing and running @code{make}.
124 * Reading::                     On reading this text.
125 * Bugs::                        Problems and bugs.
126
127 An Introduction to Makefiles
128
129 * Rule Introduction::           What a rule looks like.
130 * Simple Makefile::             A simple makefile.
131 * How Make Works::              How @code{make} processes this makefile.
132 * Variables Simplify::          Variables make makefiles simpler.
133 * make Deduces::                Letting @code{make} deduce the recipes.
134 * Combine By Prerequisite::     Another style of makefile.
135 * Cleanup::                     Rules for cleaning the directory.
136
137 Writing Makefiles
138
139 * Makefile Contents::           What makefiles contain.
140 * Makefile Names::              How to name your makefile.
141 * Include::                     How one makefile can use another makefile.
142 * MAKEFILES Variable::          The environment can specify extra makefiles.
143 * Remaking Makefiles::          How makefiles get remade.
144 * Overriding Makefiles::        How to override part of one makefile
145                                   with another makefile.
146 * Reading Makefiles::           How makefiles are read in.
147 * Parsing Makefiles::           How makefiles are parsed.
148 * Secondary Expansion::         How and when secondary expansion is performed.
149
150 What Makefiles Contain
151
152 * Splitting Lines::             Splitting long lines in makefiles
153
154 Writing Rules
155
156 * Rule Example::                An example explained.
157 * Rule Syntax::                 General syntax explained.
158 * Prerequisite Types::          There are two types of prerequisites.
159 * Wildcards::                   Using wildcard characters such as `*'.
160 * Directory Search::            Searching other directories for source files.
161 * Phony Targets::               Using a target that is not a real file's name.
162 * Force Targets::               You can use a target without a recipe
163                                   or prerequisites to mark other targets
164                                   as phony.
165 * Empty Targets::               When only the date matters and the
166                                   files are empty.
167 * Special Targets::             Targets with special built-in meanings.
168 * Multiple Targets::            When to make use of several targets in a rule.
169 * Multiple Rules::              How to use several rules with the same target.
170 * Static Pattern::              Static pattern rules apply to multiple targets
171                                   and can vary the prerequisites according to
172                                   the target name.
173 * Double-Colon::                How to use a special kind of rule to allow
174                                   several independent rules for one target.
175 * Automatic Prerequisites::     How to automatically generate rules giving
176                                   prerequisites from source files themselves.
177
178 Using Wildcard Characters in File Names
179
180 * Wildcard Examples::           Several examples.
181 * Wildcard Pitfall::            Problems to avoid.
182 * Wildcard Function::           How to cause wildcard expansion where
183                                   it does not normally take place.
184
185 Searching Directories for Prerequisites
186
187 * General Search::              Specifying a search path that applies
188                                   to every prerequisite.
189 * Selective Search::            Specifying a search path
190                                   for a specified class of names.
191 * Search Algorithm::            When and how search paths are applied.
192 * Recipes/Search::              How to write recipes that work together
193                                   with search paths.
194 * Implicit/Search::             How search paths affect implicit rules.
195 * Libraries/Search::            Directory search for link libraries.
196
197 Static Pattern Rules
198
199 * Static Usage::                The syntax of static pattern rules.
200 * Static versus Implicit::      When are they better than implicit rules?
201
202 Writing Recipes in Rules
203
204 * Recipe Syntax::               Recipe syntax features and pitfalls.
205 * Echoing::                     How to control when recipes are echoed.
206 * Execution::                   How recipes are executed.
207 * Parallel::                    How recipes can be executed in parallel.
208 * Errors::                      What happens after a recipe execution error.
209 * Interrupts::                  What happens when a recipe is interrupted.
210 * Recursion::                   Invoking @code{make} from makefiles.
211 * Canned Recipes::              Defining canned recipes.
212 * Empty Recipes::               Defining useful, do-nothing recipes.
213
214 Recipe Syntax
215
216 * Splitting Recipe Lines::      Breaking long recipe lines for readability.
217 * Variables in Recipes::        Using @code{make} variables in recipes.
218
219 Recipe Execution
220
221 * One Shell::                   One shell for all lines in a recipe.
222 * Choosing the Shell::          How @code{make} chooses the shell used
223                                   to run recipes.
224
225 Parallel Execution
226
227 * Parallel Disable::            Disabling parallel execution
228 * Parallel Output::             Handling output during parallel execution
229 * Parallel Input::              Handling input during parallel execution
230
231 Recursive Use of @code{make}
232
233 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
234 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
235 * Options/Recursion::           How to communicate options to a sub-@code{make}.
236 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
237                                   helps debug use of recursive @code{make} commands.
238
239 How to Use Variables
240
241 * Reference::                   How to use the value of a variable.
242 * Flavors::                     Variables come in two flavors.
243 * Advanced::                    Advanced features for referencing a variable.
244 * Values::                      All the ways variables get their values.
245 * Setting::                     How to set a variable in the makefile.
246 * Appending::                   How to append more text to the old value
247                                   of a variable.
248 * Override Directive::          How to set a variable in the makefile even if
249                                   the user has set it with a command argument.
250 * Multi-Line::                  An alternate way to set a variable
251                                   to a multi-line string.
252 * Undefine Directive::          How to undefine a variable so that it appears
253                                   as if it was never set.
254 * Environment::                 Variable values can come from the environment.
255 * Target-specific::             Variable values can be defined on a per-target
256                                   basis.
257 * Pattern-specific::            Target-specific variable values can be applied
258                                   to a group of targets that match a pattern.
259 * Suppressing Inheritance::     Suppress inheritance of variables.
260 * Special Variables::           Variables with special meaning or behavior.
261
262 The Two Flavors of Variables
263
264 * Recursive Assignment::        Setting recursively expanded variables.
265 * Simple Assignment::           Setting simply expanded variables.
266 * Immediate Assignment::        Setting immediately expanded variables.
267 * Conditional Assignment::      Assigning variable values conditionally.
268
269 Advanced Features for Reference to Variables
270
271 * Substitution Refs::           Referencing a variable with
272                                   substitutions on the value.
273 * Computed Names::              Computing the name of the variable to refer to.
274
275 Conditional Parts of Makefiles
276
277 * Conditional Example::         Example of a conditional
278 * Conditional Syntax::          The syntax of conditionals.
279 * Testing Flags::               Conditionals that test flags.
280
281 Functions for Transforming Text
282
283 * Syntax of Functions::         How to write a function call.
284 * Text Functions::              General-purpose text manipulation functions.
285 * File Name Functions::         Functions for manipulating file names.
286 * Conditional Functions::       Functions that implement conditions.
287 * Let Function::                Local variables.
288 * Foreach Function::            Repeat some text with controlled variation.
289 * File Function::               Write text to a file.
290 * Call Function::               Expand a user-defined function.
291 * Value Function::              Return the un-expanded value of a variable.
292 * Eval Function::               Evaluate the arguments as makefile syntax.
293 * Origin Function::             Find where a variable got its value.
294 * Flavor Function::             Find out the flavor of a variable.
295 * Make Control Functions::      Functions that control how make runs.
296 * Shell Function::              Substitute the output of a shell command.
297 * Guile Function::              Use GNU Guile embedded scripting language.
298
299 How to Run @code{make}
300
301 * Makefile Arguments::          How to specify which makefile to use.
302 * Goals::                       How to use goal arguments to specify which
303                                   parts of the makefile to use.
304 * Instead of Execution::        How to use mode flags to specify what
305                                   kind of thing to do with the recipes
306                                   in the makefile other than simply
307                                   execute them.
308 * Avoiding Compilation::        How to avoid recompiling certain files.
309 * Overriding::                  How to override a variable to specify
310                                   an alternate compiler and other things.
311 * Testing::                     How to proceed past some errors, to
312                                   test compilation.
313 * Temporary Files::             Where @code{make} keeps its temporary files.
314 * Options Summary::             Summary of Options
315
316 Using Implicit Rules
317
318 * Using Implicit::              How to use an existing implicit rule
319                                   to get the recipes for updating a file.
320 * Catalogue of Rules::          A list of built-in rules.
321 * Implicit Variables::          How to change what predefined rules do.
322 * Chained Rules::               How to use a chain of implicit rules.
323 * Pattern Rules::               How to define new implicit rules.
324 * Last Resort::                 How to define a recipe for rules which
325                                   cannot find any.
326 * Suffix Rules::                The old-fashioned style of implicit rule.
327 * Implicit Rule Search::        The precise algorithm for applying
328                                   implicit rules.
329
330 Defining and Redefining Pattern Rules
331
332 * Pattern Intro::               An introduction to pattern rules.
333 * Pattern Examples::            Examples of pattern rules.
334 * Automatic Variables::         How to use automatic variables in the
335                                   recipe of implicit rules.
336 * Pattern Match::               How patterns match.
337 * Match-Anything Rules::        Precautions you should take prior to
338                                   defining rules that can match any
339                                   target file whatever.
340 * Canceling Rules::             How to override or cancel built-in rules.
341
342 Using @code{make} to Update Archive Files
343
344 * Archive Members::             Archive members as targets.
345 * Archive Update::              The implicit rule for archive member targets.
346 * Archive Pitfalls::            Dangers to watch out for when using archives.
347 * Archive Suffix Rules::        You can write a special kind of suffix rule
348                                   for updating archives.
349
350 Implicit Rule for Archive Member Targets
351
352 * Archive Symbols::             How to update archive symbol directories.
353
354 Extending GNU @code{make}
355
356 * Guile Integration::           Using Guile as an embedded scripting language.
357 * Loading Objects::             Loading dynamic objects as extensions.
358
359 GNU Guile Integration
360
361 * Guile Types::                 Converting Guile types to @code{make} strings.
362 * Guile Interface::             Invoking @code{make} functions from Guile.
363 * Guile Example::               Example using Guile in @code{make}.
364
365 Loading Dynamic Objects
366
367 * load Directive::              Loading dynamic objects as extensions.
368 * Remaking Loaded Objects::     How loaded objects get remade.
369 * Loaded Object API::           Programmatic interface for loaded objects.
370 * Loaded Object Example::       Example of a loaded object
371
372 Integrating GNU @code{make}
373
374 * Job Slots::                   Share job slots with GNU @code{make}.
375 * Terminal Output::             Control output to terminals.
376
377 Sharing Job Slots with GNU @code{make}
378
379 * POSIX Jobserver::             Using the jobserver on POSIX systems.
380 * Windows Jobserver::           Using the jobserver on Windows systems.
381
382 @end detailmenu
383 @end menu
384
385 @node Overview, Introduction, Top, Top
386 @comment  node-name,  next,  previous,  up
387 @chapter Overview of @code{make}
388
389 The @code{make} utility automatically determines which pieces of a large
390 program need to be recompiled, and issues commands to recompile them.
391 This manual describes GNU @code{make}, which was implemented by Richard
392 Stallman and Roland McGrath.  Development since Version 3.76 has been
393 handled by Paul D. Smith.
394
395 GNU @code{make} conforms to section 6.2 of @cite{IEEE Standard
396 1003.2-1992} (POSIX.2).
397 @cindex POSIX
398 @cindex IEEE Standard 1003.2
399 @cindex standards conformance
400
401 Our examples show C programs, since they are most common, but you can use
402 @code{make} with any programming language whose compiler can be run with a
403 shell command.  Indeed, @code{make} is not limited to programs.  You can
404 use it to describe any task where some files must be updated automatically
405 from others whenever the others change.
406
407 @menu
408 * Preparing::                   Preparing and running @code{make}.
409 * Reading::                     On reading this text.
410 * Bugs::                        Problems and bugs.
411 @end menu
412
413 @node Preparing, Reading, Overview, Overview
414 @ifnottex
415 @heading Preparing and Running Make
416 @end ifnottex
417
418 To prepare to use @code{make}, you must write a file called
419 the @dfn{makefile} that describes the relationships among files
420 in your program and provides commands for updating each file.
421 In a program, typically, the executable file is updated from object
422 files, which are in turn made by compiling source files.
423
424 Once a suitable makefile exists, each time you change some source files,
425 this simple shell command:
426
427 @example
428 make
429 @end example
430
431 @noindent
432 suffices to perform all necessary recompilations.  The @code{make} program
433 uses the makefile data base and the last-modification times of the files to
434 decide which of the files need to be updated.  For each of those files, it
435 issues the recipes recorded in the data base.
436
437 You can provide command line arguments to @code{make} to control which
438 files should be recompiled, or how.  @xref{Running, ,How to Run
439 @code{make}}.
440
441 @node Reading, Bugs, Preparing, Overview
442 @section How to Read This Manual
443
444 If you are new to @code{make}, or are looking for a general
445 introduction, read the first few sections of each chapter, skipping the
446 later sections.  In each chapter, the first few sections contain
447 introductory or general information and the later sections contain
448 specialized or technical information.
449 @ifnottex
450 The exception is the second chapter, @ref{Introduction, ,An
451 Introduction to Makefiles}, all of which is introductory.
452 @end ifnottex
453 @iftex
454 The exception is @ref{Introduction, ,An Introduction to Makefiles},
455 all of which is introductory.
456 @end iftex
457
458 If you are familiar with other @code{make} programs, see @ref{Features,
459 ,Features of GNU @code{make}}, which lists the enhancements GNU
460 @code{make} has, and @ref{Missing, ,Incompatibilities and Missing
461 Features}, which explains the few things GNU @code{make} lacks that
462 others have.
463
464 For a quick summary, see @ref{Options Summary}, @ref{Quick Reference},
465 and @ref{Special Targets}.
466
467 @node Bugs,  , Reading, Overview
468 @section Problems and Bugs
469 @cindex reporting bugs
470 @cindex bugs, reporting
471 @cindex problems and bugs, reporting
472
473 If you have problems with GNU @code{make} or think you've found a bug,
474 please report it to the developers; we cannot promise to do anything but
475 we might well want to fix it.
476
477 Before reporting a bug, make sure you've actually found a real bug.
478 Carefully reread the documentation and see if it really says you can do
479 what you're trying to do.  If it's not clear whether you should be able
480 to do something or not, report that too; it's a bug in the
481 documentation!
482
483 Before reporting a bug or trying to fix it yourself, try to isolate it
484 to the smallest possible makefile that reproduces the problem.  Then
485 send us the makefile and the exact results @code{make} gave you,
486 including any error or warning messages.  Please don't paraphrase
487 these messages: it's best to cut and paste them into your report.
488 When generating this small makefile, be sure to not use any non-free
489 or unusual tools in your recipes: you can almost always emulate what
490 such a tool would do with simple shell commands.  Finally, be sure to
491 explain what you expected to occur; this will help us decide whether
492 the problem was really in the documentation.
493
494 Once you have a precise problem you can report it in one of two ways.
495 Either send electronic mail to:
496
497 @example
498     bug-make@@gnu.org
499 @end example
500
501 @noindent
502 or use our Web-based project management tool, at:
503
504 @example
505     https://savannah.gnu.org/projects/make/
506 @end example
507
508 @noindent
509 In addition to the information above, please be careful to include the
510 version number of @code{make} you are using.  You can get this
511 information with the command @samp{make --version}.  Be sure also to
512 include the type of machine and operating system you are using.  One
513 way to obtain this information is by looking at the final lines of
514 output from the command @samp{make --help}.
515
516 If you have a code change you'd like to submit, see the @file{README} file
517 section ``Submitting Patches'' for information.
518
519 @node Introduction, Makefiles, Overview, Top
520 @comment  node-name,  next,  previous,  up
521 @chapter An Introduction to Makefiles
522
523 You need a file called a @dfn{makefile} to tell @code{make} what to do.
524 Most often, the makefile tells @code{make} how to compile and link a
525 program.
526 @cindex makefile
527
528 In this chapter, we will discuss a simple makefile that describes how to
529 compile and link a text editor which consists of eight C source files
530 and three header files.  The makefile can also tell @code{make} how to
531 run miscellaneous commands when explicitly asked (for example, to remove
532 certain files as a clean-up operation).  To see a more complex example
533 of a makefile, see @ref{Complex Makefile}.
534
535 When @code{make} recompiles the editor, each changed C source file
536 must be recompiled.  If a header file has changed, each C source file
537 that includes the header file must be recompiled to be safe.  Each
538 compilation produces an object file corresponding to the source file.
539 Finally, if any source file has been recompiled, all the object files,
540 whether newly made or saved from previous compilations, must be linked
541 together to produce the new executable editor.
542 @cindex recompilation
543 @cindex editor
544
545 @menu
546 * Rule Introduction::           What a rule looks like.
547 * Simple Makefile::             A simple makefile.
548 * How Make Works::              How @code{make} processes this makefile.
549 * Variables Simplify::          Variables make makefiles simpler.
550 * make Deduces::                Letting @code{make} deduce the recipes.
551 * Combine By Prerequisite::     Another style of makefile.
552 * Cleanup::                     Rules for cleaning the directory.
553 @end menu
554
555 @node Rule Introduction, Simple Makefile, Introduction, Introduction
556 @comment  node-name,  next,  previous,  up
557 @section What a Rule Looks Like
558 @cindex rule, introduction to
559 @cindex makefile rule parts
560 @cindex parts of makefile rule
561
562 A simple makefile consists of ``rules'' with the following shape:
563
564 @cindex targets, introduction to
565 @cindex prerequisites, introduction to
566 @cindex recipes, introduction to
567 @example
568 @group
569 @var{target} @dots{} : @var{prerequisites} @dots{}
570         @var{recipe}
571         @dots{}
572         @dots{}
573 @end group
574 @end example
575
576 A @dfn{target} is usually the name of a file that is generated by a
577 program; examples of targets are executable or object files.  A target
578 can also be the name of an action to carry out, such as @samp{clean}
579 (@pxref{Phony Targets}).
580
581 A @dfn{prerequisite} is a file that is used as input to create the
582 target.  A target often depends on several files.
583
584 @cindex tabs in rules
585 A @dfn{recipe} is an action that @code{make} carries out.  A recipe
586 may have more than one command, either on the same line or each on its
587 own line.  @strong{Please note:} you need to put a tab character at
588 the beginning of every recipe line!  This is an obscurity that catches
589 the unwary.  If you prefer to prefix your recipes with a character
590 other than tab, you can set the @code{.RECIPEPREFIX} variable to an
591 alternate character (@pxref{Special Variables}).
592
593 Usually a recipe is in a rule with prerequisites and serves to create a
594 target file if any of the prerequisites change.  However, the rule that
595 specifies a recipe for the target need not have prerequisites.  For
596 example, the rule containing the delete command associated with the
597 target @samp{clean} does not have prerequisites.
598
599 A @dfn{rule}, then, explains how and when to remake certain files
600 which are the targets of the particular rule.  @code{make} carries out
601 the recipe on the prerequisites to create or update the target.  A
602 rule can also explain how and when to carry out an action.
603 @xref{Rules, , Writing Rules}.
604
605 A makefile may contain other text besides rules, but a simple makefile
606 need only contain rules.  Rules may look somewhat more complicated
607 than shown in this template, but all fit the pattern more or less.
608
609 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
610 @section A Simple Makefile
611 @cindex simple makefile
612 @cindex makefile, simple
613
614 Here is a straightforward makefile that describes the way an
615 executable file called @code{edit} depends on eight object files
616 which, in turn, depend on eight C source and three header files.
617
618 In this example, all the C files include @file{defs.h}, but only those
619 defining editing commands include @file{command.h}, and only low
620 level files that change the editor buffer include @file{buffer.h}.
621
622 @example
623 @group
624 edit : main.o kbd.o command.o display.o \
625        insert.o search.o files.o utils.o
626         cc -o edit main.o kbd.o command.o display.o \
627                    insert.o search.o files.o utils.o
628
629 main.o : main.c defs.h
630         cc -c main.c
631 kbd.o : kbd.c defs.h command.h
632         cc -c kbd.c
633 command.o : command.c defs.h command.h
634         cc -c command.c
635 display.o : display.c defs.h buffer.h
636         cc -c display.c
637 insert.o : insert.c defs.h buffer.h
638         cc -c insert.c
639 search.o : search.c defs.h buffer.h
640         cc -c search.c
641 files.o : files.c defs.h buffer.h command.h
642         cc -c files.c
643 utils.o : utils.c defs.h
644         cc -c utils.c
645 clean :
646         rm edit main.o kbd.o command.o display.o \
647            insert.o search.o files.o utils.o
648 @end group
649 @end example
650
651 @noindent
652 We split each long line into two lines using backslash/newline; this is
653 like using one long line, but is easier to read.  @xref{Splitting Lines,
654 , Splitting Long Lines}.
655 @cindex continuation lines
656 @cindex @code{\} (backslash), for continuation lines
657 @cindex backslash (@code{\}), for continuation lines
658 @cindex quoting newline, in makefile
659 @cindex newline, quoting, in makefile
660
661 To use this makefile to create the executable file called @file{edit},
662 type:
663
664 @example
665 make
666 @end example
667
668 To use this makefile to delete the executable file and all the object
669 files from the directory, type:
670
671 @example
672 make clean
673 @end example
674
675 In the example makefile, the targets include the executable file
676 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
677 prerequisites are files such as @samp{main.c} and @samp{defs.h}.
678 In fact, each @samp{.o} file is both a target and a prerequisite.
679 Recipes include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
680
681 When a target is a file, it needs to be recompiled or relinked if any
682 of its prerequisites change.  In addition, any prerequisites that are
683 themselves automatically generated should be updated first.  In this
684 example, @file{edit} depends on each of the eight object files; the
685 object file @file{main.o} depends on the source file @file{main.c} and
686 on the header file @file{defs.h}.
687
688 A recipe may follow each line that contains a target and
689 prerequisites.  These recipes say how to update the target file.  A
690 tab character (or whatever character is specified by the
691 @code{.RECIPEPREFIX} variable; @pxref{Special Variables}) must come at
692 the beginning of every line in the recipe to distinguish recipes from
693 other lines in the makefile.  (Bear in mind that @code{make} does not
694 know anything about how the recipes work.  It is up to you to supply
695 recipes that will update the target file properly.  All @code{make}
696 does is execute the recipe you have specified when the target file
697 needs to be updated.)
698 @cindex recipe
699
700 The target @samp{clean} is not a file, but merely the name of an
701 action.  Since you normally do not want to carry out the actions in
702 this rule, @samp{clean} is not a prerequisite of any other rule.
703 Consequently, @code{make} never does anything with it unless you tell
704 it specifically.  Note that this rule not only is not a prerequisite,
705 it also does not have any prerequisites, so the only purpose of the
706 rule is to run the specified recipe.  Targets that do not refer to
707 files but are just actions are called @dfn{phony targets}.
708 @xref{Phony Targets}, for information about this kind of target.
709 @xref{Errors, , Errors in Recipes}, to see how to cause @code{make}
710 to ignore errors from @code{rm} or any other command.
711 @cindex @code{clean} target
712 @cindex @code{rm} (shell command)
713
714 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
715 @comment  node-name,  next,  previous,  up
716 @section How @code{make} Processes a Makefile
717 @cindex processing a makefile
718 @cindex makefile, how @code{make} processes
719
720 By default, @code{make} starts with the first target (not targets whose names
721 start with @samp{.} unless they also contain one or more @samp{/}).  This is
722 called the @dfn{default goal}.  (@dfn{Goals} are the targets that @code{make}
723 strives ultimately to update.  You can override this behavior using the
724 command line (@pxref{Goals, , Arguments to Specify the Goals}) or with the
725 @code{.DEFAULT_GOAL} special variable (@pxref{Special Variables, , Other
726 Special Variables}).
727 @cindex default goal
728 @cindex goal, default
729 @cindex goal
730
731 In the simple example of the previous section, the default goal is to
732 update the executable program @file{edit}; therefore, we put that rule
733 first.
734
735 Thus, when you give the command:
736
737 @example
738 make
739 @end example
740
741 @noindent
742 @code{make} reads the makefile in the current directory and begins by
743 processing the first rule.  In the example, this rule is for relinking
744 @file{edit}; but before @code{make} can fully process this rule, it
745 must process the rules for the files that @file{edit} depends on,
746 which in this case are the object files.  Each of these files is
747 processed according to its own rule.  These rules say to update each
748 @samp{.o} file by compiling its source file.  The recompilation must
749 be done if the source file, or any of the header files named as
750 prerequisites, is more recent than the object file, or if the object
751 file does not exist.
752
753 The other rules are processed because their targets appear as
754 prerequisites of the goal.  If some other rule is not depended on by the
755 goal (or anything it depends on, etc.), that rule is not processed,
756 unless you tell @code{make} to do so (with a command such as
757 @w{@code{make clean}}).
758
759 Before recompiling an object file, @code{make} considers updating its
760 prerequisites, the source file and header files.  This makefile does not
761 specify anything to be done for them---the @samp{.c} and @samp{.h} files
762 are not the targets of any rules---so @code{make} does nothing for these
763 files.  But @code{make} would update automatically generated C programs,
764 such as those made by Bison or Yacc, by their own rules at this time.
765
766 After recompiling whichever object files need it, @code{make} decides
767 whether to relink @file{edit}.  This must be done if the file
768 @file{edit} does not exist, or if any of the object files are newer than
769 it.  If an object file was just recompiled, it is now newer than
770 @file{edit}, so @file{edit} is relinked.
771 @cindex relinking
772
773 Thus, if we change the file @file{insert.c} and run @code{make},
774 @code{make} will compile that file to update @file{insert.o}, and then
775 link @file{edit}.  If we change the file @file{command.h} and run
776 @code{make}, @code{make} will recompile the object files @file{kbd.o},
777 @file{command.o} and @file{files.o} and then link the file @file{edit}.
778
779 @node Variables Simplify, make Deduces, How Make Works, Introduction
780 @section Variables Make Makefiles Simpler
781 @cindex variables
782 @cindex simplifying with variables
783
784 In our example, we had to list all the object files twice in the rule for
785 @file{edit} (repeated here):
786
787 @example
788 @group
789 edit : main.o kbd.o command.o display.o \
790               insert.o search.o files.o utils.o
791         cc -o edit main.o kbd.o command.o display.o \
792                    insert.o search.o files.o utils.o
793 @end group
794 @end example
795
796 @cindex @code{objects}
797 Such duplication is error-prone; if a new object file is added to the
798 system, we might add it to one list and forget the other.  We can eliminate
799 the risk and simplify the makefile by using a variable.  @dfn{Variables}
800 allow a text string to be defined once and substituted in multiple places
801 later (@pxref{Using Variables, ,How to Use Variables}).
802
803 @cindex @code{OBJECTS}
804 @cindex @code{objs}
805 @cindex @code{OBJS}
806 @cindex @code{obj}
807 @cindex @code{OBJ}
808 It is standard practice for every makefile to have a variable named
809 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
810 or @code{OBJ} which is a list of all object file names.  We would
811 define such a variable @code{objects} with a line like this in the
812 makefile:
813
814 @example
815 @group
816 objects = main.o kbd.o command.o display.o \
817           insert.o search.o files.o utils.o
818 @end group
819 @end example
820
821 @noindent
822 Then, each place we want to put a list of the object file names, we can
823 substitute the variable's value by writing @samp{$(objects)}
824 (@pxref{Using Variables, ,How to Use Variables}).
825
826 Here is how the complete simple makefile looks when you use a variable
827 for the object files:
828
829 @example
830 @group
831 objects = main.o kbd.o command.o display.o \
832           insert.o search.o files.o utils.o
833
834 edit : $(objects)
835         cc -o edit $(objects)
836 main.o : main.c defs.h
837         cc -c main.c
838 kbd.o : kbd.c defs.h command.h
839         cc -c kbd.c
840 command.o : command.c defs.h command.h
841         cc -c command.c
842 display.o : display.c defs.h buffer.h
843         cc -c display.c
844 insert.o : insert.c defs.h buffer.h
845         cc -c insert.c
846 search.o : search.c defs.h buffer.h
847         cc -c search.c
848 files.o : files.c defs.h buffer.h command.h
849         cc -c files.c
850 utils.o : utils.c defs.h
851         cc -c utils.c
852 clean :
853         rm edit $(objects)
854 @end group
855 @end example
856
857 @node make Deduces, Combine By Prerequisite, Variables Simplify, Introduction
858 @section Letting @code{make} Deduce the Recipes
859 @cindex deducing recipes (implicit rules)
860 @cindex implicit rule, introduction to
861 @cindex rule, implicit, introduction to
862
863 It is not necessary to spell out the recipes for compiling the individual
864 C source files, because @code{make} can figure them out: it has an
865 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
866 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
867 use the recipe @samp{cc -c main.c -o main.o} to compile @file{main.c} into
868 @file{main.o}.  We can therefore omit the recipes from the rules for the
869 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.
870
871 When a @samp{.c} file is used automatically in this way, it is also
872 automatically added to the list of prerequisites.  We can therefore omit
873 the @samp{.c} files from the prerequisites, provided we omit the recipe.
874
875 Here is the entire example, with both of these changes, and a variable
876 @code{objects} as suggested above:
877
878 @example
879 @group
880 objects = main.o kbd.o command.o display.o \
881           insert.o search.o files.o utils.o
882
883 edit : $(objects)
884         cc -o edit $(objects)
885
886 main.o : defs.h
887 kbd.o : defs.h command.h
888 command.o : defs.h command.h
889 display.o : defs.h buffer.h
890 insert.o : defs.h buffer.h
891 search.o : defs.h buffer.h
892 files.o : defs.h buffer.h command.h
893 utils.o : defs.h
894
895 .PHONY : clean
896 clean :
897         rm edit $(objects)
898 @end group
899 @end example
900
901 @noindent
902 This is how we would write the makefile in actual practice.  (The
903 complications associated with @samp{clean} are described elsewhere.
904 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Recipes}.)
905
906 Because implicit rules are so convenient, they are important.  You
907 will see them used frequently.
908
909 @node Combine By Prerequisite, Cleanup, make Deduces, Introduction
910 @section Another Style of Makefile
911 @cindex combining rules by prerequisite
912
913 When the objects of a makefile are created only by implicit rules, an
914 alternative style of makefile is possible.  In this style of makefile,
915 you group entries by their prerequisites instead of by their targets.
916 Here is what one looks like:
917
918 @example
919 @group
920 objects = main.o kbd.o command.o display.o \
921           insert.o search.o files.o utils.o
922
923 edit : $(objects)
924         cc -o edit $(objects)
925
926 $(objects) : defs.h
927 kbd.o command.o files.o : command.h
928 display.o insert.o search.o files.o : buffer.h
929 @end group
930 @end example
931
932 @noindent
933 Here @file{defs.h} is given as a prerequisite of all the object files;
934 @file{command.h} and @file{buffer.h} are prerequisites of the specific
935 object files listed for them.
936
937 Whether this is better is a matter of taste: it is more compact, but some
938 people dislike it because they find it clearer to put all the information
939 about each target in one place.
940
941 @node Cleanup,  , Combine By Prerequisite, Introduction
942 @section Rules for Cleaning the Directory
943 @cindex cleaning up
944 @cindex removing, to clean up
945
946 Compiling a program is not the only thing you might want to write rules
947 for.  Makefiles commonly tell how to do a few other things besides
948 compiling a program: for example, how to delete all the object files
949 and executables so that the directory is @samp{clean}.
950
951 @cindex @code{clean} target
952 Here is how we
953 could write a @code{make} rule for cleaning our example editor:
954
955 @example
956 @group
957 clean:
958         rm edit $(objects)
959 @end group
960 @end example
961
962 In practice, we might want to write the rule in a somewhat more
963 complicated manner to handle unanticipated situations.  We would do this:
964
965 @example
966 @group
967 .PHONY : clean
968 clean :
969         -rm edit $(objects)
970 @end group
971 @end example
972
973 @noindent
974 This prevents @code{make} from getting confused by an actual file
975 called @file{clean} and causes it to continue in spite of errors from
976 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
977 Recipes}.)
978
979 @noindent
980 A rule such as this should not be placed at the beginning of the
981 makefile, because we do not want it to run by default!  Thus, in the
982 example makefile, we want the rule for @code{edit}, which recompiles
983 the editor, to remain the default goal.
984
985 Since @code{clean} is not a prerequisite of @code{edit}, this rule will not
986 run at all if we give the command @samp{make} with no arguments.  In
987 order to make the rule run, we have to type @samp{make clean}.
988 @xref{Running, ,How to Run @code{make}}.
989
990 @node Makefiles, Rules, Introduction, Top
991 @chapter Writing Makefiles
992
993 @cindex makefile, how to write
994 The information that tells @code{make} how to recompile a system comes from
995 reading a data base called the @dfn{makefile}.
996
997 @menu
998 * Makefile Contents::           What makefiles contain.
999 * Makefile Names::              How to name your makefile.
1000 * Include::                     How one makefile can use another makefile.
1001 * MAKEFILES Variable::          The environment can specify extra makefiles.
1002 * Remaking Makefiles::          How makefiles get remade.
1003 * Overriding Makefiles::        How to override part of one makefile
1004                                   with another makefile.
1005 * Reading Makefiles::           How makefiles are read in.
1006 * Parsing Makefiles::           How makefiles are parsed.
1007 * Secondary Expansion::         How and when secondary expansion is performed.
1008 @end menu
1009
1010 @node Makefile Contents, Makefile Names, Makefiles, Makefiles
1011 @section What Makefiles Contain
1012
1013 Makefiles contain five kinds of things: @dfn{explicit rules},
1014 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
1015 and @dfn{comments}.  Rules, variables, and directives are described at
1016 length in later chapters.
1017
1018 @itemize @bullet
1019 @cindex rule, explicit, definition of
1020 @cindex explicit rule, definition of
1021 @item
1022 An @dfn{explicit rule} says when and how to remake one or more files,
1023 called the rule's @dfn{targets}.  It lists the other files that the
1024 targets depend on, called the @dfn{prerequisites} of the target, and
1025 may also give a recipe to use to create or update the targets.
1026 @xref{Rules, ,Writing Rules}.
1027
1028 @cindex rule, implicit, definition of
1029 @cindex implicit rule, definition of
1030 @item
1031 An @dfn{implicit rule} says when and how to remake a class of files
1032 based on their names.  It describes how a target may depend on a file
1033 with a name similar to the target and gives a recipe to create or
1034 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
1035
1036 @cindex variable definition
1037 @item
1038 A @dfn{variable definition} is a line that specifies a text string
1039 value for a variable that can be substituted into the text later.  The
1040 simple makefile example shows a variable definition for @code{objects}
1041 as a list of all object files (@pxref{Variables Simplify, , Variables
1042 Make Makefiles Simpler}).
1043
1044 @cindex directive
1045 @item
1046 A @dfn{directive} is an instruction for @code{make} to do something
1047 special while reading the makefile.  These include:
1048
1049 @itemize @bullet
1050 @item
1051 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
1052
1053 @item
1054 Deciding (based on the values of variables) whether to use or
1055 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
1056
1057 @item
1058 Defining a variable from a verbatim string containing multiple lines
1059 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).
1060 @end itemize
1061
1062 @cindex comments, in makefile
1063 @cindex @code{#} (comments), in makefile
1064 @item
1065 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the
1066 rest of the line are ignored, except that a trailing backslash not
1067 escaped by another backslash will continue the comment across multiple
1068 lines.  A line containing just a comment (with perhaps spaces before
1069 it) is effectively blank, and is ignored.  If you want a literal
1070 @code{#}, escape it with a backslash (e.g., @code{\#}).  Comments may
1071 appear on any line in the makefile, although they are treated
1072 specially in certain situations.
1073
1074 You cannot use comments within variable references or function calls:
1075 any instance of @code{#} will be treated literally (rather than as the
1076 start of a comment) inside a variable reference or function call.
1077
1078 Comments within a recipe are passed to the shell, just as with any
1079 other recipe text.  The shell decides how to interpret it: whether or
1080 not this is a comment is up to the shell.
1081
1082 Within a @code{define} directive, comments are not ignored during the
1083 definition of the variable, but rather kept intact in the value of the
1084 variable.  When the variable is expanded they will either be treated
1085 as @code{make} comments or as recipe text, depending on the context in
1086 which the variable is evaluated.
1087 @end itemize
1088
1089 @menu
1090 * Splitting Lines::             Splitting long lines in makefiles
1091 @end menu
1092
1093 @node Splitting Lines,  , Makefile Contents, Makefile Contents
1094 @subsection Splitting Long Lines
1095 @cindex splitting long lines
1096 @cindex long lines, splitting
1097 @cindex backslash (@code{\}), to quote newlines
1098
1099 Makefiles use a ``line-based'' syntax in which the newline character
1100 is special and marks the end of a statement.  GNU @code{make} has no
1101 limit on the length of a statement line, up to the amount of memory in
1102 your computer.
1103
1104 However, it is difficult to read lines which are too long to display
1105 without wrapping or scrolling.  So, you can format your makefiles for
1106 readability by adding newlines into the middle of a statement: you do
1107 this by escaping the internal newlines with a backslash (@code{\})
1108 character.  Where we need to make a distinction we will refer to
1109 ``physical lines'' as a single line ending with a newline (regardless
1110 of whether it is escaped) and a ``logical line'' being a complete
1111 statement including all escaped newlines up to the first non-escaped
1112 newline.
1113
1114 The way in which backslash/newline combinations are handled depends on
1115 whether the statement is a recipe line or a non-recipe line.  Handling
1116 of backslash/newline in a recipe line is discussed later
1117 (@pxref{Splitting Recipe Lines}).
1118
1119 Outside of recipe lines, backslash/newlines are converted into a
1120 single space character.  Once that is done, all whitespace around the
1121 backslash/newline is condensed into a single space: this includes all
1122 whitespace preceding the backslash, all whitespace at the beginning of
1123 the line after the backslash/newline, and any consecutive
1124 backslash/newline combinations.
1125
1126 If the @code{.POSIX} special target is defined then backslash/newline
1127 handling is modified slightly to conform to POSIX.2: first, whitespace
1128 preceding a backslash is not removed and second, consecutive
1129 backslash/newlines are not condensed.
1130
1131 @subsubheading Splitting Without Adding Whitespace
1132 @cindex whitespace, avoiding on line split
1133 @cindex removing whitespace from split lines
1134
1135 If you need to split a line but do @emph{not} want any whitespace
1136 added, you can utilize a subtle trick: replace your backslash/newline
1137 pairs with the three characters dollar sign, backslash, and newline:
1138
1139 @example
1140 var := one$\
1141        word
1142 @end example
1143
1144 After @code{make} removes the backslash/newline and condenses the
1145 following line into a single space, this is equivalent to:
1146
1147 @example
1148 var := one$ word
1149 @end example
1150
1151 Then @code{make} will perform variable expansion.  The variable
1152 reference @samp{$ } refers to a variable with the one-character name
1153 `` '' (space) which does not exist, and so expands to the empty
1154 string, giving a final assignment which is the equivalent of:
1155
1156 @example
1157 var := oneword
1158 @end example
1159
1160
1161 @node Makefile Names, Include, Makefile Contents, Makefiles
1162 @section What Name to Give Your Makefile
1163 @cindex makefile name
1164 @cindex name of makefile
1165 @cindex default makefile name
1166 @cindex file name of makefile
1167
1168 @c following paragraph rewritten to avoid overfull hbox
1169 By default, when @code{make} looks for the makefile, it tries the
1170 following names, in order: @file{GNUmakefile}, @file{makefile}
1171 and @file{Makefile}.
1172 @findex Makefile
1173 @findex GNUmakefile
1174 @findex makefile
1175
1176 @cindex @code{README}
1177 Normally you should call your makefile either @file{makefile} or
1178 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1179 prominently near the beginning of a directory listing, right near other
1180 important files such as @file{README}.)  The first name checked,
1181 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1182 use this name if you have a makefile that is specific to GNU
1183 @code{make}, and will not be understood by other versions of
1184 @code{make}.  Other @code{make} programs look for @file{makefile} and
1185 @file{Makefile}, but not @file{GNUmakefile}.
1186
1187 If @code{make} finds none of these names, it does not use any makefile.
1188 Then you must specify a goal with a command argument, and @code{make}
1189 will attempt to figure out how to remake it using only its built-in
1190 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1191
1192 @cindex @code{-f}
1193 @cindex @code{--file}
1194 @cindex @code{--makefile}
1195 If you want to use a nonstandard name for your makefile, you can specify
1196 the makefile name with the @samp{-f} or @samp{--file} option.  The
1197 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1198 @code{make} to read the file @var{name} as the makefile.  If you use
1199 more than one @samp{-f} or @samp{--file} option, you can specify several
1200 makefiles.  All the makefiles are effectively concatenated in the order
1201 specified.  The default makefile names @file{GNUmakefile},
1202 @file{makefile} and @file{Makefile} are not checked automatically if you
1203 specify @samp{-f} or @samp{--file}.
1204 @cindex specifying makefile name
1205 @cindex makefile name, how to specify
1206 @cindex name of makefile, how to specify
1207 @cindex file name of makefile, how to specify
1208
1209 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1210 @section Including Other Makefiles
1211 @cindex including other makefiles
1212 @cindex makefile, including
1213
1214 @findex include
1215 The @code{include} directive tells @code{make} to suspend reading the
1216 current makefile and read one or more other makefiles before continuing.
1217 The directive is a line in the makefile that looks like this:
1218
1219 @example
1220 include @var{filenames}@dots{}
1221 @end example
1222
1223 @noindent
1224 @var{filenames} can contain shell file name patterns.  If
1225 @var{filenames} is empty, nothing is included and no error is printed.
1226 @cindex shell file name pattern (in @code{include})
1227 @cindex shell wildcards (in @code{include})
1228 @cindex wildcard, in @code{include}
1229
1230 Extra spaces are allowed and ignored at the beginning of the line, but
1231 the first character must not be a tab (or the value of
1232 @code{.RECIPEPREFIX})---if the line begins with a tab, it will be
1233 considered a recipe line.  Whitespace is required between
1234 @code{include} and the file names, and between file names; extra
1235 whitespace is ignored there and at the end of the directive.  A
1236 comment starting with @samp{#} is allowed at the end of the line.  If
1237 the file names contain any variable or function references, they are
1238 expanded.  @xref{Using Variables, ,How to Use Variables}.
1239
1240 For example, if you have three @file{.mk} files, @file{a.mk},
1241 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1242 @code{bish bash}, then the following expression
1243
1244 @example
1245 include foo *.mk $(bar)
1246 @end example
1247
1248 is equivalent to
1249
1250 @example
1251 include foo a.mk b.mk c.mk bish bash
1252 @end example
1253
1254 When @code{make} processes an @code{include} directive, it suspends
1255 reading of the containing makefile and reads from each listed file in
1256 turn.  When that is finished, @code{make} resumes reading the
1257 makefile in which the directive appears.
1258
1259 One occasion for using @code{include} directives is when several programs,
1260 handled by individual makefiles in various directories, need to use a
1261 common set of variable definitions
1262 (@pxref{Setting, ,Setting Variables}) or pattern rules
1263 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1264
1265 Another such occasion is when you want to generate prerequisites from
1266 source files automatically; the prerequisites can be put in a file that
1267 is included by the main makefile.  This practice is generally cleaner
1268 than that of somehow appending the prerequisites to the end of the main
1269 makefile as has been traditionally done with other versions of
1270 @code{make}.  @xref{Automatic Prerequisites}.
1271 @cindex prerequisites, automatic generation
1272 @cindex automatic generation of prerequisites
1273 @cindex generating prerequisites automatically
1274
1275 @cindex @code{-I}
1276 @cindex @code{--include-dir}
1277 @cindex included makefiles, default directories
1278 @cindex default directories for included makefiles
1279 @findex /usr/gnu/include
1280 @findex /usr/local/include
1281 @findex /usr/include
1282 If the specified name does not start with a slash, and the file is not
1283 found in the current directory, several other directories are searched.
1284 First, any directories you have specified with the @samp{-I} or
1285 @samp{--include-dir} options are searched
1286 (@pxref{Options Summary, ,Summary of Options}).
1287 Then the following directories (if they exist)
1288 are searched, in this order:
1289 @file{@var{prefix}/include} (normally @file{/usr/local/include}
1290 @footnote{GNU Make compiled for MS-DOS and MS-Windows behaves as if
1291 @var{prefix} has been defined to be the root of the DJGPP tree
1292 hierarchy.})
1293 @file{/usr/gnu/include},
1294 @file{/usr/local/include}, @file{/usr/include}.
1295
1296 The @code{.INCLUDE_DIRS} variable will contain the current list of
1297 directories that make will search for included files.  @xref{Special
1298 Variables, ,Other Special Variables}.
1299
1300 You can avoid searching in these default directories by adding the
1301 command line option @code{-I} with the special value @code{-} (e.g.,
1302 @code{-I-}) to the command line.  This will cause @code{make} to
1303 forget any already-set include directories, including the default
1304 directories.
1305
1306 If an included makefile cannot be found in any of these directories it is not
1307 an immediately fatal error; processing of the makefile containing the
1308 @code{include} continues.  Once it has finished reading makefiles, @code{make}
1309 will try to remake any that are out of date or don't exist.  @xref{Remaking
1310 Makefiles, ,How Makefiles Are Remade}.  Only after it has failed to find a
1311 rule to remake the makefile, or it found a rule but the recipe failed, will
1312 @code{make} diagnose the missing makefile as a fatal error.
1313
1314 If you want @code{make} to simply ignore a makefile which does not exist
1315 or cannot be remade, with no error message, use the @w{@code{-include}}
1316 directive instead of @code{include}, like this:
1317
1318 @example
1319 -include @var{filenames}@dots{}
1320 @end example
1321
1322 This acts like @code{include} in every way except that there is no
1323 error (not even a warning) if any of the @var{filenames} (or any
1324 prerequisites of any of the @var{filenames}) do not exist or cannot be
1325 remade.
1326
1327 For compatibility with some other @code{make} implementations,
1328 @code{sinclude} is another name for @w{@code{-include}}.
1329
1330 @node MAKEFILES Variable, Remaking Makefiles, Include, Makefiles
1331 @section The Variable @code{MAKEFILES}
1332 @cindex makefile, and @code{MAKEFILES} variable
1333 @cindex including (@code{MAKEFILES} variable)
1334
1335 @vindex MAKEFILES
1336 If the environment variable @code{MAKEFILES} is defined, @code{make}
1337 considers its value as a list of names (separated by whitespace) of
1338 additional makefiles to be read before the others.  This works much
1339 like the @code{include} directive: various directories are searched
1340 for those files (@pxref{Include, ,Including Other Makefiles}).  In
1341 addition, the default goal is never taken from one of these makefiles
1342 (or any makefile included by them) and it is not an error if the files
1343 listed in @code{MAKEFILES} are not found.
1344
1345 @cindex recursion, and @code{MAKEFILES} variable
1346 The main use of @code{MAKEFILES} is in communication between recursive
1347 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1348 @code{make}}).  It usually is not desirable to set the environment
1349 variable before a top-level invocation of @code{make}, because it is
1350 usually better not to mess with a makefile from outside.  However, if
1351 you are running @code{make} without a specific makefile, a makefile in
1352 @code{MAKEFILES} can do useful things to help the built-in implicit
1353 rules work better, such as defining search paths (@pxref{Directory Search}).
1354
1355 Some users are tempted to set @code{MAKEFILES} in the environment
1356 automatically on login, and program makefiles to expect this to be done.
1357 This is a very bad idea, because such makefiles will fail to work if run by
1358 anyone else.  It is much better to write explicit @code{include} directives
1359 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1360
1361 @node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
1362 @section How Makefiles Are Remade
1363 @cindex updating makefiles
1364 @cindex remaking makefiles
1365 @cindex makefile, remaking of
1366 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1367 files.  If a makefile can be remade from other files, you probably want
1368 @code{make} to get an up-to-date version of the makefile to read in.
1369
1370 To this end, after reading in all makefiles @code{make} will consider
1371 each as a goal target, in the order in which they were processed, and
1372 attempt to update it.  If parallel builds (@pxref{Parallel, ,Parallel
1373 Execution}) are enabled then makefiles will be rebuilt in parallel as
1374 well.
1375
1376 If a makefile has a rule which says how to update it (found either in
1377 that very makefile or in another one) or if an implicit rule applies
1378 to it (@pxref{Implicit Rules, ,Using Implicit Rules}), it will be
1379 updated if necessary.  After all makefiles have been checked, if any
1380 have actually been changed, @code{make} starts with a clean slate and
1381 reads all the makefiles over again.  (It will also attempt to update
1382 each of them over again, but normally this will not change them again,
1383 since they are already up to date.)  Each restart will cause the
1384 special variable @code{MAKE_RESTARTS} to be updated (@pxref{Special
1385 Variables}).
1386
1387 If you know that one or more of your makefiles cannot be remade and
1388 you want to keep @code{make} from performing an implicit rule search
1389 on them, perhaps for efficiency reasons, you can use any normal method
1390 of preventing implicit rule look-up to do so.  For example, you can
1391 write an explicit rule with the makefile as the target, and an empty
1392 recipe (@pxref{Empty Recipes, ,Using Empty Recipes}).
1393
1394 If the makefiles specify a double-colon rule to remake a file with a recipe
1395 but no prerequisites, that file will always be remade (@pxref{Double-Colon}).
1396 In the case of makefiles, a makefile that has a double-colon rule with a
1397 recipe but no prerequisites will be remade every time @code{make} is run, and
1398 then again after @code{make} starts over and reads the makefiles in again.
1399 This would cause an infinite loop: @code{make} would constantly remake the
1400 makefile and restart, and never do anything else.  So, to avoid this,
1401 @code{make} will @strong{not} attempt to remake makefiles which are specified
1402 as targets of a double-colon rule with a recipe but no prerequisites.
1403
1404 Phony targets (@pxref{Phony Targets}) have the same effect: they are never
1405 considered up-to-date and so an included file marked as phony would cause
1406 @code{make} to restart continuously.  To avoid this @code{make} will not
1407 attempt to remake makefiles which are marked phony.
1408
1409 You can take advantage of this to optimize startup time: if you know you don't
1410 need your @file{Makefile} to be remade you can prevent make from trying to
1411 remake it by adding either:
1412
1413 @example
1414 .PHONY: Makefile
1415 @end example
1416
1417 or:
1418
1419 @example
1420 Makefile:: ;
1421 @end example
1422
1423 If you do not specify any makefiles to be read with @samp{-f} or
1424 @samp{--file} options, @code{make} will try the default makefile names;
1425 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1426 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1427 @code{make} is not certain that these makefiles should exist.  However,
1428 if a default makefile does not exist but can be created by running
1429 @code{make} rules, you probably want the rules to be run so that the
1430 makefile can be used.
1431
1432 Therefore, if none of the default makefiles exists, @code{make} will
1433 try to make each of them until it succeeds in making one, or it runs
1434 out of names to try.  Note that it is not an error if @code{make}
1435 cannot find or make any makefile; a makefile is not always
1436 necessary.
1437
1438 When you use the @samp{-t} or @samp{--touch} option
1439 (@pxref{Instead of Execution, ,Instead of Executing Recipes}),
1440 you would not want to use an out-of-date makefile to decide which
1441 targets to touch.  So the @samp{-t} option has no effect on updating
1442 makefiles; they are really updated even if @samp{-t} is specified.
1443 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1444 @samp{--just-print}) do not prevent updating of makefiles, because an
1445 out-of-date makefile would result in the wrong output for other targets.
1446 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1447 and then print the recipe to update @file{foo} and its prerequisites
1448 without running it.  The recipe printed for @file{foo} will be the one
1449 specified in the updated contents of @file{mfile}.
1450
1451 However, on occasion you might actually wish to prevent updating of even
1452 the makefiles.  You can do this by specifying the makefiles as goals in
1453 the command line as well as specifying them as makefiles.  When the
1454 makefile name is specified explicitly as a goal, the options @samp{-t}
1455 and so on do apply to them.
1456
1457 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1458 @file{mfile}, print the recipe needed to update it without actually
1459 running it, and then print the recipe needed to update @file{foo}
1460 without running that.  The recipe for @file{foo} will be the one
1461 specified by the existing contents of @file{mfile}.
1462
1463 @node Overriding Makefiles, Reading Makefiles, Remaking Makefiles, Makefiles
1464 @section Overriding Part of Another Makefile
1465
1466 @cindex overriding makefiles
1467 @cindex makefile, overriding
1468 Sometimes it is useful to have a makefile that is mostly just like
1469 another makefile.  You can often use the @samp{include} directive to
1470 include one in the other, and add more targets or variable definitions.
1471 However, it is invalid for two makefiles to give different recipes for
1472 the same target.  But there is another way.
1473
1474 @cindex match-anything rule, used to override
1475 In the containing makefile (the one that wants to include the other),
1476 you can use a match-anything pattern rule to say that to remake any
1477 target that cannot be made from the information in the containing
1478 makefile, @code{make} should look in another makefile.
1479 @xref{Pattern Rules}, for more information on pattern rules.
1480
1481 For example, if you have a makefile called @file{Makefile} that says how
1482 to make the target @samp{foo} (and other targets), you can write a
1483 makefile called @file{GNUmakefile} that contains:
1484
1485 @example
1486 foo:
1487         frobnicate > foo
1488
1489 %: force
1490         @@$(MAKE) -f Makefile $@@
1491 force: ;
1492 @end example
1493
1494 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1495 read it, and see that to make @file{foo}, it needs to run the recipe
1496 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1497 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1498 recipe from the pattern rule: @samp{make -f Makefile bar}.  If
1499 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1500 will apply the rule.  And likewise for any other target that
1501 @file{GNUmakefile} does not say how to make.
1502
1503 The way this works is that the pattern rule has a pattern of just
1504 @samp{%}, so it matches any target whatever.  The rule specifies a
1505 prerequisite @file{force}, to guarantee that the recipe will be run even
1506 if the target file already exists.  We give the @file{force} target an
1507 empty recipe to prevent @code{make} from searching for an implicit rule to
1508 build it---otherwise it would apply the same match-anything rule to
1509 @file{force} itself and create a prerequisite loop!
1510
1511 @node Reading Makefiles, Parsing Makefiles, Overriding Makefiles, Makefiles
1512 @section How @code{make} Reads a Makefile
1513 @cindex reading makefiles
1514 @cindex makefile, reading
1515
1516 GNU @code{make} does its work in two distinct phases.  During the
1517 first phase it reads all the makefiles, included makefiles, etc. and
1518 internalizes all the variables and their values and implicit and
1519 explicit rules, and builds a dependency graph of all the targets and
1520 their prerequisites.  During the second phase, @code{make} uses this
1521 internalized data to determine which targets need to be updated and
1522 run the recipes necessary to update them.
1523
1524 It's important to understand this two-phase approach because it has a
1525 direct impact on how variable and function expansion happens; this is
1526 often a source of some confusion when writing makefiles.  Below is a
1527 summary of the different constructs that can be found in a makefile,
1528 and the phase in which expansion happens for each part of the
1529 construct.
1530
1531 We say that expansion is @dfn{immediate} if it happens during the
1532 first phase: @code{make} will expand that part of the construct as the
1533 makefile is parsed.  We say that expansion is @dfn{deferred} if it is
1534 not immediate.  Expansion of a deferred construct part is delayed
1535 until the expansion is used: either when it is referenced in an
1536 immediate context, or when it is needed during the second phase.
1537
1538 You may not be familiar with some of these constructs yet.  You can
1539 reference this section as you become familiar with them, in later
1540 chapters.
1541
1542 @subheading Variable Assignment
1543 @cindex +=, expansion
1544 @cindex =, expansion
1545 @cindex ?=, expansion
1546 @cindex +=, expansion
1547 @cindex !=, expansion
1548 @cindex define, expansion
1549
1550 Variable definitions are parsed as follows:
1551
1552 @example
1553 @var{immediate} = @var{deferred}
1554 @var{immediate} ?= @var{deferred}
1555 @var{immediate} := @var{immediate}
1556 @var{immediate} ::= @var{immediate}
1557 @var{immediate} :::= @var{immediate-with-escape}
1558 @var{immediate} += @var{deferred} or @var{immediate}
1559 @var{immediate} != @var{immediate}
1560
1561 define @var{immediate}
1562   @var{deferred}
1563 endef
1564
1565 define @var{immediate} =
1566   @var{deferred}
1567 endef
1568
1569 define @var{immediate} ?=
1570   @var{deferred}
1571 endef
1572
1573 define @var{immediate} :=
1574   @var{immediate}
1575 endef
1576
1577 define @var{immediate} ::=
1578   @var{immediate}
1579 endef
1580
1581 define @var{immediate} :::=
1582   @var{immediate-with-escape}
1583 endef
1584
1585 define @var{immediate} +=
1586   @var{deferred} or @var{immediate}
1587 endef
1588
1589 define @var{immediate} !=
1590   @var{immediate}
1591 endef
1592 @end example
1593
1594 For the append operator @samp{+=}, the right-hand side is considered
1595 immediate if the variable was previously set as a simple variable
1596 (@samp{:=} or @samp{::=}), and deferred otherwise.
1597
1598 For the @var{immediate-with-escape} operator @samp{:::=}, the value on
1599 the right-hand side is immediately expanded but then escaped (that is,
1600 all instances of @code{$} in the result of the expansion are replaced
1601 with @code{$$}).
1602
1603 For the shell assignment operator @samp{!=}, the right-hand side is
1604 evaluated immediately and handed to the shell.  The result is stored
1605 in the variable named on the left, and that variable is considered a
1606 recursively expanded variable (and will thus be re-evaluated on each
1607 reference).
1608
1609 @subheading Conditional Directives
1610 @cindex ifdef, expansion
1611 @cindex ifeq, expansion
1612 @cindex ifndef, expansion
1613 @cindex ifneq, expansion
1614
1615 Conditional directives are parsed immediately.  This means, for
1616 example, that automatic variables cannot be used in conditional
1617 directives, as automatic variables are not set until the recipe for
1618 that rule is invoked.  If you need to use automatic variables in a
1619 conditional directive you @emph{must} move the condition into the
1620 recipe and use shell conditional syntax instead.
1621
1622 @subheading Rule Definition
1623 @cindex target, expansion
1624 @cindex prerequisite, expansion
1625 @cindex implicit rule, expansion
1626 @cindex pattern rule, expansion
1627 @cindex explicit rule, expansion
1628
1629 A rule is always expanded the same way, regardless of the form:
1630
1631 @example
1632 @var{immediate} : @var{immediate} ; @var{deferred}
1633         @var{deferred}
1634 @end example
1635
1636 That is, the target and prerequisite sections are expanded
1637 immediately, and the recipe used to build the target is always
1638 deferred.  This is true for explicit rules, pattern rules, suffix
1639 rules, static pattern rules, and simple prerequisite definitions.
1640
1641 @node Parsing Makefiles, Secondary Expansion, Reading Makefiles, Makefiles
1642 @section How Makefiles Are Parsed
1643 @cindex parsing makefiles
1644 @cindex makefiles, parsing
1645
1646 GNU @code{make} parses makefiles line-by-line.  Parsing proceeds using
1647 the following steps:
1648
1649 @enumerate
1650 @item
1651 Read in a full logical line, including backslash-escaped lines
1652 (@pxref{Splitting Lines, , Splitting Long Lines}).
1653
1654 @item
1655 Remove comments (@pxref{Makefile Contents, , What Makefiles Contain}).
1656
1657 @item
1658 If the line begins with the recipe prefix character and we are in a
1659 rule context, add the line to the current recipe and read the next
1660 line (@pxref{Recipe Syntax}).
1661
1662 @item
1663 Expand elements of the line which appear in an @emph{immediate}
1664 expansion context (@pxref{Reading Makefiles, , How @code{make} Reads a
1665 Makefile}).
1666
1667 @item
1668 Scan the line for a separator character, such as @samp{:} or @samp{=},
1669 to determine whether the line is a macro assignment or a rule
1670 (@pxref{Recipe Syntax}).
1671
1672 @item
1673 Internalize the resulting operation and read the next line.
1674 @end enumerate
1675
1676 An important consequence of this is that a macro can expand to an
1677 entire rule, @emph{if it is one line long}.  This will work:
1678
1679 @example
1680 myrule = target : ; echo built
1681
1682 $(myrule)
1683 @end example
1684
1685 However, this will not work because @code{make} does not re-split lines
1686 after it has expanded them:
1687
1688 @example
1689 define myrule
1690 target:
1691         echo built
1692 endef
1693
1694 $(myrule)
1695 @end example
1696
1697 The above makefile results in the definition of a target @samp{target}
1698 with prerequisites @samp{echo} and @samp{built}, as if the makefile
1699 contained @code{target: echo built}, rather than a rule with a recipe.
1700 Newlines still present in a line after expansion is complete are
1701 ignored as normal whitespace.
1702
1703 In order to properly expand a multi-line macro you must use the
1704 @code{eval} function: this causes the @code{make} parser to be run on
1705 the results of the expanded macro (@pxref{Eval Function}).
1706
1707 @node Secondary Expansion,  , Parsing Makefiles, Makefiles
1708 @section Secondary Expansion
1709 @cindex secondary expansion
1710 @cindex expansion, secondary
1711
1712 @findex .SECONDEXPANSION
1713 Previously we learned that GNU @code{make} works in two distinct
1714 phases: a read-in phase and a target-update phase (@pxref{Reading
1715 Makefiles, , How @code{make} Reads a Makefile}).  GNU make also has
1716 the ability to enable a @emph{second expansion} of the prerequisites
1717 (only) for some or all targets defined in the makefile.  In order for
1718 this second expansion to occur, the special target
1719 @code{.SECONDEXPANSION} must be defined before the first prerequisite
1720 list that makes use of this feature.
1721
1722 If @code{.SECONDEXPANSION} is defined then when GNU @code{make} needs to check
1723 the prerequisites of a target, the prerequisites are expanded a @emph{second
1724 time}.  In most circumstances this secondary expansion will have no effect,
1725 since all variable and function references will have been expanded during the
1726 initial parsing of the makefiles.  In order to take advantage of the secondary
1727 expansion phase of the parser, then, it's necessary to @emph{escape} the
1728 variable or function reference in the makefile.  In this case the first
1729 expansion merely un-escapes the reference but doesn't expand it, and expansion
1730 is left to the secondary expansion phase.  For example, consider this
1731 makefile:
1732
1733 @example
1734 .SECONDEXPANSION:
1735 ONEVAR = onefile
1736 TWOVAR = twofile
1737 myfile: $(ONEVAR) $$(TWOVAR)
1738 @end example
1739
1740 After the first expansion phase the prerequisites list of the
1741 @file{myfile} target will be @code{onefile} and @code{$(TWOVAR)}; the
1742 first (unescaped) variable reference to @var{ONEVAR} is expanded,
1743 while the second (escaped) variable reference is simply unescaped,
1744 without being recognized as a variable reference.  Now during the
1745 secondary expansion the first word is expanded again but since it
1746 contains no variable or function references it remains the value
1747 @file{onefile}, while the second word is now a normal reference to the
1748 variable @var{TWOVAR}, which is expanded to the value @file{twofile}.
1749 The final result is that there are two prerequisites, @file{onefile}
1750 and @file{twofile}.
1751
1752 Obviously, this is not a very interesting case since the same result
1753 could more easily have been achieved simply by having both variables
1754 appear, unescaped, in the prerequisites list.  One difference becomes
1755 apparent if the variables are reset; consider this example:
1756
1757 @example
1758 .SECONDEXPANSION:
1759 AVAR = top
1760 onefile: $(AVAR)
1761 twofile: $$(AVAR)
1762 AVAR = bottom
1763 @end example
1764
1765 Here the prerequisite of @file{onefile} will be expanded immediately,
1766 and resolve to the value @file{top}, while the prerequisite of
1767 @file{twofile} will not be full expanded until the secondary expansion
1768 and yield a value of @file{bottom}.
1769
1770 This is marginally more exciting, but the true power of this feature
1771 only becomes apparent when you discover that secondary expansions
1772 always take place within the scope of the automatic variables for that
1773 target.  This means that you can use variables such as @code{$@@},
1774 @code{$*}, etc. during the second expansion and they will have their
1775 expected values, just as in the recipe.  All you have to do is defer
1776 the expansion by escaping the @code{$}.  Also, secondary expansion
1777 occurs for both explicit and implicit (pattern) rules.  Knowing this,
1778 the possible uses for this feature increase dramatically.  For
1779 example:
1780
1781 @example
1782 .SECONDEXPANSION:
1783 main_OBJS := main.o try.o test.o
1784 lib_OBJS := lib.o api.o
1785
1786 main lib: $$($$@@_OBJS)
1787 @end example
1788
1789 Here, after the initial expansion the prerequisites of both the
1790 @file{main} and @file{lib} targets will be @code{$($@@_OBJS)}.  During
1791 the secondary expansion, the @code{$@@} variable is set to the name of
1792 the target and so the expansion for the @file{main} target will yield
1793 @code{$(main_OBJS)}, or @code{main.o try.o test.o}, while the
1794 secondary expansion for the @file{lib} target will yield
1795 @code{$(lib_OBJS)}, or @code{lib.o api.o}.
1796
1797 You can also mix in functions here, as long as they are properly escaped:
1798
1799 @example
1800 main_SRCS := main.c try.c test.c
1801 lib_SRCS := lib.c api.c
1802
1803 .SECONDEXPANSION:
1804 main lib: $$(patsubst %.c,%.o,$$($$@@_SRCS))
1805 @end example
1806
1807 This version allows users to specify source files rather than object
1808 files, but gives the same resulting prerequisites list as the previous
1809 example.
1810
1811 Evaluation of automatic variables during the secondary expansion
1812 phase, especially of the target name variable @code{$$@@}, behaves
1813 similarly to evaluation within recipes.  However, there are some
1814 subtle differences and ``corner cases'' which come into play for the
1815 different types of rule definitions that @code{make} understands.  The
1816 subtleties of using the different automatic variables are described
1817 below.
1818
1819 @subheading Secondary Expansion of Explicit Rules
1820 @cindex secondary expansion and explicit rules
1821 @cindex explicit rules, secondary expansion of
1822
1823 During the secondary expansion of explicit rules, @code{$$@@} and
1824 @code{$$%} evaluate, respectively, to the file name of the target and,
1825 when the target is an archive member, the target member name.  The
1826 @code{$$<} variable evaluates to the first prerequisite in the first
1827 rule for this target.  @code{$$^} and @code{$$+} evaluate to the list
1828 of all prerequisites of rules @emph{that have already appeared} for
1829 the same target (@code{$$+} with repetitions and @code{$$^}
1830 without).  The following example will help illustrate these behaviors:
1831
1832 @example
1833 .SECONDEXPANSION:
1834
1835 foo: foo.1 bar.1 $$< $$^ $$+    # line #1
1836
1837 foo: foo.2 bar.2 $$< $$^ $$+    # line #2
1838
1839 foo: foo.3 bar.3 $$< $$^ $$+    # line #3
1840 @end example
1841
1842 In the first prerequisite list, all three variables (@code{$$<},
1843 @code{$$^}, and @code{$$+}) expand to the empty string.  In the
1844 second, they will have values @code{foo.1}, @code{foo.1 bar.1}, and
1845 @code{foo.1 bar.1} respectively.  In the third they will have values
1846 @code{foo.1}, @code{foo.1 bar.1 foo.2 bar.2}, and @code{foo.1 bar.1
1847 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1} respectively.
1848
1849 Rules undergo secondary expansion in makefile order, except that
1850 the rule with the recipe is always evaluated last.
1851
1852 The variables @code{$$?} and @code{$$*} are not available and expand
1853 to the empty string.
1854
1855 @subheading Secondary Expansion of Static Pattern Rules
1856 @cindex secondary expansion and static pattern rules
1857 @cindex static pattern rules, secondary expansion of
1858
1859 Rules for secondary expansion of static pattern rules are identical to
1860 those for explicit rules, above, with one exception: for static
1861 pattern rules the @code{$$*} variable is set to the pattern stem.  As
1862 with explicit rules, @code{$$?} is not available and expands to the
1863 empty string.
1864
1865 @subheading Secondary Expansion of Implicit Rules
1866 @cindex secondary expansion and implicit rules
1867 @cindex implicit rules, secondary expansion of
1868
1869 As @code{make} searches for an implicit rule, it substitutes the stem
1870 and then performs secondary expansion for every rule with a matching
1871 target pattern.  The value of the automatic variables is derived in
1872 the same fashion as for static pattern rules.  As an example:
1873
1874 @example
1875 .SECONDEXPANSION:
1876
1877 foo: bar
1878
1879 foo foz: fo%: bo%
1880
1881 %oo: $$< $$^ $$+ $$*
1882 @end example
1883
1884 When the implicit rule is tried for target @file{foo}, @code{$$<}
1885 expands to @file{bar}, @code{$$^} expands to @file{bar boo},
1886 @code{$$+} also expands to @file{bar boo}, and @code{$$*} expands to
1887 @file{f}.
1888
1889 Note that the directory prefix (D), as described in @ref{Implicit Rule
1890 Search, ,Implicit Rule Search Algorithm}, is appended (after
1891 expansion) to all the patterns in the prerequisites list.  As an
1892 example:
1893
1894 @example
1895 .SECONDEXPANSION:
1896
1897 /tmp/foo.o:
1898
1899 %.o: $$(addsuffix /%.c,foo bar) foo.h
1900         @@echo $^
1901 @end example
1902
1903 The prerequisite list printed, after the secondary expansion and
1904 directory prefix reconstruction, will be @file{/tmp/foo/foo.c
1905 /tmp/bar/foo.c foo.h}.  If you are not interested in this
1906 reconstruction, you can use @code{$$*} instead of @code{%} in the
1907 prerequisites list.
1908
1909 @node Rules, Recipes, Makefiles, Top
1910 @chapter Writing Rules
1911 @cindex writing rules
1912 @cindex rule, how to write
1913 @cindex target
1914 @cindex prerequisite
1915
1916 A @dfn{rule} appears in the makefile and says when and how to remake
1917 certain files, called the rule's @dfn{targets} (most often only one per rule).
1918 It lists the other files that are the @dfn{prerequisites} of the target, and
1919 the @dfn{recipe} to use to create or update the target.
1920
1921 @cindex default goal
1922 @cindex goal, default
1923 The order of rules is not significant, except for determining the @dfn{default
1924 goal}: the target for @code{make} to consider, if you do not otherwise specify
1925 one.  The default goal is the first target of the first rule in the first
1926 makefile.  There are two exceptions: a target starting with a period is not a
1927 default unless it also contains one or more slashes, @samp{/}; and, a target
1928 that defines a pattern rule has no effect on the default goal.  (@xref{Pattern
1929 Rules, ,Defining and Redefining Pattern Rules}.)
1930
1931 Therefore, we usually write the makefile so that the first rule is the
1932 one for compiling the entire program or all the programs described by
1933 the makefile (often with a target called @samp{all}).
1934 @xref{Goals, ,Arguments to Specify the Goals}.
1935
1936 @menu
1937 * Rule Example::                An example explained.
1938 * Rule Syntax::                 General syntax explained.
1939 * Prerequisite Types::          There are two types of prerequisites.
1940 * Wildcards::                   Using wildcard characters such as `*'.
1941 * Directory Search::            Searching other directories for source files.
1942 * Phony Targets::               Using a target that is not a real file's name.
1943 * Force Targets::               You can use a target without a recipe
1944                                   or prerequisites to mark other targets
1945                                   as phony.
1946 * Empty Targets::               When only the date matters and the
1947                                   files are empty.
1948 * Special Targets::             Targets with special built-in meanings.
1949 * Multiple Targets::            When to make use of several targets in a rule.
1950 * Multiple Rules::              How to use several rules with the same target.
1951 * Static Pattern::              Static pattern rules apply to multiple targets
1952                                   and can vary the prerequisites according to
1953                                   the target name.
1954 * Double-Colon::                How to use a special kind of rule to allow
1955                                   several independent rules for one target.
1956 * Automatic Prerequisites::     How to automatically generate rules giving
1957                                   prerequisites from source files themselves.
1958 @end menu
1959
1960 @ifnottex
1961 @node Rule Example, Rule Syntax, Rules, Rules
1962 @section Rule Example
1963
1964 Here is an example of a rule:
1965
1966 @example
1967 foo.o : foo.c defs.h       # module for twiddling the frobs
1968         cc -c -g foo.c
1969 @end example
1970
1971 Its target is @file{foo.o} and its prerequisites are @file{foo.c} and
1972 @file{defs.h}.  It has one command in the recipe: @samp{cc -c -g foo.c}.
1973 The recipe starts with a tab to identify it as a recipe.
1974
1975 This rule says two things:
1976
1977 @itemize @bullet
1978 @item
1979 How to decide whether @file{foo.o} is out of date: it is out of date
1980 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1981 more recent than it.
1982
1983 @item
1984 How to update the file @file{foo.o}: by running @code{cc} as stated.
1985 The recipe does not explicitly mention @file{defs.h}, but we presume
1986 that @file{foo.c} includes it, and that is why @file{defs.h} was added
1987 to the prerequisites.
1988 @end itemize
1989 @end ifnottex
1990
1991 @node Rule Syntax, Prerequisite Types, Rule Example, Rules
1992 @section Rule Syntax
1993
1994 @cindex rule syntax
1995 @cindex syntax of rules
1996 In general, a rule looks like this:
1997
1998 @example
1999 @var{targets} : @var{prerequisites}
2000         @var{recipe}
2001         @dots{}
2002 @end example
2003
2004 @noindent
2005 or like this:
2006
2007 @example
2008 @var{targets} : @var{prerequisites} ; @var{recipe}
2009         @var{recipe}
2010         @dots{}
2011 @end example
2012
2013 @cindex targets
2014 @cindex rule targets
2015 The @var{targets} are file names, separated by spaces.  Wildcard
2016 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
2017 in File Names}) and a name of the form @file{@var{a}(@var{m})}
2018 represents member @var{m} in archive file @var{a}
2019 (@pxref{Archive Members, ,Archive Members as Targets}).
2020 Usually there is only one
2021 target per rule, but occasionally there is a reason to have more
2022 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).
2023
2024 @cindex recipes
2025 @cindex tab character (in commands)
2026 The @var{recipe} lines start with a tab character (or the first
2027 character in the value of the @code{.RECIPEPREFIX} variable;
2028 @pxref{Special Variables}).  The first recipe line may appear on the line
2029 after the prerequisites, with a tab character, or may appear on the
2030 same line, with a semicolon.  Either way, the effect is the same.
2031 There are other differences in the syntax of recipes.
2032 @xref{Recipes, ,Writing Recipes in Rules}.
2033
2034 @cindex dollar sign (@code{$}), in rules
2035 @cindex @code{$}, in rules
2036 @cindex rules, and @code{$}
2037 Because dollar signs are used to start @code{make} variable
2038 references, if you really want a dollar sign in a target or
2039 prerequisite you must write two of them, @samp{$$} (@pxref{Using
2040 Variables, ,How to Use Variables}).  If you have enabled secondary
2041 expansion (@pxref{Secondary Expansion}) and you want a literal dollar
2042 sign in the prerequisites list, you must actually write @emph{four}
2043 dollar signs (@samp{$$$$}).
2044
2045 You may split a long line by inserting a backslash followed by a
2046 newline, but this is not required, as @code{make} places no limit on
2047 the length of a line in a makefile.
2048
2049 A rule tells @code{make} two things: when the targets are out of date,
2050 and how to update them when necessary.
2051
2052 @cindex prerequisites
2053 @cindex rule prerequisites
2054 The criterion for being out of date is specified in terms of the
2055 @var{prerequisites}, which consist of file names separated by spaces.
2056 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
2057 A target is out of date if it does not exist or if it is older than any
2058 of the prerequisites (by comparison of last-modification times).  The
2059 idea is that the contents of the target file are computed based on
2060 information in the prerequisites, so if any of the prerequisites changes,
2061 the contents of the existing target file are no longer necessarily
2062 valid.
2063
2064 How to update is specified by a @var{recipe}.  This is one or more
2065 lines to be executed by the shell (normally @samp{sh}), but with some
2066 extra features (@pxref{Recipes, ,Writing Recipes in Rules}).
2067
2068 @node Prerequisite Types, Wildcards, Rule Syntax, Rules
2069 @comment  node-name,  next,  previous,  up
2070 @section Types of Prerequisites
2071 @cindex prerequisite types
2072 @cindex types of prerequisites
2073
2074 @cindex prerequisites, normal
2075 @cindex normal prerequisites
2076 @cindex prerequisites, order-only
2077 @cindex order-only prerequisites
2078 There are two different types of prerequisites understood by GNU @code{make}:
2079 normal prerequisites, described in the previous section, and @dfn{order-only}
2080 prerequisites.  A normal prerequisite makes two statements: first, it imposes
2081 an order in which recipes will be invoked: the recipes for all prerequisites
2082 of a target will be completed before the recipe for the target is started.
2083 Second, it imposes a dependency relationship: if any prerequisite is newer
2084 than the target, then the target is considered out-of-date and must be
2085 rebuilt.
2086
2087 Normally, this is exactly what you want: if a target's prerequisite is
2088 updated, then the target should also be updated.
2089
2090 Occasionally you may want to ensure that a prerequisite is built before a
2091 target, but @emph{without} forcing the target to be updated if the
2092 prerequisite is updated.  @dfn{Order-only} prerequisites are used to create
2093 this type of relationship.  Order-only prerequisites can be specified by
2094 placing a pipe symbol (@code{|}) in the prerequisites list: any prerequisites
2095 to the left of the pipe symbol are normal; any prerequisites to the right are
2096 order-only:
2097
2098 @example
2099 @var{targets} : @var{normal-prerequisites} | @var{order-only-prerequisites}
2100 @end example
2101
2102 The normal prerequisites section may of course be empty.  Also, you
2103 may still declare multiple lines of prerequisites for the same target:
2104 they are appended appropriately (normal prerequisites are appended to
2105 the list of normal prerequisites; order-only prerequisites are
2106 appended to the list of order-only prerequisites).  Note that if you
2107 declare the same file to be both a normal and an order-only
2108 prerequisite, the normal prerequisite takes precedence (since they
2109 have a strict superset of the behavior of an order-only prerequisite).
2110
2111 Order-only prerequisites are never checked when determining if the
2112 target is out of date; even order-only prerequisites marked as phony
2113 (@pxref{Phony Targets}) will not cause the target to be rebuilt.
2114
2115 Consider an example where your targets are to be placed in a separate
2116 directory, and that directory might not exist before @code{make} is
2117 run.  In this situation, you want the directory to be created before
2118 any targets are placed into it but, because the timestamps on
2119 directories change whenever a file is added, removed, or renamed, we
2120 certainly don't want to rebuild all the targets whenever the
2121 directory's timestamp changes.  One way to manage this is with
2122 order-only prerequisites: make the directory an order-only
2123 prerequisite on all the targets:
2124
2125 @example
2126 OBJDIR := objdir
2127 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
2128
2129 $(OBJDIR)/%.o : %.c
2130         $(COMPILE.c) $(OUTPUT_OPTION) $<
2131
2132 all: $(OBJS)
2133
2134 $(OBJS): | $(OBJDIR)
2135
2136 $(OBJDIR):
2137         mkdir $(OBJDIR)
2138 @end example
2139
2140 Now the rule to create the @file{objdir} directory will be run, if
2141 needed, before any @samp{.o} is built, but no @samp{.o} will be built
2142 because the @file{objdir} directory timestamp changed.
2143
2144 @node Wildcards, Directory Search, Prerequisite Types, Rules
2145 @section Using Wildcard Characters in File Names
2146 @cindex wildcard
2147 @cindex file name with wildcards
2148 @cindex globbing (wildcards)
2149
2150 @cindex @code{*} (wildcard character)
2151 @cindex @code{?} (wildcard character)
2152 @cindex @code{[@dots{}]} (wildcard characters)
2153 A single file name can specify many files using @dfn{wildcard characters}.
2154 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
2155 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
2156 specifies a list of all the files (in the working directory) whose names
2157 end in @samp{.c}.
2158
2159 If an expression matches multiple files than the results will be
2160 sorted.@footnote{Some older versions of GNU @code{make} did not sort the
2161 results of wildcard expansion.}  However multiple expressions will not be
2162 globally sorted.  For example, @file{*.c *.h} will list all the files whose
2163 names end in @samp{.c}, sorted, followed by all the files whose names end in
2164 @samp{.h}, sorted.
2165
2166 @cindex @code{~} (tilde)
2167 @cindex tilde (@code{~})
2168 @cindex home directory
2169 The character @samp{~} at the beginning of a file name also has special
2170 significance.  If alone, or followed by a slash, it represents your home
2171 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
2172 If the @samp{~} is followed by a word, the string represents the home
2173 directory of the user named by that word.  For example @file{~john/bin}
2174 expands to @file{/home/john/bin}.  On systems which don't have a home
2175 directory for each user (such as MS-DOS or MS-Windows), this
2176 functionality can be simulated by setting the environment variable
2177 @var{HOME}.
2178
2179 Wildcard expansion is performed by @code{make} automatically in
2180 targets and in prerequisites.  In recipes, the shell is responsible
2181 for wildcard expansion.  In other contexts, wildcard expansion happens
2182 only if you request it explicitly with the @code{wildcard} function.
2183
2184 The special significance of a wildcard character can be turned off by
2185 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
2186 specific file whose name consists of @samp{foo}, an asterisk, and
2187 @samp{bar}.
2188
2189 @menu
2190 * Wildcard Examples::           Several examples.
2191 * Wildcard Pitfall::            Problems to avoid.
2192 * Wildcard Function::           How to cause wildcard expansion where
2193                                   it does not normally take place.
2194 @end menu
2195
2196 @node Wildcard Examples, Wildcard Pitfall, Wildcards, Wildcards
2197 @subsection Wildcard Examples
2198
2199 Wildcards can be used in the recipe of a rule, where they are expanded
2200 by the shell.  For example, here is a rule to delete all the object files:
2201
2202 @example
2203 @group
2204 clean:
2205         rm -f *.o
2206 @end group
2207 @end example
2208 @cindex @code{rm} (shell command)
2209
2210 Wildcards are also useful in the prerequisites of a rule.  With the
2211 following rule in the makefile, @samp{make print} will print all the
2212 @samp{.c} files that have changed since the last time you printed them:
2213
2214 @example
2215 print: *.c
2216         lpr -p $?
2217         touch print
2218 @end example
2219
2220 @cindex @code{print} target
2221 @cindex @code{lpr} (shell command)
2222 @cindex @code{touch} (shell command)
2223 @noindent
2224 This rule uses @file{print} as an empty target file; see @ref{Empty
2225 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
2226 @samp{$?} is used to print only those files that have changed; see
2227 @ref{Automatic Variables}.)
2228
2229 Wildcard expansion does not happen when you define a variable.  Thus, if
2230 you write this:
2231
2232 @example
2233 objects = *.o
2234 @end example
2235
2236 @noindent
2237 then the value of the variable @code{objects} is the actual string
2238 @samp{*.o}.  However, if you use the value of @code{objects} in a
2239 target or prerequisite, wildcard expansion will take place there.  If
2240 you use the value of @code{objects} in a recipe, the shell may perform
2241 wildcard expansion when the recipe runs.  To set @code{objects} to the
2242 expansion, instead use:
2243
2244 @example
2245 objects := $(wildcard *.o)
2246 @end example
2247
2248 @noindent
2249 @xref{Wildcard Function}.
2250
2251 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
2252 @subsection Pitfalls of Using Wildcards
2253 @cindex wildcard pitfalls
2254 @cindex pitfalls of wildcards
2255 @cindex mistakes with wildcards
2256 @cindex errors with wildcards
2257 @cindex problems with wildcards
2258
2259 Now here is an example of a naive way of using wildcard expansion, that
2260 does not do what you would intend.  Suppose you would like to say that the
2261 executable file @file{foo} is made from all the object files in the
2262 directory, and you write this:
2263
2264 @example
2265 objects = *.o
2266
2267 foo : $(objects)
2268         cc -o foo $(CFLAGS) $(objects)
2269 @end example
2270
2271 @noindent
2272 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
2273 expansion happens in the rule for @file{foo}, so that each @emph{existing}
2274 @samp{.o} file becomes a prerequisite of @file{foo} and will be recompiled if
2275 necessary.
2276
2277 But what if you delete all the @samp{.o} files?  When a wildcard matches
2278 no files, it is left as it is, so then @file{foo} will depend on the
2279 oddly-named file @file{*.o}.  Since no such file is likely to exist,
2280 @code{make} will give you an error saying it cannot figure out how to
2281 make @file{*.o}.  This is not what you want!
2282
2283 Actually it is possible to obtain the desired result with wildcard
2284 expansion, but you need more sophisticated techniques, including the
2285 @code{wildcard} function and string substitution.
2286 @ifnottex
2287 @xref{Wildcard Function, ,The Function @code{wildcard}}.
2288 @end ifnottex
2289 @iftex
2290 These are described in the following section.
2291 @end iftex
2292
2293 @cindex wildcards and MS-DOS/MS-Windows backslashes
2294 @cindex backslashes in pathnames and wildcard expansion
2295
2296 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes to
2297 separate directories in pathnames, like so:
2298
2299 @example
2300   c:\foo\bar\baz.c
2301 @end example
2302
2303 This is equivalent to the Unix-style @file{c:/foo/bar/baz.c} (the
2304 @file{c:} part is the so-called drive letter).  When @code{make} runs on
2305 these systems, it supports backslashes as well as the Unix-style forward
2306 slashes in pathnames.  However, this support does @emph{not} include the
2307 wildcard expansion, where backslash is a quote character.  Therefore,
2308 you @emph{must} use Unix-style slashes in these cases.
2309
2310
2311 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
2312 @subsection The Function @code{wildcard}
2313 @findex wildcard
2314
2315 Wildcard expansion happens automatically in rules.  But wildcard expansion
2316 does not normally take place when a variable is set, or inside the
2317 arguments of a function.  If you want to do wildcard expansion in such
2318 places, you need to use the @code{wildcard} function, like this:
2319
2320 @example
2321 $(wildcard @var{pattern}@dots{})
2322 @end example
2323
2324 @noindent
2325 This string, used anywhere in a makefile, is replaced by a
2326 space-separated list of names of existing files that match one of the
2327 given file name patterns.  If no existing file name matches a pattern,
2328 then that pattern is omitted from the output of the @code{wildcard}
2329 function.  Note that this is different from how unmatched wildcards
2330 behave in rules, where they are used verbatim rather than ignored
2331 (@pxref{Wildcard Pitfall}).
2332
2333 As with wildcard expansion in rules, the results of the @code{wildcard}
2334 function are sorted.  But again, each individual expression is sorted
2335 separately, so @samp{$(wildcard *.c *.h)} will expand to all files matching
2336 @samp{.c}, sorted, followed by all files matching @samp{.h}, sorted.
2337
2338 One use of the @code{wildcard} function is to get a list of all the C source
2339 files in a directory, like this:
2340
2341 @example
2342 $(wildcard *.c)
2343 @end example
2344
2345 We can change the list of C source files into a list of object files by
2346 replacing the @samp{.c} suffix with @samp{.o} in the result, like this:
2347
2348 @example
2349 $(patsubst %.c,%.o,$(wildcard *.c))
2350 @end example
2351
2352 @noindent
2353 (Here we have used another function, @code{patsubst}.
2354 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)
2355
2356 Thus, a makefile to compile all C source files in the directory and then
2357 link them together could be written as follows:
2358
2359 @example
2360 objects := $(patsubst %.c,%.o,$(wildcard *.c))
2361
2362 foo : $(objects)
2363         cc -o foo $(objects)
2364 @end example
2365
2366 @noindent
2367 (This takes advantage of the implicit rule for compiling C programs, so
2368 there is no need to write explicit rules for compiling the files.
2369 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
2370 @samp{:=}, which is a variant of @samp{=}.)
2371
2372 @node Directory Search, Phony Targets, Wildcards, Rules
2373 @section Searching Directories for Prerequisites
2374 @vindex VPATH
2375 @findex vpath
2376 @cindex vpath
2377 @cindex search path for prerequisites (@code{VPATH})
2378 @cindex directory search (@code{VPATH})
2379
2380 For large systems, it is often desirable to put sources in a separate
2381 directory from the binaries.  The @dfn{directory search} features of
2382 @code{make} facilitate this by searching several directories
2383 automatically to find a prerequisite.  When you redistribute the files
2384 among directories, you do not need to change the individual rules,
2385 just the search paths.
2386
2387 @menu
2388 * General Search::              Specifying a search path that applies
2389                                   to every prerequisite.
2390 * Selective Search::            Specifying a search path
2391                                   for a specified class of names.
2392 * Search Algorithm::            When and how search paths are applied.
2393 * Recipes/Search::              How to write recipes that work together
2394                                   with search paths.
2395 * Implicit/Search::             How search paths affect implicit rules.
2396 * Libraries/Search::            Directory search for link libraries.
2397 @end menu
2398
2399 @node General Search, Selective Search, Directory Search, Directory Search
2400 @subsection @code{VPATH}: Search Path for All Prerequisites
2401 @vindex VPATH
2402
2403 The value of the @code{make} variable @code{VPATH} specifies a list of
2404 directories that @code{make} should search.  Most often, the
2405 directories are expected to contain prerequisite files that are not in the
2406 current directory; however, @code{make} uses @code{VPATH} as a search
2407 list for both prerequisites and targets of rules.
2408
2409 Thus, if a file that is listed as a target or prerequisite does not exist
2410 in the current directory, @code{make} searches the directories listed in
2411 @code{VPATH} for a file with that name.  If a file is found in one of
2412 them, that file may become the prerequisite (see below).  Rules may then
2413 specify the names of files in the prerequisite list as if they all
2414 existed in the current directory.  @xref{Recipes/Search, ,Writing Recipes with Directory Search}.
2415
2416 In the @code{VPATH} variable, directory names are separated by colons or
2417 blanks.  The order in which directories are listed is the order followed
2418 by @code{make} in its search.  (On MS-DOS and MS-Windows, semi-colons
2419 are used as separators of directory names in @code{VPATH}, since the
2420 colon can be used in the pathname itself, after the drive letter.)
2421
2422 For example,
2423
2424 @example
2425 VPATH = src:../headers
2426 @end example
2427
2428 @noindent
2429 specifies a path containing two directories, @file{src} and
2430 @file{../headers}, which @code{make} searches in that order.
2431
2432 With this value of @code{VPATH}, the following rule,
2433
2434 @example
2435 foo.o : foo.c
2436 @end example
2437
2438 @noindent
2439 is interpreted as if it were written like this:
2440
2441 @example
2442 foo.o : src/foo.c
2443 @end example
2444
2445 @noindent
2446 assuming the file @file{foo.c} does not exist in the current directory but
2447 is found in the directory @file{src}.
2448
2449 @node Selective Search, Search Algorithm, General Search, Directory Search
2450 @subsection The @code{vpath} Directive
2451 @findex vpath
2452
2453 Similar to the @code{VPATH} variable, but more selective, is the
2454 @code{vpath} directive (note lower case), which allows you to specify a
2455 search path for a particular class of file names: those that match a
2456 particular pattern.  Thus you can supply certain search directories for
2457 one class of file names and other directories (or none) for other file
2458 names.
2459
2460 There are three forms of the @code{vpath} directive:
2461
2462 @table @code
2463 @item vpath @var{pattern} @var{directories}
2464 Specify the search path @var{directories} for file names that match
2465 @var{pattern}.
2466
2467 The search path, @var{directories}, is a list of directories to be
2468 searched, separated by colons (semi-colons on MS-DOS and MS-Windows) or
2469 blanks, just like the search path used in the @code{VPATH} variable.
2470
2471 @item vpath @var{pattern}
2472 Clear out the search path associated with @var{pattern}.
2473
2474 @c Extra blank line makes sure this gets two lines.
2475 @item vpath
2476
2477 Clear all search paths previously specified with @code{vpath} directives.
2478 @end table
2479
2480 A @code{vpath} pattern is a string containing a @samp{%} character.  The
2481 string must match the file name of a prerequisite that is being searched
2482 for, the @samp{%} character matching any sequence of zero or more
2483 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
2484 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
2485 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
2486 prerequisite exactly, which is not useful very often.)
2487
2488 @cindex @code{%}, quoting in @code{vpath}
2489 @cindex @code{%}, quoting with @code{\} (backslash)
2490 @cindex @code{\} (backslash), to quote @code{%}
2491 @cindex backslash (@code{\}), to quote @code{%}
2492 @cindex quoting @code{%}, in @code{vpath}
2493 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
2494 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
2495 quote @samp{%} characters can be quoted with more backslashes.
2496 Backslashes that quote @samp{%} characters or other backslashes are
2497 removed from the pattern before it is compared to file names.  Backslashes
2498 that are not in danger of quoting @samp{%} characters go unmolested.
2499
2500 When a prerequisite fails to exist in the current directory, if the
2501 @var{pattern} in a @code{vpath} directive matches the name of the
2502 prerequisite file, then the @var{directories} in that directive are searched
2503 just like (and before) the directories in the @code{VPATH} variable.
2504
2505 For example,
2506
2507 @example
2508 vpath %.h ../headers
2509 @end example
2510
2511 @noindent
2512 tells @code{make} to look for any prerequisite whose name ends in @file{.h}
2513 in the directory @file{../headers} if the file is not found in the current
2514 directory.
2515
2516 If several @code{vpath} patterns match the prerequisite file's name, then
2517 @code{make} processes each matching @code{vpath} directive one by one,
2518 searching all the directories mentioned in each directive.  @code{make}
2519 handles multiple @code{vpath} directives in the order in which they
2520 appear in the makefile; multiple directives with the same pattern are
2521 independent of each other.
2522
2523 @need 750
2524 Thus,
2525
2526 @example
2527 @group
2528 vpath %.c foo
2529 vpath %   blish
2530 vpath %.c bar
2531 @end group
2532 @end example
2533
2534 @noindent
2535 will look for a file ending in @samp{.c} in @file{foo}, then
2536 @file{blish}, then @file{bar}, while
2537
2538 @example
2539 @group
2540 vpath %.c foo:bar
2541 vpath %   blish
2542 @end group
2543 @end example
2544
2545 @noindent
2546 will look for a file ending in @samp{.c} in @file{foo}, then
2547 @file{bar}, then @file{blish}.
2548
2549 @node Search Algorithm, Recipes/Search, Selective Search, Directory Search
2550 @subsection How Directory Searches are Performed
2551 @cindex algorithm for directory search
2552 @cindex directory search algorithm
2553
2554 When a prerequisite is found through directory search, regardless of type
2555 (general or selective), the pathname located may not be the one that
2556 @code{make} actually provides you in the prerequisite list.  Sometimes
2557 the path discovered through directory search is thrown away.
2558
2559 The algorithm @code{make} uses to decide whether to keep or abandon a
2560 path found via directory search is as follows:
2561
2562 @enumerate
2563 @item
2564 If a target file does not exist at the path specified in the makefile,
2565 directory search is performed.
2566
2567 @item
2568 If the directory search is successful, that path is kept and this file
2569 is tentatively stored as the target.
2570
2571 @item
2572 All prerequisites of this target are examined using this same method.
2573
2574 @item
2575 After processing the prerequisites, the target may or may not need to be
2576 rebuilt:
2577
2578 @enumerate a
2579 @item
2580 If the target does @emph{not} need to be rebuilt, the path to the file
2581 found during directory search is used for any prerequisite lists which
2582 contain this target.  In short, if @code{make} doesn't need to rebuild
2583 the target then you use the path found via directory search.
2584
2585 @item
2586 If the target @emph{does} need to be rebuilt (is out-of-date), the
2587 pathname found during directory search is @emph{thrown away}, and the
2588 target is rebuilt using the file name specified in the makefile.  In
2589 short, if @code{make} must rebuild, then the target is rebuilt locally,
2590 not in the directory found via directory search.
2591 @end enumerate
2592 @end enumerate
2593
2594 This algorithm may seem complex, but in practice it is quite often
2595 exactly what you want.
2596
2597 @cindex traditional directory search (GPATH)
2598 @cindex directory search, traditional (GPATH)
2599 Other versions of @code{make} use a simpler algorithm: if the file does
2600 not exist, and it is found via directory search, then that pathname is
2601 always used whether or not the target needs to be built.  Thus, if the
2602 target is rebuilt it is created at the pathname discovered during
2603 directory search.
2604
2605 @vindex GPATH
2606 If, in fact, this is the behavior you want for some or all of your
2607 directories, you can use the @code{GPATH} variable to indicate this to
2608 @code{make}.
2609
2610 @code{GPATH} has the same syntax and format as @code{VPATH} (that is, a
2611 space- or colon-delimited list of pathnames).  If an out-of-date target
2612 is found by directory search in a directory that also appears in
2613 @code{GPATH}, then that pathname is not thrown away.  The target is
2614 rebuilt using the expanded path.
2615
2616 @node Recipes/Search, Implicit/Search, Search Algorithm, Directory Search
2617 @subsection Writing Recipes with Directory Search
2618 @cindex recipes, and directory search
2619 @cindex directory search (@code{VPATH}), and recipes
2620
2621 When a prerequisite is found in another directory through directory search,
2622 this cannot change the recipe of the rule; they will execute as written.
2623 Therefore, you must write the recipe with care so that it will look for
2624 the prerequisite in the directory where @code{make} finds it.
2625
2626 This is done with the @dfn{automatic variables} such as @samp{$^}
2627 (@pxref{Automatic Variables}).
2628 For instance, the value of @samp{$^} is a
2629 list of all the prerequisites of the rule, including the names of
2630 the directories in which they were found, and the value of
2631 @samp{$@@} is the target.  Thus:
2632
2633 @example
2634 foo.o : foo.c
2635         cc -c $(CFLAGS) $^ -o $@@
2636 @end example
2637
2638 @noindent
2639 (The variable @code{CFLAGS} exists so you can specify flags for C
2640 compilation by implicit rules; we use it here for consistency so it will
2641 affect all C compilations uniformly;
2642 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
2643
2644 Often the prerequisites include header files as well, which you do not
2645 want to mention in the recipe.  The automatic variable @samp{$<} is
2646 just the first prerequisite:
2647
2648 @example
2649 VPATH = src:../headers
2650 foo.o : foo.c defs.h hack.h
2651         cc -c $(CFLAGS) $< -o $@@
2652 @end example
2653
2654 @node Implicit/Search, Libraries/Search, Recipes/Search, Directory Search
2655 @subsection Directory Search and Implicit Rules
2656 @cindex @code{VPATH}, and implicit rules
2657 @cindex directory search (@code{VPATH}), and implicit rules
2658 @cindex search path for prerequisites (@code{VPATH}), and implicit rules
2659 @cindex implicit rule, and directory search
2660 @cindex implicit rule, and @code{VPATH}
2661 @cindex rule, implicit, and directory search
2662 @cindex rule, implicit, and @code{VPATH}
2663
2664 The search through the directories specified in @code{VPATH} or with
2665 @code{vpath} also happens during consideration of implicit rules
2666 (@pxref{Implicit Rules, ,Using Implicit Rules}).
2667
2668 For example, when a file @file{foo.o} has no explicit rule, @code{make}
2669 considers implicit rules, such as the built-in rule to compile
2670 @file{foo.c} if that file exists.  If such a file is lacking in the
2671 current directory, the appropriate directories are searched for it.  If
2672 @file{foo.c} exists (or is mentioned in the makefile) in any of the
2673 directories, the implicit rule for C compilation is applied.
2674
2675 The recipes of implicit rules normally use automatic variables as a
2676 matter of necessity; consequently they will use the file names found by
2677 directory search with no extra effort.
2678
2679 @node Libraries/Search,  , Implicit/Search, Directory Search
2680 @subsection Directory Search for Link Libraries
2681 @cindex link libraries, and directory search
2682 @cindex libraries for linking, directory search
2683 @cindex directory search (@code{VPATH}), and link libraries
2684 @cindex @code{VPATH}, and link libraries
2685 @cindex search path for prerequisites (@code{VPATH}), and link libraries
2686 @cindex @code{-l} (library search)
2687 @cindex link libraries, patterns matching
2688 @cindex @code{.LIBPATTERNS}, and link libraries
2689 @vindex .LIBPATTERNS
2690
2691 Directory search applies in a special way to libraries used with the
2692 linker.  This special feature comes into play when you write a prerequisite
2693 whose name is of the form @samp{-l@var{name}}.  (You can tell something
2694 strange is going on here because the prerequisite is normally the name of a
2695 file, and the @emph{file name} of a library generally looks like
2696 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)
2697
2698 When a prerequisite's name has the form @samp{-l@var{name}}, @code{make}
2699 handles it specially by searching for the file @file{lib@var{name}.so},
2700 and, if it is not found, for the file @file{lib@var{name}.a} in the current
2701 directory, in directories specified by matching @code{vpath}
2702 search paths and the @code{VPATH} search path, and then in the
2703 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
2704 (normally @file{/usr/local/lib}, but MS-DOS/MS-Windows versions of
2705 @code{make} behave as if @var{prefix} is defined to be the root of the
2706 DJGPP installation tree).
2707
2708 For example, if there is a @file{/usr/lib/libcurses.a} library on your
2709 system (and no @file{/usr/lib/libcurses.so} file), then
2710
2711 @example
2712 @group
2713 foo : foo.c -lcurses
2714         cc $^ -o $@@
2715 @end group
2716 @end example
2717
2718 @noindent
2719 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
2720 be executed when @file{foo} is older than @file{foo.c} or than
2721 @file{/usr/lib/libcurses.a}.
2722
2723 Although the default set of files to be searched for is
2724 @file{lib@var{name}.so} and @file{lib@var{name}.a}, this is customizable
2725 via the @code{.LIBPATTERNS} variable.  Each word in the value of this
2726 variable is a pattern string.  When a prerequisite like
2727 @samp{-l@var{name}} is seen, @code{make} will replace the percent in
2728 each pattern in the list with @var{name} and perform the above directory
2729 searches using each library file name.
2730
2731 The default value for @code{.LIBPATTERNS} is @samp{lib%.so lib%.a},
2732 which provides the default behavior described above.
2733
2734 You can turn off link library expansion completely by setting this
2735 variable to an empty value.
2736
2737 @node Phony Targets, Force Targets, Directory Search, Rules
2738 @section Phony Targets
2739 @cindex phony targets
2740 @cindex targets, phony
2741 @cindex targets without a file
2742
2743 A phony target is one that is not really the name of a file; rather it
2744 is just a name for a recipe to be executed when you make an explicit
2745 request.  There are two reasons to use a phony target: to avoid a
2746 conflict with a file of the same name, and to improve performance.
2747
2748 If you write a rule whose recipe will not create the target file, the
2749 recipe will be executed every time the target comes up for remaking.
2750 Here is an example:
2751
2752 @example
2753 @group
2754 clean:
2755         rm *.o temp
2756 @end group
2757 @end example
2758
2759 @noindent
2760 Because the @code{rm} command does not create a file named @file{clean},
2761 probably no such file will ever exist.  Therefore, the @code{rm} command
2762 will be executed every time you say @samp{make clean}.
2763 @cindex @code{rm} (shell command)
2764
2765 @findex .PHONY
2766 In this example, the @file{clean} target will not work properly if a
2767 file named @file{clean} is ever created in this directory.  Since it
2768 has no prerequisites, @file{clean} would always be considered up to
2769 date and its recipe would not be executed.  To avoid this problem you
2770 can explicitly declare the target to be phony by making it a
2771 prerequisite of the special target @code{.PHONY}
2772 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
2773
2774 @example
2775 @group
2776 .PHONY: clean
2777 clean:
2778         rm *.o temp
2779 @end group
2780 @end example
2781
2782 @noindent
2783 Once this is done, @samp{make clean} will run the recipe regardless of
2784 whether there is a file named @file{clean}.
2785
2786 Prerequisites of @code{.PHONY} are always interpreted as literal
2787 target names, never as patterns (even if they contain @samp{%}
2788 characters).  To always rebuild a pattern rule consider using a
2789 ``force target'' (@pxref{Force Targets, ,Rules without Recipes or
2790 Prerequisites}).
2791
2792 Phony targets are also useful in conjunction with recursive
2793 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of @code{make}}).
2794 In this situation the makefile will often contain a variable which
2795 lists a number of sub-directories to be built.  A simplistic way to
2796 handle this is to define one rule with a recipe that loops over the
2797 sub-directories, like this:
2798
2799 @example
2800 @group
2801 SUBDIRS = foo bar baz
2802
2803 subdirs:
2804         for dir in $(SUBDIRS); do \
2805           $(MAKE) -C $$dir; \
2806         done
2807 @end group
2808 @end example
2809
2810 There are problems with this method, however.  First, any error detected in a
2811 sub-make is ignored by this rule, so it will continue to build the rest of the
2812 directories even when one fails.  This can be overcome by adding shell
2813 commands to note the error and exit, but then it will do so even if
2814 @code{make} is invoked with the @code{-k} option, which is unfortunate.
2815 Second, and perhaps more importantly, you cannot take full advantage of
2816 @code{make}'s ability to build targets in parallel (@pxref{Parallel, ,Parallel
2817 Execution}), since there is only one rule.  Each individual makefile's targets
2818 will be built in parallel, but only one sub-directory will be built at a time.
2819
2820 By declaring the sub-directories as @code{.PHONY} targets (you must do
2821 this as the sub-directory obviously always exists; otherwise it won't
2822 be built) you can remove these problems:
2823
2824 @example
2825 @group
2826 SUBDIRS = foo bar baz
2827
2828 .PHONY: subdirs $(SUBDIRS)
2829
2830 subdirs: $(SUBDIRS)
2831
2832 $(SUBDIRS):
2833         $(MAKE) -C $@@
2834
2835 foo: baz
2836 @end group
2837 @end example
2838
2839 Here we've also declared that the @file{foo} sub-directory cannot be
2840 built until after the @file{baz} sub-directory is complete; this kind of
2841 relationship declaration is particularly important when attempting
2842 parallel builds.
2843
2844 The implicit rule search (@pxref{Implicit Rules}) is skipped for
2845 @code{.PHONY} targets.  This is why declaring a target as
2846 @code{.PHONY} is good for performance, even if you are not worried
2847 about the actual file existing.
2848
2849 A phony target should not be a prerequisite of a real target file; if it is,
2850 its recipe will be run every time @code{make} considers that file.  As long as
2851 a phony target is never a prerequisite of a real target, the phony target
2852 recipe will be executed only when the phony target is a specified goal
2853 (@pxref{Goals, ,Arguments to Specify the Goals}).
2854
2855 You should not declare an included makefile as phony.  Phony targets are not
2856 intended to represent real files, and because the target is always considered
2857 out of date make will always rebuild it then re-execute itself
2858 (@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).  To avoid this,
2859 @code{make} will not re-execute itself if an included file marked as phony is
2860 re-built.
2861
2862 Phony targets can have prerequisites.  When one directory contains multiple
2863 programs, it is most convenient to describe all of the programs in one
2864 makefile @file{./Makefile}.  Since the target remade by default will be the
2865 first one in the makefile, it is common to make this a phony target named
2866 @samp{all} and give it, as prerequisites, all the individual programs.  For
2867 example:
2868
2869 @example
2870 all : prog1 prog2 prog3
2871 .PHONY : all
2872
2873 prog1 : prog1.o utils.o
2874         cc -o prog1 prog1.o utils.o
2875
2876 prog2 : prog2.o
2877         cc -o prog2 prog2.o
2878
2879 prog3 : prog3.o sort.o utils.o
2880         cc -o prog3 prog3.o sort.o utils.o
2881 @end example
2882
2883 @noindent
2884 Now you can say just @samp{make} to remake all three programs, or
2885 specify as arguments the ones to remake (as in @samp{make prog1
2886 prog3}).  Phoniness is not inherited: the prerequisites of a phony
2887 target are not themselves phony, unless explicitly declared to be so.
2888
2889 When one phony target is a prerequisite of another, it serves as a subroutine
2890 of the other.  For example, here @samp{make cleanall} will delete the
2891 object files, the difference files, and the file @file{program}:
2892
2893 @example
2894 .PHONY: cleanall cleanobj cleandiff
2895
2896 cleanall : cleanobj cleandiff
2897         rm program
2898
2899 cleanobj :
2900         rm *.o
2901
2902 cleandiff :
2903         rm *.diff
2904 @end example
2905
2906 @node Force Targets, Empty Targets, Phony Targets, Rules
2907 @section Rules without Recipes or Prerequisites
2908 @cindex force targets
2909 @cindex targets, force
2910 @cindex @code{FORCE}
2911 @cindex rule, no recipe or prerequisites
2912
2913 If a rule has no prerequisites or recipe, and the target of the rule
2914 is a nonexistent file, then @code{make} imagines this target to have
2915 been updated whenever its rule is run.  This implies that all targets
2916 depending on this one will always have their recipe run.
2917
2918 An example will illustrate this:
2919
2920 @example
2921 @group
2922 clean: FORCE
2923         rm $(objects)
2924 FORCE:
2925 @end group
2926 @end example
2927
2928 Here the target @samp{FORCE} satisfies the special conditions, so the
2929 target @file{clean} that depends on it is forced to run its recipe.
2930 There is nothing special about the name @samp{FORCE}, but that is one
2931 name commonly used this way.
2932
2933 As you can see, using @samp{FORCE} this way has the same results as using
2934 @samp{.PHONY: clean}.
2935
2936 Using @samp{.PHONY} is more explicit and more efficient.  However,
2937 other versions of @code{make} do not support @samp{.PHONY}; thus
2938 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2939
2940 @node Empty Targets, Special Targets, Force Targets, Rules
2941 @section Empty Target Files to Record Events
2942 @cindex empty targets
2943 @cindex targets, empty
2944 @cindex recording events with empty targets
2945
2946 The @dfn{empty target} is a variant of the phony target; it is used to hold
2947 recipes for an action that you request explicitly from time to time.
2948 Unlike a phony target, this target file can really exist; but the file's
2949 contents do not matter, and usually are empty.
2950
2951 The purpose of the empty target file is to record, with its
2952 last-modification time, when the rule's recipe was last executed.  It
2953 does so because one of the commands in the recipe is a @code{touch}
2954 command to update the target file.
2955
2956 The empty target file should have some prerequisites (otherwise it
2957 doesn't make sense).  When you ask to remake the empty target, the
2958 recipe is executed if any prerequisite is more recent than the target;
2959 in other words, if a prerequisite has changed since the last time you
2960 remade the target.  Here is an example:
2961
2962 @example
2963 print: foo.c bar.c
2964         lpr -p $?
2965         touch print
2966 @end example
2967 @cindex @code{print} target
2968 @cindex @code{lpr} (shell command)
2969 @cindex @code{touch} (shell command)
2970
2971 @noindent
2972 With this rule, @samp{make print} will execute the @code{lpr} command if
2973 either source file has changed since the last @samp{make print}.  The
2974 automatic variable @samp{$?} is used to print only those files that have
2975 changed (@pxref{Automatic Variables}).
2976
2977 @node Special Targets, Multiple Targets, Empty Targets, Rules
2978 @section Special Built-in Target Names
2979 @cindex special targets
2980 @cindex built-in special targets
2981 @cindex targets, built-in special
2982
2983 Certain names have special meanings if they appear as targets.
2984
2985 @table @code
2986 @findex .PHONY
2987 @item .PHONY
2988
2989 The prerequisites of the special target @code{.PHONY} are considered to
2990 be phony targets.  When it is time to consider such a target,
2991 @code{make} will run its recipe unconditionally, regardless of
2992 whether a file with that name exists or what its last-modification
2993 time is.  @xref{Phony Targets, ,Phony Targets}.
2994
2995 @findex .SUFFIXES
2996 @item .SUFFIXES
2997
2998 The prerequisites of the special target @code{.SUFFIXES} are the list
2999 of suffixes to be used in checking for suffix rules.
3000 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
3001
3002 @findex .DEFAULT
3003 @item .DEFAULT
3004
3005 The recipe specified for @code{.DEFAULT} is used for any target for
3006 which no rules are found (either explicit rules or implicit rules).
3007 @xref{Last Resort}.  If a @code{.DEFAULT} recipe is specified, every
3008 file mentioned as a prerequisite, but not as a target in a rule, will have
3009 that recipe executed on its behalf.  @xref{Implicit Rule Search,
3010 ,Implicit Rule Search Algorithm}.
3011
3012 @findex .PRECIOUS
3013 @item .PRECIOUS
3014 @cindex precious targets
3015 @cindex preserving with @code{.PRECIOUS}
3016
3017 The targets which @code{.PRECIOUS} depends on are given the following
3018 special treatment: if @code{make} is killed or interrupted during the
3019 execution of their recipes, the target is not deleted.
3020 @xref{Interrupts, ,Interrupting or Killing @code{make}}.  Also, if the
3021 target is an intermediate file, it will not be deleted after it is no
3022 longer needed, as is normally done.  @xref{Chained Rules, ,Chains of
3023 Implicit Rules}.  In this latter respect it overlaps with the
3024 @code{.SECONDARY} special target.
3025
3026 You can also list the target pattern of an implicit rule (such as
3027 @samp{%.o}) as a prerequisite file of the special target @code{.PRECIOUS}
3028 to preserve intermediate files created by rules whose target patterns
3029 match that file's name.
3030
3031 @findex .INTERMEDIATE
3032 @item .INTERMEDIATE
3033 @cindex intermediate targets, explicit
3034
3035 The targets which @code{.INTERMEDIATE} depends on are treated as
3036 intermediate files.  @xref{Chained Rules, ,Chains of Implicit Rules}.
3037 @code{.INTERMEDIATE} with no prerequisites has no effect.
3038
3039 @findex .NOTINTERMEDIATE
3040 @item .NOTINTERMEDIATE
3041 @cindex not intermediate targets, explicit
3042
3043 Prerequisites of the special target @code{.NOTINTERMEDIATE} are never
3044 considered intermediate files.  @xref{Chained Rules, ,Chains of Implicit Rules}.
3045 @code{.NOTINTERMEDIATE} with no prerequisites causes all targets to be treated
3046 as not intermediate.
3047
3048 If the prerequisite is a target pattern then targets that are built using that
3049 pattern rule are not considered intermediate.
3050
3051 @findex .SECONDARY
3052 @item .SECONDARY
3053 @cindex secondary targets
3054 @cindex preserving with @code{.SECONDARY}
3055
3056 The targets which @code{.SECONDARY} depends on are treated as
3057 intermediate files, except that they are never automatically deleted.
3058 @xref{Chained Rules, ,Chains of Implicit Rules}.
3059
3060 @code{.SECONDARY} can be used to avoid redundant rebuilds in some unusual
3061 situations.  For example:
3062
3063 @example
3064 @group
3065 hello.bin: hello.o bye.o
3066         $(CC) -o $@@ $^
3067
3068 %.o: %.c
3069         $(CC) -c -o $@@ $<
3070
3071 .SECONDARY: hello.o bye.o
3072 @end group
3073 @end example
3074
3075 Suppose @file{hello.bin} is up to date in regards to the source files,
3076 @emph{but} the object file @file{hello.o} is missing.  Without
3077 @code{.SECONDARY} make would rebuild @file{hello.o} then rebuild
3078 @file{hello.bin} even though the source files had not changed.  By declaring
3079 @file{hello.o} as @code{.SECONDARY} @code{make} will not need to rebuild it
3080 and won't need to rebuild @file{hello.bin} either.  Of course, of one of the
3081 source files @emph{were} updated then all object files would be rebuilt so
3082 that the creation of @file{hello.bin} could succeed.
3083
3084 @code{.SECONDARY} with no prerequisites causes all targets to be treated
3085 as secondary (i.e., no target is removed because it is considered
3086 intermediate).
3087
3088 @findex .SECONDEXPANSION
3089 @item .SECONDEXPANSION
3090
3091 If @code{.SECONDEXPANSION} is mentioned as a target anywhere in the
3092 makefile, then all prerequisite lists defined @emph{after} it appears
3093 will be expanded a second time after all makefiles have been read in.
3094 @xref{Secondary Expansion, ,Secondary Expansion}.
3095
3096 @findex .DELETE_ON_ERROR
3097 @item .DELETE_ON_ERROR
3098 @cindex removing targets on failure
3099
3100 If @code{.DELETE_ON_ERROR} is mentioned as a target anywhere in the
3101 makefile, then @code{make} will delete the target of a rule if it has
3102 changed and its recipe exits with a nonzero exit status, just as it
3103 does when it receives a signal.  @xref{Errors, ,Errors in Recipes}.
3104
3105 @findex .IGNORE
3106 @item .IGNORE
3107
3108 If you specify prerequisites for @code{.IGNORE}, then @code{make} will
3109 ignore errors in execution of the recipe for those particular files.
3110 The recipe for @code{.IGNORE} (if any) is ignored.
3111
3112 If mentioned as a target with no prerequisites, @code{.IGNORE} says to
3113 ignore errors in execution of recipes for all files.  This usage of
3114 @samp{.IGNORE} is supported only for historical compatibility.  Since
3115 this affects every recipe in the makefile, it is not very useful; we
3116 recommend you use the more selective ways to ignore errors in specific
3117 recipes.  @xref{Errors, ,Errors in Recipes}.
3118
3119 @findex .LOW_RESOLUTION_TIME
3120 @item .LOW_RESOLUTION_TIME
3121
3122 If you specify prerequisites for @code{.LOW_RESOLUTION_TIME},
3123 @command{make} assumes that these files are created by commands that
3124 generate low resolution time stamps.  The recipe for the
3125 @code{.LOW_RESOLUTION_TIME} target are ignored.
3126
3127 The high resolution file time stamps of many modern file systems
3128 lessen the chance of @command{make} incorrectly concluding that a file
3129 is up to date.  Unfortunately, some hosts do not provide a way to set a
3130 high resolution file time stamp, so commands like @samp{cp -p} that
3131 explicitly set a file's time stamp must discard its sub-second part.
3132 If a file is created by such a command, you should list it as a
3133 prerequisite of @code{.LOW_RESOLUTION_TIME} so that @command{make}
3134 does not mistakenly conclude that the file is out of date.  For
3135 example:
3136
3137 @example
3138 @group
3139 .LOW_RESOLUTION_TIME: dst
3140 dst: src
3141         cp -p src dst
3142 @end group
3143 @end example
3144
3145 Since @samp{cp -p} discards the sub-second part of @file{src}'s time
3146 stamp, @file{dst} is typically slightly older than @file{src} even when
3147 it is up to date.  The @code{.LOW_RESOLUTION_TIME} line causes
3148 @command{make} to consider @file{dst} to be up to date if its time stamp
3149 is at the start of the same second that @file{src}'s time stamp is in.
3150
3151 Due to a limitation of the archive format, archive member time stamps
3152 are always low resolution.  You need not list archive members as
3153 prerequisites of @code{.LOW_RESOLUTION_TIME}, as @command{make} does this
3154 automatically.
3155
3156 @findex .SILENT
3157 @item .SILENT
3158
3159 If you specify prerequisites for @code{.SILENT}, then @code{make} will
3160 not print the recipe used to remake those particular files before
3161 executing them.  The recipe for @code{.SILENT} is ignored.
3162
3163 If mentioned as a target with no prerequisites, @code{.SILENT} says
3164 not to print any recipes before executing them.  You may also use more
3165 selective ways to silence specific recipe command lines.
3166 @xref{Echoing, ,Recipe Echoing}.  If you want to silence all recipes
3167 for a particular run of @code{make}, use the @samp{-s} or
3168 @w{@samp{--silent}} option (@pxref{Options Summary}).
3169
3170 @findex .EXPORT_ALL_VARIABLES
3171 @item .EXPORT_ALL_VARIABLES
3172
3173 Simply by being mentioned as a target, this tells @code{make} to export all
3174 variables to child processes by default.  This is an alternative to using
3175 @code{export} with no arguments.  @xref{Variables/Recursion, ,Communicating
3176 Variables to a Sub-@code{make}}.
3177
3178 @findex .NOTPARALLEL
3179 @item .NOTPARALLEL
3180 @cindex parallel execution, overriding
3181
3182 If @code{.NOTPARALLEL} is mentioned as a target with no prerequisites, all
3183 targets in this invocation of @code{make} will be run serially, even if the
3184 @samp{-j} option is given.  Any recursively invoked @code{make} command will
3185 still run recipes in parallel (unless its makefile also contains this target).
3186
3187 If @code{.NOTPARALLEL} has targets as prerequisites, then all the
3188 prerequisites of those targets will be run serially.  This implicitly adds a
3189 @code{.WAIT} between each prerequisite of the listed targets.  @xref{Parallel
3190 Disable, , Disabling Parallel Execution}.
3191
3192 @findex .ONESHELL
3193 @item .ONESHELL
3194 @cindex recipe execution, single invocation
3195
3196 If @code{.ONESHELL} is mentioned as a target, then when a target is
3197 built all lines of the recipe will be given to a single invocation of
3198 the shell rather than each line being invoked separately.
3199 @xref{Execution, ,Recipe Execution}.
3200
3201 @findex .POSIX
3202 @item .POSIX
3203 @cindex POSIX-conforming mode, setting
3204
3205 If @code{.POSIX} is mentioned as a target, then the makefile will be
3206 parsed and run in POSIX-conforming mode.  This does @emph{not} mean
3207 that only POSIX-conforming makefiles will be accepted: all advanced
3208 GNU @code{make} features are still available.  Rather, this target
3209 causes @code{make} to behave as required by POSIX in those areas
3210 where @code{make}'s default behavior differs.
3211
3212 In particular, if this target is mentioned then recipes will be
3213 invoked as if the shell had been passed the @code{-e} flag: the first
3214 failing command in a recipe will cause the recipe to fail immediately.
3215 @end table
3216
3217 Any defined implicit rule suffix also counts as a special target if it
3218 appears as a target, and so does the concatenation of two suffixes, such
3219 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
3220 defining implicit rules (but a way still widely used).  In principle, any
3221 target name could be special in this way if you break it in two and add
3222 both pieces to the suffix list.  In practice, suffixes normally begin with
3223 @samp{.}, so these special target names also begin with @samp{.}.
3224 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
3225
3226 @node Multiple Targets, Multiple Rules, Special Targets, Rules
3227 @section Multiple Targets in a Rule
3228 @cindex multiple targets
3229 @cindex several targets in a rule
3230 @cindex targets, multiple
3231 @cindex rule, with multiple targets
3232
3233 When an explicit rule has multiple targets they can be treated in one
3234 of two possible ways: as independent targets or as grouped targets.
3235 The manner in which they are treated is determined by the separator that
3236 appears after the list of targets.
3237
3238 @subsubheading Rules with Independent Targets
3239 @cindex independent targets
3240 @cindex targets, independent
3241
3242 Rules that use the standard target separator, @code{:}, define
3243 independent targets.  This is equivalent to writing the same rule once
3244 for each target, with duplicated prerequisites and recipes.  Typically,
3245 the recipe would use automatic variables such as @samp{$@@} to specify
3246 which target is being built.
3247
3248 Rules with independent targets are useful in two cases:
3249
3250 @itemize @bullet
3251 @item
3252 You want just prerequisites, no recipe.  For example:
3253
3254 @example
3255 kbd.o command.o files.o: command.h
3256 @end example
3257
3258 @noindent
3259 gives an additional prerequisite to each of the three object files
3260 mentioned.  It is equivalent to writing:
3261
3262 @example
3263 kbd.o: command.h
3264 command.o: command.h
3265 files.o: command.h
3266 @end example
3267
3268 @item
3269 Similar recipes work for all the targets.  The automatic variable
3270 @samp{$@@} can be used to substitute the particular target to be
3271 remade into the commands (@pxref{Automatic Variables}).  For example:
3272
3273 @example
3274 @group
3275 bigoutput littleoutput : text.g
3276         generate text.g -$(subst output,,$@@) > $@@
3277 @end group
3278 @end example
3279 @findex subst
3280
3281 @noindent
3282 is equivalent to
3283
3284 @example
3285 bigoutput : text.g
3286         generate text.g -big > bigoutput
3287 littleoutput : text.g
3288         generate text.g -little > littleoutput
3289 @end example
3290
3291 @noindent
3292 Here we assume the hypothetical program @code{generate} makes two
3293 types of output, one if given @samp{-big} and one if given
3294 @samp{-little}.
3295 @xref{Text Functions, ,Functions for String Substitution and Analysis},
3296 for an explanation of the @code{subst} function.
3297 @end itemize
3298
3299 Suppose you would like to vary the prerequisites according to the
3300 target, much as the variable @samp{$@@} allows you to vary the recipe.
3301 You cannot do this with multiple targets in an ordinary rule, but you
3302 can do it with a @dfn{static pattern rule}.  @xref{Static Pattern,
3303 ,Static Pattern Rules}.
3304
3305 @subsubheading Rules with Grouped Targets
3306 @cindex grouped targets
3307 @cindex targets, grouped
3308
3309 If instead of independent targets you have a recipe that generates multiple
3310 files from a single invocation, you can express that relationship by declaring
3311 your rule to use @emph{grouped targets}.  A grouped target rule uses the
3312 separator @code{&:} (the @samp{&} here is used to imply ``all'').
3313
3314 When @code{make} builds any one of the grouped targets, it understands that
3315 all the other targets in the group are also updated as a result of the
3316 invocation of the recipe.  Furthermore, if only some of the grouped targets
3317 are out of date or missing @code{make} will realize that running the recipe
3318 will update all of the targets.  Finally, if any of the grouped targets are
3319 out of date, all the grouped targets are considered out of date.
3320
3321 As an example, this rule defines a grouped target:
3322
3323 @example
3324 @group
3325 foo bar biz &: baz boz
3326         echo $^ > foo
3327         echo $^ > bar
3328         echo $^ > biz
3329 @end group
3330 @end example
3331
3332 During the execution of a grouped target's recipe, the automatic
3333 variable @samp{$@@} is set to the name of the particular target in the
3334 group which triggered the rule.  Caution must be used if relying on
3335 this variable in the recipe of a grouped target rule.
3336
3337 Unlike independent targets, a grouped target rule @emph{must} include
3338 a recipe.  However, targets that are members of a grouped target may
3339 also appear in independent target rule definitions that do not have
3340 recipes.
3341
3342 Each target may have only one recipe associated with it.  If a grouped
3343 target appears in either an independent target rule or in another
3344 grouped target rule with a recipe, you will get a warning and the
3345 latter recipe will replace the former recipe.  Additionally the target
3346 will be removed from the previous group and appear only in the new
3347 group.
3348
3349 If you would like a target to appear in multiple groups, then you must
3350 use the double-colon grouped target separator, @code{&::} when
3351 declaring all of the groups containing that target.  Grouped
3352 double-colon targets are each considered independently, and each
3353 grouped double-colon rule's recipe is executed at most once, if at
3354 least one of its multiple targets requires updating.
3355
3356 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
3357 @section Multiple Rules for One Target
3358 @cindex multiple rules for one target
3359 @cindex several rules for one target
3360 @cindex rule, multiple for one target
3361 @cindex target, multiple rules for one
3362
3363 One file can be the target of several rules.  All the prerequisites
3364 mentioned in all the rules are merged into one list of prerequisites for
3365 the target.  If the target is older than any prerequisite from any rule,
3366 the recipe is executed.
3367
3368 There can only be one recipe to be executed for a file.  If more than
3369 one rule gives a recipe for the same file, @code{make} uses the last
3370 one given and prints an error message.  (As a special case, if the
3371 file's name begins with a dot, no error message is printed.  This odd
3372 behavior is only for compatibility with other implementations of
3373 @code{make}@dots{} you should avoid using it).  Occasionally it is
3374 useful to have the same target invoke multiple recipes which are
3375 defined in different parts of your makefile; you can use
3376 @dfn{double-colon rules} (@pxref{Double-Colon}) for this.
3377
3378 An extra rule with just prerequisites can be used to give a few extra
3379 prerequisites to many files at once.  For example, makefiles often
3380 have a variable, such as @code{objects}, containing a list of all the
3381 compiler output files in the system being made.  An easy way to say
3382 that all of them must be recompiled if @file{config.h} changes is to
3383 write the following:
3384
3385 @example
3386 objects = foo.o bar.o
3387 foo.o : defs.h
3388 bar.o : defs.h test.h
3389 $(objects) : config.h
3390 @end example
3391
3392 This could be inserted or taken out without changing the rules that really
3393 specify how to make the object files, making it a convenient form to use if
3394 you wish to add the additional prerequisite intermittently.
3395
3396 Another wrinkle is that the additional prerequisites could be
3397 specified with a variable that you set with a command line argument to
3398 @code{make} (@pxref{Overriding, ,Overriding Variables}).  For example,
3399
3400 @example
3401 @group
3402 extradeps=
3403 $(objects) : $(extradeps)
3404 @end group
3405 @end example
3406
3407 @noindent
3408 means that the command @samp{make extradeps=foo.h} will consider
3409 @file{foo.h} as a prerequisite of each object file, but plain @samp{make}
3410 will not.
3411
3412 If none of the explicit rules for a target has a recipe, then @code{make}
3413 searches for an applicable implicit rule to find one
3414 @pxref{Implicit Rules, ,Using Implicit Rules}).
3415
3416 @node Static Pattern, Double-Colon, Multiple Rules, Rules
3417 @section Static Pattern Rules
3418 @cindex static pattern rule
3419 @cindex rule, static pattern
3420 @cindex pattern rules, static (not implicit)
3421 @cindex varying prerequisites
3422 @cindex prerequisites, varying (static pattern)
3423
3424 @dfn{Static pattern rules} are rules which specify multiple targets and
3425 construct the prerequisite names for each target based on the target name.
3426 They are more general than ordinary rules with multiple targets because the
3427 targets do not have to have identical prerequisites.  Their prerequisites must
3428 be @emph{analogous}, but not necessarily @emph{identical}.
3429
3430 @menu
3431 * Static Usage::                The syntax of static pattern rules.
3432 * Static versus Implicit::      When are they better than implicit rules?
3433 @end menu
3434
3435 @node Static Usage, Static versus Implicit, Static Pattern, Static Pattern
3436 @subsection Syntax of Static Pattern Rules
3437 @cindex static pattern rule, syntax of
3438 @cindex pattern rules, static, syntax of
3439
3440 Here is the syntax of a static pattern rule:
3441
3442 @example
3443 @var{targets} @dots{}: @var{target-pattern}: @var{prereq-patterns} @dots{}
3444         @var{recipe}
3445         @dots{}
3446 @end example
3447
3448 @noindent
3449 The @var{targets} list specifies the targets that the rule applies to.
3450 The targets can contain wildcard characters, just like the targets of
3451 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
3452 Names}).
3453
3454 @cindex target pattern, static (not implicit)
3455 @cindex stem
3456 The @var{target-pattern} and @var{prereq-patterns} say how to compute the
3457 prerequisites of each target.  Each target is matched against the
3458 @var{target-pattern} to extract a part of the target name, called the
3459 @dfn{stem}.  This stem is substituted into each of the @var{prereq-patterns}
3460 to make the prerequisite names (one from each @var{prereq-pattern}).
3461
3462 Each pattern normally contains the character @samp{%} just once.  When the
3463 @var{target-pattern} matches a target, the @samp{%} can match any part of
3464 the target name; this part is called the @dfn{stem}.  The rest of the
3465 pattern must match exactly.  For example, the target @file{foo.o} matches
3466 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
3467 @file{foo.c} and @file{foo.out} do not match that pattern.
3468
3469 @cindex prerequisite pattern, static (not implicit)
3470 The prerequisite names for each target are made by substituting the stem
3471 for the @samp{%} in each prerequisite pattern.  For example, if one
3472 prerequisite pattern is @file{%.c}, then substitution of the stem
3473 @samp{foo} gives the prerequisite name @file{foo.c}.  It is legitimate
3474 to write a prerequisite pattern that does not contain @samp{%}; then this
3475 prerequisite is the same for all targets.
3476
3477 @cindex @code{%}, quoting in static pattern
3478 @cindex @code{%}, quoting with @code{\} (backslash)
3479 @cindex @code{\} (backslash), to quote @code{%}
3480 @cindex backslash (@code{\}), to quote @code{%}
3481 @cindex quoting @code{%}, in static pattern
3482 @samp{%} characters in pattern rules can be quoted with preceding
3483 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
3484 characters can be quoted with more backslashes.  Backslashes that quote
3485 @samp{%} characters or other backslashes are removed from the pattern
3486 before it is compared to file names or has a stem substituted into it.
3487 Backslashes that are not in danger of quoting @samp{%} characters go
3488 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
3489 @samp{the%weird\} preceding the operative @samp{%} character, and
3490 @samp{pattern\\} following it.  The final two backslashes are left alone
3491 because they cannot affect any @samp{%} character.
3492
3493 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
3494 from the corresponding @file{.c} file:
3495
3496 @example
3497 @group
3498 objects = foo.o bar.o
3499
3500 all: $(objects)
3501
3502 $(objects): %.o: %.c
3503         $(CC) -c $(CFLAGS) $< -o $@@
3504 @end group
3505 @end example
3506
3507 @noindent
3508 Here @samp{$<} is the automatic variable that holds the name of the
3509 prerequisite and @samp{$@@} is the automatic variable that holds the name
3510 of the target; see @ref{Automatic Variables}.
3511
3512 Each target specified must match the target pattern; a warning is issued
3513 for each target that does not.  If you have a list of files, only some of
3514 which will match the pattern, you can use the @code{filter} function to
3515 remove non-matching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
3516
3517 @example
3518 files = foo.elc bar.o lose.o
3519
3520 $(filter %.o,$(files)): %.o: %.c
3521         $(CC) -c $(CFLAGS) $< -o $@@
3522 $(filter %.elc,$(files)): %.elc: %.el
3523         emacs -f batch-byte-compile $<
3524 @end example
3525
3526 @noindent
3527 In this example the result of @samp{$(filter %.o,$(files))} is
3528 @file{bar.o lose.o}, and the first static pattern rule causes each of
3529 these object files to be updated by compiling the corresponding C source
3530 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
3531 @file{foo.elc}, so that file is made from @file{foo.el}.
3532
3533 Another example shows how to use @code{$*} in static pattern rules:
3534 @vindex $*@r{, and static pattern}
3535
3536 @example
3537 @group
3538 bigoutput littleoutput : %output : text.g
3539         generate text.g -$* > $@@
3540 @end group
3541 @end example
3542
3543 @noindent
3544 When the @code{generate} command is run, @code{$*} will expand to the
3545 stem, either @samp{big} or @samp{little}.
3546
3547 @node Static versus Implicit,  , Static Usage, Static Pattern
3548 @subsection Static Pattern Rules versus Implicit Rules
3549 @cindex rule, static pattern versus implicit
3550 @cindex static pattern rule, versus implicit
3551
3552 A static pattern rule has much in common with an implicit rule defined as a
3553 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
3554 Both have a pattern for the target and patterns for constructing the
3555 names of prerequisites.  The difference is in how @code{make} decides
3556 @emph{when} the rule applies.
3557
3558 An implicit rule @emph{can} apply to any target that matches its pattern,
3559 but it @emph{does} apply only when the target has no recipe otherwise
3560 specified, and only when the prerequisites can be found.  If more than one
3561 implicit rule appears applicable, only one applies; the choice depends on
3562 the order of rules.
3563
3564 By contrast, a static pattern rule applies to the precise list of targets
3565 that you specify in the rule.  It cannot apply to any other target and it
3566 invariably does apply to each of the targets specified.  If two conflicting
3567 rules apply, and both have recipes, that's an error.
3568
3569 The static pattern rule can be better than an implicit rule for these
3570 reasons:
3571
3572 @itemize @bullet
3573 @item
3574 You may wish to override the usual implicit rule for a few
3575 files whose names cannot be categorized syntactically but
3576 can be given in an explicit list.
3577
3578 @item
3579 If you cannot be sure of the precise contents of the directories
3580 you are using, you may not be sure which other irrelevant files
3581 might lead @code{make} to use the wrong implicit rule.  The choice
3582 might depend on the order in which the implicit rule search is done.
3583 With static pattern rules, there is no uncertainty: each rule applies
3584 to precisely the targets specified.
3585 @end itemize
3586
3587 @node Double-Colon, Automatic Prerequisites, Static Pattern, Rules
3588 @section Double-Colon Rules
3589 @cindex double-colon rules
3590 @cindex rule, double-colon (@code{::})
3591 @cindex multiple rules for one target (@code{::})
3592 @cindex @code{::} rules (double-colon)
3593
3594 @dfn{Double-colon} rules are explicit rules written with @samp{::}
3595 instead of @samp{:} after the target names.  They are handled
3596 differently from ordinary rules when the same target appears in more
3597 than one rule.  Pattern rules with double-colons have an entirely
3598 different meaning (@pxref{Match-Anything Rules}).
3599
3600 When a target appears in multiple rules, all the rules must be the same
3601 type: all ordinary, or all double-colon.  If they are double-colon, each
3602 of them is independent of the others.  Each double-colon rule's recipe
3603 is executed if the target is older than any prerequisites of that rule.
3604 If there are no prerequisites for that rule, its recipe is always
3605 executed (even if the target already exists).  This can result in
3606 executing none, any, or all of the double-colon rules.
3607
3608 Double-colon rules with the same target are in fact completely separate
3609 from one another.  Each double-colon rule is processed individually, just
3610 as rules with different targets are processed.
3611
3612 The double-colon rules for a target are executed in the order they appear
3613 in the makefile.  However, the cases where double-colon rules really make
3614 sense are those where the order of executing the recipes would not matter.
3615
3616 Double-colon rules are somewhat obscure and not often very useful; they
3617 provide a mechanism for cases in which the method used to update a target
3618 differs depending on which prerequisite files caused the update, and such
3619 cases are rare.
3620
3621 Each double-colon rule should specify a recipe; if it does not, an
3622 implicit rule will be used if one applies.
3623 @xref{Implicit Rules, ,Using Implicit Rules}.
3624
3625 @node Automatic Prerequisites,  , Double-Colon, Rules
3626 @section Generating Prerequisites Automatically
3627 @cindex prerequisites, automatic generation
3628 @cindex automatic generation of prerequisites
3629 @cindex generating prerequisites automatically
3630
3631 In the makefile for a program, many of the rules you need to write often
3632 say only that some object file depends on some header
3633 file.  For example, if @file{main.c} uses @file{defs.h} via an
3634 @code{#include}, you would write:
3635
3636 @example
3637 main.o: defs.h
3638 @end example
3639
3640 @noindent
3641 You need this rule so that @code{make} knows that it must remake
3642 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
3643 large program you would have to write dozens of such rules in your
3644 makefile.  And, you must always be very careful to update the makefile
3645 every time you add or remove an @code{#include}.
3646 @cindex @code{#include}
3647
3648 @cindex @code{-M} (to compiler)
3649 To avoid this hassle, most modern C compilers can write these rules for
3650 you, by looking at the @code{#include} lines in the source files.
3651 Usually this is done with the @samp{-M} option to the compiler.
3652 For example, the command:
3653
3654 @example
3655 cc -M main.c
3656 @end example
3657
3658 @noindent
3659 generates the output:
3660
3661 @example
3662 main.o : main.c defs.h
3663 @end example
3664
3665 @noindent
3666 Thus you no longer have to write all those rules yourself.
3667 The compiler will do it for you.
3668
3669 Note that such a rule constitutes mentioning @file{main.o} in a
3670 makefile, so it can never be considered an intermediate file by
3671 implicit rule search.  This means that @code{make} won't ever remove
3672 the file after using it; @pxref{Chained Rules, ,Chains of Implicit
3673 Rules}.
3674
3675 @cindex @code{make depend}
3676 With old @code{make} programs, it was traditional practice to use this
3677 compiler feature to generate prerequisites on demand with a command like
3678 @samp{make depend}.  That command would create a file @file{depend}
3679 containing all the automatically-generated prerequisites; then the
3680 makefile could use @code{include} to read them in (@pxref{Include}).
3681
3682 In GNU @code{make}, the feature of remaking makefiles makes this
3683 practice obsolete---you need never tell @code{make} explicitly to
3684 regenerate the prerequisites, because it always regenerates any makefile
3685 that is out of date.  @xref{Remaking Makefiles}.
3686
3687 The practice we recommend for automatic prerequisite generation is to have
3688 one makefile corresponding to each source file.  For each source file
3689 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
3690 what files the object file @file{@var{name}.o} depends on.  That way
3691 only the source files that have changed need to be rescanned to produce
3692 the new prerequisites.
3693
3694 Here is the pattern rule to generate a file of prerequisites (i.e., a makefile)
3695 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
3696
3697 @smallexample
3698 @group
3699 %.d: %.c
3700         @@set -e; rm -f $@@; \
3701          $(CC) -M $(CPPFLAGS) $< > $@@.$$$$; \
3702          sed 's,\($*\)\.o[ :]*,\1.o $@@ : ,g' < $@@.$$$$ > $@@; \
3703          rm -f $@@.$$$$
3704 @end group
3705 @end smallexample
3706
3707 @noindent
3708 @xref{Pattern Rules}, for information on defining pattern rules.  The
3709 @samp{-e} flag to the shell causes it to exit immediately if the
3710 @code{$(CC)} command (or any other command) fails (exits with a
3711 nonzero status).
3712 @cindex @code{-e} (shell flag)
3713
3714 @cindex @code{-MM} (to GNU compiler)
3715 With the GNU C compiler, you may wish to use the @samp{-MM} flag instead
3716 of @samp{-M}.  This omits prerequisites on system header files.
3717 @xref{Preprocessor Options, , Options Controlling the Preprocessor,
3718 gcc, Using GNU CC}, for details.
3719
3720 @cindex @code{sed} (shell command)
3721 The purpose of the @code{sed} command is to translate (for example):
3722
3723 @example
3724 main.o : main.c defs.h
3725 @end example
3726
3727 @noindent
3728 into:
3729
3730 @example
3731 main.o main.d : main.c defs.h
3732 @end example
3733
3734 @noindent
3735 @cindex @code{.d}
3736 This makes each @samp{.d} file depend on all the source and header files
3737 that the corresponding @samp{.o} file depends on.  @code{make} then
3738 knows it must regenerate the prerequisites whenever any of the source or
3739 header files changes.
3740
3741 Once you've defined the rule to remake the @samp{.d} files,
3742 you then use the @code{include} directive to read them all in.
3743 @xref{Include}.  For example:
3744
3745 @example
3746 @group
3747 sources = foo.c bar.c
3748
3749 include $(sources:.c=.d)
3750 @end group
3751 @end example
3752
3753 @noindent
3754 (This example uses a substitution variable reference to translate the
3755 list of source files @samp{foo.c bar.c} into a list of prerequisite
3756 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
3757 information on substitution references.)  Since the @samp{.d} files are
3758 makefiles like any others, @code{make} will remake them as necessary
3759 with no further work from you.  @xref{Remaking Makefiles}.
3760
3761 Note that the @samp{.d} files contain target definitions; you should
3762 be sure to place the @code{include} directive @emph{after} the first,
3763 default goal in your makefiles or run the risk of having a random
3764 object file become the default goal.
3765 @xref{How Make Works}.
3766
3767 @node Recipes, Using Variables, Rules, Top
3768 @chapter Writing Recipes in Rules
3769 @cindex recipes
3770 @cindex recipes, how to write
3771 @cindex writing recipes
3772
3773 The recipe of a rule consists of one or more shell command lines to
3774 be executed, one at a time, in the order they appear.  Typically, the
3775 result of executing these commands is that the target of the rule is
3776 brought up to date.
3777
3778 Users use many different shell programs, but recipes in makefiles are
3779 always interpreted by @file{/bin/sh} unless the makefile specifies
3780 otherwise.  @xref{Execution, ,Recipe Execution}.
3781
3782 @menu
3783 * Recipe Syntax::               Recipe syntax features and pitfalls.
3784 * Echoing::                     How to control when recipes are echoed.
3785 * Execution::                   How recipes are executed.
3786 * Parallel::                    How recipes can be executed in parallel.
3787 * Errors::                      What happens after a recipe execution error.
3788 * Interrupts::                  What happens when a recipe is interrupted.
3789 * Recursion::                   Invoking @code{make} from makefiles.
3790 * Canned Recipes::              Defining canned recipes.
3791 * Empty Recipes::               Defining useful, do-nothing recipes.
3792 @end menu
3793
3794 @node Recipe Syntax, Echoing, Recipes, Recipes
3795 @section Recipe Syntax
3796 @cindex recipe syntax
3797 @cindex syntax of recipe
3798
3799 Makefiles have the unusual property that there are really two distinct
3800 syntaxes in one file.  Most of the makefile uses @code{make} syntax
3801 (@pxref{Makefiles, ,Writing Makefiles}).  However, recipes are meant
3802 to be interpreted by the shell and so they are written using shell
3803 syntax.  The @code{make} program does not try to understand shell
3804 syntax: it performs only a very few specific translations on the
3805 content of the recipe before handing it to the shell.
3806
3807 Each line in the recipe must start with a tab (or the first character
3808 in the value of the @code{.RECIPEPREFIX} variable; @pxref{Special
3809 Variables}), except that the first recipe line may be attached to the
3810 target-and-prerequisites line with a semicolon in between.  @emph{Any}
3811 line in the makefile that begins with a tab and appears in a ``rule
3812 context'' (that is, after a rule has been started until another rule
3813 or variable definition) will be considered part of a recipe for that
3814 rule.  Blank lines and lines of just comments may appear among the
3815 recipe lines; they are ignored.
3816
3817 Some consequences of these rules include:
3818
3819 @itemize @bullet
3820 @item
3821 A blank line that begins with a tab is not blank: it's an empty
3822 recipe (@pxref{Empty Recipes}).
3823
3824 @cindex comments, in recipes
3825 @cindex recipes, comments in
3826 @cindex @code{#} (comments), in recipes
3827 @item
3828 A comment in a recipe is not a @code{make} comment; it will be
3829 passed to the shell as-is.  Whether the shell treats it as a comment
3830 or not depends on your shell.
3831
3832 @item
3833 A variable definition in a ``rule context'' which is indented by a tab
3834 as the first character on the line, will be considered part of a
3835 recipe, not a @code{make} variable definition, and passed to the
3836 shell.
3837
3838 @item
3839 A conditional expression (@code{ifdef}, @code{ifeq},
3840 etc. @pxref{Conditional Syntax, ,Syntax of Conditionals}) in a ``rule
3841 context'' which is indented by a tab as the first character on the
3842 line, will be considered part of a recipe and be passed to the shell.
3843
3844 @end itemize
3845
3846 @menu
3847 * Splitting Recipe Lines::      Breaking long recipe lines for readability.
3848 * Variables in Recipes::        Using @code{make} variables in recipes.
3849 @end menu
3850
3851 @node Splitting Recipe Lines, Variables in Recipes, Recipe Syntax, Recipe Syntax
3852 @subsection Splitting Recipe Lines
3853 @cindex recipes, splitting
3854 @cindex splitting recipes
3855 @cindex recipes, backslash (@code{\}) in
3856 @cindex recipes, quoting newlines in
3857 @cindex backslash (@code{\}), in recipes
3858 @cindex @code{\} (backslash), in recipes
3859 @cindex quoting newline, in recipes
3860 @cindex newline, quoting, in recipes
3861
3862 One of the few ways in which @code{make} does interpret recipes is
3863 checking for a backslash just before the newline.  As in normal
3864 makefile syntax, a single logical recipe line can be split into
3865 multiple physical lines in the makefile by placing a backslash before
3866 each newline.  A sequence of lines like this is considered a single
3867 recipe line, and one instance of the shell will be invoked to run it.
3868
3869 However, in contrast to how they are treated in other places in a
3870 makefile (@pxref{Splitting Lines, , Splitting Long Lines}),
3871 backslash/newline pairs are @emph{not} removed from the recipe.  Both
3872 the backslash and the newline characters are preserved and passed to
3873 the shell.  How the backslash/newline is interpreted depends on your
3874 shell.  If the first character of the next line after the
3875 backslash/newline is the recipe prefix character (a tab by default;
3876 @pxref{Special Variables}), then that character (and only that
3877 character) is removed.  Whitespace is never added to the recipe.
3878
3879 For example, the recipe for the all target in this makefile:
3880
3881 @example
3882 @group
3883 all :
3884         @@echo no\
3885 space
3886         @@echo no\
3887         space
3888         @@echo one \
3889         space
3890         @@echo one\
3891          space
3892 @end group
3893 @end example
3894
3895 @noindent
3896 consists of four separate shell commands where the output is:
3897
3898 @example
3899 @group
3900 nospace
3901 nospace
3902 one space
3903 one space
3904 @end group
3905 @end example
3906
3907 As a more complex example, this makefile:
3908
3909 @example
3910 @group
3911 all : ; @@echo 'hello \
3912         world' ; echo "hello \
3913     world"
3914 @end group
3915 @end example
3916
3917 @noindent
3918 will invoke one shell with a command of:
3919
3920 @example
3921 @group
3922 echo 'hello \
3923 world' ; echo "hello \
3924     world"
3925 @end group
3926 @end example
3927
3928 @noindent
3929 which, according to shell quoting rules, will yield the following output:
3930
3931 @example
3932 @group
3933 hello \
3934 world
3935 hello     world
3936 @end group
3937 @end example
3938
3939 @noindent
3940 Notice how the backslash/newline pair was removed inside the string
3941 quoted with double quotes (@code{"@dots{}"}), but not from the string
3942 quoted with single quotes (@code{'@dots{}'}).  This is the way the
3943 default shell (@file{/bin/sh}) handles backslash/newline pairs.  If
3944 you specify a different shell in your makefiles it may treat them
3945 differently.
3946
3947 Sometimes you want to split a long line inside of single quotes, but
3948 you don't want the backslash/newline to appear in the quoted content.
3949 This is often the case when passing scripts to languages such as Perl,
3950 where extraneous backslashes inside the script can change its meaning
3951 or even be a syntax error.  One simple way of handling this is to
3952 place the quoted string, or even the entire command, into a
3953 @code{make} variable then use the variable in the recipe.  In this
3954 situation the newline quoting rules for makefiles will be used, and
3955 the backslash/newline will be removed.  If we rewrite our example
3956 above using this method:
3957
3958 @example
3959 @group
3960 HELLO = 'hello \
3961 world'
3962
3963 all : ; @@echo $(HELLO)
3964 @end group
3965 @end example
3966
3967 @noindent
3968 we will get output like this:
3969
3970 @example
3971 @group
3972 hello world
3973 @end group
3974 @end example
3975
3976 If you like, you can also use target-specific variables
3977 (@pxref{Target-specific, ,Target-specific Variable Values}) to obtain
3978 a tighter correspondence between the variable and the recipe that
3979 uses it.
3980
3981 @node Variables in Recipes,  , Splitting Recipe Lines, Recipe Syntax
3982 @subsection Using Variables in Recipes
3983 @cindex variable references in recipes
3984 @cindex recipes, using variables in
3985
3986 The other way in which @code{make} processes recipes is by expanding
3987 any variable references in them (@pxref{Reference,Basics of Variable
3988 References}).  This occurs after make has finished reading all the
3989 makefiles and the target is determined to be out of date; so, the
3990 recipes for targets which are not rebuilt are never expanded.
3991
3992 Variable and function references in recipes have identical syntax and
3993 semantics to references elsewhere in the makefile.  They also have the
3994 same quoting rules: if you want a dollar sign to appear in your
3995 recipe, you must double it (@samp{$$}).  For shells like the default
3996 shell, that use dollar signs to introduce variables, it's important to
3997 keep clear in your mind whether the variable you want to reference is
3998 a @code{make} variable (use a single dollar sign) or a shell variable
3999 (use two dollar signs).  For example:
4000
4001 @example
4002 @group
4003 LIST = one two three
4004 all:
4005         for i in $(LIST); do \
4006             echo $$i; \
4007         done
4008 @end group
4009 @end example
4010
4011 @noindent
4012 results in the following command being passed to the shell:
4013
4014 @example
4015 @group
4016 for i in one two three; do \
4017     echo $i; \
4018 done
4019 @end group
4020 @end example
4021
4022 @noindent
4023 which generates the expected result:
4024
4025 @example
4026 @group
4027 one
4028 two
4029 three
4030 @end group
4031 @end example
4032
4033 @node Echoing, Execution, Recipe Syntax, Recipes
4034 @section Recipe Echoing
4035 @cindex echoing of recipes
4036 @cindex silent operation
4037 @cindex @code{@@} (in recipes)
4038 @cindex recipes, echoing
4039 @cindex printing of recipes
4040
4041 Normally @code{make} prints each line of the recipe before it is
4042 executed.  We call this @dfn{echoing} because it gives the appearance
4043 that you are typing the lines yourself.
4044
4045 When a line starts with @samp{@@}, the echoing of that line is suppressed.
4046 The @samp{@@} is discarded before the line is passed to the shell.
4047 Typically you would use this for a command whose only effect is to print
4048 something, such as an @code{echo} command to indicate progress through
4049 the makefile:
4050
4051 @example
4052 @@echo About to make distribution files
4053 @end example
4054
4055 @cindex @code{-n}
4056 @cindex @code{--just-print}
4057 @cindex @code{--dry-run}
4058 @cindex @code{--recon}
4059 When @code{make} is given the flag @samp{-n} or @samp{--just-print} it
4060 only echoes most recipes, without executing them.  @xref{Options
4061 Summary, ,Summary of Options}.  In this case even the recipe lines
4062 starting with @samp{@@} are printed.  This flag is useful for finding
4063 out which recipes @code{make} thinks are necessary without actually
4064 doing them.
4065
4066 @cindex @code{-s}
4067 @cindex @code{--silent}
4068 @cindex @code{--quiet}
4069 @findex .SILENT
4070 The @samp{-s} or @samp{--silent}
4071 flag to @code{make} prevents all echoing, as if all recipes
4072 started with @samp{@@}.  A rule in the makefile for the special target
4073 @code{.SILENT} without prerequisites has the same effect
4074 (@pxref{Special Targets, ,Special Built-in Target Names}).
4075
4076 @node Execution, Parallel, Echoing, Recipes
4077 @section Recipe Execution
4078 @cindex recipe, execution
4079 @cindex execution, of recipes
4080 @vindex @code{SHELL} @r{(recipe execution)}
4081
4082 When it is time to execute recipes to update a target, they are
4083 executed by invoking a new sub-shell for each line of the recipe,
4084 unless the @code{.ONESHELL} special target is in effect
4085 (@pxref{One Shell, ,Using One Shell})  (In practice, @code{make} may
4086 take shortcuts that do not affect the results.)
4087
4088 @cindex @code{cd} (shell command)
4089 @cindex shell variables, setting in recipes
4090 @cindex recipes setting shell variables
4091 @strong{Please note:} this implies that setting shell variables and
4092 invoking shell commands such as @code{cd} that set a context local to
4093 each process will not affect the following lines in the recipe.@footnote{On
4094 MS-DOS, the value of current working directory is @strong{global}, so
4095 changing it @emph{will} affect the following recipe lines on those
4096 systems.}  If you want to use @code{cd} to affect the next statement,
4097 put both statements in a single recipe line.  Then @code{make} will
4098 invoke one shell to run the entire line, and the shell will execute
4099 the statements in sequence.  For example:
4100
4101 @example
4102 foo : bar/lose
4103         cd $(<D) && gobble $(<F) > ../$@@
4104 @end example
4105
4106 @noindent
4107 Here we use the shell AND operator (@code{&&}) so that if the
4108 @code{cd} command fails, the script will fail without trying to invoke
4109 the @code{gobble} command in the wrong directory, which could cause
4110 problems (in this case it would certainly cause @file{../foo} to be
4111 truncated, at least).
4112
4113 @menu
4114 * One Shell::                   One shell for all lines in a recipe.
4115 * Choosing the Shell::          How @code{make} chooses the shell used
4116                                   to run recipes.
4117 @end menu
4118
4119 @node One Shell, Choosing the Shell, Execution, Execution
4120 @subsection Using One Shell
4121 @cindex recipe lines, single shell
4122 @cindex @code{.ONESHELL}, use of
4123 @findex .ONESHELL
4124
4125 Sometimes you would prefer that all the lines in the recipe be passed
4126 to a single invocation of the shell.  There are generally two
4127 situations where this is useful: first, it can improve performance in
4128 makefiles where recipes consist of many command lines, by avoiding
4129 extra processes.  Second, you might want newlines to be included in
4130 your recipe command (for example perhaps you are using a very
4131 different interpreter as your @code{SHELL}).  If the @code{.ONESHELL}
4132 special target appears anywhere in the makefile then @emph{all}
4133 recipe lines for each target will be provided to a single invocation
4134 of the shell.  Newlines between recipe lines will be preserved.  For
4135 example:
4136
4137 @example
4138 .ONESHELL:
4139 foo : bar/lose
4140         cd $(<D)
4141         gobble $(<F) > ../$@@
4142 @end example
4143
4144 @noindent
4145 would now work as expected even though the commands are on different
4146 recipe lines.
4147
4148 If @code{.ONESHELL} is provided, then only the first line of the
4149 recipe will be checked for the special prefix characters (@samp{@@},
4150 @samp{-}, and @samp{+}).  Subsequent lines will include the special
4151 characters in the recipe line when the @code{SHELL} is invoked.  If
4152 you want your recipe to start with one of these special characters
4153 you'll need to arrange for them to not be the first characters on the
4154 first line, perhaps by adding a comment or similar.  For example, this
4155 would be a syntax error in Perl because the first @samp{@@} is removed
4156 by make:
4157
4158 @example
4159 .ONESHELL:
4160 SHELL = /usr/bin/perl
4161 .SHELLFLAGS = -e
4162 show :
4163         @@f = qw(a b c);
4164         print "@@f\n";
4165 @end example
4166
4167 @noindent
4168 However, either of these alternatives would work properly:
4169
4170 @example
4171 .ONESHELL:
4172 SHELL = /usr/bin/perl
4173 .SHELLFLAGS = -e
4174 show :
4175         # Make sure "@@" is not the first character on the first line
4176         @@f = qw(a b c);
4177         print "@@f\n";
4178 @end example
4179
4180 @noindent
4181 or
4182
4183 @example
4184 .ONESHELL:
4185 SHELL = /usr/bin/perl
4186 .SHELLFLAGS = -e
4187 show :
4188         my @@f = qw(a b c);
4189         print "@@f\n";
4190 @end example
4191
4192 As a special feature, if @code{SHELL} is determined to be a
4193 POSIX-style shell, the special prefix characters in ``internal''
4194 recipe lines will be @emph{removed} before the recipe is processed.
4195 This feature is intended to allow existing makefiles to add the
4196 @code{.ONESHELL} special target and still run properly without
4197 extensive modifications.  Since the special prefix characters are not
4198 legal at the beginning of a line in a POSIX shell script this is not a
4199 loss in functionality.  For example, this works as expected:
4200
4201 @example
4202 .ONESHELL:
4203 foo : bar/lose
4204         @@cd $(@@D)
4205         @@gobble $(@@F) > ../$@@
4206 @end example
4207
4208 Even with this special feature, however, makefiles with
4209 @code{.ONESHELL} will behave differently in ways that could be
4210 noticeable.  For example, normally if any line in the recipe fails,
4211 that causes the rule to fail and no more recipe lines are processed.
4212 Under @code{.ONESHELL} a failure of any but the final recipe line will
4213 not be noticed by @code{make}.  You can modify @code{.SHELLFLAGS} to
4214 add the @code{-e} option to the shell which will cause any failure
4215 anywhere in the command line to cause the shell to fail, but this
4216 could itself cause your recipe to behave differently.  Ultimately you
4217 may need to harden your recipe lines to allow them to work with
4218 @code{.ONESHELL}.
4219
4220 @node Choosing the Shell,  , One Shell, Execution
4221 @subsection Choosing the Shell
4222 @cindex shell, choosing the
4223 @cindex @code{SHELL}, value of
4224 @cindex @code{.SHELLFLAGS}, value of
4225
4226 @vindex SHELL
4227 @vindex .SHELLFLAGS
4228 The program used as the shell is taken from the variable @code{SHELL}.
4229 If this variable is not set in your makefile, the program
4230 @file{/bin/sh} is used as the shell.  The argument(s) passed to the
4231 shell are taken from the variable @code{.SHELLFLAGS}.  The default
4232 value of @code{.SHELLFLAGS} is @code{-c} normally, or @code{-ec} in
4233 POSIX-conforming mode.
4234
4235 @cindex environment, @code{SHELL} in
4236 Unlike most variables, the variable @code{SHELL} is never set from the
4237 environment.  This is because the @code{SHELL} environment variable is
4238 used to specify your personal choice of shell program for interactive
4239 use.  It would be very bad for personal choices like this to affect the
4240 functioning of makefiles.  @xref{Environment, ,Variables from the
4241 Environment}.
4242
4243 Furthermore, when you do set @code{SHELL} in your makefile that value
4244 is @emph{not} exported in the environment to recipe lines that
4245 @code{make} invokes.  Instead, the value inherited from the user's
4246 environment, if any, is exported.  You can override this behavior by
4247 explicitly exporting @code{SHELL} (@pxref{Variables/Recursion,
4248 ,Communicating Variables to a Sub-@code{make}}), forcing it to be
4249 passed in the environment to recipe lines.
4250
4251 @vindex @code{MAKESHELL} @r{(MS-DOS alternative to @code{SHELL})}
4252 However, on MS-DOS and MS-Windows the value of @code{SHELL} in the
4253 environment @strong{is} used, since on those systems most users do not
4254 set this variable, and therefore it is most likely set specifically to
4255 be used by @code{make}.  On MS-DOS, if the setting of @code{SHELL} is
4256 not suitable for @code{make}, you can set the variable
4257 @code{MAKESHELL} to the shell that @code{make} should use; if set it
4258 will be used as the shell instead of the value of @code{SHELL}.
4259
4260 @subsubheading Choosing a Shell in DOS and Windows
4261 @cindex shell, in DOS and Windows
4262 @cindex DOS, choosing a shell in
4263 @cindex Windows, choosing a shell in
4264
4265 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
4266 other systems.
4267
4268 @vindex COMSPEC
4269 On MS-DOS, if @code{SHELL} is not set, the value of the variable
4270 @code{COMSPEC} (which is always set) is used instead.
4271
4272 @cindex @code{SHELL}, MS-DOS specifics
4273 The processing of lines that set the variable @code{SHELL} in Makefiles
4274 is different on MS-DOS.  The stock shell, @file{command.com}, is
4275 ridiculously limited in its functionality and many users of @code{make}
4276 tend to install a replacement shell.  Therefore, on MS-DOS, @code{make}
4277 examines the value of @code{SHELL}, and changes its behavior based on
4278 whether it points to a Unix-style or DOS-style shell.  This allows
4279 reasonable functionality even if @code{SHELL} points to
4280 @file{command.com}.
4281
4282 If @code{SHELL} points to a Unix-style shell, @code{make} on MS-DOS
4283 additionally checks whether that shell can indeed be found; if not, it
4284 ignores the line that sets @code{SHELL}.  In MS-DOS, GNU @code{make}
4285 searches for the shell in the following places:
4286
4287 @enumerate
4288 @item
4289 In the precise place pointed to by the value of @code{SHELL}.  For
4290 example, if the makefile specifies @samp{SHELL = /bin/sh}, @code{make}
4291 will look in the directory @file{/bin} on the current drive.
4292
4293 @item
4294 In the current directory.
4295
4296 @item
4297 In each of the directories in the @code{PATH} variable, in order.
4298
4299 @end enumerate
4300
4301 In every directory it examines, @code{make} will first look for the
4302 specific file (@file{sh} in the example above).  If this is not found,
4303 it will also look in that directory for that file with one of the known
4304 extensions which identify executable files.  For example @file{.exe},
4305 @file{.com}, @file{.bat}, @file{.btm}, @file{.sh}, and some others.
4306
4307 If any of these attempts is successful, the value of @code{SHELL} will
4308 be set to the full pathname of the shell as found.  However, if none of
4309 these is found, the value of @code{SHELL} will not be changed, and thus
4310 the line that sets it will be effectively ignored.  This is so
4311 @code{make} will only support features specific to a Unix-style shell if
4312 such a shell is actually installed on the system where @code{make} runs.
4313
4314 Note that this extended search for the shell is limited to the cases
4315 where @code{SHELL} is set from the Makefile; if it is set in the
4316 environment or command line, you are expected to set it to the full
4317 pathname of the shell, exactly as things are on Unix.
4318
4319 The effect of the above DOS-specific processing is that a Makefile that
4320 contains @samp{SHELL = /bin/sh} (as many Unix makefiles do), will work
4321 on MS-DOS unaltered if you have e.g.@: @file{sh.exe} installed in some
4322 directory along your @code{PATH}.
4323
4324 @vindex SHELL
4325 @vindex .SHELLFLAGS
4326
4327 @node Parallel, Errors, Execution, Recipes
4328 @section Parallel Execution
4329 @cindex recipes, execution in parallel
4330 @cindex parallel execution
4331 @cindex execution, in parallel
4332 @cindex job slots
4333 @cindex @code{-j}
4334 @cindex @code{--jobs}
4335
4336 GNU @code{make} knows how to execute several recipes at once.  Normally,
4337 @code{make} will execute only one recipe at a time, waiting for it to finish
4338 before executing the next.  However, the @samp{-j} or @samp{--jobs} option
4339 tells @code{make} to execute many recipes simultaneously.  You can inhibit
4340 parallelism for some or all targets from within the makefile (@pxref{Parallel
4341 Disable, ,Disabling Parallel Execution}).
4342
4343 On MS-DOS, the @samp{-j} option has no effect, since that system doesn't
4344 support multi-processing.
4345
4346 If the @samp{-j} option is followed by an integer, this is the number of
4347 recipes to execute at once; this is called the number of @dfn{job slots}.
4348 If there is nothing looking like an integer after the @samp{-j} option,
4349 there is no limit on the number of job slots.  The default number of job
4350 slots is one, which means serial execution (one thing at a time).
4351
4352 Handling recursive @code{make} invocations raises issues for parallel
4353 execution.  For more information on this, see @ref{Options/Recursion,
4354 ,Communicating Options to a Sub-@code{make}}.
4355
4356 If a recipe fails (is killed by a signal or exits with a nonzero
4357 status), and errors are not ignored for that recipe (@pxref{Errors,
4358 ,Errors in Recipes}), the remaining recipe lines to remake the same
4359 target will not be run.  If a recipe fails and the @samp{-k} or
4360 @samp{--keep-going} option was not given (@pxref{Options Summary,
4361 ,Summary of Options}), @code{make} aborts execution.  If make
4362 terminates for any reason (including a signal) with child processes
4363 running, it waits for them to finish before actually exiting.
4364
4365 @cindex load average
4366 @cindex limiting jobs based on load
4367 @cindex jobs, limiting based on load
4368 @cindex @code{-l} (load average)
4369 @cindex @code{--max-load}
4370 @cindex @code{--load-average}
4371 When the system is heavily loaded, you will probably want to run fewer jobs
4372 than when it is lightly loaded.  You can use the @samp{-l} option to tell
4373 @code{make} to limit the number of jobs to run at once, based on the load
4374 average.  The @samp{-l} or @samp{--max-load}
4375 option is followed by a floating-point number.  For
4376 example,
4377
4378 @example
4379 -l 2.5
4380 @end example
4381
4382 @noindent
4383 will not let @code{make} start more than one job if the load average is
4384 above 2.5.  The @samp{-l} option with no following number removes the
4385 load limit, if one was given with a previous @samp{-l} option.
4386
4387 More precisely, when @code{make} goes to start up a job, and it already has
4388 at least one job running, it checks the current load average; if it is not
4389 lower than the limit given with @samp{-l}, @code{make} waits until the load
4390 average goes below that limit, or until all the other jobs finish.
4391
4392 By default, there is no load limit.
4393
4394 @menu
4395 * Parallel Disable::            Disabling parallel execution
4396 * Parallel Output::             Handling output during parallel execution
4397 * Parallel Input::              Handling input during parallel execution
4398 @end menu
4399
4400 @node Parallel Disable, Parallel Output, Parallel, Parallel
4401 @subsection Disabling Parallel Execution
4402 @cindex disabling parallel execution
4403 @cindex parallel execution, disabling
4404
4405 If a makefile completely and accurately defines the dependency relationships
4406 between all of its targets, then @code{make} will correctly build the goals
4407 regardless of whether parallel execution is enabled or not.  This is the ideal
4408 way to write makefiles.
4409
4410 However, sometimes some or all of the targets in a makefile cannot be executed
4411 in parallel and it's not feasible to add the prerequisites needed to inform
4412 @code{make}.  In that case the makefile can use various methods to disable
4413 parallel execution.
4414
4415 @cindex .NOTPARALLEL special target
4416 @findex .NOTPARALLEL
4417 If the @code{.NOTPARALLEL} special target with no prerequisites is specified
4418 anywhere then the entire instance of @code{make} will be run serially,
4419 regardless of the parallel setting.  For example:
4420
4421 @example
4422 @group
4423 all: one two three
4424 one two three: ; @@sleep 1; echo $@@
4425
4426 .NOTPARALLEL:
4427 @end group
4428 @end example
4429
4430 Regardless of how @code{make} is invoked, the targets @file{one}, @file{two},
4431 and @file{three} will be run serially.
4432
4433 If the @code{.NOTPARALLEL} special target has prerequisites, then each of
4434 those prerequisites will be considered a target and all prerequisites of these
4435 targets will be run serially.  Note that only when building this target will
4436 the prerequisites be run serially: if some other target lists the same
4437 prerequisites and is not in @code{.NOTPARALLEL} then these prerequisites may
4438 be run in parallel.  For example:
4439
4440 @example
4441 @group
4442 all: base notparallel
4443
4444 base: one two three
4445 notparallel: one two three
4446
4447 one two three: ; @@sleep 1; echo $@@
4448
4449 .NOTPARALLEL: notparallel
4450 @end group
4451 @end example
4452
4453 Here @samp{make -j base} will run the targets @file{one}, @file{two}, and
4454 @file{three} in parallel, while @samp{make -j notparallel} will run them
4455 serially.  If you run @samp{make -j all} then they @emph{will} be run in
4456 parallel since @file{base} lists them as prerequisites and is not serialized.
4457
4458 The @code{.NOTPARALLEL} target should not have commands.
4459
4460 @cindex .WAIT special target
4461 @findex .WAIT
4462 Finally you can control the serialization of specific prerequisites in a
4463 fine-grained way using the @code{.WAIT} special target.  When this target
4464 appears in a prerequisite list and parallel execution is enabled, @code{make}
4465 will not build any of the prerequisites to the @emph{right} of @code{.WAIT}
4466 until all prerequisites to the @emph{left} of @code{.WAIT} have completed.
4467 For example:
4468
4469 @example
4470 @group
4471 all: one two .WAIT three
4472 one two three: ; @@sleep 1; echo $@@
4473 @end group
4474 @end example
4475
4476 If parallel execution is enabled, @code{make} will try to build @file{one} and
4477 @file{two} in parallel but will not try to build @file{three} until both are
4478 complete.
4479
4480 As with targets provided to @code{.NOTPARALLEL}, @code{.WAIT} takes effect
4481 only when building the target in whose prerequisite list it appears.  If the
4482 same prerequisites are present in other targets, without @code{.WAIT}, then
4483 they may still be run in parallel.  Because of this, neither
4484 @code{.NOTPARALLEL} with targets nor @code{.WAIT} are as reliable for
4485 controlling parallel execution as defining a prerequisite relationship.
4486 However they are easy to use and may be sufficient in less complex situations.
4487
4488 The @code{.WAIT} prerequisite will not be present in any of the automatic
4489 variables for the rule.
4490
4491 You can create an actual target @code{.WAIT} in your makefile for portability
4492 but this is not required to use this feature.  If a @code{.WAIT} target is
4493 created it should not have prerequisites or commands.
4494
4495 The @code{.WAIT} feature is also implemented in other versions of @code{make}
4496 and it's specified in the POSIX standard for @code{make}.
4497
4498 @node Parallel Output, Parallel Input, Parallel Disable, Parallel
4499 @subsection Output During Parallel Execution
4500 @cindex output during parallel execution
4501 @cindex parallel execution, output during
4502
4503 When running several recipes in parallel the output from each
4504 recipe appears as soon as it is generated, with the result that
4505 messages from different recipes may be interspersed, sometimes even
4506 appearing on the same line.  This can make reading the output very
4507 difficult.
4508
4509 @cindex @code{--output-sync}
4510 @cindex @code{-O}
4511 To avoid this you can use the @samp{--output-sync} (@samp{-O}) option.
4512 This option instructs @code{make} to save the output from the commands
4513 it invokes and print it all once the commands are completed.
4514 Additionally, if there are multiple recursive @code{make} invocations
4515 running in parallel, they will communicate so that only one of them is
4516 generating output at a time.
4517
4518 If working directory printing is enabled (@pxref{-w Option, ,The
4519 @samp{--print-directory} Option}), the enter/leave messages are
4520 printed around each output grouping.  If you prefer not to see these
4521 messages add the @samp{--no-print-directory} option to @code{MAKEFLAGS}.
4522
4523 There are four levels of granularity when synchronizing output,
4524 specified by giving an argument to the option (e.g.,  @samp{-Oline} or
4525 @samp{--output-sync=recurse}).
4526
4527 @table @code
4528 @item none
4529 This is the default: all output is sent directly as it is generated and
4530 no synchronization is performed.
4531
4532 @item line
4533 Output from each individual line of the recipe is grouped and printed
4534 as soon as that line is complete.  If a recipe consists of multiple
4535 lines, they may be interspersed with lines from other recipes.
4536
4537 @item target
4538 Output from the entire recipe for each target is grouped and printed
4539 once the target is complete.  This is the default if the
4540 @code{--output-sync} or @code{-O} option is given with no argument.
4541
4542 @item recurse
4543 Output from each recursive invocation of @code{make} is grouped and
4544 printed once the recursive invocation is complete.
4545
4546 @end table
4547
4548 Regardless of the mode chosen, the total build time will be the same.
4549 The only difference is in how the output appears.
4550
4551 The @samp{target} and @samp{recurse} modes both collect the output of
4552 the entire recipe of a target and display it uninterrupted when the
4553 recipe completes.  The difference between them is in how recipes that
4554 contain recursive invocations of @code{make} are treated
4555 (@pxref{Recursion, ,Recursive Use of @code{make}}).  For all recipes
4556 which have no recursive lines, the @samp{target} and @samp{recurse}
4557 modes behave identically.
4558
4559 If the @samp{recurse} mode is chosen, recipes that contain recursive
4560 @code{make} invocations are treated the same as other targets: the
4561 output from the recipe, including the output from the recursive
4562 @code{make}, is saved and printed after the entire recipe is complete.
4563 This ensures output from all the targets built by a given recursive
4564 @code{make} instance are grouped together, which may make the output
4565 easier to understand.  However it also leads to long periods of time
4566 during the build where no output is seen, followed by large bursts of
4567 output.  If you are not watching the build as it proceeds, but instead
4568 viewing a log of the build after the fact, this may be the best option
4569 for you.
4570
4571 If you are watching the output, the long gaps of quiet during the
4572 build can be frustrating.  The @samp{target} output synchronization
4573 mode detects when @code{make} is going to be invoked recursively,
4574 using the standard methods, and it will not synchronize the output of
4575 those lines.  The recursive @code{make} will perform the
4576 synchronization for its targets and the output from each will be
4577 displayed immediately when it completes.  Be aware that output from
4578 recursive lines of the recipe are not synchronized (for example if
4579 the recursive line prints a message before running @code{make}, that
4580 message will not be synchronized).
4581
4582 The @samp{line} mode can be useful for front-ends that are watching
4583 the output of @code{make} to track when recipes are started and
4584 completed.
4585
4586 Some programs invoked by @code{make} may behave differently if they
4587 determine they're writing output to a terminal versus a file (often
4588 described as ``interactive'' vs. ``non-interactive'' modes).  For
4589 example, many programs that can display colorized output will not do
4590 so if they determine they are not writing to a terminal.  If your
4591 makefile invokes a program like this then using the output
4592 synchronization options will cause the program to believe it's running
4593 in ``non-interactive'' mode even though the output will ultimately go
4594 to the terminal.
4595
4596 @node Parallel Input,  , Parallel Output, Parallel
4597 @subsection Input During Parallel Execution
4598 @cindex input during parallel execution
4599 @cindex parallel execution, input during
4600 @cindex standard input
4601
4602 Two processes cannot both take input from the same device at the same
4603 time.  To make sure that only one recipe tries to take input from the
4604 terminal at once, @code{make} will invalidate the standard input
4605 streams of all but one running recipe.  If another recipe attempts to
4606 read from standard input it will usually incur a fatal error (a
4607 @samp{Broken pipe} signal).
4608 @cindex broken pipe
4609
4610 It is unpredictable which recipe will have a valid standard input stream
4611 (which will come from the terminal, or wherever you redirect the standard
4612 input of @code{make}).  The first recipe run will always get it first, and
4613 the first recipe started after that one finishes will get it next, and so
4614 on.
4615
4616 We will change how this aspect of @code{make} works if we find a better
4617 alternative.  In the mean time, you should not rely on any recipe using
4618 standard input at all if you are using the parallel execution feature; but
4619 if you are not using this feature, then standard input works normally in
4620 all recipes.
4621
4622 @node Errors, Interrupts, Parallel, Recipes
4623 @section Errors in Recipes
4624 @cindex errors (in recipes)
4625 @cindex recipes, errors in
4626 @cindex exit status (errors)
4627
4628 After each shell invocation returns, @code{make} looks at its exit
4629 status.  If the shell completed successfully (the exit status is
4630 zero), the next line in the recipe is executed in a new shell; after
4631 the last line is finished, the rule is finished.
4632
4633 If there is an error (the exit status is nonzero), @code{make} gives up on
4634 the current rule, and perhaps on all rules.
4635
4636 Sometimes the failure of a certain recipe line does not indicate a problem.
4637 For example, you may use the @code{mkdir} command to ensure that a
4638 directory exists.  If the directory already exists, @code{mkdir} will
4639 report an error, but you probably want @code{make} to continue regardless.
4640
4641 @cindex @code{-} (in recipes)
4642 To ignore errors in a recipe line, write a @samp{-} at the beginning
4643 of the line's text (after the initial tab).  The @samp{-} is discarded
4644 before the line is passed to the shell for execution.
4645
4646 For example,
4647
4648 @example
4649 @group
4650 clean:
4651         -rm -f *.o
4652 @end group
4653 @end example
4654 @cindex @code{rm} (shell command)
4655
4656 @noindent
4657 This causes @code{make} to continue even if @code{rm} is unable to
4658 remove a file.
4659
4660 @cindex @code{-i}
4661 @cindex @code{--ignore-errors}
4662 @findex .IGNORE
4663 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
4664 flag, errors are ignored in all recipes of all rules.  A rule in the
4665 makefile for the special target @code{.IGNORE} has the same effect, if
4666 there are no prerequisites.  This is less flexible but sometimes useful.
4667
4668 When errors are to be ignored, because of either a @samp{-} or the
4669 @samp{-i} flag, @code{make} treats an error return just like success,
4670 except that it prints out a message that tells you the status code
4671 the shell exited with, and says that the error has been ignored.
4672
4673 When an error happens that @code{make} has not been told to ignore,
4674 it implies that the current target cannot be correctly remade, and neither
4675 can any other that depends on it either directly or indirectly.  No further
4676 recipes will be executed for these targets, since their preconditions
4677 have not been achieved.
4678
4679
4680 @cindex @code{-k}
4681 @cindex @code{--keep-going}
4682 Normally @code{make} gives up immediately in this circumstance, returning a
4683 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
4684 flag is specified, @code{make}
4685 continues to consider the other prerequisites of the pending targets,
4686 remaking them if necessary, before it gives up and returns nonzero status.
4687 For example, after an error in compiling one object file, @samp{make -k}
4688 will continue compiling other object files even though it already knows
4689 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
4690
4691 The usual behavior assumes that your purpose is to get the specified
4692 targets up to date; once @code{make} learns that this is impossible, it
4693 might as well report the failure immediately.  The @samp{-k} option says
4694 that the real purpose is to test as many of the changes made in the
4695 program as possible, perhaps to find several independent problems so
4696 that you can correct them all before the next attempt to compile.  This
4697 is why Emacs' @code{compile} command passes the @samp{-k} flag by
4698 default.
4699 @cindex Emacs (@code{M-x compile})
4700
4701 @findex .DELETE_ON_ERROR
4702 @cindex deletion of target files
4703 @cindex removal of target files
4704 @cindex target, deleting on error
4705 Usually when a recipe line fails, if it has changed the target file at all,
4706 the file is corrupted and cannot be used---or at least it is not
4707 completely updated.  Yet the file's time stamp says that it is now up to
4708 date, so the next time @code{make} runs, it will not try to update that
4709 file.  The situation is just the same as when the shell is killed by a
4710 signal; @pxref{Interrupts}.  So generally the right thing to do is to
4711 delete the target file if the recipe fails after beginning to change
4712 the file.  @code{make} will do this if @code{.DELETE_ON_ERROR} appears
4713 as a target.  This is almost always what you want @code{make} to do, but
4714 it is not historical practice; so for compatibility, you must explicitly
4715 request it.
4716
4717 @node Interrupts, Recursion, Errors, Recipes
4718 @section Interrupting or Killing @code{make}
4719 @cindex interrupt
4720 @cindex signal
4721 @cindex deletion of target files
4722 @cindex removal of target files
4723 @cindex target, deleting on interrupt
4724 @cindex killing (interruption)
4725
4726 If @code{make} gets a fatal signal while a shell is executing, it may
4727 delete the target file that the recipe was supposed to update.  This is
4728 done if the target file's last-modification time has changed since
4729 @code{make} first checked it.
4730
4731 The purpose of deleting the target is to make sure that it is remade from
4732 scratch when @code{make} is next run.  Why is this?  Suppose you type
4733 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
4734 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
4735 in an incomplete file whose last-modification time is newer than the source
4736 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
4737 and deletes this incomplete file.  If @code{make} did not do this, the next
4738 invocation of @code{make} would think that @file{foo.o} did not require
4739 updating---resulting in a strange error message from the linker when it
4740 tries to link an object file half of which is missing.
4741
4742 @findex .PRECIOUS
4743 You can prevent the deletion of a target file in this way by making the
4744 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
4745 @code{make} checks to see whether it appears on the prerequisites of
4746 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
4747 if a signal happens.  Some reasons why you might do this are that the
4748 target is updated in some atomic fashion, or exists only to record a
4749 modification-time (its contents do not matter), or must exist at all
4750 times to prevent other sorts of trouble.
4751
4752 Although @code{make} does its best to clean up there are certain situations
4753 in which cleanup is impossible.  For example, @code{make} may be killed by
4754 an uncatchable signal.  Or, one of the programs make invokes may be killed
4755 or crash, leaving behind an up-to-date but corrupt target file: @code{make}
4756 will not realize that this failure requires the target to be cleaned.  Or
4757 @code{make} itself may encounter a bug and crash.
4758
4759 For these reasons it's best to write @emph{defensive recipes}, which won't
4760 leave behind corrupted targets even if they fail.  Most commonly these
4761 recipes create temporary files rather than updating the target directly,
4762 then rename the temporary file to the final target name.  Some compilers
4763 already behave this way, so that you don't need to write a defensive recipe.
4764
4765 @node Recursion, Canned Recipes, Interrupts, Recipes
4766 @section Recursive Use of @code{make}
4767 @cindex recursion
4768 @cindex subdirectories, recursion for
4769
4770 Recursive use of @code{make} means using @code{make} as a command in a
4771 makefile.  This technique is useful when you want separate makefiles for
4772 various subsystems that compose a larger system.  For example, suppose you
4773 have a sub-directory @file{subdir} which has its own makefile, and you would
4774 like the containing directory's makefile to run @code{make} on the
4775 sub-directory.  You can do it by writing this:
4776
4777 @example
4778 subsystem:
4779         cd subdir && $(MAKE)
4780 @end example
4781
4782 @noindent
4783 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
4784
4785 @example
4786 subsystem:
4787         $(MAKE) -C subdir
4788 @end example
4789 @cindex @code{-C}
4790 @cindex @code{--directory}
4791
4792 You can write recursive @code{make} commands just by copying this example,
4793 but there are many things to know about how they work and why, and about
4794 how the sub-@code{make} relates to the top-level @code{make}.  You may
4795 also find it useful to declare targets that invoke recursive
4796 @code{make} commands as @samp{.PHONY} (for more discussion on when
4797 this is useful, see @ref{Phony Targets}).
4798
4799 @vindex @code{CURDIR}
4800 For your convenience, when GNU @code{make} starts (after it has
4801 processed any @code{-C} options) it sets the variable @code{CURDIR} to
4802 the pathname of the current working directory.  This value is never
4803 touched by @code{make} again: in particular note that if you include
4804 files from other directories the value of @code{CURDIR} does not
4805 change.  The value has the same precedence it would have if it were
4806 set in the makefile (by default, an environment variable @code{CURDIR}
4807 will not override this value).  Note that setting this variable has no
4808 impact on the operation of @code{make} (it does not cause @code{make}
4809 to change its working directory, for example).
4810
4811 @menu
4812 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
4813 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
4814 * Options/Recursion::           How to communicate options to a sub-@code{make}.
4815 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
4816                                   helps debug use of recursive @code{make} commands.
4817 @end menu
4818
4819 @node MAKE Variable, Variables/Recursion, Recursion, Recursion
4820 @subsection How the @code{MAKE} Variable Works
4821 @vindex MAKE
4822 @cindex recursion, and @code{MAKE} variable
4823
4824 Recursive @code{make} commands should always use the variable @code{MAKE},
4825 not the explicit command name @samp{make}, as shown here:
4826
4827 @example
4828 @group
4829 subsystem:
4830         cd subdir && $(MAKE)
4831 @end group
4832 @end example
4833
4834 The value of this variable is the file name with which @code{make} was
4835 invoked.  If this file name was @file{/bin/make}, then the recipe executed
4836 is @samp{cd subdir && /bin/make}.  If you use a special version of
4837 @code{make} to run the top-level makefile, the same special version will be
4838 executed for recursive invocations.
4839 @cindex @code{cd} (shell command)
4840
4841 @cindex +, and recipes
4842 As a special feature, using the variable @code{MAKE} in the recipe of
4843 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
4844 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
4845 Using the @code{MAKE} variable has the same effect as using a @samp{+}
4846 character at the beginning of the recipe line.  @xref{Instead of
4847 Execution, ,Instead of Executing the Recipes}.  This special feature
4848 is only enabled if the @code{MAKE} variable appears directly in the
4849 recipe: it does not apply if the @code{MAKE} variable is referenced
4850 through expansion of another variable.  In the latter case you must
4851 use the @samp{+} token to get these special effects.
4852
4853 Consider the command @samp{make -t} in the above example.  (The
4854 @samp{-t} option marks targets as up to date without actually running
4855 any recipes; see @ref{Instead of Execution}.)  Following the usual
4856 definition of @samp{-t}, a @samp{make -t} command in the example would
4857 create a file named @file{subsystem} and do nothing else.  What you
4858 really want it to do is run @samp{@w{cd subdir &&} @w{make -t}}; but
4859 that would require executing the recipe, and @samp{-t} says not to
4860 execute recipes.
4861 @cindex @code{-t}, and recursion
4862 @cindex recursion, and @code{-t}
4863 @cindex @code{--touch}, and recursion
4864
4865 The special feature makes this do what you want: whenever a recipe
4866 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
4867 @samp{-n} and @samp{-q} do not apply to that line.  Recipe lines
4868 containing @code{MAKE} are executed normally despite the presence of a
4869 flag that causes most recipes not to be run.  The usual
4870 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
4871 (@pxref{Options/Recursion, ,Communicating Options to a
4872 Sub-@code{make}}), so your request to touch the files, or print the
4873 recipes, is propagated to the subsystem.
4874
4875 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
4876 @subsection Communicating Variables to a Sub-@code{make}
4877 @cindex sub-@code{make}
4878 @cindex environment, and recursion
4879 @cindex exporting variables
4880 @cindex variables, environment
4881 @cindex variables, exporting
4882 @cindex recursion, and environment
4883 @cindex recursion, and variables
4884
4885 Variable values of the top-level @code{make} can be passed to the
4886 sub-@code{make} through the environment by explicit request.  These
4887 variables are defined in the sub-@code{make} as defaults, but they do
4888 not override variables defined in the makefile used by
4889 the sub-@code{make} unless you use the @samp{-e} switch (@pxref{Options
4890 Summary, ,Summary of Options}).
4891
4892 To pass down, or @dfn{export}, a variable, @code{make} adds the
4893 variable and its value to the environment for running each line of the
4894 recipe.  The sub-@code{make}, in turn, uses the environment to
4895 initialize its table of variable values.  @xref{Environment,
4896 ,Variables from the Environment}.
4897
4898 Except by explicit request, @code{make} exports a variable only if it
4899 is either defined in the environment initially, or if set on the command
4900 line and its name consists only of letters, numbers, and underscores.
4901
4902 @cindex SHELL, exported value
4903 The value of the @code{make} variable @code{SHELL} is not exported.
4904 Instead, the value of the @code{SHELL} variable from the invoking
4905 environment is passed to the sub-@code{make}.  You can force
4906 @code{make} to export its value for @code{SHELL} by using the
4907 @code{export} directive, described below.  @xref{Choosing the Shell}.
4908
4909 The special variable @code{MAKEFLAGS} is always exported (unless you
4910 unexport it).  @code{MAKEFILES} is exported if you set it to anything.
4911
4912 @code{make} automatically passes down variable values that were defined
4913 on the command line, by putting them in the @code{MAKEFLAGS} variable.
4914 @iftex
4915 See the next section.
4916 @end iftex
4917 @ifnottex
4918 @xref{Options/Recursion}.
4919 @end ifnottex
4920
4921 Variables are @emph{not} normally passed down if they were created by
4922 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
4923 Implicit Rules}).  The sub-@code{make} will define these for
4924 itself.
4925
4926 @findex export
4927 If you want to export specific variables to a sub-@code{make}, use the
4928 @code{export} directive, like this:
4929
4930 @example
4931 export @var{variable} @dots{}
4932 @end example
4933
4934 @noindent
4935 @findex unexport
4936 If you want to @emph{prevent} a variable from being exported, use the
4937 @code{unexport} directive, like this:
4938
4939 @example
4940 unexport @var{variable} @dots{}
4941 @end example
4942
4943 @noindent
4944 In both of these forms, the arguments to @code{export} and
4945 @code{unexport} are expanded, and so could be variables or functions
4946 which expand to a (list of) variable names to be (un)exported.
4947
4948 As a convenience, you can define a variable and export it at the same
4949 time by doing:
4950
4951 @example
4952 export @var{variable} = value
4953 @end example
4954
4955 @noindent
4956 has the same result as:
4957
4958 @example
4959 @var{variable} = value
4960 export @var{variable}
4961 @end example
4962
4963 @noindent
4964 and
4965
4966 @example
4967 export @var{variable} := value
4968 @end example
4969
4970 @noindent
4971 has the same result as:
4972
4973 @example
4974 @var{variable} := value
4975 export @var{variable}
4976 @end example
4977
4978 Likewise,
4979
4980 @example
4981 export @var{variable} += value
4982 @end example
4983
4984 @noindent
4985 is just like:
4986
4987 @example
4988 @var{variable} += value
4989 export @var{variable}
4990 @end example
4991
4992 @noindent
4993 @xref{Appending, ,Appending More Text to Variables}.
4994
4995 You may notice that the @code{export} and @code{unexport} directives
4996 work in @code{make} in the same way they work in the shell, @code{sh}.
4997
4998 If you want all variables to be exported by default, you can use
4999 @code{export} by itself:
5000
5001 @example
5002 export
5003 @end example
5004
5005 @noindent
5006 This tells @code{make} that variables which are not explicitly mentioned in an
5007 @code{export} or @code{unexport} directive should be exported.  Any variable
5008 given in an @code{unexport} directive will still @emph{not} be exported.
5009
5010 @findex .EXPORT_ALL_VARIABLES
5011 @cindex compatibility in exporting
5012 The behavior elicited by an @code{export} directive by itself was the default
5013 in older versions of GNU @code{make}.  If your makefiles depend on this
5014 behavior and you want to be compatible with old versions of @code{make}, you
5015 can add the special target @code{.EXPORT_ALL_VARIABLES} to your makefile
5016 instead of using the @code{export} directive.  This will be ignored by old
5017 @code{make}s, while the @code{export} directive will cause a syntax
5018 error.
5019
5020 When using @code{export} by itself or @code{.EXPORT_ALL_VARIABLES} to export
5021 variables by default, only variables whose names consist solely of
5022 alphanumerics and underscores will be exported.  To export other variables you
5023 must specifically mention them in an @code{export} directive.
5024
5025 Adding a variable's value to the environment requires it to be expanded.  If
5026 expanding a variable has side-effects (such as the @code{info} or @code{eval}
5027 or similar functions) then these side-effects will be seen every time a
5028 command is invoked.  You can avoid this by ensuring that such variables have
5029 names which are not exportable by default.  However, a better solution is to
5030 @emph{not} use this ``export by default'' facility at all, and instead
5031 explicitly @code{export} the relevant variables by name.
5032
5033 You can use @code{unexport} by itself to tell @code{make} @emph{not} to export
5034 variables by default.  Since this is the default behavior, you would only need
5035 to do this if @code{export} had been used by itself earlier (in an included
5036 makefile, perhaps).  You @strong{cannot} use @code{export} and @code{unexport}
5037 by themselves to have variables exported for some recipes and not for others.
5038 The last @code{export} or @code{unexport} directive that appears by itself
5039 determines the behavior for the entire run of @code{make}.
5040
5041 @vindex MAKELEVEL
5042 @cindex recursion, level of
5043 As a special feature, the variable @code{MAKELEVEL} is changed when it
5044 is passed down from level to level.  This variable's value is a string
5045 which is the depth of the level as a decimal number.  The value is
5046 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
5047 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
5048 happens when @code{make} sets up the environment for a recipe.
5049
5050 The main use of @code{MAKELEVEL} is to test it in a conditional
5051 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
5052 way you can write a makefile that behaves one way if run recursively and
5053 another way if run directly by you.
5054
5055 @vindex MAKEFILES
5056 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
5057 commands to use additional makefiles.  The value of @code{MAKEFILES} is
5058 a whitespace-separated list of file names.  This variable, if defined in
5059 the outer-level makefile, is passed down through the environment; then
5060 it serves as a list of extra makefiles for the sub-@code{make} to read
5061 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
5062 Variable @code{MAKEFILES}}.
5063
5064 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
5065 @subsection Communicating Options to a Sub-@code{make}
5066 @cindex options, and recursion
5067 @cindex recursion, and options
5068
5069 @vindex MAKEFLAGS
5070 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
5071 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
5072 set up automatically by @code{make} to contain the flag letters that
5073 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
5074 @code{MAKEFLAGS} gets the value @samp{ks}.
5075
5076 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
5077 in its environment.  In response, it takes the flags from that value and
5078 processes them as if they had been given as arguments.
5079 @xref{Options Summary, ,Summary of Options}.
5080
5081 The value of @code{MAKEFLAGS} is a possibly empty group of characters
5082 representing single-letter options that take no argument, followed by a space
5083 and any options that take arguments or which have long option names.  If an
5084 option has both single-letter and long options, the single-letter option is
5085 always preferred.  If there are no single-letter options on the command line,
5086 then the value of @code{MAKEFLAGS} starts with a space.
5087
5088 @cindex command line variable definitions, and recursion
5089 @cindex variables, command line, and recursion
5090 @cindex recursion, and command line variable definitions
5091 Likewise variables defined on the command line are passed to the
5092 sub-@code{make} through @code{MAKEFLAGS}.  Words in the value of
5093 @code{MAKEFLAGS} that contain @samp{=}, @code{make} treats as variable
5094 definitions just as if they appeared on the command line.
5095 @xref{Overriding, ,Overriding Variables}.
5096
5097 @cindex @code{-C}, and recursion
5098 @cindex @code{-f}, and recursion
5099 @cindex @code{-o}, and recursion
5100 @cindex @code{-W}, and recursion
5101 @cindex @code{--directory}, and recursion
5102 @cindex @code{--file}, and recursion
5103 @cindex @code{--old-file}, and recursion
5104 @cindex @code{--assume-old}, and recursion
5105 @cindex @code{--assume-new}, and recursion
5106 @cindex @code{--new-file}, and recursion
5107 @cindex recursion, and @code{-C}
5108 @cindex recursion, and @code{-f}
5109 @cindex recursion, and @code{-o}
5110 @cindex recursion, and @code{-W}
5111 The options @samp{-C}, @samp{-f}, @samp{-o}, and @samp{-W} are not put
5112 into @code{MAKEFLAGS}; these options are not passed down.
5113
5114 @cindex @code{-j}, and recursion
5115 @cindex @code{--jobs}, and recursion
5116 @cindex recursion, and @code{-j}
5117 @cindex job slots, and recursion
5118 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
5119 If you set it to some numeric value @samp{N} and your operating system
5120 supports it (most any UNIX system will; others typically won't), the
5121 parent @code{make} and all the sub-@code{make}s will communicate to
5122 ensure that there are only @samp{N} jobs running at the same time
5123 between them all.  Note that any job that is marked recursive
5124 (@pxref{Instead of Execution, ,Instead of Executing Recipes})
5125 doesn't count against the total jobs (otherwise we could get @samp{N}
5126 sub-@code{make}s running and have no slots left over for any real work!)
5127
5128 If your operating system doesn't support the above communication, then
5129 no @samp{-j} is added to @code{MAKEFLAGS}, so that sub-@code{make}s
5130 run in non-parallel mode.  If the @w{@samp{-j}} option were passed down
5131 to sub-@code{make}s you would get many more jobs running in parallel
5132 than you asked for.  If you give @samp{-j} with no numeric argument,
5133 meaning to run as many jobs as possible in parallel, this is passed
5134 down, since multiple infinities are no more than one.
5135
5136 If you do not want to pass the other flags down, you must change the
5137 value of @code{MAKEFLAGS}, for example like this:
5138
5139 @example
5140 subsystem:
5141         cd subdir && $(MAKE) MAKEFLAGS=
5142 @end example
5143
5144 @vindex MAKEOVERRIDES
5145 The command line variable definitions really appear in the variable
5146 @code{MAKEOVERRIDES}, and @code{MAKEFLAGS} contains a reference to this
5147 variable.  If you do want to pass flags down normally, but don't want to
5148 pass down the command line variable definitions, you can reset
5149 @code{MAKEOVERRIDES} to empty, like this:
5150
5151 @example
5152 MAKEOVERRIDES =
5153 @end example
5154
5155 @noindent
5156 @cindex Arg list too long
5157 @cindex E2BIG
5158 This is not usually useful to do.  However, some systems have a small
5159 fixed limit on the size of the environment, and putting so much
5160 information into the value of @code{MAKEFLAGS} can exceed it.  If you
5161 see the error message @samp{Arg list too long}, this may be the problem.
5162 @findex .POSIX
5163 @cindex POSIX
5164 (For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
5165 not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
5166 in the makefile.  You probably do not care about this.)
5167
5168 @vindex MFLAGS
5169 A similar variable @code{MFLAGS} exists also, for historical
5170 compatibility.  It has the same value as @code{MAKEFLAGS} except that it
5171 does not contain the command line variable definitions, and it always
5172 begins with a hyphen unless it is empty (@code{MAKEFLAGS} begins with a
5173 hyphen only when it begins with an option that has no single-letter
5174 version, such as @samp{--warn-undefined-variables}).  @code{MFLAGS} was
5175 traditionally used explicitly in the recursive @code{make} command, like
5176 this:
5177
5178 @example
5179 subsystem:
5180         cd subdir && $(MAKE) $(MFLAGS)
5181 @end example
5182
5183 @noindent
5184 but now @code{MAKEFLAGS} makes this usage redundant.  If you want your
5185 makefiles to be compatible with old @code{make} programs, use this
5186 technique; it will work fine with more modern @code{make} versions too.
5187
5188 @cindex setting options from environment
5189 @cindex options, setting from environment
5190 @cindex setting options in makefiles
5191 @cindex options, setting in makefiles
5192 The @code{MAKEFLAGS} variable can also be useful if you want to have
5193 certain options, such as @samp{-k} (@pxref{Options Summary, ,Summary of
5194 Options}), set each time you run @code{make}.  You simply put a value for
5195 @code{MAKEFLAGS} in your environment.  You can also set @code{MAKEFLAGS} in
5196 a makefile, to specify additional flags that should also be in effect for
5197 that makefile.  (Note that you cannot use @code{MFLAGS} this way.  That
5198 variable is set only for compatibility; @code{make} does not interpret a
5199 value you set for it in any way.)
5200
5201 When @code{make} interprets the value of @code{MAKEFLAGS} (either from the
5202 environment or from a makefile), it first prepends a hyphen if the value
5203 does not already begin with one.  Then it chops the value into words
5204 separated by blanks, and parses these words as if they were options given
5205 on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
5206 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
5207 is no error for an invalid option).
5208
5209 If you do put @code{MAKEFLAGS} in your environment, you should be sure not
5210 to include any options that will drastically affect the actions of
5211 @code{make} and undermine the purpose of makefiles and of @code{make}
5212 itself.  For instance, the @samp{-t}, @samp{-n}, and @samp{-q} options, if
5213 put in one of these variables, could have disastrous consequences and would
5214 certainly have at least surprising and probably annoying effects.
5215
5216 If you'd like to run other implementations of @code{make} in addition
5217 to GNU @code{make}, and hence do not want to add GNU
5218 @code{make}-specific flags to the @code{MAKEFLAGS} variable, you can
5219 add them to the @code{GNUMAKEFLAGS} variable instead.  This variable
5220 is parsed just before @code{MAKEFLAGS}, in the same way as
5221 @code{MAKEFLAGS}.  When @code{make} constructs @code{MAKEFLAGS} to
5222 pass to a recursive @code{make} it will include all flags, even those
5223 taken from @code{GNUMAKEFLAGS}.  As a result, after parsing
5224 @code{GNUMAKEFLAGS} GNU @code{make} sets this variable to the empty
5225 string to avoid duplicating flags during recursion.
5226
5227 It's best to use @code{GNUMAKEFLAGS} only with flags which won't
5228 materially change the behavior of your makefiles.  If your makefiles
5229 require GNU make anyway then simply use @code{MAKEFLAGS}.  Flags such
5230 as @samp{--no-print-directory} or @samp{--output-sync} may be
5231 appropriate for @code{GNUMAKEFLAGS}.
5232
5233 @node -w Option,  , Options/Recursion, Recursion
5234 @subsection The @samp{--print-directory} Option
5235 @cindex directories, printing them
5236 @cindex printing directories
5237 @cindex recursion, and printing directories
5238
5239 If you use several levels of recursive @code{make} invocations, the
5240 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
5241 lot easier to understand by showing each directory as @code{make}
5242 starts processing it and as @code{make} finishes processing it.  For
5243 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
5244 @code{make} will print a line of the form:
5245
5246 @example
5247 make: Entering directory `/u/gnu/make'.
5248 @end example
5249
5250 @noindent
5251 before doing anything else, and a line of the form:
5252
5253 @example
5254 make: Leaving directory `/u/gnu/make'.
5255 @end example
5256
5257 @noindent
5258 when processing is completed.
5259
5260 @cindex @code{-C}, and @code{-w}
5261 @cindex @code{--directory}, and @code{--print-directory}
5262 @cindex recursion, and @code{-w}
5263 @cindex @code{-w}, and @code{-C}
5264 @cindex @code{-w}, and recursion
5265 @cindex @code{--print-directory}, and @code{--directory}
5266 @cindex @code{--print-directory}, and recursion
5267 @cindex @code{--no-print-directory}
5268 @cindex @code{--print-directory}, disabling
5269 @cindex @code{-w}, disabling
5270 Normally, you do not need to specify this option because @samp{make}
5271 does it for you: @samp{-w} is turned on automatically when you use the
5272 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
5273 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
5274 be silent, or if you use @samp{--no-print-directory} to explicitly
5275 disable it.
5276
5277 @node Canned Recipes, Empty Recipes, Recursion, Recipes
5278 @section Defining Canned Recipes
5279 @cindex canned recipes
5280 @cindex recipes, canned
5281 @cindex sequences of commands
5282 @cindex commands, sequences of
5283
5284 When the same sequence of commands is useful in making various
5285 targets, you can define it as a canned sequence with the @code{define}
5286 directive, and refer to the canned sequence from the recipes for those
5287 targets.  The canned sequence is actually a variable, so the name must
5288 not conflict with other variable names.
5289
5290 Here is an example of defining a canned recipe:
5291
5292 @example
5293 define run-yacc =
5294 yacc $(firstword $^)
5295 mv y.tab.c $@@
5296 endef
5297 @end example
5298 @cindex @code{yacc}
5299
5300 @noindent
5301 Here @code{run-yacc} is the name of the variable being defined;
5302 @code{endef} marks the end of the definition; the lines in between are the
5303 commands.  The @code{define} directive does not expand variable references
5304 and function calls in the canned sequence; the @samp{$} characters,
5305 parentheses, variable names, and so on, all become part of the value of the
5306 variable you are defining.
5307 @xref{Multi-Line, ,Defining Multi-Line Variables},
5308 for a complete explanation of @code{define}.
5309
5310 The first command in this example runs Yacc on the first prerequisite of
5311 whichever rule uses the canned sequence.  The output file from Yacc is
5312 always named @file{y.tab.c}.  The second command moves the output to the
5313 rule's target file name.
5314
5315 To use the canned sequence, substitute the variable into the recipe of a
5316 rule.  You can substitute it like any other variable
5317 (@pxref{Reference, ,Basics of Variable References}).
5318 Because variables defined by @code{define} are recursively expanded
5319 variables, all the variable references you wrote inside the @code{define}
5320 are expanded now.  For example:
5321
5322 @example
5323 foo.c : foo.y
5324         $(run-yacc)
5325 @end example
5326
5327 @noindent
5328 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
5329 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.
5330
5331 This is a realistic example, but this particular one is not needed in
5332 practice because @code{make} has an implicit rule to figure out these
5333 commands based on the file names involved
5334 (@pxref{Implicit Rules, ,Using Implicit Rules}).
5335
5336 @cindex @@, and @code{define}
5337 @cindex -, and @code{define}
5338 @cindex +, and @code{define}
5339 In recipe execution, each line of a canned sequence is treated just as
5340 if the line appeared on its own in the rule, preceded by a tab.  In
5341 particular, @code{make} invokes a separate sub-shell for each line.  You
5342 can use the special prefix characters that affect command lines
5343 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
5344 @xref{Recipes, ,Writing Recipes in Rules}.
5345 For example, using this canned sequence:
5346
5347 @example
5348 define frobnicate =
5349 @@echo "frobnicating target $@@"
5350 frob-step-1 $< -o $@@-step-1
5351 frob-step-2 $@@-step-1 -o $@@
5352 endef
5353 @end example
5354
5355 @noindent
5356 @code{make} will not echo the first line, the @code{echo} command.
5357 But it @emph{will} echo the following two recipe lines.
5358
5359 On the other hand, prefix characters on the recipe line that refers to
5360 a canned sequence apply to every line in the sequence.  So the rule:
5361
5362 @example
5363 frob.out: frob.in
5364         @@$(frobnicate)
5365 @end example
5366
5367 @noindent
5368 does not echo @emph{any} recipe lines.
5369 (@xref{Echoing, ,Recipe Echoing}, for a full explanation of @samp{@@}.)
5370
5371 @node Empty Recipes,  , Canned Recipes, Recipes
5372 @section Using Empty Recipes
5373 @cindex empty recipes
5374 @cindex recipes, empty
5375
5376 It is sometimes useful to define recipes which do nothing.  This is done
5377 simply by giving a recipe that consists of nothing but whitespace.  For
5378 example:
5379
5380 @example
5381 target: ;
5382 @end example
5383
5384 @noindent
5385 defines an empty recipe for @file{target}.  You could also use a line
5386 beginning with a recipe prefix character to define an empty recipe,
5387 but this would be confusing because such a line looks empty.
5388
5389 @findex .DEFAULT@r{, and empty recipes}
5390 You may be wondering why you would want to define a recipe that does
5391 nothing.  One reason this is useful is to prevent a target from
5392 getting implicit recipes (from implicit rules or the @code{.DEFAULT}
5393 special target; @pxref{Implicit Rules} and @pxref{Last Resort,
5394 ,Defining Last-Resort Default Rules}).
5395
5396 Empty recipes can also be used to avoid errors for targets that will
5397 be created as a side-effect of another recipe: if the target does not
5398 exist the empty recipe ensures that @code{make} won't complain that it
5399 doesn't know how to build the target, and @code{make} will assume the
5400 target is out of date.
5401
5402 You may be inclined to define empty recipes for targets that are not
5403 actual files, but only exist so that their prerequisites can be
5404 remade.  However, this is not the best way to do that, because the
5405 prerequisites may not be remade properly if the target file actually
5406 does exist.  @xref{Phony Targets, ,Phony Targets}, for a better way to
5407 do this.
5408
5409 @node Using Variables, Conditionals, Recipes, Top
5410 @chapter How to Use Variables
5411 @cindex variable
5412 @cindex value
5413 @cindex recursive variable expansion
5414 @cindex simple variable expansion
5415
5416 A @dfn{variable} is a name defined in a makefile to represent a string
5417 of text, called the variable's @dfn{value}.  These values are
5418 substituted by explicit request into targets, prerequisites, recipes,
5419 and other parts of the makefile.  (In some other versions of @code{make},
5420 variables are called @dfn{macros}.)
5421 @cindex macro
5422
5423 Variables and functions in all parts of a makefile are expanded when
5424 read, except for in recipes, the right-hand sides of variable
5425 definitions using @samp{=}, and the bodies of variable definitions
5426 using the @code{define} directive.  The value a variable expands to is
5427 that of its most recent definition at the time of expansion.  In other
5428 words, variables are dynamically scoped.
5429
5430 Variables can represent lists of file names, options to pass to compilers,
5431 programs to run, directories to look in for source files, directories to
5432 write output in, or anything else you can imagine.
5433
5434 A variable name may be any sequence of characters not containing
5435 @samp{:}, @samp{#}, @samp{=}, or whitespace.  However, variable names
5436 containing characters other than letters, numbers, and underscores
5437 should be considered carefully, as in some shells they cannot be
5438 passed through the environment to a sub-@code{make}
5439 (@pxref{Variables/Recursion, ,Communicating Variables to a
5440 Sub-@code{make}}).  Variable names beginning with @samp{.} and an
5441 uppercase letter may be given special meaning in future versions of
5442 @code{make}.
5443
5444 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
5445 and @samp{Foo} all refer to different variables.
5446
5447 It is traditional to use upper case letters in variable names, but we
5448 recommend using lower case letters for variable names that serve internal
5449 purposes in the makefile, and reserving upper case for parameters that
5450 control implicit rules or for parameters that the user should override with
5451 command options (@pxref{Overriding, ,Overriding Variables}).
5452
5453 A few variables have names that are a single punctuation character or
5454 just a few characters.  These are the @dfn{automatic variables}, and
5455 they have particular specialized uses.  @xref{Automatic Variables}.
5456
5457 @menu
5458 * Reference::                   How to use the value of a variable.
5459 * Flavors::                     Variables come in two flavors.
5460 * Advanced::                    Advanced features for referencing a variable.
5461 * Values::                      All the ways variables get their values.
5462 * Setting::                     How to set a variable in the makefile.
5463 * Appending::                   How to append more text to the old value
5464                                   of a variable.
5465 * Override Directive::          How to set a variable in the makefile even if
5466                                   the user has set it with a command argument.
5467 * Multi-Line::                  An alternate way to set a variable
5468                                   to a multi-line string.
5469 * Undefine Directive::          How to undefine a variable so that it appears
5470                                   as if it was never set.
5471 * Environment::                 Variable values can come from the environment.
5472 * Target-specific::             Variable values can be defined on a per-target
5473                                   basis.
5474 * Pattern-specific::            Target-specific variable values can be applied
5475                                   to a group of targets that match a pattern.
5476 * Suppressing Inheritance::     Suppress inheritance of variables.
5477 * Special Variables::           Variables with special meaning or behavior.
5478 @end menu
5479
5480 @node Reference, Flavors, Using Variables, Using Variables
5481 @section Basics of Variable References
5482 @cindex variables, how to reference
5483 @cindex reference to variables
5484 @cindex @code{$}, in variable reference
5485 @cindex dollar sign (@code{$}), in variable reference
5486
5487 To substitute a variable's value, write a dollar sign followed by the name
5488 of the variable in parentheses or braces: either @samp{$(foo)} or
5489 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
5490 special significance of @samp{$} is why you must write @samp{$$} to have
5491 the effect of a single dollar sign in a file name or recipe.
5492
5493 Variable references can be used in any context: targets, prerequisites,
5494 recipes, most directives, and new variable values.  Here is an
5495 example of a common case, where a variable holds the names of all the
5496 object files in a program:
5497
5498 @example
5499 @group
5500 objects = program.o foo.o utils.o
5501 program : $(objects)
5502         cc -o program $(objects)
5503
5504 $(objects) : defs.h
5505 @end group
5506 @end example
5507
5508 Variable references work by strict textual substitution.  Thus, the rule
5509
5510 @example
5511 @group
5512 foo = c
5513 prog.o : prog.$(foo)
5514         $(foo)$(foo) -$(foo) prog.$(foo)
5515 @end group
5516 @end example
5517
5518 @noindent
5519 could be used to compile a C program @file{prog.c}.  Since spaces before
5520 the variable value are ignored in variable assignments, the value of
5521 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
5522 this way!)
5523
5524 A dollar sign followed by a character other than a dollar sign,
5525 open-parenthesis or open-brace treats that single character as the
5526 variable name.  Thus, you could reference the variable @code{x} with
5527 @samp{$x}.  However, this practice can lead to confusion (e.g.,
5528 @samp{$foo} refers to the variable @code{f} followed by the string
5529 @code{oo}) so we recommend using parentheses or braces around all
5530 variables, even single-letter variables, unless omitting them gives
5531 significant readability improvements.  One place where readability is
5532 often improved is automatic variables (@pxref{Automatic Variables}).
5533
5534 @node Flavors, Advanced, Reference, Using Variables
5535 @section The Two Flavors of Variables
5536 @cindex flavors of variables
5537 @cindex recursive variable expansion
5538 @cindex variables, flavors
5539 @cindex recursively expanded variables
5540 @cindex variables, recursively expanded
5541
5542 There are different ways that a variable in GNU @code{make} can get a value;
5543 we call them the @dfn{flavors} of variables.  The flavors are distinguished in
5544 how they handle the values they are assigned in the makefile, and in how those
5545 values are managed when the variable is later used and expanded.
5546
5547 @menu
5548 * Recursive Assignment::        Setting recursively expanded variables.
5549 * Simple Assignment::           Setting simply expanded variables.
5550 * Immediate Assignment::        Setting immediately expanded variables.
5551 * Conditional Assignment::      Assigning variable values conditionally.
5552 @end menu
5553
5554 @node Recursive Assignment, Simple Assignment, Flavors, Flavors
5555 @subsection Recursively Expanded Variable Assignment
5556 @cindex =
5557 The first flavor of variable is a @dfn{recursively expanded} variable.
5558 Variables of this sort are defined by lines using @samp{=}
5559 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
5560 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).  The value you specify
5561 is installed verbatim; if it contains references to other variables,
5562 these references are expanded whenever this variable is substituted (in
5563 the course of expanding some other string).  When this happens, it is
5564 called @dfn{recursive expansion}.
5565
5566 For example,
5567
5568 @example
5569 foo = $(bar)
5570 bar = $(ugh)
5571 ugh = Huh?
5572
5573 all:;echo $(foo)
5574 @end example
5575
5576 @noindent
5577 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
5578 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.
5579
5580 This flavor of variable is the only sort supported by most other
5581 versions of @code{make}.  It has its advantages and its disadvantages.
5582 An advantage (most would say) is that:
5583
5584 @example
5585 CFLAGS = $(include_dirs) -O
5586 include_dirs = -Ifoo -Ibar
5587 @end example
5588
5589 @noindent
5590 will do what was intended: when @samp{CFLAGS} is expanded in a recipe,
5591 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
5592 cannot append something on the end of a variable, as in
5593
5594 @example
5595 CFLAGS = $(CFLAGS) -O
5596 @end example
5597
5598 @noindent
5599 because it will cause an infinite loop in the variable expansion.
5600 (Actually @code{make} detects the infinite loop and reports an error.)
5601 @cindex loops in variable expansion
5602 @cindex variables, loops in expansion
5603
5604 Another disadvantage is that any functions
5605 (@pxref{Functions, ,Functions for Transforming Text})
5606 referenced in the definition will be executed every time the variable is
5607 expanded.  This makes @code{make} run slower; worse, it causes the
5608 @code{wildcard} and @code{shell} functions to give unpredictable results
5609 because you cannot easily control when they are called, or even how many
5610 times.
5611
5612 @node Simple Assignment, Immediate Assignment, Recursive Assignment, Flavors
5613 @subsection Simply Expanded Variable Assignment
5614 To avoid the problems and inconveniences of recursively expanded
5615 variables, there is another flavor: simply expanded variables.
5616
5617 @cindex simply expanded variables
5618 @cindex variables, simply expanded
5619 @cindex :=
5620 @cindex ::=
5621 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
5622 or @samp{::=} (@pxref{Setting, ,Setting Variables}).  Both forms are
5623 equivalent in GNU @code{make}; however only the @samp{::=} form is
5624 described by the POSIX standard (support for @samp{::=} is added to
5625 the POSIX standard for POSIX Issue 8).
5626
5627 The value of a simply expanded variable is scanned once, expanding any
5628 references to other variables and functions, when the variable is
5629 defined.  Once that expansion is complete the value of the variable is
5630 never expanded again: when the variable is used the value is copied
5631 verbatim as the expansion.  If the value contained variable references
5632 the result of the expansion will contain their values @emph{as of the
5633 time this variable was defined}.  Therefore,
5634
5635 @example
5636 @group
5637 x := foo
5638 y := $(x) bar
5639 x := later
5640 @end group
5641 @end example
5642
5643 @noindent
5644 is equivalent to
5645
5646 @example
5647 @group
5648 y := foo bar
5649 x := later
5650 @end group
5651 @end example
5652
5653 Here is a somewhat more complicated example, illustrating the use of
5654 @samp{:=} in conjunction with the @code{shell} function.
5655 (@xref{Shell Function, , The @code{shell} Function}.)  This example
5656 also shows use of the variable @code{MAKELEVEL}, which is changed
5657 when it is passed down from level to level.
5658 (@xref{Variables/Recursion, , Communicating Variables to a
5659 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
5660
5661 @vindex MAKELEVEL
5662 @vindex MAKE
5663 @example
5664 @group
5665 ifeq (0,$@{MAKELEVEL@})
5666 whoami    := $(shell whoami)
5667 host-type := $(shell arch)
5668 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
5669 endif
5670 @end group
5671 @end example
5672
5673 @noindent
5674 An advantage of this use of @samp{:=} is that a typical
5675 `descend into a directory' recipe then looks like this:
5676
5677 @example
5678 @group
5679 $@{subdirs@}:
5680         $@{MAKE@} -C $@@ all
5681 @end group
5682 @end example
5683
5684 Simply expanded variables generally make complicated makefile programming
5685 more predictable because they work like variables in most programming
5686 languages.  They allow you to redefine a variable using its own value (or
5687 its value processed in some way by one of the expansion functions) and to
5688 use the expansion functions much more efficiently
5689 (@pxref{Functions, ,Functions for Transforming Text}).
5690
5691 @cindex spaces, in variable values
5692 @cindex whitespace, in variable values
5693 @cindex variables, spaces in values
5694 You can also use them to introduce controlled leading whitespace into
5695 variable values.  Leading whitespace characters are discarded from your
5696 input before substitution of variable references and function calls;
5697 this means you can include leading spaces in a variable value by
5698 protecting them with variable references, like this:
5699
5700 @example
5701 @group
5702 nullstring :=
5703 space := $(nullstring) # end of the line
5704 @end group
5705 @end example
5706
5707 @noindent
5708 Here the value of the variable @code{space} is precisely one space.  The
5709 comment @w{@samp{# end of the line}} is included here just for clarity.
5710 Since trailing space characters are @emph{not} stripped from variable
5711 values, just a space at the end of the line would have the same effect
5712 (but be rather hard to read).  If you put whitespace at the end of a
5713 variable value, it is a good idea to put a comment like that at the end
5714 of the line to make your intent clear.  Conversely, if you do @emph{not}
5715 want any whitespace characters at the end of your variable value, you
5716 must remember not to put a random comment on the end of the line after
5717 some whitespace, such as this:
5718
5719 @example
5720 dir := /foo/bar    # directory to put the frobs in
5721 @end example
5722
5723 @noindent
5724 Here the value of the variable @code{dir} is @w{@samp{/foo/bar    }}
5725 (with four trailing spaces), which was probably not the intention.
5726 (Imagine something like @w{@samp{$(dir)/file}} with this definition!)
5727
5728 @node Immediate Assignment, Conditional Assignment, Simple Assignment, Flavors
5729 @subsection Immediately Expanded Variable Assignment
5730 @cindex immediate variable assignment
5731 @cindex variables, immediate assignment
5732 @cindex :::=
5733
5734 Another form of assignment allows for immediate expansion, but unlike simple
5735 assignment the resulting variable is recursive: it will be re-expanded again
5736 on every use.  In order to avoid unexpected results, after the value is
5737 immediately expanded it will automatically be quoted: all instances of
5738 @code{$} in the value after expansion will be converted into @code{$$}.  This
5739 type of assignment uses the @samp{:::=} operator.  For example,
5740
5741 @example
5742 @group
5743 var = first
5744 OUT :::= $(var)
5745 var = second
5746 @end group
5747 @end example
5748
5749 @noindent
5750 results in the @code{OUT} variable containing the text @samp{first}, while here:
5751
5752 @example
5753 @group
5754 var = one$$two
5755 OUT :::= $(var)
5756 var = three$$four
5757 @end group
5758 @end example
5759
5760 @noindent
5761 results in the @code{OUT} variable containing the text @samp{one$$two}.  The
5762 value is expanded when the variable is assigned, so the result is the
5763 expansion of the first value of @code{var}, @samp{one$two}; then the value is
5764 re-escaped before the assignment is complete giving the final result of
5765 @samp{one$$two}.
5766
5767 The variable @code{OUT} is thereafter considered a recursive variable, so it
5768 will be re-expanded when it is used.
5769
5770 This seems functionally equivalent to the @samp{:=} / @samp{::=} operators,
5771 but there are a few differences:
5772
5773 First, after assignment the variable is a normal recursive variable; when you
5774 append to it with @samp{+=} the value on the right-hand side is not expanded
5775 immediately.  If you prefer the @samp{+=} operator to expand the right-hand
5776 side immediately you should use the @samp{:=} / @samp{::=} assignment instead.
5777
5778 Second, these variables are slightly less efficient than simply expanded
5779 variables since they do need to be re-expanded when they are used, rather than
5780 merely copied.  However since all variable references are escaped this
5781 expansion simply un-escapes the value, it won't expand any variables or run
5782 any functions.
5783
5784 Here is another example:
5785
5786 @example
5787 @group
5788 var = one$$two
5789 OUT :::= $(var)
5790 OUT += $(var)
5791 var = three$$four
5792 @end group
5793 @end example
5794
5795 After this, the value of @code{OUT} is the text @samp{one$$two $(var)}.  When
5796 this variable is used it will be expanded and the result will be
5797 @samp{one$two three$four}.
5798
5799 This style of assignment is equivalent to the traditional BSD @code{make}
5800 @samp{:=} operator; as you can see it works slightly differently than the GNU
5801 @code{make} @samp{:=} operator.  The @code{:::=} operator is added to the
5802 POSIX specification in Issue 8 to provide portability.
5803
5804 @node Conditional Assignment, , Immediate Assignment, Flavors
5805 @subsection Conditional Variable Assignment
5806 @cindex conditional variable assignment
5807 @cindex variables, conditional assignment
5808 @cindex ?=
5809 There is another assignment operator for variables, @samp{?=}.  This
5810 is called a conditional variable assignment operator, because it only
5811 has an effect if the variable is not yet defined.  This statement:
5812
5813 @example
5814 FOO ?= bar
5815 @end example
5816
5817 @noindent
5818 is exactly equivalent to this
5819 (@pxref{Origin Function, ,The @code{origin} Function}):
5820
5821 @example
5822 ifeq ($(origin FOO), undefined)
5823   FOO = bar
5824 endif
5825 @end example
5826
5827 Note that a variable set to an empty value is still defined, so
5828 @samp{?=} will not set that variable.
5829
5830 @node Advanced, Values, Flavors, Using Variables
5831 @section Advanced Features for Reference to Variables
5832 @cindex reference to variables
5833
5834 This section describes some advanced features you can use to reference
5835 variables in more flexible ways.
5836
5837 @menu
5838 * Substitution Refs::           Referencing a variable with
5839                                   substitutions on the value.
5840 * Computed Names::              Computing the name of the variable to refer to.
5841 @end menu
5842
5843 @node Substitution Refs, Computed Names, Advanced, Advanced
5844 @subsection Substitution References
5845 @cindex modified variable reference
5846 @cindex substitution variable reference
5847 @cindex variables, modified reference
5848 @cindex variables, substitution reference
5849
5850 @cindex variables, substituting suffix in
5851 @cindex suffix, substituting in variables
5852 A @dfn{substitution reference} substitutes the value of a variable with
5853 alterations that you specify.  It has the form
5854 @samp{$(@var{var}:@var{a}=@var{b})} (or
5855 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
5856 of the variable @var{var}, replace every @var{a} at the end of a word with
5857 @var{b} in that value, and substitute the resulting string.
5858
5859 When we say ``at the end of a word'', we mean that @var{a} must appear
5860 either followed by whitespace or at the end of the value in order to be
5861 replaced; other occurrences of @var{a} in the value are unaltered.  For
5862 example:
5863
5864 @example
5865 foo := a.o b.o l.a c.o
5866 bar := $(foo:.o=.c)
5867 @end example
5868
5869 @noindent
5870 sets @samp{bar} to @samp{a.c b.c l.a c.c}.  @xref{Setting, ,Setting Variables}.
5871
5872 A substitution reference is shorthand for the @code{patsubst}
5873 expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
5874 @samp{$(@var{var}:@var{a}=@var{b})} is equivalent to
5875 @samp{$(patsubst %@var{a},%@var{b},@var{var})}.  We provide
5876 substitution references as well as @code{patsubst} for compatibility
5877 with other implementations of @code{make}.
5878
5879 @findex patsubst
5880 Another type of substitution reference lets you use the full power of
5881 the @code{patsubst} function.  It has the same form
5882 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
5883 @var{a} must contain a single @samp{%} character.  This case is
5884 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
5885 @xref{Text Functions, ,Functions for String Substitution and Analysis},
5886 for a description of the @code{patsubst} function.  For example:
5887
5888 @example
5889 @group
5890 foo := a.o b.o l.a c.o
5891 bar := $(foo:%.o=%.c)
5892 @end group
5893 @end example
5894
5895 @noindent
5896 sets @samp{bar} to @samp{a.c b.c l.a c.c}.
5897
5898 @node Computed Names,  , Substitution Refs, Advanced
5899 @subsection Computed Variable Names
5900 @cindex nested variable reference
5901 @cindex computed variable name
5902 @cindex variables, computed names
5903 @cindex variables, nested references
5904 @cindex variables, @samp{$} in name
5905 @cindex @code{$}, in variable name
5906 @cindex dollar sign (@code{$}), in variable name
5907
5908 Computed variable names are an advanced concept, very useful in more
5909 sophisticated makefile programming.  In simple situations you need not
5910 consider them, but they can be extremely useful.
5911
5912 Variables may be referenced inside the name of a variable.  This is
5913 called a @dfn{computed variable name} or a @dfn{nested variable
5914 reference}.  For example,
5915
5916 @example
5917 x = y
5918 y = z
5919 a := $($(x))
5920 @end example
5921
5922 @noindent
5923 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
5924 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
5925 to @samp{z}.  Here the name of the variable to reference is not stated
5926 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
5927 @samp{$(x)} here is nested within the outer variable reference.
5928
5929 The previous example shows two levels of nesting, but any number of levels
5930 is possible.  For example, here are three levels:
5931
5932 @example
5933 x = y
5934 y = z
5935 z = u
5936 a := $($($(x)))
5937 @end example
5938
5939 @noindent
5940 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
5941 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
5942 @samp{$(z)}, which becomes @samp{u}.
5943
5944 References to recursively-expanded variables within a variable name are
5945 re-expanded in the usual fashion.  For example:
5946
5947 @example
5948 x = $(y)
5949 y = z
5950 z = Hello
5951 a := $($(x))
5952 @end example
5953
5954 @noindent
5955 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
5956 which becomes @samp{$(z)} which becomes @samp{Hello}.
5957
5958 Nested variable references can also contain modified references and function
5959 invocations (@pxref{Functions, ,Functions for Transforming Text}), just like
5960 any other reference.  For example, using the @code{subst} function
5961 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
5962
5963 @example
5964 @group
5965 x = variable1
5966 variable2 := Hello
5967 y = $(subst 1,2,$(x))
5968 z = y
5969 a := $($($(z)))
5970 @end group
5971 @end example
5972
5973 @noindent
5974 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
5975 would ever want to write a nested reference as convoluted as this one, but
5976 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
5977 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
5978 @code{x} and changes it by substitution to @samp{variable2}, so that the
5979 entire string becomes @samp{$(variable2)}, a simple variable reference
5980 whose value is @samp{Hello}.
5981
5982 A computed variable name need not consist entirely of a single variable
5983 reference.  It can contain several variable references, as well as some
5984 invariant text.  For example,
5985
5986 @example
5987 @group
5988 a_dirs := dira dirb
5989 1_dirs := dir1 dir2
5990 @end group
5991
5992 @group
5993 a_files := filea fileb
5994 1_files := file1 file2
5995 @end group
5996
5997 @group
5998 ifeq "$(use_a)" "yes"
5999 a1 := a
6000 else
6001 a1 := 1
6002 endif
6003 @end group
6004
6005 @group
6006 ifeq "$(use_dirs)" "yes"
6007 df := dirs
6008 else
6009 df := files
6010 endif
6011
6012 dirs := $($(a1)_$(df))
6013 @end group
6014 @end example
6015
6016 @noindent
6017 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
6018 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
6019 and @code{use_dirs}.
6020
6021 Computed variable names can also be used in substitution references:
6022
6023 @example
6024 @group
6025 a_objects := a.o b.o c.o
6026 1_objects := 1.o 2.o 3.o
6027
6028 sources := $($(a1)_objects:.o=.c)
6029 @end group
6030 @end example
6031
6032 @noindent
6033 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
6034 depending on the value of @code{a1}.
6035
6036 The only restriction on this sort of use of nested variable references
6037 is that they cannot specify part of the name of a function to be called.
6038 This is because the test for a recognized function name is done before
6039 the expansion of nested references.  For example,
6040
6041 @example
6042 @group
6043 ifdef do_sort
6044 func := sort
6045 else
6046 func := strip
6047 endif
6048 @end group
6049
6050 @group
6051 bar := a d b g q c
6052 @end group
6053
6054 @group
6055 foo := $($(func) $(bar))
6056 @end group
6057 @end example
6058
6059 @noindent
6060 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
6061 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
6062 as the argument to either the @code{sort} or the @code{strip} function.
6063 This restriction could be removed in the future if that change is shown
6064 to be a good idea.
6065
6066 You can also use computed variable names in the left-hand side of a
6067 variable assignment, or in a @code{define} directive, as in:
6068
6069 @example
6070 dir = foo
6071 $(dir)_sources := $(wildcard $(dir)/*.c)
6072 define $(dir)_print =
6073 lpr $($(dir)_sources)
6074 endef
6075 @end example
6076
6077 @noindent
6078 This example defines the variables @samp{dir}, @samp{foo_sources}, and
6079 @samp{foo_print}.
6080
6081 Note that @dfn{nested variable references} are quite different from
6082 @dfn{recursively expanded variables}
6083 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
6084 used together in complex ways when doing makefile programming.
6085
6086 @node Values, Setting, Advanced, Using Variables
6087 @section How Variables Get Their Values
6088 @cindex variables, how they get their values
6089 @cindex value, how a variable gets it
6090
6091 Variables can get values in several different ways:
6092
6093 @itemize @bullet
6094 @item
6095 You can specify an overriding value when you run @code{make}.
6096 @xref{Overriding, ,Overriding Variables}.
6097
6098 @item
6099 You can specify a value in the makefile, either
6100 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
6101 verbatim definition (@pxref{Multi-Line, ,Defining Multi-Line Variables}).
6102
6103 @item
6104 You can specify a short-lived value with the @code{let} function
6105 (@pxref{Let Function}) or with the @code{foreach} function
6106 (@pxref{Foreach Function}).
6107
6108 @item
6109 Variables in the environment become @code{make} variables.
6110 @xref{Environment, ,Variables from the Environment}.
6111
6112 @item
6113 Several @dfn{automatic} variables are given new values for each rule.
6114 Each of these has a single conventional use.
6115 @xref{Automatic Variables}.
6116
6117 @item
6118 Several variables have constant initial values.
6119 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
6120 @end itemize
6121
6122 @node Setting, Appending, Values, Using Variables
6123 @section Setting Variables
6124 @cindex setting variables
6125 @cindex variables, setting
6126 @cindex =
6127 @cindex :=
6128 @cindex ::=
6129 @cindex :::=
6130 @cindex ?=
6131 @cindex !=
6132
6133 To set a variable from the makefile, write a line starting with the variable
6134 name followed by one of the assignment operators @samp{=}, @samp{:=},
6135 @samp{::=}, or @samp{:::=}.  Whatever follows the operator and any initial
6136 whitespace on the line becomes the value.  For example,
6137
6138 @example
6139 objects = main.o foo.o bar.o utils.o
6140 @end example
6141
6142 @noindent
6143 defines a variable named @code{objects} to contain the value @samp{main.o
6144 foo.o bar.o utils.o}.  Whitespace around the variable name and immediately
6145 after the @samp{=} is ignored.
6146
6147 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
6148 Variables defined with @samp{:=} or @samp{::=} are @dfn{simply expanded}
6149 variables; these definitions can contain variable references which will be
6150 expanded before the definition is made.  Variables defined with @samp{:::=}
6151 are @dfn{immediately expanded} variables.  The different assignment operators
6152 are described in @xref{Flavors, ,The Two Flavors of Variables}.
6153
6154 The variable name may contain function and variable references, which
6155 are expanded when the line is read to find the actual variable name to use.
6156
6157 There is no limit on the length of the value of a variable except the
6158 amount of memory on the computer.  You can split the value of a
6159 variable into multiple physical lines for readability
6160 (@pxref{Splitting Lines, ,Splitting Long Lines}).
6161
6162 Most variable names are considered to have the empty string as a value if
6163 you have never set them.  Several variables have built-in initial values
6164 that are not empty, but you can set them in the usual ways
6165 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).
6166 Several special variables are set
6167 automatically to a new value for each rule; these are called the
6168 @dfn{automatic} variables (@pxref{Automatic Variables}).
6169
6170 If you'd like a variable to be set to a value only if it's not already
6171 set, then you can use the shorthand operator @samp{?=} instead of
6172 @samp{=}.  These two settings of the variable @samp{FOO} are identical
6173 (@pxref{Origin Function, ,The @code{origin} Function}):
6174
6175 @example
6176 FOO ?= bar
6177 @end example
6178
6179 @noindent
6180 and
6181
6182 @example
6183 ifeq ($(origin FOO), undefined)
6184 FOO = bar
6185 endif
6186 @end example
6187
6188 The shell assignment operator @samp{!=} can be used to execute a
6189 shell script and set a variable to its output.  This operator first
6190 evaluates the right-hand side, then passes that result to the shell
6191 for execution.  If the result of the execution ends in a newline, that
6192 one newline is removed; all other newlines are replaced by spaces.
6193 The resulting string is then placed into the named
6194 recursively-expanded variable.  For example:
6195
6196 @example
6197 hash != printf '\043'
6198 file_list != find . -name '*.c'
6199 @end example
6200
6201 If the result of the execution could produce a @code{$}, and you don't
6202 intend what follows that to be interpreted as a make variable or
6203 function reference, then you must replace every @code{$} with
6204 @code{$$} as part of the execution.  Alternatively, you can set a
6205 simply expanded variable to the result of running a program using the
6206 @code{shell} function call.  @xref{Shell Function, , The @code{shell}
6207 Function}.  For example:
6208
6209 @example
6210 hash := $(shell printf '\043')
6211 var := $(shell find . -name "*.c")
6212 @end example
6213
6214 As with the @code{shell} function, the exit status of the just-invoked
6215 shell script is stored in the @code{.SHELLSTATUS} variable.
6216
6217
6218 @node Appending, Override Directive, Setting, Using Variables
6219 @section Appending More Text to Variables
6220 @cindex +=
6221 @cindex appending to variables
6222 @cindex variables, appending to
6223
6224 Often it is useful to add more text to the value of a variable already defined.
6225 You do this with a line containing @samp{+=}, like this:
6226
6227 @example
6228 objects += another.o
6229 @end example
6230
6231 @noindent
6232 This takes the value of the variable @code{objects}, and adds the text
6233 @samp{another.o} to it (preceded by a single space, if it has a value
6234 already).  Thus:
6235
6236 @example
6237 objects = main.o foo.o bar.o utils.o
6238 objects += another.o
6239 @end example
6240
6241 @noindent
6242 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
6243
6244 Using @samp{+=} is similar to:
6245
6246 @example
6247 objects = main.o foo.o bar.o utils.o
6248 objects := $(objects) another.o
6249 @end example
6250
6251 @noindent
6252 but differs in ways that become important when you use more complex values.
6253
6254 When the variable in question has not been defined before, @samp{+=}
6255 acts just like normal @samp{=}: it defines a recursively-expanded
6256 variable.  However, when there @emph{is} a previous definition, exactly
6257 what @samp{+=} does depends on what flavor of variable you defined
6258 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
6259 explanation of the two flavors of variables.
6260
6261 When you add to a variable's value with @samp{+=}, @code{make} acts
6262 essentially as if you had included the extra text in the initial definition of
6263 the variable.  If you defined it first with @samp{:=} or @samp{::=}, making it
6264 a simply-expanded variable, @samp{+=} adds to that simply-expanded definition,
6265 and expands the new text before appending it to the old value just as
6266 @samp{:=} does (see @ref{Setting, ,Setting Variables}, for a full explanation
6267 of @samp{:=} or @samp{::=}).  In fact,
6268
6269 @example
6270 variable := value
6271 variable += more
6272 @end example
6273
6274 @noindent
6275 is exactly equivalent to:
6276
6277 @noindent
6278 @example
6279 variable := value
6280 variable := $(variable) more
6281 @end example
6282
6283 On the other hand, when you use @samp{+=} with a variable that you defined
6284 first to be recursively-expanded using plain @samp{=} or @samp{:::=},
6285 @code{make} appends the un-expanded text to the existing value, whatever it
6286 is.  This means that
6287
6288 @example
6289 @group
6290 variable = value
6291 variable += more
6292 @end group
6293 @end example
6294
6295 @noindent
6296 is roughly equivalent to:
6297
6298 @example
6299 @group
6300 temp = value
6301 variable = $(temp) more
6302 @end group
6303 @end example
6304
6305 @noindent
6306 except that of course it never defines a variable called @code{temp}.
6307 The importance of this comes when the variable's old value contains
6308 variable references.  Take this common example:
6309
6310 @example
6311 CFLAGS = $(includes) -O
6312 @dots{}
6313 CFLAGS += -pg # enable profiling
6314 @end example
6315
6316 @noindent
6317 The first line defines the @code{CFLAGS} variable with a reference to another
6318 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
6319 compilation; @pxref{Catalogue of Rules, ,Catalogue of Built-In Rules}.)
6320 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
6321 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
6322 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
6323 need not be defined yet for its value to take effect.  It only has to be
6324 defined before any reference to @code{CFLAGS}.  If we tried to append to the
6325 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
6326
6327 @example
6328 CFLAGS := $(CFLAGS) -pg # enable profiling
6329 @end example
6330
6331 @noindent
6332 This is pretty close, but not quite what we want.  Using @samp{:=}
6333 redefines @code{CFLAGS} as a simply-expanded variable; this means
6334 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
6335 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
6336 -pg}}, and a later definition of @code{includes} will have no effect.
6337 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
6338 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
6339 the reference to @code{includes}, so if that variable gets defined at
6340 any later point, a reference like @samp{$(CFLAGS)} still uses its
6341 value.
6342
6343 @node Override Directive, Multi-Line, Appending, Using Variables
6344 @section The @code{override} Directive
6345 @findex override
6346 @cindex overriding with @code{override}
6347 @cindex variables, overriding
6348
6349 If a variable has been set with a command argument
6350 (@pxref{Overriding, ,Overriding Variables}),
6351 then ordinary assignments in the makefile are ignored.  If you want to set
6352 the variable in the makefile even though it was set with a command
6353 argument, you can use an @code{override} directive, which is a line that
6354 looks like this:
6355
6356 @example
6357 override @var{variable} = @var{value}
6358 @end example
6359
6360 @noindent
6361 or
6362
6363 @example
6364 override @var{variable} := @var{value}
6365 @end example
6366
6367 To append more text to a variable defined on the command line, use:
6368
6369 @example
6370 override @var{variable} += @var{more text}
6371 @end example
6372
6373 @noindent
6374 @xref{Appending, ,Appending More Text to Variables}.
6375
6376 Variable assignments marked with the @code{override} flag have a
6377 higher priority than all other assignments, except another
6378 @code{override}.  Subsequent assignments or appends to this variable
6379 which are not marked @code{override} will be ignored.
6380
6381 The @code{override} directive was not invented for escalation in the war
6382 between makefiles and command arguments.  It was invented so you can alter
6383 and add to values that the user specifies with command arguments.
6384
6385 For example, suppose you always want the @samp{-g} switch when you run the
6386 C compiler, but you would like to allow the user to specify the other
6387 switches with a command argument just as usual.  You could use this
6388 @code{override} directive:
6389
6390 @example
6391 override CFLAGS += -g
6392 @end example
6393
6394 You can also use @code{override} directives with @code{define} directives.
6395 This is done as you might expect:
6396
6397 @example
6398 override define foo =
6399 bar
6400 endef
6401 @end example
6402
6403 @noindent
6404 @iftex
6405 See the next section for information about @code{define}.
6406 @end iftex
6407 @ifnottex
6408 @xref{Multi-Line, ,Defining Multi-Line Variables}.
6409 @end ifnottex
6410
6411 @node Multi-Line, Undefine Directive, Override Directive, Using Variables
6412 @section Defining Multi-Line Variables
6413 @findex define
6414 @findex endef
6415 @cindex multi-line variable definition
6416 @cindex variables, multi-line
6417 @cindex verbatim variable definition
6418 @cindex defining variables verbatim
6419 @cindex variables, defining verbatim
6420
6421 Another way to set the value of a variable is to use the @code{define}
6422 directive.  This directive has an unusual syntax which allows newline
6423 characters to be included in the value, which is convenient for
6424 defining both canned sequences of commands (@pxref{Canned Recipes,
6425 ,Defining Canned Recipes}), and also sections of makefile syntax to
6426 use with @code{eval} (@pxref{Eval Function}).
6427
6428 The @code{define} directive is followed on the same line by the name
6429 of the variable being defined and an (optional) assignment operator,
6430 and nothing more.  The value to give the variable appears on the
6431 following lines.  The end of the value is marked by a line containing
6432 just the word @code{endef}.
6433
6434 Aside from this difference in syntax, @code{define} works just like
6435 any other variable definition.  The variable name may contain function
6436 and variable references, which are expanded when the directive is read
6437 to find the actual variable name to use.
6438
6439 The final newline before the @code{endef} is not included in the
6440 value; if you want your value to contain a trailing newline you must
6441 include a blank line.  For example in order to define a variable that
6442 contains a newline character you must use @emph{two} empty lines, not one:
6443
6444 @example
6445 define newline
6446
6447
6448 endef
6449 @end example
6450
6451 You may omit the variable assignment operator if you prefer.  If
6452 omitted, @code{make} assumes it to be @samp{=} and creates a
6453 recursively-expanded variable (@pxref{Flavors, ,The Two Flavors of Variables}).
6454 When using a @samp{+=} operator, the value is appended to the previous
6455 value as with any other append operation: with a single space
6456 separating the old and new values.
6457
6458 You may nest @code{define} directives: @code{make} will keep track of
6459 nested directives and report an error if they are not all properly
6460 closed with @code{endef}.  Note that lines beginning with the recipe
6461 prefix character are considered part of a recipe, so any @code{define}
6462 or @code{endef} strings appearing on such a line will not be
6463 considered @code{make} directives.
6464
6465 @example
6466 define two-lines
6467 echo foo
6468 echo $(bar)
6469 endef
6470 @end example
6471
6472 @need 800
6473 When used in a recipe, the previous example is functionally equivalent
6474 to this:
6475
6476 @example
6477 two-lines = echo foo; echo $(bar)
6478 @end example
6479
6480 @noindent
6481 since two commands separated by semicolon behave much like two separate
6482 shell commands.  However, note that using two separate lines means
6483 @code{make} will invoke the shell twice, running an independent sub-shell
6484 for each line.  @xref{Execution, ,Recipe Execution}.
6485
6486 If you want variable definitions made with @code{define} to take
6487 precedence over command-line variable definitions, you can use the
6488 @code{override} directive together with @code{define}:
6489
6490 @example
6491 override define two-lines =
6492 foo
6493 $(bar)
6494 endef
6495 @end example
6496
6497 @noindent
6498 @xref{Override Directive, ,The @code{override} Directive}.
6499
6500 @node Undefine Directive, Environment, Multi-Line, Using Variables
6501 @section Undefining Variables
6502 @findex undefine
6503 @cindex undefining variable
6504
6505 If you want to clear a variable, setting its value to empty is usually
6506 sufficient. Expanding such a variable will yield the same result (empty
6507 string) regardless of whether it was set or not. However, if you are
6508 using the @code{flavor} (@pxref{Flavor Function}) and
6509 @code{origin} (@pxref{Origin Function}) functions, there is a difference
6510 between a variable that was never set and a variable with an empty value.
6511 In such situations you may want to use the @code{undefine} directive to
6512 make a variable appear as if it was never set. For example:
6513
6514 @example
6515 @group
6516 foo := foo
6517 bar = bar
6518
6519 undefine foo
6520 undefine bar
6521
6522 $(info $(origin foo))
6523 $(info $(flavor bar))
6524 @end group
6525 @end example
6526
6527 This example will print ``undefined'' for both variables.
6528
6529 If you want to undefine a command-line variable definition, you can use
6530 the @code{override} directive together with @code{undefine}, similar to
6531 how this is done for variable definitions:
6532
6533 @example
6534 override undefine CFLAGS
6535 @end example
6536
6537 @node Environment, Target-specific, Undefine Directive, Using Variables
6538 @section Variables from the Environment
6539
6540 @cindex variables, environment
6541 @cindex environment
6542 Variables in @code{make} can come from the environment in which
6543 @code{make} is run.  Every environment variable that @code{make} sees
6544 when it starts up is transformed into a @code{make} variable with the
6545 same name and value.  However, an explicit assignment in the makefile,
6546 or with a command argument, overrides the environment.  (If the
6547 @samp{-e} flag is specified, then values from the environment override
6548 assignments in the makefile.  @xref{Options Summary, ,Summary of
6549 Options}.  But this is not recommended practice.)
6550
6551 Thus, by setting the variable @code{CFLAGS} in your environment, you can
6552 cause all C compilations in most makefiles to use the compiler switches you
6553 prefer.  This is safe for variables with standard or conventional meanings
6554 because you know that no makefile will use them for other things.  (Note
6555 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
6556 and therefore are not affected by the value in the environment.)
6557
6558 When @code{make} runs a recipe, some variables defined in the makefile
6559 are placed into the environment of each command @code{make} invokes.
6560 By default, only variables that came from the @code{make}'s
6561 environment or set on its command line are placed into the environment
6562 of the commands.  You can use the @code{export} directive to pass
6563 other variables.  @xref{Variables/Recursion, , Communicating Variables
6564 to a Sub-@code{make}}, for full details.
6565
6566 Other use of variables from the environment is not recommended.  It is not
6567 wise for makefiles to depend for their functioning on environment variables
6568 set up outside their control, since this would cause different users to get
6569 different results from the same makefile.  This is against the whole
6570 purpose of most makefiles.
6571
6572 @cindex SHELL, import from environment
6573 Such problems would be especially likely with the variable
6574 @code{SHELL}, which is normally present in the environment to specify
6575 the user's choice of interactive shell.  It would be very undesirable
6576 for this choice to affect @code{make}; so, @code{make} handles the
6577 @code{SHELL} environment variable in a special way; see @ref{Choosing
6578 the Shell}.
6579
6580 @node Target-specific, Pattern-specific, Environment, Using Variables
6581 @section Target-specific Variable Values
6582 @cindex target-specific variables
6583 @cindex variables, target-specific
6584
6585 Variable values in @code{make} are usually global; that is, they are the
6586 same regardless of where they are evaluated (unless they're reset, of
6587 course).  Exceptions to that are variables defined with the @code{let}
6588 function (@pxref{Let Function}) or the @code{foreach} function
6589 (@pxref{Foreach Function}, and automatic variables
6590 (@pxref{Automatic Variables}).
6591
6592 Another exception are @dfn{target-specific variable values}.  This
6593 feature allows you to define different values for the same variable,
6594 based on the target that @code{make} is currently building.  As with
6595 automatic variables, these values are only available within the context
6596 of a target's recipe (and in other target-specific assignments).
6597
6598 Set a target-specific variable value like this:
6599
6600 @example
6601 @var{target} @dots{} : @var{variable-assignment}
6602 @end example
6603
6604 Target-specific variable assignments can be prefixed with any or all of the
6605 special keywords @code{export}, @code{unexport}, @code{override}, or
6606 @code{private}; these apply their normal behavior to this instance of the
6607 variable only.
6608
6609 Multiple @var{target} values create a target-specific variable value for
6610 each member of the target list individually.
6611
6612 The @var{variable-assignment} can be any valid form of assignment; recursive
6613 (@samp{=}), simple (@samp{:=} or @samp{::=}), immediate (@samp{::=}),
6614 appending (@samp{+=}), or conditional (@samp{?=}).  All variables that appear
6615 within the @var{variable-assignment} are evaluated within the context of the
6616 target: thus, any previously-defined target-specific variable values will be
6617 in effect.  Note that this variable is actually distinct from any ``global''
6618 value: the two variables do not have to have the same flavor (recursive vs.@:
6619 simple).
6620
6621 Target-specific variables have the same priority as any other makefile
6622 variable.  Variables provided on the command line (and in the
6623 environment if the @samp{-e} option is in force) will take precedence.
6624 Specifying the @code{override} directive will allow the target-specific
6625 variable value to be preferred.
6626
6627 There is one more special feature of target-specific variables: when
6628 you define a target-specific variable that variable value is also in
6629 effect for all prerequisites of this target, and all their
6630 prerequisites, etc.@: (unless those prerequisites override that variable
6631 with their own target-specific variable value).  So, for example, a
6632 statement like this:
6633
6634 @example
6635 prog : CFLAGS = -g
6636 prog : prog.o foo.o bar.o
6637 @end example
6638
6639 @noindent
6640 will set @code{CFLAGS} to @samp{-g} in the recipe for @file{prog}, but
6641 it will also set @code{CFLAGS} to @samp{-g} in the recipes that create
6642 @file{prog.o}, @file{foo.o}, and @file{bar.o}, and any recipes which
6643 create their prerequisites.
6644
6645 Be aware that a given prerequisite will only be built once per
6646 invocation of make, at most.  If the same file is a prerequisite of
6647 multiple targets, and each of those targets has a different value for
6648 the same target-specific variable, then the first target to be built
6649 will cause that prerequisite to be built and the prerequisite will
6650 inherit the target-specific value from the first target.  It will
6651 ignore the target-specific values from any other targets.
6652
6653 @node Pattern-specific, Suppressing Inheritance, Target-specific, Using Variables
6654 @section Pattern-specific Variable Values
6655 @cindex pattern-specific variables
6656 @cindex variables, pattern-specific
6657
6658 In addition to target-specific variable values
6659 (@pxref{Target-specific, ,Target-specific Variable Values}), GNU
6660 @code{make} supports pattern-specific variable values.  In this form,
6661 the variable is defined for any target that matches the pattern
6662 specified.
6663
6664 Set a pattern-specific variable value like this:
6665
6666 @example
6667 @var{pattern} @dots{} : @var{variable-assignment}
6668 @end example
6669 where @var{pattern} is a %-pattern.  As with target-specific variable
6670 values, multiple @var{pattern} values create a pattern-specific variable
6671 value for each pattern individually.  The @var{variable-assignment} can
6672 be any valid form of assignment.  Any command line variable setting will
6673 take precedence, unless @code{override} is specified.
6674
6675 For example:
6676
6677 @example
6678 %.o : CFLAGS = -O
6679 @end example
6680
6681 @noindent
6682 will assign @code{CFLAGS} the value of @samp{-O} for all targets
6683 matching the pattern @code{%.o}.
6684
6685 If a target matches more than one pattern, the matching pattern-specific
6686 variables with longer stems are interpreted first. This results in more
6687 specific variables taking precedence over the more generic ones, for
6688 example:
6689
6690 @example
6691 %.o: %.c
6692         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
6693
6694 lib/%.o: CFLAGS := -fPIC -g
6695 %.o: CFLAGS := -g
6696
6697 all: foo.o lib/bar.o
6698 @end example
6699
6700 In this example the first definition of the @code{CFLAGS} variable
6701 will be used to update @file{lib/bar.o} even though the second one
6702 also applies to this target. Pattern-specific variables which result
6703 in the same stem length are considered in the order in which they
6704 were defined in the makefile.
6705
6706 Pattern-specific variables are searched after any target-specific
6707 variables defined explicitly for that target, and before target-specific
6708 variables defined for the parent target.
6709
6710 @node Suppressing Inheritance, Special Variables, Pattern-specific, Using Variables
6711 @section Suppressing Inheritance
6712 @findex private
6713 @cindex suppressing inheritance
6714 @cindex inheritance, suppressing
6715
6716 As described in previous sections, @code{make} variables are inherited
6717 by prerequisites.  This capability allows you to modify the behavior
6718 of a prerequisite based on which targets caused it to be rebuilt.  For
6719 example, you might set a target-specific variable on a @code{debug}
6720 target, then running @samp{make debug} will cause that variable to be
6721 inherited by all prerequisites of @code{debug}, while just running
6722 @samp{make all} (for example) would not have that assignment.
6723
6724 Sometimes, however, you may not want a variable to be inherited.  For
6725 these situations, @code{make} provides the @code{private} modifier.
6726 Although this modifier can be used with any variable assignment, it
6727 makes the most sense with target- and pattern-specific variables.  Any
6728 variable marked @code{private} will be visible to its local target but
6729 will not be inherited by prerequisites of that target.  A global
6730 variable marked @code{private} will be visible in the global scope but
6731 will not be inherited by any target, and hence will not be visible
6732 in any recipe.
6733
6734 As an example, consider this makefile:
6735 @example
6736 EXTRA_CFLAGS =
6737
6738 prog: private EXTRA_CFLAGS = -L/usr/local/lib
6739 prog: a.o b.o
6740 @end example
6741
6742 Due to the @code{private} modifier, @code{a.o} and @code{b.o} will not
6743 inherit the @code{EXTRA_CFLAGS} variable assignment from the
6744 @code{prog} target.
6745
6746 @node Special Variables,  , Suppressing Inheritance, Using Variables
6747 @comment  node-name,  next,  previous,  up
6748 @section Other Special Variables
6749 @cindex makefiles, and special variables
6750 @cindex special variables
6751
6752 GNU @code{make} supports some variables that have special properties.
6753
6754 @table @code
6755
6756 @vindex MAKEFILE_LIST @r{(list of parsed makefiles)}
6757 @cindex makefiles, and @code{MAKEFILE_LIST} variable
6758 @cindex including (@code{MAKEFILE_LIST} variable)
6759 @item MAKEFILE_LIST
6760 Contains the name of each makefile that is parsed by @code{make}, in
6761 the order in which it was parsed.  The name is appended just
6762 before @code{make} begins to parse the makefile.  Thus, if the first
6763 thing a makefile does is examine the last word in this variable, it
6764 will be the name of the current makefile.  Once the current makefile
6765 has used @code{include}, however, the last word will be the
6766 just-included makefile.
6767
6768 If a makefile named @code{Makefile} has this content:
6769
6770 @example
6771 @group
6772 name1 := $(lastword $(MAKEFILE_LIST))
6773
6774 include inc.mk
6775
6776 name2 := $(lastword $(MAKEFILE_LIST))
6777
6778 all:
6779         @@echo name1 = $(name1)
6780         @@echo name2 = $(name2)
6781 @end group
6782 @end example
6783
6784 @noindent
6785 then you would expect to see this output:
6786
6787 @example
6788 @group
6789 name1 = Makefile
6790 name2 = inc.mk
6791 @end group
6792 @end example
6793
6794 @vindex .DEFAULT_GOAL @r{(define default goal)}
6795 @item .DEFAULT_GOAL
6796 Sets the default goal to be used if no targets were specified on the
6797 command line (@pxref{Goals, , Arguments to Specify the Goals}).  The
6798 @code{.DEFAULT_GOAL} variable allows you to discover the current
6799 default goal, restart the default goal selection algorithm by clearing
6800 its value, or to explicitly set the default goal.  The following
6801 example illustrates these cases:
6802
6803 @example
6804 @group
6805 # Query the default goal.
6806 ifeq ($(.DEFAULT_GOAL),)
6807   $(warning no default goal is set)
6808 endif
6809
6810 .PHONY: foo
6811 foo: ; @@echo $@@
6812
6813 $(warning default goal is $(.DEFAULT_GOAL))
6814
6815 # Reset the default goal.
6816 .DEFAULT_GOAL :=
6817
6818 .PHONY: bar
6819 bar: ; @@echo $@@
6820
6821 $(warning default goal is $(.DEFAULT_GOAL))
6822
6823 # Set our own.
6824 .DEFAULT_GOAL := foo
6825 @end group
6826 @end example
6827
6828 This makefile prints:
6829
6830 @example
6831 @group
6832 no default goal is set
6833 default goal is foo
6834 default goal is bar
6835 foo
6836 @end group
6837 @end example
6838
6839 Note that assigning more than one target name to @code{.DEFAULT_GOAL} is
6840 invalid and will result in an error.
6841
6842 @vindex MAKE_RESTARTS @r{(number of times @code{make} has restarted)}
6843 @item MAKE_RESTARTS
6844 This variable is set only if this instance of @code{make} has
6845 restarted (@pxref{Remaking Makefiles, , How Makefiles Are Remade}): it
6846 will contain the number of times this instance has restarted.  Note
6847 this is not the same as recursion (counted by the @code{MAKELEVEL}
6848 variable).  You should not set, modify, or export this variable.
6849
6850 @vindex MAKE_TERMOUT @r{(whether stdout is a terminal)}
6851 @vindex MAKE_TERMERR @r{(whether stderr is a terminal)}
6852 @item MAKE_TERMOUT
6853 @itemx MAKE_TERMERR
6854 When @code{make} starts it will check whether stdout and stderr will
6855 show their output on a terminal.  If so, it will set
6856 @code{MAKE_TERMOUT} and @code{MAKE_TERMERR}, respectively, to the name
6857 of the terminal device (or @code{true} if this cannot be determined).
6858 If set these variables will be marked for export.  These variables
6859 will not be changed by @code{make} and they will not be modified if
6860 already set.
6861
6862 These values can be used (particularly in combination with output
6863 synchronization (@pxref{Parallel Output, ,Output During Parallel
6864 Execution}) to determine whether @code{make} itself is writing to a
6865 terminal; they can be tested to decide whether to force recipe
6866 commands to generate colorized output for example.
6867
6868 If you invoke a sub-@code{make} and redirect its stdout or stderr it
6869 is your responsibility to reset or unexport these variables as well,
6870 if your makefiles rely on them.
6871
6872 @vindex .RECIPEPREFIX @r{(change the recipe prefix character)}
6873 @item .RECIPEPREFIX
6874 The first character of the value of this variable is used as the
6875 character make assumes is introducing a recipe line.  If the variable
6876 is empty (as it is by default) that character is the standard tab
6877 character.  For example, this is a valid makefile:
6878
6879 @example
6880 @group
6881 .RECIPEPREFIX = >
6882 all:
6883 > @@echo Hello, world
6884 @end group
6885 @end example
6886
6887 The value of @code{.RECIPEPREFIX} can be changed multiple times; once set
6888 it stays in effect for all rules parsed until it is modified.
6889
6890 @vindex .VARIABLES @r{(list of variables)}
6891 @item .VARIABLES
6892 Expands to a list of the @emph{names} of all global variables defined
6893 so far.  This includes variables which have empty values, as well as
6894 built-in variables (@pxref{Implicit Variables, , Variables Used by
6895 Implicit Rules}), but does not include any variables which are only
6896 defined in a target-specific context.  Note that any value you assign
6897 to this variable will be ignored; it will always return its special
6898 value.
6899
6900 @c @vindex .TARGETS @r{(list of targets)}
6901 @c @item .TARGETS
6902 @c The second special variable is @code{.TARGETS}.  When expanded, the
6903 @c value consists of a list of all targets defined in all makefiles read
6904 @c up until that point.  Note it's not enough for a file to be simply
6905 @c mentioned in the makefile to be listed in this variable, even if it
6906 @c would match an implicit rule and become an ``implicit target''.  The
6907 @c file must appear as a target, on the left-hand side of a ``:'', to be
6908 @c considered a target for the purposes of this variable.
6909
6910 @vindex .FEATURES @r{(list of supported features)}
6911 @item .FEATURES
6912 Expands to a list of special features supported by this version of
6913 @code{make}.  Possible values include, but are not limited to:
6914
6915 @table @samp
6916
6917 @item archives
6918 Supports @code{ar} (archive) files using special file name syntax.
6919 @xref{Archives, ,Using @code{make} to Update Archive Files}.
6920
6921 @item check-symlink
6922 Supports the @code{-L} (@code{--check-symlink-times}) flag.
6923 @xref{Options Summary, ,Summary of Options}.
6924
6925 @item else-if
6926 Supports ``else if'' non-nested conditionals.  @xref{Conditional
6927 Syntax, ,Syntax of Conditionals}.
6928
6929 @item extra-prereqs
6930 Supports the @code{.EXTRA_PREREQS} special target.
6931
6932 @item grouped-target
6933 Supports grouped target syntax for explicit rules.  @xref{Multiple Targets,
6934 ,Multiple Targets in a Rule}.
6935
6936 @item guile
6937 Has GNU Guile available as an embedded extension language.
6938 @xref{Guile Integration, ,GNU Guile Integration}.
6939
6940 @item jobserver
6941 Supports ``job server'' enhanced parallel builds.  @xref{Parallel,
6942 ,Parallel Execution}.
6943
6944 @item jobserver-fifo
6945 Supports ``job server'' enhanced parallel builds using named pipes.
6946 @xref{Integrating make, ,Integrating GNU @code{make}}.
6947
6948 @item load
6949 Supports dynamically loadable objects for creating custom extensions.
6950 @xref{Loading Objects, ,Loading Dynamic Objects}.
6951
6952 @item notintermediate
6953 Supports the @code{.NOTINTERMEDIATE} special target.
6954 @xref{Integrating make, ,Integrating GNU @code{make}}.
6955
6956 @item oneshell
6957 Supports the @code{.ONESHELL} special target.  @xref{One Shell, ,Using
6958 One Shell}.
6959
6960 @item order-only
6961 Supports order-only prerequisites.  @xref{Prerequisite Types, ,Types
6962 of Prerequisites}.
6963
6964 @item output-sync
6965 Supports the @code{--output-sync} command line option.  @xref{Options Summary,
6966 ,Summary of Options}.
6967
6968 @item second-expansion
6969 Supports secondary expansion of prerequisite lists.
6970
6971 @item shell-export
6972 Supports exporting @code{make} variables to @code{shell} functions.
6973
6974 @item shortest-stem
6975 Uses the ``shortest stem'' method of choosing which pattern, of
6976 multiple applicable options, will be used.  @xref{Pattern Match, ,How
6977 Patterns Match}.
6978
6979 @item target-specific
6980 Supports target-specific and pattern-specific variable assignments.
6981 @xref{Target-specific, ,Target-specific Variable Values}.
6982
6983 @item undefine
6984 Supports the @code{undefine} directive.  @xref{Undefine Directive}.
6985 @end table
6986
6987 @vindex .INCLUDE_DIRS @r{(list of include directories)}
6988 @item .INCLUDE_DIRS
6989 Expands to a list of directories that @code{make} searches for
6990 included makefiles (@pxref{Include, , Including Other Makefiles}).
6991 Note that modifying this variable's value does not change the list of
6992 directories which are searched.
6993
6994 @vindex .EXTRA_PREREQS @r{(prerequisites not added to automatic variables)}
6995 @item .EXTRA_PREREQS
6996 Each word in this variable is a new prerequisite which is added to
6997 targets for which it is set.  These prerequisites differ from normal
6998 prerequisites in that they do not appear in any of the automatic
6999 variables (@pxref{Automatic Variables}).  This allows prerequisites to
7000 be defined which do not impact the recipe.
7001
7002 Consider a rule to link a program:
7003
7004 @example
7005 myprog: myprog.o file1.o file2.o
7006        $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ $^ $(LDLIBS)
7007 @end example
7008
7009 Now suppose you want to enhance this makefile to ensure that updates
7010 to the compiler cause the program to be re-linked.  You can add the
7011 compiler as a prerequisite, but you must ensure that it's not passed
7012 as an argument to link command.  You'll need something like this:
7013
7014 @example
7015 myprog: myprog.o file1.o file2.o $(CC)
7016        $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ \
7017            $(filter-out $(CC),$^) $(LDLIBS)
7018 @end example
7019
7020 Then consider having multiple extra prerequisites: they would all have
7021 to be filtered out.  Using @code{.EXTRA_PREREQS} and target-specific
7022 variables provides a simpler solution:
7023
7024 @example
7025 myprog: myprog.o file1.o file2.o
7026        $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ $^ $(LDLIBS)
7027 myprog: .EXTRA_PREREQS = $(CC)
7028 @end example
7029
7030 This feature can also be useful if you want to add prerequisites to a
7031 makefile you cannot easily modify: you can create a new file such as
7032 @file{extra.mk}:
7033
7034 @example
7035 myprog: .EXTRA_PREREQS = $(CC)
7036 @end example
7037
7038 then invoke @code{make -f extra.mk -f Makefile}.
7039
7040 Setting @code{.EXTRA_PREREQS} globally will cause those prerequisites
7041 to be added to all targets (which did not themselves override it with
7042 a target-specific value).  Note @code{make} is smart enough not to add
7043 a prerequisite listed in @code{.EXTRA_PREREQS} as a prerequisite to
7044 itself.
7045
7046 @end table
7047
7048 @node Conditionals, Functions, Using Variables, Top
7049 @chapter Conditional Parts of Makefiles
7050
7051 @cindex conditionals
7052 A @dfn{conditional} directive causes part of a makefile to be obeyed
7053 or ignored depending on the values of variables.  Conditionals can
7054 compare the value of one variable to another, or the value of a
7055 variable to a constant string.  Conditionals control what @code{make}
7056 actually ``sees'' in the makefile, so they @emph{cannot} be used to
7057 control recipes at the time of execution.
7058
7059 @menu
7060 * Conditional Example::         Example of a conditional
7061 * Conditional Syntax::          The syntax of conditionals.
7062 * Testing Flags::               Conditionals that test flags.
7063 @end menu
7064
7065 @node Conditional Example, Conditional Syntax, Conditionals, Conditionals
7066 @section Example of a Conditional
7067
7068 The following example of a conditional tells @code{make} to use one
7069 set of libraries if the @code{CC} variable is @samp{gcc}, and a
7070 different set of libraries otherwise.  It works by controlling which
7071 of two recipe lines will be used for the rule.  The result is that
7072 @samp{CC=gcc} as an argument to @code{make} changes not only which
7073 compiler is used but also which libraries are linked.
7074
7075 @example
7076 libs_for_gcc = -lgnu
7077 normal_libs =
7078
7079 foo: $(objects)
7080 ifeq ($(CC),gcc)
7081         $(CC) -o foo $(objects) $(libs_for_gcc)
7082 else
7083         $(CC) -o foo $(objects) $(normal_libs)
7084 endif
7085 @end example
7086
7087 This conditional uses three directives: one @code{ifeq}, one @code{else}
7088 and one @code{endif}.
7089
7090 The @code{ifeq} directive begins the conditional, and specifies the
7091 condition.  It contains two arguments, separated by a comma and surrounded
7092 by parentheses.  Variable substitution is performed on both arguments and
7093 then they are compared.  The lines of the makefile following the
7094 @code{ifeq} are obeyed if the two arguments match; otherwise they are
7095 ignored.
7096
7097 The @code{else} directive causes the following lines to be obeyed if the
7098 previous conditional failed.  In the example above, this means that the
7099 second alternative linking command is used whenever the first alternative
7100 is not used.  It is optional to have an @code{else} in a conditional.
7101
7102 The @code{endif} directive ends the conditional.  Every conditional must
7103 end with an @code{endif}.  Unconditional makefile text follows.
7104
7105 As this example illustrates, conditionals work at the textual level:
7106 the lines of the conditional are treated as part of the makefile, or
7107 ignored, according to the condition.  This is why the larger syntactic
7108 units of the makefile, such as rules, may cross the beginning or the
7109 end of the conditional.
7110
7111 When the variable @code{CC} has the value @samp{gcc}, the above example has
7112 this effect:
7113
7114 @example
7115 foo: $(objects)
7116         $(CC) -o foo $(objects) $(libs_for_gcc)
7117 @end example
7118
7119 @noindent
7120 When the variable @code{CC} has any other value, the effect is this:
7121
7122 @example
7123 foo: $(objects)
7124         $(CC) -o foo $(objects) $(normal_libs)
7125 @end example
7126
7127 Equivalent results can be obtained in another way by conditionalizing a
7128 variable assignment and then using the variable unconditionally:
7129
7130 @example
7131 libs_for_gcc = -lgnu
7132 normal_libs =
7133
7134 ifeq ($(CC),gcc)
7135   libs=$(libs_for_gcc)
7136 else
7137   libs=$(normal_libs)
7138 endif
7139
7140 foo: $(objects)
7141         $(CC) -o foo $(objects) $(libs)
7142 @end example
7143
7144 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
7145 @section Syntax of Conditionals
7146 @findex ifdef
7147 @findex ifeq
7148 @findex ifndef
7149 @findex ifneq
7150 @findex else
7151 @findex endif
7152
7153 The syntax of a simple conditional with no @code{else} is as follows:
7154
7155 @example
7156 @var{conditional-directive}
7157 @var{text-if-true}
7158 endif
7159 @end example
7160
7161 @noindent
7162 The @var{text-if-true} may be any lines of text, to be considered as part
7163 of the makefile if the condition is true.  If the condition is false, no
7164 text is used instead.
7165
7166 The syntax of a complex conditional is as follows:
7167
7168 @example
7169 @var{conditional-directive}
7170 @var{text-if-true}
7171 else
7172 @var{text-if-false}
7173 endif
7174 @end example
7175
7176 or:
7177
7178 @example
7179 @var{conditional-directive-one}
7180 @var{text-if-one-is-true}
7181 else @var{conditional-directive-two}
7182 @var{text-if-two-is-true}
7183 else
7184 @var{text-if-one-and-two-are-false}
7185 endif
7186 @end example
7187
7188 @noindent
7189 There can be as many ``@code{else} @var{conditional-directive}''
7190 clauses as necessary.  Once a given condition is true,
7191 @var{text-if-true} is used and no other clause is used; if no
7192 condition is true then @var{text-if-false} is used.  The
7193 @var{text-if-true} and @var{text-if-false} can be any number of lines
7194 of text.
7195
7196 The syntax of the @var{conditional-directive} is the same whether the
7197 conditional is simple or complex; after an @code{else} or not.  There
7198 are four different directives that test different conditions.  Here is
7199 a table of them:
7200
7201 @table @code
7202 @item ifeq (@var{arg1}, @var{arg2})
7203 @itemx ifeq '@var{arg1}' '@var{arg2}'
7204 @itemx ifeq "@var{arg1}" "@var{arg2}"
7205 @itemx ifeq "@var{arg1}" '@var{arg2}'
7206 @itemx ifeq '@var{arg1}' "@var{arg2}"
7207 Expand all variable references in @var{arg1} and @var{arg2} and
7208 compare them.  If they are identical, the @var{text-if-true} is
7209 effective; otherwise, the @var{text-if-false}, if any, is effective.
7210
7211 Often you want to test if a variable has a non-empty value.  When the
7212 value results from complex expansions of variables and functions,
7213 expansions you would consider empty may actually contain whitespace
7214 characters and thus are not seen as empty.  However, you can use the
7215 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
7216 whitespace as a non-empty value.  For example:
7217
7218 @example
7219 @group
7220 ifeq ($(strip $(foo)),)
7221 @var{text-if-empty}
7222 endif
7223 @end group
7224 @end example
7225
7226 @noindent
7227 will evaluate @var{text-if-empty} even if the expansion of
7228 @code{$(foo)} contains whitespace characters.
7229
7230 @item ifneq (@var{arg1}, @var{arg2})
7231 @itemx ifneq '@var{arg1}' '@var{arg2}'
7232 @itemx ifneq "@var{arg1}" "@var{arg2}"
7233 @itemx ifneq "@var{arg1}" '@var{arg2}'
7234 @itemx ifneq '@var{arg1}' "@var{arg2}"
7235 Expand all variable references in @var{arg1} and @var{arg2} and
7236 compare them.  If they are different, the @var{text-if-true} is
7237 effective; otherwise, the @var{text-if-false}, if any, is effective.
7238
7239 @item ifdef @var{variable-name}
7240 The @code{ifdef} form takes the @emph{name} of a variable as its
7241 argument, not a reference to a variable.  If the value of that
7242 variable has a non-empty value, the @var{text-if-true} is effective;
7243 otherwise, the @var{text-if-false}, if any, is effective.  Variables
7244 that have never been defined have an empty value.  The text
7245 @var{variable-name} is expanded, so it could be a variable or function
7246 that expands to the name of a variable.  For example:
7247
7248 @example
7249 bar = true
7250 foo = bar
7251 ifdef $(foo)
7252 frobozz = yes
7253 endif
7254 @end example
7255
7256 The variable reference @code{$(foo)} is expanded, yielding @code{bar},
7257 which is considered to be the name of a variable.  The variable
7258 @code{bar} is not expanded, but its value is examined to determine if
7259 it is non-empty.
7260
7261 Note that @code{ifdef} only tests whether a variable has a value.  It
7262 does not expand the variable to see if that value is nonempty.
7263 Consequently, tests using @code{ifdef} return true for all definitions
7264 except those like @code{foo =}.  To test for an empty value, use
7265 @w{@code{ifeq ($(foo),)}}.  For example,
7266
7267 @example
7268 bar =
7269 foo = $(bar)
7270 ifdef foo
7271 frobozz = yes
7272 else
7273 frobozz = no
7274 endif
7275 @end example
7276
7277 @noindent
7278 sets @samp{frobozz} to @samp{yes}, while:
7279
7280 @example
7281 foo =
7282 ifdef foo
7283 frobozz = yes
7284 else
7285 frobozz = no
7286 endif
7287 @end example
7288
7289 @noindent
7290 sets @samp{frobozz} to @samp{no}.
7291
7292 @item ifndef @var{variable-name}
7293 If the variable @var{variable-name} has an empty value, the
7294 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
7295 if any, is effective.  The rules for expansion and testing of
7296 @var{variable-name} are identical to the @code{ifdef} directive.
7297 @end table
7298
7299 Extra spaces are allowed and ignored at the beginning of the
7300 conditional directive line, but a tab is not allowed.  (If the line
7301 begins with a tab, it will be considered part of a recipe for a rule.)
7302 Aside from this, extra spaces or tabs may be inserted with no effect
7303 anywhere except within the directive name or within an argument.  A
7304 comment starting with @samp{#} may appear at the end of the line.
7305
7306 The other two directives that play a part in a conditional are @code{else}
7307 and @code{endif}.  Each of these directives is written as one word, with no
7308 arguments.  Extra spaces are allowed and ignored at the beginning of the
7309 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
7310 appear at the end of the line.
7311
7312 Conditionals affect which lines of the makefile @code{make} uses.  If
7313 the condition is true, @code{make} reads the lines of the
7314 @var{text-if-true} as part of the makefile; if the condition is false,
7315 @code{make} ignores those lines completely.  It follows that syntactic
7316 units of the makefile, such as rules, may safely be split across the
7317 beginning or the end of the conditional.
7318
7319 @code{make} evaluates conditionals when it reads a makefile.
7320 Consequently, you cannot use automatic variables in the tests of
7321 conditionals because they are not defined until recipes are run
7322 (@pxref{Automatic Variables}).
7323
7324 To prevent intolerable confusion, it is not permitted to start a
7325 conditional in one makefile and end it in another.  However, you may
7326 write an @code{include} directive within a conditional, provided you do
7327 not attempt to terminate the conditional inside the included file.
7328
7329 @node Testing Flags,  , Conditional Syntax, Conditionals
7330 @section Conditionals that Test Flags
7331
7332 You can write a conditional that tests @code{make} command flags such as
7333 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
7334 @code{findstring} function
7335 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
7336 This is useful when @code{touch} is not enough to make a file appear up
7337 to date.
7338
7339 Recall that @code{MAKEFLAGS} will put all single-letter options (such as
7340 @samp{-t}) into the first word, and that word will be empty if no
7341 single-letter options were given.  To work with this, it's helpful to add a
7342 value at the start to ensure there's a word: for example
7343 @samp{-$(MAKEFLAGS)}.
7344
7345 The @code{findstring} function determines whether one string appears as a
7346 substring of another.  If you want to test for the @samp{-t} flag, use
7347 @samp{t} as the first string and the first word of @code{MAKEFLAGS} as the
7348 other.
7349
7350 For example, here is how to arrange to use @samp{ranlib -t} to finish
7351 marking an archive file up to date:
7352
7353 @example
7354 archive.a: @dots{}
7355 ifneq (,$(findstring t,$(word 1,-$(MAKEFLAGS))))
7356         +touch archive.a
7357         +ranlib -t archive.a
7358 else
7359         ranlib archive.a
7360 endif
7361 @end example
7362
7363 @noindent
7364 The @samp{+} prefix marks those recipe lines as ``recursive'' so that
7365 they will be executed despite use of the @samp{-t} flag.
7366 @xref{Recursion, ,Recursive Use of @code{make}}.
7367
7368 @node Functions, Running, Conditionals, Top
7369 @chapter Functions for Transforming Text
7370 @cindex functions
7371
7372 @dfn{Functions} allow you to do text processing in the makefile to
7373 compute the files to operate on or the commands to use in recipes.
7374 You use a function in a @dfn{function call}, where you give the name
7375 of the function and some text (the @dfn{arguments}) for the function
7376 to operate on.  The result of the function's processing is substituted
7377 into the makefile at the point of the call, just as a variable might
7378 be substituted.
7379
7380 @menu
7381 * Syntax of Functions::         How to write a function call.
7382 * Text Functions::              General-purpose text manipulation functions.
7383 * File Name Functions::         Functions for manipulating file names.
7384 * Conditional Functions::       Functions that implement conditions.
7385 * Let Function::                Local variables.
7386 * Foreach Function::            Repeat some text with controlled variation.
7387 * File Function::               Write text to a file.
7388 * Call Function::               Expand a user-defined function.
7389 * Value Function::              Return the un-expanded value of a variable.
7390 * Eval Function::               Evaluate the arguments as makefile syntax.
7391 * Origin Function::             Find where a variable got its value.
7392 * Flavor Function::             Find out the flavor of a variable.
7393 * Make Control Functions::      Functions that control how make runs.
7394 * Shell Function::              Substitute the output of a shell command.
7395 * Guile Function::              Use GNU Guile embedded scripting language.
7396 @end menu
7397
7398 @node Syntax of Functions, Text Functions, Functions, Functions
7399 @section Function Call Syntax
7400 @cindex @code{$}, in function call
7401 @cindex dollar sign (@code{$}), in function call
7402 @cindex arguments of functions
7403 @cindex functions, syntax of
7404
7405 A function call resembles a variable reference.  It can appear
7406 anywhere a variable reference can appear, and it is expanded using the
7407 same rules as variable references.  A function call looks like this:
7408
7409 @example
7410 $(@var{function} @var{arguments})
7411 @end example
7412
7413 @noindent
7414 or like this:
7415
7416 @example
7417 $@{@var{function} @var{arguments}@}
7418 @end example
7419
7420 Here @var{function} is a function name; one of a short list of names
7421 that are part of @code{make}.  You can also essentially create your own
7422 functions by using the @code{call} built-in function.
7423
7424 The @var{arguments} are the arguments of the function.  They are separated
7425 from the function name by one or more spaces or tabs, and if there is more
7426 than one argument, then they are separated by commas.  Such whitespace and
7427 commas are not part of an argument's value.  The delimiters which you use to
7428 surround the function call, whether parentheses or braces, can appear in an
7429 argument only in matching pairs; the other kind of delimiters may appear
7430 singly.  If the arguments themselves contain other function calls or variable
7431 references, it is wisest to use the same kind of delimiters for all the
7432 references; write @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst
7433 a,b,$@{x@})}}.  This is because it is clearer, and because only one type of
7434 delimiter is matched to find the end of the reference.
7435
7436 Each argument is expanded before the function is invoked, unless otherwise
7437 noted below.  The substitution is done in the order in which the arguments
7438 appear.
7439
7440 @subsubheading Special Characters
7441 @cindex special characters in function arguments
7442 @cindex function arguments, special characters in
7443
7444 When using characters that are special to @code{make} as function arguments,
7445 you may need to hide them.  GNU @code{make} doesn't support escaping
7446 characters with backslashes or other escape sequences; however, because
7447 arguments are split before they are expanded you can hide them by putting them
7448 into variables.
7449
7450 Characters you may need to hide include:
7451
7452 @itemize @bullet
7453 @item
7454 Commas
7455 @item
7456 Initial whitespace in the first argument
7457 @item
7458 Unmatched open parenthesis or brace
7459 @item
7460 An open parenthesis or brace if you don't want it to start a matched pair
7461 @end itemize
7462
7463 For example, you can define variables @code{comma} and @code{space} whose
7464 values are isolated comma and space characters, then substitute these
7465 variables where such characters are wanted, like this:
7466
7467 @example
7468 @group
7469 comma:= ,
7470 empty:=
7471 space:= $(empty) $(empty)
7472 foo:= a b c
7473 bar:= $(subst $(space),$(comma),$(foo))
7474 # @r{bar is now `a,b,c'.}
7475 @end group
7476 @end example
7477
7478 @noindent
7479 Here the @code{subst} function replaces each space with a comma, through
7480 the value of @code{foo}, and substitutes the result.
7481
7482 @node Text Functions, File Name Functions, Syntax of Functions, Functions
7483 @section Functions for String Substitution and Analysis
7484 @cindex functions, for text
7485
7486 Here are some functions that operate on strings:
7487
7488 @table @code
7489 @item $(subst @var{from},@var{to},@var{text})
7490 @findex subst
7491 Performs a textual replacement on the text @var{text}: each occurrence
7492 of @var{from} is replaced by @var{to}.  The result is substituted for
7493 the function call.  For example,
7494
7495 @example
7496 $(subst ee,EE,feet on the street)
7497 @end example
7498
7499 produces the value @samp{fEEt on the strEEt}.
7500
7501 @item $(patsubst @var{pattern},@var{replacement},@var{text})
7502 @findex patsubst
7503 Finds whitespace-separated words in @var{text} that match
7504 @var{pattern} and replaces them with @var{replacement}.  Here
7505 @var{pattern} may contain a @samp{%} which acts as a wildcard,
7506 matching any number of any characters within a word.  If
7507 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
7508 by the text that matched the @samp{%} in @var{pattern}.  Words that do
7509 not match the pattern are kept without change in the output.  Only the
7510 first @samp{%} in the @var{pattern} and @var{replacement} is treated
7511 this way; any subsequent @samp{%} is unchanged.
7512
7513 @cindex @code{%}, quoting in @code{patsubst}
7514 @cindex @code{%}, quoting with @code{\} (backslash)
7515 @cindex @code{\} (backslash), to quote @code{%}
7516 @cindex backslash (@code{\}), to quote @code{%}
7517 @cindex quoting @code{%}, in @code{patsubst}
7518 @samp{%} characters in @code{patsubst} function invocations can be
7519 quoted with preceding backslashes (@samp{\}).  Backslashes that would
7520 otherwise quote @samp{%} characters can be quoted with more backslashes.
7521 Backslashes that quote @samp{%} characters or other backslashes are
7522 removed from the pattern before it is compared file names or has a stem
7523 substituted into it.  Backslashes that are not in danger of quoting
7524 @samp{%} characters go unmolested.  For example, the pattern
7525 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
7526 operative @samp{%} character, and @samp{pattern\\} following it.  The
7527 final two backslashes are left alone because they cannot affect any
7528 @samp{%} character.
7529
7530 Whitespace between words is folded into single space characters;
7531 leading and trailing whitespace is discarded.
7532
7533 For example,
7534
7535 @example
7536 $(patsubst %.c,%.o,x.c.c bar.c)
7537 @end example
7538
7539 @noindent
7540 produces the value @samp{x.c.o bar.o}.
7541
7542 Substitution references (@pxref{Substitution Refs, ,Substitution
7543 References}) are a simpler way to get the effect of the @code{patsubst}
7544 function:
7545
7546 @example
7547 $(@var{var}:@var{pattern}=@var{replacement})
7548 @end example
7549
7550 @noindent
7551 is equivalent to
7552
7553 @example
7554 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
7555 @end example
7556
7557 The second shorthand simplifies one of the most common uses of
7558 @code{patsubst}: replacing the suffix at the end of file names.
7559
7560 @example
7561 $(@var{var}:@var{suffix}=@var{replacement})
7562 @end example
7563
7564 @noindent
7565 is equivalent to
7566
7567 @example
7568 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
7569 @end example
7570
7571 @noindent
7572 For example, you might have a list of object files:
7573
7574 @example
7575 objects = foo.o bar.o baz.o
7576 @end example
7577
7578 @noindent
7579 To get the list of corresponding source files, you could simply write:
7580
7581 @example
7582 $(objects:.o=.c)
7583 @end example
7584
7585 @noindent
7586 instead of using the general form:
7587
7588 @example
7589 $(patsubst %.o,%.c,$(objects))
7590 @end example
7591
7592 @item $(strip @var{string})
7593 @cindex stripping whitespace
7594 @cindex whitespace, stripping
7595 @cindex spaces, stripping
7596 @findex strip
7597 Removes leading and trailing whitespace from @var{string} and replaces
7598 each internal sequence of one or more whitespace characters with a
7599 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
7600
7601 The function @code{strip} can be very useful when used in conjunction
7602 with conditionals.  When comparing something with the empty string
7603 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
7604 just whitespace to match the empty string (@pxref{Conditionals}).
7605
7606 Thus, the following may fail to have the desired results:
7607
7608 @example
7609 .PHONY: all
7610 ifneq   "$(needs_made)" ""
7611 all: $(needs_made)
7612 else
7613 all:;@@echo 'Nothing to make!'
7614 endif
7615 @end example
7616
7617 @noindent
7618 Replacing the variable reference @w{@samp{$(needs_made)}} with the
7619 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
7620 directive would make it more robust.
7621
7622 @item $(findstring @var{find},@var{in})
7623 @findex findstring
7624 @cindex searching for strings
7625 @cindex finding strings
7626 @cindex strings, searching for
7627 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
7628 value is @var{find}; otherwise, the value is empty.  You can use this
7629 function in a conditional to test for the presence of a specific
7630 substring in a given string.  Thus, the two examples,
7631
7632 @example
7633 $(findstring a,a b c)
7634 $(findstring a,b c)
7635 @end example
7636
7637 @noindent
7638 produce the values @samp{a} and @samp{} (the empty string),
7639 respectively.  @xref{Testing Flags}, for a practical application of
7640 @code{findstring}.
7641
7642 @need 750
7643 @findex filter
7644 @cindex filtering words
7645 @cindex words, filtering
7646 @item $(filter @var{pattern}@dots{},@var{text})
7647 Returns all whitespace-separated words in @var{text} that @emph{do} match
7648 any of the @var{pattern} words, removing any words that @emph{do not}
7649 match.  The patterns are written using @samp{%}, just like the patterns
7650 used in the @code{patsubst} function above.
7651
7652 The @code{filter} function can be used to separate out different types
7653 of strings (such as file names) in a variable.  For example:
7654
7655 @example
7656 sources := foo.c bar.c baz.s ugh.h
7657 foo: $(sources)
7658         cc $(filter %.c %.s,$(sources)) -o foo
7659 @end example
7660
7661 @noindent
7662 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
7663 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
7664 @file{baz.s} should be specified in the command to the
7665 compiler.
7666
7667 @item $(filter-out @var{pattern}@dots{},@var{text})
7668 @findex filter-out
7669 @cindex filtering out words
7670 @cindex words, filtering out
7671 Returns all whitespace-separated words in @var{text} that @emph{do not}
7672 match any of the @var{pattern} words, removing the words that @emph{do}
7673 match one or more.  This is the exact opposite of the @code{filter}
7674 function.
7675
7676 For example, given:
7677
7678 @example
7679 @group
7680 objects=main1.o foo.o main2.o bar.o
7681 mains=main1.o main2.o
7682 @end group
7683 @end example
7684
7685 @noindent
7686 the following generates a list which contains all the object files not
7687 in @samp{mains}:
7688
7689 @example
7690 $(filter-out $(mains),$(objects))
7691 @end example
7692
7693 @need 1500
7694 @findex sort
7695 @cindex sorting words
7696 @item $(sort @var{list})
7697 Sorts the words of @var{list} in lexical order, removing duplicate
7698 words.  The output is a list of words separated by single spaces.
7699 Thus,
7700
7701 @example
7702 $(sort foo bar lose)
7703 @end example
7704
7705 @noindent
7706 returns the value @samp{bar foo lose}.
7707
7708 @cindex removing duplicate words
7709 @cindex duplicate words, removing
7710 @cindex words, removing duplicates
7711 Incidentally, since @code{sort} removes duplicate words, you can use
7712 it for this purpose even if you don't care about the sort order.
7713
7714 @item $(word @var{n},@var{text})
7715 @findex word
7716 @cindex word, selecting a
7717 @cindex selecting a word
7718 Returns the @var{n}th word of @var{text}.  The legitimate values of
7719 @var{n} start from 1.  If @var{n} is bigger than the number of words
7720 in @var{text}, the value is empty.  For example,
7721
7722 @example
7723 $(word 2, foo bar baz)
7724 @end example
7725
7726 @noindent
7727 returns @samp{bar}.
7728
7729 @item $(wordlist @var{s},@var{e},@var{text})
7730 @findex wordlist
7731 @cindex words, selecting lists of
7732 @cindex selecting word lists
7733 Returns the list of words in @var{text} starting with word @var{s} and
7734 ending with word @var{e} (inclusive).  The legitimate values of @var{s}
7735 start from 1; @var{e} may start from 0.  If @var{s} is bigger than the
7736 number of words in @var{text}, the value is empty.  If @var{e} is
7737 bigger than the number of words in @var{text}, words up to the end of
7738 @var{text} are returned.  If @var{s} is greater than @var{e}, nothing
7739 is returned.  For example,
7740
7741 @example
7742 $(wordlist 2, 3, foo bar baz)
7743 @end example
7744
7745 @noindent
7746 returns @samp{bar baz}.
7747
7748 @item $(words @var{text})
7749 @findex words
7750 @cindex words, finding number
7751 Returns the number of words in @var{text}.  Thus, the last word of @var{text}
7752 is @w{@code{$(word $(words @var{text}),@var{text})}}.
7753
7754 @item $(firstword @var{names}@dots{})
7755 @findex firstword
7756 @cindex words, extracting first
7757 The argument @var{names} is regarded as a series of names, separated
7758 by whitespace.  The value is the first name in the series.  The rest
7759 of the names are ignored.
7760
7761 For example,
7762
7763 @example
7764 $(firstword foo bar)
7765 @end example
7766
7767 @noindent
7768 produces the result @samp{foo}.  Although @code{$(firstword
7769 @var{text})} is the same as @code{$(word 1,@var{text})}, the
7770 @code{firstword} function is retained for its simplicity.
7771
7772
7773 @item $(lastword @var{names}@dots{})
7774 @findex lastword
7775 @cindex words, extracting last
7776 The argument @var{names} is regarded as a series of names, separated
7777 by whitespace.  The value is the last name in the series.
7778
7779 For example,
7780
7781 @example
7782 $(lastword foo bar)
7783 @end example
7784
7785 @noindent
7786 produces the result @samp{bar}.  Although @code{$(lastword
7787 @var{text})} is the same as @code{$(word $(words @var{text}),@var{text})},
7788 the @code{lastword} function was added for its simplicity and better
7789 performance.
7790 @end table
7791
7792
7793 Here is a realistic example of the use of @code{subst} and
7794 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
7795 to specify a list of directories that @code{make} should search for
7796 prerequisite files
7797 (@pxref{General Search, , @code{VPATH} Search Path for All Prerequisites}).
7798 This example shows how to
7799 tell the C compiler to search for header files in the same list of
7800 directories.
7801
7802 The value of @code{VPATH} is a list of directories separated by colons,
7803 such as @samp{src:../headers}.  First, the @code{subst} function is used to
7804 change the colons to spaces:
7805
7806 @example
7807 $(subst :, ,$(VPATH))
7808 @end example
7809
7810 @noindent
7811 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
7812 each directory name into a @samp{-I} flag.  These can be added to the
7813 value of the variable @code{CFLAGS}, which is passed automatically to the C
7814 compiler, like this:
7815
7816 @example
7817 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
7818 @end example
7819
7820 @noindent
7821 The effect is to append the text @samp{-Isrc -I../headers} to the
7822 previously given value of @code{CFLAGS}.  The @code{override} directive is
7823 used so that the new value is assigned even if the previous value of
7824 @code{CFLAGS} was specified with a command argument (@pxref{Override
7825 Directive, , The @code{override} Directive}).
7826
7827 @node File Name Functions, Conditional Functions, Text Functions, Functions
7828 @section Functions for File Names
7829 @cindex functions, for file names
7830 @cindex file name functions
7831
7832 Several of the built-in expansion functions relate specifically to
7833 taking apart file names or lists of file names.
7834
7835 Each of the following functions performs a specific transformation on a
7836 file name.  The argument of the function is regarded as a series of file
7837 names, separated by whitespace.  (Leading and trailing whitespace is
7838 ignored.)  Each file name in the series is transformed in the same way and
7839 the results are concatenated with single spaces between them.
7840
7841 @table @code
7842 @item $(dir @var{names}@dots{})
7843 @findex dir
7844 @cindex directory part
7845 @cindex file name, directory part
7846 Extracts the directory-part of each file name in @var{names}.  The
7847 directory-part of the file name is everything up through (and
7848 including) the last slash in it.  If the file name contains no slash,
7849 the directory part is the string @samp{./}.  For example,
7850
7851 @example
7852 $(dir src/foo.c hacks)
7853 @end example
7854
7855 @noindent
7856 produces the result @samp{src/ ./}.
7857
7858 @item $(notdir @var{names}@dots{})
7859 @findex notdir
7860 @cindex file name, nondirectory part
7861 @cindex nondirectory part
7862 Extracts all but the directory-part of each file name in @var{names}.
7863 If the file name contains no slash, it is left unchanged.  Otherwise,
7864 everything through the last slash is removed from it.
7865
7866 A file name that ends with a slash becomes an empty string.  This is
7867 unfortunate, because it means that the result does not always have the
7868 same number of whitespace-separated file names as the argument had;
7869 but we do not see any other valid alternative.
7870
7871 For example,
7872
7873 @example
7874 $(notdir src/foo.c hacks)
7875 @end example
7876
7877 @noindent
7878 produces the result @samp{foo.c hacks}.
7879
7880 @item $(suffix @var{names}@dots{})
7881 @findex suffix
7882 @cindex suffix, function to find
7883 @cindex file name suffix
7884 Extracts the suffix of each file name in @var{names}.  If the file name
7885 contains a period, the suffix is everything starting with the last
7886 period.  Otherwise, the suffix is the empty string.  This frequently
7887 means that the result will be empty when @var{names} is not, and if
7888 @var{names} contains multiple file names, the result may contain fewer
7889 file names.
7890
7891 For example,
7892
7893 @example
7894 $(suffix src/foo.c src-1.0/bar.c hacks)
7895 @end example
7896
7897 @noindent
7898 produces the result @samp{.c .c}.
7899
7900 @item $(basename @var{names}@dots{})
7901 @findex basename
7902 @cindex basename
7903 @cindex file name, basename of
7904 Extracts all but the suffix of each file name in @var{names}.  If the
7905 file name contains a period, the basename is everything starting up to
7906 (and not including) the last period.  Periods in the directory part are
7907 ignored.  If there is no period, the basename is the entire file name.
7908 For example,
7909
7910 @example
7911 $(basename src/foo.c src-1.0/bar hacks)
7912 @end example
7913
7914 @noindent
7915 produces the result @samp{src/foo src-1.0/bar hacks}.
7916
7917 @c plural convention with dots (be consistent)
7918 @item $(addsuffix @var{suffix},@var{names}@dots{})
7919 @findex addsuffix
7920 @cindex suffix, adding
7921 @cindex file name suffix, adding
7922 The argument @var{names} is regarded as a series of names, separated
7923 by whitespace; @var{suffix} is used as a unit.  The value of
7924 @var{suffix} is appended to the end of each individual name and the
7925 resulting larger names are concatenated with single spaces between
7926 them.  For example,
7927
7928 @example
7929 $(addsuffix .c,foo bar)
7930 @end example
7931
7932 @noindent
7933 produces the result @samp{foo.c bar.c}.
7934
7935 @item $(addprefix @var{prefix},@var{names}@dots{})
7936 @findex addprefix
7937 @cindex prefix, adding
7938 @cindex file name prefix, adding
7939 The argument @var{names} is regarded as a series of names, separated
7940 by whitespace; @var{prefix} is used as a unit.  The value of
7941 @var{prefix} is prepended to the front of each individual name and the
7942 resulting larger names are concatenated with single spaces between
7943 them.  For example,
7944
7945 @example
7946 $(addprefix src/,foo bar)
7947 @end example
7948
7949 @noindent
7950 produces the result @samp{src/foo src/bar}.
7951
7952 @item $(join @var{list1},@var{list2})
7953 @findex join
7954 @cindex joining lists of words
7955 @cindex words, joining lists
7956 Concatenates the two arguments word by word: the two first words (one
7957 from each argument) concatenated form the first word of the result, the
7958 two second words form the second word of the result, and so on.  So the
7959 @var{n}th word of the result comes from the @var{n}th word of each
7960 argument.  If one argument has more words that the other, the extra
7961 words are copied unchanged into the result.
7962
7963 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
7964
7965 Whitespace between the words in the lists is not preserved; it is
7966 replaced with a single space.
7967
7968 This function can merge the results of the @code{dir} and
7969 @code{notdir} functions, to produce the original list of files which
7970 was given to those two functions.
7971
7972 @item $(wildcard @var{pattern})
7973 @findex wildcard
7974 @cindex wildcard, function
7975 The argument @var{pattern} is a file name pattern, typically containing
7976 wildcard characters (as in shell file name patterns).  The result of
7977 @code{wildcard} is a space-separated list of the names of existing files
7978 that match the pattern.
7979 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
7980
7981 @item $(realpath @var{names}@dots{})
7982 @findex realpath
7983 @cindex realpath
7984 @cindex file name, realpath of
7985 For each file name in @var{names} return the canonical absolute name.
7986 A canonical name does not contain any @code{.} or @code{..} components,
7987 nor any repeated path separators (@code{/}) or symlinks.  In case of a
7988 failure the empty string is returned.  Consult the @code{realpath(3)}
7989 documentation for a list of possible failure causes.
7990
7991 @item $(abspath @var{names}@dots{})
7992 @findex abspath
7993 @cindex abspath
7994 @cindex file name, abspath of
7995 For each file name in @var{names} return an absolute name that does
7996 not contain any @code{.} or @code{..} components, nor any repeated path
7997 separators (@code{/}).  Note that, in contrast to @code{realpath}
7998 function, @code{abspath} does not resolve symlinks and does not require
7999 the file names to refer to an existing file or directory.  Use the
8000 @code{wildcard} function to test for existence.
8001 @end table
8002
8003 @node Conditional Functions, Let Function, File Name Functions, Functions
8004 @section Functions for Conditionals
8005 @findex if
8006 @cindex conditional expansion
8007 There are four functions that provide conditional expansion.  A key
8008 aspect of these functions is that not all of the arguments are
8009 expanded initially.  Only those arguments which need to be expanded,
8010 will be expanded.
8011
8012 @table @code
8013 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
8014 @findex if
8015 The @code{if} function provides support for conditional expansion in a
8016 functional context (as opposed to the GNU @code{make} makefile
8017 conditionals such as @code{ifeq} (@pxref{Conditional Syntax, ,Syntax of
8018 Conditionals})).
8019
8020 The first argument, @var{condition}, first has all preceding and
8021 trailing whitespace stripped, then is expanded.  If it expands to any
8022 non-empty string, then the condition is considered to be true.  If it
8023 expands to an empty string, the condition is considered to be false.
8024
8025 If the condition is true then the second argument, @var{then-part}, is
8026 evaluated and this is used as the result of the evaluation of the entire
8027 @code{if} function.
8028
8029 If the condition is false then the third argument, @var{else-part}, is
8030 evaluated and this is the result of the @code{if} function.  If there is
8031 no third argument, the @code{if} function evaluates to nothing (the
8032 empty string).
8033
8034 Note that only one of the @var{then-part} or the @var{else-part} will be
8035 evaluated, never both.  Thus, either can contain side-effects (such as
8036 @code{shell} function calls, etc.)
8037
8038 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
8039 @findex or
8040 The @code{or} function provides a ``short-circuiting'' OR operation.
8041 Each argument is expanded, in order.  If an argument expands to a
8042 non-empty string the processing stops and the result of the expansion
8043 is that string.  If, after all arguments are expanded, all of them are
8044 false (empty), then the result of the expansion is the empty string.
8045
8046 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
8047 @findex and
8048 The @code{and} function provides a ``short-circuiting'' AND operation.
8049 Each argument is expanded, in order.  If an argument expands to an
8050 empty string the processing stops and the result of the expansion is
8051 the empty string.  If all arguments expand to a non-empty string then
8052 the result of the expansion is the expansion of the last argument.
8053
8054 @item $(intcmp @var{lhs},@var{rhs}[,@var{lt-part}[,@var{eq-part}[,@var{gt-part}]]])
8055 @findex intcmp
8056 The @code{intcmp} function provides support for numerical comparison of
8057 integers.  This function has no counterpart among the GNU @code{make} makefile
8058 conditionals.
8059
8060 The left-hand side, @var{lhs}, and right-hand side, @var{rhs}, are expanded
8061 and parsed as integral numbers in base 10.  Expansion of the remaining
8062 arguments is controlled by how the numerical left-hand side compares to the
8063 numerical right-hand side.
8064
8065 If there are no further arguments, then the function expands to empty if the
8066 left-hand side and right-hand side do not compare equal, or to their numerical
8067 value if they do compare equal.
8068
8069 Else if the left-hand side is strictly less than the right-hand side, the
8070 @code{intcmp} function evaluates to the expansion of the third argument,
8071 @var{lt-part}.  If both sides compare equal, then the @code{intcmp} function
8072 evaluates to the expansion of the fourth argument, @var{eq-part}.  If the
8073 left-hand side is strictly greater than the right-hand side, then the
8074 @code{intcmp} function evaluates to the expansion of the fifth argument,
8075 @var{gt-part}.
8076
8077 If @var{gt-part} is missing, it defaults to @var{eq-part}.  If @var{eq-part}
8078 is missing, it defaults to the empty string.  Thus both @samp{$(intcmp
8079 9,7,hello)} and @samp{$(intcmp 9,7,hello,world,)} evaluate to the empty
8080 string, while @samp{$(intcmp 9,7,hello,world)} (notice the absence of a comma
8081 after @code{world}) evaluates to @samp{world}.
8082
8083 @end table
8084
8085 @node Let Function, Foreach Function, Conditional Functions, Functions
8086 @section The @code{let} Function
8087 @findex let
8088 @cindex variables, local
8089
8090 The @code{let} function provides a means to limit the scope of a
8091 variable.  The assignment of the named variables in a @code{let}
8092 expression is in effect only within the text provided by the
8093 @code{let} expression, and this assignment doesn't impact that named
8094 variable in any outer scope.
8095
8096 Additionally, the @code{let} function enables list unpacking by
8097 assigning all unassigned values to the last named variable.
8098
8099 The syntax of the @code{let} function is:
8100
8101 @example
8102 $(let @var{var} [@var{var} ...],[@var{list}],@var{text})
8103 @end example
8104
8105 @noindent
8106 The first two arguments, @var{var} and @var{list}, are expanded before
8107 anything else is done; note that the last argument, @var{text}, is
8108 @strong{not} expanded at the same time.  Next, each word of the
8109 expanded value of @var{list} is bound to each of the variable names,
8110 @var{var}, in turn, with the final variable name being bound to the
8111 remainder of the expanded @var{list}.  In other words, the first word
8112 of @var{list} is bound to the first variable @var{var}, the second
8113 word to the second variable @var{var}, and so on.
8114
8115 If there are more variable names in @var{var} than there are words in
8116 @var{list}, the remaining @var{var} variable names are set to the
8117 empty string.  If there are fewer @var{var}s than words in @var{list}
8118 then the last @var{var} is set to all remaining words in @var{list}.
8119
8120 The variables in @var{var} are assigned as simply-expanded variables
8121 during the execution of @code{let}.  @xref{Flavors, ,The Two Flavors
8122 of Variables}.
8123
8124 After all variables are thus bound, @var{text} is expanded to provide
8125 the result of the @code{let} function.
8126
8127 For example, this macro reverses the order of the words in the list
8128 that it is given as its first argument:
8129
8130 @example
8131 reverse = $(let first rest,$1,\
8132             $(if $(rest),$(call reverse,$(rest)) )$(first))
8133
8134 all: ; @@echo $(call reverse,d c b a)
8135 @end example
8136
8137 @noindent
8138 will print @code{a b c d}.  When first called, @code{let} will expand
8139 @var{$1} to @code{d c b a}.  It will then assign @var{first} to
8140 @code{d} and assign @var{rest} to @code{c b a}.  It will then expand
8141 the if-statement, where @code{$(rest)} is not empty so we recursively
8142 invoke the @var{reverse} function with the value of @var{rest} which
8143 is now @code{c b a}.  The recursive invocation of @code{let} assigns
8144 @var{first} to @code{c} and @var{rest} to @code{b a}.  The recursion
8145 continues until @code{let} is called with just a single value,
8146 @code{a}.  Here @var{first} is @code{a} and @var{rest} is empty, so we
8147 do not recurse but simply expand @code{$(first)} to @code{a} and
8148 return, which adds @code{ b}, etc.
8149
8150 After the @var{reverse} call is complete, the @var{first} and
8151 @var{rest} variables are no longer set.  If variables by those names
8152 existed beforehand, they are not affected by the expansion of the
8153 @code{reverse} macro.
8154
8155 @node Foreach Function, File Function, Let Function, Functions
8156 @section The @code{foreach} Function
8157 @findex foreach
8158 @cindex words, iterating over
8159
8160 The @code{foreach} function is similar to the @code{let} function, but very
8161 different from other functions.  It causes one piece of text to be used
8162 repeatedly, each time with a different substitution performed on it.  The
8163 @code{foreach} function resembles the @code{for} command in the
8164 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
8165
8166 The syntax of the @code{foreach} function is:
8167
8168 @example
8169 $(foreach @var{var},@var{list},@var{text})
8170 @end example
8171
8172 @noindent
8173 The first two arguments, @var{var} and @var{list}, are expanded before
8174 anything else is done; note that the last argument, @var{text}, is
8175 @strong{not} expanded at the same time.  Then for each word of the expanded
8176 value of @var{list}, the variable named by the expanded value of @var{var}
8177 is set to that word, and @var{text} is expanded.  Presumably @var{text}
8178 contains references to that variable, so its expansion will be different
8179 each time.
8180
8181 The result is that @var{text} is expanded as many times as there are
8182 whitespace-separated words in @var{list}.  The multiple expansions of
8183 @var{text} are concatenated, with spaces between them, to make the result
8184 of @code{foreach}.
8185
8186 This simple example sets the variable @samp{files} to the list of all files
8187 in the directories in the list @samp{dirs}:
8188
8189 @example
8190 dirs := a b c d
8191 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
8192 @end example
8193
8194 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
8195 finds the value @samp{a} for @code{dir}, so it produces the same result
8196 as @samp{$(wildcard a/*)}; the second repetition produces the result
8197 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
8198
8199 This example has the same result (except for setting @samp{dirs}) as
8200 the following example:
8201
8202 @example
8203 files := $(wildcard a/* b/* c/* d/*)
8204 @end example
8205
8206 When @var{text} is complicated, you can improve readability by giving it
8207 a name, with an additional variable:
8208
8209 @example
8210 find_files = $(wildcard $(dir)/*)
8211 dirs := a b c d
8212 files := $(foreach dir,$(dirs),$(find_files))
8213 @end example
8214
8215 @noindent
8216 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
8217 to define a recursively-expanding variable, so that its value contains an
8218 actual function call to be re-expanded under the control of @code{foreach};
8219 a simply-expanded variable would not do, since @code{wildcard} would be
8220 called only once at the time of defining @code{find_files}.
8221
8222 Like the @code{let} function, the @code{foreach} function has no permanent
8223 effect on the variable @var{var}; its value and flavor after the
8224 @code{foreach} function call are the same as they were beforehand.  The
8225 other values which are taken from @var{list} are in effect only
8226 temporarily, during the execution of @code{foreach}.  The variable
8227 @var{var} is a simply-expanded variable during the execution of
8228 @code{foreach}.  If @var{var} was undefined before the @code{foreach}
8229 function call, it is undefined after the call.
8230 @xref{Flavors, ,The Two Flavors of Variables}.
8231
8232 You must take care when using complex variable expressions that result in
8233 variable names because many strange things are valid variable names, but
8234 are probably not what you intended.  For example,
8235
8236 @smallexample
8237 files := $(foreach Esta-escrito-en-espanol!,b c ch,$(find_files))
8238 @end smallexample
8239
8240 @noindent
8241 might be useful if the value of @code{find_files} references the variable
8242 whose name is @samp{Esta-escrito-en-espanol!} (es un nombre bastante largo,
8243 no?), but it is more likely to be a mistake.
8244
8245 @node File Function, Call Function, Foreach Function, Functions
8246 @section The @code{file} Function
8247 @findex file
8248 @cindex writing to a file
8249 @cindex file, writing to
8250 @cindex reading from a file
8251 @cindex file, reading from
8252
8253 The @code{file} function allows the makefile to write to or read from
8254 a file.  Two modes of writing are supported: overwrite, where the text
8255 is written to the beginning of the file and any existing content is
8256 lost, and append, where the text is written to the end of the file,
8257 preserving the existing content.  In both cases the file is created if
8258 it does not exist.  It is a fatal error if the file cannot be opened
8259 for writing, or if the write operation fails.  The @code{file}
8260 function expands to the empty string when writing to a file.
8261
8262 When reading from a file, the @code{file} function expands to the
8263 verbatim contents of the file, except that the final newline (if there
8264 is one) will be stripped.  Attempting to read from a non-existent file
8265 expands to the empty string.
8266
8267 The syntax of the @code{file} function is:
8268
8269 @example
8270 $(file @var{op} @var{filename}[,@var{text}])
8271 @end example
8272
8273 When the @code{file} function is evaluated all its arguments are
8274 expanded first, then the file indicated by @var{filename} will be
8275 opened in the mode described by @var{op}.
8276
8277 The operator @var{op} can be @code{>} to indicate the file will be
8278 overwritten with new content, @code{>>} to indicate the current
8279 contents of the file will be appended to, or @code{<} to indicate the
8280 contents of the file will be read in.  The @var{filename} specifies
8281 the file to be written to or read from.  There may optionally be
8282 whitespace between the operator and the file name.
8283
8284 When reading files, it is an error to provide a @var{text} value.
8285
8286 When writing files, @var{text} will be written to the file.  If
8287 @var{text} does not already end in a newline a final newline will be
8288 written (even if @var{text} is the empty string).  If the @var{text}
8289 argument is not given at all, nothing will be written.
8290
8291 For example, the @code{file} function can be useful if your build
8292 system has a limited command line size and your recipe runs a command
8293 that can accept arguments from a file as well.  Many commands use the
8294 convention that an argument prefixed with an @code{@@} specifies a
8295 file containing more arguments.  Then you might write your recipe in
8296 this way:
8297
8298 @example
8299 @group
8300 program: $(OBJECTS)
8301         $(file >$@@.in,$^)
8302         $(CMD) $(CMDFLAGS) @@$@@.in
8303         @@rm $@@.in
8304 @end group
8305 @end example
8306
8307 If the command required each argument to be on a separate line of the
8308 input file, you might write your recipe like this:
8309
8310 @example
8311 @group
8312 program: $(OBJECTS)
8313         $(file >$@@.in) $(foreach O,$^,$(file >>$@@.in,$O))
8314         $(CMD) $(CMDFLAGS) @@$@@.in
8315         @@rm $@@.in
8316 @end group
8317 @end example
8318
8319 @node Call Function, Value Function, File Function, Functions
8320 @section The @code{call} Function
8321 @findex call
8322 @cindex functions, user defined
8323 @cindex user defined functions
8324
8325 The @code{call} function is unique in that it can be used to create new
8326 parameterized functions.  You can write a complex expression as the
8327 value of a variable, then use @code{call} to expand it with different
8328 values.
8329
8330 The syntax of the @code{call} function is:
8331
8332 @example
8333 $(call @var{variable},@var{param},@var{param},@dots{})
8334 @end example
8335
8336 When @code{make} expands this function, it assigns each @var{param} to
8337 temporary variables @code{$(1)}, @code{$(2)}, etc.  The variable
8338 @code{$(0)} will contain @var{variable}.  There is no maximum number of
8339 parameter arguments.  There is no minimum, either, but it doesn't make
8340 sense to use @code{call} with no parameters.
8341
8342 Then @var{variable} is expanded as a @code{make} variable in the context
8343 of these temporary assignments.  Thus, any reference to @code{$(1)} in
8344 the value of @var{variable} will resolve to the first @var{param} in the
8345 invocation of @code{call}.
8346
8347 Note that @var{variable} is the @emph{name} of a variable, not a
8348 @emph{reference} to that variable.  Therefore you would not normally use
8349 a @samp{$} or parentheses when writing it.  (You can, however, use a
8350 variable reference in the name if you want the name not to be a
8351 constant.)
8352
8353 If @var{variable} is the name of a built-in function, the built-in function
8354 is always invoked (even if a @code{make} variable by that name also
8355 exists).
8356
8357 The @code{call} function expands the @var{param} arguments before
8358 assigning them to temporary variables.  This means that @var{variable}
8359 values containing references to built-in functions that have special
8360 expansion rules, like @code{foreach} or @code{if}, may not work as you
8361 expect.
8362
8363 Some examples may make this clearer.
8364
8365 This macro simply reverses its arguments:
8366
8367 @smallexample
8368 reverse = $(2) $(1)
8369
8370 foo = $(call reverse,a,b)
8371 @end smallexample
8372
8373 @noindent
8374 Here @code{foo} will contain @samp{b a}.
8375
8376 This one is slightly more interesting: it defines a macro to search for
8377 the first instance of a program in @code{PATH}:
8378
8379 @smallexample
8380 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
8381
8382 LS := $(call pathsearch,ls)
8383 @end smallexample
8384
8385 @noindent
8386 Now the variable @code{LS} contains @code{/bin/ls} or similar.
8387
8388 The @code{call} function can be nested.  Each recursive invocation gets
8389 its own local values for @code{$(1)}, etc.@: that mask the values of
8390 higher-level @code{call}.  For example, here is an implementation of a
8391 @dfn{map} function:
8392
8393 @smallexample
8394 map = $(foreach a,$(2),$(call $(1),$(a)))
8395 @end smallexample
8396
8397 Now you can @code{map} a function that normally takes only one argument,
8398 such as @code{origin}, to multiple values in one step:
8399
8400 @smallexample
8401 o = $(call map,origin,o map MAKE)
8402 @end smallexample
8403
8404 and end up with @code{o} containing something like @samp{file file default}.
8405
8406 A final caution: be careful when adding whitespace to the arguments to
8407 @code{call}.  As with other functions, any whitespace contained in the
8408 second and subsequent arguments is kept; this can cause strange
8409 effects.  It's generally safest to remove all extraneous whitespace when
8410 providing parameters to @code{call}.
8411
8412 @node Value Function, Eval Function, Call Function, Functions
8413 @comment  node-name,  next,  previous,  up
8414 @section The @code{value} Function
8415 @findex value
8416 @cindex variables, unexpanded value
8417
8418 The @code{value} function provides a way for you to use the value of a
8419 variable @emph{without} having it expanded.  Please note that this
8420 does not undo expansions which have already occurred; for example if
8421 you create a simply expanded variable its value is expanded during the
8422 definition; in that case the @code{value} function will return the
8423 same result as using the variable directly.
8424
8425 The syntax of the @code{value} function is:
8426
8427 @example
8428 $(value @var{variable})
8429 @end example
8430
8431 Note that @var{variable} is the @emph{name} of a variable, not a
8432 @emph{reference} to that variable.  Therefore you would not normally
8433 use a @samp{$} or parentheses when writing it.  (You can, however, use
8434 a variable reference in the name if you want the name not to be a
8435 constant.)
8436
8437 The result of this function is a string containing the value of
8438 @var{variable}, without any expansion occurring.  For example, in this
8439 makefile:
8440
8441 @example
8442 @group
8443 FOO = $PATH
8444
8445 all:
8446         @@echo $(FOO)
8447         @@echo $(value FOO)
8448 @end group
8449 @end example
8450
8451 @noindent
8452 The first output line would be @code{ATH}, since the ``$P'' would be
8453 expanded as a @code{make} variable, while the second output line would
8454 be the current value of your @code{$PATH} environment variable, since
8455 the @code{value} function avoided the expansion.
8456
8457 The @code{value} function is most often used in conjunction with the
8458 @code{eval} function (@pxref{Eval Function}).
8459
8460 @node Eval Function, Origin Function, Value Function, Functions
8461 @comment  node-name,  next,  previous,  up
8462 @section The @code{eval} Function
8463 @findex eval
8464 @cindex evaluating makefile syntax
8465 @cindex makefile syntax, evaluating
8466
8467 The @code{eval} function is very special: it allows you to define new
8468 makefile constructs that are not constant; which are the result of
8469 evaluating other variables and functions.  The argument to the
8470 @code{eval} function is expanded, then the results of that expansion
8471 are parsed as makefile syntax.  The expanded results can define new
8472 @code{make} variables, targets, implicit or explicit rules, etc.
8473
8474 The result of the @code{eval} function is always the empty string;
8475 thus, it can be placed virtually anywhere in a makefile without
8476 causing syntax errors.
8477
8478 It's important to realize that the @code{eval} argument is expanded
8479 @emph{twice}; first by the @code{eval} function, then the results of
8480 that expansion are expanded again when they are parsed as makefile
8481 syntax.  This means you may need to provide extra levels of escaping
8482 for ``$'' characters when using @code{eval}.  The @code{value}
8483 function (@pxref{Value Function}) can sometimes be useful in these
8484 situations, to circumvent unwanted expansions.
8485
8486 Here is an example of how @code{eval} can be used; this example
8487 combines a number of concepts and other functions.  Although it might
8488 seem overly complex to use @code{eval} in this example, rather than
8489 just writing out the rules, consider two things: first, the template
8490 definition (in @code{PROGRAM_template}) could need to be much more
8491 complex than it is here; and second, you might put the complex,
8492 ``generic'' part of this example into another makefile, then include
8493 it in all the individual makefiles.  Now your individual makefiles are
8494 quite straightforward.
8495
8496 @example
8497 @group
8498 PROGRAMS    = server client
8499
8500 server_OBJS = server.o server_priv.o server_access.o
8501 server_LIBS = priv protocol
8502
8503 client_OBJS = client.o client_api.o client_mem.o
8504 client_LIBS = protocol
8505
8506 # Everything after this is generic
8507
8508 .PHONY: all
8509 all: $(PROGRAMS)
8510
8511 define PROGRAM_template =
8512  $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
8513  ALL_OBJS   += $$($(1)_OBJS)
8514 endef
8515
8516 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
8517
8518 $(PROGRAMS):
8519         $(LINK.o) $^ $(LDLIBS) -o $@@
8520
8521 clean:
8522         rm -f $(ALL_OBJS) $(PROGRAMS)
8523 @end group
8524 @end example
8525
8526 @node Origin Function, Flavor Function, Eval Function, Functions
8527 @section The @code{origin} Function
8528 @findex origin
8529 @cindex variables, origin of
8530 @cindex origin of variable
8531
8532 The @code{origin} function is unlike most other functions in that it does
8533 not operate on the values of variables; it tells you something @emph{about}
8534 a variable.  Specifically, it tells you where it came from.
8535
8536 The syntax of the @code{origin} function is:
8537
8538 @example
8539 $(origin @var{variable})
8540 @end example
8541
8542 Note that @var{variable} is the @emph{name} of a variable to inquire about,
8543 not a @emph{reference} to that variable.  Therefore you would not normally
8544 use a @samp{$} or parentheses when writing it.  (You can, however, use a
8545 variable reference in the name if you want the name not to be a constant.)
8546
8547 The result of this function is a string telling you how the variable
8548 @var{variable} was defined:
8549
8550 @table @samp
8551 @item undefined
8552
8553 if @var{variable} was never defined.
8554
8555 @item default
8556
8557 if @var{variable} has a default definition, as is usual with @code{CC}
8558 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
8559 Note that if you have redefined a default variable, the @code{origin}
8560 function will return the origin of the later definition.
8561
8562 @item environment
8563
8564 if @var{variable} was inherited from the environment provided to
8565 @code{make}.
8566
8567 @item environment override
8568
8569 if @var{variable} was inherited from the environment provided to
8570 @code{make}, and is overriding a setting for @var{variable} in the
8571 makefile as a result of the @w{@samp{-e}} option (@pxref{Options
8572 Summary, ,Summary of Options}).
8573
8574 @item file
8575
8576 if @var{variable} was defined in a makefile.
8577
8578 @item command line
8579
8580 if @var{variable} was defined on the command line.
8581
8582 @item override
8583
8584 if @var{variable} was defined with an @code{override} directive in a
8585 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
8586
8587 @item automatic
8588
8589 if @var{variable} is an automatic variable defined for the execution
8590 of the recipe for each rule (@pxref{Automatic Variables}).
8591 @end table
8592
8593 This information is primarily useful (other than for your curiosity) to
8594 determine if you want to believe the value of a variable.  For example,
8595 suppose you have a makefile @file{foo} that includes another makefile
8596 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
8597 if you run the command @w{@samp{make -f bar}}, even if the environment contains
8598 a definition of @code{bletch}.  However, if @file{foo} defined
8599 @code{bletch} before including @file{bar}, you do not want to override that
8600 definition.  This could be done by using an @code{override} directive in
8601 @file{foo}, giving that definition precedence over the later definition in
8602 @file{bar}; unfortunately, the @code{override} directive would also
8603 override any command line definitions.  So, @file{bar} could
8604 include:
8605
8606 @example
8607 @group
8608 ifdef bletch
8609 ifeq "$(origin bletch)" "environment"
8610 bletch = barf, gag, etc.
8611 endif
8612 endif
8613 @end group
8614 @end example
8615
8616 @noindent
8617 If @code{bletch} has been defined from the environment, this will redefine
8618 it.
8619
8620 If you want to override a previous definition of @code{bletch} if it came
8621 from the environment, even under @samp{-e}, you could instead write:
8622
8623 @example
8624 @group
8625 ifneq "$(findstring environment,$(origin bletch))" ""
8626 bletch = barf, gag, etc.
8627 endif
8628 @end group
8629 @end example
8630
8631 Here the redefinition takes place if @samp{$(origin bletch)} returns either
8632 @samp{environment} or @samp{environment override}.
8633 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8634
8635 @node Flavor Function, Make Control Functions, Origin Function, Functions
8636 @section The @code{flavor} Function
8637 @findex flavor
8638 @cindex variables, flavor of
8639 @cindex flavor of variable
8640
8641 The @code{flavor} function, like the @code{origin} function, does not
8642 operate on the values of variables but rather it tells you something
8643 @emph{about} a variable.  Specifically, it tells you the flavor of a
8644 variable (@pxref{Flavors, ,The Two Flavors of Variables}).
8645
8646 The syntax of the @code{flavor} function is:
8647
8648 @example
8649 $(flavor @var{variable})
8650 @end example
8651
8652 Note that @var{variable} is the @emph{name} of a variable to inquire about,
8653 not a @emph{reference} to that variable.  Therefore you would not normally
8654 use a @samp{$} or parentheses when writing it.  (You can, however, use a
8655 variable reference in the name if you want the name not to be a constant.)
8656
8657 The result of this function is a string that identifies the flavor of the
8658 variable @var{variable}:
8659
8660 @table @samp
8661 @item undefined
8662
8663 if @var{variable} was never defined.
8664
8665 @item recursive
8666
8667 if @var{variable} is a recursively expanded variable.
8668
8669 @item simple
8670
8671 if @var{variable} is a simply expanded variable.
8672
8673 @end table
8674
8675 @node Make Control Functions, Shell Function, Flavor Function, Functions
8676 @section Functions That Control Make
8677 @cindex functions, for controlling make
8678 @cindex controlling make
8679
8680 These functions control the way make runs.  Generally, they are used to
8681 provide information to the user of the makefile or to cause make to stop
8682 if some sort of environmental error is detected.
8683
8684 @table @code
8685 @item $(error @var{text}@dots{})
8686 @findex error
8687 @cindex error, stopping on
8688 @cindex stopping make
8689 Generates a fatal error where the message is @var{text}.  Note that
8690 the error is generated whenever this function is evaluated.  So, if
8691 you put it inside a recipe or on the right side of a recursive
8692 variable assignment, it won't be evaluated until later.  The
8693 @var{text} will be expanded before the error is generated.
8694
8695 For example,
8696
8697 @example
8698 ifdef ERROR1
8699 $(error error is $(ERROR1))
8700 endif
8701 @end example
8702
8703 @noindent
8704 will generate a fatal error during the read of the makefile if the
8705 @code{make} variable @code{ERROR1} is defined.  Or,
8706
8707 @example
8708 ERR = $(error found an error!)
8709
8710 .PHONY: err
8711 err: ; $(ERR)
8712 @end example
8713
8714 @noindent
8715 will generate a fatal error while @code{make} is running, if the
8716 @code{err} target is invoked.
8717
8718 @item $(warning @var{text}@dots{})
8719 @findex warning
8720 @cindex warnings, printing
8721 @cindex printing user warnings
8722 This function works similarly to the @code{error} function, above,
8723 except that @code{make} doesn't exit.  Instead, @var{text} is expanded
8724 and the resulting message is displayed, but processing of the makefile
8725 continues.
8726
8727 The result of the expansion of this function is the empty string.
8728
8729 @item $(info @var{text}@dots{})
8730 @findex info
8731 @cindex printing messages
8732 This function does nothing more than print its (expanded) argument(s)
8733 to standard output.  No makefile name or line number is added.  The
8734 result of the expansion of this function is the empty string.
8735 @end table
8736
8737 @node Shell Function, Guile Function, Make Control Functions, Functions
8738 @section The @code{shell} Function
8739 @findex shell
8740 @cindex command expansion
8741 @cindex backquotes
8742 @cindex shell command, function for
8743
8744 The @code{shell} function is unlike any other function other than the
8745 @code{wildcard} function
8746 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
8747 communicates with the world outside of @code{make}.
8748
8749 The @code{shell} function provides for @code{make} the same facility that
8750 backquotes (@samp{`}) provide in most shells: it does @dfn{command expansion}.
8751 This means that it takes as an argument a shell command and expands to the
8752 output of the command.  The only processing @code{make} does on the result is
8753 to convert each newline (or carriage-return / newline pair) to a single space.
8754 If there is a trailing (carriage-return and) newline it will simply be
8755 removed.
8756
8757 The commands run by calls to the @code{shell} function are run when the
8758 function calls are expanded (@pxref{Reading Makefiles, , How @code{make} Reads
8759 a Makefile}).  Because this function involves spawning a new shell, you should
8760 carefully consider the performance implications of using the @code{shell}
8761 function within recursively expanded variables vs.@: simply expanded variables
8762 (@pxref{Flavors, ,The Two Flavors of Variables}).
8763
8764 An alternative to the @code{shell} function is the @samp{!=} assignment
8765 operator; it provides a similar behavior but has subtle differences
8766 (@pxref{Setting, , Setting Variables}).  The @samp{!=} assignment operator is
8767 included in newer POSIX standards.
8768
8769 @vindex .SHELLSTATUS
8770 After the @code{shell} function or @samp{!=} assignment operator is
8771 used, its exit status is placed in the @code{.SHELLSTATUS} variable.
8772
8773 Here are some examples of the use of the @code{shell} function:
8774
8775 @example
8776 contents := $(shell cat foo)
8777 @end example
8778
8779 @noindent
8780 sets @code{contents} to the contents of the file @file{foo}, with a space
8781 (rather than a newline) separating each line.
8782
8783 @example
8784 files := $(shell echo *.c)
8785 @end example
8786
8787 @noindent
8788 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
8789 using a very strange shell, this has the same result as
8790 @w{@samp{$(wildcard *.c)}} (as long as at least one @samp{.c} file
8791 exists).
8792
8793 All variables that are marked as @code{export} will also be passed to the
8794 shell started by the @code{shell} function.  It is possible to create a
8795 variable expansion loop: consider this @file{makefile}:
8796
8797 @example
8798 export HI = $(shell echo hi)
8799 all: ; @@echo $$HI
8800 @end example
8801
8802 When @code{make} wants to run the recipe it must add the variable @var{HI} to
8803 the environment; to do so it must be expanded.  The value of this variable
8804 requires an invocation of the @code{shell} function, and to invoke it we must
8805 create its environment.  Since @var{HI} is exported, we need to expand it to
8806 create its environment.  And so on.  In this obscure case @code{make} will use
8807 the value of the variable from the environment provided to @code{make}, or
8808 else the empty string if there was none, rather than looping or issuing an
8809 error.  This is often what you want; for example:
8810
8811 @example
8812 export PATH = $(shell echo /usr/local/bin:$$PATH)
8813 @end example
8814
8815 However, it would be simpler and more efficient to use a simply-expanded
8816 variable here (@samp{:=}) in the first place.
8817
8818 @node Guile Function,  , Shell Function, Functions
8819 @section The @code{guile} Function
8820 @findex guile
8821 @cindex Guile
8822
8823 If GNU @code{make} is built with support for GNU Guile as an embedded
8824 extension language then the @code{guile} function will be available.
8825 The @code{guile} function takes one argument which is first expanded
8826 by @code{make} in the normal fashion, then passed to the GNU Guile
8827 evaluator.  The result of the evaluator is converted into a string and
8828 used as the expansion of the @code{guile} function in the makefile.
8829 See @ref{Guile Integration, ,GNU Guile Integration} for details on
8830 writing extensions to @code{make} in Guile.
8831
8832 You can determine whether GNU Guile support is available by checking
8833 the @code{.FEATURES} variable for the word @var{guile}.
8834
8835 @node Running, Implicit Rules, Functions, Top
8836 @chapter How to Run @code{make}
8837
8838 A makefile that says how to recompile a program can be used in more
8839 than one way.  The simplest use is to recompile every file that is out
8840 of date.  Usually, makefiles are written so that if you run
8841 @code{make} with no arguments, it does just that.
8842
8843 But you might want to update only some of the files; you might want to use
8844 a different compiler or different compiler options; you might want just to
8845 find out which files are out of date without changing them.
8846
8847 By giving arguments when you run @code{make}, you can do any of these
8848 things and many others.
8849
8850 @cindex exit status of make
8851 The exit status of @code{make} is always one of three values:
8852 @table @code
8853 @item 0
8854 The exit status is zero if @code{make} is successful.
8855 @item 2
8856 The exit status is two if @code{make} encounters any errors.
8857 It will print messages describing the particular errors.
8858 @item 1
8859 The exit status is one if you use the @samp{-q} flag and @code{make}
8860 determines that some target is not already up to date.
8861 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8862 @end table
8863
8864 @menu
8865 * Makefile Arguments::          How to specify which makefile to use.
8866 * Goals::                       How to use goal arguments to specify which
8867                                   parts of the makefile to use.
8868 * Instead of Execution::        How to use mode flags to specify what
8869                                   kind of thing to do with the recipes
8870                                   in the makefile other than simply
8871                                   execute them.
8872 * Avoiding Compilation::        How to avoid recompiling certain files.
8873 * Overriding::                  How to override a variable to specify
8874                                   an alternate compiler and other things.
8875 * Testing::                     How to proceed past some errors, to
8876                                   test compilation.
8877 * Temporary Files::             Where @code{make} keeps its temporary files.
8878 * Options Summary::             Summary of Options
8879 @end menu
8880
8881 @node Makefile Arguments, Goals, Running, Running
8882 @section Arguments to Specify the Makefile
8883 @cindex @code{--file}
8884 @cindex @code{--makefile}
8885 @cindex @code{-f}
8886
8887 The way to specify the name of the makefile is with the @samp{-f} or
8888 @samp{--file} option (@samp{--makefile} also works).  For example,
8889 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
8890
8891 If you use the @samp{-f} flag several times and follow each @samp{-f}
8892 with an argument, all the specified files are used jointly as
8893 makefiles.
8894
8895 If you do not use the @samp{-f} or @samp{--file} flag, the default is
8896 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
8897 that order, and use the first of these three which exists or can be made
8898 (@pxref{Makefiles, ,Writing Makefiles}).
8899
8900 @node Goals, Instead of Execution, Makefile Arguments, Running
8901 @section Arguments to Specify the Goals
8902 @cindex goal, how to specify
8903
8904 The @dfn{goals} are the targets that @code{make} should strive ultimately
8905 to update.  Other targets are updated as well if they appear as
8906 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
8907
8908 By default, the goal is the first target in the makefile (not counting
8909 targets that start with a period).  Therefore, makefiles are usually
8910 written so that the first target is for compiling the entire program or
8911 programs they describe.  If the first rule in the makefile has several
8912 targets, only the first target in the rule becomes the default goal, not
8913 the whole list.  You can manage the selection of the default goal from
8914 within your makefile using the @code{.DEFAULT_GOAL} variable
8915 (@pxref{Special Variables, , Other Special Variables}).
8916
8917 You can also specify a different goal or goals with command line
8918 arguments to @code{make}.  Use the name of the goal as an argument.
8919 If you specify several goals, @code{make} processes each of them in
8920 turn, in the order you name them.
8921
8922 Any target in the makefile may be specified as a goal (unless it
8923 starts with @samp{-} or contains an @samp{=}, in which case it will be
8924 parsed as a switch or variable definition, respectively).  Even
8925 targets not in the makefile may be specified, if @code{make} can find
8926 implicit rules that say how to make them.
8927
8928 @vindex MAKECMDGOALS
8929 @code{Make} will set the special variable @code{MAKECMDGOALS} to the
8930 list of goals you specified on the command line.  If no goals were given
8931 on the command line, this variable is empty.  Note that this variable
8932 should be used only in special circumstances.
8933
8934 An example of appropriate use is to avoid including @file{.d} files
8935 during @code{clean} rules (@pxref{Automatic Prerequisites}), so
8936 @code{make} won't create them only to immediately remove them
8937 again:
8938
8939 @example
8940 @group
8941 sources = foo.c bar.c
8942
8943 ifeq (,$(filter clean,$(MAKECMDGOALS))
8944 include $(sources:.c=.d)
8945 endif
8946 @end group
8947 @end example
8948
8949 One use of specifying a goal is if you want to compile only a part of
8950 the program, or only one of several programs.  Specify as a goal each
8951 file that you wish to remake.  For example, consider a directory containing
8952 several programs, with a makefile that starts like this:
8953
8954 @example
8955 .PHONY: all
8956 all: size nm ld ar as
8957 @end example
8958
8959 If you are working on the program @code{size}, you might want to say
8960 @w{@samp{make size}} so that only the files of that program are recompiled.
8961
8962 Another use of specifying a goal is to make files that are not normally
8963 made.  For example, there may be a file of debugging output, or a
8964 version of the program that is compiled specially for testing, which has
8965 a rule in the makefile but is not a prerequisite of the default goal.
8966
8967 Another use of specifying a goal is to run the recipe associated with
8968 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
8969 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
8970 a phony target named @file{clean} which deletes everything except source
8971 files.  Naturally, this is done only if you request it explicitly with
8972 @w{@samp{make clean}}.  Following is a list of typical phony and empty
8973 target names.  @xref{Standard Targets}, for a detailed list of all the
8974 standard target names which GNU software packages use.
8975
8976 @table @file
8977 @item all
8978 @cindex @code{all} @r{(standard target)}
8979 Make all the top-level targets the makefile knows about.
8980
8981 @item clean
8982 @cindex @code{clean} @r{(standard target)}
8983 Delete all files that are normally created by running @code{make}.
8984
8985 @item mostlyclean
8986 @cindex @code{mostlyclean} @r{(standard target)}
8987 Like @samp{clean}, but may refrain from deleting a few files that people
8988 normally don't want to recompile.  For example, the @samp{mostlyclean}
8989 target for GCC does not delete @file{libgcc.a}, because recompiling it
8990 is rarely necessary and takes a lot of time.
8991
8992 @item distclean
8993 @cindex @code{distclean} @r{(standard target)}
8994 @itemx realclean
8995 @cindex @code{realclean} @r{(standard target)}
8996 @itemx clobber
8997 @cindex @code{clobber} @r{(standard target)}
8998 Any of these targets might be defined to delete @emph{more} files than
8999 @samp{clean} does.  For example, this would delete configuration files
9000 or links that you would normally create as preparation for compilation,
9001 even if the makefile itself cannot create these files.
9002
9003 @item install
9004 @cindex @code{install} @r{(standard target)}
9005 Copy the executable file into a directory that users typically search
9006 for commands; copy any auxiliary files that the executable uses into
9007 the directories where it will look for them.
9008
9009 @item print
9010 @cindex @code{print} @r{(standard target)}
9011 Print listings of the source files that have changed.
9012
9013 @item tar
9014 @cindex @code{tar} @r{(standard target)}
9015 Create a tar file of the source files.
9016
9017 @item shar
9018 @cindex @code{shar} @r{(standard target)}
9019 Create a shell archive (shar file) of the source files.
9020
9021 @item dist
9022 @cindex @code{dist} @r{(standard target)}
9023 Create a distribution file of the source files.  This might
9024 be a tar file, or a shar file, or a compressed version of one of the
9025 above, or even more than one of the above.
9026
9027 @item TAGS
9028 @cindex @code{TAGS} @r{(standard target)}
9029 Update a tags table for this program.
9030
9031 @item check
9032 @cindex @code{check} @r{(standard target)}
9033 @itemx test
9034 @cindex @code{test} @r{(standard target)}
9035 Perform self tests on the program this makefile builds.
9036 @end table
9037
9038 @node Instead of Execution, Avoiding Compilation, Goals, Running
9039 @section Instead of Executing Recipes
9040 @cindex execution, instead of
9041 @cindex recipes, instead of executing
9042
9043 The makefile tells @code{make} how to tell whether a target is up to date,
9044 and how to update each target.  But updating the targets is not always
9045 what you want.  Certain options specify other activities for @code{make}.
9046
9047 @comment Extra blank lines make it print better.
9048 @table @samp
9049 @item -n
9050 @itemx --just-print
9051 @itemx --dry-run
9052 @itemx --recon
9053 @cindex @code{--just-print}
9054 @cindex @code{--dry-run}
9055 @cindex @code{--recon}
9056 @cindex @code{-n}
9057
9058 ``No-op''.  Causes @code{make} to print the recipes that are needed to
9059 make the targets up to date, but not actually execute them.  Note that
9060 some recipes are still executed, even with this flag (@pxref{MAKE
9061 Variable, ,How the @code{MAKE} Variable Works}).  Also any recipes
9062 needed to update included makefiles are still executed
9063 (@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).
9064
9065 @item -t
9066 @itemx --touch
9067 @cindex @code{--touch}
9068 @cindex touching files
9069 @cindex target, touching
9070 @cindex @code{-t}
9071
9072 ``Touch''.  Marks targets as up to date without actually changing
9073 them.  In other words, @code{make} pretends to update the targets but
9074 does not really change their contents; instead only their modified
9075 times are updated.
9076
9077 @item -q
9078 @itemx --question
9079 @cindex @code{--question}
9080 @cindex @code{-q}
9081 @cindex question mode
9082
9083 ``Question''.  Silently check whether the targets are up to date, but
9084 do not execute recipes; the exit code shows whether any updates are
9085 needed.
9086
9087 @item -W @var{file}
9088 @itemx --what-if=@var{file}
9089 @itemx --assume-new=@var{file}
9090 @itemx --new-file=@var{file}
9091 @cindex @code{--what-if}
9092 @cindex @code{-W}
9093 @cindex @code{--assume-new}
9094 @cindex @code{--new-file}
9095 @cindex what if
9096 @cindex files, assuming new
9097
9098 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
9099 files' modification times are recorded by @code{make} as being the present
9100 time, although the actual modification times remain the same.
9101 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
9102 to see what would happen if you were to modify specific files.
9103 @end table
9104
9105 With the @samp{-n} flag, @code{make} prints the recipe that it would
9106 normally execute but usually does not execute it.
9107
9108 With the @samp{-t} flag, @code{make} ignores the recipes in the rules
9109 and uses (in effect) the command @code{touch} for each target that needs to
9110 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
9111 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
9112 the program @code{touch}.  It does the work directly.
9113
9114 With the @samp{-q} flag, @code{make} prints nothing and executes no
9115 recipes, but the exit status code it returns is zero if and only if the
9116 targets to be considered are already up to date.  If the exit status is
9117 one, then some updating needs to be done.  If @code{make} encounters an
9118 error, the exit status is two, so you can distinguish an error from a
9119 target that is not up to date.
9120
9121 It is an error to use more than one of these three flags in the same
9122 invocation of @code{make}.
9123
9124 @cindex +, and recipe execution
9125 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect recipe
9126 lines that begin with @samp{+} characters or contain the strings
9127 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
9128 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
9129 is run regardless of these options.  Other lines in the same rule are
9130 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
9131 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
9132
9133 @cindex phony targets and recipe execution
9134 The @samp{-t} flag prevents phony targets (@pxref{Phony Targets}) from
9135 being updated, unless there are recipe lines beginning with @samp{+}
9136 or containing @samp{$(MAKE)} or @samp{$@{MAKE@}}.
9137
9138 The @samp{-W} flag provides two features:
9139
9140 @itemize @bullet
9141 @item
9142 If you also use the @samp{-n} or @samp{-q} flag, you can see what
9143 @code{make} would do if you were to modify some files.
9144
9145 @item
9146 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
9147 executing recipes, the @samp{-W} flag can direct @code{make} to act as
9148 if some files had been modified, without actually running the recipes
9149 for those files.
9150 @end itemize
9151
9152 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
9153 information about @code{make} or about the makefiles in use
9154 (@pxref{Options Summary, ,Summary of Options}).
9155
9156 @node Avoiding Compilation, Overriding, Instead of Execution, Running
9157 @section Avoiding Recompilation of Some Files
9158 @cindex @code{-o}
9159 @cindex @code{--old-file}
9160 @cindex @code{--assume-old}
9161 @cindex files, assuming old
9162 @cindex files, avoiding recompilation of
9163 @cindex recompilation, avoiding
9164
9165 Sometimes you may have changed a source file but you do not want to
9166 recompile all the files that depend on it.  For example, suppose you add
9167 a macro or a declaration to a header file that many other files depend
9168 on.  Being conservative, @code{make} assumes that any change in the
9169 header file requires recompilation of all dependent files, but you know
9170 that they do not need to be recompiled and you would rather not waste
9171 the time waiting for them to compile.
9172
9173 If you anticipate the problem before changing the header file, you can
9174 use the @samp{-t} flag.  This flag tells @code{make} not to run the
9175 recipes in the rules, but rather to mark the target up to date by
9176 changing its last-modification date.  You would follow this procedure:
9177
9178 @enumerate
9179 @item
9180 Use the command @samp{make} to recompile the source files that really
9181 need recompilation, ensuring that the object files are up-to-date
9182 before you begin.
9183
9184 @item
9185 Make the changes in the header files.
9186
9187 @item
9188 Use the command @samp{make -t} to mark all the object files as
9189 up to date.  The next time you run @code{make}, the changes in the
9190 header files will not cause any recompilation.
9191 @end enumerate
9192
9193 If you have already changed the header file at a time when some files
9194 do need recompilation, it is too late to do this.  Instead, you can
9195 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
9196 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
9197 that the file itself will not be remade, and nothing else will be
9198 remade on its account.  Follow this procedure:
9199
9200 @enumerate
9201 @item
9202 Recompile the source files that need compilation for reasons independent
9203 of the particular header file, with @samp{make -o @var{headerfile}}.
9204 If several header files are involved, use a separate @samp{-o} option
9205 for each header file.
9206
9207 @item
9208 Touch all the object files with @samp{make -t}.
9209 @end enumerate
9210
9211 @node Overriding, Testing, Avoiding Compilation, Running
9212 @section Overriding Variables
9213 @cindex overriding variables with arguments
9214 @cindex variables, overriding with arguments
9215 @cindex command line variables
9216 @cindex variables, command line
9217
9218 An argument that contains @samp{=} specifies the value of a variable:
9219 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
9220 If you specify a value in this way, all ordinary assignments of the same
9221 variable in the makefile are ignored; we say they have been
9222 @dfn{overridden} by the command line argument.
9223
9224 The most common way to use this facility is to pass extra flags to
9225 compilers.  For example, in a properly written makefile, the variable
9226 @code{CFLAGS} is included in each recipe that runs the C compiler, so a
9227 file @file{foo.c} would be compiled something like this:
9228
9229 @example
9230 cc -c $(CFLAGS) foo.c
9231 @end example
9232
9233 Thus, whatever value you set for @code{CFLAGS} affects each compilation
9234 that occurs.  The makefile probably specifies the usual value for
9235 @code{CFLAGS}, like this:
9236
9237 @example
9238 CFLAGS=-g
9239 @end example
9240
9241 Each time you run @code{make}, you can override this value if you
9242 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
9243 compilation will be done with @samp{cc -c -g -O}.  (This also
9244 illustrates how you can use quoting in the shell to enclose spaces and
9245 other special characters in the value of a variable when you override
9246 it.)
9247
9248 The variable @code{CFLAGS} is only one of many standard variables that
9249 exist just so that you can change them this way.  @xref{Implicit
9250 Variables, , Variables Used by Implicit Rules}, for a complete list.
9251
9252 You can also program the makefile to look at additional variables of your
9253 own, giving the user the ability to control other aspects of how the
9254 makefile works by changing the variables.
9255
9256 When you override a variable with a command line argument, you can
9257 define either a recursively-expanded variable or a simply-expanded
9258 variable.  The examples shown above make a recursively-expanded
9259 variable; to make a simply-expanded variable, write @samp{:=} or
9260 @samp{::=} instead of @samp{=}.  But, unless you want to include a
9261 variable reference or function call in the @emph{value} that you
9262 specify, it makes no difference which kind of variable you create.
9263
9264 There is one way that the makefile can change a variable that you have
9265 overridden.  This is to use the @code{override} directive, which is a line
9266 that looks like this: @samp{override @var{variable} = @var{value}}
9267 (@pxref{Override Directive, ,The @code{override} Directive}).
9268
9269 @node Testing, Temporary Files, Overriding, Running
9270 @section Testing the Compilation of a Program
9271 @cindex testing compilation
9272 @cindex compilation, testing
9273
9274 Normally, when an error happens in executing a shell command, @code{make}
9275 gives up immediately, returning a nonzero status.  No further recipes are
9276 executed for any target.  The error implies that the goal cannot be
9277 correctly remade, and @code{make} reports this as soon as it knows.
9278
9279 When you are compiling a program that you have just changed, this is not
9280 what you want.  Instead, you would rather that @code{make} try compiling
9281 every file that can be tried, to show you as many compilation errors
9282 as possible.
9283
9284 @cindex @code{-k}
9285 @cindex @code{--keep-going}
9286 On these occasions, you should use the @samp{-k} or
9287 @samp{--keep-going} flag.  This tells @code{make} to continue to
9288 consider the other prerequisites of the pending targets, remaking them
9289 if necessary, before it gives up and returns nonzero status.  For
9290 example, after an error in compiling one object file, @samp{make -k}
9291 will continue compiling other object files even though it already
9292 knows that linking them will be impossible.  In addition to continuing
9293 after failed shell commands, @samp{make -k} will continue as much as
9294 possible after discovering that it does not know how to make a target
9295 or prerequisite file.  This will always cause an error message, but
9296 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
9297 ,Summary of Options}).
9298
9299 The usual behavior of @code{make} assumes that your purpose is to get the
9300 goals up to date; once @code{make} learns that this is impossible, it might
9301 as well report the failure immediately.  The @samp{-k} flag says that the
9302 real purpose is to test as much as possible of the changes made in the
9303 program, perhaps to find several independent problems so that you can
9304 correct them all before the next attempt to compile.  This is why Emacs'
9305 @kbd{M-x compile} command passes the @samp{-k} flag by default.
9306
9307 @node Temporary Files, Options Summary, Testing, Running
9308 @section Temporary Files
9309 @cindex temporary files
9310
9311 In some situations, @code{make} will need to create its own temporary files.
9312 These files must not be disturbed while @code{make} is running, including all
9313 recursively-invoked instances of @code{make}.
9314
9315 @cindex @code{MAKE_TMPDIR}
9316 If the environment variable @code{MAKE_TMPDIR} is set then all temporary files
9317 created by @code{make} will be placed there.
9318
9319 @cindex @code{TMPDIR}
9320 @cindex @code{TMP}
9321 @cindex @code{TEMP}
9322 If @code{MAKE_TMPDIR} is not set, then the standard location for temporary
9323 files for the current operating system will be used.  For POSIX systems this
9324 will be the location set in the @code{TMPDIR} environment variable, or else
9325 the system's default location (e.g., @file{/tmp}) is used.  On Windows,
9326 first @code{TMP} then @code{TEMP} will be checked, then @code{TMPDIR}, and
9327 finally the system default temporary file location will be used.
9328
9329 Note that this directory must already exist or @code{make} will fail:
9330 @code{make} will not attempt to create it.
9331
9332 These variables @emph{cannot} be set from within a makefile: GNU @code{make}
9333 must have access to this location before it begins reading the makefiles.
9334
9335 @node Options Summary,  , Temporary Files, Running
9336 @section Summary of Options
9337 @cindex options
9338 @cindex flags
9339 @cindex switches
9340
9341 Here is a table of all the options @code{make} understands:
9342
9343 @table @samp
9344 @item -b
9345 @cindex @code{-b}
9346 @itemx -m
9347 @cindex @code{-m}
9348 These options are ignored for compatibility with other versions of @code{make}.
9349
9350 @item -B
9351 @cindex @code{-B}
9352 @itemx --always-make
9353 @cindex @code{--always-make}
9354 Consider all targets out-of-date.  GNU @code{make} proceeds to
9355 consider targets and their prerequisites using the normal algorithms;
9356 however, all targets so considered are always remade regardless of the
9357 status of their prerequisites.  To avoid infinite recursion, if
9358 @code{MAKE_RESTARTS} (@pxref{Special Variables, , Other Special
9359 Variables}) is set to a number greater than 0 this option is disabled
9360 when considering whether to remake makefiles (@pxref{Remaking
9361 Makefiles, , How Makefiles Are Remade}).
9362
9363 @item -C @var{dir}
9364 @cindex @code{-C}
9365 @itemx --directory=@var{dir}
9366 @cindex @code{--directory}
9367 Change to directory @var{dir} before reading the makefiles.  If multiple
9368 @samp{-C} options are specified, each is interpreted relative to the
9369 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
9370 This is typically used with recursive invocations of @code{make}
9371 (@pxref{Recursion, ,Recursive Use of @code{make}}).
9372
9373 @item -d
9374 @cindex @code{-d}
9375 @c Extra blank line here makes the table look better.
9376
9377 Print debugging information in addition to normal processing.  The
9378 debugging information says which files are being considered for
9379 remaking, which file-times are being compared and with what results,
9380 which files actually need to be remade, which implicit rules are
9381 considered and which are applied---everything interesting about how
9382 @code{make} decides what to do.  The @code{-d} option is equivalent to
9383 @samp{--debug=a} (see below).
9384
9385 @item --debug[=@var{options}]
9386 @cindex @code{--debug}
9387 @c Extra blank line here makes the table look better.
9388
9389 Print debugging information in addition to normal processing.  Various
9390 levels and types of output can be chosen.  With no arguments, print the
9391 ``basic'' level of debugging.  Possible arguments are below; only the
9392 first character is considered, and values must be comma- or
9393 space-separated.
9394
9395 @table @code
9396 @item a (@i{all})
9397 All types of debugging output are enabled.  This is equivalent to using
9398 @samp{-d}.
9399
9400 @item b (@i{basic})
9401 Basic debugging prints each target that was found to be out-of-date, and
9402 whether the build was successful or not.
9403
9404 @item v (@i{verbose})
9405 A level above @samp{basic}; includes messages about which makefiles were
9406 parsed, prerequisites that did not need to be rebuilt, etc.  This option
9407 also enables @samp{basic} messages.
9408
9409 @item i (@i{implicit})
9410 Prints messages describing the implicit rule searches for each target.
9411 This option also enables @samp{basic} messages.
9412
9413 @item j (@i{jobs})
9414 Prints messages giving details on the invocation of specific sub-commands.
9415
9416 @item m (@i{makefile})
9417 By default, the above messages are not enabled while trying to remake
9418 the makefiles.  This option enables messages while rebuilding makefiles,
9419 too.  Note that the @samp{all} option does enable this option.  This
9420 option also enables @samp{basic} messages.
9421
9422 @item p (@i{print})
9423 Prints the recipe to be executed, even when the recipe is normally
9424 silent (due to @code{.SILENT} or @samp{@@}).  Also prints the makefile
9425 name and line number where the recipe was defined.
9426
9427 @item w (@i{why})
9428 Explains why each target must be remade by showing which prerequisites
9429 are more up to date than the target.
9430
9431 @item n (@i{none})
9432 Disable all debugging currently enabled.  If additional debugging
9433 flags are encountered after this they will still take effect.
9434 @end table
9435
9436 @item -e
9437 @cindex @code{-e}
9438 @itemx --environment-overrides
9439 @cindex @code{--environment-overrides}
9440 Give variables taken from the environment precedence
9441 over variables from makefiles.
9442 @xref{Environment, ,Variables from the Environment}.
9443
9444 @item -E @var{string}
9445 @cindex @code{-E}
9446 @item --eval=@var{string}
9447 @cindex @code{--eval}
9448 @c Extra blank line here makes the table look better.
9449
9450 Evaluate @var{string} as makefile syntax.  This is a command-line
9451 version of the @code{eval} function (@pxref{Eval Function}).  The
9452 evaluation is performed after the default rules and variables have
9453 been defined, but before any makefiles are read.
9454
9455 @item -f @var{file}
9456 @cindex @code{-f}
9457 @itemx --file=@var{file}
9458 @cindex @code{--file}
9459 @itemx --makefile=@var{file}
9460 @cindex @code{--makefile}
9461 Read the file named @var{file} as a makefile.
9462 @xref{Makefiles, ,Writing Makefiles}.
9463
9464 @item -h
9465 @cindex @code{-h}
9466 @itemx --help
9467 @cindex @code{--help}
9468 @c Extra blank line here makes the table look better.
9469
9470 Remind you of the options that @code{make} understands and then exit.
9471
9472 @item -i
9473 @cindex @code{-i}
9474 @itemx --ignore-errors
9475 @cindex @code{--ignore-errors}
9476 Ignore all errors in recipes executed to remake files.
9477 @xref{Errors, ,Errors in Recipes}.
9478
9479 @item -I @var{dir}
9480 @cindex @code{-I}
9481 @itemx --include-dir=@var{dir}
9482 @cindex @code{--include-dir}
9483 Specifies a directory @var{dir} to search for included makefiles.
9484 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
9485 options are used to specify several directories, the directories are
9486 searched in the order specified.  If the directory @var{dir} is a
9487 single dash (@code{-}) then any already-specified directories up to
9488 that point (including the default directory paths) will be discarded.
9489 You can examine the current list of directories to be searched via the
9490 @code{.INCLUDE_DIRS} variable.
9491
9492 @item -j [@var{jobs}]
9493 @cindex @code{-j}
9494 @itemx --jobs[=@var{jobs}]
9495 @cindex @code{--jobs}
9496 Specifies the number of recipes (jobs) to run simultaneously.  With no
9497 argument, @code{make} runs as many recipes simultaneously as possible.
9498 If there is more than one @samp{-j} option, the last one is effective.
9499 @xref{Parallel, ,Parallel Execution}, for more information on how
9500 recipes are run.  Note that this option is ignored on MS-DOS.
9501
9502 @item --jobserver-style=[@var{style}]
9503 @cindex @code{--jobserver-style}
9504 Chooses the style of jobserver to use.  This option only has effect if
9505 parallel builds are enabled (@pxref{Parallel, ,Parallel Execution}).  On POSIX
9506 systems @var{style} can be one of @code{fifo} (the default) or @code{pipe}.
9507 On Windows the only acceptable @var{style} is @code{sem} (the default).  This
9508 option is useful if you need to use an older versions of GNU @code{make}, or a
9509 different tool that requires a specific jobserver style.
9510
9511 @item -k
9512 @cindex @code{-k}
9513 @itemx --keep-going
9514 @cindex @code{--keep-going}
9515 Continue as much as possible after an error.  While the target that
9516 failed, and those that depend on it, cannot be remade, the other
9517 prerequisites of these targets can be processed all the same.
9518 @xref{Testing, ,Testing the Compilation of a Program}.
9519
9520 @item -l [@var{load}]
9521 @cindex @code{-l}
9522 @itemx --load-average[=@var{load}]
9523 @cindex @code{--load-average}
9524 @itemx --max-load[=@var{load}]
9525 @cindex @code{--max-load}
9526 Specifies that no new recipes should be started if there are other
9527 recipes running and the load average is at least @var{load} (a
9528 floating-point number).  With no argument, removes a previous load
9529 limit.  @xref{Parallel, ,Parallel Execution}.
9530
9531 @item -L
9532 @cindex @code{-L}
9533 @itemx --check-symlink-times
9534 @cindex @code{--check-symlink-times}
9535 On systems that support symbolic links, this option causes @code{make}
9536 to consider the timestamps on any symbolic links in addition to the
9537 timestamp on the file referenced by those links.  When this option is
9538 provided, the most recent timestamp among the file and the symbolic
9539 links is taken as the modification time for this target file.
9540
9541 @item -n
9542 @cindex @code{-n}
9543 @itemx --just-print
9544 @cindex @code{--just-print}
9545 @itemx --dry-run
9546 @cindex @code{--dry-run}
9547 @itemx --recon
9548 @cindex @code{--recon}
9549 @c Extra blank line here makes the table look better.
9550
9551 Print the recipe that would be executed, but do not execute it (except
9552 in certain circumstances).
9553 @xref{Instead of Execution, ,Instead of Executing Recipes}.
9554
9555 @item -o @var{file}
9556 @cindex @code{-o}
9557 @itemx --old-file=@var{file}
9558 @cindex @code{--old-file}
9559 @itemx --assume-old=@var{file}
9560 @cindex @code{--assume-old}
9561 Do not remake the file @var{file} even if it is older than its
9562 prerequisites, and do not remake anything on account of changes in
9563 @var{file}.  Essentially the file is treated as very old and its rules
9564 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
9565 Some Files}.
9566
9567 @item -O[@var{type}]
9568 @cindex @code{-O}
9569 @itemx --output-sync[=@var{type}]
9570 @cindex @code{--output-sync}
9571 @cindex output during parallel execution
9572 @cindex parallel execution, output during
9573 Ensure that the complete output from each recipe is printed in one
9574 uninterrupted sequence.  This option is only useful when using the
9575 @code{--jobs} option to run multiple recipes simultaneously
9576 (@pxref{Parallel, ,Parallel Execution})  Without this option output
9577 will be displayed as it is generated by the recipes.
9578
9579 With no type or the type @samp{target}, output from the entire recipe
9580 of each target is grouped together.  With the type @samp{line}, output
9581 from each line in the recipe is grouped together.  With the type
9582 @samp{recurse}, the output from an entire recursive make is grouped
9583 together.  With the type @samp{none}, no output synchronization is
9584 performed.  @xref{Parallel Output, ,Output During Parallel Execution}.
9585
9586 @item -p
9587 @cindex @code{-p}
9588 @itemx --print-data-base
9589 @cindex @code{--print-data-base}
9590 @cindex data base of @code{make} rules
9591 @cindex predefined rules and variables, printing
9592 Print the data base (rules and variable values) that results from
9593 reading the makefiles; then execute as usual or as otherwise
9594 specified.  This also prints the version information given by the
9595 @samp{-v} switch (see below).  To print the data base without trying
9596 to remake any files, use @w{@samp{make -qp}}.  To print the data base
9597 of predefined rules and variables, use @w{@samp{make -p -f /dev/null}}.
9598 The data base output contains file name and line number information for
9599 recipe and variable definitions, so it can be a useful debugging tool
9600 in complex environments.
9601
9602 @item -q
9603 @cindex @code{-q}
9604 @itemx --question
9605 @cindex @code{--question}
9606 ``Question mode''.  Do not run any recipes, or print anything; just
9607 return an exit status that is zero if the specified targets are already
9608 up to date, one if any remaking is required, or two if an error is
9609 encountered.  @xref{Instead of Execution, ,Instead of Executing
9610 Recipes}.
9611
9612 @item -r
9613 @cindex @code{-r}
9614 @itemx --no-builtin-rules
9615 @cindex @code{--no-builtin-rules}
9616 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
9617 ,Using Implicit Rules}).  You can still define your own by writing
9618 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
9619 Rules}).  The @samp{-r} option also clears out the default list of
9620 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
9621 Rules}).  But you can still define your own suffixes with a rule for
9622 @code{.SUFFIXES}, and then define your own suffix rules.  Note that only
9623 @emph{rules} are affected by the @code{-r} option; default variables
9624 remain in effect (@pxref{Implicit Variables, ,Variables Used by Implicit
9625 Rules}); see the @samp{-R} option below.
9626
9627 @item -R
9628 @cindex @code{-R}
9629 @itemx --no-builtin-variables
9630 @cindex @code{--no-builtin-variables}
9631 Eliminate use of the built-in rule-specific variables (@pxref{Implicit
9632 Variables, ,Variables Used by Implicit Rules}).  You can still define
9633 your own, of course.  The @samp{-R} option also automatically enables
9634 the @samp{-r} option (see above), since it doesn't make sense to have
9635 implicit rules without any definitions for the variables that they use.
9636
9637 @item -s
9638 @cindex @code{-s}
9639 @itemx --silent
9640 @cindex @code{--silent}
9641 @itemx --quiet
9642 @cindex @code{--quiet}
9643 @c Extra blank line here makes the table look better.
9644
9645 Silent operation; do not print the recipes as they are executed.
9646 @xref{Echoing, ,Recipe Echoing}.
9647
9648 @item -S
9649 @cindex @code{-S}
9650 @itemx --no-keep-going
9651 @cindex @code{--no-keep-going}
9652 @itemx --stop
9653 @cindex @code{--stop}
9654 @c Extra blank line here makes the table look better.
9655
9656 Cancel the effect of the @samp{-k} option.  This is never necessary
9657 except in a recursive @code{make} where @samp{-k} might be inherited
9658 from the top-level @code{make} via @code{MAKEFLAGS}
9659 (@pxref{Recursion, ,Recursive Use of @code{make}})
9660 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.
9661
9662 @item --shuffle[=@var{mode}]
9663 @cindex @code{--shuffle}
9664 @c Extra blank line here makes the table look better.
9665
9666 This option enables a form of fuzz-testing of prerequisite relationships.
9667 When parallelism is enabled (@samp{-j}) the order in which targets are
9668 built becomes less deterministic.  If prerequisites are not fully declared
9669 in the makefile this can lead to intermittent and hard-to-track-down build
9670 failures.
9671
9672 The @samp{--shuffle} option forces @code{make} to purposefully reorder goals
9673 and prerequisites so target/prerequisite relationships still hold, but
9674 ordering of prerequisites of a given target are reordered as described below.
9675
9676 The order in which prerequisites are listed in automatic variables is not
9677 changed by this option.
9678
9679 The @code{.NOTPARALLEL} pseudo-target disables shuffling for that makefile.
9680 Also any prerequisite list which contains @code{.WAIT} will not be shuffled.
9681 @xref{Parallel Disable, ,Disabling Parallel Execution}.
9682
9683 The @samp{--shuffle=} option accepts these values:
9684
9685 @table @code
9686 @item random
9687 Choose a random seed for the shuffle.  This is the default if no mode is
9688 specified.  The chosen seed is also provided to sub-@code{make} commands.  The
9689 seed is included in error messages so that it can be re-used in future runs to
9690 reproduce the problem or verify that it has been resolved.
9691
9692 @item reverse
9693 Reverse the order of goals and prerequisites, rather than a random shuffle.
9694
9695 @item @var{seed}
9696 Use @samp{random} shuffle initialized with the specified seed value.  The
9697 @var{seed} is an integer.
9698
9699 @item none
9700 Disable shuffling.  This negates any previous @samp{--shuffle} options.
9701 @end table
9702
9703 @item -t
9704 @cindex @code{-t}
9705 @itemx --touch
9706 @cindex @code{--touch}
9707 @c Extra blank line here makes the table look better.
9708
9709 Touch files (mark them up to date without really changing them)
9710 instead of running their recipes.  This is used to pretend that the
9711 recipes were done, in order to fool future invocations of
9712 @code{make}.  @xref{Instead of Execution, ,Instead of Executing Recipes}.
9713
9714 @item --trace
9715 @cindex @code{--trace}
9716 Show tracing information for @code{make} execution.  Using @code{--trace} is
9717 shorthand for @code{--debug=print,why}.
9718
9719 @item -v
9720 @cindex @code{-v}
9721 @itemx --version
9722 @cindex @code{--version}
9723 Print the version of the @code{make} program plus a copyright, a list
9724 of authors, and a notice that there is no warranty; then exit.
9725
9726 @item -w
9727 @cindex @code{-w}
9728 @itemx --print-directory
9729 @cindex @code{--print-directory}
9730 Print a message containing the working directory both before and after
9731 executing the makefile.  This may be useful for tracking down errors
9732 from complicated nests of recursive @code{make} commands.
9733 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
9734 rarely need to specify this option since @samp{make} does it for you;
9735 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
9736
9737 @item --no-print-directory
9738 @cindex @code{--no-print-directory}
9739 Disable printing of the working directory under @code{-w}.
9740 This option is useful when @code{-w} is turned on automatically,
9741 but you do not want to see the extra messages.
9742 @xref{-w Option, ,The @samp{--print-directory} Option}.
9743
9744 @item -W @var{file}
9745 @cindex @code{-W}
9746 @itemx --what-if=@var{file}
9747 @cindex @code{--what-if}
9748 @itemx --new-file=@var{file}
9749 @cindex @code{--new-file}
9750 @itemx --assume-new=@var{file}
9751 @cindex @code{--assume-new}
9752 Pretend that the target @var{file} has just been modified.  When used
9753 with the @samp{-n} flag, this shows you what would happen if you were
9754 to modify that file.  Without @samp{-n}, it is almost the same as
9755 running a @code{touch} command on the given file before running
9756 @code{make}, except that the modification time is changed only in the
9757 imagination of @code{make}.
9758 @xref{Instead of Execution, ,Instead of Executing Recipes}.
9759
9760 @item --warn-undefined-variables
9761 @cindex @code{--warn-undefined-variables}
9762 @cindex variables, warning for undefined
9763 @cindex undefined variables, warning message
9764 Issue a warning message whenever @code{make} sees a reference to an
9765 undefined variable.  This can be helpful when you are trying to debug
9766 makefiles which use variables in complex ways.
9767 @end table
9768
9769 @node Implicit Rules, Archives, Running, Top
9770 @chapter Using Implicit Rules
9771 @cindex implicit rule
9772 @cindex rule, implicit
9773
9774 Certain standard ways of remaking target files are used very often.  For
9775 example, one customary way to make an object file is from a C source file
9776 using the C compiler, @code{cc}.
9777
9778 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
9779 that you do not have to specify them in detail when you want to use
9780 them.  For example, there is an implicit rule for C compilation.  File
9781 names determine which implicit rules are run.  For example, C
9782 compilation typically takes a @file{.c} file and makes a @file{.o} file.
9783 So @code{make} applies the implicit rule for C compilation when it sees
9784 this combination of file name endings.
9785
9786 A chain of implicit rules can apply in sequence; for example, @code{make}
9787 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
9788 @iftex
9789 @xref{Chained Rules, ,Chains of Implicit Rules}.
9790 @end iftex
9791
9792 The built-in implicit rules use several variables in their recipes so
9793 that, by changing the values of the variables, you can change the way the
9794 implicit rule works.  For example, the variable @code{CFLAGS} controls the
9795 flags given to the C compiler by the implicit rule for C compilation.
9796 @iftex
9797 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
9798 @end iftex
9799
9800 You can define your own implicit rules by writing @dfn{pattern rules}.
9801 @iftex
9802 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
9803 @end iftex
9804
9805 @dfn{Suffix rules} are a more limited way to define implicit rules.
9806 Pattern rules are more general and clearer, but suffix rules are
9807 retained for compatibility.
9808 @iftex
9809 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
9810 @end iftex
9811
9812 @menu
9813 * Using Implicit::              How to use an existing implicit rule
9814                                   to get the recipes for updating a file.
9815 * Catalogue of Rules::          A list of built-in rules.
9816 * Implicit Variables::          How to change what predefined rules do.
9817 * Chained Rules::               How to use a chain of implicit rules.
9818 * Pattern Rules::               How to define new implicit rules.
9819 * Last Resort::                 How to define a recipe for rules which
9820                                   cannot find any.
9821 * Suffix Rules::                The old-fashioned style of implicit rule.
9822 * Implicit Rule Search::        The precise algorithm for applying
9823                                   implicit rules.
9824 @end menu
9825
9826 @node Using Implicit, Catalogue of Rules, Implicit Rules, Implicit Rules
9827 @section Using Implicit Rules
9828 @cindex implicit rule, how to use
9829 @cindex rule, implicit, how to use
9830
9831 To allow @code{make} to find a customary method for updating a target
9832 file, all you have to do is refrain from specifying recipes yourself.
9833 Either write a rule with no recipe, or don't write a rule at all.
9834 Then @code{make} will figure out which implicit rule to use based on
9835 which kind of source file exists or can be made.
9836
9837 For example, suppose the makefile looks like this:
9838
9839 @example
9840 foo : foo.o bar.o
9841         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
9842 @end example
9843
9844 @noindent
9845 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
9846 will automatically look for an implicit rule that tells how to update it.
9847 This happens whether or not the file @file{foo.o} currently exists.
9848
9849 If an implicit rule is found, it can supply both a recipe and one or
9850 more prerequisites (the source files).  You would want to write a rule
9851 for @file{foo.o} with no recipe if you need to specify additional
9852 prerequisites, such as header files, that the implicit rule cannot
9853 supply.
9854
9855 Each implicit rule has a target pattern and prerequisite patterns.  There may
9856 be many implicit rules with the same target pattern.  For example, numerous
9857 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
9858 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
9859 that actually applies is the one whose prerequisites exist or can be made.
9860 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
9861 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
9862 compiler; and so on.
9863
9864 Of course, when you write the makefile, you know which implicit rule you
9865 want @code{make} to use, and you know it will choose that one because you
9866 know which possible prerequisite files are supposed to exist.
9867 @xref{Catalogue of Rules, ,Catalogue of Built-In Rules},
9868 for a catalogue of all the predefined implicit rules.
9869
9870 Above, we said an implicit rule applies if the required prerequisites ``exist
9871 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
9872 the makefile as a target or a prerequisite, or if an implicit rule can be
9873 recursively found for how to make it.  When an implicit prerequisite is the
9874 result of another implicit rule, we say that @dfn{chaining} is occurring.
9875 @xref{Chained Rules, ,Chains of Implicit Rules}.
9876
9877 In general, @code{make} searches for an implicit rule for each target, and
9878 for each double-colon rule, that has no recipe.  A file that is mentioned
9879 only as a prerequisite is considered a target whose rule specifies nothing,
9880 so implicit rule search happens for it.  @xref{Implicit Rule Search, ,Implicit Rule Search Algorithm}, for the
9881 details of how the search is done.
9882
9883 Note that explicit prerequisites do not influence implicit rule search.
9884 For example, consider this explicit rule:
9885
9886 @example
9887 foo.o: foo.p
9888 @end example
9889
9890 @noindent
9891 The prerequisite on @file{foo.p} does not necessarily mean that
9892 @code{make} will remake @file{foo.o} according to the implicit rule to
9893 make an object file, a @file{.o} file, from a Pascal source file, a
9894 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
9895 rule to make an object file from a C source file is used instead,
9896 because it appears before the Pascal rule in the list of predefined
9897 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Built-In
9898 Rules}).
9899
9900 If you do not want an implicit rule to be used for a target that has no
9901 recipe, you can give that target an empty recipe by writing a semicolon
9902 (@pxref{Empty Recipes, ,Defining Empty Recipes}).
9903
9904 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
9905 @section Catalogue of Built-In Rules
9906 @cindex implicit rule, predefined
9907 @cindex rule, implicit, predefined
9908
9909 Here is a catalogue of predefined implicit rules which are always
9910 available unless the makefile explicitly overrides or cancels them.
9911 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
9912 canceling or overriding an implicit rule.  The @samp{-r} or
9913 @samp{--no-builtin-rules} option cancels all predefined rules.
9914
9915 This manual only documents the default rules available on POSIX-based
9916 operating systems.  Other operating systems, such as VMS, Windows,
9917 OS/2, etc. may have different sets of default rules.  To see the full
9918 list of default rules and variables available in your version of GNU
9919 @code{make}, run @samp{make -p} in a directory with no makefile.
9920
9921 Not all of these rules will always be defined, even when the @samp{-r}
9922 option is not given.  Many of the predefined implicit rules are
9923 implemented in @code{make} as suffix rules, so which ones will be
9924 defined depends on the @dfn{suffix list} (the list of prerequisites of
9925 the special target @code{.SUFFIXES}).  The default suffix list is:
9926 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
9927 @code{.C}, @code{.cpp}, @code{.p}, @code{.f}, @code{.F}, @code{.m},
9928 @code{.r}, @code{.y}, @code{.l}, @code{.ym}, @code{.lm}, @code{.s},
9929 @code{.S}, @code{.mod}, @code{.sym}, @code{.def}, @code{.h},
9930 @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo}, @code{.texi},
9931 @code{.txinfo}, @code{.w}, @code{.ch} @code{.web}, @code{.sh},
9932 @code{.elc}, @code{.el}.  All of the implicit rules described below
9933 whose prerequisites have one of these suffixes are actually suffix
9934 rules.  If you modify the suffix list, the only predefined suffix
9935 rules in effect will be those named by one or two of the suffixes that
9936 are on the list you specify; rules whose suffixes fail to be on the
9937 list are disabled.  @xref{Suffix Rules, ,Old-Fashioned Suffix Rules},
9938 for full details on suffix rules.
9939
9940 @table @asis
9941 @item Compiling C programs
9942 @cindex C, rule to compile
9943 @pindex cc
9944 @pindex gcc
9945 @pindex .o
9946 @pindex .c
9947 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
9948 a recipe of the form @w{@samp{$(CC) $(CPPFLAGS) $(CFLAGS) -c}}.
9949
9950 @item Compiling C++ programs
9951 @cindex C++, rule to compile
9952 @pindex g++
9953 @pindex .cc
9954 @pindex .cpp
9955 @pindex .C
9956 @file{@var{n}.o} is made automatically from @file{@var{n}.cc},
9957 @file{@var{n}.cpp}, or @file{@var{n}.C} with a recipe of the form
9958 @w{@samp{$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c}}.  We encourage you to use the
9959 suffix @samp{.cc} or @samp{.cpp} for C++ source files instead of @samp{.C} to
9960 better support case-insensitive file systems.
9961
9962 @item Compiling Pascal programs
9963 @cindex Pascal, rule to compile
9964 @pindex pc
9965 @pindex .p
9966 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
9967 with the recipe @samp{$(PC) $(PFLAGS) -c}.
9968
9969 @item Compiling Fortran and Ratfor programs
9970 @cindex Fortran, rule to compile
9971 @cindex Ratfor, rule to compile
9972 @pindex f77
9973 @pindex .f
9974 @pindex .r
9975 @pindex .F
9976 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
9977 @file{@var{n}.F} or @file{@var{n}.f} by running the
9978 Fortran compiler.  The precise recipe used is as follows:
9979
9980 @table @samp
9981 @item .f
9982 @samp{$(FC) $(FFLAGS) -c}.
9983 @item .F
9984 @samp{$(FC) $(FFLAGS) $(CPPFLAGS) -c}.
9985 @item .r
9986 @samp{$(FC) $(FFLAGS) $(RFLAGS) -c}.
9987 @end table
9988
9989 @item Preprocessing Fortran and Ratfor programs
9990 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
9991 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
9992 Ratfor or preprocessable Fortran program into a strict Fortran
9993 program.  The precise recipe used is as follows:
9994
9995 @table @samp
9996 @item .F
9997 @samp{$(FC) $(CPPFLAGS) $(FFLAGS) -F}.
9998 @item .r
9999 @samp{$(FC) $(FFLAGS) $(RFLAGS) -F}.
10000 @end table
10001
10002 @item Compiling Modula-2 programs
10003 @cindex Modula-2, rule to compile
10004 @pindex m2c
10005 @pindex .sym
10006 @pindex .def
10007 @pindex .mod
10008 @file{@var{n}.sym} is made from @file{@var{n}.def} with a recipe of the form
10009 @w{@samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}}.  @file{@var{n}.o} is made from
10010 @file{@var{n}.mod}; the form is: @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.
10011
10012 @need 1200
10013 @item Assembling and preprocessing assembler programs
10014 @cindex assembly, rule to compile
10015 @pindex as
10016 @pindex .s
10017 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
10018 running the assembler, @code{as}.  The precise recipe is
10019 @samp{$(AS) $(ASFLAGS)}.
10020
10021 @pindex .S
10022 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
10023 running the C preprocessor, @code{cpp}.  The precise recipe is
10024 @w{@samp{$(CPP) $(CPPFLAGS)}}.
10025
10026 @item Linking a single object file
10027 @cindex linking, predefined rule for
10028 @pindex ld
10029 @pindex .o
10030 @file{@var{n}} is made automatically from @file{@var{n}.o} by running the C
10031 compiler to link the program.  The precise recipe used is @w{@samp{$(CC)
10032 $(LDFLAGS) @var{n}.o $(LOADLIBES) $(LDLIBS)}}.
10033
10034 This rule does the right thing for a simple program with only one
10035 source file.  It will also do the right thing if there are multiple
10036 object files (presumably coming from various other source files), one
10037 of which has a name matching that of the executable file.  Thus,
10038
10039 @example
10040 x: y.o z.o
10041 @end example
10042
10043 @noindent
10044 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
10045
10046 @example
10047 @group
10048 cc -c x.c -o x.o
10049 cc -c y.c -o y.o
10050 cc -c z.c -o z.o
10051 cc x.o y.o z.o -o x
10052 rm -f x.o
10053 rm -f y.o
10054 rm -f z.o
10055 @end group
10056 @end example
10057
10058 @noindent
10059 In more complicated cases, such as when there is no object file whose
10060 name derives from the executable file name, you must write an explicit
10061 recipe for linking.
10062
10063 Each kind of file automatically made into @samp{.o} object files will
10064 be automatically linked by using the compiler (@samp{$(CC)},
10065 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
10066 assemble @samp{.s} files) without the @samp{-c} option.  This could be
10067 done by using the @samp{.o} object files as intermediates, but it is
10068 faster to do the compiling and linking in one step, so that's how it's
10069 done.
10070
10071 @item Yacc for C programs
10072 @pindex yacc
10073 @cindex Yacc, rule to run
10074 @pindex .y
10075 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
10076 running Yacc with the recipe @samp{$(YACC) $(YFLAGS)}.
10077
10078 @item Lex for C programs
10079 @pindex lex
10080 @cindex Lex, rule to run
10081 @pindex .l
10082 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
10083 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
10084
10085 @item Lex for Ratfor programs
10086 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
10087 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
10088
10089 The convention of using the same suffix @samp{.l} for all Lex files
10090 regardless of whether they produce C code or Ratfor code makes it
10091 impossible for @code{make} to determine automatically which of the two
10092 languages you are using in any particular case.  If @code{make} is
10093 called upon to remake an object file from a @samp{.l} file, it must
10094 guess which compiler to use.  It will guess the C compiler, because
10095 that is more common.  If you are using Ratfor, make sure @code{make}
10096 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
10097 are using Ratfor exclusively, with no C files, remove @samp{.c} from
10098 the list of implicit rule suffixes with:
10099
10100 @example
10101 @group
10102 .SUFFIXES:
10103 .SUFFIXES: .o .r .f .l @dots{}
10104 @end group
10105 @end example
10106
10107 @item Making Lint Libraries from C, Yacc, or Lex programs
10108 @pindex lint
10109 @cindex @code{lint}, rule to run
10110 @pindex .ln
10111 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
10112 The precise recipe is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.
10113 The same recipe is used on the C code produced from
10114 @file{@var{n}.y} or @file{@var{n}.l}.
10115
10116 @item @TeX{} and Web
10117 @cindex @TeX{}, rule to run
10118 @cindex Web, rule to run
10119 @pindex tex
10120 @pindex cweave
10121 @pindex weave
10122 @pindex tangle
10123 @pindex ctangle
10124 @pindex .dvi
10125 @pindex .tex
10126 @pindex .web
10127 @pindex .w
10128 @pindex .ch
10129 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the recipe
10130 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
10131 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
10132 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
10133 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
10134 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
10135 or can be made) with @samp{$(CTANGLE)}.
10136
10137 @item Texinfo and Info
10138 @cindex Texinfo, rule to format
10139 @cindex Info, rule to format
10140 @pindex texi2dvi
10141 @pindex makeinfo
10142 @pindex .texinfo
10143 @pindex .info
10144 @pindex .texi
10145 @pindex .txinfo
10146 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo},
10147 @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with the recipe
10148 @w{@samp{$(TEXI2DVI) $(TEXI2DVI_FLAGS)}}.  @file{@var{n}.info} is made from
10149 @file{@var{n}.texinfo}, @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with
10150 the recipe @w{@samp{$(MAKEINFO) $(MAKEINFO_FLAGS)}}.
10151
10152 @item RCS
10153 @cindex RCS, rule to extract from
10154 @pindex co
10155 @pindex ,v @r{(RCS file extension)}
10156 Any file @file{@var{n}} is extracted if necessary from an RCS file
10157 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
10158 recipe used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
10159 extracted from RCS if it already exists, even if the RCS file is
10160 newer.  The rules for RCS are terminal
10161 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
10162 so RCS files cannot be generated from another source; they must
10163 actually exist.
10164
10165 @item SCCS
10166 @cindex SCCS, rule to extract from
10167 @pindex get
10168 @pindex s. @r{(SCCS file prefix)}
10169 Any file @file{@var{n}} is extracted if necessary from an SCCS file
10170 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
10171 recipe used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
10172 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
10173 so SCCS files cannot be generated from another source; they must
10174 actually exist.
10175
10176 @pindex .sh
10177 For the benefit of SCCS, a file @file{@var{n}} is copied from
10178 @file{@var{n}.sh} and made executable (by everyone).  This is for
10179 shell scripts that are checked into SCCS.  Since RCS preserves the
10180 execution permission of a file, you do not need to use this feature
10181 with RCS.
10182
10183 We recommend that you avoid using of SCCS.  RCS is widely held to be
10184 superior, and is also free.  By choosing free software in place of
10185 comparable (or inferior) proprietary software, you support the free
10186 software movement.
10187 @end table
10188
10189 Usually, you want to change only the variables listed in the table
10190 above, which are documented in the following section.
10191
10192 However, the recipes in built-in implicit rules actually use
10193 variables such as @code{COMPILE.c}, @code{LINK.p}, and
10194 @code{PREPROCESS.S}, whose values contain the recipes listed above.
10195
10196 @code{make} follows the convention that the rule to compile a
10197 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
10198 Similarly, the rule to produce an executable from a @file{.@var{x}}
10199 file uses @code{LINK.@var{x}}; and the rule to preprocess a
10200 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
10201
10202 @vindex OUTPUT_OPTION
10203 Every rule that produces an object file uses the variable
10204 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
10205 contain @samp{-o $@@}, or to be empty, depending on a compile-time
10206 option.  You need the @samp{-o} option to ensure that the output goes
10207 into the right file when the source file is in a different directory,
10208 as when using @code{VPATH} (@pxref{Directory Search}).  However,
10209 compilers on some systems do not accept a @samp{-o} switch for object
10210 files.  If you use such a system, and use @code{VPATH}, some
10211 compilations will put their output in the wrong place.
10212 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
10213 the value @w{@samp{; mv $*.o $@@}}.
10214
10215 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
10216 @section Variables Used by Implicit Rules
10217 @cindex flags for compilers
10218
10219 The recipes in built-in implicit rules make liberal use of certain
10220 predefined variables.  You can alter the values of these variables in
10221 the makefile, with arguments to @code{make}, or in the environment to
10222 alter how the implicit rules work without redefining the rules
10223 themselves.  You can cancel all variables used by implicit rules with
10224 the @samp{-R} or @samp{--no-builtin-variables} option.
10225
10226 For example, the recipe used to compile a C source file actually says
10227 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
10228 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
10229 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
10230 used for all C compilations performed by the implicit rule.  By redefining
10231 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
10232 each compilation.  @emph{All} implicit rules that do C compilation use
10233 @samp{$(CC)} to get the program name for the compiler and @emph{all}
10234 include @samp{$(CFLAGS)} among the arguments given to the compiler.
10235
10236 The variables used in implicit rules fall into two classes: those that are
10237 names of programs (like @code{CC}) and those that contain arguments for the
10238 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
10239 some command arguments, but it must start with an actual executable program
10240 name.)  If a variable value contains more than one argument, separate them
10241 with spaces.
10242
10243 The following tables describe of some of the more commonly-used predefined
10244 variables.  This list is not exhaustive, and the default values shown here may
10245 not be what @code{make} selects for your environment.  To see the
10246 complete list of predefined variables for your instance of GNU @code{make} you
10247 can run @samp{make -p} in a directory with no makefiles.
10248
10249 Here is a table of some of the more common variables used as names of
10250 programs in built-in rules:
10251
10252 @table @code
10253 @item AR
10254 @vindex AR
10255 Archive-maintaining program; default @samp{ar}.
10256 @pindex ar
10257
10258 @item AS
10259 @vindex AS
10260 Program for compiling assembly files; default @samp{as}.
10261 @pindex as
10262
10263 @item CC
10264 @vindex CC
10265 Program for compiling C programs; default @samp{cc}.
10266 @pindex cc
10267
10268 @item CXX
10269 @vindex CXX
10270 Program for compiling C++ programs; default @samp{g++}.
10271 @pindex g++
10272
10273 @item CPP
10274 @vindex CPP
10275 Program for running the C preprocessor, with results to standard output;
10276 default @samp{$(CC) -E}.
10277
10278 @item FC
10279 @vindex FC
10280 Program for compiling or preprocessing Fortran and Ratfor programs;
10281 default @samp{f77}.
10282 @pindex f77
10283
10284 @item M2C
10285 @vindex M2C
10286 Program to use to compile Modula-2 source code; default @samp{m2c}.
10287 @pindex m2c
10288
10289 @item PC
10290 @vindex PC
10291 Program for compiling Pascal programs; default @samp{pc}.
10292 @pindex pc
10293
10294 @item CO
10295 @vindex CO
10296 Program for extracting a file from RCS; default @samp{co}.
10297 @pindex co
10298
10299 @item GET
10300 @vindex GET
10301 Program for extracting a file from SCCS; default @samp{get}.
10302 @pindex get
10303
10304 @item LEX
10305 @vindex LEX
10306 Program to use to turn Lex grammars into source code; default @samp{lex}.
10307 @pindex lex
10308
10309 @item YACC
10310 @vindex YACC
10311 Program to use to turn Yacc grammars into source code; default @samp{yacc}.
10312 @pindex yacc
10313
10314 @item LINT
10315 @vindex LINT
10316 Program to use to run lint on source code; default @samp{lint}.
10317 @pindex lint
10318
10319 @item MAKEINFO
10320 @vindex MAKEINFO
10321 Program to convert a Texinfo source file into an Info file; default
10322 @samp{makeinfo}.
10323 @pindex makeinfo
10324
10325 @item TEX
10326 @vindex TEX
10327 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
10328 default @samp{tex}.
10329 @pindex tex
10330
10331 @item TEXI2DVI
10332 @vindex TEXI2DVI
10333 Program to make @TeX{} @sc{dvi} files from Texinfo source;
10334 default @samp{texi2dvi}.
10335 @pindex texi2dvi
10336
10337 @item WEAVE
10338 @vindex WEAVE
10339 Program to translate Web into @TeX{}; default @samp{weave}.
10340 @pindex weave
10341
10342 @item CWEAVE
10343 @vindex CWEAVE
10344 Program to translate C Web into @TeX{}; default @samp{cweave}.
10345 @pindex cweave
10346
10347 @item TANGLE
10348 @vindex TANGLE
10349 Program to translate Web into Pascal; default @samp{tangle}.
10350 @pindex tangle
10351
10352 @item CTANGLE
10353 @vindex CTANGLE
10354 Program to translate C Web into C; default @samp{ctangle}.
10355 @pindex ctangle
10356
10357 @item RM
10358 @vindex RM
10359 Command to remove a file; default @samp{rm -f}.
10360 @pindex rm
10361 @end table
10362
10363 Here is a table of variables whose values are additional arguments for the
10364 programs above.  The default values for all of these is the empty
10365 string, unless otherwise noted.
10366
10367 @table @code
10368 @item ARFLAGS
10369 @vindex ARFLAGS
10370 Flags to give the archive-maintaining program; default @samp{rv}.
10371
10372 @item ASFLAGS
10373 @vindex ASFLAGS
10374 Extra flags to give to the assembler (when explicitly
10375 invoked on a @samp{.s} or @samp{.S} file).
10376
10377 @item CFLAGS
10378 @vindex CFLAGS
10379 Extra flags to give to the C compiler.
10380
10381 @item CXXFLAGS
10382 @vindex CXXFLAGS
10383 Extra flags to give to the C++ compiler.
10384
10385 @item COFLAGS
10386 @vindex COFLAGS
10387 Extra flags to give to the RCS @code{co} program.
10388
10389 @item CPPFLAGS
10390 @vindex CPPFLAGS
10391 Extra flags to give to the C preprocessor and programs
10392 that use it (the C and Fortran compilers).
10393
10394 @item FFLAGS
10395 @vindex FFLAGS
10396 Extra flags to give to the Fortran compiler.
10397
10398 @item GFLAGS
10399 @vindex GFLAGS
10400 Extra flags to give to the SCCS @code{get} program.
10401
10402 @item LDFLAGS
10403 @vindex LDFLAGS
10404 Extra flags to give to compilers when they are supposed to invoke the linker,
10405 @samp{ld}, such as @code{-L}.  Libraries (@code{-lfoo}) should be
10406 added to the @code{LDLIBS} variable instead.
10407
10408 @item LDLIBS
10409 @vindex LDLIBS
10410 @vindex LOADLIBES
10411 Library flags or names given to compilers when they are supposed to
10412 invoke the linker, @samp{ld}.  @code{LOADLIBES} is a deprecated (but
10413 still supported) alternative to @code{LDLIBS}.  Non-library linker
10414 flags, such as @code{-L}, should go in the @code{LDFLAGS} variable.
10415
10416 @item LFLAGS
10417 @vindex LFLAGS
10418 Extra flags to give to Lex.
10419
10420 @item YFLAGS
10421 @vindex YFLAGS
10422 Extra flags to give to Yacc.
10423
10424 @item PFLAGS
10425 @vindex PFLAGS
10426 Extra flags to give to the Pascal compiler.
10427
10428 @item RFLAGS
10429 @vindex RFLAGS
10430 Extra flags to give to the Fortran compiler for Ratfor programs.
10431
10432 @item LINTFLAGS
10433 @vindex LINTFLAGS
10434 Extra flags to give to lint.
10435 @end table
10436
10437 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
10438 @section Chains of Implicit Rules
10439
10440 @cindex chains of rules
10441 @cindex rule, implicit, chains of
10442 Sometimes a file can be made by a sequence of implicit rules.  For example,
10443 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
10444 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
10445
10446 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
10447 special searching is required: @code{make} finds that the object file can
10448 be made by C compilation from @file{@var{n}.c}; later on, when considering
10449 how to make @file{@var{n}.c}, the rule for running Yacc is
10450 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
10451 updated.
10452
10453 @cindex intermediate files
10454 @cindex files, intermediate
10455 However, even if @file{@var{n}.c} does not exist and is not mentioned,
10456 @code{make} knows how to envision it as the missing link between
10457 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
10458 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
10459 intermediate file, it is entered in the data base as if it had been
10460 mentioned in the makefile, along with the implicit rule that says how to
10461 create it.
10462
10463 Intermediate files are remade using their rules just like all other
10464 files.  But intermediate files are treated differently in two ways.
10465
10466 The first difference is what happens if the intermediate file does not
10467 exist.  If an ordinary file @var{b} does not exist, and @code{make}
10468 considers a target that depends on @var{b}, it invariably creates
10469 @var{b} and then updates the target from @var{b}.  But if @var{b} is
10470 an intermediate file, then @code{make} can leave well enough alone:
10471 it won't create @var{b} unless one of its prerequisites is out of
10472 date.  This means the target depending on @var{b} won't be rebuilt
10473 either, unless there is some other reason to update that target: for
10474 example the target doesn't exist or a different prerequisite is newer
10475 than the target.
10476
10477 The second difference is that if @code{make} @emph{does} create @var{b} in
10478 order to update something else, it deletes @var{b} later on after it is no
10479 longer needed.  Therefore, an intermediate file which did not exist before
10480 @code{make} also does not exist after @code{make}.  @code{make} reports the
10481 deletion to you by printing a @samp{rm} command showing which file it is
10482 deleting.
10483
10484 You can explicitly mark a file as intermediate by listing it as a prerequisite
10485 of the special target @code{.INTERMEDIATE}.  This takes effect even if the
10486 file is mentioned explicitly in some other way.
10487
10488 A file cannot be intermediate if it is mentioned in the makefile as a target
10489 or prerequisite, so one way to avoid the deletion of intermediate files is by
10490 adding it as a prerequisite to some target.  However, doing so can cause make
10491 to do extra work when searching pattern rules (@pxref{Implicit Rule Search,
10492 ,Implicit Rule Search Algorithm}).
10493
10494 As an alternative, listing a file as a prerequisite of the special target
10495 @code{.NOTINTERMEDIATE} forces it to not be considered intermediate (just as
10496 any other mention of the file will do).  Also, listing the target pattern of a
10497 pattern rule as a prerequisite of @code{.NOTINTERMEDIATE} ensures that no
10498 targets generated using that pattern rule are considered intermediate.
10499
10500 You can disable intermediate files completely in your makefile by
10501 providing @code{.NOTINTERMEDIATE} as a target with no prerequisites:
10502 in that case it applies to every file in the makefile.
10503
10504 @cindex intermediate files, preserving
10505 @cindex preserving intermediate files
10506 @cindex secondary files
10507 If you do not want @code{make} to create a file merely because it does
10508 not already exist, but you also do not want @code{make} to
10509 automatically delete the file, you can mark it as a @dfn{secondary}
10510 file.  To do this, list it as a prerequisite of the special target
10511 @code{.SECONDARY}.  Marking a file as secondary also marks it as
10512 intermediate.
10513
10514 A chain can involve more than two implicit rules.  For example, it is
10515 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
10516 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
10517 intermediate files that are deleted at the end.
10518
10519 No single implicit rule can appear more than once in a chain.  This means
10520 that @code{make} will not even consider such a ridiculous thing as making
10521 @file{foo} from @file{foo.o.o} by running the linker twice.  This
10522 constraint has the added benefit of preventing any infinite loop in the
10523 search for an implicit rule chain.
10524
10525 There are some special implicit rules to optimize certain cases that would
10526 otherwise be handled by rule chains.  For example, making @file{foo} from
10527 @file{foo.c} could be handled by compiling and linking with separate
10528 chained rules, using @file{foo.o} as an intermediate file.  But what
10529 actually happens is that a special rule for this case does the compilation
10530 and linking with a single @code{cc} command.  The optimized rule is used in
10531 preference to the step-by-step chain because it comes earlier in the
10532 ordering of rules.
10533
10534 Finally, for performance reasons @code{make} will not consider non-terminal
10535 match-anything rules (i.e., @samp{%:}) when searching for a rule to
10536 build a prerequisite of an implicit rule (@pxref{Match-Anything Rules}).
10537
10538 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
10539 @section Defining and Redefining Pattern Rules
10540
10541 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
10542 rule looks like an ordinary rule, except that its target contains the
10543 character @samp{%} (exactly one of them).  The target is considered a
10544 pattern for matching file names; the @samp{%} can match any nonempty
10545 substring, while other characters match only themselves.  The prerequisites
10546 likewise use @samp{%} to show how their names relate to the target name.
10547
10548 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
10549 @file{@var{stem}.o} from another file @file{@var{stem}.c}.
10550
10551 Note that expansion using @samp{%} in pattern rules occurs
10552 @strong{after} any variable or function expansions, which take place
10553 when the makefile is read.  @xref{Using Variables, , How to Use
10554 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
10555
10556 @menu
10557 * Pattern Intro::               An introduction to pattern rules.
10558 * Pattern Examples::            Examples of pattern rules.
10559 * Automatic Variables::         How to use automatic variables in the
10560                                   recipe of implicit rules.
10561 * Pattern Match::               How patterns match.
10562 * Match-Anything Rules::        Precautions you should take prior to
10563                                   defining rules that can match any
10564                                   target file whatever.
10565 * Canceling Rules::             How to override or cancel built-in rules.
10566 @end menu
10567
10568 @node Pattern Intro, Pattern Examples, Pattern Rules, Pattern Rules
10569 @subsection Introduction to Pattern Rules
10570 @cindex pattern rule
10571 @cindex rule, pattern
10572
10573 A pattern rule contains the character @samp{%} (exactly one of them)
10574 in the target; otherwise, it looks exactly like an ordinary rule.  The
10575 target is a pattern for matching file names; the @samp{%} matches any
10576 nonempty substring, while other characters match only themselves.
10577 @cindex target pattern, implicit
10578 @cindex @code{%}, in pattern rules
10579
10580 For example, @samp{%.c} as a pattern matches any file name that ends in
10581 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
10582 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
10583 (There must be at least one character to match the @samp{%}.)  The substring
10584 that the @samp{%} matches is called the @dfn{stem}.
10585
10586 @samp{%} in a prerequisite of a pattern rule stands for the same stem
10587 that was matched by the @samp{%} in the target.  In order for the
10588 pattern rule to apply, its target pattern must match the file name
10589 under consideration and all of its prerequisites (after pattern
10590 substitution) must name files that exist or can be made.  These files
10591 become prerequisites of the target.
10592 @cindex prerequisite pattern, implicit
10593
10594 Thus, a rule of the form
10595
10596 @example
10597 %.o : %.c ; @var{recipe}@dots{}
10598 @end example
10599
10600 @noindent
10601 specifies how to make a file @file{@var{n}.o}, with another file
10602 @file{@var{n}.c} as its prerequisite, provided that @file{@var{n}.c}
10603 exists or can be made.
10604
10605 There may also be prerequisites that do not use @samp{%}; such a prerequisite
10606 attaches to every file made by this pattern rule.  These unvarying
10607 prerequisites are useful occasionally.
10608
10609 A pattern rule need not have any prerequisites that contain @samp{%}, or
10610 in fact any prerequisites at all.  Such a rule is effectively a general
10611 wildcard.  It provides a way to make any file that matches the target
10612 pattern.  @xref{Last Resort}.
10613
10614 More than one pattern rule may match a target.  In this case
10615 @code{make} will choose the ``best fit'' rule.  @xref{Pattern Match,
10616 ,How Patterns Match}.
10617
10618 @cindex multiple targets, in pattern rule
10619 @cindex target, multiple in pattern rule
10620 Pattern rules may have more than one target; however, every target must
10621 contain a @code{%} character.  Multiple target patterns in pattern rules are
10622 always treated as grouped targets (@pxref{Multiple Targets, , Multiple Targets
10623 in a Rule}) regardless of whether they use the @code{:} or @code{&:}
10624 separator.
10625
10626 There is one exception: if a pattern target is out of date or does
10627 not exist and the makefile does not need to build it, then it will not cause
10628 the other targets to be considered out of date.  Note that this historical
10629 exception will be removed in future versions of GNU @code{make} and should not
10630 be relied on.  If this situation is detected @code{make} will generate a
10631 warning @emph{pattern recipe did not update peer target}; however, @code{make}
10632 cannot detect all such situations.  Please be sure that your recipe updates
10633 @emph{all} the target patterns when it runs.
10634
10635 @node Pattern Examples, Automatic Variables, Pattern Intro, Pattern Rules
10636 @subsection Pattern Rule Examples
10637
10638 Here are some examples of pattern rules actually predefined in
10639 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
10640 files:
10641
10642 @example
10643 %.o : %.c
10644         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
10645 @end example
10646
10647 @noindent
10648 defines a rule that can make any file @file{@var{x}.o} from
10649 @file{@var{x}.c}.  The recipe uses the automatic variables @samp{$@@} and
10650 @samp{$<} to substitute the names of the target file and the source file
10651 in each case where the rule applies (@pxref{Automatic Variables}).
10652
10653 Here is a second built-in rule:
10654
10655 @example
10656 % :: RCS/%,v
10657         $(CO) $(COFLAGS) $<
10658 @end example
10659
10660 @noindent
10661 defines a rule that can make any file @file{@var{x}} whatsoever from a
10662 corresponding file @file{@var{x},v} in the sub-directory @file{RCS}.  Since
10663 the target is @samp{%}, this rule will apply to any file whatever, provided
10664 the appropriate prerequisite file exists.  The double colon makes the rule
10665 @dfn{terminal}, which means that its prerequisite may not be an intermediate
10666 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).
10667
10668 @need 500
10669 This pattern rule has two targets:
10670
10671 @example
10672 @group
10673 %.tab.c %.tab.h: %.y
10674         bison -d $<
10675 @end group
10676 @end example
10677
10678 @noindent
10679 @c The following paragraph is rewritten to avoid overfull hboxes
10680 This tells @code{make} that the recipe @samp{bison -d @var{x}.y} will
10681 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
10682 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
10683 and the file @file{scan.o} depends on the file @file{parse.tab.h},
10684 when @file{parse.y} is changed, the recipe @samp{bison -d parse.y}
10685 will be executed only once, and the prerequisites of both
10686 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
10687 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
10688 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
10689 linked from @file{parse.tab.o}, @file{scan.o}, and its other
10690 prerequisites, and it will execute happily ever after.)
10691
10692 @node Automatic Variables, Pattern Match, Pattern Examples, Pattern Rules
10693 @subsection Automatic Variables
10694 @cindex automatic variables
10695 @cindex variables, automatic
10696 @cindex variables, and implicit rule
10697
10698 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
10699 @samp{.o} file: how do you write the @samp{cc} command so that it operates
10700 on the right source file name?  You cannot write the name in the recipe,
10701 because the name is different each time the implicit rule is applied.
10702
10703 What you do is use a special feature of @code{make}, the @dfn{automatic
10704 variables}.  These variables have values computed afresh for each rule that
10705 is executed, based on the target and prerequisites of the rule.  In this
10706 example, you would use @samp{$@@} for the object file name and @samp{$<}
10707 for the source file name.
10708
10709 @cindex automatic variables in prerequisites
10710 @cindex prerequisites, and automatic variables
10711 It's very important that you recognize the limited scope in which
10712 automatic variable values are available: they only have values within
10713 the recipe.  In particular, you cannot use them anywhere
10714 within the target list of a rule; they have no value there and will
10715 expand to the empty string.  Also, they cannot be accessed directly
10716 within the prerequisite list of a rule.  A common mistake is
10717 attempting to use @code{$@@} within the prerequisites list; this will
10718 not work.  However, there is a special feature of GNU @code{make},
10719 secondary expansion (@pxref{Secondary Expansion}), which will allow
10720 automatic variable values to be used in prerequisite lists.
10721
10722 Here is a table of automatic variables:
10723
10724 @table @code
10725 @vindex $@@
10726 @vindex @@ @r{(automatic variable)}
10727 @item $@@
10728 The file name of the target of the rule.  If the target is an archive
10729 member, then @samp{$@@} is the name of the archive file.  In a pattern
10730 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
10731 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
10732 rule's recipe to be run.
10733
10734 @vindex $%
10735 @vindex % @r{(automatic variable)}
10736 @item $%
10737 The target member name, when the target is an archive member.
10738 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
10739 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
10740 empty when the target is not an archive member.
10741
10742 @vindex $<
10743 @vindex < @r{(automatic variable)}
10744 @item $<
10745 The name of the first prerequisite.  If the target got its recipe from
10746 an implicit rule, this will be the first prerequisite added by the
10747 implicit rule (@pxref{Implicit Rules}).
10748
10749 @vindex $?
10750 @vindex ? @r{(automatic variable)}
10751 @item $?
10752 The names of all the prerequisites that are newer than the target, with
10753 spaces between them.  If the target does not exist, all prerequisites
10754 will be included.  For prerequisites which are archive members, only the
10755 named member is used (@pxref{Archives}).
10756
10757 @samp{$?} is useful even in explicit rules when you wish to operate on only
10758 the prerequisites that have changed.  For example, suppose that an archive
10759 named @file{lib} is supposed to contain copies of several object files.
10760 This rule copies just the changed object files into the archive:
10761
10762 @example
10763 @group
10764 lib: foo.o bar.o lose.o win.o
10765         ar r lib $?
10766 @end group
10767 @end example
10768 @cindex prerequisites, list of changed
10769 @cindex list of changed prerequisites
10770
10771 @vindex $^
10772 @vindex ^ @r{(automatic variable)}
10773 @item $^
10774 The names of all the prerequisites, with spaces between them.  For
10775 prerequisites which are archive members, only the named member is used
10776 (@pxref{Archives}).  A target has only one prerequisite on each other file
10777 it depends on, no matter how many times each file is listed as a
10778 prerequisite.  So if you list a prerequisite more than once for a target,
10779 the value of @code{$^} contains just one copy of the name.  This list
10780 does @strong{not} contain any of the order-only prerequisites; for those
10781 see the @samp{$|} variable, below.
10782 @cindex prerequisites, list of all
10783 @cindex list of all prerequisites
10784
10785 @vindex $+
10786 @vindex + @r{(automatic variable)}
10787 @item $+
10788 This is like @samp{$^}, but prerequisites listed more than once are
10789 duplicated in the order they were listed in the makefile.  This is
10790 primarily useful for use in linking commands where it is meaningful to
10791 repeat library file names in a particular order.
10792
10793 @vindex $|
10794 @vindex | @r{(automatic variable)}
10795 @item $|
10796 The names of all the order-only prerequisites, with spaces between
10797 them.
10798
10799 @vindex $*
10800 @vindex * @r{(automatic variable)}
10801 @item $*
10802 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
10803 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
10804 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
10805 useful for constructing names of related files.
10806 @cindex stem, variable for
10807
10808 In a static pattern rule, the stem is part of the file name that matched
10809 the @samp{%} in the target pattern.
10810
10811 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
10812 in that way.  Instead, if the target name ends with a recognized suffix
10813 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
10814 the target name minus the suffix.  For example, if the target name is
10815 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
10816 suffix.  GNU @code{make} does this bizarre thing only for compatibility
10817 with other implementations of @code{make}.  You should generally avoid
10818 using @samp{$*} except in implicit rules or static pattern rules.
10819
10820 If the target name in an explicit rule does not end with a recognized
10821 suffix, @samp{$*} is set to the empty string for that rule.
10822 @end table
10823
10824 Of the variables listed above, four have values that are single file
10825 names, and three have values that are lists of file names.  These
10826 seven have variants that get just the file's directory name or just
10827 the file name within the directory.  The variant variables' names are
10828 formed by appending @samp{D} or @samp{F}, respectively.  The functions
10829 @code{dir} and @code{notdir} can be used to obtain a similar effect
10830 (@pxref{File Name Functions, , Functions for File Names}).  Note,
10831 however, that the @samp{D} variants all omit the trailing slash which
10832 always appears in the output of the @code{dir} function.  Here is a
10833 table of the variants:
10834
10835 @table @samp
10836 @vindex $(@@D)
10837 @vindex @@D @r{(automatic variable)}
10838 @item $(@@D)
10839 The directory part of the file name of the target, with the trailing
10840 slash removed.  If the value of @samp{$@@} is @file{dir/foo.o} then
10841 @samp{$(@@D)} is @file{dir}.  This value is @file{.} if @samp{$@@} does
10842 not contain a slash.
10843
10844 @vindex $(@@F)
10845 @vindex @@F @r{(automatic variable)}
10846 @item $(@@F)
10847 The file-within-directory part of the file name of the target.  If the
10848 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
10849 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
10850
10851 @vindex $(*D)
10852 @vindex *D @r{(automatic variable)}
10853 @item $(*D)
10854 @vindex $(*F)
10855 @vindex *F @r{(automatic variable)}
10856 @itemx $(*F)
10857 The directory part and the file-within-directory
10858 part of the stem; @file{dir} and @file{foo} in this example.
10859
10860 @vindex $(%D)
10861 @vindex %D @r{(automatic variable)}
10862 @item $(%D)
10863 @vindex $(%F)
10864 @vindex %F @r{(automatic variable)}
10865 @itemx $(%F)
10866 The directory part and the file-within-directory part of the target
10867 archive member name.  This makes sense only for archive member targets
10868 of the form @file{@var{archive}(@var{member})} and is useful only when
10869 @var{member} may contain a directory name.  (@xref{Archive Members,
10870 ,Archive Members as Targets}.)
10871
10872 @vindex $(<D)
10873 @vindex <D @r{(automatic variable)}
10874 @item $(<D)
10875 @vindex $(<F)
10876 @vindex <F @r{(automatic variable)}
10877 @itemx $(<F)
10878 The directory part and the file-within-directory
10879 part of the first prerequisite.
10880
10881 @vindex $(^D)
10882 @vindex ^D @r{(automatic variable)}
10883 @item $(^D)
10884 @vindex $(^F)
10885 @vindex ^F @r{(automatic variable)}
10886 @itemx $(^F)
10887 Lists of the directory parts and the file-within-directory
10888 parts of all prerequisites.
10889
10890 @vindex $(+D)
10891 @vindex +D @r{(automatic variable)}
10892 @item $(+D)
10893 @vindex $(+F)
10894 @vindex +F @r{(automatic variable)}
10895 @itemx $(+F)
10896 Lists of the directory parts and the file-within-directory
10897 parts of all prerequisites, including multiple instances of duplicated
10898 prerequisites.
10899
10900 @vindex $(?D)
10901 @vindex ?D @r{(automatic variable)}
10902 @item $(?D)
10903 @vindex $(?F)
10904 @vindex ?F @r{(automatic variable)}
10905 @itemx $(?F)
10906 Lists of the directory parts and the file-within-directory parts of
10907 all prerequisites that are newer than the target.
10908 @end table
10909
10910 Note that we use a special stylistic convention when we talk about these
10911 automatic variables; we write ``the value of @samp{$<}'', rather than
10912 @w{``the variable @code{<}''} as we would write for ordinary variables
10913 such as @code{objects} and @code{CFLAGS}.  We think this convention
10914 looks more natural in this special case.  Please do not assume it has a
10915 deep significance; @samp{$<} refers to the variable named @code{<} just
10916 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
10917 You could just as well use @samp{$(<)} in place of @samp{$<}.
10918
10919 @node Pattern Match, Match-Anything Rules, Automatic Variables, Pattern Rules
10920 @subsection How Patterns Match
10921
10922 @cindex stem
10923 A target pattern is composed of a @samp{%} between a prefix and a suffix,
10924 either or both of which may be empty.  The pattern matches a file name only
10925 if the file name starts with the prefix and ends with the suffix, without
10926 overlap.  The text between the prefix and the suffix is called the
10927 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
10928 @file{test.o}, the stem is @samp{test}.  The pattern rule prerequisites are
10929 turned into actual file names by substituting the stem for the character
10930 @samp{%}.  Thus, if in the same example one of the prerequisites is written
10931 as @samp{%.c}, it expands to @samp{test.c}.
10932
10933 When the target pattern does not contain a slash (and it usually does
10934 not), directory names in the file names are removed from the file name
10935 before it is compared with the target prefix and suffix.  After the
10936 comparison of the file name to the target pattern, the directory
10937 names, along with the slash that ends them, are added on to the
10938 prerequisite file names generated from the pattern rule's prerequisite
10939 patterns and the file name.  The directories are ignored only for the
10940 purpose of finding an implicit rule to use, not in the application of
10941 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
10942 with @samp{src/a} as the stem.  When prerequisites are turned into file
10943 names, the directories from the stem are added at the front, while the
10944 rest of the stem is substituted for the @samp{%}.  The stem
10945 @samp{src/a} with a prerequisite pattern @samp{c%r} gives the file name
10946 @file{src/car}.
10947
10948 @cindex pattern rules, order of
10949 @cindex order of pattern rules
10950 A pattern rule can be used to build a given file only if there is a
10951 target pattern that matches the file name, @emph{and} all
10952 prerequisites in that rule either exist or can be built.  The rules
10953 you write take precedence over those that are built in. Note however,
10954 that a rule which can be satisfied without chaining other implicit
10955 rules (for example, one which has no prerequisites or its
10956 prerequisites already exist or are mentioned) always takes priority
10957 over a rule with prerequisites that must be made by chaining other
10958 implicit rules.
10959
10960 @cindex stem, shortest
10961 It is possible that more than one pattern rule will meet these
10962 criteria.  In that case, @code{make} will choose the rule with the
10963 shortest stem (that is, the pattern that matches most specifically).
10964 If more than one pattern rule has the shortest stem, @code{make} will
10965 choose the first one found in the makefile.
10966
10967 This algorithm results in more specific rules being preferred over
10968 more generic ones; for example:
10969
10970 @example
10971 %.o: %.c
10972         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
10973
10974 %.o : %.f
10975         $(COMPILE.F) $(OUTPUT_OPTION) $<
10976
10977 lib/%.o: lib/%.c
10978         $(CC) -fPIC -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
10979 @end example
10980
10981 Given these rules and asked to build @file{bar.o} where both
10982 @file{bar.c} and @file{bar.f} exist, @code{make} will choose the first
10983 rule and compile @file{bar.c} into @file{bar.o}.  In the same
10984 situation where @file{bar.c} does not exist, then @code{make} will
10985 choose the second rule and compile @file{bar.f} into @file{bar.o}.
10986
10987 If @code{make} is asked to build @file{lib/bar.o} and both
10988 @file{lib/bar.c} and @file{lib/bar.f} exist, then the third rule will
10989 be chosen since the stem for this rule (@samp{bar}) is shorter than
10990 the stem for the first rule (@samp{lib/bar}).  If @file{lib/bar.c}
10991 does not exist then the third rule is not eligible and the second rule
10992 will be used, even though the stem is longer.
10993
10994 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
10995 @subsection Match-Anything Pattern Rules
10996
10997 @cindex match-anything rule
10998 @cindex terminal rule
10999 When a pattern rule's target is just @samp{%}, it matches any file name
11000 whatever.  We call these rules @dfn{match-anything} rules.  They are very
11001 useful, but it can take a lot of time for @code{make} to think about them,
11002 because it must consider every such rule for each file name listed either
11003 as a target or as a prerequisite.
11004
11005 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
11006 would have to consider making it by linking an object file @file{foo.c.o},
11007 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
11008 Pascal compilation-and-linking from @file{foo.c.p}, and many other
11009 possibilities.
11010
11011 We know these possibilities are ridiculous since @file{foo.c} is a C source
11012 file, not an executable.  If @code{make} did consider these possibilities,
11013 it would ultimately reject them, because files such as @file{foo.c.o} and
11014 @file{foo.c.p} would not exist.  But these possibilities are so
11015 numerous that @code{make} would run very slowly if it had to consider
11016 them.
11017
11018 To gain speed, we have put various constraints on the way @code{make}
11019 considers match-anything rules.  There are two different constraints that
11020 can be applied, and each time you define a match-anything rule you must
11021 choose one or the other for that rule.
11022
11023 One choice is to mark the match-anything rule as @dfn{terminal} by defining
11024 it with a double colon.  When a rule is terminal, it does not apply unless
11025 its prerequisites actually exist.  Prerequisites that could be made with
11026 other implicit rules are not good enough.  In other words, no further
11027 chaining is allowed beyond a terminal rule.
11028
11029 For example, the built-in implicit rules for extracting sources from RCS
11030 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
11031 not exist, @code{make} will not even consider trying to make it as an
11032 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
11033 RCS and SCCS files are generally ultimate source files, which should not be
11034 remade from any other files; therefore, @code{make} can save time by not
11035 looking for ways to remake them.
11036
11037 If you do not mark the match-anything rule as terminal, then it is
11038 non-terminal.  A non-terminal match-anything rule cannot apply to a
11039 prerequisite of an implicit rule, or to a file name that indicates a
11040 specific type of data.  A file name indicates a specific type of data
11041 if some non-match-anything implicit rule target matches it.
11042
11043 For example, the file name @file{foo.c} matches the target for the pattern
11044 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
11045 rule is actually applicable (which happens only if there is a file
11046 @file{foo.y}), the fact that its target matches is enough to prevent
11047 consideration of any non-terminal match-anything rules for the file
11048 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
11049 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
11050 @file{foo.c.p}, etc.
11051
11052 The motivation for this constraint is that non-terminal match-anything
11053 rules are used for making files containing specific types of data (such as
11054 executable files) and a file name with a recognized suffix indicates some
11055 other specific type of data (such as a C source file).
11056
11057 Special built-in dummy pattern rules are provided solely to recognize
11058 certain file names so that non-terminal match-anything rules will not be
11059 considered.  These dummy rules have no prerequisites and no recipes, and
11060 they are ignored for all other purposes.  For example, the built-in
11061 implicit rule
11062
11063 @example
11064 %.p :
11065 @end example
11066
11067 @noindent
11068 exists to make sure that Pascal source files such as @file{foo.p} match a
11069 specific target pattern and thereby prevent time from being wasted looking
11070 for @file{foo.p.o} or @file{foo.p.c}.
11071
11072 Dummy pattern rules such as the one for @samp{%.p} are made for every
11073 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
11074
11075 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
11076 @subsection Canceling Implicit Rules
11077
11078 You can override a built-in implicit rule (or one you have defined
11079 yourself) by defining a new pattern rule with the same target and
11080 prerequisites, but a different recipe.  When the new rule is defined, the
11081 built-in one is replaced.  The new rule's position in the sequence of
11082 implicit rules is determined by where you write the new rule.
11083
11084 You can cancel a built-in implicit rule by defining a pattern rule with the
11085 same target and prerequisites, but no recipe.  For example, the following
11086 would cancel the rule that runs the assembler:
11087
11088 @example
11089 %.o : %.s
11090 @end example
11091
11092 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
11093 @section Defining Last-Resort Default Rules
11094 @cindex last-resort default rules
11095 @cindex default rules, last-resort
11096
11097 You can define a last-resort implicit rule by writing a terminal
11098 match-anything pattern rule with no prerequisites (@pxref{Match-Anything
11099 Rules}).  This is just like any other pattern rule; the only thing
11100 special about it is that it will match any target.  So such a rule's
11101 recipe is used for all targets and prerequisites that have no recipe
11102 of their own and for which no other implicit rule applies.
11103
11104 For example, when testing a makefile, you might not care if the source
11105 files contain real data, only that they exist.  Then you might do this:
11106
11107 @example
11108 %::
11109         touch $@@
11110 @end example
11111
11112 @noindent
11113 to cause all the source files needed (as prerequisites) to be created
11114 automatically.
11115
11116 @findex .DEFAULT
11117 You can instead define a recipe to be used for targets for which there
11118 are no rules at all, even ones which don't specify recipes.  You do
11119 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
11120 recipe is used for all prerequisites which do not appear as targets in
11121 any explicit rule, and for which no implicit rule applies.  Naturally,
11122 there is no @code{.DEFAULT} rule unless you write one.
11123
11124 If you use @code{.DEFAULT} with no recipe or prerequisites:
11125
11126 @example
11127 .DEFAULT:
11128 @end example
11129
11130 @noindent
11131 the recipe previously stored for @code{.DEFAULT} is cleared.  Then
11132 @code{make} acts as if you had never defined @code{.DEFAULT} at all.
11133
11134 If you do not want a target to get the recipe from a match-anything
11135 pattern rule or @code{.DEFAULT}, but you also do not want any recipe
11136 to be run for the target, you can give it an empty recipe
11137 (@pxref{Empty Recipes, ,Defining Empty Recipes}).
11138
11139 You can use a last-resort rule to override part of another makefile.
11140 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
11141
11142 @node Suffix Rules, Implicit Rule Search, Last Resort, Implicit Rules
11143 @section Old-Fashioned Suffix Rules
11144 @cindex old-fashioned suffix rules
11145 @cindex suffix rule
11146
11147 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
11148 @code{make}.  Suffix rules are obsolete because pattern rules are more
11149 general and clearer.  They are supported in GNU @code{make} for
11150 compatibility with old makefiles.  They come in two kinds:
11151 @dfn{double-suffix} and @dfn{single-suffix}.
11152
11153 A double-suffix rule is defined by a pair of suffixes: the target
11154 suffix and the source suffix.  It matches any file whose name ends
11155 with the target suffix.  The corresponding implicit prerequisite is
11156 made by replacing the target suffix with the source suffix in the file
11157 name.  A two-suffix rule @samp{.c.o} (whose target and source suffixes
11158 are @samp{.o} and @samp{.c}) is equivalent to the pattern rule
11159 @samp{%.o : %.c}.
11160
11161 A single-suffix rule is defined by a single suffix, which is the source
11162 suffix.  It matches any file name, and the corresponding implicit
11163 prerequisite name is made by appending the source suffix.  A single-suffix
11164 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
11165 @samp{% : %.c}.
11166
11167 Suffix rule definitions are recognized by comparing each rule's target
11168 against a defined list of known suffixes.  When @code{make} sees a rule
11169 whose target is a known suffix, this rule is considered a single-suffix
11170 rule.  When @code{make} sees a rule whose target is two known suffixes
11171 concatenated, this rule is taken as a double-suffix rule.
11172
11173 For example, @samp{.c} and @samp{.o} are both on the default list of
11174 known suffixes.  Therefore, if you define a rule whose target is
11175 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
11176 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
11177 way to define the rule for compiling a C source file:
11178
11179 @example
11180 .c.o:
11181         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
11182 @end example
11183
11184 Suffix rules cannot have any prerequisites of their own.  If they have any,
11185 they are treated as normal files with funny names, not as suffix rules.
11186 Thus, the rule:
11187
11188 @example
11189 .c.o: foo.h
11190         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
11191 @end example
11192
11193 @noindent
11194 tells how to make the file @file{.c.o} from the prerequisite file
11195 @file{foo.h}, and is not at all like the pattern rule:
11196
11197 @example
11198 %.o: %.c foo.h
11199         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
11200 @end example
11201
11202 @noindent
11203 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
11204 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
11205
11206 Suffix rules with no recipe are also meaningless.  They do not remove
11207 previous rules as do pattern rules with no recipe (@pxref{Canceling
11208 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or
11209 pair of suffixes concatenated as a target in the data base.
11210
11211 @findex .SUFFIXES
11212 The known suffixes are simply the names of the prerequisites of the special
11213 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
11214 for @code{.SUFFIXES} that adds more prerequisites, as in:
11215
11216 @example
11217 .SUFFIXES: .hack .win
11218 @end example
11219
11220 @noindent
11221 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
11222
11223 If you wish to eliminate the default known suffixes instead of just adding
11224 to them, write a rule for @code{.SUFFIXES} with no prerequisites.  By
11225 special dispensation, this eliminates all existing prerequisites of
11226 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
11227 want.  For example,
11228
11229 @example
11230 @group
11231 .SUFFIXES:            # @r{Delete the default suffixes}
11232 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
11233 @end group
11234 @end example
11235
11236 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
11237 list of suffixes to be empty.
11238
11239 @vindex SUFFIXES
11240 The variable @code{SUFFIXES} is defined to the default list of suffixes
11241 before @code{make} reads any makefiles.  You can change the list of suffixes
11242 with a rule for the special target @code{.SUFFIXES}, but that does not alter
11243 this variable.
11244
11245 @node Implicit Rule Search,  , Suffix Rules, Implicit Rules
11246 @section Implicit Rule Search Algorithm
11247 @cindex implicit rule, search algorithm
11248 @cindex search algorithm, implicit rule
11249
11250 Here is the procedure @code{make} uses for searching for an implicit rule
11251 for a target @var{t}.  This procedure is followed for each double-colon
11252 rule with no recipe, for each target of ordinary rules none of which have
11253 a recipe, and for each prerequisite that is not the target of any rule.  It
11254 is also followed recursively for prerequisites that come from implicit
11255 rules, in the search for a chain of rules.
11256
11257 Suffix rules are not mentioned in this algorithm because suffix rules are
11258 converted to equivalent pattern rules once the makefiles have been read in.
11259
11260 For an archive member target of the form
11261 @samp{@var{archive}(@var{member})}, the following algorithm is run
11262 twice, first using the entire target name @var{t}, and second using
11263 @samp{(@var{member})} as the target @var{t} if the first run found no
11264 rule.
11265
11266 @enumerate
11267 @item
11268 Split @var{t} into a directory part, called @var{d}, and the rest,
11269 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
11270 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.
11271
11272 @item
11273 Make a list of all the pattern rules one of whose targets matches
11274 @var{t} or @var{n}.  If the target pattern contains a slash, it is
11275 matched against @var{t}; otherwise, against @var{n}.
11276
11277 @item
11278 If any rule in that list is @emph{not} a match-anything rule, or if
11279 @var{t} is a prerequisite of an implicit rule, then remove all
11280 non-terminal match-anything rules from the list.
11281
11282 @item
11283 Remove from the list all rules with no recipe.
11284
11285 @item
11286 For each pattern rule in the list:
11287
11288 @enumerate a
11289 @item
11290 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
11291 matched by the @samp{%} in the target pattern.
11292
11293 @item
11294 Compute the prerequisite names by substituting @var{s} for @samp{%}; if
11295 the target pattern does not contain a slash, append @var{d} to
11296 the front of each prerequisite name.
11297
11298 @item
11299 Test whether all the prerequisites exist or ought to exist.  (If a
11300 file name is mentioned in the makefile as a target or as an explicit
11301 prerequisite of target T, then we say it ought to exist.)
11302
11303 If all prerequisites exist or ought to exist, or there are no prerequisites,
11304 then this rule applies.
11305 @end enumerate
11306
11307 @item
11308 If no pattern rule has been found so far, try harder.
11309 For each pattern rule in the list:
11310
11311 @enumerate a
11312 @item
11313 If the rule is terminal, ignore it and go on to the next rule.
11314
11315 @item
11316 Compute the prerequisite names as before.
11317
11318 @item
11319 Test whether all the prerequisites exist or ought to exist.
11320
11321 @item
11322 For each prerequisite that does not exist, follow this algorithm
11323 recursively to see if the prerequisite can be made by an implicit
11324 rule.
11325
11326 @item
11327 If all prerequisites exist, ought to exist, or can be
11328 made by implicit rules, then this rule applies.
11329 @end enumerate
11330
11331 @item
11332 If no pattern rule has been found then try step 5 and step 6 again with a
11333 modified definition of ``ought to exist'': if a filename is mentioned as a
11334 target or as an explicit prerequisite of @emph{any} target, then it ought to
11335 exist.  This check is only present for backward-compatibility with older
11336 versions of GNU make: we don't recommend relying on it.
11337
11338 @item
11339 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
11340 applies.  In that case, give @var{t} the same recipe that
11341 @code{.DEFAULT} has.  Otherwise, there is no recipe for @var{t}.
11342 @end enumerate
11343
11344 Once a rule that applies has been found, for each target pattern of
11345 the rule other than the one that matched @var{t} or @var{n}, the
11346 @samp{%} in the pattern is replaced with @var{s} and the resultant
11347 file name is stored until the recipe to remake the target file @var{t}
11348 is executed.  After the recipe is executed, each of these stored file
11349 names are entered into the data base and marked as having been updated
11350 and having the same update status as the file @var{t}.
11351
11352 When the recipe of a pattern rule is executed for @var{t}, the
11353 automatic variables are set corresponding to the target and
11354 prerequisites.  @xref{Automatic Variables}.
11355
11356 @node Archives, Extending make, Implicit Rules, Top
11357 @chapter Using @code{make} to Update Archive Files
11358 @cindex archive
11359
11360 @dfn{Archive files} are files containing named sub-files called
11361 @dfn{members}; they are maintained with the program @code{ar} and their
11362 main use is as subroutine libraries for linking.
11363
11364 @menu
11365 * Archive Members::             Archive members as targets.
11366 * Archive Update::              The implicit rule for archive member targets.
11367 * Archive Pitfalls::            Dangers to watch out for when using archives.
11368 * Archive Suffix Rules::        You can write a special kind of suffix rule
11369                                   for updating archives.
11370 @end menu
11371
11372 @node Archive Members, Archive Update, Archives, Archives
11373 @section Archive Members as Targets
11374 @cindex archive member targets
11375
11376 An individual member of an archive file can be used as a target or
11377 prerequisite in @code{make}.  You specify the member named @var{member} in
11378 archive file @var{archive} as follows:
11379
11380 @example
11381 @var{archive}(@var{member})
11382 @end example
11383
11384 @noindent
11385 This construct is available only in targets and prerequisites, not in
11386 recipes!  Most programs that you might use in recipes do not support
11387 this syntax and cannot act directly on archive members.  Only
11388 @code{ar} and other programs specifically designed to operate on
11389 archives can do so.  Therefore, valid recipes to update an archive
11390 member target probably must use @code{ar}.  For example, this rule
11391 says to create a member @file{hack.o} in archive @file{foolib} by
11392 copying the file @file{hack.o}:
11393
11394 @example
11395 foolib(hack.o) : hack.o
11396         ar cr foolib hack.o
11397 @end example
11398
11399 In fact, nearly all archive member targets are updated in just this way
11400 and there is an implicit rule to do it for you.  @strong{Please note:} The
11401 @samp{c} flag to @code{ar} is required if the archive file does not
11402 already exist.
11403
11404 To specify several members in the same archive, you can write all the
11405 member names together between the parentheses.  For example:
11406
11407 @example
11408 foolib(hack.o kludge.o)
11409 @end example
11410
11411 @noindent
11412 is equivalent to:
11413
11414 @example
11415 foolib(hack.o) foolib(kludge.o)
11416 @end example
11417
11418 @cindex wildcard, in archive member
11419 You can also use shell-style wildcards in an archive member reference.
11420 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
11421 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
11422 @file{foolib} archive whose names end in @samp{.o}; perhaps
11423 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
11424
11425 @node Archive Update, Archive Pitfalls, Archive Members, Archives
11426 @section Implicit Rule for Archive Member Targets
11427
11428 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
11429 member named @var{m} in the archive file @var{a}.
11430
11431 When @code{make} looks for an implicit rule for such a target, as a special
11432 feature it considers implicit rules that match @file{(@var{m})}, as well as
11433 those that match the actual target @file{@var{a}(@var{m})}.
11434
11435 This causes one special rule whose target is @file{(%)} to match.  This
11436 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
11437 into the archive.  For example, it will update the archive member target
11438 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
11439 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
11440
11441 When this rule is chained with others, the result is very powerful.
11442 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
11443 @samp{(} and @samp{)} from being interpreted specially by the shell) in
11444 the presence of a file @file{bar.c} is enough to cause the following
11445 recipe to be run, even without a makefile:
11446
11447 @example
11448 cc -c bar.c -o bar.o
11449 ar r foo.a bar.o
11450 rm -f bar.o
11451 @end example
11452
11453 @noindent
11454 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
11455 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
11456
11457 Implicit rules such as this one are written using the automatic variable
11458 @samp{$%}.  @xref{Automatic Variables}.
11459
11460 An archive member name in an archive cannot contain a directory name, but
11461 it may be useful in a makefile to pretend that it does.  If you write an
11462 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
11463 automatic updating with this recipe:
11464
11465 @example
11466 ar r foo.a dir/file.o
11467 @end example
11468
11469 @noindent
11470 which has the effect of copying the file @file{dir/file.o} into a member
11471 named @file{file.o}.  In connection with such usage, the automatic variables
11472 @code{%D} and @code{%F} may be useful.
11473
11474 @menu
11475 * Archive Symbols::             How to update archive symbol directories.
11476 @end menu
11477
11478 @node Archive Symbols,  , Archive Update, Archive Update
11479 @subsection Updating Archive Symbol Directories
11480 @cindex @code{__.SYMDEF}
11481 @cindex updating archive symbol directories
11482 @cindex archive symbol directory updating
11483 @cindex symbol directories, updating archive
11484 @cindex directories, updating archive symbol
11485
11486 An archive file that is used as a library usually contains a special member
11487 named @file{__.SYMDEF} that contains a directory of the external symbol
11488 names defined by all the other members.  After you update any other
11489 members, you need to update @file{__.SYMDEF} so that it will summarize the
11490 other members properly.  This is done by running the @code{ranlib} program:
11491
11492 @example
11493 ranlib @var{archivefile}
11494 @end example
11495
11496 Normally you would put this command in the rule for the archive file,
11497 and make all the members of the archive file prerequisites of that rule.
11498 For example,
11499
11500 @example
11501 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
11502         ranlib libfoo.a
11503 @end example
11504
11505 @noindent
11506 The effect of this is to update archive members @file{x.o}, @file{y.o},
11507 etc., and then update the symbol directory member @file{__.SYMDEF} by
11508 running @code{ranlib}.  The rules for updating the members are not shown
11509 here; most likely you can omit them and use the implicit rule which copies
11510 files into the archive, as described in the preceding section.
11511
11512 This is not necessary when using the GNU @code{ar} program, which
11513 updates the @file{__.SYMDEF} member automatically.
11514
11515 @node Archive Pitfalls, Archive Suffix Rules, Archive Update, Archives
11516 @section Dangers When Using Archives
11517 @cindex archive, and parallel execution
11518 @cindex parallel execution, and archive update
11519 @cindex archive, and @code{-j}
11520 @cindex @code{-j}, and archive update
11521
11522 It is important to be careful when using parallel execution (the
11523 @code{-j} switch; @pxref{Parallel, ,Parallel Execution}) and archives.
11524 If multiple @code{ar} commands run at the same time on the same archive
11525 file, they will not know about each other and can corrupt the file.
11526
11527 Possibly a future version of @code{make} will provide a mechanism to
11528 circumvent this problem by serializing all recipes that operate on the
11529 same archive file.  But for the time being, you must either write your
11530 makefiles to avoid this problem in some other way, or not use @code{-j}.
11531
11532 @node Archive Suffix Rules,  , Archive Pitfalls, Archives
11533 @section Suffix Rules for Archive Files
11534 @cindex suffix rule, for archive
11535 @cindex archive, suffix rule for
11536 @cindex library archive, suffix rule for
11537 @cindex @code{.a} (archives)
11538
11539 You can write a special kind of suffix rule for dealing with archive
11540 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
11541 Archive suffix rules are obsolete in GNU @code{make}, because pattern
11542 rules for archives are a more general mechanism (@pxref{Archive
11543 Update}).  But they are retained for compatibility with other
11544 @code{make}s.
11545
11546 To write a suffix rule for archives, you simply write a suffix rule
11547 using the target suffix @samp{.a} (the usual suffix for archive files).
11548 For example, here is the old-fashioned suffix rule to update a library
11549 archive from C source files:
11550
11551 @example
11552 @group
11553 .c.a:
11554         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
11555         $(AR) r $@@ $*.o
11556         $(RM) $*.o
11557 @end group
11558 @end example
11559
11560 @noindent
11561 This works just as if you had written the pattern rule:
11562
11563 @example
11564 @group
11565 (%.o): %.c
11566         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
11567         $(AR) r $@@ $*.o
11568         $(RM) $*.o
11569 @end group
11570 @end example
11571
11572 In fact, this is just what @code{make} does when it sees a suffix rule
11573 with @samp{.a} as the target suffix.  Any double-suffix rule
11574 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
11575 pattern @samp{(%.o)} and a prerequisite pattern of @samp{%.@var{x}}.
11576
11577 Since you might want to use @samp{.a} as the suffix for some other kind
11578 of file, @code{make} also converts archive suffix rules to pattern rules
11579 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
11580 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
11581 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.
11582
11583 @node Extending make, Integrating make, Archives, Top
11584 @chapter Extending GNU @code{make}
11585 @cindex make extensions
11586
11587 GNU @code{make} provides many advanced capabilities, including many
11588 useful functions.  However, it does not contain a complete programming
11589 language and so it has limitations.  Sometimes these limitations can be
11590 overcome through use of the @code{shell} function to invoke a separate
11591 program, although this can be inefficient.
11592
11593 In cases where the built-in capabilities of GNU @code{make} are
11594 insufficient to your requirements there are two options for extending
11595 @code{make}.  On systems where it's provided, you can utilize GNU
11596 Guile as an embedded scripting language (@pxref{Guile Integration,,GNU
11597 Guile Integration}).  On systems which support dynamically loadable
11598 objects, you can write your own extension in any language (which can
11599 be compiled into such an object) and load it to provide extended
11600 capabilities (@pxref{load Directive, ,The @code{load} Directive}).
11601
11602 @menu
11603 * Guile Integration::           Using Guile as an embedded scripting language.
11604 * Loading Objects::             Loading dynamic objects as extensions.
11605 @end menu
11606
11607 @node Guile Integration, Loading Objects, Extending make, Extending make
11608 @section GNU Guile Integration
11609 @cindex Guile
11610 @cindex extensions, Guile
11611
11612 GNU @code{make} may be built with support for GNU Guile as an embedded
11613 extension language.  Guile implements the Scheme language.  A review
11614 of GNU Guile and the Scheme language and its features is beyond the
11615 scope of this manual: see the documentation for GNU Guile and Scheme.
11616
11617 You can determine if @code{make} contains support for Guile by
11618 examining the @code{.FEATURES} variable; it will contain the word
11619 @var{guile} if Guile support is available.
11620
11621 The Guile integration provides one new @code{make} function: @code{guile}.
11622 The @code{guile} function takes one argument which is first expanded
11623 by @code{make} in the normal fashion, then passed to the GNU Guile
11624 evaluator.  The result of the evaluator is converted into a string and
11625 used as the expansion of the @code{guile} function in the makefile.
11626
11627 In addition, GNU @code{make} exposes Guile procedures for use in Guile
11628 scripts.
11629
11630 @menu
11631 * Guile Types::                 Converting Guile types to @code{make} strings.
11632 * Guile Interface::             Invoking @code{make} functions from Guile.
11633 * Guile Example::               Example using Guile in @code{make}.
11634 @end menu
11635
11636 @node Guile Types, Guile Interface, Guile Integration, Guile Integration
11637 @subsection Conversion of Guile Types
11638 @cindex convert guile types
11639 @cindex guile, conversion of types
11640 @cindex types, conversion of
11641
11642 There is only one ``data type'' in @code{make}: a string.  GNU Guile,
11643 on the other hand, provides a rich variety of different data types.
11644 An important aspect of the interface between @code{make} and GNU Guile
11645 is the conversion of Guile data types into @code{make} strings.
11646
11647 This conversion is relevant in two places: when a makefile invokes the
11648 @code{guile} function to evaluate a Guile expression, the result of
11649 that evaluation must be converted into a make string so it can be
11650 further evaluated by @code{make}.  And secondly, when a Guile script
11651 invokes one of the procedures exported by @code{make} the argument
11652 provided to the procedure must be converted into a string.
11653
11654 The conversion of Guile types into @code{make} strings is as below:
11655
11656 @table @code
11657 @item #f
11658 False is converted into the empty string: in @code{make} conditionals
11659 the empty string is considered false.
11660
11661 @item #t
11662 True is converted to the string @samp{#t}: in @code{make} conditionals
11663 any non-empty string is considered true.
11664
11665 @item symbol
11666 @item number
11667 A symbol or number is converted into the string representation of that
11668 symbol or number.
11669
11670 @item character
11671 A printable character is converted to the same character.
11672
11673 @item string
11674 A string containing only printable characters is converted to the same
11675 string.
11676
11677 @item list
11678 A list is converted recursively according to the above rules.  This
11679 implies that any structured list will be flattened (that is, a result
11680 of @samp{'(a b (c d) e)} will be converted to the @code{make} string
11681 @samp{a b c d e}).
11682
11683 @item other
11684 Any other Guile type results in an error.  In future versions of
11685 @code{make}, other Guile types may be converted.
11686
11687 @end table
11688
11689 The translation of @samp{#f} (to the empty string) and @samp{#t} (to
11690 the non-empty string @samp{#t}) is designed to allow you to use Guile
11691 boolean results directly as @code{make} boolean conditions.  For
11692 example:
11693
11694 @example
11695 $(if $(guile (access? "myfile" R_OK)),$(info myfile exists))
11696 @end example
11697
11698 As a consequence of these conversion rules you must consider the
11699 result of your Guile script, as that result will be converted into a
11700 string and parsed by @code{make}.  If there is no natural result for
11701 the script (that is, the script exists solely for its side-effects),
11702 you should add @samp{#f} as the final expression in order to avoid
11703 syntax errors in your makefile.
11704
11705 @node Guile Interface, Guile Example, Guile Types, Guile Integration
11706 @subsection Interfaces from Guile to @code{make}
11707 @cindex make interface to guile
11708 @cindex make procedures in guile
11709
11710 In addition to the @code{guile} function available in makefiles,
11711 @code{make} exposes some procedures for use in your Guile scripts.  At
11712 startup @code{make} creates a new Guile module, @code{gnu make}, and
11713 exports these procedures as public interfaces from that module:
11714
11715 @table @code
11716 @item gmk-expand
11717 @findex gmk-expand
11718 This procedure takes a single argument which is converted into a
11719 string.  The string is expanded by @code{make} using normal
11720 @code{make} expansion rules.  The result of the expansion is converted
11721 into a Guile string and provided as the result of the procedure.
11722
11723 @item gmk-eval
11724 @findex gmk-eval
11725 This procedure takes a single argument which is converted into a
11726 string.  The string is evaluated by @code{make} as if it were a
11727 makefile.  This is the same capability available via the @code{eval}
11728 function (@pxref{Eval Function}).  The result of the @code{gmk-eval}
11729 procedure is always the empty string.
11730
11731 Note that @code{gmk-eval} is not quite the same as using
11732 @code{gmk-expand} with the @code{eval} function: in the latter case
11733 the evaluated string will be expanded @emph{twice}; first by
11734 @code{gmk-expand}, then again by the @code{eval} function.
11735
11736 @end table
11737
11738 @node Guile Example,  , Guile Interface, Guile Integration
11739 @subsection Example Using Guile in @code{make}
11740 @cindex Guile example
11741 @cindex example using Guile
11742
11743 Here is a very simple example using GNU Guile to manage writing to a
11744 file.  These Guile procedures simply open a file, allow writing to the
11745 file (one string per line), and close the file.  Note that because we
11746 cannot store complex values such as Guile ports in @code{make}
11747 variables, we'll keep the port as a global variable in the Guile
11748 interpreter.
11749
11750 You can create Guile functions easily using @code{define}/@code{endef}
11751 to create a Guile script, then use the @code{guile} function to
11752 internalize it:
11753
11754 @example
11755 @group
11756 define GUILEIO
11757 ;; A simple Guile IO library for GNU make
11758
11759 (define MKPORT #f)
11760
11761 (define (mkopen name mode)
11762   (set! MKPORT (open-file name mode))
11763   #f)
11764
11765 (define (mkwrite s)
11766   (display s MKPORT)
11767   (newline MKPORT)
11768   #f)
11769
11770 (define (mkclose)
11771   (close-port MKPORT)
11772   #f)
11773
11774 #f
11775 endef
11776
11777 # Internalize the Guile IO functions
11778 $(guile $(GUILEIO))
11779 @end group
11780 @end example
11781
11782 If you have a significant amount of Guile support code, you might
11783 consider keeping it in a different file (e.g., @file{guileio.scm}) and
11784 then loading it in your makefile using the @code{guile} function:
11785
11786 @example
11787 $(guile (load "guileio.scm"))
11788 @end example
11789
11790 An advantage to this method is that when editing @file{guileio.scm},
11791 your editor will understand that this file contains Scheme syntax
11792 rather than makefile syntax.
11793
11794 Now you can use these Guile functions to create files.  Suppose you
11795 need to operate on a very large list, which cannot fit on the command
11796 line, but the utility you're using accepts the list as input as well:
11797
11798 @example
11799 @group
11800 prog: $(PREREQS)
11801         @@$(guile (mkopen "tmp.out" "w")) \
11802          $(foreach X,$^,$(guile (mkwrite "$(X)"))) \
11803          $(guile (mkclose))
11804         $(LINK) < tmp.out
11805 @end group
11806 @end example
11807
11808 A more comprehensive suite of file manipulation procedures is possible
11809 of course.  You could, for example, maintain multiple output files at
11810 the same time by choosing a symbol for each one and using it as the
11811 key to a hash table, where the value is a port, then returning the
11812 symbol to be stored in a @code{make} variable.
11813
11814 @node Loading Objects,  , Guile Integration, Extending make
11815 @section Loading Dynamic Objects
11816 @cindex loaded objects
11817 @cindex objects, loaded
11818 @cindex extensions, loading
11819
11820 @cartouche
11821 @quotation Warning
11822 The @code{load} directive and extension capability is considered a
11823 ``technology preview'' in this release of GNU make.  We encourage you
11824 to experiment with this feature and we appreciate any feedback on it.
11825 However we cannot guarantee to maintain backward-compatibility in the
11826 next release.  Consider using GNU Guile instead for extending GNU make
11827 (@pxref{Guile Function, ,The @code{guile} Function}).
11828 @end quotation
11829 @end cartouche
11830
11831 Many operating systems provide a facility for dynamically loading
11832 compiled objects.  If your system provides this facility, GNU
11833 @code{make} can make use of it to load dynamic objects at runtime,
11834 providing new capabilities which may then be invoked by your makefile.
11835
11836 The @code{load} directive is used to load a dynamic object.  Once the
11837 object is loaded, a ``setup'' function will be invoked to allow the
11838 object to initialize itself and register new facilities with GNU
11839 @code{make}.  A dynamic object might include new @code{make} functions,
11840 for example, and the ``setup'' function would register them with GNU
11841 @code{make}'s function handling system.
11842
11843 @menu
11844 * load Directive::              Loading dynamic objects as extensions.
11845 * Remaking Loaded Objects::     How loaded objects get remade.
11846 * Loaded Object API::           Programmatic interface for loaded objects.
11847 * Loaded Object Example::       Example of a loaded object
11848 @end menu
11849
11850 @node load Directive, Remaking Loaded Objects, Loading Objects, Loading Objects
11851 @subsection The @code{load} Directive
11852 @cindex load directive
11853 @cindex extensions, load directive
11854
11855 Objects are loaded into GNU @code{make} by placing the @code{load}
11856 directive into your makefile.  The syntax of the @code{load} directive
11857 is as follows:
11858
11859 @findex load
11860 @example
11861 load @var{object-file} @dots{}
11862 @end example
11863
11864 or:
11865
11866 @example
11867 load @var{object-file}(@var{symbol-name}) @dots{}
11868 @end example
11869
11870 The file @var{object-file} is dynamically loaded by GNU @code{make}.
11871 If @var{object-file} does not include a directory path then it is
11872 first looked for in the current directory.  If it is not found there,
11873 or a directory path is included, then system-specific paths will be
11874 searched.  If the load fails for any reason, @code{make} will print a
11875 message and exit.
11876
11877 If the load succeeds @code{make} will invoke an initializing function.
11878
11879 If @var{symbol-name} is provided, it will be used as the name of the
11880 initializing function.
11881
11882 If no @var{symbol-name} is provided, the initializing function name is
11883 created by taking the base file name of @var{object-file}, up to the
11884 first character which is not a valid symbol name character
11885 (alphanumerics and underscores are valid symbol name characters).  To
11886 this prefix will be appended the suffix @code{_gmk_setup}.
11887
11888 More than one object file may be loaded with a single @code{load}
11889 directive, and both forms of @code{load} arguments may be used in the
11890 same directive.
11891
11892 The initializing function will be provided the file name and line
11893 number of the invocation of the @code{load} operation.  It should
11894 return a value of type @code{int}, which must be @code{0} on failure
11895 and non-@code{0} on success.  If the return value is @code{-1}, then
11896 GNU make will @emph{not} attempt to rebuild the object file
11897 (@pxref{Remaking Loaded Objects, ,How Loaded Objects Are Remade}).
11898
11899 For example:
11900
11901 @example
11902 load ../mk_funcs.so
11903 @end example
11904
11905 will load the dynamic object @file{../mk_funcs.so}.  After the object
11906 is loaded, @code{make} will invoke the function (assumed to be defined
11907 by the shared object) @code{mk_funcs_gmk_setup}.
11908
11909 On the other hand:
11910
11911 @example
11912 load ../mk_funcs.so(init_mk_func)
11913 @end example
11914
11915 will load the dynamic object @file{../mk_funcs.so}.  After the object
11916 is loaded, @code{make} will invoke the function @code{init_mk_func}.
11917
11918 Regardless of how many times an object file appears in a @code{load}
11919 directive, it will only be loaded (and its setup function will only
11920 be invoked) once.
11921
11922 @vindex .LOADED
11923 After an object has been successfully loaded, its file name is
11924 appended to the @code{.LOADED} variable.
11925
11926 @findex -load
11927 If you would prefer that failure to load a dynamic object not be
11928 reported as an error, you can use the @code{-load} directive instead
11929 of @code{load}.  GNU @code{make} will not fail and no message will be
11930 generated if an object fails to load.  The failed object is not added
11931 to the @code{.LOADED} variable, which can then be consulted to
11932 determine if the load was successful.
11933
11934 @node Remaking Loaded Objects, Loaded Object API, load Directive, Loading Objects
11935 @subsection How Loaded Objects Are Remade
11936 @cindex updating loaded objects
11937 @cindex remaking loaded objects
11938 @cindex loaded objects, remaking of
11939
11940 Loaded objects undergo the same re-make procedure as makefiles
11941 (@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).  If any
11942 loaded object is recreated, then @code{make} will start from scratch
11943 and re-read all the makefiles, and reload the object files again.  It
11944 is not necessary for the loaded object to do anything special to
11945 support this.
11946
11947 It's up to the makefile author to provide the rules needed for
11948 rebuilding the loaded object.
11949
11950 @node Loaded Object API, Loaded Object Example, Remaking Loaded Objects, Loading Objects
11951 @subsection Loaded Object Interface
11952 @cindex loaded object API
11953 @cindex interface for loaded objects
11954
11955 @cartouche
11956 @quotation Warning
11957 For this feature to be useful your extensions will need to invoke
11958 various functions internal to GNU @code{make}.  The programming
11959 interfaces provided in this release should not be considered stable:
11960 functions may be added, removed, or change calling signatures or
11961 implementations in future versions of GNU @code{make}.
11962 @end quotation
11963 @end cartouche
11964
11965 To be useful, loaded objects must be able to interact with GNU
11966 @code{make}.  This interaction includes both interfaces the loaded
11967 object provides to makefiles and also interfaces @code{make} provides
11968 to the loaded object to manipulate @code{make}'s operation.
11969
11970 The interface between loaded objects and @code{make} is defined by the
11971 @file{gnumake.h} C header file.  All loaded objects written in C
11972 should include this header file.  Any loaded object not written in C
11973 will need to implement the interface defined in this header file.
11974
11975 Typically, a loaded object will register one or more new GNU
11976 @code{make} functions using the @code{gmk_add_function} routine from
11977 within its setup function.  The implementations of these @code{make}
11978 functions may make use of the @code{gmk_expand} and @code{gmk_eval}
11979 routines to perform their tasks, then optionally return a string as
11980 the result of the function expansion.
11981
11982 @subsubheading Loaded Object Licensing
11983 @cindex loaded object licensing
11984 @cindex plugin_is_GPL_compatible
11985
11986 Every dynamic extension should define the global symbol
11987 @code{plugin_is_GPL_compatible} to assert that it has been licensed
11988 under a GPL-compatible license.  If this symbol does not exist,
11989 @code{make} emits a fatal error and exits when it tries to load your
11990 extension.
11991
11992 The declared type of the symbol should be @code{int}. It does not need
11993 to be in any allocated section, though.  The code merely asserts that
11994 the symbol exists in the global scope. Something like this is enough:
11995
11996 @example
11997 int plugin_is_GPL_compatible;
11998 @end example
11999
12000 @subsubheading Data Structures
12001
12002 @table @code
12003 @item gmk_floc
12004 This structure represents a filename/location pair.  It is provided
12005 when defining items, so GNU @code{make} can inform the user later
12006 where the definition occurred if necessary.
12007 @end table
12008
12009 @subsubheading Registering Functions
12010 @findex gmk_add_function
12011
12012 There is currently one way for makefiles to invoke operations provided
12013 by the loaded object: through the @code{make} function call
12014 interface.  A loaded object can register one or more new functions
12015 which may then be invoked from within the makefile in the same way as
12016 any other function.
12017
12018 Use @code{gmk_add_function} to create a new @code{make} function.  Its
12019 arguments are as follows:
12020
12021 @table @code
12022 @item name
12023 The function name.  This is what the makefile should use to invoke the
12024 function.  The name must be between 1 and 255 characters long and it
12025 may only contain alphanumeric, period (@samp{.}), dash (@samp{-}), and
12026 underscore (@samp{_}) characters.  It may not begin with a period.
12027
12028 @item func_ptr
12029 A pointer to a function that @code{make} will invoke when it expands
12030 the function in a makefile.  This function must be defined by the
12031 loaded object.
12032
12033 @item min_args
12034 The minimum number of arguments the function will accept.  Must be
12035 between 0 and 255.  GNU @code{make} will check this and fail before
12036 invoking @code{func_ptr} if the function was invoked with too few
12037 arguments.
12038
12039 @item max_args
12040 The maximum number of arguments the function will accept.  Must be
12041 between 0 and 255.  GNU @code{make} will check this and fail before
12042 invoking @code{func_ptr} if the function was invoked with too many
12043 arguments.  If the value is 0, then any number of arguments is
12044 accepted.  If the value is greater than 0, then it must be greater
12045 than or equal to @code{min_args}.
12046
12047 @item flags
12048 Flags that specify how this function will operate; the desired flags
12049 should be OR'd together.  If the @code{GMK_FUNC_NOEXPAND} flag is
12050 given then the function arguments will not be expanded before the
12051 function is called; otherwise they will be expanded first.
12052 @end table
12053
12054 @subsubheading Registered Function Interface
12055 @findex gmk_func_ptr
12056
12057 A function registered with @code{make} must match the
12058 @code{gmk_func_ptr} type.  It will be invoked with three parameters:
12059 @code{name} (the name of the function), @code{argc} (the number of
12060 arguments to the function), and @code{argv} (an array of pointers to
12061 arguments to the function).  The last pointer (that is,
12062 @code{argv[argc]}) will be null (@code{0}).
12063
12064 The return value of the function is the result of expanding the
12065 function.  If the function expands to nothing the return value may be
12066 null.  Otherwise, it must be a pointer to a string created with
12067 @code{gmk_alloc}.  Once the function returns, @code{make} owns this
12068 string and will free it when appropriate; it cannot be accessed by the
12069 loaded object.
12070
12071 @subsubheading GNU @code{make} Facilities
12072
12073 There are some facilities exported by GNU @code{make} for use by
12074 loaded objects.  Typically these would be run from within the
12075 setup function and/or the functions registered via
12076 @code{gmk_add_function}, to retrieve or modify the data @code{make}
12077 works with.
12078
12079 @table @code
12080 @item gmk_expand
12081 @findex gmk_expand
12082 This function takes a string and expands it using @code{make}
12083 expansion rules.  The result of the expansion is returned in a
12084 nil-terminated string buffer.  The caller is responsible for calling
12085 @code{gmk_free} with a pointer to the returned buffer when done.
12086
12087 @item gmk_eval
12088 @findex gmk_eval
12089 This function takes a buffer and evaluates it as a segment of makefile
12090 syntax.  This function can be used to define new variables, new rules,
12091 etc.  It is equivalent to using the @code{eval} @code{make} function.
12092 @end table
12093
12094 Note that there is a difference between @code{gmk_eval} and calling
12095 @code{gmk_expand} with a string using the @code{eval} function: in
12096 the latter case the string will be expanded @emph{twice}; once by
12097 @code{gmk_expand} and then again by the @code{eval} function.  Using
12098 @code{gmk_eval} the buffer is only expanded once, at most (as it's
12099 read by the @code{make} parser).
12100
12101 @subsubheading Memory Management
12102
12103 Some systems allow for different memory management schemes.  Thus you
12104 should never pass memory that you've allocated directly to any
12105 @code{make} function, nor should you attempt to directly free any
12106 memory returned to you by any @code{make} function.  Instead, use the
12107 @code{gmk_alloc} and @code{gmk_free} functions.
12108
12109 In particular, the string returned to @code{make} by a function
12110 registered using @code{gmk_add_function} @emph{must} be allocated
12111 using @code{gmk_alloc}, and the string returned from the @code{make}
12112 @code{gmk_expand} function @emph{must} be freed (when no longer
12113 needed) using @code{gmk_free}.
12114
12115 @table @code
12116 @item gmk_alloc
12117 @findex gmk_alloc
12118 Return a pointer to a newly-allocated buffer.  This function will
12119 always return a valid pointer; if not enough memory is available
12120 @code{make} will exit.  @code{gmk_alloc} does not initialize allocated memory.
12121
12122 @item gmk_free
12123 @findex gmk_free
12124 Free a buffer returned to you by @code{make}.  Once the
12125 @code{gmk_free} function returns the string will no longer be valid.
12126 If NULL is passed to @code{gmk_free}, no operation is performed.
12127 @end table
12128
12129 @node Loaded Object Example,  , Loaded Object API, Loading Objects
12130 @subsection Example Loaded Object
12131 @cindex loaded object example
12132 @cindex example of loaded objects
12133
12134 Let's suppose we wanted to write a new GNU @code{make} function that
12135 would create a temporary file and return its name.  We would like our
12136 function to take a prefix as an argument.  First we can write the
12137 function in a file @file{mk_temp.c}:
12138
12139 @example
12140 @group
12141 #include <stdlib.h>
12142 #include <stdio.h>
12143 #include <string.h>
12144 #include <unistd.h>
12145 #include <errno.h>
12146
12147 #include <gnumake.h>
12148
12149 int plugin_is_GPL_compatible;
12150
12151 char *
12152 gen_tmpfile(const char *nm, int argc, char **argv)
12153 @{
12154   int fd;
12155
12156   /* Compute the size of the filename and allocate space for it.  */
12157   int len = strlen (argv[0]) + 6 + 1;
12158   char *buf = gmk_alloc (len);
12159
12160   strcpy (buf, argv[0]);
12161   strcat (buf, "XXXXXX");
12162
12163   fd = mkstemp(buf);
12164   if (fd >= 0)
12165     @{
12166       /* Don't leak the file descriptor.  */
12167       close (fd);
12168       return buf;
12169     @}
12170
12171   /* Failure.  */
12172   fprintf (stderr, "mkstemp(%s) failed: %s\n", buf, strerror (errno));
12173   gmk_free (buf);
12174   return NULL;
12175 @}
12176
12177 int
12178 mk_temp_gmk_setup (const gmk_floc *floc)
12179 @{
12180   printf ("mk_temp plugin loaded from %s:%lu\n", floc->filenm, floc->lineno);
12181   /* Register the function with make name "mk-temp".  */
12182   gmk_add_function ("mk-temp", gen_tmpfile, 1, 1, 1);
12183   return 1;
12184 @}
12185 @end group
12186 @end example
12187
12188 Next, we will write a @file{Makefile} that can build this shared object, load
12189 it, and use it:
12190
12191 @example
12192 @group
12193 all:
12194         @@echo Temporary file: $(mk-temp tmpfile.)
12195
12196 load mk_temp.so
12197
12198 mk_temp.so: mk_temp.c
12199         $(CC) -shared -fPIC -o $@@ $<
12200 @end group
12201 @end example
12202
12203 On MS-Windows, due to peculiarities of how shared objects are
12204 produced, the compiler needs to scan the @dfn{import library} produced
12205 when building @code{make}, typically called
12206 @file{libgnumake-@var{version}.dll.a}, where @var{version} is the
12207 version of the load object API.  So the recipe to produce a shared
12208 object will look on Windows like this (assuming the API version is 1):
12209
12210 @example
12211 @group
12212 mk_temp.dll: mk_temp.c
12213         $(CC) -shared -o $@@ $< -lgnumake-1
12214 @end group
12215 @end example
12216
12217 Now when you run @code{make} you'll see something like:
12218
12219 @example
12220 $ make
12221 mk_temp plugin loaded from Makefile:4
12222 cc -shared -fPIC -o mk_temp.so mk_temp.c
12223 Temporary filename: tmpfile.A7JEwd
12224 @end example
12225
12226 @node Integrating make, Features, Extending make, Top
12227 @chapter Integrating GNU @code{make}
12228 @cindex make integration
12229
12230 GNU @code{make} is often one component in a larger system of tools,
12231 including integrated development environments, compiler toolchains,
12232 and others.  The role of @code{make} is to start commands and
12233 determine whether they succeeded or not: no special integration is
12234 needed to accomplish that.  However, sometimes it is convenient to
12235 bind @code{make} more tightly with other parts of the system, both
12236 higher-level (tools that invoke @code{make}) and lower-level (tools
12237 that @code{make} invokes).
12238
12239 @menu
12240 * Job Slots::                   Share job slots with GNU @code{make}.
12241 * Terminal Output::             Control output to terminals.
12242 @end menu
12243
12244 @node Job Slots, Terminal Output, Integrating make, Integrating make
12245 @section Sharing Job Slots with GNU @code{make}
12246 @cindex job slots, sharing
12247 @cindex tools, sharing job slots
12248
12249 GNU @code{make} has the ability to run multiple recipes in parallel
12250 (@pxref{Parallel, ,Parallel Execution}) and to cap the total number of
12251 parallel jobs even across recursive invocations of @code{make}
12252 (@pxref{Options/Recursion, ,Communicating Options to a
12253 Sub-@code{make}}).  Tools that @code{make} invokes which are also able
12254 to run multiple operations in parallel, either using multiple threads
12255 or multiple processes, can be enhanced to participate in GNU
12256 @code{make}'s job management facility to ensure that the total number
12257 of active threads/processes running on the system does not exceed the
12258 maximum number of slots provided to GNU @code{make}. 
12259
12260 @cindex jobserver
12261 GNU @code{make} uses a method called the ``jobserver'' to control the
12262 number of active jobs across recursive invocations.  The actual
12263 implementation of the jobserver varies across different operating
12264 systems, but some fundamental aspects are always true.
12265
12266 @cindex @code{--jobserver-auth}
12267 First, @code{make} will provide information necessary for accessing the
12268 jobserver through the environment to its children, in the @code{MAKEFLAGS}
12269 environment variable.  Tools which want to participate in the jobserver
12270 protocol will need to parse this environment variable and find the word
12271 starting with @code{--jobserver-auth=}.  The value of this option will
12272 describe how to communicate with the jobserver.  The interpretation of this
12273 value is described in the sections below.
12274
12275 Be aware that the @code{MAKEFLAGS} variable may contain multiple instances of
12276 the @code{--jobserver-auth=} option.  Only the @emph{last} instance is
12277 relevant.
12278
12279 Second, every command @code{make} starts has one implicit job slot
12280 reserved for it before it starts.  Any tool which wants to participate
12281 in the jobserver protocol should assume it can always run one job
12282 without having to contact the jobserver at all.
12283
12284 Finally, it's critical that tools that participate in the jobserver
12285 protocol return the exact number of slots they obtained from the
12286 jobserver back to the jobserver before they exit, even under error
12287 conditions.  Remember that the implicit job slot should @strong{not}
12288 be returned to the jobserver!  Returning too few slots means that
12289 those slots will be lost for the rest of the build process; returning
12290 too many slots means that extra slots will be available.  The
12291 top-level @code{make} command will print an error message at the end
12292 of the build if it detects an incorrect number of slots available in
12293 the jobserver.
12294
12295 As an example, suppose you are implementing a linker which provides
12296 for multithreaded operation.  You would like to enhance the linker so
12297 that if it is invoked by GNU @code{make} it can participate in the
12298 jobserver protocol to control how many threads are used during link.
12299 First you will need to modify the linker to determine if the
12300 @code{MAKEFLAGS} environment variable is set.  Next you will need to
12301 parse the value of that variable to determine if the jobserver is
12302 available, and how to access it.  If it is available then you can
12303 access it to obtain job slots controlling how much parallelism your
12304 tool can use.  Once done your tool must return those job slots back to
12305 the jobserver.
12306
12307 @menu
12308 * POSIX Jobserver::             Using the jobserver on POSIX systems.
12309 * Windows Jobserver::           Using the jobserver on Windows systems.
12310 @end menu
12311
12312 @node POSIX Jobserver, Windows Jobserver, Job Slots, Job Slots
12313 @subsection POSIX Jobserver Interaction
12314 @cindex jobserver on POSIX
12315
12316 On POSIX systems the jobserver is implemented in one of two ways: on systems
12317 that support it, GNU @code{make} will create a named pipe and use that for the
12318 jobserver.  In this case the auth option will have the form
12319 @code{--jobserver-auth=fifo:PATH} where @samp{PATH} is the pathname of the
12320 named pipe.  To access the jobserver you should open the named pipe path and
12321 read/write to it as described below.
12322
12323 @cindex @code{--jobserver-style}
12324 If the system doesn't support named pipes, or if the user provided the
12325 @code{--jobserver-style} option and specified @samp{pipe}, then the jobserver
12326 will be implemented as a simple UNIX pipe.  In this case the auth option will
12327 have the form @code{--jobserver-auth=R,W} where @samp{R} and @samp{W} are
12328 non-negative integers representing file descriptors: @samp{R} is the read file
12329 descriptor and @samp{W} is the write file descriptor.  If either or both of
12330 these file descriptors are negative, it means the jobserver is disabled for
12331 this process.
12332
12333 When using a simple pipe, only command lines that @code{make} understands to
12334 be recursive invocations of @code{make} (@pxref{MAKE Variable, ,How the
12335 @code{MAKE} Variable Works}) will have access to the jobserver.  When writing
12336 makefiles you must be sure to mark the command as recursive (most commonly by
12337 prefixing the command line with the @code{+} indicator (@pxref{Recursion,
12338 ,Recursive Use of @code{make}}).  Note that the read side of the jobserver
12339 pipe is set to ``blocking'' mode.  This should not be changed.
12340
12341 In both implementations of the jobserver, the pipe will be pre-loaded with one
12342 single-character token for each available job.  To obtain an extra slot you
12343 must read a single character from the jobserver; to release a slot you must
12344 write a single character back into the jobserver.
12345
12346 It's important that when you release the job slot, you write back the same
12347 character you read.  Don't assume that all tokens are the same character;
12348 different characters may have different meanings to GNU @code{make}.  The
12349 order is not important, since @code{make} has no idea in what order jobs will
12350 complete anyway.
12351
12352 There are various error conditions you must consider to ensure your
12353 implementation is robust:
12354
12355 @itemize @bullet
12356 @item
12357 If you have a command-line argument controlling the parallel operation of your
12358 tool, consider whether your tool should detect situations where both the
12359 jobserver and the command-line argument are specified, and how it should
12360 react.
12361
12362 @item
12363 If your tool does not recognize the format of the @code{--jobserver-auth}
12364 string, it should assume the jobserver is using a different style and it
12365 cannot connect.
12366
12367 @item
12368 If your tool determines that the @code{--jobserver-auth} option references a
12369 simple pipe but that the file descriptors specified are closed, this means
12370 that the calling @code{make} process did not think that your tool was a
12371 recursive @code{make} invocation (e.g., the command line was not prefixed with
12372 a @code{+} character).  You should notify your users of this situation.
12373
12374 @item
12375 Your tool should be sure to write back the tokens it read, even under error
12376 conditions.  This includes not only errors in your tool but also outside
12377 influences such as interrupts (@code{SIGINT}), etc.  You may want to install
12378 signal handlers to manage this write-back.
12379
12380 @item
12381 Your tool may also examine the first word of the @code{MAKEFLAGS} variable and
12382 look for the character @code{n}.  If this character is present then
12383 @code{make} was invoked with the @samp{-n} option and your tool may want to
12384 stop without performing any operations.
12385 @end itemize
12386
12387 @node Windows Jobserver,  , POSIX Jobserver, Job Slots
12388 @subsection Windows Jobserver Interaction
12389 @cindex jobserver on Windows
12390
12391 On Windows systems the jobserver is implemented as a named semaphore.
12392 The semaphore will be set with an initial count equal to the number of
12393 available slots; to obtain a slot you must wait on the semaphore (with
12394 or without a timeout).  To release a slot, release the semaphore.
12395
12396 To access the semaphore you must parse the @code{MAKEFLAGS} variable and
12397 look for the argument string @code{--jobserver-auth=NAME} where
12398 @samp{NAME} is the name of the named semaphore.  Use this name with
12399 @code{OpenSemaphore} to create a handle to the semaphore.
12400
12401 @cindex @code{--jobserver-style} for Windows
12402 The only valid style for @code{--jobserver-style} is @samp{sem}.
12403
12404 There are various error conditions you must consider to ensure your
12405 implementation is robust:
12406
12407 @itemize @bullet
12408 @item
12409 Usually you will have a command-line argument controlling the parallel
12410 operation of your tool.  Consider whether your tool should detect
12411 situations where both the jobserver and the command-line argument are
12412 specified, and how it should react.
12413
12414 @item
12415 Your tool should be sure to release the semaphore for the tokens it
12416 read, even under error conditions.  This includes not only errors in
12417 your tool but also outside influences such as interrupts
12418 (@code{SIGINT}), etc.  You may want to install signal handlers to
12419 manage this write-back.
12420 @end itemize
12421
12422 @node Terminal Output,  , Job Slots, Integrating make
12423 @section Synchronized Terminal Output
12424 @cindex parallel output to terminal
12425 @cindex terminal, output to
12426
12427 Normally GNU @code{make} will invoke all commands with access to the
12428 same standard and error outputs that @code{make} itself was started
12429 with.  A number of tools will detect whether the output is a terminal
12430 or not-a-terminal, and use this information to change the output
12431 style.  For example if the output goes to a terminal the tool may add
12432 control characters that set color, or even change the location of the
12433 cursor.  If the output is not going to a terminal then these special
12434 control characters are not emitted so that they don't corrupt log
12435 files, etc.
12436
12437 The @code{--output-sync} (@pxref{Parallel Output, ,Output During
12438 Parallel Execution}) option will defeat the terminal detection.  When
12439 output synchronization is enabled GNU @code{make} arranges for all
12440 command output to be written to a file, so that its output can be
12441 written as a block without interference from other commands.  This
12442 means that all tools invoked by @code{make} will believe that their
12443 output is not going to be displayed on a terminal, even when it will
12444 be (because @code{make} will display it there after the command is
12445 completed).
12446
12447 In order to facilitate tools which would like to determine whether or
12448 not their output will be displayed on a terminal, GNU @code{make} will
12449 set the @code{MAKE_TERMOUT} and @code{MAKE_TERMERR} environment
12450 variables before invoking any commands.  Tools which would like to
12451 determine whether standard or error output (respectively) will be
12452 displayed on a terminal can check these environment variables to
12453 determine if they exist and contain a non-empty value.  If so the tool
12454 can assume that the output will (eventually) be displayed on a
12455 terminal.  If the variables are not set or have an empty value, then
12456 the tool should fall back to its normal methods of detecting whether
12457 output is going to a terminal or not.
12458
12459 The content of the variables can be parsed to determine the type of
12460 terminal which will be used to display the output.
12461
12462 Similarly, environments which invoke @code{make} and would like to
12463 capture the output and eventually display it on a terminal (or some
12464 display which can interpret terminal control characters) can set these
12465 variables before invoking @code{make}.  GNU @code{make} will not
12466 modify these environment variables if they already exist when it
12467 starts.
12468
12469 @node Features, Missing, Integrating make, Top
12470 @chapter Features of GNU @code{make}
12471 @cindex features of GNU @code{make}
12472 @cindex portability
12473 @cindex compatibility
12474
12475 Here is a summary of the features of GNU @code{make}, for comparison
12476 with and credit to other versions of @code{make}.  We consider the
12477 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
12478 concerned with writing portable makefiles, you should not use the
12479 features of @code{make} listed here, nor the ones in @ref{Missing}.
12480
12481 Many features come from the version of @code{make} in System V.
12482
12483 @itemize @bullet
12484 @item
12485 The @code{VPATH} variable and its special meaning.
12486 @xref{Directory Search, , Searching Directories for Prerequisites}.
12487 This feature exists in System V @code{make}, but is undocumented.
12488 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
12489 @code{VPATH} feature).
12490
12491 @item
12492 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
12493 Allowing multiple files to be included with a single directive is a GNU
12494 extension.
12495
12496 @item
12497 Variables are read from and communicated via the environment.
12498 @xref{Environment, ,Variables from the Environment}.
12499
12500 @item
12501 Options passed through the variable @code{MAKEFLAGS} to recursive
12502 invocations of @code{make}.
12503 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
12504
12505 @item
12506 The automatic variable @code{$%} is set to the member name
12507 in an archive reference.  @xref{Automatic Variables}.
12508
12509 @item
12510 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
12511 and @code{$?} have corresponding forms like @code{$(@@F)} and
12512 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
12513 extension.  @xref{Automatic Variables}.
12514
12515 @item
12516 Substitution variable references.
12517 @xref{Reference, ,Basics of Variable References}.
12518
12519 @item
12520 The command line options @samp{-b} and @samp{-m}, accepted and
12521 ignored.  In System V @code{make}, these options actually do something.
12522
12523 @item
12524 Execution of recursive commands to run @code{make} via the variable
12525 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
12526 @xref{Recursion, ,Recursive Use of @code{make}}.
12527
12528 @item
12529 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
12530 Rules}.  This feature is obsolete in GNU @code{make}, because the
12531 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
12532 Implicit Rules}) allows one pattern rule for installing members in an
12533 archive (@pxref{Archive Update}) to be sufficient.
12534
12535 @item
12536 The arrangement of lines and backslash/newline combinations in
12537 recipes is retained when the recipes are printed, so they appear as
12538 they do in the makefile, except for the stripping of initial
12539 whitespace.
12540 @end itemize
12541
12542 The following features were inspired by various other versions of
12543 @code{make}.  In some cases it is unclear exactly which versions inspired
12544 which others.
12545
12546 @itemize @bullet
12547 @item
12548 Pattern rules using @samp{%}.
12549 This has been implemented in several versions of @code{make}.
12550 We're not sure who invented it first, but it's been spread around a bit.
12551 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
12552
12553 @item
12554 Rule chaining and implicit intermediate files.
12555 This was implemented by Stu Feldman in his version of @code{make}
12556 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
12557 AT&T Bell Labs in his @code{mk} program (where he terms it
12558 ``transitive closure'').  We do not really know if
12559 we got this from either of them or thought it up ourselves at the
12560 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
12561
12562 @item
12563 The automatic variable @code{$^} containing a list of all prerequisites
12564 of the current target.  We did not invent this, but we have no idea who
12565 did.  @xref{Automatic Variables}.  The automatic variable
12566 @code{$+} is a simple extension of @code{$^}.
12567
12568 @item
12569 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
12570 invented by Andrew Hume in @code{mk}.
12571 @xref{Instead of Execution, ,Instead of Executing Recipes}.
12572
12573 @item
12574 The concept of doing several things at once (parallelism) exists in
12575 many incarnations of @code{make} and similar programs, though not in the
12576 System V or BSD implementations.  @xref{Execution, ,Recipe Execution}.
12577
12578 @item
12579 A number of different build tools that support parallelism also
12580 support collecting output and displaying as a single block.
12581 @xref{Parallel Output, ,Output During Parallel Execution}.
12582
12583 @item
12584 Modified variable references using pattern substitution come from
12585 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
12586 This functionality was provided in GNU @code{make} by the
12587 @code{patsubst} function before the alternate syntax was implemented
12588 for compatibility with SunOS 4.  It is not altogether clear who
12589 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
12590 4 was released.
12591
12592 @item
12593 The special significance of @samp{+} characters preceding recipe lines
12594 (@pxref{Instead of Execution, ,Instead of Executing Recipes}) is
12595 mandated by @cite{IEEE Standard 1003.2-1992} (POSIX.2).
12596
12597 @item
12598 The @samp{+=} syntax to append to the value of a variable comes from SunOS
12599 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
12600
12601 @item
12602 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
12603 multiple members in a single archive file comes from SunOS 4 @code{make}.
12604 @xref{Archive Members}.
12605
12606 @item
12607 The @code{-include} directive to include makefiles with no error for a
12608 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
12609 @code{make} does not allow multiple makefiles to be specified in one
12610 @code{-include} directive.)  The same feature appears with the name
12611 @code{sinclude} in SGI @code{make} and perhaps others.
12612
12613 @item
12614 The @code{!=} shell assignment operator exists in many BSD of
12615 @code{make} and is purposefully implemented here to behave identically
12616 to those implementations.
12617
12618 @item
12619 Various build management tools are implemented using scripting
12620 languages such as Perl or Python and thus provide a natural embedded
12621 scripting language, similar to GNU @code{make}'s integration of GNU
12622 Guile.
12623 @end itemize
12624
12625 The remaining features are inventions new in GNU @code{make}:
12626
12627 @itemize @bullet
12628 @item
12629 Use the @samp{-v} or @samp{--version} option to print version and
12630 copyright information.
12631
12632 @item
12633 Use the @samp{-h} or @samp{--help} option to summarize the options to
12634 @code{make}.
12635
12636 @item
12637 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
12638
12639 @item
12640 Pass command line variable assignments automatically through the
12641 variable @code{MAKE} to recursive @code{make} invocations.
12642 @xref{Recursion, ,Recursive Use of @code{make}}.
12643
12644 @item
12645 Use the @samp{-C} or @samp{--directory} command option to change
12646 directory.  @xref{Options Summary, ,Summary of Options}.
12647
12648 @item
12649 Make verbatim variable definitions with @code{define}.
12650 @xref{Multi-Line, ,Defining Multi-Line Variables}.
12651
12652 @item
12653 Declare phony targets with the special target @code{.PHONY}.
12654
12655 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
12656 different syntax in his @code{mk} program.  This seems to be a case of
12657 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
12658
12659 @item
12660 Manipulate text by calling functions.
12661 @xref{Functions, ,Functions for Transforming Text}.
12662
12663 @item
12664 Use the @samp{-o} or @samp{--old-file}
12665 option to pretend a file's modification-time is old.
12666 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
12667
12668 @item
12669 Conditional execution.
12670
12671 This feature has been implemented numerous times in various versions
12672 of @code{make}; it seems a natural extension derived from the features
12673 of the C preprocessor and similar macro languages and is not a
12674 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
12675
12676 @item
12677 Specify a search path for included makefiles.
12678 @xref{Include, ,Including Other Makefiles}.
12679
12680 @item
12681 Specify extra makefiles to read with an environment variable.
12682 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
12683
12684 @item
12685 Strip leading sequences of @samp{./} from file names, so that
12686 @file{./@var{file}} and @file{@var{file}} are considered to be the
12687 same file.
12688
12689 @item
12690 Use a special search method for library prerequisites written in the
12691 form @samp{-l@var{name}}.
12692 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
12693
12694 @item
12695 Allow suffixes for suffix rules
12696 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
12697 characters.  In other versions of @code{make}, they must begin with
12698 @samp{.} and not contain any @samp{/} characters.
12699
12700 @item
12701 Keep track of the current level of @code{make} recursion using the
12702 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
12703
12704 @item
12705 Provide any goals given on the command line in the variable
12706 @code{MAKECMDGOALS}.  @xref{Goals, ,Arguments to Specify the Goals}.
12707
12708 @item
12709 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
12710
12711 @item
12712 Provide selective @code{vpath} search.
12713 @xref{Directory Search, ,Searching Directories for Prerequisites}.
12714
12715 @item
12716 Provide computed variable references.
12717 @xref{Reference, ,Basics of Variable References}.
12718
12719 @item
12720 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
12721 System V @code{make} has a very, very limited form of this
12722 functionality in that it will check out SCCS files for makefiles.
12723
12724 @item
12725 Various new built-in implicit rules.
12726 @xref{Catalogue of Rules, ,Catalogue of Built-In Rules}.
12727
12728 @item
12729 Load dynamic objects which can modify the behavior of @code{make}.
12730 @xref{Loading Objects, ,Loading Dynamic Objects}.
12731 @end itemize
12732
12733 @node Missing, Makefile Conventions, Features, Top
12734 @chapter Incompatibilities and Missing Features
12735 @cindex incompatibilities
12736 @cindex missing features
12737 @cindex features, missing
12738
12739 The @code{make} programs in various other systems support a few features
12740 that are not implemented in GNU @code{make}.  The POSIX.2 standard
12741 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
12742 require any of these features.
12743
12744 @itemize @bullet
12745 @item
12746 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
12747 of archive file @var{file}.  The member is chosen, not by name, but by
12748 being an object file which defines the linker symbol @var{entry}.
12749
12750 This feature was not put into GNU @code{make} because of the
12751 non-modularity of putting knowledge into @code{make} of the internal
12752 format of archive file symbol tables.
12753 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
12754
12755 @item
12756 Suffixes (used in suffix rules) that end with the character @samp{~}
12757 have a special meaning to System V @code{make};
12758 they refer to the SCCS file that corresponds
12759 to the file one would get without the @samp{~}.  For example, the
12760 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
12761 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
12762 series of such suffix rules is required.
12763 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
12764
12765 In GNU @code{make}, this entire series of cases is handled by two
12766 pattern rules for extraction from SCCS, in combination with the
12767 general feature of rule chaining.
12768 @xref{Chained Rules, ,Chains of Implicit Rules}.
12769
12770 @item
12771 In System V and 4.3 BSD @code{make}, files found by @code{VPATH}
12772 search (@pxref{Directory Search, ,Searching Directories for
12773 Prerequisites}) have their names changed inside recipes.  We feel it
12774 is much cleaner to always use automatic variables and thus make this
12775 feature unnecessary.
12776
12777 @item
12778 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
12779 the prerequisites of a rule has the amazingly strange ``feature'' of
12780 expanding to the full name of the @emph{target of that rule}.  We cannot
12781 imagine what went on in the minds of Unix @code{make} developers to do
12782 this; it is utterly inconsistent with the normal definition of @code{$*}.
12783 @vindex * @r{(automatic variable), unsupported bizarre usage}
12784
12785 @item
12786 In some Unix @code{make}s, implicit rule search (@pxref{Implicit
12787 Rules, ,Using Implicit Rules}) is apparently done for @emph{all}
12788 targets, not just those without recipes.  This means you can
12789 do:
12790
12791 @example
12792 @group
12793 foo.o:
12794         cc -c foo.c
12795 @end group
12796 @end example
12797
12798 @noindent
12799 and Unix @code{make} will intuit that @file{foo.o} depends on
12800 @file{foo.c}.
12801
12802 We feel that such usage is broken.  The prerequisite properties of
12803 @code{make} are well-defined (for GNU @code{make}, at least),
12804 and doing such a thing simply does not fit the model.
12805
12806 @item
12807 GNU @code{make} does not include any built-in implicit rules for
12808 compiling or preprocessing EFL programs.  If we hear of anyone who is
12809 using EFL, we will gladly add them.
12810
12811 @item
12812 It appears that in SVR4 @code{make}, a suffix rule can be specified
12813 with no recipe, and it is treated as if it had an empty recipe
12814 (@pxref{Empty Recipes}).  For example:
12815
12816 @example
12817 .c.a:
12818 @end example
12819
12820 @noindent
12821 will override the built-in @file{.c.a} suffix rule.
12822
12823 We feel that it is cleaner for a rule without a recipe to always simply
12824 add to the prerequisite list for the target.  The above example can be
12825 easily rewritten to get the desired behavior in GNU @code{make}:
12826
12827 @example
12828 .c.a: ;
12829 @end example
12830
12831 @item
12832 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
12833 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
12834 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
12835 program it runs returns a nonzero status.  We feel it is cleaner to
12836 write each line of the recipe to stand on its own and not require this
12837 special treatment.
12838 @end itemize
12839
12840 @comment The makefile standards are in a separate file that is also
12841 @comment included by standards.texi.
12842 @include make-stds.texi
12843
12844 @node Quick Reference, Error Messages, Makefile Conventions, Top
12845 @appendix Quick Reference
12846
12847 This appendix summarizes the directives, text manipulation functions,
12848 and special variables which GNU @code{make} understands.
12849 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Built-In Rules},
12850 and @ref{Options Summary, ,Summary of Options},
12851 for other summaries.
12852
12853 Here is a summary of the directives GNU @code{make} recognizes:
12854
12855 @table @code
12856 @item define @var{variable}
12857 @itemx define @var{variable} =
12858 @itemx define @var{variable} :=
12859 @itemx define @var{variable} ::=
12860 @itemx define @var{variable} :::=
12861 @itemx define @var{variable} +=
12862 @itemx define @var{variable} ?=
12863 @itemx endef
12864 Define multi-line variables.@*
12865 @xref{Multi-Line}.
12866
12867 @item undefine @var{variable}
12868 Undefining variables.@*
12869 @xref{Undefine Directive}.
12870
12871 @item ifdef @var{variable}
12872 @itemx ifndef @var{variable}
12873 @itemx ifeq (@var{a},@var{b})
12874 @itemx ifeq "@var{a}" "@var{b}"
12875 @itemx ifeq '@var{a}' '@var{b}'
12876 @itemx ifneq (@var{a},@var{b})
12877 @itemx ifneq "@var{a}" "@var{b}"
12878 @itemx ifneq '@var{a}' '@var{b}'
12879 @itemx else
12880 @itemx endif
12881 Conditionally evaluate part of the makefile.@*
12882 @xref{Conditionals}.
12883
12884 @item include @var{file}
12885 @itemx -include @var{file}
12886 @itemx sinclude @var{file}
12887 Include another makefile.@*
12888 @xref{Include, ,Including Other Makefiles}.
12889
12890 @item override @var{variable-assignment}
12891 Define a variable, overriding any previous definition, even one from
12892 the command line.@*
12893 @xref{Override Directive, ,The @code{override} Directive}.
12894
12895 @item export
12896 Tell @code{make} to export all variables to child processes by default.@*
12897 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
12898
12899 @item export @var{variable}
12900 @itemx export @var{variable-assignment}
12901 @itemx unexport @var{variable}
12902 Tell @code{make} whether or not to export a particular variable to child
12903 processes.@*
12904 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
12905
12906 @item private @var{variable-assignment}
12907 Do not allow this variable assignment to be inherited by prerequisites.@*
12908 @xref{Suppressing Inheritance}.
12909
12910 @item vpath @var{pattern} @var{path}
12911 Specify a search path for files matching a @samp{%} pattern.@*
12912 @xref{Selective Search, , The @code{vpath} Directive}.
12913
12914 @item vpath @var{pattern}
12915 Remove all search paths previously specified for @var{pattern}.
12916
12917 @item vpath
12918 Remove all search paths previously specified in any @code{vpath}
12919 directive.
12920 @end table
12921
12922 Here is a summary of the built-in functions (@pxref{Functions}):
12923
12924 @table @code
12925 @item $(subst @var{from},@var{to},@var{text})
12926 Replace @var{from} with @var{to} in @var{text}.@*
12927 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12928
12929 @item $(patsubst @var{pattern},@var{replacement},@var{text})
12930 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
12931 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12932
12933 @item $(strip @var{string})
12934 Remove excess whitespace characters from @var{string}.@*
12935 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12936
12937 @item $(findstring @var{find},@var{text})
12938 Locate @var{find} in @var{text}.@*
12939 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12940
12941 @item $(filter @var{pattern}@dots{},@var{text})
12942 Select words in @var{text} that match one of the @var{pattern} words.@*
12943 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12944
12945 @item $(filter-out @var{pattern}@dots{},@var{text})
12946 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
12947 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12948
12949 @item $(sort @var{list})
12950 Sort the words in @var{list} lexicographically, removing duplicates.@*
12951 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12952
12953 @item $(word @var{n},@var{text})
12954 Extract the @var{n}th word (one-origin) of @var{text}.@*
12955 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12956
12957 @item $(words @var{text})
12958 Count the number of words in @var{text}.@*
12959 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12960
12961 @item $(wordlist @var{s},@var{e},@var{text})
12962 Returns the list of words in @var{text} from @var{s} to @var{e}.@*
12963 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12964
12965 @item $(firstword @var{names}@dots{})
12966 Extract the first word of @var{names}.@*
12967 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12968
12969 @item $(lastword @var{names}@dots{})
12970 Extract the last word of @var{names}.@*
12971 @xref{Text Functions, , Functions for String Substitution and Analysis}.
12972
12973 @item $(dir @var{names}@dots{})
12974 Extract the directory part of each file name.@*
12975 @xref{File Name Functions, ,Functions for File Names}.
12976
12977 @item $(notdir @var{names}@dots{})
12978 Extract the non-directory part of each file name.@*
12979 @xref{File Name Functions, ,Functions for File Names}.
12980
12981 @item $(suffix @var{names}@dots{})
12982 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
12983 @xref{File Name Functions, ,Functions for File Names}.
12984
12985 @item $(basename @var{names}@dots{})
12986 Extract the base name (name without suffix) of each file name.@*
12987 @xref{File Name Functions, ,Functions for File Names}.
12988
12989 @item $(addsuffix @var{suffix},@var{names}@dots{})
12990 Append @var{suffix} to each word in @var{names}.@*
12991 @xref{File Name Functions, ,Functions for File Names}.
12992
12993 @item $(addprefix @var{prefix},@var{names}@dots{})
12994 Prepend @var{prefix} to each word in @var{names}.@*
12995 @xref{File Name Functions, ,Functions for File Names}.
12996
12997 @item $(join @var{list1},@var{list2})
12998 Join two parallel lists of words.@*
12999 @xref{File Name Functions, ,Functions for File Names}.
13000
13001 @item $(wildcard @var{pattern}@dots{})
13002 Find file names matching a shell file name pattern (@emph{not} a
13003 @samp{%} pattern).@*
13004 @xref{Wildcard Function, ,The Function @code{wildcard}}.
13005
13006 @item $(realpath @var{names}@dots{})
13007 For each file name in @var{names}, expand to an absolute name that
13008 does not contain any @code{.}, @code{..}, nor symlinks.@*
13009 @xref{File Name Functions, ,Functions for File Names}.
13010
13011 @item $(abspath @var{names}@dots{})
13012 For each file name in @var{names}, expand to an absolute name that
13013 does not contain any @code{.} or @code{..} components, but preserves
13014 symlinks.@*
13015 @xref{File Name Functions, ,Functions for File Names}.
13016
13017 @item $(error @var{text}@dots{})
13018 When this function is evaluated, @code{make} generates a fatal error
13019 with the message @var{text}.@*
13020 @xref{Make Control Functions, ,Functions That Control Make}.
13021
13022 @item $(warning @var{text}@dots{})
13023 When this function is evaluated, @code{make} generates a warning with
13024 the message @var{text}.@*
13025 @xref{Make Control Functions, ,Functions That Control Make}.
13026
13027 @item $(shell @var{command})
13028 Execute a shell command and return its output.@*
13029 @xref{Shell Function, , The @code{shell} Function}.
13030
13031 @item $(origin @var{variable})
13032 Return a string describing how the @code{make} variable @var{variable} was
13033 defined.@*
13034 @xref{Origin Function, , The @code{origin} Function}.
13035
13036 @item $(flavor @var{variable})
13037 Return a string describing the flavor of the @code{make} variable
13038 @var{variable}.@*
13039 @xref{Flavor Function, , The @code{flavor} Function}.
13040
13041 @item $(let @var{var} [@var{var} ...],@var{words},@var{text})
13042 Evaluate @var{text} with the @var{var}s bound to the words in
13043 @var{words}.@*
13044 @xref{Let Function, ,The @code{let} Function}.
13045
13046 @item $(foreach @var{var},@var{words},@var{text})
13047 Evaluate @var{text} with @var{var} bound to each word in @var{words},
13048 and concatenate the results.@*
13049 @xref{Foreach Function, ,The @code{foreach} Function}.
13050
13051 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
13052 Evaluate the condition @var{condition}; if it's non-empty substitute
13053 the expansion of the @var{then-part} otherwise substitute the
13054 expansion of the @var{else-part}.@*
13055 @xref{Conditional Functions, ,Functions for Conditionals}.
13056
13057 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
13058 Evaluate each condition @var{conditionN} one at a time; substitute the
13059 first non-empty expansion.  If all expansions are empty, substitute
13060 the empty string.@*
13061 @xref{Conditional Functions, ,Functions for Conditionals}.
13062
13063 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
13064 Evaluate each condition @var{conditionN} one at a time; if any
13065 expansion results in the empty string substitute the empty string.  If
13066 all expansions result in a non-empty string, substitute the expansion
13067 of the last @var{condition}.@*
13068 @xref{Conditional Functions, ,Functions for Conditionals}.
13069
13070 @item $(intcmp @var{lhs},@var{rhs}[,@var{lt-part}[,@var{eq-part}[,@var{gt-part}]]])
13071 Compare @var{lhs} and @var{rhs} numerically; substitute the expansion of
13072 @var{lt-part}, @var{eq-part}, or @var{gt-part} depending on whether the
13073 left-hand side is less-than, equal-to, or greater-than the right-hand
13074 side, respectively.@*
13075 @xref{Conditional Functions, ,Functions for Conditionals}.
13076
13077 @item $(call @var{var},@var{param},@dots{})
13078 Evaluate the variable @var{var} replacing any references to @code{$(1)},
13079 @code{$(2)} with the first, second, etc.@: @var{param} values.@*
13080 @xref{Call Function, ,The @code{call} Function}.
13081
13082 @item $(eval @var{text})
13083 Evaluate @var{text} then read the results as makefile commands.
13084 Expands to the empty string.@*
13085 @xref{Eval Function, ,The @code{eval} Function}.
13086
13087 @item $(file @var{op} @var{filename},@var{text})
13088 Expand the arguments, then open the file @var{filename} using mode
13089 @var{op} and write @var{text} to that file.@*
13090 @xref{File Function, ,The @code{file} Function}.
13091
13092 @item $(value @var{var})
13093 Evaluates to the contents of the variable @var{var}, with no expansion
13094 performed on it.@*
13095 @xref{Value Function, ,The @code{value} Function}.
13096 @end table
13097
13098 Here is a summary of the automatic variables.
13099 @xref{Automatic Variables},
13100 for full information.
13101
13102 @table @code
13103 @item $@@
13104 The file name of the target.
13105
13106 @item $%
13107 The target member name, when the target is an archive member.
13108
13109 @item $<
13110 The name of the first prerequisite.
13111
13112 @item $?
13113 The names of all the prerequisites that are
13114 newer than the target, with spaces between them.
13115 For prerequisites which are archive members, only
13116 the named member is used (@pxref{Archives}).
13117
13118 @item $^
13119 @itemx $+
13120 The names of all the prerequisites, with spaces between them.  For
13121 prerequisites which are archive members, only the named member is used
13122 (@pxref{Archives}).  The value of @code{$^} omits duplicate
13123 prerequisites, while @code{$+} retains them and preserves their order.
13124
13125 @item $*
13126 The stem with which an implicit rule matches
13127 (@pxref{Pattern Match, ,How Patterns Match}).
13128
13129 @item $(@@D)
13130 @itemx $(@@F)
13131 The directory part and the file-within-directory part of @code{$@@}.
13132
13133 @item $(*D)
13134 @itemx $(*F)
13135 The directory part and the file-within-directory part of @code{$*}.
13136
13137 @item $(%D)
13138 @itemx $(%F)
13139 The directory part and the file-within-directory part of @code{$%}.
13140
13141 @item $(<D)
13142 @itemx $(<F)
13143 The directory part and the file-within-directory part of @code{$<}.
13144
13145 @item $(^D)
13146 @itemx $(^F)
13147 The directory part and the file-within-directory part of @code{$^}.
13148
13149 @item $(+D)
13150 @itemx $(+F)
13151 The directory part and the file-within-directory part of @code{$+}.
13152
13153 @item $(?D)
13154 @itemx $(?F)
13155 The directory part and the file-within-directory part of @code{$?}.
13156 @end table
13157
13158 These variables are used specially by GNU @code{make}:
13159
13160 @table @code
13161 @item MAKEFILES
13162
13163 Makefiles to be read on every invocation of @code{make}.@*
13164 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
13165
13166 @item VPATH
13167
13168 Directory search path for files not found in the current directory.@*
13169 @xref{General Search, , @code{VPATH} Search Path for All Prerequisites}.
13170
13171 @item SHELL
13172
13173 The name of the system default command interpreter, usually @file{/bin/sh}.
13174 You can set @code{SHELL} in the makefile to change the shell used to run
13175 recipes.  @xref{Execution, ,Recipe Execution}.  The @code{SHELL}
13176 variable is handled specially when importing from and exporting to the
13177 environment.  @xref{Choosing the Shell}.
13178
13179 @item MAKESHELL
13180
13181 On MS-DOS only, the name of the command interpreter that is to be used
13182 by @code{make}.  This value takes precedence over the value of
13183 @code{SHELL}.  @xref{Execution, ,MAKESHELL variable}.
13184
13185 @item MAKE
13186
13187 The name with which @code{make} was invoked.  Using this variable in
13188 recipes has special meaning.  @xref{MAKE Variable, ,How the
13189 @code{MAKE} Variable Works}.
13190
13191 @item MAKE_VERSION
13192
13193 The built-in variable @samp{MAKE_VERSION} expands to the version
13194 number of the GNU @code{make} program.
13195 @vindex MAKE_VERSION
13196
13197 @item MAKE_HOST
13198
13199 The built-in variable @samp{MAKE_HOST} expands to a string
13200 representing the host that GNU @code{make} was built to run on.
13201 @vindex MAKE_HOST
13202
13203 @item MAKELEVEL
13204
13205 The number of levels of recursion (sub-@code{make}s).@*
13206 @xref{Variables/Recursion}.
13207
13208 @item MAKEFLAGS
13209
13210 The flags given to @code{make}.  You can set this in the environment or
13211 a makefile to set flags.@*
13212 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
13213
13214 It is @emph{never} appropriate to use @code{MAKEFLAGS} directly in a
13215 recipe line: its contents may not be quoted correctly for use in the
13216 shell.  Always allow recursive @code{make}'s to obtain these values
13217 through the environment from its parent.
13218
13219 @item GNUMAKEFLAGS
13220
13221 Other flags parsed by @code{make}.  You can set this in the environment or
13222 a makefile to set @code{make} command-line flags.  GNU @code{make}
13223 never sets this variable itself.  This variable is only needed if
13224 you'd like to set GNU @code{make}-specific flags in a POSIX-compliant
13225 makefile.  This variable will be seen by GNU @code{make} and ignored
13226 by other @code{make} implementations.  It's not needed if you only use
13227 GNU @code{make}; just use @code{MAKEFLAGS} directly.
13228 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
13229
13230 @item MAKECMDGOALS
13231
13232 The targets given to @code{make} on the command line.  Setting this
13233 variable has no effect on the operation of @code{make}.@*
13234 @xref{Goals, ,Arguments to Specify the Goals}.
13235
13236 @item CURDIR
13237
13238 Set to the absolute pathname of the current working directory (after
13239 all @code{-C} options are processed, if any).  Setting this variable
13240 has no effect on the operation of @code{make}.@*
13241 @xref{Recursion, ,Recursive Use of @code{make}}.
13242
13243 @item SUFFIXES
13244
13245 The default list of suffixes before @code{make} reads any makefiles.
13246
13247 @item .LIBPATTERNS
13248 Defines the naming of the libraries @code{make} searches for, and their
13249 order.@*
13250 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
13251 @end table
13252
13253 @node Error Messages, Complex Makefile, Quick Reference, Top
13254 @comment  node-name,  next,  previous,  up
13255 @appendix Errors Generated by Make
13256
13257 Here is a list of the more common errors you might see generated by
13258 @code{make}, and some information about what they mean and how to fix
13259 them.
13260
13261 Sometimes @code{make} errors are not fatal, especially in the presence
13262 of a @code{-} prefix on a recipe line, or the @code{-k} command line
13263 option.  Errors that are fatal are prefixed with the string
13264 @code{***}.
13265
13266 Error messages are all either prefixed with the name of the program
13267 (usually @samp{make}), or, if the error is found in a makefile, the name
13268 of the file and line number containing the problem.
13269
13270 In the table below, these common prefixes are left off.
13271
13272 @table @samp
13273
13274 @item [@var{foo}] Error @var{NN}
13275 @itemx [@var{foo}] @var{signal description}
13276 These errors are not really @code{make} errors at all.  They mean that a
13277 program that @code{make} invoked as part of a recipe returned a
13278 non-0 error code (@samp{Error @var{NN}}), which @code{make} interprets
13279 as failure, or it exited in some other abnormal fashion (with a
13280 signal of some type).  @xref{Errors, ,Errors in Recipes}.
13281
13282 If no @code{***} is attached to the message, then the sub-process failed
13283 but the rule in the makefile was prefixed with the @code{-} special
13284 character, so @code{make} ignored the error.
13285
13286 @item missing separator.  Stop.
13287 @itemx missing separator (did you mean TAB instead of 8 spaces?).  Stop.
13288 This means that @code{make} could not understand much of anything
13289 about the makefile line it just read.  GNU @code{make} looks for
13290 various separators (@code{:}, @code{=}, recipe prefix characters,
13291 etc.) to indicate what kind of line it's parsing.  This message means
13292 it couldn't find a valid one.
13293
13294 One of the most common reasons for this message is that you (or
13295 perhaps your oh-so-helpful editor, as is the case with many MS-Windows
13296 editors) have attempted to indent your recipe lines with spaces
13297 instead of a tab character.  In this case, @code{make} will use the
13298 second form of the error above.  Remember that every line in the
13299 recipe must begin with a tab character (unless you set
13300 @code{.RECIPEPREFIX}; @pxref{Special Variables}).  Eight spaces do not
13301 count.  @xref{Rule Syntax}.
13302
13303 @item recipe commences before first target.  Stop.
13304 @itemx missing rule before recipe.  Stop.
13305 This means the first thing in the makefile seems to be part of a
13306 recipe: it begins with a recipe prefix character and doesn't appear to
13307 be a legal @code{make} directive (such as a variable assignment).
13308 Recipes must always be associated with a target.
13309
13310 The second form is generated if the line has a semicolon as the first
13311 non-whitespace character; @code{make} interprets this to mean you left
13312 out the "target: prerequisite" section of a rule.  @xref{Rule Syntax}.
13313
13314 @item No rule to make target `@var{xxx}'.
13315 @itemx No rule to make target `@var{xxx}', needed by `@var{yyy}'.
13316 This means that @code{make} decided it needed to build a target, but
13317 then couldn't find any instructions in the makefile on how to do that,
13318 either explicit or implicit (including in the default rules database).
13319
13320 If you want that file to be built, you will need to add a rule to your
13321 makefile describing how that target can be built.  Other possible
13322 sources of this problem are typos in the makefile (if that file name is
13323 wrong) or a corrupted source tree (if that file is not supposed to be
13324 built, but rather only a prerequisite).
13325
13326 @item No targets specified and no makefile found.  Stop.
13327 @itemx No targets.  Stop.
13328 The former means that you didn't provide any targets to be built on the
13329 command line, and @code{make} couldn't find any makefiles to read in.
13330 The latter means that some makefile was found, but it didn't contain any
13331 default goal and none was given on the command line.  GNU @code{make}
13332 has nothing to do in these situations.
13333 @xref{Makefile Arguments, ,Arguments to Specify the Makefile}.
13334
13335 @item Makefile `@var{xxx}' was not found.
13336 @itemx Included makefile `@var{xxx}' was not found.
13337 A makefile specified on the command line (first form) or included
13338 (second form) was not found.
13339
13340 @item warning: overriding recipe for target `@var{xxx}'
13341 @itemx warning: ignoring old recipe for target `@var{xxx}'
13342 GNU @code{make} allows only one recipe to be specified per target
13343 (except for double-colon rules).  If you give a recipe for a target
13344 which already has been defined to have one, this warning is issued and
13345 the second recipe will overwrite the first.  @xref{Multiple Rules,
13346 ,Multiple Rules for One Target}.
13347
13348 @item Circular @var{xxx} <- @var{yyy} dependency dropped.
13349 This means that @code{make} detected a loop in the dependency graph:
13350 after tracing the prerequisite @var{yyy} of target @var{xxx}, and its
13351 prerequisites, etc., one of them depended on @var{xxx} again.
13352
13353 @item Recursive variable `@var{xxx}' references itself (eventually).  Stop.
13354 This means you've defined a normal (recursive) @code{make} variable
13355 @var{xxx} that, when it's expanded, will refer to itself (@var{xxx}).
13356 This is not allowed; either use simply-expanded variables (@samp{:=}
13357 or @samp{::=}) or use the append operator (@samp{+=}).  @xref{Using
13358 Variables, ,How to Use Variables}.
13359
13360 @item Unterminated variable reference.  Stop.
13361 This means you forgot to provide the proper closing parenthesis
13362 or brace in your variable or function reference.
13363
13364 @item insufficient arguments to function `@var{xxx}'.  Stop.
13365 This means you haven't provided the requisite number of arguments for
13366 this function.  See the documentation of the function for a description
13367 of its arguments.  @xref{Functions, ,Functions for Transforming Text}.
13368
13369 @item missing target pattern.  Stop.
13370 @itemx multiple target patterns.  Stop.
13371 @itemx target pattern contains no `%'.  Stop.
13372 @itemx mixed implicit and static pattern rules.  Stop.
13373 These errors are generated for malformed static pattern rules
13374 (@pxref{Static Usage, ,Syntax of Static Pattern Rules}).  The first
13375 means the target-pattern part of the rule is empty; the second means
13376 there are multiple pattern characters (@code{%}) in the target-pattern
13377 part; the third means there are no pattern characters in the
13378 target-pattern part; and the fourth means that all three parts of the
13379 static pattern rule contain pattern characters (@code{%})--the first
13380 part should not contain pattern characters.
13381
13382 If you see these errors and you aren't trying to create a static
13383 pattern rule, check the value of any variables in your target and
13384 prerequisite lists to be sure they do not contain colons.
13385
13386 @item warning: -jN forced in submake: disabling jobserver mode.
13387 This warning and the next are generated if @code{make} detects error
13388 conditions related to parallel processing on systems where
13389 sub-@code{make}s can communicate (@pxref{Options/Recursion,
13390 ,Communicating Options to a Sub-@code{make}}).  This warning is
13391 generated if a recursive invocation of a @code{make} process is forced
13392 to have @samp{-j@var{N}} in its argument list (where @var{N} is greater
13393 than one).  This could happen, for example, if you set the @code{MAKE}
13394 environment variable to @samp{make -j2}.  In this case, the
13395 sub-@code{make} doesn't communicate with other @code{make} processes and
13396 will simply pretend it has two jobs of its own.
13397
13398 @item warning: jobserver unavailable: using -j1.  Add `+' to parent make rule.
13399 In order for @code{make} processes to communicate, the parent will pass
13400 information to the child.  Since this could result in problems if the
13401 child process isn't actually a @code{make}, the parent will only do this
13402 if it thinks the child is a @code{make}.  The parent uses the normal
13403 algorithms to determine this (@pxref{MAKE Variable, ,How the @code{MAKE}
13404 Variable Works}).  If the makefile is constructed such that the parent
13405 doesn't know the child is a @code{make} process, then the child will
13406 receive only part of the information necessary.  In this case, the child
13407 will generate this warning message and proceed with its build in a
13408 sequential manner.
13409
13410 @item warning: ignoring prerequisites on suffix rule definition
13411 According to POSIX, a suffix rule cannot contain prerequisites.  If a rule
13412 that could be a suffix rule has prerequisites it is interpreted as a simple
13413 explicit rule, with an odd target name.  This requirement is obeyed when
13414 POSIX-conforming mode is enabled (the @code{.POSIX} target is defined).  In
13415 versions of GNU @code{make} prior to 4.3, no warning was emitted and a
13416 suffix rule was created, however all prerequisites were ignored and were not
13417 part of the suffix rule.  Starting with GNU @code{make} 4.3 the behavior is
13418 the same, and in addition this warning is generated.  In a future version
13419 the POSIX-conforming behavior will be the only behavior: no rule with a
13420 prerequisite can be suffix rule and this warning will be removed.
13421
13422 @end table
13423
13424 @node Complex Makefile, GNU Free Documentation License, Error Messages, Top
13425 @appendix Complex Makefile Example
13426
13427 Here is the makefile for the GNU @code{tar} program.  This is a
13428 moderately complex makefile.  The first line uses a @code{#!} setting
13429 to allow the makefile to be executed directly.
13430
13431 Because it is the first target, the default goal is @samp{all}.  An
13432 interesting feature of this makefile is that @file{testpad.h} is a
13433 source file automatically created by the @code{testpad} program,
13434 itself compiled from @file{testpad.c}.
13435
13436 If you type @samp{make} or @samp{make all}, then @code{make} creates
13437 the @file{tar} executable, the @file{rmt} daemon that provides
13438 remote tape access, and the @file{tar.info} Info file.
13439
13440 If you type @samp{make install}, then @code{make} not only creates
13441 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
13442 them.
13443
13444 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
13445 files, and the @file{tar}, @file{rmt}, @file{testpad},
13446 @file{testpad.h}, and @file{core} files.
13447
13448 If you type @samp{make distclean}, then @code{make} not only removes
13449 the same files as does @samp{make clean} but also the
13450 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
13451 (Although it is not evident, this makefile (and
13452 @file{config.status}) is generated by the user with the
13453 @code{configure} program, which is provided in the @code{tar}
13454 distribution, but is not shown here.)
13455
13456 If you type @samp{make realclean}, then @code{make} removes the same
13457 files as does @samp{make distclean} and also removes the Info files
13458 generated from @file{tar.texinfo}.
13459
13460 In addition, there are targets @code{shar} and @code{dist} that create
13461 distribution kits.
13462
13463 @example
13464 @group
13465 #!/usr/bin/make -f
13466 # Generated automatically from Makefile.in by configure.
13467 # Un*x Makefile for GNU tar program.
13468 # Copyright (C) 1991 Free Software Foundation, Inc.
13469 @end group
13470
13471 @group
13472 # This program is free software; you can redistribute
13473 # it and/or modify it under the terms of the GNU
13474 # General Public License @dots{}
13475 @dots{}
13476 @dots{}
13477 @end group
13478
13479 SHELL = /bin/sh
13480
13481 #### Start of system configuration section. ####
13482
13483 srcdir = .
13484
13485 @group
13486 # If you use gcc, you should either run the
13487 # fixincludes script that comes with it or else use
13488 # gcc with the -traditional option.  Otherwise ioctl
13489 # calls will be compiled incorrectly on some systems.
13490 CC = gcc -O
13491 YACC = bison -y
13492 INSTALL = /usr/local/bin/install -c
13493 INSTALLDATA = /usr/local/bin/install -c -m 644
13494 @end group
13495
13496 # Things you might add to DEFS:
13497 # -DSTDC_HEADERS        If you have ANSI C headers and
13498 #                       libraries.
13499 # -DPOSIX               If you have POSIX.1 headers and
13500 #                       libraries.
13501 # -DBSD42               If you have sys/dir.h (unless
13502 #                       you use -DPOSIX), sys/file.h,
13503 #                       and st_blocks in `struct stat'.
13504 # -DUSG                 If you have System V/ANSI C
13505 #                       string and memory functions
13506 #                       and headers, sys/sysmacros.h,
13507 #                       fcntl.h, getcwd, no valloc,
13508 #                       and ndir.h (unless
13509 #                       you use -DDIRENT).
13510 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not
13511 #                       include memory.h.
13512 # -DDIRENT              If USG and you have dirent.h
13513 #                       instead of ndir.h.
13514 # -DSIGTYPE=int         If your signal handlers
13515 #                       return int, not void.
13516 # -DNO_MTIO             If you lack sys/mtio.h
13517 #                       (magtape ioctls).
13518 # -DNO_REMOTE           If you do not have a remote shell
13519 #                       or rexec.
13520 # -DUSE_REXEC           To use rexec for remote tape
13521 #                       operations instead of
13522 #                       forking rsh or remsh.
13523 # -DVPRINTF_MISSING     If you lack vprintf function
13524 #                       (but have _doprnt).
13525 # -DDOPRNT_MISSING      If you lack _doprnt function.
13526 #                       Also need to define
13527 #                       -DVPRINTF_MISSING.
13528 # -DFTIME_MISSING       If you lack ftime system call.
13529 # -DSTRSTR_MISSING      If you lack strstr function.
13530 # -DVALLOC_MISSING      If you lack valloc function.
13531 # -DMKDIR_MISSING       If you lack mkdir and
13532 #                       rmdir system calls.
13533 # -DRENAME_MISSING      If you lack rename system call.
13534 # -DFTRUNCATE_MISSING   If you lack ftruncate
13535 #                       system call.
13536 # -DV7                  On Version 7 Unix (not
13537 #                       tested in a long time).
13538 # -DEMUL_OPEN3          If you lack a 3-argument version
13539 #                       of open, and want to emulate it
13540 #                       with system calls you do have.
13541 # -DNO_OPEN3            If you lack the 3-argument open
13542 #                       and want to disable the tar -k
13543 #                       option instead of emulating open.
13544 # -DXENIX               If you have sys/inode.h
13545 #                       and need it 94 to be included.
13546
13547 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
13548         -DVPRINTF_MISSING -DBSD42
13549 # Set this to rtapelib.o unless you defined NO_REMOTE,
13550 # in which case make it empty.
13551 RTAPELIB = rtapelib.o
13552 LIBS =
13553 DEF_AR_FILE = /dev/rmt8
13554 DEFBLOCKING = 20
13555
13556 @group
13557 CDEBUG = -g
13558 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
13559         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
13560         -DDEFBLOCKING=$(DEFBLOCKING)
13561 LDFLAGS = -g
13562 @end group
13563
13564 @group
13565 prefix = /usr/local
13566 # Prefix for each installed program,
13567 # normally empty or `g'.
13568 binprefix =
13569
13570 # The directory to install tar in.
13571 bindir = $(prefix)/bin
13572
13573 # The directory to install the info files in.
13574 infodir = $(prefix)/info
13575 @end group
13576
13577 #### End of system configuration section. ####
13578
13579 @group
13580 SRCS_C  = tar.c create.c extract.c buffer.c   \
13581           getoldopt.c update.c gnu.c mangle.c \
13582           version.c list.c names.c diffarch.c \
13583           port.c wildmat.c getopt.c getopt1.c \
13584           regex.c
13585 SRCS_Y  = getdate.y
13586 SRCS    = $(SRCS_C) $(SRCS_Y)
13587 OBJS    = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB)
13588 @end group
13589 @group
13590 AUX =   README COPYING ChangeLog Makefile.in  \
13591         makefile.pc configure configure.in \
13592         tar.texinfo tar.info* texinfo.tex \
13593         tar.h port.h open3.h getopt.h regex.h \
13594         rmt.h rmt.c rtapelib.c alloca.c \
13595         msd_dir.h msd_dir.c tcexparg.c \
13596         level-0 level-1 backup-specs testpad.c
13597 @end group
13598
13599 .PHONY: all
13600 all:    tar rmt tar.info
13601
13602 @group
13603 tar:    $(OBJS)
13604         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
13605 @end group
13606
13607 @group
13608 rmt:    rmt.c
13609         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
13610 @end group
13611
13612 @group
13613 tar.info: tar.texinfo
13614         makeinfo tar.texinfo
13615 @end group
13616
13617 @group
13618 .PHONY: install
13619 install: all
13620         $(INSTALL) tar $(bindir)/$(binprefix)tar
13621         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
13622         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
13623 @end group
13624
13625 @group
13626 $(OBJS): tar.h port.h testpad.h
13627 regex.o buffer.o tar.o: regex.h
13628 # getdate.y has 8 shift/reduce conflicts.
13629 @end group
13630
13631 @group
13632 testpad.h: testpad
13633         ./testpad
13634 @end group
13635
13636 @group
13637 testpad: testpad.o
13638         $(CC) -o $@@ testpad.o
13639 @end group
13640
13641 @group
13642 TAGS:   $(SRCS)
13643         etags $(SRCS)
13644 @end group
13645
13646 @group
13647 .PHONY: clean
13648 clean:
13649         rm -f *.o tar rmt testpad testpad.h core
13650 @end group
13651
13652 @group
13653 .PHONY: distclean
13654 distclean: clean
13655         rm -f TAGS Makefile config.status
13656 @end group
13657
13658 @group
13659 .PHONY: realclean
13660 realclean: distclean
13661         rm -f tar.info*
13662 @end group
13663
13664 @group
13665 .PHONY: shar
13666 shar: $(SRCS) $(AUX)
13667         shar $(SRCS) $(AUX) | compress \
13668           > tar-`sed -e '/version_string/!d' \
13669                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
13670                      -e q
13671                      version.c`.shar.Z
13672 @end group
13673
13674 @group
13675 .PHONY: dist
13676 dist: $(SRCS) $(AUX)
13677         echo tar-`sed \
13678              -e '/version_string/!d' \
13679              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
13680              -e q
13681              version.c` > .fname
13682         -rm -rf `cat .fname`
13683         mkdir `cat .fname`
13684         ln $(SRCS) $(AUX) `cat .fname`
13685         tar chZf `cat .fname`.tar.Z `cat .fname`
13686         -rm -rf `cat .fname` .fname
13687 @end group
13688
13689 @group
13690 tar.zoo: $(SRCS) $(AUX)
13691         -rm -rf tmp.dir
13692         -mkdir tmp.dir
13693         -rm tar.zoo
13694         for X in $(SRCS) $(AUX) ; do \
13695             echo $$X ; \
13696             sed 's/$$/^M/' $$X \
13697             > tmp.dir/$$X ; done
13698         cd tmp.dir ; zoo aM ../tar.zoo *
13699         -rm -rf tmp.dir
13700 @end group
13701 @end example
13702
13703 @node GNU Free Documentation License, Concept Index, Complex Makefile, Top
13704 @appendix GNU Free Documentation License
13705 @cindex FDL, GNU Free Documentation License
13706 @include fdl.texi
13707
13708 @node Concept Index, Name Index, GNU Free Documentation License, Top
13709 @unnumbered Index of Concepts
13710
13711 @printindex cp
13712
13713 @node Name Index,  , Concept Index, Top
13714 @unnumbered Index of Functions, Variables, & Directives
13715
13716 @printindex fn
13717
13718 @bye
13719
13720 @c Local Variables:
13721 @c eval: (setq fill-column 78)
13722 @c End: