Rearrange elements to reduce struct size on 64bit architectures.
[make.git] / doc / make.texi
blobe61b8a012d77a9b2ad032e0b61f87f9ff326b72b
1 \input texinfo                @c -*- Texinfo -*-
2 @c %**start of header
3 @setfilename make.info
5 @include version.texi
6 @set EDITION 0.72
7 @set RCSID $Id: make.texi,v 1.79 2012/03/03 18:45:08 psmith Exp $
9 @settitle GNU @code{make}
10 @setchapternewpage odd
11 @c Combine the variable and function indices:
12 @syncodeindex vr fn
13 @c Combine the program and concept indices:
14 @syncodeindex pg cp
15 @c FSF publishers: format makebook.texi instead of using this file directly.
16 @c ISBN confirmed by Jasimin Huang <jasimin@fsf.org> on 25 Mar 2009
17 @set ISBN 1-882114-83-3
18 @c %**end of header
20 @copying
21 This file documents the GNU @code{make} utility, which determines
22 automatically which pieces of a large program need to be recompiled,
23 and issues the commands to recompile them.
25 This is Edition @value{EDITION}, last updated @value{UPDATED},
26 of @cite{The GNU Make Manual}, for GNU @code{make} version @value{VERSION}.
28 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
29 1996, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007,
30 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
32 @quotation
33 Permission is granted to copy, distribute and/or modify this document
34 under the terms of the GNU Free Documentation License, Version 1.3 or
35 any later version published by the Free Software Foundation; with no
36 Invariant Sections, with the Front-Cover Texts being ``A GNU Manual,''
37 and with the Back-Cover Texts as in (a) below.  A copy of the
38 license is included in the section entitled ``GNU Free Documentation
39 License.''
41 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
42 modify this GNU manual.  Buying copies from the FSF supports it in
43 developing GNU and promoting software freedom.''
44 @end quotation
45 @end copying
47 @c finalout
49 @c ISPELL CHECK: done, 10 June 1993 --roland
50 @c ISPELL CHECK: done, 2000-06-25 --Martin Buchholz
53 @dircategory Software development
54 @direntry
55 * Make: (make).            Remake files automatically.
56 @end direntry
58 @iftex
59 @shorttitlepage GNU Make
60 @end iftex
61 @titlepage
62 @title GNU Make
63 @subtitle A Program for Directing Recompilation
64 @subtitle GNU @code{make} Version @value{VERSION}
65 @subtitle @value{UPDATED-MONTH}
66 @author Richard M. Stallman, Roland McGrath, Paul D. Smith
67 @page
68 @vskip 0pt plus 1filll
69 @insertcopying
70 @sp 2
71 Published by the Free Software Foundation @*
72 51 Franklin St. -- Fifth Floor @*
73 Boston, MA 02110-1301 USA @*
74 ISBN @value{ISBN} @*
75 @sp 2
76 Cover art by Etienne Suvasa.
77 @end titlepage
79 @summarycontents
80 @contents
82 @ifnottex
83 @node Top, Overview, (dir), (dir)
84 @top GNU @code{make}
86 @insertcopying
87 @end ifnottex
89 @menu
90 * Overview::                    Overview of @code{make}.
91 * Introduction::                An introduction to @code{make}.
92 * Makefiles::                   Makefiles tell @code{make} what to do.
93 * Rules::                       Rules describe when a file must be remade.
94 * Recipes::                     Recipes say how to remake a file.
95 * Using Variables::             You can use variables to avoid repetition.
96 * Conditionals::                Use or ignore parts of the makefile based
97                                   on the values of variables.
98 * Functions::                   Many powerful ways to manipulate text.
99 * Invoking make: Running.       How to invoke @code{make} on the command line.
100 * Implicit Rules::              Use implicit rules to treat many files alike,
101                                   based on their file names.
102 * Archives::                    How @code{make} can update library archives.
103 * Features::                    Features GNU @code{make} has over other @code{make}s.
104 * Missing::                     What GNU @code{make} lacks from other @code{make}s.
105 * Makefile Conventions::        Conventions for writing makefiles for
106                                   GNU programs.
107 * Quick Reference::             A quick reference for experienced users.
108 * Error Messages::              A list of common errors generated by @code{make}.
109 * Complex Makefile::            A real example of a straightforward,
110                                   but nontrivial, makefile.
112 * GNU Free Documentation License::  License for copying this manual.
113 * Concept Index::               Index of Concepts.
114 * Name Index::                  Index of Functions, Variables, & Directives.
116 @detailmenu
117  --- The Detailed Node Listing ---
119 Overview of @code{make}
121 * Preparing::                   Preparing and running @code{make}.
122 * Reading::                     On reading this text.
123 * Bugs::                        Problems and bugs.
125 An Introduction to Makefiles
127 * Rule Introduction::           What a rule looks like.
128 * Simple Makefile::             A simple makefile.
129 * How Make Works::              How @code{make} processes this makefile.
130 * Variables Simplify::          Variables make makefiles simpler.
131 * make Deduces::                Letting @code{make} deduce the recipes.
132 * Combine By Prerequisite::     Another style of makefile.
133 * Cleanup::                     Rules for cleaning the directory.
135 Writing Makefiles
137 * Makefile Contents::           What makefiles contain.
138 * Makefile Names::              How to name your makefile.
139 * Include::                     How one makefile can use another makefile.
140 * MAKEFILES Variable::          The environment can specify extra makefiles.
141 * Remaking Makefiles::          How makefiles get remade.
142 * Overriding Makefiles::        How to override part of one makefile
143                                   with another makefile.
144 * Reading Makefiles::           How makefiles are parsed.
145 * Secondary Expansion::         How and when secondary expansion is performed.
147 What Makefiles Contain
149 * Splitting Lines::             Splitting long lines in makefiles
151 Writing Rules
153 * Rule Example::                An example explained.
154 * Rule Syntax::                 General syntax explained.
155 * Prerequisite Types::          There are two types of prerequisites.
156 * Wildcards::                   Using wildcard characters such as `*'.
157 * Directory Search::            Searching other directories for source files.
158 * Phony Targets::               Using a target that is not a real file's name.
159 * Force Targets::               You can use a target without a recipe
160                                   or prerequisites to mark other targets
161                                   as phony.
162 * Empty Targets::               When only the date matters and the
163                                   files are empty.
164 * Special Targets::             Targets with special built-in meanings.
165 * Multiple Targets::            When to make use of several targets in a rule.
166 * Multiple Rules::              How to use several rules with the same target.
167 * Static Pattern::              Static pattern rules apply to multiple targets
168                                   and can vary the prerequisites according to
169                                   the target name.
170 * Double-Colon::                How to use a special kind of rule to allow
171                                   several independent rules for one target.
172 * Automatic Prerequisites::     How to automatically generate rules giving
173                                   prerequisites from source files themselves.
175 Using Wildcard Characters in File Names
177 * Wildcard Examples::           Several examples.
178 * Wildcard Pitfall::            Problems to avoid.
179 * Wildcard Function::           How to cause wildcard expansion where
180                                   it does not normally take place.
182 Searching Directories for Prerequisites
184 * General Search::              Specifying a search path that applies
185                                   to every prerequisite.
186 * Selective Search::            Specifying a search path
187                                   for a specified class of names.
188 * Search Algorithm::            When and how search paths are applied.
189 * Recipes/Search::              How to write recipes that work together
190                                   with search paths.
191 * Implicit/Search::             How search paths affect implicit rules.
192 * Libraries/Search::            Directory search for link libraries.
194 Static Pattern Rules
196 * Static Usage::                The syntax of static pattern rules.
197 * Static versus Implicit::      When are they better than implicit rules?
199 Writing Recipes in Rules
201 * Recipe Syntax::               Recipe syntax features and pitfalls.
202 * Echoing::                     How to control when recipes are echoed.
203 * Execution::                   How recipes are executed.
204 * Parallel::                    How recipes can be executed in parallel.
205 * Errors::                      What happens after a recipe execution error.
206 * Interrupts::                  What happens when a recipe is interrupted.
207 * Recursion::                   Invoking @code{make} from makefiles.
208 * Canned Recipes::              Defining canned recipes.
209 * Empty Recipes::               Defining useful, do-nothing recipes.
211 Recipe Syntax
213 * Splitting Recipe Lines::      Breaking long recipe lines for readability.
214 * Variables in Recipes::        Using @code{make} variables in recipes.
216 Recipe Execution
218 * One Shell::                   One shell for all lines in a recipe.
219 * Choosing the Shell::          How @code{make} chooses the shell used
220                                   to run recipes.
222 Recursive Use of @code{make}
224 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
225 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
226 * Options/Recursion::           How to communicate options to a sub-@code{make}.
227 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
228                                   helps debug use of recursive @code{make} commands.
230 How to Use Variables
232 * Reference::                   How to use the value of a variable.
233 * Flavors::                     Variables come in two flavors.
234 * Advanced::                    Advanced features for referencing a variable.
235 * Values::                      All the ways variables get their values.
236 * Setting::                     How to set a variable in the makefile.
237 * Appending::                   How to append more text to the old value
238                                   of a variable.
239 * Override Directive::          How to set a variable in the makefile even if
240                                   the user has set it with a command argument.
241 * Multi-Line::                  An alternate way to set a variable
242                                   to a multi-line string.
243 * Undefine Directive::          How to undefine a variable so that it appears
244                                   as if it was never set.
245 * Environment::                 Variable values can come from the environment.
246 * Target-specific::             Variable values can be defined on a per-target
247                                   basis.
248 * Pattern-specific::            Target-specific variable values can be applied
249                                   to a group of targets that match a pattern.
250 * Suppressing Inheritance::     Suppress inheritance of variables.
251 * Special Variables::           Variables with special meaning or behavior.
253 Advanced Features for Reference to Variables
255 * Substitution Refs::           Referencing a variable with
256                                   substitutions on the value.
257 * Computed Names::              Computing the name of the variable to refer to.
259 Conditional Parts of Makefiles
261 * Conditional Example::         Example of a conditional
262 * Conditional Syntax::          The syntax of conditionals.
263 * Testing Flags::               Conditionals that test flags.
265 Functions for Transforming Text
267 * Syntax of Functions::         How to write a function call.
268 * Text Functions::              General-purpose text manipulation functions.
269 * File Name Functions::         Functions for manipulating file names.
270 * Conditional Functions::       Functions that implement conditions.
271 * Foreach Function::            Repeat some text with controlled variation.
272 * File Function::               Write text to a file.
273 * Call Function::               Expand a user-defined function.
274 * Value Function::              Return the un-expanded value of a variable.
275 * Eval Function::               Evaluate the arguments as makefile syntax.
276 * Origin Function::             Find where a variable got its value.
277 * Flavor Function::             Find out the flavor of a variable.
278 * Make Control Functions::      Functions that control how make runs.
279 * Shell Function::              Substitute the output of a shell command.
280 * Guile Function::              Call the GNU Guile embedded scripting language.
282 The @code{guile} Function
284 * Guile Types::                 Converting Guile types to @code{make} strings.
285 * Guile Interface::             Invoking @code{make} functions from Guile.
286 * Guile Example::               Example using Guile in @code{make}.
288 How to Run @code{make}
290 * Makefile Arguments::          How to specify which makefile to use.
291 * Goals::                       How to use goal arguments to specify which
292                                   parts of the makefile to use.
293 * Instead of Execution::        How to use mode flags to specify what
294                                   kind of thing to do with the recipes
295                                   in the makefile other than simply
296                                   execute them.
297 * Avoiding Compilation::        How to avoid recompiling certain files.
298 * Overriding::                  How to override a variable to specify
299                                   an alternate compiler and other things.
300 * Testing::                     How to proceed past some errors, to
301                                   test compilation.
302 * Options Summary::             Summary of Options
304 Using Implicit Rules
306 * Using Implicit::              How to use an existing implicit rule
307                                   to get the recipes for updating a file.
308 * Catalogue of Rules::          A list of built-in implicit rules.
309 * Implicit Variables::          How to change what predefined rules do.
310 * Chained Rules::               How to use a chain of implicit rules.
311 * Pattern Rules::               How to define new implicit rules.
312 * Last Resort::                 How to define a recipe for rules which
313                                   cannot find any.
314 * Suffix Rules::                The old-fashioned style of implicit rule.
315 * Implicit Rule Search::        The precise algorithm for applying
316                                   implicit rules.
318 Defining and Redefining Pattern Rules
320 * Pattern Intro::               An introduction to pattern rules.
321 * Pattern Examples::            Examples of pattern rules.
322 * Automatic Variables::         How to use automatic variables in the
323                                   recipe of implicit rules.
324 * Pattern Match::               How patterns match.
325 * Match-Anything Rules::        Precautions you should take prior to
326                                   defining rules that can match any
327                                   target file whatever.
328 * Canceling Rules::             How to override or cancel built-in rules.
330 Using @code{make} to Update Archive Files
332 * Archive Members::             Archive members as targets.
333 * Archive Update::              The implicit rule for archive member targets.
334 * Archive Pitfalls::            Dangers to watch out for when using archives.
335 * Archive Suffix Rules::        You can write a special kind of suffix rule
336                                   for updating archives.
338 Implicit Rule for Archive Member Targets
340 * Archive Symbols::             How to update archive symbol directories.
342 @end detailmenu
343 @end menu
345 @node Overview, Introduction, Top, Top
346 @comment  node-name,  next,  previous,  up
347 @chapter Overview of @code{make}
349 The @code{make} utility automatically determines which pieces of a large
350 program need to be recompiled, and issues commands to recompile them.
351 This manual describes GNU @code{make}, which was implemented by Richard
352 Stallman and Roland McGrath.  Development since Version 3.76 has been
353 handled by Paul D. Smith.
355 GNU @code{make} conforms to section 6.2 of @cite{IEEE Standard
356 1003.2-1992} (POSIX.2).
357 @cindex POSIX
358 @cindex IEEE Standard 1003.2
359 @cindex standards conformance
361 Our examples show C programs, since they are most common, but you can use
362 @code{make} with any programming language whose compiler can be run with a
363 shell command.  Indeed, @code{make} is not limited to programs.  You can
364 use it to describe any task where some files must be updated automatically
365 from others whenever the others change.
367 @menu
368 * Preparing::                   Preparing and running @code{make}.
369 * Reading::                     On reading this text.
370 * Bugs::                        Problems and bugs.
371 @end menu
373 @node Preparing, Reading, Overview, Overview
374 @ifnottex
375 @heading Preparing and Running Make
376 @end ifnottex
378 To prepare to use @code{make}, you must write a file called
379 the @dfn{makefile} that describes the relationships among files
380 in your program and provides commands for updating each file.
381 In a program, typically, the executable file is updated from object
382 files, which are in turn made by compiling source files.@refill
384 Once a suitable makefile exists, each time you change some source files,
385 this simple shell command:
387 @example
388 make
389 @end example
391 @noindent
392 suffices to perform all necessary recompilations.  The @code{make} program
393 uses the makefile data base and the last-modification times of the files to
394 decide which of the files need to be updated.  For each of those files, it
395 issues the recipes recorded in the data base.
397 You can provide command line arguments to @code{make} to control which
398 files should be recompiled, or how.  @xref{Running, ,How to Run
399 @code{make}}.
401 @node Reading, Bugs, Preparing, Overview
402 @section How to Read This Manual
404 If you are new to @code{make}, or are looking for a general
405 introduction, read the first few sections of each chapter, skipping the
406 later sections.  In each chapter, the first few sections contain
407 introductory or general information and the later sections contain
408 specialized or technical information.
409 @ifnottex
410 The exception is the second chapter, @ref{Introduction, ,An
411 Introduction to Makefiles}, all of which is introductory.
412 @end ifnottex
413 @iftex
414 The exception is @ref{Introduction, ,An Introduction to Makefiles},
415 all of which is introductory.
416 @end iftex
418 If you are familiar with other @code{make} programs, see @ref{Features,
419 ,Features of GNU @code{make}}, which lists the enhancements GNU
420 @code{make} has, and @ref{Missing, ,Incompatibilities and Missing
421 Features}, which explains the few things GNU @code{make} lacks that
422 others have.
424 For a quick summary, see @ref{Options Summary}, @ref{Quick Reference},
425 and @ref{Special Targets}.
427 @node Bugs,  , Reading, Overview
428 @section Problems and Bugs
429 @cindex reporting bugs
430 @cindex bugs, reporting
431 @cindex problems and bugs, reporting
433 If you have problems with GNU @code{make} or think you've found a bug,
434 please report it to the developers; we cannot promise to do anything but
435 we might well want to fix it.
437 Before reporting a bug, make sure you've actually found a real bug.
438 Carefully reread the documentation and see if it really says you can do
439 what you're trying to do.  If it's not clear whether you should be able
440 to do something or not, report that too; it's a bug in the
441 documentation!
443 Before reporting a bug or trying to fix it yourself, try to isolate it
444 to the smallest possible makefile that reproduces the problem.  Then
445 send us the makefile and the exact results @code{make} gave you,
446 including any error or warning messages.  Please don't paraphrase
447 these messages: it's best to cut and paste them into your report.
448 When generating this small makefile, be sure to not use any non-free
449 or unusual tools in your recipes: you can almost always emulate what
450 such a tool would do with simple shell commands.  Finally, be sure to
451 explain what you expected to occur; this will help us decide whether
452 the problem was really in the documentation.
454 Once you have a precise problem you can report it in one of two ways.
455 Either send electronic mail to:
457 @example
458     bug-make@@gnu.org
459 @end example
461 @noindent
462 or use our Web-based project management tool, at:
464 @example
465     http://savannah.gnu.org/projects/make/
466 @end example
468 @noindent
469 In addition to the information above, please be careful to include the
470 version number of @code{make} you are using.  You can get this
471 information with the command @samp{make --version}.  Be sure also to
472 include the type of machine and operating system you are using.  One
473 way to obtain this information is by looking at the final lines of
474 output from the command @samp{make --help}.
476 @node Introduction, Makefiles, Overview, Top
477 @comment  node-name,  next,  previous,  up
478 @chapter An Introduction to Makefiles
480 You need a file called a @dfn{makefile} to tell @code{make} what to do.
481 Most often, the makefile tells @code{make} how to compile and link a
482 program.
483 @cindex makefile
485 In this chapter, we will discuss a simple makefile that describes how to
486 compile and link a text editor which consists of eight C source files
487 and three header files.  The makefile can also tell @code{make} how to
488 run miscellaneous commands when explicitly asked (for example, to remove
489 certain files as a clean-up operation).  To see a more complex example
490 of a makefile, see @ref{Complex Makefile}.
492 When @code{make} recompiles the editor, each changed C source file
493 must be recompiled.  If a header file has changed, each C source file
494 that includes the header file must be recompiled to be safe.  Each
495 compilation produces an object file corresponding to the source file.
496 Finally, if any source file has been recompiled, all the object files,
497 whether newly made or saved from previous compilations, must be linked
498 together to produce the new executable editor.
499 @cindex recompilation
500 @cindex editor
502 @menu
503 * Rule Introduction::           What a rule looks like.
504 * Simple Makefile::             A simple makefile.
505 * How Make Works::              How @code{make} processes this makefile.
506 * Variables Simplify::          Variables make makefiles simpler.
507 * make Deduces::                Letting @code{make} deduce the recipes.
508 * Combine By Prerequisite::     Another style of makefile.
509 * Cleanup::                     Rules for cleaning the directory.
510 @end menu
512 @node Rule Introduction, Simple Makefile, Introduction, Introduction
513 @comment  node-name,  next,  previous,  up
514 @section What a Rule Looks Like
515 @cindex rule, introduction to
516 @cindex makefile rule parts
517 @cindex parts of makefile rule
519 A simple makefile consists of ``rules'' with the following shape:
521 @cindex targets, introduction to
522 @cindex prerequisites, introduction to
523 @cindex recipes, introduction to
524 @example
525 @group
526 @var{target} @dots{} : @var{prerequisites} @dots{}
527         @var{recipe}
528         @dots{}
529         @dots{}
530 @end group
531 @end example
533 A @dfn{target} is usually the name of a file that is generated by a
534 program; examples of targets are executable or object files.  A target
535 can also be the name of an action to carry out, such as @samp{clean}
536 (@pxref{Phony Targets}).
538 A @dfn{prerequisite} is a file that is used as input to create the
539 target.  A target often depends on several files.
541 @cindex tabs in rules
542 A @dfn{recipe} is an action that @code{make} carries out.  A recipe
543 may have more than one command, either on the same line or each on its
544 own line.  @strong{Please note:} you need to put a tab character at
545 the beginning of every recipe line!  This is an obscurity that catches
546 the unwary.  If you prefer to prefix your recipes with a character
547 other than tab, you can set the @code{.RECIPEPREFIX} variable to an
548 alternate character (@pxref{Special Variables}).
550 Usually a recipe is in a rule with prerequisites and serves to create a
551 target file if any of the prerequisites change.  However, the rule that
552 specifies a recipe for the target need not have prerequisites.  For
553 example, the rule containing the delete command associated with the
554 target @samp{clean} does not have prerequisites.
556 A @dfn{rule}, then, explains how and when to remake certain files
557 which are the targets of the particular rule.  @code{make} carries out
558 the recipe on the prerequisites to create or update the target.  A
559 rule can also explain how and when to carry out an action.
560 @xref{Rules, , Writing Rules}.
562 A makefile may contain other text besides rules, but a simple makefile
563 need only contain rules.  Rules may look somewhat more complicated
564 than shown in this template, but all fit the pattern more or less.
566 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
567 @section A Simple Makefile
568 @cindex simple makefile
569 @cindex makefile, simple
571 Here is a straightforward makefile that describes the way an
572 executable file called @code{edit} depends on eight object files
573 which, in turn, depend on eight C source and three header files.
575 In this example, all the C files include @file{defs.h}, but only those
576 defining editing commands include @file{command.h}, and only low
577 level files that change the editor buffer include @file{buffer.h}.
579 @example
580 @group
581 edit : main.o kbd.o command.o display.o \
582        insert.o search.o files.o utils.o
583         cc -o edit main.o kbd.o command.o display.o \
584                    insert.o search.o files.o utils.o
586 main.o : main.c defs.h
587         cc -c main.c
588 kbd.o : kbd.c defs.h command.h
589         cc -c kbd.c
590 command.o : command.c defs.h command.h
591         cc -c command.c
592 display.o : display.c defs.h buffer.h
593         cc -c display.c
594 insert.o : insert.c defs.h buffer.h
595         cc -c insert.c
596 search.o : search.c defs.h buffer.h
597         cc -c search.c
598 files.o : files.c defs.h buffer.h command.h
599         cc -c files.c
600 utils.o : utils.c defs.h
601         cc -c utils.c
602 clean :
603         rm edit main.o kbd.o command.o display.o \
604            insert.o search.o files.o utils.o
605 @end group
606 @end example
608 @noindent
609 We split each long line into two lines using backslash/newline; this is
610 like using one long line, but is easier to read.  @xref{Splitting Lines,
611 , Splitting Long Lines}.
612 @cindex continuation lines
613 @cindex @code{\} (backslash), for continuation lines
614 @cindex backslash (@code{\}), for continuation lines
615 @cindex quoting newline, in makefile
616 @cindex newline, quoting, in makefile
618 To use this makefile to create the executable file called @file{edit},
619 type:
621 @example
622 make
623 @end example
625 To use this makefile to delete the executable file and all the object
626 files from the directory, type:
628 @example
629 make clean
630 @end example
632 In the example makefile, the targets include the executable file
633 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
634 prerequisites are files such as @samp{main.c} and @samp{defs.h}.
635 In fact, each @samp{.o} file is both a target and a prerequisite.
636 Recipes include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
638 When a target is a file, it needs to be recompiled or relinked if any
639 of its prerequisites change.  In addition, any prerequisites that are
640 themselves automatically generated should be updated first.  In this
641 example, @file{edit} depends on each of the eight object files; the
642 object file @file{main.o} depends on the source file @file{main.c} and
643 on the header file @file{defs.h}.
645 A recipe may follow each line that contains a target and
646 prerequisites.  These recipes say how to update the target file.  A
647 tab character (or whatever character is specified by the
648 @code{.RECIPEPREFIX} variable; @pxref{Special Variables}) must come at
649 the beginning of every line in the recipe to distinguish recipes from
650 other lines in the makefile.  (Bear in mind that @code{make} does not
651 know anything about how the recipes work.  It is up to you to supply
652 recipes that will update the target file properly.  All @code{make}
653 does is execute the recipe you have specified when the target file
654 needs to be updated.)@refill
655 @cindex recipe
657 The target @samp{clean} is not a file, but merely the name of an
658 action.  Since you normally do not want to carry out the actions in
659 this rule, @samp{clean} is not a prerequisite of any other rule.
660 Consequently, @code{make} never does anything with it unless you tell
661 it specifically.  Note that this rule not only is not a prerequisite,
662 it also does not have any prerequisites, so the only purpose of the
663 rule is to run the specified recipe.  Targets that do not refer to
664 files but are just actions are called @dfn{phony targets}.
665 @xref{Phony Targets}, for information about this kind of target.
666 @xref{Errors, , Errors in Recipes}, to see how to cause @code{make}
667 to ignore errors from @code{rm} or any other command.
668 @cindex @code{clean} target
669 @cindex @code{rm} (shell command)
671 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
672 @comment  node-name,  next,  previous,  up
673 @section How @code{make} Processes a Makefile
674 @cindex processing a makefile
675 @cindex makefile, how @code{make} processes
677 By default, @code{make} starts with the first target (not targets whose
678 names start with @samp{.}).  This is called the @dfn{default goal}.
679 (@dfn{Goals} are the targets that @code{make} strives ultimately to
680 update.    You can override this behavior using the command line
681 (@pxref{Goals, , Arguments to Specify the Goals}) or with the
682 @code{.DEFAULT_GOAL} special variable (@pxref{Special Variables, ,
683 Other Special Variables}).
684 @cindex default goal
685 @cindex goal, default
686 @cindex goal
688 In the simple example of the previous section, the default goal is to
689 update the executable program @file{edit}; therefore, we put that rule
690 first.
692 Thus, when you give the command:
694 @example
695 make
696 @end example
698 @noindent
699 @code{make} reads the makefile in the current directory and begins by
700 processing the first rule.  In the example, this rule is for relinking
701 @file{edit}; but before @code{make} can fully process this rule, it
702 must process the rules for the files that @file{edit} depends on,
703 which in this case are the object files.  Each of these files is
704 processed according to its own rule.  These rules say to update each
705 @samp{.o} file by compiling its source file.  The recompilation must
706 be done if the source file, or any of the header files named as
707 prerequisites, is more recent than the object file, or if the object
708 file does not exist.
710 The other rules are processed because their targets appear as
711 prerequisites of the goal.  If some other rule is not depended on by the
712 goal (or anything it depends on, etc.), that rule is not processed,
713 unless you tell @code{make} to do so (with a command such as
714 @w{@code{make clean}}).
716 Before recompiling an object file, @code{make} considers updating its
717 prerequisites, the source file and header files.  This makefile does not
718 specify anything to be done for them---the @samp{.c} and @samp{.h} files
719 are not the targets of any rules---so @code{make} does nothing for these
720 files.  But @code{make} would update automatically generated C programs,
721 such as those made by Bison or Yacc, by their own rules at this time.
723 After recompiling whichever object files need it, @code{make} decides
724 whether to relink @file{edit}.  This must be done if the file
725 @file{edit} does not exist, or if any of the object files are newer than
726 it.  If an object file was just recompiled, it is now newer than
727 @file{edit}, so @file{edit} is relinked.
728 @cindex relinking
730 Thus, if we change the file @file{insert.c} and run @code{make},
731 @code{make} will compile that file to update @file{insert.o}, and then
732 link @file{edit}.  If we change the file @file{command.h} and run
733 @code{make}, @code{make} will recompile the object files @file{kbd.o},
734 @file{command.o} and @file{files.o} and then link the file @file{edit}.
736 @node Variables Simplify, make Deduces, How Make Works, Introduction
737 @section Variables Make Makefiles Simpler
738 @cindex variables
739 @cindex simplifying with variables
741 In our example, we had to list all the object files twice in the rule for
742 @file{edit} (repeated here):
744 @example
745 @group
746 edit : main.o kbd.o command.o display.o \
747               insert.o search.o files.o utils.o
748         cc -o edit main.o kbd.o command.o display.o \
749                    insert.o search.o files.o utils.o
750 @end group
751 @end example
753 @cindex @code{objects}
754 Such duplication is error-prone; if a new object file is added to the
755 system, we might add it to one list and forget the other.  We can eliminate
756 the risk and simplify the makefile by using a variable.  @dfn{Variables}
757 allow a text string to be defined once and substituted in multiple places
758 later (@pxref{Using Variables, ,How to Use Variables}).
760 @cindex @code{OBJECTS}
761 @cindex @code{objs}
762 @cindex @code{OBJS}
763 @cindex @code{obj}
764 @cindex @code{OBJ}
765 It is standard practice for every makefile to have a variable named
766 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
767 or @code{OBJ} which is a list of all object file names.  We would
768 define such a variable @code{objects} with a line like this in the
769 makefile:@refill
771 @example
772 @group
773 objects = main.o kbd.o command.o display.o \
774           insert.o search.o files.o utils.o
775 @end group
776 @end example
778 @noindent
779 Then, each place we want to put a list of the object file names, we can
780 substitute the variable's value by writing @samp{$(objects)}
781 (@pxref{Using Variables, ,How to Use Variables}).
783 Here is how the complete simple makefile looks when you use a variable
784 for the object files:
786 @example
787 @group
788 objects = main.o kbd.o command.o display.o \
789           insert.o search.o files.o utils.o
791 edit : $(objects)
792         cc -o edit $(objects)
793 main.o : main.c defs.h
794         cc -c main.c
795 kbd.o : kbd.c defs.h command.h
796         cc -c kbd.c
797 command.o : command.c defs.h command.h
798         cc -c command.c
799 display.o : display.c defs.h buffer.h
800         cc -c display.c
801 insert.o : insert.c defs.h buffer.h
802         cc -c insert.c
803 search.o : search.c defs.h buffer.h
804         cc -c search.c
805 files.o : files.c defs.h buffer.h command.h
806         cc -c files.c
807 utils.o : utils.c defs.h
808         cc -c utils.c
809 clean :
810         rm edit $(objects)
811 @end group
812 @end example
814 @node make Deduces, Combine By Prerequisite, Variables Simplify, Introduction
815 @section Letting @code{make} Deduce the Recipes
816 @cindex deducing recipes (implicit rules)
817 @cindex implicit rule, introduction to
818 @cindex rule, implicit, introduction to
820 It is not necessary to spell out the recipes for compiling the individual
821 C source files, because @code{make} can figure them out: it has an
822 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
823 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
824 use the recipe @samp{cc -c main.c -o main.o} to compile @file{main.c} into
825 @file{main.o}.  We can therefore omit the recipes from the rules for the
826 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.@refill
828 When a @samp{.c} file is used automatically in this way, it is also
829 automatically added to the list of prerequisites.  We can therefore omit
830 the @samp{.c} files from the prerequisites, provided we omit the recipe.
832 Here is the entire example, with both of these changes, and a variable
833 @code{objects} as suggested above:
835 @example
836 @group
837 objects = main.o kbd.o command.o display.o \
838           insert.o search.o files.o utils.o
840 edit : $(objects)
841         cc -o edit $(objects)
843 main.o : defs.h
844 kbd.o : defs.h command.h
845 command.o : defs.h command.h
846 display.o : defs.h buffer.h
847 insert.o : defs.h buffer.h
848 search.o : defs.h buffer.h
849 files.o : defs.h buffer.h command.h
850 utils.o : defs.h
852 .PHONY : clean
853 clean :
854         rm edit $(objects)
855 @end group
856 @end example
858 @noindent
859 This is how we would write the makefile in actual practice.  (The
860 complications associated with @samp{clean} are described elsewhere.
861 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Recipes}.)
863 Because implicit rules are so convenient, they are important.  You
864 will see them used frequently.@refill
866 @node Combine By Prerequisite, Cleanup, make Deduces, Introduction
867 @section Another Style of Makefile
868 @cindex combining rules by prerequisite
870 When the objects of a makefile are created only by implicit rules, an
871 alternative style of makefile is possible.  In this style of makefile,
872 you group entries by their prerequisites instead of by their targets.
873 Here is what one looks like:
875 @example
876 @group
877 objects = main.o kbd.o command.o display.o \
878           insert.o search.o files.o utils.o
880 edit : $(objects)
881         cc -o edit $(objects)
883 $(objects) : defs.h
884 kbd.o command.o files.o : command.h
885 display.o insert.o search.o files.o : buffer.h
886 @end group
887 @end example
889 @noindent
890 Here @file{defs.h} is given as a prerequisite of all the object files;
891 @file{command.h} and @file{buffer.h} are prerequisites of the specific
892 object files listed for them.
894 Whether this is better is a matter of taste: it is more compact, but some
895 people dislike it because they find it clearer to put all the information
896 about each target in one place.
898 @node Cleanup,  , Combine By Prerequisite, Introduction
899 @section Rules for Cleaning the Directory
900 @cindex cleaning up
901 @cindex removing, to clean up
903 Compiling a program is not the only thing you might want to write rules
904 for.  Makefiles commonly tell how to do a few other things besides
905 compiling a program: for example, how to delete all the object files
906 and executables so that the directory is @samp{clean}.
908 @cindex @code{clean} target
909 Here is how we
910 could write a @code{make} rule for cleaning our example editor:
912 @example
913 @group
914 clean:
915         rm edit $(objects)
916 @end group
917 @end example
919 In practice, we might want to write the rule in a somewhat more
920 complicated manner to handle unanticipated situations.  We would do this:
922 @example
923 @group
924 .PHONY : clean
925 clean :
926         -rm edit $(objects)
927 @end group
928 @end example
930 @noindent
931 This prevents @code{make} from getting confused by an actual file
932 called @file{clean} and causes it to continue in spite of errors from
933 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
934 Recipes}.)
936 @noindent
937 A rule such as this should not be placed at the beginning of the
938 makefile, because we do not want it to run by default!  Thus, in the
939 example makefile, we want the rule for @code{edit}, which recompiles
940 the editor, to remain the default goal.
942 Since @code{clean} is not a prerequisite of @code{edit}, this rule will not
943 run at all if we give the command @samp{make} with no arguments.  In
944 order to make the rule run, we have to type @samp{make clean}.
945 @xref{Running, ,How to Run @code{make}}.
947 @node Makefiles, Rules, Introduction, Top
948 @chapter Writing Makefiles
950 @cindex makefile, how to write
951 The information that tells @code{make} how to recompile a system comes from
952 reading a data base called the @dfn{makefile}.
954 @menu
955 * Makefile Contents::           What makefiles contain.
956 * Makefile Names::              How to name your makefile.
957 * Include::                     How one makefile can use another makefile.
958 * MAKEFILES Variable::          The environment can specify extra makefiles.
959 * Remaking Makefiles::          How makefiles get remade.
960 * Overriding Makefiles::        How to override part of one makefile
961                                   with another makefile.
962 * Reading Makefiles::           How makefiles are parsed.
963 * Secondary Expansion::         How and when secondary expansion is performed.
964 @end menu
966 @node Makefile Contents, Makefile Names, Makefiles, Makefiles
967 @section What Makefiles Contain
969 Makefiles contain five kinds of things: @dfn{explicit rules},
970 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
971 and @dfn{comments}.  Rules, variables, and directives are described at
972 length in later chapters.@refill
974 @itemize @bullet
975 @cindex rule, explicit, definition of
976 @cindex explicit rule, definition of
977 @item
978 An @dfn{explicit rule} says when and how to remake one or more files,
979 called the rule's @dfn{targets}.  It lists the other files that the
980 targets depend on, called the @dfn{prerequisites} of the target, and
981 may also give a recipe to use to create or update the targets.
982 @xref{Rules, ,Writing Rules}.
984 @cindex rule, implicit, definition of
985 @cindex implicit rule, definition of
986 @item
987 An @dfn{implicit rule} says when and how to remake a class of files
988 based on their names.  It describes how a target may depend on a file
989 with a name similar to the target and gives a recipe to create or
990 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
992 @cindex variable definition
993 @item
994 A @dfn{variable definition} is a line that specifies a text string
995 value for a variable that can be substituted into the text later.  The
996 simple makefile example shows a variable definition for @code{objects}
997 as a list of all object files (@pxref{Variables Simplify, , Variables
998 Make Makefiles Simpler}).
1000 @cindex directive
1001 @item
1002 A @dfn{directive} is an instruction for @code{make} to do something
1003 special while reading the makefile.  These include:
1005 @itemize @bullet
1006 @item
1007 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
1009 @item
1010 Deciding (based on the values of variables) whether to use or
1011 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
1013 @item
1014 Defining a variable from a verbatim string containing multiple lines
1015 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).
1016 @end itemize
1018 @cindex comments, in makefile
1019 @cindex @code{#} (comments), in makefile
1020 @item
1021 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the
1022 rest of the line are ignored, except that a trailing backslash not
1023 escaped by another backslash will continue the comment across multiple
1024 lines.  A line containing just a comment (with perhaps spaces before
1025 it) is effectively blank, and is ignored.  If you want a literal
1026 @code{#}, escape it with a backslash (e.g., @code{\#}).  Comments may
1027 appear on any line in the makefile, although they are treated
1028 specially in certain situations.
1030 You cannot use comments within variable references or function calls:
1031 any instance of @code{#} will be treated literally (rather than as the
1032 start of a comment) inside a variable reference or function call.
1034 Comments within a recipe are passed to the shell, just as with any
1035 other recipe text.  The shell decides how to interpret it: whether or
1036 not this is a comment is up to the shell.
1038 Within a @code{define} directive, comments are not ignored during the
1039 definition of the variable, but rather kept intact in the value of the
1040 variable.  When the variable is expanded they will either be treated
1041 as @code{make} comments or as recipe text, depending on the context in
1042 which the variable is evaluated.
1043 @end itemize
1045 @menu
1046 * Splitting Lines::             Splitting long lines in makefiles
1047 @end menu
1049 @node Splitting Lines,  , Makefile Contents, Makefile Contents
1050 @subsection Splitting Long Lines
1051 @cindex splitting long lines
1052 @cindex long lines, splitting
1053 @cindex backslash (@code{\}), to quote newlines
1055 Makefiles use a ``line-based'' syntax in which the newline character
1056 is special and marks the end of a statement.  GNU @code{make} has no
1057 limit on the length of a statement line, up to the amount of memory in
1058 your computer.
1060 However, it is difficult to read lines which are too long to display
1061 without wrapping or scrolling.  So, you can format your makefiles for
1062 readability by adding newlines into the middle of a statement: you do
1063 this by escaping the internal newlines with a backslash (@code{\})
1064 character.  Where we need to make a distinction we will refer to
1065 ``physical lines'' as a single line ending with a newline (regardless
1066 of whether it is escaped) and a ``logical line'' being a complete
1067 statement including all escaped newlines up to the first non-escaped
1068 newline.
1070 The way in which backslash/newline combinations are handled depends on
1071 whether the statement is a recipe line or a non-recipe line.  Handling
1072 of backslash/newline in a recipe line is discussed later
1073 (@pxref{Splitting Recipe Lines}).
1075 Outside of recipe lines, backslash/newlines are converted into a
1076 single space character.  Once that is done, all whitespace around the
1077 backslash/newline is condensed into a single space: this includes all
1078 whitespace preceding the backslash, all whitespace at the beginning of
1079 the line after the backslash/newline, and any consecutive
1080 backslash/newline combinations.
1082 If the @code{.POSIX} special target is defined then backslash/newline
1083 handling is modified slightly to conform to POSIX.2: first, whitespace
1084 preceding a backslash is not removed and second, consecutive
1085 backslash/newlines are not condensed.
1087 @node Makefile Names, Include, Makefile Contents, Makefiles
1088 @section What Name to Give Your Makefile
1089 @cindex makefile name
1090 @cindex name of makefile
1091 @cindex default makefile name
1092 @cindex file name of makefile
1094 @c following paragraph rewritten to avoid overfull hbox
1095 By default, when @code{make} looks for the makefile, it tries the
1096 following names, in order: @file{GNUmakefile}, @file{makefile}
1097 and @file{Makefile}.@refill
1098 @findex Makefile
1099 @findex GNUmakefile
1100 @findex makefile
1102 @cindex @code{README}
1103 Normally you should call your makefile either @file{makefile} or
1104 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1105 prominently near the beginning of a directory listing, right near other
1106 important files such as @file{README}.)  The first name checked,
1107 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1108 use this name if you have a makefile that is specific to GNU
1109 @code{make}, and will not be understood by other versions of
1110 @code{make}.  Other @code{make} programs look for @file{makefile} and
1111 @file{Makefile}, but not @file{GNUmakefile}.
1113 If @code{make} finds none of these names, it does not use any makefile.
1114 Then you must specify a goal with a command argument, and @code{make}
1115 will attempt to figure out how to remake it using only its built-in
1116 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1118 @cindex @code{-f}
1119 @cindex @code{--file}
1120 @cindex @code{--makefile}
1121 If you want to use a nonstandard name for your makefile, you can specify
1122 the makefile name with the @samp{-f} or @samp{--file} option.  The
1123 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1124 @code{make} to read the file @var{name} as the makefile.  If you use
1125 more than one @samp{-f} or @samp{--file} option, you can specify several
1126 makefiles.  All the makefiles are effectively concatenated in the order
1127 specified.  The default makefile names @file{GNUmakefile},
1128 @file{makefile} and @file{Makefile} are not checked automatically if you
1129 specify @samp{-f} or @samp{--file}.@refill
1130 @cindex specifying makefile name
1131 @cindex makefile name, how to specify
1132 @cindex name of makefile, how to specify
1133 @cindex file name of makefile, how to specify
1135 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1136 @section Including Other Makefiles
1137 @cindex including other makefiles
1138 @cindex makefile, including
1140 @findex include
1141 The @code{include} directive tells @code{make} to suspend reading the
1142 current makefile and read one or more other makefiles before continuing.
1143 The directive is a line in the makefile that looks like this:
1145 @example
1146 include @var{filenames}@dots{}
1147 @end example
1149 @noindent
1150 @var{filenames} can contain shell file name patterns.  If
1151 @var{filenames} is empty, nothing is included and no error is printed.
1152 @cindex shell file name pattern (in @code{include})
1153 @cindex shell wildcards (in @code{include})
1154 @cindex wildcard, in @code{include}
1156 Extra spaces are allowed and ignored at the beginning of the line, but
1157 the first character must not be a tab (or the value of
1158 @code{.RECIPEPREFIX})---if the line begins with a tab, it will be
1159 considered a recipe line.  Whitespace is required between
1160 @code{include} and the file names, and between file names; extra
1161 whitespace is ignored there and at the end of the directive.  A
1162 comment starting with @samp{#} is allowed at the end of the line.  If
1163 the file names contain any variable or function references, they are
1164 expanded.  @xref{Using Variables, ,How to Use Variables}.
1166 For example, if you have three @file{.mk} files, @file{a.mk},
1167 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1168 @code{bish bash}, then the following expression
1170 @example
1171 include foo *.mk $(bar)
1172 @end example
1174 is equivalent to
1176 @example
1177 include foo a.mk b.mk c.mk bish bash
1178 @end example
1180 When @code{make} processes an @code{include} directive, it suspends
1181 reading of the containing makefile and reads from each listed file in
1182 turn.  When that is finished, @code{make} resumes reading the
1183 makefile in which the directive appears.
1185 One occasion for using @code{include} directives is when several programs,
1186 handled by individual makefiles in various directories, need to use a
1187 common set of variable definitions
1188 (@pxref{Setting, ,Setting Variables}) or pattern rules
1189 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1191 Another such occasion is when you want to generate prerequisites from
1192 source files automatically; the prerequisites can be put in a file that
1193 is included by the main makefile.  This practice is generally cleaner
1194 than that of somehow appending the prerequisites to the end of the main
1195 makefile as has been traditionally done with other versions of
1196 @code{make}.  @xref{Automatic Prerequisites}.
1197 @cindex prerequisites, automatic generation
1198 @cindex automatic generation of prerequisites
1199 @cindex generating prerequisites automatically
1201 @cindex @code{-I}
1202 @cindex @code{--include-dir}
1203 @cindex included makefiles, default directories
1204 @cindex default directories for included makefiles
1205 @findex /usr/gnu/include
1206 @findex /usr/local/include
1207 @findex /usr/include
1208 If the specified name does not start with a slash, and the file is not
1209 found in the current directory, several other directories are searched.
1210 First, any directories you have specified with the @samp{-I} or
1211 @samp{--include-dir} option are searched
1212 (@pxref{Options Summary, ,Summary of Options}).
1213 Then the following directories (if they exist)
1214 are searched, in this order:
1215 @file{@var{prefix}/include} (normally @file{/usr/local/include}
1216 @footnote{GNU Make compiled for MS-DOS and MS-Windows behaves as if
1217 @var{prefix} has been defined to be the root of the DJGPP tree
1218 hierarchy.})
1219 @file{/usr/gnu/include},
1220 @file{/usr/local/include}, @file{/usr/include}.
1222 If an included makefile cannot be found in any of these directories, a
1223 warning message is generated, but it is not an immediately fatal error;
1224 processing of the makefile containing the @code{include} continues.
1225 Once it has finished reading makefiles, @code{make} will try to remake
1226 any that are out of date or don't exist.
1227 @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
1228 Only after it has tried to find a way to remake a makefile and failed,
1229 will @code{make} diagnose the missing makefile as a fatal error.
1231 If you want @code{make} to simply ignore a makefile which does not exist
1232 or cannot be remade, with no error message, use the @w{@code{-include}}
1233 directive instead of @code{include}, like this:
1235 @example
1236 -include @var{filenames}@dots{}
1237 @end example
1239 This acts like @code{include} in every way except that there is no
1240 error (not even a warning) if any of the @var{filenames} (or any
1241 prerequisites of any of the @var{filenames}) do not exist or cannot be
1242 remade.
1244 For compatibility with some other @code{make} implementations,
1245 @code{sinclude} is another name for @w{@code{-include}}.
1247 @node MAKEFILES Variable, Remaking Makefiles, Include, Makefiles
1248 @section The Variable @code{MAKEFILES}
1249 @cindex makefile, and @code{MAKEFILES} variable
1250 @cindex including (@code{MAKEFILES} variable)
1252 @vindex MAKEFILES
1253 If the environment variable @code{MAKEFILES} is defined, @code{make}
1254 considers its value as a list of names (separated by whitespace) of
1255 additional makefiles to be read before the others.  This works much
1256 like the @code{include} directive: various directories are searched
1257 for those files (@pxref{Include, ,Including Other Makefiles}).  In
1258 addition, the default goal is never taken from one of these makefiles
1259 (or any makefile included by them) and it is not an error if the files
1260 listed in @code{MAKEFILES} are not found.@refill
1262 @cindex recursion, and @code{MAKEFILES} variable
1263 The main use of @code{MAKEFILES} is in communication between recursive
1264 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1265 @code{make}}).  It usually is not desirable to set the environment
1266 variable before a top-level invocation of @code{make}, because it is
1267 usually better not to mess with a makefile from outside.  However, if
1268 you are running @code{make} without a specific makefile, a makefile in
1269 @code{MAKEFILES} can do useful things to help the built-in implicit
1270 rules work better, such as defining search paths (@pxref{Directory Search}).
1272 Some users are tempted to set @code{MAKEFILES} in the environment
1273 automatically on login, and program makefiles to expect this to be done.
1274 This is a very bad idea, because such makefiles will fail to work if run by
1275 anyone else.  It is much better to write explicit @code{include} directives
1276 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1278 @node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
1279 @section How Makefiles Are Remade
1281 @cindex updating makefiles
1282 @cindex remaking makefiles
1283 @cindex makefile, remaking of
1284 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1285 files.  If a makefile can be remade from other files, you probably want
1286 @code{make} to get an up-to-date version of the makefile to read in.
1288 To this end, after reading in all makefiles, @code{make} will consider
1289 each as a goal target and attempt to update it.  If a makefile has a
1290 rule which says how to update it (found either in that very makefile or
1291 in another one) or if an implicit rule applies to it (@pxref{Implicit
1292 Rules, ,Using Implicit Rules}), it will be updated if necessary.  After
1293 all makefiles have been checked, if any have actually been changed,
1294 @code{make} starts with a clean slate and reads all the makefiles over
1295 again.  (It will also attempt to update each of them over again, but
1296 normally this will not change them again, since they are already up to
1297 date.)@refill
1299 If you know that one or more of your makefiles cannot be remade and
1300 you want to keep @code{make} from performing an implicit rule search
1301 on them, perhaps for efficiency reasons, you can use any normal method
1302 of preventing implicit rule look-up to do so.  For example, you can
1303 write an explicit rule with the makefile as the target, and an empty
1304 recipe (@pxref{Empty Recipes, ,Using Empty Recipes}).
1306 If the makefiles specify a double-colon rule to remake a file with
1307 a recipe but no prerequisites, that file will always be remade
1308 (@pxref{Double-Colon}).  In the case of makefiles, a makefile that has a
1309 double-colon rule with a recipe but no prerequisites will be remade every
1310 time @code{make} is run, and then again after @code{make} starts over
1311 and reads the makefiles in again.  This would cause an infinite loop:
1312 @code{make} would constantly remake the makefile, and never do anything
1313 else.  So, to avoid this, @code{make} will @strong{not} attempt to
1314 remake makefiles which are specified as targets of a double-colon rule
1315 with a recipe but no prerequisites.@refill
1317 If you do not specify any makefiles to be read with @samp{-f} or
1318 @samp{--file} options, @code{make} will try the default makefile names;
1319 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1320 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1321 @code{make} is not certain that these makefiles should exist.  However,
1322 if a default makefile does not exist but can be created by running
1323 @code{make} rules, you probably want the rules to be run so that the
1324 makefile can be used.
1326 Therefore, if none of the default makefiles exists, @code{make} will try
1327 to make each of them in the same order in which they are searched for
1328 (@pxref{Makefile Names, ,What Name to Give Your Makefile})
1329 until it succeeds in making one, or it runs out of names to try.  Note
1330 that it is not an error if @code{make} cannot find or make any makefile;
1331 a makefile is not always necessary.@refill
1333 When you use the @samp{-t} or @samp{--touch} option
1334 (@pxref{Instead of Execution, ,Instead of Executing Recipes}),
1335 you would not want to use an out-of-date makefile to decide which
1336 targets to touch.  So the @samp{-t} option has no effect on updating
1337 makefiles; they are really updated even if @samp{-t} is specified.
1338 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1339 @samp{--just-print}) do not prevent updating of makefiles, because an
1340 out-of-date makefile would result in the wrong output for other targets.
1341 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1342 and then print the recipe to update @file{foo} and its prerequisites
1343 without running it.  The recipe printed for @file{foo} will be the one
1344 specified in the updated contents of @file{mfile}.
1346 However, on occasion you might actually wish to prevent updating of even
1347 the makefiles.  You can do this by specifying the makefiles as goals in
1348 the command line as well as specifying them as makefiles.  When the
1349 makefile name is specified explicitly as a goal, the options @samp{-t}
1350 and so on do apply to them.
1352 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1353 @file{mfile}, print the recipe needed to update it without actually
1354 running it, and then print the recipe needed to update @file{foo}
1355 without running that.  The recipe for @file{foo} will be the one
1356 specified by the existing contents of @file{mfile}.
1358 @node Overriding Makefiles, Reading Makefiles, Remaking Makefiles, Makefiles
1359 @section Overriding Part of Another Makefile
1361 @cindex overriding makefiles
1362 @cindex makefile, overriding
1363 Sometimes it is useful to have a makefile that is mostly just like
1364 another makefile.  You can often use the @samp{include} directive to
1365 include one in the other, and add more targets or variable definitions.
1366 However, it is invalid for two makefiles to give different recipes for
1367 the same target.  But there is another way.
1369 @cindex match-anything rule, used to override
1370 In the containing makefile (the one that wants to include the other),
1371 you can use a match-anything pattern rule to say that to remake any
1372 target that cannot be made from the information in the containing
1373 makefile, @code{make} should look in another makefile.
1374 @xref{Pattern Rules}, for more information on pattern rules.
1376 For example, if you have a makefile called @file{Makefile} that says how
1377 to make the target @samp{foo} (and other targets), you can write a
1378 makefile called @file{GNUmakefile} that contains:
1380 @example
1381 foo:
1382         frobnicate > foo
1384 %: force
1385         @@$(MAKE) -f Makefile $@@
1386 force: ;
1387 @end example
1389 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1390 read it, and see that to make @file{foo}, it needs to run the recipe
1391 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1392 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1393 recipe from the pattern rule: @samp{make -f Makefile bar}.  If
1394 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1395 will apply the rule.  And likewise for any other target that
1396 @file{GNUmakefile} does not say how to make.
1398 The way this works is that the pattern rule has a pattern of just
1399 @samp{%}, so it matches any target whatever.  The rule specifies a
1400 prerequisite @file{force}, to guarantee that the recipe will be run even
1401 if the target file already exists.  We give the @file{force} target an
1402 empty recipe to prevent @code{make} from searching for an implicit rule to
1403 build it---otherwise it would apply the same match-anything rule to
1404 @file{force} itself and create a prerequisite loop!
1406 @node Reading Makefiles,  Secondary Expansion, Overriding Makefiles, Makefiles
1407 @section How @code{make} Reads a Makefile
1408 @cindex reading makefiles
1409 @cindex makefile, parsing
1411 GNU @code{make} does its work in two distinct phases.  During the first
1412 phase it reads all the makefiles, included makefiles, etc. and
1413 internalizes all the variables and their values, implicit and explicit
1414 rules, and constructs a dependency graph of all the targets and their
1415 prerequisites.  During the second phase, @code{make} uses these internal
1416 structures to determine what targets will need to be rebuilt and to
1417 invoke the rules necessary to do so.
1419 It's important to understand this two-phase approach because it has a
1420 direct impact on how variable and function expansion happens; this is
1421 often a source of some confusion when writing makefiles.  Here we will
1422 present a summary of the phases in which expansion happens for different
1423 constructs within the makefile.  We say that expansion is
1424 @dfn{immediate} if it happens during the first phase: in this case
1425 @code{make} will expand any variables or functions in that section of a
1426 construct as the makefile is parsed.  We say that expansion is
1427 @dfn{deferred} if expansion is not performed immediately.  Expansion of
1428 a deferred construct is not performed until either the construct appears
1429 later in an immediate context, or until the second phase.
1431 You may not be familiar with some of these constructs yet.  You can
1432 reference this section as you become familiar with them, in later
1433 chapters.
1435 @subheading Variable Assignment
1436 @cindex +=, expansion
1437 @cindex =, expansion
1438 @cindex ?=, expansion
1439 @cindex +=, expansion
1440 @cindex !=, expansion
1441 @cindex define, expansion
1443 Variable definitions are parsed as follows:
1445 @example
1446 @var{immediate} = @var{deferred}
1447 @var{immediate} ?= @var{deferred}
1448 @var{immediate} := @var{immediate}
1449 @var{immediate} ::= @var{immediate}
1450 @var{immediate} += @var{deferred} or @var{immediate}
1451 @var{immediate} != @var{immediate}
1453 define @var{immediate}
1454   @var{deferred}
1455 endef
1457 define @var{immediate} =
1458   @var{deferred}
1459 endef
1461 define @var{immediate} ?=
1462   @var{deferred}
1463 endef
1465 define @var{immediate} :=
1466   @var{immediate}
1467 endef
1469 define @var{immediate} ::=
1470   @var{immediate}
1471 endef
1473 define @var{immediate} +=
1474   @var{deferred} or @var{immediate}
1475 endef
1477 define @var{immediate} !=
1478   @var{immediate}
1479 endef
1480 @end example
1482 For the append operator, @samp{+=}, the right-hand side is considered
1483 immediate if the variable was previously set as a simple variable
1484 (@samp{:=} or @samp{::=}), and deferred otherwise.
1486 For the shell assignment operator, @samp{!=}, the right-hand side is
1487 evaluated immediately and handed to the shell.  The result is stored in the
1488 variable named on the left, and that variable becomes a simple variable
1489 (and will thus be re-evaluated on each reference).
1491 @subheading Conditional Directives
1492 @cindex ifdef, expansion
1493 @cindex ifeq, expansion
1494 @cindex ifndef, expansion
1495 @cindex ifneq, expansion
1497 Conditional directives are parsed immediately.  This means, for
1498 example, that automatic variables cannot be used in conditional
1499 directives, as automatic variables are not set until the recipe for
1500 that rule is invoked.  If you need to use automatic variables in a
1501 conditional directive you @emph{must} move the condition into the
1502 recipe and use shell conditional syntax instead.
1504 @subheading Rule Definition
1505 @cindex target, expansion
1506 @cindex prerequisite, expansion
1507 @cindex implicit rule, expansion
1508 @cindex pattern rule, expansion
1509 @cindex explicit rule, expansion
1511 A rule is always expanded the same way, regardless of the form:
1513 @example
1514 @var{immediate} : @var{immediate} ; @var{deferred}
1515         @var{deferred}
1516 @end example
1518 That is, the target and prerequisite sections are expanded immediately,
1519 and the recipe used to construct the target is always deferred.  This
1520 general rule is true for explicit rules, pattern rules, suffix rules,
1521 static pattern rules, and simple prerequisite definitions.
1523 @node Secondary Expansion, , Reading Makefiles, Makefiles
1524 @section Secondary Expansion
1525 @cindex secondary expansion
1526 @cindex expansion, secondary
1528 @findex .SECONDEXPANSION
1529 In the previous section we learned that GNU @code{make} works in two
1530 distinct phases: a read-in phase and a target-update phase
1531 (@pxref{Reading Makefiles, , How @code{make} Reads a Makefile}).  GNU
1532 make also has the ability to enable a @emph{second expansion} of the
1533 prerequisites (only) for some or all targets defined in the makefile.
1534 In order for this second expansion to occur, the special target
1535 @code{.SECONDEXPANSION} must be defined before the first prerequisite
1536 list that makes use of this feature.
1538 If that special target is defined then in between the two phases
1539 mentioned above, right at the end of the read-in phase, all the
1540 prerequisites of the targets defined after the special target are
1541 expanded a @emph{second time}.  In most circumstances this secondary
1542 expansion will have no effect, since all variable and function
1543 references will have been expanded during the initial parsing of the
1544 makefiles.  In order to take advantage of the secondary expansion
1545 phase of the parser, then, it's necessary to @emph{escape} the
1546 variable or function reference in the makefile.  In this case the
1547 first expansion merely un-escapes the reference but doesn't expand it,
1548 and expansion is left to the secondary expansion phase.  For example,
1549 consider this makefile:
1551 @example
1552 .SECONDEXPANSION:
1553 ONEVAR = onefile
1554 TWOVAR = twofile
1555 myfile: $(ONEVAR) $$(TWOVAR)
1556 @end example
1558 After the first expansion phase the prerequisites list of the
1559 @file{myfile} target will be @code{onefile} and @code{$(TWOVAR)}; the
1560 first (unescaped) variable reference to @var{ONEVAR} is expanded,
1561 while the second (escaped) variable reference is simply unescaped,
1562 without being recognized as a variable reference.  Now during the
1563 secondary expansion the first word is expanded again but since it
1564 contains no variable or function references it remains the value
1565 @file{onefile}, while the second word is now a normal reference to the
1566 variable @var{TWOVAR}, which is expanded to the value @file{twofile}.
1567 The final result is that there are two prerequisites, @file{onefile}
1568 and @file{twofile}.
1570 Obviously, this is not a very interesting case since the same result
1571 could more easily have been achieved simply by having both variables
1572 appear, unescaped, in the prerequisites list.  One difference becomes
1573 apparent if the variables are reset; consider this example:
1575 @example
1576 .SECONDEXPANSION:
1577 AVAR = top
1578 onefile: $(AVAR)
1579 twofile: $$(AVAR)
1580 AVAR = bottom
1581 @end example
1583 Here the prerequisite of @file{onefile} will be expanded immediately,
1584 and resolve to the value @file{top}, while the prerequisite of
1585 @file{twofile} will not be full expanded until the secondary expansion
1586 and yield a value of @file{bottom}.
1588 This is marginally more exciting, but the true power of this feature
1589 only becomes apparent when you discover that secondary expansions
1590 always take place within the scope of the automatic variables for that
1591 target.  This means that you can use variables such as @code{$@@},
1592 @code{$*}, etc. during the second expansion and they will have their
1593 expected values, just as in the recipe.  All you have to do is defer
1594 the expansion by escaping the @code{$}.  Also, secondary expansion
1595 occurs for both explicit and implicit (pattern) rules.  Knowing this,
1596 the possible uses for this feature increase dramatically.  For
1597 example:
1599 @example
1600 .SECONDEXPANSION:
1601 main_OBJS := main.o try.o test.o
1602 lib_OBJS := lib.o api.o
1604 main lib: $$($$@@_OBJS)
1605 @end example
1607 Here, after the initial expansion the prerequisites of both the
1608 @file{main} and @file{lib} targets will be @code{$($@@_OBJS)}.  During
1609 the secondary expansion, the @code{$@@} variable is set to the name of
1610 the target and so the expansion for the @file{main} target will yield
1611 @code{$(main_OBJS)}, or @code{main.o try.o test.o}, while the
1612 secondary expansion for the @file{lib} target will yield
1613 @code{$(lib_OBJS)}, or @code{lib.o api.o}.
1615 You can also mix in functions here, as long as they are properly escaped:
1617 @example
1618 main_SRCS := main.c try.c test.c
1619 lib_SRCS := lib.c api.c
1621 .SECONDEXPANSION:
1622 main lib: $$(patsubst %.c,%.o,$$($$@@_SRCS))
1623 @end example
1625 This version allows users to specify source files rather than object
1626 files, but gives the same resulting prerequisites list as the previous
1627 example.
1629 Evaluation of automatic variables during the secondary expansion
1630 phase, especially of the target name variable @code{$$@@}, behaves
1631 similarly to evaluation within recipes.  However, there are some
1632 subtle differences and ``corner cases'' which come into play for the
1633 different types of rule definitions that @code{make} understands.  The
1634 subtleties of using the different automatic variables are described
1635 below.
1637 @subheading Secondary Expansion of Explicit Rules
1638 @cindex secondary expansion and explicit rules
1639 @cindex explicit rules, secondary expansion of
1641 During the secondary expansion of explicit rules, @code{$$@@} and
1642 @code{$$%} evaluate, respectively, to the file name of the target and,
1643 when the target is an archive member, the target member name.  The
1644 @code{$$<} variable evaluates to the first prerequisite in the first
1645 rule for this target.  @code{$$^} and @code{$$+} evaluate to the list
1646 of all prerequisites of rules @emph{that have already appeared} for
1647 the same target (@code{$$+} with repetitions and @code{$$^}
1648 without).  The following example will help illustrate these behaviors:
1650 @example
1651 .SECONDEXPANSION:
1653 foo: foo.1 bar.1 $$< $$^ $$+    # line #1
1655 foo: foo.2 bar.2 $$< $$^ $$+    # line #2
1657 foo: foo.3 bar.3 $$< $$^ $$+    # line #3
1658 @end example
1660 In the first prerequisite list, all three variables (@code{$$<},
1661 @code{$$^}, and @code{$$+}) expand to the empty string.  In the
1662 second, they will have values @code{foo.1}, @code{foo.1 bar.1}, and
1663 @code{foo.1 bar.1} respectively.  In the third they will have values
1664 @code{foo.1}, @code{foo.1 bar.1 foo.2 bar.2}, and @code{foo.1 bar.1
1665 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1} respectively.
1667 Rules undergo secondary expansion in makefile order, except that
1668 the rule with the recipe is always evaluated last.
1670 The variables @code{$$?} and @code{$$*} are not available and expand
1671 to the empty string.
1673 @subheading Secondary Expansion of Static Pattern Rules
1674 @cindex secondary expansion and static pattern rules
1675 @cindex static pattern rules, secondary expansion of
1677 Rules for secondary expansion of static pattern rules are identical to
1678 those for explicit rules, above, with one exception: for static
1679 pattern rules the @code{$$*} variable is set to the pattern stem.  As
1680 with explicit rules, @code{$$?} is not available and expands to the
1681 empty string.
1683 @subheading Secondary Expansion of Implicit Rules
1684 @cindex secondary expansion and implicit rules
1685 @cindex implicit rules, secondary expansion of
1687 As @code{make} searches for an implicit rule, it substitutes the stem
1688 and then performs secondary expansion for every rule with a matching
1689 target pattern.  The value of the automatic variables is derived in
1690 the same fashion as for static pattern rules.  As an example:
1692 @example
1693 .SECONDEXPANSION:
1695 foo: bar
1697 foo foz: fo%: bo%
1699 %oo: $$< $$^ $$+ $$*
1700 @end example
1702 When the implicit rule is tried for target @file{foo}, @code{$$<}
1703 expands to @file{bar}, @code{$$^} expands to @file{bar boo},
1704 @code{$$+} also expands to @file{bar boo}, and @code{$$*} expands to
1705 @file{f}.
1707 Note that the directory prefix (D), as described in @ref{Implicit Rule
1708 Search, ,Implicit Rule Search Algorithm}, is appended (after
1709 expansion) to all the patterns in the prerequisites list.  As an
1710 example:@refill
1712 @example
1713 .SECONDEXPANSION:
1715 /tmp/foo.o:
1717 %.o: $$(addsuffix /%.c,foo bar) foo.h
1718         @@echo $^
1719 @end example
1721 The prerequisite list printed, after the secondary expansion and
1722 directory prefix reconstruction, will be @file{/tmp/foo/foo.c
1723 /tmp/bar/foo.c foo.h}.  If you are not interested in this
1724 reconstruction, you can use @code{$$*} instead of @code{%} in the
1725 prerequisites list.
1727 @node Rules, Recipes, Makefiles, Top
1728 @chapter Writing Rules
1729 @cindex writing rules
1730 @cindex rule, how to write
1731 @cindex target
1732 @cindex prerequisite
1734 A @dfn{rule} appears in the makefile and says when and how to remake
1735 certain files, called the rule's @dfn{targets} (most often only one per rule).
1736 It lists the other files that are the @dfn{prerequisites} of the target, and
1737 the @dfn{recipe} to use to create or update the target.
1739 @cindex default goal
1740 @cindex goal, default
1741 The order of rules is not significant, except for determining the
1742 @dfn{default goal}: the target for @code{make} to consider, if you do
1743 not otherwise specify one.  The default goal is the target of the first
1744 rule in the first makefile.  If the first rule has multiple targets,
1745 only the first target is taken as the default.  There are two
1746 exceptions: a target starting with a period is not a default unless it
1747 contains one or more slashes, @samp{/}, as well; and, a target that
1748 defines a pattern rule has no effect on the default goal.
1749 (@xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.)
1751 Therefore, we usually write the makefile so that the first rule is the
1752 one for compiling the entire program or all the programs described by
1753 the makefile (often with a target called @samp{all}).
1754 @xref{Goals, ,Arguments to Specify the Goals}.
1756 @menu
1757 * Rule Example::                An example explained.
1758 * Rule Syntax::                 General syntax explained.
1759 * Prerequisite Types::          There are two types of prerequisites.
1760 * Wildcards::                   Using wildcard characters such as `*'.
1761 * Directory Search::            Searching other directories for source files.
1762 * Phony Targets::               Using a target that is not a real file's name.
1763 * Force Targets::               You can use a target without a recipe
1764                                   or prerequisites to mark other targets
1765                                   as phony.
1766 * Empty Targets::               When only the date matters and the
1767                                   files are empty.
1768 * Special Targets::             Targets with special built-in meanings.
1769 * Multiple Targets::            When to make use of several targets in a rule.
1770 * Multiple Rules::              How to use several rules with the same target.
1771 * Static Pattern::              Static pattern rules apply to multiple targets
1772                                   and can vary the prerequisites according to
1773                                   the target name.
1774 * Double-Colon::                How to use a special kind of rule to allow
1775                                   several independent rules for one target.
1776 * Automatic Prerequisites::     How to automatically generate rules giving
1777                                   prerequisites from source files themselves.
1778 @end menu
1780 @ifnottex
1781 @node Rule Example, Rule Syntax, Rules, Rules
1782 @section Rule Example
1784 Here is an example of a rule:
1786 @example
1787 foo.o : foo.c defs.h       # module for twiddling the frobs
1788         cc -c -g foo.c
1789 @end example
1791 Its target is @file{foo.o} and its prerequisites are @file{foo.c} and
1792 @file{defs.h}.  It has one command in the recipe: @samp{cc -c -g foo.c}.
1793 The recipe starts with a tab to identify it as a recipe.
1795 This rule says two things:
1797 @itemize @bullet
1798 @item
1799 How to decide whether @file{foo.o} is out of date: it is out of date
1800 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1801 more recent than it.
1803 @item
1804 How to update the file @file{foo.o}: by running @code{cc} as stated.
1805 The recipe does not explicitly mention @file{defs.h}, but we presume
1806 that @file{foo.c} includes it, and that that is why @file{defs.h} was
1807 added to the prerequisites.
1808 @end itemize
1809 @end ifnottex
1811 @node Rule Syntax, Prerequisite Types, Rule Example, Rules
1812 @section Rule Syntax
1814 @cindex rule syntax
1815 @cindex syntax of rules
1816 In general, a rule looks like this:
1818 @example
1819 @var{targets} : @var{prerequisites}
1820         @var{recipe}
1821         @dots{}
1822 @end example
1824 @noindent
1825 or like this:
1827 @example
1828 @var{targets} : @var{prerequisites} ; @var{recipe}
1829         @var{recipe}
1830         @dots{}
1831 @end example
1833 @cindex targets
1834 @cindex rule targets
1835 The @var{targets} are file names, separated by spaces.  Wildcard
1836 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
1837 in File Names}) and a name of the form @file{@var{a}(@var{m})}
1838 represents member @var{m} in archive file @var{a}
1839 (@pxref{Archive Members, ,Archive Members as Targets}).
1840 Usually there is only one
1841 target per rule, but occasionally there is a reason to have more
1842 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).@refill
1844 @cindex recipes
1845 @cindex tab character (in commands)
1846 The @var{recipe} lines start with a tab character (or the first
1847 character in the value of the @code{.RECIPEPREFIX} variable;
1848 @pxref{Special Variables}).  The first recipe line may appear on the line
1849 after the prerequisites, with a tab character, or may appear on the
1850 same line, with a semicolon.  Either way, the effect is the same.
1851 There are other differences in the syntax of recipes.
1852 @xref{Recipes, ,Writing Recipes in Rules}.
1854 @cindex dollar sign (@code{$}), in rules
1855 @cindex @code{$}, in rules
1856 @cindex rules, and @code{$}
1857 Because dollar signs are used to start @code{make} variable
1858 references, if you really want a dollar sign in a target or
1859 prerequisite you must write two of them, @samp{$$} (@pxref{Using
1860 Variables, ,How to Use Variables}).  If you have enabled secondary
1861 expansion (@pxref{Secondary Expansion}) and you want a literal dollar
1862 sign in the prerequisites list, you must actually write @emph{four}
1863 dollar signs (@samp{$$$$}).
1865 You may split a long line by inserting a backslash followed by a
1866 newline, but this is not required, as @code{make} places no limit on
1867 the length of a line in a makefile.
1869 A rule tells @code{make} two things: when the targets are out of date,
1870 and how to update them when necessary.
1872 @cindex prerequisites
1873 @cindex rule prerequisites
1874 The criterion for being out of date is specified in terms of the
1875 @var{prerequisites}, which consist of file names separated by spaces.
1876 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
1877 A target is out of date if it does not exist or if it is older than any
1878 of the prerequisites (by comparison of last-modification times).  The
1879 idea is that the contents of the target file are computed based on
1880 information in the prerequisites, so if any of the prerequisites changes,
1881 the contents of the existing target file are no longer necessarily
1882 valid.
1884 How to update is specified by a @var{recipe}.  This is one or more
1885 lines to be executed by the shell (normally @samp{sh}), but with some
1886 extra features (@pxref{Recipes, ,Writing Recipes in Rules}).
1888 @node Prerequisite Types, Wildcards, Rule Syntax, Rules
1889 @comment  node-name,  next,  previous,  up
1890 @section Types of Prerequisites
1891 @cindex prerequisite types
1892 @cindex types of prerequisites
1894 @cindex prerequisites, normal
1895 @cindex normal prerequisites
1896 @cindex prerequisites, order-only
1897 @cindex order-only prerequisites
1898 There are actually two different types of prerequisites understood by
1899 GNU @code{make}: normal prerequisites such as described in the
1900 previous section, and @dfn{order-only} prerequisites.  A normal
1901 prerequisite makes two statements: first, it imposes an order in which
1902 recipes will be invoked: the recipes for all prerequisites of a target
1903 will be completed before the recipe for the target is run.  Second, it
1904 imposes a dependency relationship: if any prerequisite is newer than
1905 the target, then the target is considered out-of-date and must be
1906 rebuilt.
1908 Normally, this is exactly what you want: if a target's prerequisite is
1909 updated, then the target should also be updated.
1911 Occasionally, however, you have a situation where you want to impose a
1912 specific ordering on the rules to be invoked @emph{without} forcing
1913 the target to be updated if one of those rules is executed.  In that
1914 case, you want to define @dfn{order-only} prerequisites.  Order-only
1915 prerequisites can be specified by placing a pipe symbol (@code{|})
1916 in the prerequisites list: any prerequisites to the left of the pipe
1917 symbol are normal; any prerequisites to the right are order-only:
1919 @example
1920 @var{targets} : @var{normal-prerequisites} | @var{order-only-prerequisites}
1921 @end example
1923 The normal prerequisites section may of course be empty.  Also, you
1924 may still declare multiple lines of prerequisites for the same target:
1925 they are appended appropriately (normal prerequisites are appended to
1926 the list of normal prerequisites; order-only prerequisites are
1927 appended to the list of order-only prerequisites).  Note that if you
1928 declare the same file to be both a normal and an order-only
1929 prerequisite, the normal prerequisite takes precedence (since they
1930 have a strict superset of the behavior of an order-only prerequisite).
1932 Consider an example where your targets are to be placed in a separate
1933 directory, and that directory might not exist before @code{make} is
1934 run.  In this situation, you want the directory to be created before
1935 any targets are placed into it but, because the timestamps on
1936 directories change whenever a file is added, removed, or renamed, we
1937 certainly don't want to rebuild all the targets whenever the
1938 directory's timestamp changes.  One way to manage this is with
1939 order-only prerequisites: make the directory an order-only
1940 prerequisite on all the targets:
1942 @example
1943 OBJDIR := objdir
1944 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
1946 $(OBJDIR)/%.o : %.c
1947         $(COMPILE.c) $(OUTPUT_OPTION) $<
1949 all: $(OBJS)
1951 $(OBJS): | $(OBJDIR)
1953 $(OBJDIR):
1954         mkdir $(OBJDIR)
1955 @end example
1957 Now the rule to create the @file{objdir} directory will be run, if
1958 needed, before any @samp{.o} is built, but no @samp{.o} will be built
1959 because the @file{objdir} directory timestamp changed.
1961 @node Wildcards, Directory Search, Prerequisite Types, Rules
1962 @section Using Wildcard Characters in File Names
1963 @cindex wildcard
1964 @cindex file name with wildcards
1965 @cindex globbing (wildcards)
1967 @cindex @code{*} (wildcard character)
1968 @cindex @code{?} (wildcard character)
1969 @cindex @code{[@dots{}]} (wildcard characters)
1970 A single file name can specify many files using @dfn{wildcard characters}.
1971 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
1972 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
1973 specifies a list of all the files (in the working directory) whose names
1974 end in @samp{.c}.@refill
1976 @cindex @code{~} (tilde)
1977 @cindex tilde (@code{~})
1978 @cindex home directory
1979 The character @samp{~} at the beginning of a file name also has special
1980 significance.  If alone, or followed by a slash, it represents your home
1981 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
1982 If the @samp{~} is followed by a word, the string represents the home
1983 directory of the user named by that word.  For example @file{~john/bin}
1984 expands to @file{/home/john/bin}.  On systems which don't have a home
1985 directory for each user (such as MS-DOS or MS-Windows), this
1986 functionality can be simulated by setting the environment variable
1987 @var{HOME}.@refill
1989 Wildcard expansion is performed by @code{make} automatically in
1990 targets and in prerequisites.  In recipes, the shell is responsible
1991 for wildcard expansion.  In other contexts, wildcard expansion happens
1992 only if you request it explicitly with the @code{wildcard} function.
1994 The special significance of a wildcard character can be turned off by
1995 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
1996 specific file whose name consists of @samp{foo}, an asterisk, and
1997 @samp{bar}.@refill
1999 @menu
2000 * Wildcard Examples::           Several examples.
2001 * Wildcard Pitfall::            Problems to avoid.
2002 * Wildcard Function::           How to cause wildcard expansion where
2003                                   it does not normally take place.
2004 @end menu
2006 @node Wildcard Examples, Wildcard Pitfall, Wildcards, Wildcards
2007 @subsection Wildcard Examples
2009 Wildcards can be used in the recipe of a rule, where they are expanded
2010 by the shell.  For example, here is a rule to delete all the object files:
2012 @example
2013 @group
2014 clean:
2015         rm -f *.o
2016 @end group
2017 @end example
2018 @cindex @code{rm} (shell command)
2020 Wildcards are also useful in the prerequisites of a rule.  With the
2021 following rule in the makefile, @samp{make print} will print all the
2022 @samp{.c} files that have changed since the last time you printed them:
2024 @example
2025 print: *.c
2026         lpr -p $?
2027         touch print
2028 @end example
2030 @cindex @code{print} target
2031 @cindex @code{lpr} (shell command)
2032 @cindex @code{touch} (shell command)
2033 @noindent
2034 This rule uses @file{print} as an empty target file; see @ref{Empty
2035 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
2036 @samp{$?} is used to print only those files that have changed; see
2037 @ref{Automatic Variables}.)@refill
2039 Wildcard expansion does not happen when you define a variable.  Thus, if
2040 you write this:
2042 @example
2043 objects = *.o
2044 @end example
2046 @noindent
2047 then the value of the variable @code{objects} is the actual string
2048 @samp{*.o}.  However, if you use the value of @code{objects} in a
2049 target or prerequisite, wildcard expansion will take place there.  If
2050 you use the value of @code{objects} in a recipe, the shell may perform
2051 wildcard expansion when the recipe runs.  To set @code{objects} to the
2052 expansion, instead use:
2054 @example
2055 objects := $(wildcard *.o)
2056 @end example
2058 @noindent
2059 @xref{Wildcard Function}.
2061 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
2062 @subsection Pitfalls of Using Wildcards
2063 @cindex wildcard pitfalls
2064 @cindex pitfalls of wildcards
2065 @cindex mistakes with wildcards
2066 @cindex errors with wildcards
2067 @cindex problems with wildcards
2069 Now here is an example of a naive way of using wildcard expansion, that
2070 does not do what you would intend.  Suppose you would like to say that the
2071 executable file @file{foo} is made from all the object files in the
2072 directory, and you write this:
2074 @example
2075 objects = *.o
2077 foo : $(objects)
2078         cc -o foo $(CFLAGS) $(objects)
2079 @end example
2081 @noindent
2082 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
2083 expansion happens in the rule for @file{foo}, so that each @emph{existing}
2084 @samp{.o} file becomes a prerequisite of @file{foo} and will be recompiled if
2085 necessary.
2087 But what if you delete all the @samp{.o} files?  When a wildcard matches
2088 no files, it is left as it is, so then @file{foo} will depend on the
2089 oddly-named file @file{*.o}.  Since no such file is likely to exist,
2090 @code{make} will give you an error saying it cannot figure out how to
2091 make @file{*.o}.  This is not what you want!
2093 Actually it is possible to obtain the desired result with wildcard
2094 expansion, but you need more sophisticated techniques, including the
2095 @code{wildcard} function and string substitution.
2096 @ifnottex
2097 @xref{Wildcard Function, ,The Function @code{wildcard}}.
2098 @end ifnottex
2099 @iftex
2100 These are described in the following section.
2101 @end iftex
2103 @cindex wildcards and MS-DOS/MS-Windows backslashes
2104 @cindex backslashes in pathnames and wildcard expansion
2106 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes to
2107 separate directories in pathnames, like so:
2109 @example
2110   c:\foo\bar\baz.c
2111 @end example
2113 This is equivalent to the Unix-style @file{c:/foo/bar/baz.c} (the
2114 @file{c:} part is the so-called drive letter).  When @code{make} runs on
2115 these systems, it supports backslashes as well as the Unix-style forward
2116 slashes in pathnames.  However, this support does @emph{not} include the
2117 wildcard expansion, where backslash is a quote character.  Therefore,
2118 you @emph{must} use Unix-style slashes in these cases.
2121 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
2122 @subsection The Function @code{wildcard}
2123 @findex wildcard
2125 Wildcard expansion happens automatically in rules.  But wildcard expansion
2126 does not normally take place when a variable is set, or inside the
2127 arguments of a function.  If you want to do wildcard expansion in such
2128 places, you need to use the @code{wildcard} function, like this:
2130 @example
2131 $(wildcard @var{pattern}@dots{})
2132 @end example
2134 @noindent
2135 This string, used anywhere in a makefile, is replaced by a
2136 space-separated list of names of existing files that match one of the
2137 given file name patterns.  If no existing file name matches a pattern,
2138 then that pattern is omitted from the output of the @code{wildcard}
2139 function.  Note that this is different from how unmatched wildcards
2140 behave in rules, where they are used verbatim rather than ignored
2141 (@pxref{Wildcard Pitfall}).
2143 One use of the @code{wildcard} function is to get a list of all the C source
2144 files in a directory, like this:
2146 @example
2147 $(wildcard *.c)
2148 @end example
2150 We can change the list of C source files into a list of object files by
2151 replacing the @samp{.c} suffix with @samp{.o} in the result, like this:
2153 @example
2154 $(patsubst %.c,%.o,$(wildcard *.c))
2155 @end example
2157 @noindent
2158 (Here we have used another function, @code{patsubst}.
2159 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)@refill
2161 Thus, a makefile to compile all C source files in the directory and then
2162 link them together could be written as follows:
2164 @example
2165 objects := $(patsubst %.c,%.o,$(wildcard *.c))
2167 foo : $(objects)
2168         cc -o foo $(objects)
2169 @end example
2171 @noindent
2172 (This takes advantage of the implicit rule for compiling C programs, so
2173 there is no need to write explicit rules for compiling the files.
2174 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
2175 @samp{:=}, which is a variant of @samp{=}.)
2177 @node Directory Search, Phony Targets, Wildcards, Rules
2178 @section Searching Directories for Prerequisites
2179 @vindex VPATH
2180 @findex vpath
2181 @cindex vpath
2182 @cindex search path for prerequisites (@code{VPATH})
2183 @cindex directory search (@code{VPATH})
2185 For large systems, it is often desirable to put sources in a separate
2186 directory from the binaries.  The @dfn{directory search} features of
2187 @code{make} facilitate this by searching several directories
2188 automatically to find a prerequisite.  When you redistribute the files
2189 among directories, you do not need to change the individual rules,
2190 just the search paths.
2192 @menu
2193 * General Search::              Specifying a search path that applies
2194                                   to every prerequisite.
2195 * Selective Search::            Specifying a search path
2196                                   for a specified class of names.
2197 * Search Algorithm::            When and how search paths are applied.
2198 * Recipes/Search::              How to write recipes that work together
2199                                   with search paths.
2200 * Implicit/Search::             How search paths affect implicit rules.
2201 * Libraries/Search::            Directory search for link libraries.
2202 @end menu
2204 @node General Search, Selective Search, Directory Search, Directory Search
2205 @subsection @code{VPATH}: Search Path for All Prerequisites
2206 @vindex VPATH
2208 The value of the @code{make} variable @code{VPATH} specifies a list of
2209 directories that @code{make} should search.  Most often, the
2210 directories are expected to contain prerequisite files that are not in the
2211 current directory; however, @code{make} uses @code{VPATH} as a search
2212 list for both prerequisites and targets of rules.
2214 Thus, if a file that is listed as a target or prerequisite does not exist
2215 in the current directory, @code{make} searches the directories listed in
2216 @code{VPATH} for a file with that name.  If a file is found in one of
2217 them, that file may become the prerequisite (see below).  Rules may then
2218 specify the names of files in the prerequisite list as if they all
2219 existed in the current directory.  @xref{Recipes/Search, ,Writing Recipes with Directory Search}.
2221 In the @code{VPATH} variable, directory names are separated by colons or
2222 blanks.  The order in which directories are listed is the order followed
2223 by @code{make} in its search.  (On MS-DOS and MS-Windows, semi-colons
2224 are used as separators of directory names in @code{VPATH}, since the
2225 colon can be used in the pathname itself, after the drive letter.)
2227 For example,
2229 @example
2230 VPATH = src:../headers
2231 @end example
2233 @noindent
2234 specifies a path containing two directories, @file{src} and
2235 @file{../headers}, which @code{make} searches in that order.
2237 With this value of @code{VPATH}, the following rule,
2239 @example
2240 foo.o : foo.c
2241 @end example
2243 @noindent
2244 is interpreted as if it were written like this:
2246 @example
2247 foo.o : src/foo.c
2248 @end example
2250 @noindent
2251 assuming the file @file{foo.c} does not exist in the current directory but
2252 is found in the directory @file{src}.
2254 @node Selective Search, Search Algorithm, General Search, Directory Search
2255 @subsection The @code{vpath} Directive
2256 @findex vpath
2258 Similar to the @code{VPATH} variable, but more selective, is the
2259 @code{vpath} directive (note lower case), which allows you to specify a
2260 search path for a particular class of file names: those that match a
2261 particular pattern.  Thus you can supply certain search directories for
2262 one class of file names and other directories (or none) for other file
2263 names.
2265 There are three forms of the @code{vpath} directive:
2267 @table @code
2268 @item vpath @var{pattern} @var{directories}
2269 Specify the search path @var{directories} for file names that match
2270 @var{pattern}.
2272 The search path, @var{directories}, is a list of directories to be
2273 searched, separated by colons (semi-colons on MS-DOS and MS-Windows) or
2274 blanks, just like the search path used in the @code{VPATH} variable.
2276 @item vpath @var{pattern}
2277 Clear out the search path associated with @var{pattern}.
2279 @c Extra blank line makes sure this gets two lines.
2280 @item vpath
2282 Clear all search paths previously specified with @code{vpath} directives.
2283 @end table
2285 A @code{vpath} pattern is a string containing a @samp{%} character.  The
2286 string must match the file name of a prerequisite that is being searched
2287 for, the @samp{%} character matching any sequence of zero or more
2288 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
2289 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
2290 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
2291 prerequisite exactly, which is not useful very often.)
2293 @cindex @code{%}, quoting in @code{vpath}
2294 @cindex @code{%}, quoting with @code{\} (backslash)
2295 @cindex @code{\} (backslash), to quote @code{%}
2296 @cindex backslash (@code{\}), to quote @code{%}
2297 @cindex quoting @code{%}, in @code{vpath}
2298 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
2299 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
2300 quote @samp{%} characters can be quoted with more backslashes.
2301 Backslashes that quote @samp{%} characters or other backslashes are
2302 removed from the pattern before it is compared to file names.  Backslashes
2303 that are not in danger of quoting @samp{%} characters go unmolested.@refill
2305 When a prerequisite fails to exist in the current directory, if the
2306 @var{pattern} in a @code{vpath} directive matches the name of the
2307 prerequisite file, then the @var{directories} in that directive are searched
2308 just like (and before) the directories in the @code{VPATH} variable.
2310 For example,
2312 @example
2313 vpath %.h ../headers
2314 @end example
2316 @noindent
2317 tells @code{make} to look for any prerequisite whose name ends in @file{.h}
2318 in the directory @file{../headers} if the file is not found in the current
2319 directory.
2321 If several @code{vpath} patterns match the prerequisite file's name, then
2322 @code{make} processes each matching @code{vpath} directive one by one,
2323 searching all the directories mentioned in each directive.  @code{make}
2324 handles multiple @code{vpath} directives in the order in which they
2325 appear in the makefile; multiple directives with the same pattern are
2326 independent of each other.
2328 @need 750
2329 Thus,
2331 @example
2332 @group
2333 vpath %.c foo
2334 vpath %   blish
2335 vpath %.c bar
2336 @end group
2337 @end example
2339 @noindent
2340 will look for a file ending in @samp{.c} in @file{foo}, then
2341 @file{blish}, then @file{bar}, while
2343 @example
2344 @group
2345 vpath %.c foo:bar
2346 vpath %   blish
2347 @end group
2348 @end example
2350 @noindent
2351 will look for a file ending in @samp{.c} in @file{foo}, then
2352 @file{bar}, then @file{blish}.
2354 @node Search Algorithm, Recipes/Search, Selective Search, Directory Search
2355 @subsection How Directory Searches are Performed
2356 @cindex algorithm for directory search
2357 @cindex directory search algorithm
2359 When a prerequisite is found through directory search, regardless of type
2360 (general or selective), the pathname located may not be the one that
2361 @code{make} actually provides you in the prerequisite list.  Sometimes
2362 the path discovered through directory search is thrown away.
2364 The algorithm @code{make} uses to decide whether to keep or abandon a
2365 path found via directory search is as follows:
2367 @enumerate
2368 @item
2369 If a target file does not exist at the path specified in the makefile,
2370 directory search is performed.
2372 @item
2373 If the directory search is successful, that path is kept and this file
2374 is tentatively stored as the target.
2376 @item
2377 All prerequisites of this target are examined using this same method.
2379 @item
2380 After processing the prerequisites, the target may or may not need to be
2381 rebuilt:
2383 @enumerate a
2384 @item
2385 If the target does @emph{not} need to be rebuilt, the path to the file
2386 found during directory search is used for any prerequisite lists which
2387 contain this target.  In short, if @code{make} doesn't need to rebuild
2388 the target then you use the path found via directory search.
2390 @item
2391 If the target @emph{does} need to be rebuilt (is out-of-date), the
2392 pathname found during directory search is @emph{thrown away}, and the
2393 target is rebuilt using the file name specified in the makefile.  In
2394 short, if @code{make} must rebuild, then the target is rebuilt locally,
2395 not in the directory found via directory search.
2396 @end enumerate
2397 @end enumerate
2399 This algorithm may seem complex, but in practice it is quite often
2400 exactly what you want.
2402 @cindex traditional directory search (GPATH)
2403 @cindex directory search, traditional (GPATH)
2404 Other versions of @code{make} use a simpler algorithm: if the file does
2405 not exist, and it is found via directory search, then that pathname is
2406 always used whether or not the target needs to be built.  Thus, if the
2407 target is rebuilt it is created at the pathname discovered during
2408 directory search.
2410 @vindex GPATH
2411 If, in fact, this is the behavior you want for some or all of your
2412 directories, you can use the @code{GPATH} variable to indicate this to
2413 @code{make}.
2415 @code{GPATH} has the same syntax and format as @code{VPATH} (that is, a
2416 space- or colon-delimited list of pathnames).  If an out-of-date target
2417 is found by directory search in a directory that also appears in
2418 @code{GPATH}, then that pathname is not thrown away.  The target is
2419 rebuilt using the expanded path.
2421 @node Recipes/Search, Implicit/Search, Search Algorithm, Directory Search
2422 @subsection Writing Recipes with Directory Search
2423 @cindex recipes, and directory search
2424 @cindex directory search (@code{VPATH}), and recipes
2426 When a prerequisite is found in another directory through directory search,
2427 this cannot change the recipe of the rule; they will execute as written.
2428 Therefore, you must write the recipe with care so that it will look for
2429 the prerequisite in the directory where @code{make} finds it.
2431 This is done with the @dfn{automatic variables} such as @samp{$^}
2432 (@pxref{Automatic Variables}).
2433 For instance, the value of @samp{$^} is a
2434 list of all the prerequisites of the rule, including the names of
2435 the directories in which they were found, and the value of
2436 @samp{$@@} is the target.  Thus:@refill
2438 @example
2439 foo.o : foo.c
2440         cc -c $(CFLAGS) $^ -o $@@
2441 @end example
2443 @noindent
2444 (The variable @code{CFLAGS} exists so you can specify flags for C
2445 compilation by implicit rules; we use it here for consistency so it will
2446 affect all C compilations uniformly;
2447 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
2449 Often the prerequisites include header files as well, which you do not
2450 want to mention in the recipe.  The automatic variable @samp{$<} is
2451 just the first prerequisite:
2453 @example
2454 VPATH = src:../headers
2455 foo.o : foo.c defs.h hack.h
2456         cc -c $(CFLAGS) $< -o $@@
2457 @end example
2459 @node Implicit/Search, Libraries/Search, Recipes/Search, Directory Search
2460 @subsection Directory Search and Implicit Rules
2461 @cindex @code{VPATH}, and implicit rules
2462 @cindex directory search (@code{VPATH}), and implicit rules
2463 @cindex search path for prerequisites (@code{VPATH}), and implicit rules
2464 @cindex implicit rule, and directory search
2465 @cindex implicit rule, and @code{VPATH}
2466 @cindex rule, implicit, and directory search
2467 @cindex rule, implicit, and @code{VPATH}
2469 The search through the directories specified in @code{VPATH} or with
2470 @code{vpath} also happens during consideration of implicit rules
2471 (@pxref{Implicit Rules, ,Using Implicit Rules}).
2473 For example, when a file @file{foo.o} has no explicit rule, @code{make}
2474 considers implicit rules, such as the built-in rule to compile
2475 @file{foo.c} if that file exists.  If such a file is lacking in the
2476 current directory, the appropriate directories are searched for it.  If
2477 @file{foo.c} exists (or is mentioned in the makefile) in any of the
2478 directories, the implicit rule for C compilation is applied.
2480 The recipes of implicit rules normally use automatic variables as a
2481 matter of necessity; consequently they will use the file names found by
2482 directory search with no extra effort.
2484 @node Libraries/Search,  , Implicit/Search, Directory Search
2485 @subsection Directory Search for Link Libraries
2486 @cindex link libraries, and directory search
2487 @cindex libraries for linking, directory search
2488 @cindex directory search (@code{VPATH}), and link libraries
2489 @cindex @code{VPATH}, and link libraries
2490 @cindex search path for prerequisites (@code{VPATH}), and link libraries
2491 @cindex @code{-l} (library search)
2492 @cindex link libraries, patterns matching
2493 @cindex @code{.LIBPATTERNS}, and link libraries
2494 @vindex .LIBPATTERNS
2496 Directory search applies in a special way to libraries used with the
2497 linker.  This special feature comes into play when you write a prerequisite
2498 whose name is of the form @samp{-l@var{name}}.  (You can tell something
2499 strange is going on here because the prerequisite is normally the name of a
2500 file, and the @emph{file name} of a library generally looks like
2501 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)@refill
2503 When a prerequisite's name has the form @samp{-l@var{name}}, @code{make}
2504 handles it specially by searching for the file @file{lib@var{name}.so},
2505 and, if it is not found, for the file @file{lib@var{name}.a} in the current
2506 directory, in directories specified by matching @code{vpath}
2507 search paths and the @code{VPATH} search path, and then in the
2508 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
2509 (normally @file{/usr/local/lib}, but MS-DOS/MS-Windows versions of
2510 @code{make} behave as if @var{prefix} is defined to be the root of the
2511 DJGPP installation tree).
2513 For example, if there is a @file{/usr/lib/libcurses.a} library on your
2514 system (and no @file{/usr/lib/libcurses.so} file), then
2516 @example
2517 @group
2518 foo : foo.c -lcurses
2519         cc $^ -o $@@
2520 @end group
2521 @end example
2523 @noindent
2524 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
2525 be executed when @file{foo} is older than @file{foo.c} or than
2526 @file{/usr/lib/libcurses.a}.@refill
2528 Although the default set of files to be searched for is
2529 @file{lib@var{name}.so} and @file{lib@var{name}.a}, this is customizable
2530 via the @code{.LIBPATTERNS} variable.  Each word in the value of this
2531 variable is a pattern string.  When a prerequisite like
2532 @samp{-l@var{name}} is seen, @code{make} will replace the percent in
2533 each pattern in the list with @var{name} and perform the above directory
2534 searches using each library file name.
2536 The default value for @code{.LIBPATTERNS} is @samp{lib%.so lib%.a},
2537 which provides the default behavior described above.
2539 You can turn off link library expansion completely by setting this
2540 variable to an empty value.
2542 @node Phony Targets, Force Targets, Directory Search, Rules
2543 @section Phony Targets
2544 @cindex phony targets
2545 @cindex targets, phony
2546 @cindex targets without a file
2548 A phony target is one that is not really the name of a file; rather it
2549 is just a name for a recipe to be executed when you make an explicit
2550 request.  There are two reasons to use a phony target: to avoid a
2551 conflict with a file of the same name, and to improve performance.
2553 If you write a rule whose recipe will not create the target file, the
2554 recipe will be executed every time the target comes up for remaking.
2555 Here is an example:
2557 @example
2558 @group
2559 clean:
2560         rm *.o temp
2561 @end group
2562 @end example
2564 @noindent
2565 Because the @code{rm} command does not create a file named @file{clean},
2566 probably no such file will ever exist.  Therefore, the @code{rm} command
2567 will be executed every time you say @samp{make clean}.
2568 @cindex @code{rm} (shell command)
2570 @findex .PHONY
2571 The phony target will cease to work if anything ever does create a file
2572 named @file{clean} in this directory.  Since it has no prerequisites, the
2573 file @file{clean} would inevitably be considered up to date, and its
2574 recipe would not be executed.  To avoid this problem, you can explicitly
2575 declare the target to be phony, using the special target @code{.PHONY}
2576 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
2578 @example
2579 .PHONY : clean
2580 @end example
2582 @noindent
2583 Once this is done, @samp{make clean} will run the recipe regardless of
2584 whether there is a file named @file{clean}.
2586 Since it knows that phony targets do not name actual files that could be
2587 remade from other files, @code{make} skips the implicit rule search for
2588 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
2589 phony is good for performance, even if you are not worried about the
2590 actual file existing.
2592 Thus, you first write the line that states that @code{clean} is a
2593 phony target, then you write the rule, like this:
2595 @example
2596 @group
2597 .PHONY: clean
2598 clean:
2599         rm *.o temp
2600 @end group
2601 @end example
2603 Another example of the usefulness of phony targets is in conjunction
2604 with recursive invocations of @code{make} (for more information, see
2605 @ref{Recursion, ,Recursive Use of @code{make}}).  In this case the
2606 makefile will often contain a variable which lists a number of
2607 sub-directories to be built.  One way to handle this is with one rule
2608 whose recipe is a shell loop over the sub-directories, like this:
2610 @example
2611 @group
2612 SUBDIRS = foo bar baz
2614 subdirs:
2615         for dir in $(SUBDIRS); do \
2616           $(MAKE) -C $$dir; \
2617         done
2618 @end group
2619 @end example
2621 There are problems with this method, however.  First, any error
2622 detected in a sub-make is ignored by this rule, so it will continue
2623 to build the rest of the directories even when one fails.  This can be
2624 overcome by adding shell commands to note the error and exit, but then
2625 it will do so even if @code{make} is invoked with the @code{-k}
2626 option, which is unfortunate.  Second, and perhaps more importantly,
2627 you cannot take advantage of @code{make}'s ability to build targets in
2628 parallel (@pxref{Parallel, ,Parallel Execution}), since there is only
2629 one rule.
2631 By declaring the sub-directories as phony targets (you must do this as
2632 the sub-directory obviously always exists; otherwise it won't be built)
2633 you can remove these problems:
2635 @example
2636 @group
2637 SUBDIRS = foo bar baz
2639 .PHONY: subdirs $(SUBDIRS)
2641 subdirs: $(SUBDIRS)
2643 $(SUBDIRS):
2644         $(MAKE) -C $@@
2646 foo: baz
2647 @end group
2648 @end example
2650 Here we've also declared that the @file{foo} sub-directory cannot be
2651 built until after the @file{baz} sub-directory is complete; this kind of
2652 relationship declaration is particularly important when attempting
2653 parallel builds.
2655 A phony target should not be a prerequisite of a real target file; if it
2656 is, its recipe will be run every time @code{make} goes to update that
2657 file.  As long as a phony target is never a prerequisite of a real
2658 target, the phony target recipe will be executed only when the phony
2659 target is a specified goal (@pxref{Goals, ,Arguments to Specify the
2660 Goals}).
2662 Phony targets can have prerequisites.  When one directory contains multiple
2663 programs, it is most convenient to describe all of the programs in one
2664 makefile @file{./Makefile}.  Since the target remade by default will be the
2665 first one in the makefile, it is common to make this a phony target named
2666 @samp{all} and give it, as prerequisites, all the individual programs.  For
2667 example:
2669 @example
2670 all : prog1 prog2 prog3
2671 .PHONY : all
2673 prog1 : prog1.o utils.o
2674         cc -o prog1 prog1.o utils.o
2676 prog2 : prog2.o
2677         cc -o prog2 prog2.o
2679 prog3 : prog3.o sort.o utils.o
2680         cc -o prog3 prog3.o sort.o utils.o
2681 @end example
2683 @noindent
2684 Now you can say just @samp{make} to remake all three programs, or
2685 specify as arguments the ones to remake (as in @samp{make prog1
2686 prog3}).  Phoniness is not inherited: the prerequisites of a phony
2687 target are not themselves phony, unless explicitly declared to be so.
2689 When one phony target is a prerequisite of another, it serves as a subroutine
2690 of the other.  For example, here @samp{make cleanall} will delete the
2691 object files, the difference files, and the file @file{program}:
2693 @example
2694 .PHONY: cleanall cleanobj cleandiff
2696 cleanall : cleanobj cleandiff
2697         rm program
2699 cleanobj :
2700         rm *.o
2702 cleandiff :
2703         rm *.diff
2704 @end example
2706 @node Force Targets, Empty Targets, Phony Targets, Rules
2707 @section Rules without Recipes or Prerequisites
2708 @cindex force targets
2709 @cindex targets, force
2710 @cindex @code{FORCE}
2711 @cindex rule, no recipe or prerequisites
2713 If a rule has no prerequisites or recipe, and the target of the rule
2714 is a nonexistent file, then @code{make} imagines this target to have
2715 been updated whenever its rule is run.  This implies that all targets
2716 depending on this one will always have their recipe run.
2718 An example will illustrate this:
2720 @example
2721 @group
2722 clean: FORCE
2723         rm $(objects)
2724 FORCE:
2725 @end group
2726 @end example
2728 Here the target @samp{FORCE} satisfies the special conditions, so the
2729 target @file{clean} that depends on it is forced to run its recipe.
2730 There is nothing special about the name @samp{FORCE}, but that is one
2731 name commonly used this way.
2733 As you can see, using @samp{FORCE} this way has the same results as using
2734 @samp{.PHONY: clean}.
2736 Using @samp{.PHONY} is more explicit and more efficient.  However,
2737 other versions of @code{make} do not support @samp{.PHONY}; thus
2738 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2740 @node Empty Targets, Special Targets, Force Targets, Rules
2741 @section Empty Target Files to Record Events
2742 @cindex empty targets
2743 @cindex targets, empty
2744 @cindex recording events with empty targets
2746 The @dfn{empty target} is a variant of the phony target; it is used to hold
2747 recipes for an action that you request explicitly from time to time.
2748 Unlike a phony target, this target file can really exist; but the file's
2749 contents do not matter, and usually are empty.
2751 The purpose of the empty target file is to record, with its
2752 last-modification time, when the rule's recipe was last executed.  It
2753 does so because one of the commands in the recipe is a @code{touch}
2754 command to update the target file.
2756 The empty target file should have some prerequisites (otherwise it
2757 doesn't make sense).  When you ask to remake the empty target, the
2758 recipe is executed if any prerequisite is more recent than the target;
2759 in other words, if a prerequisite has changed since the last time you
2760 remade the target.  Here is an example:
2762 @example
2763 print: foo.c bar.c
2764         lpr -p $?
2765         touch print
2766 @end example
2767 @cindex @code{print} target
2768 @cindex @code{lpr} (shell command)
2769 @cindex @code{touch} (shell command)
2771 @noindent
2772 With this rule, @samp{make print} will execute the @code{lpr} command if
2773 either source file has changed since the last @samp{make print}.  The
2774 automatic variable @samp{$?} is used to print only those files that have
2775 changed (@pxref{Automatic Variables}).
2777 @node Special Targets, Multiple Targets, Empty Targets, Rules
2778 @section Special Built-in Target Names
2779 @cindex special targets
2780 @cindex built-in special targets
2781 @cindex targets, built-in special
2783 Certain names have special meanings if they appear as targets.
2785 @table @code
2786 @findex .PHONY
2787 @item .PHONY
2789 The prerequisites of the special target @code{.PHONY} are considered to
2790 be phony targets.  When it is time to consider such a target,
2791 @code{make} will run its recipe unconditionally, regardless of
2792 whether a file with that name exists or what its last-modification
2793 time is.  @xref{Phony Targets, ,Phony Targets}.
2795 @findex .SUFFIXES
2796 @item .SUFFIXES
2798 The prerequisites of the special target @code{.SUFFIXES} are the list
2799 of suffixes to be used in checking for suffix rules.
2800 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
2802 @findex .DEFAULT
2803 @item .DEFAULT
2805 The recipe specified for @code{.DEFAULT} is used for any target for
2806 which no rules are found (either explicit rules or implicit rules).
2807 @xref{Last Resort}.  If a @code{.DEFAULT} recipe is specified, every
2808 file mentioned as a prerequisite, but not as a target in a rule, will have
2809 that recipe executed on its behalf.  @xref{Implicit Rule Search,
2810 ,Implicit Rule Search Algorithm}.
2812 @findex .PRECIOUS
2813 @item .PRECIOUS
2814 @cindex precious targets
2815 @cindex preserving with @code{.PRECIOUS}
2817 The targets which @code{.PRECIOUS} depends on are given the following
2818 special treatment: if @code{make} is killed or interrupted during the
2819 execution of their recipes, the target is not deleted.
2820 @xref{Interrupts, ,Interrupting or Killing @code{make}}.  Also, if the
2821 target is an intermediate file, it will not be deleted after it is no
2822 longer needed, as is normally done.  @xref{Chained Rules, ,Chains of
2823 Implicit Rules}.  In this latter respect it overlaps with the
2824 @code{.SECONDARY} special target.
2826 You can also list the target pattern of an implicit rule (such as
2827 @samp{%.o}) as a prerequisite file of the special target @code{.PRECIOUS}
2828 to preserve intermediate files created by rules whose target patterns
2829 match that file's name.
2831 @findex .INTERMEDIATE
2832 @item .INTERMEDIATE
2833 @cindex intermediate targets, explicit
2835 The targets which @code{.INTERMEDIATE} depends on are treated as
2836 intermediate files.  @xref{Chained Rules, ,Chains of Implicit Rules}.
2837 @code{.INTERMEDIATE} with no prerequisites has no effect.
2839 @findex .SECONDARY
2840 @item .SECONDARY
2841 @cindex secondary targets
2842 @cindex preserving with @code{.SECONDARY}
2844 The targets which @code{.SECONDARY} depends on are treated as
2845 intermediate files, except that they are never automatically deleted.
2846 @xref{Chained Rules, ,Chains of Implicit Rules}.
2848 @code{.SECONDARY} with no prerequisites causes all targets to be treated
2849 as secondary (i.e., no target is removed because it is considered
2850 intermediate).
2852 @findex .SECONDEXPANSION
2853 @item .SECONDEXPANSION
2855 If @code{.SECONDEXPANSION} is mentioned as a target anywhere in the
2856 makefile, then all prerequisite lists defined @emph{after} it appears
2857 will be expanded a second time after all makefiles have been read in.
2858 @xref{Secondary Expansion, ,Secondary Expansion}.
2860 @findex .DELETE_ON_ERROR
2861 @item .DELETE_ON_ERROR
2862 @cindex removing targets on failure
2864 If @code{.DELETE_ON_ERROR} is mentioned as a target anywhere in the
2865 makefile, then @code{make} will delete the target of a rule if it has
2866 changed and its recipe exits with a nonzero exit status, just as it
2867 does when it receives a signal.  @xref{Errors, ,Errors in Recipes}.
2869 @findex .IGNORE
2870 @item .IGNORE
2872 If you specify prerequisites for @code{.IGNORE}, then @code{make} will
2873 ignore errors in execution of the recipe for those particular files.
2874 The recipe for @code{.IGNORE} (if any) is ignored.
2876 If mentioned as a target with no prerequisites, @code{.IGNORE} says to
2877 ignore errors in execution of recipes for all files.  This usage of
2878 @samp{.IGNORE} is supported only for historical compatibility.  Since
2879 this affects every recipe in the makefile, it is not very useful; we
2880 recommend you use the more selective ways to ignore errors in specific
2881 recipes.  @xref{Errors, ,Errors in Recipes}.
2883 @findex .LOW_RESOLUTION_TIME
2884 @item .LOW_RESOLUTION_TIME
2886 If you specify prerequisites for @code{.LOW_RESOLUTION_TIME},
2887 @command{make} assumes that these files are created by commands that
2888 generate low resolution time stamps.  The recipe for the
2889 @code{.LOW_RESOLUTION_TIME} target are ignored.
2891 The high resolution file time stamps of many modern file systems
2892 lessen the chance of @command{make} incorrectly concluding that a file
2893 is up to date.  Unfortunately, some hosts do not provide a way to set a
2894 high resolution file time stamp, so commands like @samp{cp -p} that
2895 explicitly set a file's time stamp must discard its sub-second part.
2896 If a file is created by such a command, you should list it as a
2897 prerequisite of @code{.LOW_RESOLUTION_TIME} so that @command{make}
2898 does not mistakenly conclude that the file is out of date.  For
2899 example:
2901 @example
2902 @group
2903 .LOW_RESOLUTION_TIME: dst
2904 dst: src
2905         cp -p src dst
2906 @end group
2907 @end example
2909 Since @samp{cp -p} discards the sub-second part of @file{src}'s time
2910 stamp, @file{dst} is typically slightly older than @file{src} even when
2911 it is up to date.  The @code{.LOW_RESOLUTION_TIME} line causes
2912 @command{make} to consider @file{dst} to be up to date if its time stamp
2913 is at the start of the same second that @file{src}'s time stamp is in.
2915 Due to a limitation of the archive format, archive member time stamps
2916 are always low resolution.  You need not list archive members as
2917 prerequisites of @code{.LOW_RESOLUTION_TIME}, as @command{make} does this
2918 automatically.
2920 @findex .SILENT
2921 @item .SILENT
2923 If you specify prerequisites for @code{.SILENT}, then @code{make} will
2924 not print the recipe used to remake those particular files before
2925 executing them.  The recipe for @code{.SILENT} is ignored.
2927 If mentioned as a target with no prerequisites, @code{.SILENT} says not
2928 to print any recipes before executing them.  This usage of
2929 @samp{.SILENT} is supported only for historical compatibility.  We
2930 recommend you use the more selective ways to silence specific recipes.
2931 @xref{Echoing, ,Recipe Echoing}.  If you want to silence all recipes
2932 for a particular run of @code{make}, use the @samp{-s} or
2933 @w{@samp{--silent}} option (@pxref{Options Summary}).
2935 @findex .EXPORT_ALL_VARIABLES
2936 @item .EXPORT_ALL_VARIABLES
2938 Simply by being mentioned as a target, this tells @code{make} to
2939 export all variables to child processes by default.
2940 @xref{Variables/Recursion, ,Communicating Variables to a
2941 Sub-@code{make}}.
2943 @findex .NOTPARALLEL
2944 @item .NOTPARALLEL
2945 @cindex parallel execution, overriding
2947 If @code{.NOTPARALLEL} is mentioned as a target, then this invocation
2948 of @code{make} will be run serially, even if the @samp{-j} option is
2949 given.  Any recursively invoked @code{make} command will still run
2950 recipes in parallel (unless its makefile also contains this target).
2951 Any prerequisites on this target are ignored.
2953 @findex .ONESHELL
2954 @item .ONESHELL
2955 @cindex recipe execution, single invocation
2957 If @code{.ONESHELL} is mentioned as a target, then when a target is
2958 built all lines of the recipe will be given to a single invocation of
2959 the shell rather than each line being invoked separately
2960 (@pxref{Execution, ,Recipe Execution}).
2962 @findex .POSIX
2963 @item .POSIX
2964 @cindex POSIX-conforming mode, setting
2966 If @code{.POSIX} is mentioned as a target, then the makefile will be
2967 parsed and run in POSIX-conforming mode.  This does @emph{not} mean
2968 that only POSIX-conforming makefiles will be accepted: all advanced
2969 GNU @code{make} features are still available.  Rather, this target
2970 causes @code{make} to behave as required by POSIX in those areas
2971 where @code{make}'s default behavior differs.
2973 In particular, if this target is mentioned then recipes will be
2974 invoked as if the shell had been passed the @code{-e} flag: the first
2975 failing command in a recipe will cause the recipe to fail immediately.
2976 @end table
2978 Any defined implicit rule suffix also counts as a special target if it
2979 appears as a target, and so does the concatenation of two suffixes, such
2980 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
2981 defining implicit rules (but a way still widely used).  In principle, any
2982 target name could be special in this way if you break it in two and add
2983 both pieces to the suffix list.  In practice, suffixes normally begin with
2984 @samp{.}, so these special target names also begin with @samp{.}.
2985 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
2987 @node Multiple Targets, Multiple Rules, Special Targets, Rules
2988 @section Multiple Targets in a Rule
2989 @cindex multiple targets
2990 @cindex several targets in a rule
2991 @cindex targets, multiple
2992 @cindex rule, with multiple targets
2994 A rule with multiple targets is equivalent to writing many rules, each with
2995 one target, and all identical aside from that.  The same recipe applies to
2996 all the targets, but its effect may vary because you can substitute the
2997 actual target name into the recipe using @samp{$@@}.  The rule contributes
2998 the same prerequisites to all the targets also.
3000 This is useful in two cases.
3002 @itemize @bullet
3003 @item
3004 You want just prerequisites, no recipe.  For example:
3006 @example
3007 kbd.o command.o files.o: command.h
3008 @end example
3010 @noindent
3011 gives an additional prerequisite to each of the three object files
3012 mentioned.
3014 @item
3015 Similar recipes work for all the targets.  The recipes do not need
3016 to be absolutely identical, since the automatic variable @samp{$@@}
3017 can be used to substitute the particular target to be remade into the
3018 commands (@pxref{Automatic Variables}).  For example:
3020 @example
3021 @group
3022 bigoutput littleoutput : text.g
3023         generate text.g -$(subst output,,$@@) > $@@
3024 @end group
3025 @end example
3026 @findex subst
3028 @noindent
3029 is equivalent to
3031 @example
3032 bigoutput : text.g
3033         generate text.g -big > bigoutput
3034 littleoutput : text.g
3035         generate text.g -little > littleoutput
3036 @end example
3038 @noindent
3039 Here we assume the hypothetical program @code{generate} makes two
3040 types of output, one if given @samp{-big} and one if given
3041 @samp{-little}.
3042 @xref{Text Functions, ,Functions for String Substitution and Analysis},
3043 for an explanation of the @code{subst} function.
3044 @end itemize
3046 Suppose you would like to vary the prerequisites according to the
3047 target, much as the variable @samp{$@@} allows you to vary the recipe.
3048 You cannot do this with multiple targets in an ordinary rule, but you
3049 can do it with a @dfn{static pattern rule}.  @xref{Static Pattern,
3050 ,Static Pattern Rules}.
3052 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
3053 @section Multiple Rules for One Target
3054 @cindex multiple rules for one target
3055 @cindex several rules for one target
3056 @cindex rule, multiple for one target
3057 @cindex target, multiple rules for one
3059 One file can be the target of several rules.  All the prerequisites
3060 mentioned in all the rules are merged into one list of prerequisites for
3061 the target.  If the target is older than any prerequisite from any rule,
3062 the recipe is executed.
3064 There can only be one recipe to be executed for a file.  If more than
3065 one rule gives a recipe for the same file, @code{make} uses the last
3066 one given and prints an error message.  (As a special case, if the
3067 file's name begins with a dot, no error message is printed.  This odd
3068 behavior is only for compatibility with other implementations of
3069 @code{make}@dots{} you should avoid using it).  Occasionally it is
3070 useful to have the same target invoke multiple recipes which are
3071 defined in different parts of your makefile; you can use
3072 @dfn{double-colon rules} (@pxref{Double-Colon}) for this.
3074 An extra rule with just prerequisites can be used to give a few extra
3075 prerequisites to many files at once.  For example, makefiles often
3076 have a variable, such as @code{objects}, containing a list of all the
3077 compiler output files in the system being made.  An easy way to say
3078 that all of them must be recompiled if @file{config.h} changes is to
3079 write the following:
3081 @example
3082 objects = foo.o bar.o
3083 foo.o : defs.h
3084 bar.o : defs.h test.h
3085 $(objects) : config.h
3086 @end example
3088 This could be inserted or taken out without changing the rules that really
3089 specify how to make the object files, making it a convenient form to use if
3090 you wish to add the additional prerequisite intermittently.
3092 Another wrinkle is that the additional prerequisites could be
3093 specified with a variable that you set with a command line argument to
3094 @code{make} (@pxref{Overriding, ,Overriding Variables}).  For example,
3096 @example
3097 @group
3098 extradeps=
3099 $(objects) : $(extradeps)
3100 @end group
3101 @end example
3103 @noindent
3104 means that the command @samp{make extradeps=foo.h} will consider
3105 @file{foo.h} as a prerequisite of each object file, but plain @samp{make}
3106 will not.
3108 If none of the explicit rules for a target has a recipe, then @code{make}
3109 searches for an applicable implicit rule to find one
3110 @pxref{Implicit Rules, ,Using Implicit Rules}).
3112 @node Static Pattern, Double-Colon, Multiple Rules, Rules
3113 @section Static Pattern Rules
3114 @cindex static pattern rule
3115 @cindex rule, static pattern
3116 @cindex pattern rules, static (not implicit)
3117 @cindex varying prerequisites
3118 @cindex prerequisites, varying (static pattern)
3120 @dfn{Static pattern rules} are rules which specify multiple targets and
3121 construct the prerequisite names for each target based on the target name.
3122 They are more general than ordinary rules with multiple targets because the
3123 targets do not have to have identical prerequisites.  Their prerequisites must
3124 be @emph{analogous}, but not necessarily @emph{identical}.
3126 @menu
3127 * Static Usage::                The syntax of static pattern rules.
3128 * Static versus Implicit::      When are they better than implicit rules?
3129 @end menu
3131 @node Static Usage, Static versus Implicit, Static Pattern, Static Pattern
3132 @subsection Syntax of Static Pattern Rules
3133 @cindex static pattern rule, syntax of
3134 @cindex pattern rules, static, syntax of
3136 Here is the syntax of a static pattern rule:
3138 @example
3139 @var{targets} @dots{}: @var{target-pattern}: @var{prereq-patterns} @dots{}
3140         @var{recipe}
3141         @dots{}
3142 @end example
3144 @noindent
3145 The @var{targets} list specifies the targets that the rule applies to.
3146 The targets can contain wildcard characters, just like the targets of
3147 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
3148 Names}).
3150 @cindex target pattern, static (not implicit)
3151 @cindex stem
3152 The @var{target-pattern} and @var{prereq-patterns} say how to compute the
3153 prerequisites of each target.  Each target is matched against the
3154 @var{target-pattern} to extract a part of the target name, called the
3155 @dfn{stem}.  This stem is substituted into each of the @var{prereq-patterns}
3156 to make the prerequisite names (one from each @var{prereq-pattern}).
3158 Each pattern normally contains the character @samp{%} just once.  When the
3159 @var{target-pattern} matches a target, the @samp{%} can match any part of
3160 the target name; this part is called the @dfn{stem}.  The rest of the
3161 pattern must match exactly.  For example, the target @file{foo.o} matches
3162 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
3163 @file{foo.c} and @file{foo.out} do not match that pattern.@refill
3165 @cindex prerequisite pattern, static (not implicit)
3166 The prerequisite names for each target are made by substituting the stem
3167 for the @samp{%} in each prerequisite pattern.  For example, if one
3168 prerequisite pattern is @file{%.c}, then substitution of the stem
3169 @samp{foo} gives the prerequisite name @file{foo.c}.  It is legitimate
3170 to write a prerequisite pattern that does not contain @samp{%}; then this
3171 prerequisite is the same for all targets.
3173 @cindex @code{%}, quoting in static pattern
3174 @cindex @code{%}, quoting with @code{\} (backslash)
3175 @cindex @code{\} (backslash), to quote @code{%}
3176 @cindex backslash (@code{\}), to quote @code{%}
3177 @cindex quoting @code{%}, in static pattern
3178 @samp{%} characters in pattern rules can be quoted with preceding
3179 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
3180 characters can be quoted with more backslashes.  Backslashes that quote
3181 @samp{%} characters or other backslashes are removed from the pattern
3182 before it is compared to file names or has a stem substituted into it.
3183 Backslashes that are not in danger of quoting @samp{%} characters go
3184 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
3185 @samp{the%weird\} preceding the operative @samp{%} character, and
3186 @samp{pattern\\} following it.  The final two backslashes are left alone
3187 because they cannot affect any @samp{%} character.@refill
3189 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
3190 from the corresponding @file{.c} file:
3192 @example
3193 @group
3194 objects = foo.o bar.o
3196 all: $(objects)
3198 $(objects): %.o: %.c
3199         $(CC) -c $(CFLAGS) $< -o $@@
3200 @end group
3201 @end example
3203 @noindent
3204 Here @samp{$<} is the automatic variable that holds the name of the
3205 prerequisite and @samp{$@@} is the automatic variable that holds the name
3206 of the target; see @ref{Automatic Variables}.
3208 Each target specified must match the target pattern; a warning is issued
3209 for each target that does not.  If you have a list of files, only some of
3210 which will match the pattern, you can use the @code{filter} function to
3211 remove non-matching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
3213 @example
3214 files = foo.elc bar.o lose.o
3216 $(filter %.o,$(files)): %.o: %.c
3217         $(CC) -c $(CFLAGS) $< -o $@@
3218 $(filter %.elc,$(files)): %.elc: %.el
3219         emacs -f batch-byte-compile $<
3220 @end example
3222 @noindent
3223 In this example the result of @samp{$(filter %.o,$(files))} is
3224 @file{bar.o lose.o}, and the first static pattern rule causes each of
3225 these object files to be updated by compiling the corresponding C source
3226 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
3227 @file{foo.elc}, so that file is made from @file{foo.el}.@refill
3229 Another example shows how to use @code{$*} in static pattern rules:
3230 @vindex $*@r{, and static pattern}
3232 @example
3233 @group
3234 bigoutput littleoutput : %output : text.g
3235         generate text.g -$* > $@@
3236 @end group
3237 @end example
3239 @noindent
3240 When the @code{generate} command is run, @code{$*} will expand to the
3241 stem, either @samp{big} or @samp{little}.
3243 @node Static versus Implicit,  , Static Usage, Static Pattern
3244 @subsection Static Pattern Rules versus Implicit Rules
3245 @cindex rule, static pattern versus implicit
3246 @cindex static pattern rule, versus implicit
3248 A static pattern rule has much in common with an implicit rule defined as a
3249 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
3250 Both have a pattern for the target and patterns for constructing the
3251 names of prerequisites.  The difference is in how @code{make} decides
3252 @emph{when} the rule applies.
3254 An implicit rule @emph{can} apply to any target that matches its pattern,
3255 but it @emph{does} apply only when the target has no recipe otherwise
3256 specified, and only when the prerequisites can be found.  If more than one
3257 implicit rule appears applicable, only one applies; the choice depends on
3258 the order of rules.
3260 By contrast, a static pattern rule applies to the precise list of targets
3261 that you specify in the rule.  It cannot apply to any other target and it
3262 invariably does apply to each of the targets specified.  If two conflicting
3263 rules apply, and both have recipes, that's an error.
3265 The static pattern rule can be better than an implicit rule for these
3266 reasons:
3268 @itemize @bullet
3269 @item
3270 You may wish to override the usual implicit rule for a few
3271 files whose names cannot be categorized syntactically but
3272 can be given in an explicit list.
3274 @item
3275 If you cannot be sure of the precise contents of the directories
3276 you are using, you may not be sure which other irrelevant files
3277 might lead @code{make} to use the wrong implicit rule.  The choice
3278 might depend on the order in which the implicit rule search is done.
3279 With static pattern rules, there is no uncertainty: each rule applies
3280 to precisely the targets specified.
3281 @end itemize
3283 @node Double-Colon, Automatic Prerequisites, Static Pattern, Rules
3284 @section Double-Colon Rules
3285 @cindex double-colon rules
3286 @cindex rule, double-colon (@code{::})
3287 @cindex multiple rules for one target (@code{::})
3288 @cindex @code{::} rules (double-colon)
3290 @dfn{Double-colon} rules are explicit rules written with @samp{::}
3291 instead of @samp{:} after the target names.  They are handled
3292 differently from ordinary rules when the same target appears in more
3293 than one rule.  Pattern rules with double-colons have an entirely
3294 different meaning (@pxref{Match-Anything Rules}).
3296 When a target appears in multiple rules, all the rules must be the same
3297 type: all ordinary, or all double-colon.  If they are double-colon, each
3298 of them is independent of the others.  Each double-colon rule's recipe
3299 is executed if the target is older than any prerequisites of that rule.
3300 If there are no prerequisites for that rule, its recipe is always
3301 executed (even if the target already exists).  This can result in
3302 executing none, any, or all of the double-colon rules.
3304 Double-colon rules with the same target are in fact completely separate
3305 from one another.  Each double-colon rule is processed individually, just
3306 as rules with different targets are processed.
3308 The double-colon rules for a target are executed in the order they appear
3309 in the makefile.  However, the cases where double-colon rules really make
3310 sense are those where the order of executing the recipes would not matter.
3312 Double-colon rules are somewhat obscure and not often very useful; they
3313 provide a mechanism for cases in which the method used to update a target
3314 differs depending on which prerequisite files caused the update, and such
3315 cases are rare.
3317 Each double-colon rule should specify a recipe; if it does not, an
3318 implicit rule will be used if one applies.
3319 @xref{Implicit Rules, ,Using Implicit Rules}.
3321 @node Automatic Prerequisites,  , Double-Colon, Rules
3322 @section Generating Prerequisites Automatically
3323 @cindex prerequisites, automatic generation
3324 @cindex automatic generation of prerequisites
3325 @cindex generating prerequisites automatically
3327 In the makefile for a program, many of the rules you need to write often
3328 say only that some object file depends on some header
3329 file.  For example, if @file{main.c} uses @file{defs.h} via an
3330 @code{#include}, you would write:
3332 @example
3333 main.o: defs.h
3334 @end example
3336 @noindent
3337 You need this rule so that @code{make} knows that it must remake
3338 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
3339 large program you would have to write dozens of such rules in your
3340 makefile.  And, you must always be very careful to update the makefile
3341 every time you add or remove an @code{#include}.
3342 @cindex @code{#include}
3344 @cindex @code{-M} (to compiler)
3345 To avoid this hassle, most modern C compilers can write these rules for
3346 you, by looking at the @code{#include} lines in the source files.
3347 Usually this is done with the @samp{-M} option to the compiler.
3348 For example, the command:
3350 @example
3351 cc -M main.c
3352 @end example
3354 @noindent
3355 generates the output:
3357 @example
3358 main.o : main.c defs.h
3359 @end example
3361 @noindent
3362 Thus you no longer have to write all those rules yourself.
3363 The compiler will do it for you.
3365 Note that such a rule constitutes mentioning @file{main.o} in a
3366 makefile, so it can never be considered an intermediate file by
3367 implicit rule search.  This means that @code{make} won't ever remove
3368 the file after using it; @pxref{Chained Rules, ,Chains of Implicit
3369 Rules}.
3371 @cindex @code{make depend}
3372 With old @code{make} programs, it was traditional practice to use this
3373 compiler feature to generate prerequisites on demand with a command like
3374 @samp{make depend}.  That command would create a file @file{depend}
3375 containing all the automatically-generated prerequisites; then the
3376 makefile could use @code{include} to read them in (@pxref{Include}).
3378 In GNU @code{make}, the feature of remaking makefiles makes this
3379 practice obsolete---you need never tell @code{make} explicitly to
3380 regenerate the prerequisites, because it always regenerates any makefile
3381 that is out of date.  @xref{Remaking Makefiles}.
3383 The practice we recommend for automatic prerequisite generation is to have
3384 one makefile corresponding to each source file.  For each source file
3385 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
3386 what files the object file @file{@var{name}.o} depends on.  That way
3387 only the source files that have changed need to be rescanned to produce
3388 the new prerequisites.
3390 Here is the pattern rule to generate a file of prerequisites (i.e., a makefile)
3391 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
3393 @smallexample
3394 @group
3395 %.d: %.c
3396         @@set -e; rm -f $@@; \
3397          $(CC) -M $(CPPFLAGS) $< > $@@.$$$$; \
3398          sed 's,\($*\)\.o[ :]*,\1.o $@@ : ,g' < $@@.$$$$ > $@@; \
3399          rm -f $@@.$$$$
3400 @end group
3401 @end smallexample
3403 @noindent
3404 @xref{Pattern Rules}, for information on defining pattern rules.  The
3405 @samp{-e} flag to the shell causes it to exit immediately if the
3406 @code{$(CC)} command (or any other command) fails (exits with a
3407 nonzero status).
3408 @cindex @code{-e} (shell flag)
3410 @cindex @code{-MM} (to GNU compiler)
3411 With the GNU C compiler, you may wish to use the @samp{-MM} flag instead
3412 of @samp{-M}.  This omits prerequisites on system header files.
3413 @xref{Preprocessor Options, , Options Controlling the Preprocessor,
3414 gcc, Using GNU CC}, for details.
3416 @cindex @code{sed} (shell command)
3417 The purpose of the @code{sed} command is to translate (for example):
3419 @example
3420 main.o : main.c defs.h
3421 @end example
3423 @noindent
3424 into:
3426 @example
3427 main.o main.d : main.c defs.h
3428 @end example
3430 @noindent
3431 @cindex @code{.d}
3432 This makes each @samp{.d} file depend on all the source and header files
3433 that the corresponding @samp{.o} file depends on.  @code{make} then
3434 knows it must regenerate the prerequisites whenever any of the source or
3435 header files changes.
3437 Once you've defined the rule to remake the @samp{.d} files,
3438 you then use the @code{include} directive to read them all in.
3439 @xref{Include}.  For example:
3441 @example
3442 @group
3443 sources = foo.c bar.c
3445 include $(sources:.c=.d)
3446 @end group
3447 @end example
3449 @noindent
3450 (This example uses a substitution variable reference to translate the
3451 list of source files @samp{foo.c bar.c} into a list of prerequisite
3452 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
3453 information on substitution references.)  Since the @samp{.d} files are
3454 makefiles like any others, @code{make} will remake them as necessary
3455 with no further work from you.  @xref{Remaking Makefiles}.
3457 Note that the @samp{.d} files contain target definitions; you should
3458 be sure to place the @code{include} directive @emph{after} the first,
3459 default goal in your makefiles or run the risk of having a random
3460 object file become the default goal.
3461 @xref{How Make Works}.
3463 @node Recipes, Using Variables, Rules, Top
3464 @chapter Writing Recipes in Rules
3465 @cindex recipes
3466 @cindex recipes, how to write
3467 @cindex writing recipes
3469 The recipe of a rule consists of one or more shell command lines to
3470 be executed, one at a time, in the order they appear.  Typically, the
3471 result of executing these commands is that the target of the rule is
3472 brought up to date.
3474 Users use many different shell programs, but recipes in makefiles are
3475 always interpreted by @file{/bin/sh} unless the makefile specifies
3476 otherwise.  @xref{Execution, ,Recipe Execution}.
3478 @menu
3479 * Recipe Syntax::               Recipe syntax features and pitfalls.
3480 * Echoing::                     How to control when recipes are echoed.
3481 * Execution::                   How recipes are executed.
3482 * Parallel::                    How recipes can be executed in parallel.
3483 * Errors::                      What happens after a recipe execution error.
3484 * Interrupts::                  What happens when a recipe is interrupted.
3485 * Recursion::                   Invoking @code{make} from makefiles.
3486 * Canned Recipes::              Defining canned recipes.
3487 * Empty Recipes::               Defining useful, do-nothing recipes.
3488 @end menu
3490 @node Recipe Syntax, Echoing, Recipes, Recipes
3491 @section Recipe Syntax
3492 @cindex recipe syntax
3493 @cindex syntax of recipe
3495 Makefiles have the unusual property that there are really two distinct
3496 syntaxes in one file.  Most of the makefile uses @code{make} syntax
3497 (@pxref{Makefiles, ,Writing Makefiles}).  However, recipes are meant
3498 to be interpreted by the shell and so they are written using shell
3499 syntax.  The @code{make} program does not try to understand shell
3500 syntax: it performs only a very few specific translations on the
3501 content of the recipe before handing it to the shell.
3503 Each line in the recipe must start with a tab (or the first character
3504 in the value of the @code{.RECIPEPREFIX} variable; @pxref{Special
3505 Variables}), except that the first recipe line may be attached to the
3506 target-and-prerequisites line with a semicolon in between.  @emph{Any}
3507 line in the makefile that begins with a tab and appears in a ``rule
3508 context'' (that is, after a rule has been started until another rule
3509 or variable definition) will be considered part of a recipe for that
3510 rule.  Blank lines and lines of just comments may appear among the
3511 recipe lines; they are ignored.
3513 Some consequences of these rules include:
3515 @itemize @bullet
3516 @item
3517 A blank line that begins with a tab is not blank: it's an empty
3518 recipe (@pxref{Empty Recipes}).
3520 @cindex comments, in recipes
3521 @cindex recipes, comments in
3522 @cindex @code{#} (comments), in recipes
3523 @item
3524 A comment in a recipe is not a @code{make} comment; it will be
3525 passed to the shell as-is.  Whether the shell treats it as a comment
3526 or not depends on your shell.
3528 @item
3529 A variable definition in a ``rule context'' which is indented by a tab
3530 as the first character on the line, will be considered part of a
3531 recipe, not a @code{make} variable definition, and passed to the
3532 shell.
3534 @item
3535 A conditional expression (@code{ifdef}, @code{ifeq},
3536 etc. @pxref{Conditional Syntax, ,Syntax of Conditionals}) in a ``rule
3537 context'' which is indented by a tab as the first character on the
3538 line, will be considered part of a recipe and be passed to the shell.
3540 @end itemize
3542 @menu
3543 * Splitting Recipe Lines::      Breaking long recipe lines for readability.
3544 * Variables in Recipes::        Using @code{make} variables in recipes.
3545 @end menu
3547 @node Splitting Recipe Lines, Variables in Recipes, Recipe Syntax, Recipe Syntax
3548 @subsection Splitting Recipe Lines
3549 @cindex recipes, splitting
3550 @cindex splitting recipes
3551 @cindex recipes, backslash (@code{\}) in
3552 @cindex recipes, quoting newlines in
3553 @cindex backslash (@code{\}), in recipes
3554 @cindex @code{\} (backslash), in recipes
3555 @cindex quoting newline, in recipes
3556 @cindex newline, quoting, in recipes
3558 One of the few ways in which @code{make} does interpret recipes is
3559 checking for a backslash just before the newline.  As in normal
3560 makefile syntax, a single logical recipe line can be split into
3561 multiple physical lines in the makefile by placing a backslash before
3562 each newline.  A sequence of lines like this is considered a single
3563 recipe line, and one instance of the shell will be invoked to run it.
3565 However, in contrast to how they are treated in other places in a
3566 makefile (@pxref{Splitting Lines, , Splitting Long Lines}),
3567 backslash/newline pairs are @emph{not} removed from the recipe.  Both
3568 the backslash and the newline characters are preserved and passed to
3569 the shell.  How the backslash/newline is interpreted depends on your
3570 shell.  If the first character of the next line after the
3571 backslash/newline is the recipe prefix character (a tab by default;
3572 @pxref{Special Variables}), then that character (and only that
3573 character) is removed.  Whitespace is never added to the recipe.
3575 For example, the recipe for the all target in this makefile:
3577 @example
3578 @group
3579 all :
3580         @@echo no\
3581 space
3582         @@echo no\
3583         space
3584         @@echo one \
3585         space
3586         @@echo one\
3587          space
3588 @end group
3589 @end example
3591 @noindent
3592 consists of four separate shell commands where the output is:
3594 @example
3595 @group
3596 nospace
3597 nospace
3598 one space
3599 one space
3600 @end group
3601 @end example
3603 As a more complex example, this makefile:
3605 @example
3606 @group
3607 all : ; @@echo 'hello \
3608         world' ; echo "hello \
3609     world"
3610 @end group
3611 @end example
3613 @noindent
3614 will invoke one shell with a command of:
3616 @example
3617 @group
3618 echo 'hello \
3619 world' ; echo "hello \
3620     world"
3621 @end group
3622 @end example
3624 @noindent
3625 which, according to shell quoting rules, will yield the following output:
3627 @example
3628 @group
3629 hello \
3630 world
3631 hello     world
3632 @end group
3633 @end example
3635 @noindent
3636 Notice how the backslash/newline pair was removed inside the string
3637 quoted with double quotes (@code{"@dots{}"}), but not from the string
3638 quoted with single quotes (@code{'@dots{}'}).  This is the way the
3639 default shell (@file{/bin/sh}) handles backslash/newline pairs.  If
3640 you specify a different shell in your makefiles it may treat them
3641 differently.
3643 Sometimes you want to split a long line inside of single quotes, but
3644 you don't want the backslash/newline to appear in the quoted content.
3645 This is often the case when passing scripts to languages such as Perl,
3646 where extraneous backslashes inside the script can change its meaning
3647 or even be a syntax error.  One simple way of handling this is to
3648 place the quoted string, or even the entire command, into a
3649 @code{make} variable then use the variable in the recipe.  In this
3650 situation the newline quoting rules for makefiles will be used, and
3651 the backslash/newline will be removed.  If we rewrite our example
3652 above using this method:
3654 @example
3655 @group
3656 HELLO = 'hello \
3657 world'
3659 all : ; @@echo $(HELLO)
3660 @end group
3661 @end example
3663 @noindent
3664 we will get output like this:
3666 @example
3667 @group
3668 hello world
3669 @end group
3670 @end example
3672 If you like, you can also use target-specific variables
3673 (@pxref{Target-specific, ,Target-specific Variable Values}) to obtain
3674 a tighter correspondence between the variable and the recipe that
3675 uses it.
3677 @node Variables in Recipes,  , Splitting Recipe Lines, Recipe Syntax
3678 @subsection Using Variables in Recipes
3679 @cindex variable references in recipes
3680 @cindex recipes, using variables in
3682 The other way in which @code{make} processes recipes is by expanding
3683 any variable references in them (@pxref{Reference,Basics of Variable
3684 References}).  This occurs after make has finished reading all the
3685 makefiles and the target is determined to be out of date; so, the
3686 recipes for targets which are not rebuilt are never expanded.
3688 Variable and function references in recipes have identical syntax and
3689 semantics to references elsewhere in the makefile.  They also have the
3690 same quoting rules: if you want a dollar sign to appear in your
3691 recipe, you must double it (@samp{$$}).  For shells like the default
3692 shell, that use dollar signs to introduce variables, it's important to
3693 keep clear in your mind whether the variable you want to reference is
3694 a @code{make} variable (use a single dollar sign) or a shell variable
3695 (use two dollar signs).  For example:
3697 @example
3698 @group
3699 LIST = one two three
3700 all:
3701         for i in $(LIST); do \
3702             echo $$i; \
3703         done
3704 @end group
3705 @end example
3707 @noindent
3708 results in the following command being passed to the shell:
3710 @example
3711 @group
3712 for i in one two three; do \
3713     echo $i; \
3714 done
3715 @end group
3716 @end example
3718 @noindent
3719 which generates the expected result:
3721 @example
3722 @group
3725 three
3726 @end group
3727 @end example
3729 @node Echoing, Execution, Recipe Syntax, Recipes
3730 @section Recipe Echoing
3731 @cindex echoing of recipes
3732 @cindex silent operation
3733 @cindex @code{@@} (in recipes)
3734 @cindex recipes, echoing
3735 @cindex printing of recipes
3737 Normally @code{make} prints each line of the recipe before it is
3738 executed.  We call this @dfn{echoing} because it gives the appearance
3739 that you are typing the lines yourself.
3741 When a line starts with @samp{@@}, the echoing of that line is suppressed.
3742 The @samp{@@} is discarded before the line is passed to the shell.
3743 Typically you would use this for a command whose only effect is to print
3744 something, such as an @code{echo} command to indicate progress through
3745 the makefile:
3747 @example
3748 @@echo About to make distribution files
3749 @end example
3751 @cindex @code{-n}
3752 @cindex @code{--just-print}
3753 @cindex @code{--dry-run}
3754 @cindex @code{--recon}
3755 When @code{make} is given the flag @samp{-n} or @samp{--just-print} it
3756 only echoes most recipes, without executing them.  @xref{Options
3757 Summary, ,Summary of Options}.  In this case even the recipe lines
3758 starting with @samp{@@} are printed.  This flag is useful for finding
3759 out which recipes @code{make} thinks are necessary without actually
3760 doing them.
3762 @cindex @code{-s}
3763 @cindex @code{--silent}
3764 @cindex @code{--quiet}
3765 @findex .SILENT
3766 The @samp{-s} or @samp{--silent}
3767 flag to @code{make} prevents all echoing, as if all recipes
3768 started with @samp{@@}.  A rule in the makefile for the special target
3769 @code{.SILENT} without prerequisites has the same effect
3770 (@pxref{Special Targets, ,Special Built-in Target Names}).
3771 @code{.SILENT} is essentially obsolete since @samp{@@} is more flexible.@refill
3773 @node Execution, Parallel, Echoing, Recipes
3774 @section Recipe Execution
3775 @cindex recipe, execution
3776 @cindex execution, of recipes
3777 @vindex @code{SHELL} @r{(recipe execution)}
3779 When it is time to execute recipes to update a target, they are
3780 executed by invoking a new sub-shell for each line of the recipe,
3781 unless the @code{.ONESHELL} special target is in effect
3782 (@pxref{One Shell, ,Using One Shell})  (In practice, @code{make} may
3783 take shortcuts that do not affect the results.)
3785 @cindex @code{cd} (shell command)
3786 @cindex shell variables, setting in recipes
3787 @cindex recipes setting shell variables
3788 @strong{Please note:} this implies that setting shell variables and
3789 invoking shell commands such as @code{cd} that set a context local to
3790 each process will not affect the following lines in the recipe.@footnote{On
3791 MS-DOS, the value of current working directory is @strong{global}, so
3792 changing it @emph{will} affect the following recipe lines on those
3793 systems.}  If you want to use @code{cd} to affect the next statement,
3794 put both statements in a single recipe line.  Then @code{make} will
3795 invoke one shell to run the entire line, and the shell will execute
3796 the statements in sequence.  For example:
3798 @example
3799 foo : bar/lose
3800         cd $(@@D) && gobble $(@@F) > ../$@@
3801 @end example
3803 @noindent
3804 Here we use the shell AND operator (@code{&&}) so that if the
3805 @code{cd} command fails, the script will fail without trying to invoke
3806 the @code{gobble} command in the wrong directory, which could cause
3807 problems (in this case it would certainly cause @file{../foo} to be
3808 truncated, at least).
3810 @menu
3811 * One Shell::                   One shell for all lines in a recipe.
3812 * Choosing the Shell::          How @code{make} chooses the shell used
3813                                   to run recipes.
3814 @end menu
3816 @node One Shell, Choosing the Shell, Execution, Execution
3817 @subsection Using One Shell
3818 @cindex recipe lines, single shell
3819 @cindex @code{.ONESHELL}, use of
3820 @findex .ONESHELL
3822 Sometimes you would prefer that all the lines in the recipe be passed
3823 to a single invocation of the shell.  There are generally two
3824 situations where this is useful: first, it can improve performance in
3825 makefiles where recipes consist of many command lines, by avoiding
3826 extra processes.  Second, you might want newlines to be included in
3827 your recipe command (for example perhaps you are using a very
3828 different interpreter as your @code{SHELL}).  If the @code{.ONESHELL}
3829 special target appears anywhere in the makefile then @emph{all}
3830 recipe lines for each target will be provided to a single invocation
3831 of the shell.  Newlines between recipe lines will be preserved.  For
3832 example:
3834 @example
3835 .ONESHELL:
3836 foo : bar/lose
3837         cd $(@@D)
3838         gobble $(@@F) > ../$@@
3839 @end example
3841 @noindent
3842 would now work as expected even though the commands are on different
3843 recipe lines.
3845 If @code{.ONESHELL} is provided, then only the first line of the
3846 recipe will be checked for the special prefix characters (@samp{@@},
3847 @samp{-}, and @samp{+}).  Subsequent lines will include the special
3848 characters in the recipe line when the @code{SHELL} is invoked.  If
3849 you want your recipe to start with one of these special characters
3850 you'll need to arrange for them to not be the first characters on the
3851 first line, perhaps by adding a comment or similar.  For example, this
3852 would be a syntax error in Perl because the first @samp{@@} is removed
3853 by make:
3855 @example
3856 .ONESHELL:
3857 SHELL = /usr/bin/perl
3858 .SHELLFLAGS = -e
3859 show :
3860         @@f = qw(a b c);
3861         print "@@f\n";
3862 @end example
3864 @noindent
3865 However, either of these alternatives would work properly:
3867 @example
3868 .ONESHELL:
3869 SHELL = /usr/bin/perl
3870 .SHELLFLAGS = -e
3871 show :
3872         # Make sure "@@" is not the first character on the first line
3873         @@f = qw(a b c);
3874         print "@@f\n";
3875 @end example
3877 @noindent
3880 @example
3881 .ONESHELL:
3882 SHELL = /usr/bin/perl
3883 .SHELLFLAGS = -e
3884 show :
3885         my @@f = qw(a b c);
3886         print "@@f\n";
3887 @end example
3889 As a special feature, if @code{SHELL} is determined to be a
3890 POSIX-style shell, the special prefix characters in ``internal''
3891 recipe lines will @emph{removed} before the recipe is processed.  This
3892 feature is intended to allow existing makefiles to add the
3893 @code{.ONESHELL} special target and still run properly without
3894 extensive modifications.  Since the special prefix characters are not
3895 legal at the beginning of a line in a POSIX shell script this is not a
3896 loss in functionality.  For example, this works as expected:
3898 @example
3899 .ONESHELL:
3900 foo : bar/lose
3901         @@cd $(@@D)
3902         @@gobble $(@@F) > ../$@@
3903 @end example
3905 Even with this special feature, however, makefiles with
3906 @code{.ONESHELL} will behave differently in ways that could be
3907 noticeable.  For example, normally if any line in the recipe fails,
3908 that causes the rule to fail and no more recipe lines are processed.
3909 Under @code{.ONESHELL} a failure of any but the final recipe line will
3910 not be noticed by @code{make}.  You can modify @code{.SHELLFLAGS} to
3911 add the @code{-e} option to the shell which will cause any failure
3912 anywhere in the command line to cause the shell to fail, but this
3913 could itself cause your recipe to behave differently.  Ultimately you
3914 may need to harden your recipe lines to allow them to work with
3915 @code{.ONESHELL}.
3917 @node Choosing the Shell,  , One Shell, Execution
3918 @subsection Choosing the Shell
3919 @cindex shell, choosing the
3920 @cindex @code{SHELL}, value of
3921 @cindex @code{.SHELLFLAGS}, value of
3923 @vindex SHELL
3924 @vindex .SHELLFLAGS
3925 The program used as the shell is taken from the variable @code{SHELL}.
3926 If this variable is not set in your makefile, the program
3927 @file{/bin/sh} is used as the shell.  The argument(s) passed to the
3928 shell are taken from the variable @code{.SHELLFLAGS}.  The default
3929 value of @code{.SHELLFLAGS} is @code{-c} normally, or @code{-ec} in
3930 POSIX-conforming mode.
3932 @cindex environment, @code{SHELL} in
3933 Unlike most variables, the variable @code{SHELL} is never set from the
3934 environment.  This is because the @code{SHELL} environment variable is
3935 used to specify your personal choice of shell program for interactive
3936 use.  It would be very bad for personal choices like this to affect the
3937 functioning of makefiles.  @xref{Environment, ,Variables from the
3938 Environment}.
3940 Furthermore, when you do set @code{SHELL} in your makefile that value
3941 is @emph{not} exported in the environment to recipe lines that
3942 @code{make} invokes.  Instead, the value inherited from the user's
3943 environment, if any, is exported.  You can override this behavior by
3944 explicitly exporting @code{SHELL} (@pxref{Variables/Recursion,
3945 ,Communicating Variables to a Sub-@code{make}}), forcing it to be
3946 passed in the environment to recipe lines.
3948 @vindex @code{MAKESHELL} @r{(MS-DOS alternative to @code{SHELL})}
3949 However, on MS-DOS and MS-Windows the value of @code{SHELL} in the
3950 environment @strong{is} used, since on those systems most users do not
3951 set this variable, and therefore it is most likely set specifically to
3952 be used by @code{make}.  On MS-DOS, if the setting of @code{SHELL} is
3953 not suitable for @code{make}, you can set the variable
3954 @code{MAKESHELL} to the shell that @code{make} should use; if set it
3955 will be used as the shell instead of the value of @code{SHELL}.
3957 @subsubheading Choosing a Shell in DOS and Windows
3958 @cindex shell, in DOS and Windows
3959 @cindex DOS, choosing a shell in
3960 @cindex Windows, choosing a shell in
3962 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3963 other systems.
3965 @vindex COMSPEC
3966 On MS-DOS, if @code{SHELL} is not set, the value of the variable
3967 @code{COMSPEC} (which is always set) is used instead.
3969 @cindex @code{SHELL}, MS-DOS specifics
3970 The processing of lines that set the variable @code{SHELL} in Makefiles
3971 is different on MS-DOS.  The stock shell, @file{command.com}, is
3972 ridiculously limited in its functionality and many users of @code{make}
3973 tend to install a replacement shell.  Therefore, on MS-DOS, @code{make}
3974 examines the value of @code{SHELL}, and changes its behavior based on
3975 whether it points to a Unix-style or DOS-style shell.  This allows
3976 reasonable functionality even if @code{SHELL} points to
3977 @file{command.com}.
3979 If @code{SHELL} points to a Unix-style shell, @code{make} on MS-DOS
3980 additionally checks whether that shell can indeed be found; if not, it
3981 ignores the line that sets @code{SHELL}.  In MS-DOS, GNU @code{make}
3982 searches for the shell in the following places:
3984 @enumerate
3985 @item
3986 In the precise place pointed to by the value of @code{SHELL}.  For
3987 example, if the makefile specifies @samp{SHELL = /bin/sh}, @code{make}
3988 will look in the directory @file{/bin} on the current drive.
3990 @item
3991 In the current directory.
3993 @item
3994 In each of the directories in the @code{PATH} variable, in order.
3996 @end enumerate
3998 In every directory it examines, @code{make} will first look for the
3999 specific file (@file{sh} in the example above).  If this is not found,
4000 it will also look in that directory for that file with one of the known
4001 extensions which identify executable files.  For example @file{.exe},
4002 @file{.com}, @file{.bat}, @file{.btm}, @file{.sh}, and some others.
4004 If any of these attempts is successful, the value of @code{SHELL} will
4005 be set to the full pathname of the shell as found.  However, if none of
4006 these is found, the value of @code{SHELL} will not be changed, and thus
4007 the line that sets it will be effectively ignored.  This is so
4008 @code{make} will only support features specific to a Unix-style shell if
4009 such a shell is actually installed on the system where @code{make} runs.
4011 Note that this extended search for the shell is limited to the cases
4012 where @code{SHELL} is set from the Makefile; if it is set in the
4013 environment or command line, you are expected to set it to the full
4014 pathname of the shell, exactly as things are on Unix.
4016 The effect of the above DOS-specific processing is that a Makefile that
4017 contains @samp{SHELL = /bin/sh} (as many Unix makefiles do), will work
4018 on MS-DOS unaltered if you have e.g.@: @file{sh.exe} installed in some
4019 directory along your @code{PATH}.
4021 @vindex SHELL
4022 @vindex .SHELLFLAGS
4024 @node Parallel, Errors, Execution, Recipes
4025 @section Parallel Execution
4026 @cindex recipes, execution in parallel
4027 @cindex parallel execution
4028 @cindex execution, in parallel
4029 @cindex job slots
4030 @cindex @code{-j}
4031 @cindex @code{--jobs}
4033 GNU @code{make} knows how to execute several recipes at once.
4034 Normally, @code{make} will execute only one recipe at a time, waiting
4035 for it to finish before executing the next.  However, the @samp{-j} or
4036 @samp{--jobs} option tells @code{make} to execute many recipes
4037 simultaneously.  You can inhibit parallelism in a particular makefile
4038 with the @code{.NOTPARALLEL} pseudo-target (@pxref{Special
4039 Targets,Special Built-in Target Names}).@refill
4041 On MS-DOS, the @samp{-j} option has no effect, since that system doesn't
4042 support multi-processing.
4044 If the @samp{-j} option is followed by an integer, this is the number of
4045 recipes to execute at once; this is called the number of @dfn{job slots}.
4046 If there is nothing looking like an integer after the @samp{-j} option,
4047 there is no limit on the number of job slots.  The default number of job
4048 slots is one, which means serial execution (one thing at a time).
4050 One unpleasant consequence of running several recipes simultaneously is
4051 that output generated by the recipes appears whenever each recipe
4052 sends it, so messages from different recipes may be interspersed.
4054 Another problem is that two processes cannot both take input from the
4055 same device; so to make sure that only one recipe tries to take input
4056 from the terminal at once, @code{make} will invalidate the standard
4057 input streams of all but one running recipe.  This means that
4058 attempting to read from standard input will usually be a fatal error (a
4059 @samp{Broken pipe} signal) for most child processes if there are
4060 several.
4061 @cindex broken pipe
4062 @cindex standard input
4064 It is unpredictable which recipe will have a valid standard input stream
4065 (which will come from the terminal, or wherever you redirect the standard
4066 input of @code{make}).  The first recipe run will always get it first, and
4067 the first recipe started after that one finishes will get it next, and so
4070 We will change how this aspect of @code{make} works if we find a better
4071 alternative.  In the mean time, you should not rely on any recipe using
4072 standard input at all if you are using the parallel execution feature; but
4073 if you are not using this feature, then standard input works normally in
4074 all recipes.
4076 Finally, handling recursive @code{make} invocations raises issues.  For
4077 more information on this, see
4078 @ref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
4080 If a recipe fails (is killed by a signal or exits with a nonzero
4081 status), and errors are not ignored for that recipe
4082 (@pxref{Errors, ,Errors in Recipes}),
4083 the remaining recipe lines to remake the same target will not be run.
4084 If a recipe fails and the @samp{-k} or @samp{--keep-going}
4085 option was not given
4086 (@pxref{Options Summary, ,Summary of Options}),
4087 @code{make} aborts execution.  If make
4088 terminates for any reason (including a signal) with child processes
4089 running, it waits for them to finish before actually exiting.@refill
4091 @cindex load average
4092 @cindex limiting jobs based on load
4093 @cindex jobs, limiting based on load
4094 @cindex @code{-l} (load average)
4095 @cindex @code{--max-load}
4096 @cindex @code{--load-average}
4097 When the system is heavily loaded, you will probably want to run fewer jobs
4098 than when it is lightly loaded.  You can use the @samp{-l} option to tell
4099 @code{make} to limit the number of jobs to run at once, based on the load
4100 average.  The @samp{-l} or @samp{--max-load}
4101 option is followed by a floating-point number.  For
4102 example,
4104 @example
4105 -l 2.5
4106 @end example
4108 @noindent
4109 will not let @code{make} start more than one job if the load average is
4110 above 2.5.  The @samp{-l} option with no following number removes the
4111 load limit, if one was given with a previous @samp{-l} option.@refill
4113 More precisely, when @code{make} goes to start up a job, and it already has
4114 at least one job running, it checks the current load average; if it is not
4115 lower than the limit given with @samp{-l}, @code{make} waits until the load
4116 average goes below that limit, or until all the other jobs finish.
4118 By default, there is no load limit.
4120 @node Errors, Interrupts, Parallel, Recipes
4121 @section Errors in Recipes
4122 @cindex errors (in recipes)
4123 @cindex recipes, errors in
4124 @cindex exit status (errors)
4126 After each shell invocation returns, @code{make} looks at its exit
4127 status.  If the shell completed successfully (the exit status is
4128 zero), the next line in the recipe is executed in a new shell; after
4129 the last line is finished, the rule is finished.
4131 If there is an error (the exit status is nonzero), @code{make} gives up on
4132 the current rule, and perhaps on all rules.
4134 Sometimes the failure of a certain recipe line does not indicate a problem.
4135 For example, you may use the @code{mkdir} command to ensure that a
4136 directory exists.  If the directory already exists, @code{mkdir} will
4137 report an error, but you probably want @code{make} to continue regardless.
4139 @cindex @code{-} (in recipes)
4140 To ignore errors in a recipe line, write a @samp{-} at the beginning
4141 of the line's text (after the initial tab).  The @samp{-} is discarded
4142 before the line is passed to the shell for execution.
4144 For example,
4146 @example
4147 @group
4148 clean:
4149         -rm -f *.o
4150 @end group
4151 @end example
4152 @cindex @code{rm} (shell command)
4154 @noindent
4155 This causes @code{make} to continue even if @code{rm} is unable to
4156 remove a file.
4158 @cindex @code{-i}
4159 @cindex @code{--ignore-errors}
4160 @findex .IGNORE
4161 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
4162 flag, errors are ignored in all recipes of all rules.  A rule in the
4163 makefile for the special target @code{.IGNORE} has the same effect, if
4164 there are no prerequisites.  These ways of ignoring errors are obsolete
4165 because @samp{-} is more flexible.
4167 When errors are to be ignored, because of either a @samp{-} or the
4168 @samp{-i} flag, @code{make} treats an error return just like success,
4169 except that it prints out a message that tells you the status code
4170 the shell exited with, and says that the error has been ignored.
4172 When an error happens that @code{make} has not been told to ignore,
4173 it implies that the current target cannot be correctly remade, and neither
4174 can any other that depends on it either directly or indirectly.  No further
4175 recipes will be executed for these targets, since their preconditions
4176 have not been achieved.
4179 @cindex @code{-k}
4180 @cindex @code{--keep-going}
4181 Normally @code{make} gives up immediately in this circumstance, returning a
4182 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
4183 flag is specified, @code{make}
4184 continues to consider the other prerequisites of the pending targets,
4185 remaking them if necessary, before it gives up and returns nonzero status.
4186 For example, after an error in compiling one object file, @samp{make -k}
4187 will continue compiling other object files even though it already knows
4188 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
4190 The usual behavior assumes that your purpose is to get the specified
4191 targets up to date; once @code{make} learns that this is impossible, it
4192 might as well report the failure immediately.  The @samp{-k} option says
4193 that the real purpose is to test as many of the changes made in the
4194 program as possible, perhaps to find several independent problems so
4195 that you can correct them all before the next attempt to compile.  This
4196 is why Emacs' @code{compile} command passes the @samp{-k} flag by
4197 default.
4198 @cindex Emacs (@code{M-x compile})
4200 @findex .DELETE_ON_ERROR
4201 @cindex deletion of target files
4202 @cindex removal of target files
4203 @cindex target, deleting on error
4204 Usually when a recipe line fails, if it has changed the target file at all,
4205 the file is corrupted and cannot be used---or at least it is not
4206 completely updated.  Yet the file's time stamp says that it is now up to
4207 date, so the next time @code{make} runs, it will not try to update that
4208 file.  The situation is just the same as when the shell is killed by a
4209 signal; @pxref{Interrupts}.  So generally the right thing to do is to
4210 delete the target file if the recipe fails after beginning to change
4211 the file.  @code{make} will do this if @code{.DELETE_ON_ERROR} appears
4212 as a target.  This is almost always what you want @code{make} to do, but
4213 it is not historical practice; so for compatibility, you must explicitly
4214 request it.
4216 @node Interrupts, Recursion, Errors, Recipes
4217 @section Interrupting or Killing @code{make}
4218 @cindex interrupt
4219 @cindex signal
4220 @cindex deletion of target files
4221 @cindex removal of target files
4222 @cindex target, deleting on interrupt
4223 @cindex killing (interruption)
4225 If @code{make} gets a fatal signal while a shell is executing, it may
4226 delete the target file that the recipe was supposed to update.  This is
4227 done if the target file's last-modification time has changed since
4228 @code{make} first checked it.
4230 The purpose of deleting the target is to make sure that it is remade from
4231 scratch when @code{make} is next run.  Why is this?  Suppose you type
4232 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
4233 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
4234 in an incomplete file whose last-modification time is newer than the source
4235 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
4236 and deletes this incomplete file.  If @code{make} did not do this, the next
4237 invocation of @code{make} would think that @file{foo.o} did not require
4238 updating---resulting in a strange error message from the linker when it
4239 tries to link an object file half of which is missing.
4241 @findex .PRECIOUS
4242 You can prevent the deletion of a target file in this way by making the
4243 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
4244 @code{make} checks to see whether it appears on the prerequisites of
4245 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
4246 if a signal happens.  Some reasons why you might do this are that the
4247 target is updated in some atomic fashion, or exists only to record a
4248 modification-time (its contents do not matter), or must exist at all
4249 times to prevent other sorts of trouble.
4251 @node Recursion, Canned Recipes, Interrupts, Recipes
4252 @section Recursive Use of @code{make}
4253 @cindex recursion
4254 @cindex subdirectories, recursion for
4256 Recursive use of @code{make} means using @code{make} as a command in a
4257 makefile.  This technique is useful when you want separate makefiles for
4258 various subsystems that compose a larger system.  For example, suppose you
4259 have a sub-directory @file{subdir} which has its own makefile, and you would
4260 like the containing directory's makefile to run @code{make} on the
4261 sub-directory.  You can do it by writing this:
4263 @example
4264 subsystem:
4265         cd subdir && $(MAKE)
4266 @end example
4268 @noindent
4269 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
4271 @example
4272 subsystem:
4273         $(MAKE) -C subdir
4274 @end example
4275 @cindex @code{-C}
4276 @cindex @code{--directory}
4278 You can write recursive @code{make} commands just by copying this example,
4279 but there are many things to know about how they work and why, and about
4280 how the sub-@code{make} relates to the top-level @code{make}.  You may
4281 also find it useful to declare targets that invoke recursive
4282 @code{make} commands as @samp{.PHONY} (for more discussion on when
4283 this is useful, see @ref{Phony Targets}).
4285 @vindex @code{CURDIR}
4286 For your convenience, when GNU @code{make} starts (after it has
4287 processed any @code{-C} options) it sets the variable @code{CURDIR} to
4288 the pathname of the current working directory.  This value is never
4289 touched by @code{make} again: in particular note that if you include
4290 files from other directories the value of @code{CURDIR} does not
4291 change.  The value has the same precedence it would have if it were
4292 set in the makefile (by default, an environment variable @code{CURDIR}
4293 will not override this value).  Note that setting this variable has no
4294 impact on the operation of @code{make} (it does not cause @code{make}
4295 to change its working directory, for example).
4297 @menu
4298 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
4299 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
4300 * Options/Recursion::           How to communicate options to a sub-@code{make}.
4301 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
4302                                   helps debug use of recursive @code{make} commands.
4303 @end menu
4305 @node MAKE Variable, Variables/Recursion, Recursion, Recursion
4306 @subsection How the @code{MAKE} Variable Works
4307 @vindex MAKE
4308 @cindex recursion, and @code{MAKE} variable
4310 Recursive @code{make} commands should always use the variable @code{MAKE},
4311 not the explicit command name @samp{make}, as shown here:
4313 @example
4314 @group
4315 subsystem:
4316         cd subdir && $(MAKE)
4317 @end group
4318 @end example
4320 The value of this variable is the file name with which @code{make} was
4321 invoked.  If this file name was @file{/bin/make}, then the recipe executed
4322 is @samp{cd subdir && /bin/make}.  If you use a special version of
4323 @code{make} to run the top-level makefile, the same special version will be
4324 executed for recursive invocations.
4325 @cindex @code{cd} (shell command)
4327 @cindex +, and recipes
4328 As a special feature, using the variable @code{MAKE} in the recipe of
4329 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
4330 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
4331 Using the @code{MAKE} variable has the same effect as using a @samp{+}
4332 character at the beginning of the recipe line.  @xref{Instead of
4333 Execution, ,Instead of Executing the Recipes}.  This special feature
4334 is only enabled if the @code{MAKE} variable appears directly in the
4335 recipe: it does not apply if the @code{MAKE} variable is referenced
4336 through expansion of another variable.  In the latter case you must
4337 use the @samp{+} token to get these special effects.@refill
4339 Consider the command @samp{make -t} in the above example.  (The
4340 @samp{-t} option marks targets as up to date without actually running
4341 any recipes; see @ref{Instead of Execution}.)  Following the usual
4342 definition of @samp{-t}, a @samp{make -t} command in the example would
4343 create a file named @file{subsystem} and do nothing else.  What you
4344 really want it to do is run @samp{@w{cd subdir &&} @w{make -t}}; but
4345 that would require executing the recipe, and @samp{-t} says not to
4346 execute recipes.@refill
4347 @cindex @code{-t}, and recursion
4348 @cindex recursion, and @code{-t}
4349 @cindex @code{--touch}, and recursion
4351 The special feature makes this do what you want: whenever a recipe
4352 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
4353 @samp{-n} and @samp{-q} do not apply to that line.  Recipe lines
4354 containing @code{MAKE} are executed normally despite the presence of a
4355 flag that causes most recipes not to be run.  The usual
4356 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
4357 (@pxref{Options/Recursion, ,Communicating Options to a
4358 Sub-@code{make}}), so your request to touch the files, or print the
4359 recipes, is propagated to the subsystem.@refill
4361 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
4362 @subsection Communicating Variables to a Sub-@code{make}
4363 @cindex sub-@code{make}
4364 @cindex environment, and recursion
4365 @cindex exporting variables
4366 @cindex variables, environment
4367 @cindex variables, exporting
4368 @cindex recursion, and environment
4369 @cindex recursion, and variables
4371 Variable values of the top-level @code{make} can be passed to the
4372 sub-@code{make} through the environment by explicit request.  These
4373 variables are defined in the sub-@code{make} as defaults, but they do
4374 not override variables defined in the makefile used by
4375 the sub-@code{make} unless you use the @samp{-e} switch (@pxref{Options
4376 Summary, ,Summary of Options}).@refill
4378 To pass down, or @dfn{export}, a variable, @code{make} adds the
4379 variable and its value to the environment for running each line of the
4380 recipe.  The sub-@code{make}, in turn, uses the environment to
4381 initialize its table of variable values.  @xref{Environment,
4382 ,Variables from the Environment}.
4384 Except by explicit request, @code{make} exports a variable only if it
4385 is either defined in the environment initially or set on the command
4386 line, and if its name consists only of letters, numbers, and underscores.
4387 Some shells cannot cope with environment variable names consisting of
4388 characters other than letters, numbers, and underscores.
4390 @cindex SHELL, exported value
4391 The value of the @code{make} variable @code{SHELL} is not exported.
4392 Instead, the value of the @code{SHELL} variable from the invoking
4393 environment is passed to the sub-@code{make}.  You can force
4394 @code{make} to export its value for @code{SHELL} by using the
4395 @code{export} directive, described below.  @xref{Choosing the Shell}.
4397 The special variable @code{MAKEFLAGS} is always exported (unless you
4398 unexport it).  @code{MAKEFILES} is exported if you set it to anything.
4400 @code{make} automatically passes down variable values that were defined
4401 on the command line, by putting them in the @code{MAKEFLAGS} variable.
4402 @iftex
4403 See the next section.
4404 @end iftex
4405 @ifnottex
4406 @xref{Options/Recursion}.
4407 @end ifnottex
4409 Variables are @emph{not} normally passed down if they were created by
4410 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
4411 Implicit Rules}).  The sub-@code{make} will define these for
4412 itself.@refill
4414 @findex export
4415 If you want to export specific variables to a sub-@code{make}, use the
4416 @code{export} directive, like this:
4418 @example
4419 export @var{variable} @dots{}
4420 @end example
4422 @noindent
4423 @findex unexport
4424 If you want to @emph{prevent} a variable from being exported, use the
4425 @code{unexport} directive, like this:
4427 @example
4428 unexport @var{variable} @dots{}
4429 @end example
4431 @noindent
4432 In both of these forms, the arguments to @code{export} and
4433 @code{unexport} are expanded, and so could be variables or functions
4434 which expand to a (list of) variable names to be (un)exported.
4436 As a convenience, you can define a variable and export it at the same
4437 time by doing:
4439 @example
4440 export @var{variable} = value
4441 @end example
4443 @noindent
4444 has the same result as:
4446 @example
4447 @var{variable} = value
4448 export @var{variable}
4449 @end example
4451 @noindent
4454 @example
4455 export @var{variable} := value
4456 @end example
4458 @noindent
4459 has the same result as:
4461 @example
4462 @var{variable} := value
4463 export @var{variable}
4464 @end example
4466 Likewise,
4468 @example
4469 export @var{variable} += value
4470 @end example
4472 @noindent
4473 is just like:
4475 @example
4476 @var{variable} += value
4477 export @var{variable}
4478 @end example
4480 @noindent
4481 @xref{Appending, ,Appending More Text to Variables}.
4483 You may notice that the @code{export} and @code{unexport} directives
4484 work in @code{make} in the same way they work in the shell, @code{sh}.
4486 If you want all variables to be exported by default, you can use
4487 @code{export} by itself:
4489 @example
4490 export
4491 @end example
4493 @noindent
4494 This tells @code{make} that variables which are not explicitly mentioned
4495 in an @code{export} or @code{unexport} directive should be exported.
4496 Any variable given in an @code{unexport} directive will still @emph{not}
4497 be exported.  If you use @code{export} by itself to export variables by
4498 default, variables whose names contain characters other than
4499 alphanumerics and underscores will not be exported unless specifically
4500 mentioned in an @code{export} directive.@refill
4502 @findex .EXPORT_ALL_VARIABLES
4503 The behavior elicited by an @code{export} directive by itself was the
4504 default in older versions of GNU @code{make}.  If your makefiles depend
4505 on this behavior and you want to be compatible with old versions of
4506 @code{make}, you can write a rule for the special target
4507 @code{.EXPORT_ALL_VARIABLES} instead of using the @code{export} directive.
4508 This will be ignored by old @code{make}s, while the @code{export}
4509 directive will cause a syntax error.@refill
4510 @cindex compatibility in exporting
4512 Likewise, you can use @code{unexport} by itself to tell @code{make}
4513 @emph{not} to export variables by default.  Since this is the default
4514 behavior, you would only need to do this if @code{export} had been used
4515 by itself earlier (in an included makefile, perhaps).  You
4516 @strong{cannot} use @code{export} and @code{unexport} by themselves to
4517 have variables exported for some recipes and not for others.  The last
4518 @code{export} or @code{unexport} directive that appears by itself
4519 determines the behavior for the entire run of @code{make}.@refill
4521 @vindex MAKELEVEL
4522 @cindex recursion, level of
4523 As a special feature, the variable @code{MAKELEVEL} is changed when it
4524 is passed down from level to level.  This variable's value is a string
4525 which is the depth of the level as a decimal number.  The value is
4526 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
4527 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
4528 happens when @code{make} sets up the environment for a recipe.@refill
4530 The main use of @code{MAKELEVEL} is to test it in a conditional
4531 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
4532 way you can write a makefile that behaves one way if run recursively and
4533 another way if run directly by you.@refill
4535 @vindex MAKEFILES
4536 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
4537 commands to use additional makefiles.  The value of @code{MAKEFILES} is
4538 a whitespace-separated list of file names.  This variable, if defined in
4539 the outer-level makefile, is passed down through the environment; then
4540 it serves as a list of extra makefiles for the sub-@code{make} to read
4541 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
4542 Variable @code{MAKEFILES}}.@refill
4544 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
4545 @subsection Communicating Options to a Sub-@code{make}
4546 @cindex options, and recursion
4547 @cindex recursion, and options
4549 @vindex MAKEFLAGS
4550 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
4551 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
4552 set up automatically by @code{make} to contain the flag letters that
4553 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
4554 @code{MAKEFLAGS} gets the value @samp{ks}.@refill
4556 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
4557 in its environment.  In response, it takes the flags from that value and
4558 processes them as if they had been given as arguments.
4559 @xref{Options Summary, ,Summary of Options}.
4561 @cindex command line variable definitions, and recursion
4562 @cindex variables, command line, and recursion
4563 @cindex recursion, and command line variable definitions
4564 Likewise variables defined on the command line are passed to the
4565 sub-@code{make} through @code{MAKEFLAGS}.  Words in the value of
4566 @code{MAKEFLAGS} that contain @samp{=}, @code{make} treats as variable
4567 definitions just as if they appeared on the command line.
4568 @xref{Overriding, ,Overriding Variables}.
4570 @cindex @code{-C}, and recursion
4571 @cindex @code{-f}, and recursion
4572 @cindex @code{-o}, and recursion
4573 @cindex @code{-W}, and recursion
4574 @cindex @code{--directory}, and recursion
4575 @cindex @code{--file}, and recursion
4576 @cindex @code{--old-file}, and recursion
4577 @cindex @code{--assume-old}, and recursion
4578 @cindex @code{--assume-new}, and recursion
4579 @cindex @code{--new-file}, and recursion
4580 @cindex recursion, and @code{-C}
4581 @cindex recursion, and @code{-f}
4582 @cindex recursion, and @code{-o}
4583 @cindex recursion, and @code{-W}
4584 The options @samp{-C}, @samp{-f}, @samp{-o}, and @samp{-W} are not put
4585 into @code{MAKEFLAGS}; these options are not passed down.@refill
4587 @cindex @code{-j}, and recursion
4588 @cindex @code{--jobs}, and recursion
4589 @cindex recursion, and @code{-j}
4590 @cindex job slots, and recursion
4591 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
4592 If you set it to some numeric value @samp{N} and your operating system
4593 supports it (most any UNIX system will; others typically won't), the
4594 parent @code{make} and all the sub-@code{make}s will communicate to
4595 ensure that there are only @samp{N} jobs running at the same time
4596 between them all.  Note that any job that is marked recursive
4597 (@pxref{Instead of Execution, ,Instead of Executing Recipes})
4598 doesn't count against the total jobs (otherwise we could get @samp{N}
4599 sub-@code{make}s running and have no slots left over for any real work!)
4601 If your operating system doesn't support the above communication, then
4602 @samp{-j 1} is always put into @code{MAKEFLAGS} instead of the value you
4603 specified.  This is because if the @w{@samp{-j}} option were passed down
4604 to sub-@code{make}s, you would get many more jobs running in parallel
4605 than you asked for.  If you give @samp{-j} with no numeric argument,
4606 meaning to run as many jobs as possible in parallel, this is passed
4607 down, since multiple infinities are no more than one.@refill
4609 If you do not want to pass the other flags down, you must change the
4610 value of @code{MAKEFLAGS}, like this:
4612 @example
4613 subsystem:
4614         cd subdir && $(MAKE) MAKEFLAGS=
4615 @end example
4617 @vindex MAKEOVERRIDES
4618 The command line variable definitions really appear in the variable
4619 @code{MAKEOVERRIDES}, and @code{MAKEFLAGS} contains a reference to this
4620 variable.  If you do want to pass flags down normally, but don't want to
4621 pass down the command line variable definitions, you can reset
4622 @code{MAKEOVERRIDES} to empty, like this:
4624 @example
4625 MAKEOVERRIDES =
4626 @end example
4628 @noindent
4629 @cindex Arg list too long
4630 @cindex E2BIG
4631 This is not usually useful to do.  However, some systems have a small
4632 fixed limit on the size of the environment, and putting so much
4633 information into the value of @code{MAKEFLAGS} can exceed it.  If you
4634 see the error message @samp{Arg list too long}, this may be the problem.
4635 @findex .POSIX
4636 @cindex POSIX
4637 (For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
4638 not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
4639 in the makefile.  You probably do not care about this.)
4641 @vindex MFLAGS
4642 A similar variable @code{MFLAGS} exists also, for historical
4643 compatibility.  It has the same value as @code{MAKEFLAGS} except that it
4644 does not contain the command line variable definitions, and it always
4645 begins with a hyphen unless it is empty (@code{MAKEFLAGS} begins with a
4646 hyphen only when it begins with an option that has no single-letter
4647 version, such as @samp{--warn-undefined-variables}).  @code{MFLAGS} was
4648 traditionally used explicitly in the recursive @code{make} command, like
4649 this:
4651 @example
4652 subsystem:
4653         cd subdir && $(MAKE) $(MFLAGS)
4654 @end example
4656 @noindent
4657 but now @code{MAKEFLAGS} makes this usage redundant.  If you want your
4658 makefiles to be compatible with old @code{make} programs, use this
4659 technique; it will work fine with more modern @code{make} versions too.
4661 @cindex setting options from environment
4662 @cindex options, setting from environment
4663 @cindex setting options in makefiles
4664 @cindex options, setting in makefiles
4665 The @code{MAKEFLAGS} variable can also be useful if you want to have
4666 certain options, such as @samp{-k} (@pxref{Options Summary, ,Summary of
4667 Options}), set each time you run @code{make}.  You simply put a value for
4668 @code{MAKEFLAGS} in your environment.  You can also set @code{MAKEFLAGS} in
4669 a makefile, to specify additional flags that should also be in effect for
4670 that makefile.  (Note that you cannot use @code{MFLAGS} this way.  That
4671 variable is set only for compatibility; @code{make} does not interpret a
4672 value you set for it in any way.)
4674 When @code{make} interprets the value of @code{MAKEFLAGS} (either from the
4675 environment or from a makefile), it first prepends a hyphen if the value
4676 does not already begin with one.  Then it chops the value into words
4677 separated by blanks, and parses these words as if they were options given
4678 on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
4679 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
4680 is no error for an invalid option).
4682 If you do put @code{MAKEFLAGS} in your environment, you should be sure not
4683 to include any options that will drastically affect the actions of
4684 @code{make} and undermine the purpose of makefiles and of @code{make}
4685 itself.  For instance, the @samp{-t}, @samp{-n}, and @samp{-q} options, if
4686 put in one of these variables, could have disastrous consequences and would
4687 certainly have at least surprising and probably annoying effects.@refill
4689 @node -w Option,  , Options/Recursion, Recursion
4690 @subsection The @samp{--print-directory} Option
4691 @cindex directories, printing them
4692 @cindex printing directories
4693 @cindex recursion, and printing directories
4695 If you use several levels of recursive @code{make} invocations, the
4696 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
4697 lot easier to understand by showing each directory as @code{make}
4698 starts processing it and as @code{make} finishes processing it.  For
4699 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
4700 @code{make} will print a line of the form:@refill
4702 @example
4703 make: Entering directory `/u/gnu/make'.
4704 @end example
4706 @noindent
4707 before doing anything else, and a line of the form:
4709 @example
4710 make: Leaving directory `/u/gnu/make'.
4711 @end example
4713 @noindent
4714 when processing is completed.
4716 @cindex @code{-C}, and @code{-w}
4717 @cindex @code{--directory}, and @code{--print-directory}
4718 @cindex recursion, and @code{-w}
4719 @cindex @code{-w}, and @code{-C}
4720 @cindex @code{-w}, and recursion
4721 @cindex @code{--print-directory}, and @code{--directory}
4722 @cindex @code{--print-directory}, and recursion
4723 @cindex @code{--no-print-directory}
4724 @cindex @code{--print-directory}, disabling
4725 @cindex @code{-w}, disabling
4726 Normally, you do not need to specify this option because @samp{make}
4727 does it for you: @samp{-w} is turned on automatically when you use the
4728 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
4729 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
4730 be silent, or if you use @samp{--no-print-directory} to explicitly
4731 disable it.
4733 @node Canned Recipes, Empty Recipes, Recursion, Recipes
4734 @section Defining Canned Recipes
4735 @cindex canned recipes
4736 @cindex recipes, canned
4737 @cindex sequences of commands
4738 @cindex commands, sequences of
4740 When the same sequence of commands is useful in making various
4741 targets, you can define it as a canned sequence with the @code{define}
4742 directive, and refer to the canned sequence from the recipes for those
4743 targets.  The canned sequence is actually a variable, so the name must
4744 not conflict with other variable names.
4746 Here is an example of defining a canned recipe:
4748 @example
4749 define run-yacc =
4750 yacc $(firstword $^)
4751 mv y.tab.c $@@
4752 endef
4753 @end example
4754 @cindex @code{yacc}
4756 @noindent
4757 Here @code{run-yacc} is the name of the variable being defined;
4758 @code{endef} marks the end of the definition; the lines in between are the
4759 commands.  The @code{define} directive does not expand variable references
4760 and function calls in the canned sequence; the @samp{$} characters,
4761 parentheses, variable names, and so on, all become part of the value of the
4762 variable you are defining.
4763 @xref{Multi-Line, ,Defining Multi-Line Variables},
4764 for a complete explanation of @code{define}.
4766 The first command in this example runs Yacc on the first prerequisite of
4767 whichever rule uses the canned sequence.  The output file from Yacc is
4768 always named @file{y.tab.c}.  The second command moves the output to the
4769 rule's target file name.
4771 To use the canned sequence, substitute the variable into the recipe of a
4772 rule.  You can substitute it like any other variable
4773 (@pxref{Reference, ,Basics of Variable References}).
4774 Because variables defined by @code{define} are recursively expanded
4775 variables, all the variable references you wrote inside the @code{define}
4776 are expanded now.  For example:
4778 @example
4779 foo.c : foo.y
4780         $(run-yacc)
4781 @end example
4783 @noindent
4784 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
4785 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.@refill
4787 This is a realistic example, but this particular one is not needed in
4788 practice because @code{make} has an implicit rule to figure out these
4789 commands based on the file names involved
4790 (@pxref{Implicit Rules, ,Using Implicit Rules}).
4792 @cindex @@, and @code{define}
4793 @cindex -, and @code{define}
4794 @cindex +, and @code{define}
4795 In recipe execution, each line of a canned sequence is treated just as
4796 if the line appeared on its own in the rule, preceded by a tab.  In
4797 particular, @code{make} invokes a separate sub-shell for each line.  You
4798 can use the special prefix characters that affect command lines
4799 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
4800 @xref{Recipes, ,Writing Recipes in Rules}.
4801 For example, using this canned sequence:
4803 @example
4804 define frobnicate =
4805 @@echo "frobnicating target $@@"
4806 frob-step-1 $< -o $@@-step-1
4807 frob-step-2 $@@-step-1 -o $@@
4808 endef
4809 @end example
4811 @noindent
4812 @code{make} will not echo the first line, the @code{echo} command.
4813 But it @emph{will} echo the following two recipe lines.
4815 On the other hand, prefix characters on the recipe line that refers to
4816 a canned sequence apply to every line in the sequence.  So the rule:
4818 @example
4819 frob.out: frob.in
4820         @@$(frobnicate)
4821 @end example
4823 @noindent
4824 does not echo @emph{any} recipe lines.
4825 (@xref{Echoing, ,Recipe Echoing}, for a full explanation of @samp{@@}.)
4827 @node Empty Recipes,  , Canned Recipes, Recipes
4828 @section Using Empty Recipes
4829 @cindex empty recipes
4830 @cindex recipes, empty
4832 It is sometimes useful to define recipes which do nothing.  This is done
4833 simply by giving a recipe that consists of nothing but whitespace.  For
4834 example:
4836 @example
4837 target: ;
4838 @end example
4840 @noindent
4841 defines an empty recipe for @file{target}.  You could also use a line
4842 beginning with a recipe prefix character to define an empty recipe,
4843 but this would be confusing because such a line looks empty.
4845 @findex .DEFAULT@r{, and empty recipes}
4846 You may be wondering why you would want to define a recipe that
4847 does nothing.  The only reason this is useful is to prevent a target
4848 from getting implicit recipes (from implicit rules or the
4849 @code{.DEFAULT} special target; @pxref{Implicit Rules} and
4850 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
4852 @c !!! another reason is for canonical stamp files:
4853 @ignore
4854 @example
4855 foo: stamp-foo ;
4856 stamp-foo: foo.in
4857         create foo frm foo.in
4858         touch $@
4859 @end example
4860 @end ignore
4862 You may be inclined to define empty recipes for targets that are
4863 not actual files, but only exist so that their prerequisites can be
4864 remade.  However, this is not the best way to do that, because the
4865 prerequisites may not be remade properly if the target file actually does exist.
4866 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
4868 @node Using Variables, Conditionals, Recipes, Top
4869 @chapter How to Use Variables
4870 @cindex variable
4871 @cindex value
4872 @cindex recursive variable expansion
4873 @cindex simple variable expansion
4875 A @dfn{variable} is a name defined in a makefile to represent a string
4876 of text, called the variable's @dfn{value}.  These values are
4877 substituted by explicit request into targets, prerequisites, recipes,
4878 and other parts of the makefile.  (In some other versions of @code{make},
4879 variables are called @dfn{macros}.)
4880 @cindex macro
4882 Variables and functions in all parts of a makefile are expanded when
4883 read, except for in recipes, the right-hand sides of variable
4884 definitions using @samp{=}, and the bodies of variable definitions
4885 using the @code{define} directive.@refill
4887 Variables can represent lists of file names, options to pass to compilers,
4888 programs to run, directories to look in for source files, directories to
4889 write output in, or anything else you can imagine.
4891 A variable name may be any sequence of characters not containing
4892 @samp{:}, @samp{#}, @samp{=}, or whitespace.  However, variable names
4893 containing characters other than letters, numbers, and underscores
4894 should be considered carefully, as in some shells they cannot be
4895 passed through the environment to a sub-@code{make}
4896 (@pxref{Variables/Recursion, ,Communicating Variables to a
4897 Sub-@code{make}}).  Variable names beginning with @samp{.} and an
4898 uppercase letter may be given special meaning in future versions of
4899 @code{make}.
4901 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
4902 and @samp{Foo} all refer to different variables.
4904 It is traditional to use upper case letters in variable names, but we
4905 recommend using lower case letters for variable names that serve internal
4906 purposes in the makefile, and reserving upper case for parameters that
4907 control implicit rules or for parameters that the user should override with
4908 command options (@pxref{Overriding, ,Overriding Variables}).
4910 A few variables have names that are a single punctuation character or
4911 just a few characters.  These are the @dfn{automatic variables}, and
4912 they have particular specialized uses.  @xref{Automatic Variables}.
4914 @menu
4915 * Reference::                   How to use the value of a variable.
4916 * Flavors::                     Variables come in two flavors.
4917 * Advanced::                    Advanced features for referencing a variable.
4918 * Values::                      All the ways variables get their values.
4919 * Setting::                     How to set a variable in the makefile.
4920 * Appending::                   How to append more text to the old value
4921                                   of a variable.
4922 * Override Directive::          How to set a variable in the makefile even if
4923                                   the user has set it with a command argument.
4924 * Multi-Line::                  An alternate way to set a variable
4925                                   to a multi-line string.
4926 * Undefine Directive::          How to undefine a variable so that it appears
4927                                   as if it was never set.
4928 * Environment::                 Variable values can come from the environment.
4929 * Target-specific::             Variable values can be defined on a per-target
4930                                   basis.
4931 * Pattern-specific::            Target-specific variable values can be applied
4932                                   to a group of targets that match a pattern.
4933 * Suppressing Inheritance::     Suppress inheritance of variables.
4934 * Special Variables::           Variables with special meaning or behavior.
4935 @end menu
4937 @node Reference, Flavors, Using Variables, Using Variables
4938 @section Basics of Variable References
4939 @cindex variables, how to reference
4940 @cindex reference to variables
4941 @cindex @code{$}, in variable reference
4942 @cindex dollar sign (@code{$}), in variable reference
4944 To substitute a variable's value, write a dollar sign followed by the name
4945 of the variable in parentheses or braces: either @samp{$(foo)} or
4946 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
4947 special significance of @samp{$} is why you must write @samp{$$} to have
4948 the effect of a single dollar sign in a file name or recipe.
4950 Variable references can be used in any context: targets, prerequisites,
4951 recipes, most directives, and new variable values.  Here is an
4952 example of a common case, where a variable holds the names of all the
4953 object files in a program:
4955 @example
4956 @group
4957 objects = program.o foo.o utils.o
4958 program : $(objects)
4959         cc -o program $(objects)
4961 $(objects) : defs.h
4962 @end group
4963 @end example
4965 Variable references work by strict textual substitution.  Thus, the rule
4967 @example
4968 @group
4969 foo = c
4970 prog.o : prog.$(foo)
4971         $(foo)$(foo) -$(foo) prog.$(foo)
4972 @end group
4973 @end example
4975 @noindent
4976 could be used to compile a C program @file{prog.c}.  Since spaces before
4977 the variable value are ignored in variable assignments, the value of
4978 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
4979 this way!)
4981 A dollar sign followed by a character other than a dollar sign,
4982 open-parenthesis or open-brace treats that single character as the
4983 variable name.  Thus, you could reference the variable @code{x} with
4984 @samp{$x}.  However, this practice is strongly discouraged, except in
4985 the case of the automatic variables (@pxref{Automatic Variables}).
4987 @node Flavors, Advanced, Reference, Using Variables
4988 @section The Two Flavors of Variables
4989 @cindex flavors of variables
4990 @cindex recursive variable expansion
4991 @cindex variables, flavors
4992 @cindex recursively expanded variables
4993 @cindex variables, recursively expanded
4995 There are two ways that a variable in GNU @code{make} can have a value;
4996 we call them the two @dfn{flavors} of variables.  The two flavors are
4997 distinguished in how they are defined and in what they do when expanded.
4999 @cindex =
5000 The first flavor of variable is a @dfn{recursively expanded} variable.
5001 Variables of this sort are defined by lines using @samp{=}
5002 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
5003 (@pxref{Multi-Line, ,Defining Multi-Line Variables}).  The value you specify
5004 is installed verbatim; if it contains references to other variables,
5005 these references are expanded whenever this variable is substituted (in
5006 the course of expanding some other string).  When this happens, it is
5007 called @dfn{recursive expansion}.@refill
5009 For example,
5011 @example
5012 foo = $(bar)
5013 bar = $(ugh)
5014 ugh = Huh?
5016 all:;echo $(foo)
5017 @end example
5019 @noindent
5020 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
5021 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
5023 This flavor of variable is the only sort supported by most other
5024 versions of @code{make}.  It has its advantages and its disadvantages.
5025 An advantage (most would say) is that:
5027 @example
5028 CFLAGS = $(include_dirs) -O
5029 include_dirs = -Ifoo -Ibar
5030 @end example
5032 @noindent
5033 will do what was intended: when @samp{CFLAGS} is expanded in a recipe,
5034 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
5035 cannot append something on the end of a variable, as in
5037 @example
5038 CFLAGS = $(CFLAGS) -O
5039 @end example
5041 @noindent
5042 because it will cause an infinite loop in the variable expansion.
5043 (Actually @code{make} detects the infinite loop and reports an error.)
5044 @cindex loops in variable expansion
5045 @cindex variables, loops in expansion
5047 Another disadvantage is that any functions
5048 (@pxref{Functions, ,Functions for Transforming Text})
5049 referenced in the definition will be executed every time the variable is
5050 expanded.  This makes @code{make} run slower; worse, it causes the
5051 @code{wildcard} and @code{shell} functions to give unpredictable results
5052 because you cannot easily control when they are called, or even how many
5053 times.
5055 To avoid all the problems and inconveniences of recursively expanded
5056 variables, there is another flavor: simply expanded variables.
5058 @cindex simply expanded variables
5059 @cindex variables, simply expanded
5060 @cindex :=
5061 @cindex ::=
5062 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
5063 or @samp{::=} (@pxref{Setting, ,Setting Variables}).  Both forms are
5064 equivalent in GNU @code{make}; however only the @samp{::=} form is
5065 described by the POSIX standard (support for @samp{::=} was added to
5066 the POSIX standard in 2012, so older versions of @code{make} won't
5067 accept this form either).
5069 The value of a simply expanded variable is scanned
5070 once and for all, expanding any references to other variables and
5071 functions, when the variable is defined.  The actual value of the simply
5072 expanded variable is the result of expanding the text that you write.
5073 It does not contain any references to other variables; it contains their
5074 values @emph{as of the time this variable was defined}.  Therefore,
5076 @example
5077 x := foo
5078 y := $(x) bar
5079 x := later
5080 @end example
5082 @noindent
5083 is equivalent to
5085 @example
5086 y := foo bar
5087 x := later
5088 @end example
5090 When a simply expanded variable is referenced, its value is substituted
5091 verbatim.
5093 Here is a somewhat more complicated example, illustrating the use of
5094 @samp{:=} in conjunction with the @code{shell} function.
5095 (@xref{Shell Function, , The @code{shell} Function}.)  This example
5096 also shows use of the variable @code{MAKELEVEL}, which is changed
5097 when it is passed down from level to level.
5098 (@xref{Variables/Recursion, , Communicating Variables to a
5099 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
5101 @vindex MAKELEVEL
5102 @vindex MAKE
5103 @example
5104 @group
5105 ifeq (0,$@{MAKELEVEL@})
5106 whoami    := $(shell whoami)
5107 host-type := $(shell arch)
5108 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
5109 endif
5110 @end group
5111 @end example
5113 @noindent
5114 An advantage of this use of @samp{:=} is that a typical
5115 `descend into a directory' recipe then looks like this:
5117 @example
5118 @group
5119 $@{subdirs@}:
5120         $@{MAKE@} -C $@@ all
5121 @end group
5122 @end example
5124 Simply expanded variables generally make complicated makefile programming
5125 more predictable because they work like variables in most programming
5126 languages.  They allow you to redefine a variable using its own value (or
5127 its value processed in some way by one of the expansion functions) and to
5128 use the expansion functions much more efficiently
5129 (@pxref{Functions, ,Functions for Transforming Text}).
5131 @cindex spaces, in variable values
5132 @cindex whitespace, in variable values
5133 @cindex variables, spaces in values
5134 You can also use them to introduce controlled leading whitespace into
5135 variable values.  Leading whitespace characters are discarded from your
5136 input before substitution of variable references and function calls;
5137 this means you can include leading spaces in a variable value by
5138 protecting them with variable references, like this:
5140 @example
5141 nullstring :=
5142 space := $(nullstring) # end of the line
5143 @end example
5145 @noindent
5146 Here the value of the variable @code{space} is precisely one space.  The
5147 comment @w{@samp{# end of the line}} is included here just for clarity.
5148 Since trailing space characters are @emph{not} stripped from variable
5149 values, just a space at the end of the line would have the same effect
5150 (but be rather hard to read).  If you put whitespace at the end of a
5151 variable value, it is a good idea to put a comment like that at the end
5152 of the line to make your intent clear.  Conversely, if you do @emph{not}
5153 want any whitespace characters at the end of your variable value, you
5154 must remember not to put a random comment on the end of the line after
5155 some whitespace, such as this:
5157 @example
5158 dir := /foo/bar    # directory to put the frobs in
5159 @end example
5161 @noindent
5162 Here the value of the variable @code{dir} is @w{@samp{/foo/bar    }}
5163 (with four trailing spaces), which was probably not the intention.
5164 (Imagine something like @w{@samp{$(dir)/file}} with this definition!)
5166 @cindex conditional variable assignment
5167 @cindex variables, conditional assignment
5168 @cindex ?=
5169 There is another assignment operator for variables, @samp{?=}.  This
5170 is called a conditional variable assignment operator, because it only
5171 has an effect if the variable is not yet defined.  This statement:
5173 @example
5174 FOO ?= bar
5175 @end example
5177 @noindent
5178 is exactly equivalent to this
5179 (@pxref{Origin Function, ,The @code{origin} Function}):
5181 @example
5182 ifeq ($(origin FOO), undefined)
5183   FOO = bar
5184 endif
5185 @end example
5187 Note that a variable set to an empty value is still defined, so
5188 @samp{?=} will not set that variable.
5190 @node Advanced, Values, Flavors, Using Variables
5191 @section Advanced Features for Reference to Variables
5192 @cindex reference to variables
5194 This section describes some advanced features you can use to reference
5195 variables in more flexible ways.
5197 @menu
5198 * Substitution Refs::           Referencing a variable with
5199                                   substitutions on the value.
5200 * Computed Names::              Computing the name of the variable to refer to.
5201 @end menu
5203 @node Substitution Refs, Computed Names, Advanced, Advanced
5204 @subsection Substitution References
5205 @cindex modified variable reference
5206 @cindex substitution variable reference
5207 @cindex variables, modified reference
5208 @cindex variables, substitution reference
5210 @cindex variables, substituting suffix in
5211 @cindex suffix, substituting in variables
5212 A @dfn{substitution reference} substitutes the value of a variable with
5213 alterations that you specify.  It has the form
5214 @samp{$(@var{var}:@var{a}=@var{b})} (or
5215 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
5216 of the variable @var{var}, replace every @var{a} at the end of a word with
5217 @var{b} in that value, and substitute the resulting string.
5219 When we say ``at the end of a word'', we mean that @var{a} must appear
5220 either followed by whitespace or at the end of the value in order to be
5221 replaced; other occurrences of @var{a} in the value are unaltered.  For
5222 example:@refill
5224 @example
5225 foo := a.o b.o c.o
5226 bar := $(foo:.o=.c)
5227 @end example
5229 @noindent
5230 sets @samp{bar} to @samp{a.c b.c c.c}.  @xref{Setting, ,Setting Variables}.
5232 A substitution reference is actually an abbreviation for use of the
5233 @code{patsubst} expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}).  We provide
5234 substitution references as well as @code{patsubst} for compatibility with
5235 other implementations of @code{make}.
5237 @findex patsubst
5238 Another type of substitution reference lets you use the full power of
5239 the @code{patsubst} function.  It has the same form
5240 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
5241 @var{a} must contain a single @samp{%} character.  This case is
5242 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
5243 @xref{Text Functions, ,Functions for String Substitution and Analysis},
5244 for a description of the @code{patsubst} function.@refill
5246 @example
5247 @group
5248 @exdent For example:
5250 foo := a.o b.o c.o
5251 bar := $(foo:%.o=%.c)
5252 @end group
5253 @end example
5255 @noindent
5256 sets @samp{bar} to @samp{a.c b.c c.c}.
5258 @node Computed Names,  , Substitution Refs, Advanced
5259 @subsection Computed Variable Names
5260 @cindex nested variable reference
5261 @cindex computed variable name
5262 @cindex variables, computed names
5263 @cindex variables, nested references
5264 @cindex variables, @samp{$} in name
5265 @cindex @code{$}, in variable name
5266 @cindex dollar sign (@code{$}), in variable name
5268 Computed variable names are a complicated concept needed only for
5269 sophisticated makefile programming.  For most purposes you need not
5270 consider them, except to know that making a variable with a dollar sign
5271 in its name might have strange results.  However, if you are the type
5272 that wants to understand everything, or you are actually interested in
5273 what they do, read on.
5275 Variables may be referenced inside the name of a variable.  This is
5276 called a @dfn{computed variable name} or a @dfn{nested variable
5277 reference}.  For example,
5279 @example
5280 x = y
5281 y = z
5282 a := $($(x))
5283 @end example
5285 @noindent
5286 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
5287 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
5288 to @samp{z}.  Here the name of the variable to reference is not stated
5289 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
5290 @samp{$(x)} here is nested within the outer variable reference.
5292 The previous example shows two levels of nesting, but any number of levels
5293 is possible.  For example, here are three levels:
5295 @example
5296 x = y
5297 y = z
5298 z = u
5299 a := $($($(x)))
5300 @end example
5302 @noindent
5303 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
5304 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
5305 @samp{$(z)}, which becomes @samp{u}.
5307 References to recursively-expanded variables within a variable name are
5308 re-expanded in the usual fashion.  For example:
5310 @example
5311 x = $(y)
5312 y = z
5313 z = Hello
5314 a := $($(x))
5315 @end example
5317 @noindent
5318 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
5319 which becomes @samp{$(z)} which becomes @samp{Hello}.
5321 Nested variable references can also contain modified references and
5322 function invocations (@pxref{Functions, ,Functions for Transforming Text}),
5323 just like any other reference.
5324 For example, using the @code{subst} function
5325 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
5327 @example
5328 @group
5329 x = variable1
5330 variable2 := Hello
5331 y = $(subst 1,2,$(x))
5332 z = y
5333 a := $($($(z)))
5334 @end group
5335 @end example
5337 @noindent
5338 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
5339 would ever want to write a nested reference as convoluted as this one, but
5340 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
5341 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
5342 @code{x} and changes it by substitution to @samp{variable2}, so that the
5343 entire string becomes @samp{$(variable2)}, a simple variable reference
5344 whose value is @samp{Hello}.@refill
5346 A computed variable name need not consist entirely of a single variable
5347 reference.  It can contain several variable references, as well as some
5348 invariant text.  For example,
5350 @example
5351 @group
5352 a_dirs := dira dirb
5353 1_dirs := dir1 dir2
5354 @end group
5356 @group
5357 a_files := filea fileb
5358 1_files := file1 file2
5359 @end group
5361 @group
5362 ifeq "$(use_a)" "yes"
5363 a1 := a
5364 else
5365 a1 := 1
5366 endif
5367 @end group
5369 @group
5370 ifeq "$(use_dirs)" "yes"
5371 df := dirs
5372 else
5373 df := files
5374 endif
5376 dirs := $($(a1)_$(df))
5377 @end group
5378 @end example
5380 @noindent
5381 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
5382 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
5383 and @code{use_dirs}.@refill
5385 Computed variable names can also be used in substitution references:
5387 @example
5388 @group
5389 a_objects := a.o b.o c.o
5390 1_objects := 1.o 2.o 3.o
5392 sources := $($(a1)_objects:.o=.c)
5393 @end group
5394 @end example
5396 @noindent
5397 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
5398 depending on the value of @code{a1}.
5400 The only restriction on this sort of use of nested variable references
5401 is that they cannot specify part of the name of a function to be called.
5402 This is because the test for a recognized function name is done before
5403 the expansion of nested references.  For example,
5405 @example
5406 @group
5407 ifdef do_sort
5408 func := sort
5409 else
5410 func := strip
5411 endif
5412 @end group
5414 @group
5415 bar := a d b g q c
5416 @end group
5418 @group
5419 foo := $($(func) $(bar))
5420 @end group
5421 @end example
5423 @noindent
5424 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
5425 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
5426 as the argument to either the @code{sort} or the @code{strip} function.
5427 This restriction could be removed in the future if that change is shown
5428 to be a good idea.
5430 You can also use computed variable names in the left-hand side of a
5431 variable assignment, or in a @code{define} directive, as in:
5433 @example
5434 dir = foo
5435 $(dir)_sources := $(wildcard $(dir)/*.c)
5436 define $(dir)_print =
5437 lpr $($(dir)_sources)
5438 endef
5439 @end example
5441 @noindent
5442 This example defines the variables @samp{dir}, @samp{foo_sources}, and
5443 @samp{foo_print}.
5445 Note that @dfn{nested variable references} are quite different from
5446 @dfn{recursively expanded variables}
5447 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
5448 used together in complex ways when doing makefile programming.@refill
5450 @node Values, Setting, Advanced, Using Variables
5451 @section How Variables Get Their Values
5452 @cindex variables, how they get their values
5453 @cindex value, how a variable gets it
5455 Variables can get values in several different ways:
5457 @itemize @bullet
5458 @item
5459 You can specify an overriding value when you run @code{make}.
5460 @xref{Overriding, ,Overriding Variables}.
5462 @item
5463 You can specify a value in the makefile, either
5464 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
5465 verbatim definition (@pxref{Multi-Line, ,Defining Multi-Line Variables}).@refill
5467 @item
5468 Variables in the environment become @code{make} variables.
5469 @xref{Environment, ,Variables from the Environment}.
5471 @item
5472 Several @dfn{automatic} variables are given new values for each rule.
5473 Each of these has a single conventional use.
5474 @xref{Automatic Variables}.
5476 @item
5477 Several variables have constant initial values.
5478 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
5479 @end itemize
5481 @node Setting, Appending, Values, Using Variables
5482 @section Setting Variables
5483 @cindex setting variables
5484 @cindex variables, setting
5485 @cindex =
5486 @cindex :=
5487 @cindex ::=
5488 @cindex ?=
5489 @cindex !=
5491 To set a variable from the makefile, write a line starting with the
5492 variable name followed by @samp{=} @samp{:=}, or @samp{::=}.  Whatever
5493 follows the @samp{=}, @samp{:=}, or @samp{::=} on the line becomes the
5494 value.  For example,
5496 @example
5497 objects = main.o foo.o bar.o utils.o
5498 @end example
5500 @noindent
5501 defines a variable named @code{objects}.  Whitespace around the variable
5502 name and immediately after the @samp{=} is ignored.
5504 Variables defined with @samp{=} are @dfn{recursively expanded}
5505 variables.  Variables defined with @samp{:=} or @samp{::=} are
5506 @dfn{simply expanded} variables; these definitions can contain
5507 variable references which will be expanded before the definition is
5508 made.  @xref{Flavors, ,The Two Flavors of Variables}.
5510 The variable name may contain function and variable references, which
5511 are expanded when the line is read to find the actual variable name to use.
5513 There is no limit on the length of the value of a variable except the
5514 amount of memory on the computer.  You can split the value of a
5515 variable into multiple physical lines for readability
5516 (@pxref{Splitting Lines, ,Splitting Long Lines}).
5518 Most variable names are considered to have the empty string as a value if
5519 you have never set them.  Several variables have built-in initial values
5520 that are not empty, but you can set them in the usual ways
5521 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).
5522 Several special variables are set
5523 automatically to a new value for each rule; these are called the
5524 @dfn{automatic} variables (@pxref{Automatic Variables}).
5526 If you'd like a variable to be set to a value only if it's not already
5527 set, then you can use the shorthand operator @samp{?=} instead of
5528 @samp{=}.  These two settings of the variable @samp{FOO} are identical
5529 (@pxref{Origin Function, ,The @code{origin} Function}):
5531 @example
5532 FOO ?= bar
5533 @end example
5535 @noindent
5538 @example
5539 ifeq ($(origin FOO), undefined)
5540 FOO = bar
5541 endif
5542 @end example
5544 The shell assignment operator @samp{!=} can be used to execute a
5545 program and set a variable to its output.  This operator first
5546 evaluates the right-hand side, then passes that result to the shell
5547 for execution.  If the result of the execution ends in a newline, that
5548 one newline is removed; all other newlines are replaced by spaces.
5549 The resulting string is then placed into the named
5550 recursively-expanded variable.  For example:
5552 @example
5553 hash != printf '\043'
5554 file_list != find . -name '*.c'
5555 @end example
5557 If the result of the execution could produce a @code{$}, and you don't
5558 intend what follows that to be interpreted as a make variable or
5559 function reference, then you must replace every @code{$} with
5560 @code{$$} as part of the execution.  Alternatively, you can set a
5561 simply expanded variable to the result of running a program using the
5562 @code{shell} function call.  @xref{Shell Function, , The @code{shell}
5563 Function}.  For example:
5565 @example
5566 hash := $(shell printf '\043')
5567 var := $(shell find . -name "*.c")
5568 @end example
5571 @node Appending, Override Directive, Setting, Using Variables
5572 @section Appending More Text to Variables
5573 @cindex +=
5574 @cindex appending to variables
5575 @cindex variables, appending to
5577 Often it is useful to add more text to the value of a variable already defined.
5578 You do this with a line containing @samp{+=}, like this:
5580 @example
5581 objects += another.o
5582 @end example
5584 @noindent
5585 This takes the value of the variable @code{objects}, and adds the text
5586 @samp{another.o} to it (preceded by a single space).  Thus:
5588 @example
5589 objects = main.o foo.o bar.o utils.o
5590 objects += another.o
5591 @end example
5593 @noindent
5594 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
5596 Using @samp{+=} is similar to:
5598 @example
5599 objects = main.o foo.o bar.o utils.o
5600 objects := $(objects) another.o
5601 @end example
5603 @noindent
5604 but differs in ways that become important when you use more complex values.
5606 When the variable in question has not been defined before, @samp{+=}
5607 acts just like normal @samp{=}: it defines a recursively-expanded
5608 variable.  However, when there @emph{is} a previous definition, exactly
5609 what @samp{+=} does depends on what flavor of variable you defined
5610 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
5611 explanation of the two flavors of variables.
5613 When you add to a variable's value with @samp{+=}, @code{make} acts
5614 essentially as if you had included the extra text in the initial
5615 definition of the variable.  If you defined it first with @samp{:=} or
5616 @samp{::=}, making it a simply-expanded variable, @samp{+=} adds to
5617 that simply-expanded definition, and expands the new text before
5618 appending it to the old value just as @samp{:=} does (see
5619 @ref{Setting, ,Setting Variables}, for a full explanation of
5620 @samp{:=} or @samp{::=}).  In fact,
5622 @example
5623 variable := value
5624 variable += more
5625 @end example
5627 @noindent
5628 is exactly equivalent to:
5630 @noindent
5631 @example
5632 variable := value
5633 variable := $(variable) more
5634 @end example
5636 On the other hand, when you use @samp{+=} with a variable that you defined
5637 first to be recursively-expanded using plain @samp{=}, @code{make} does
5638 something a bit different.  Recall that when you define a
5639 recursively-expanded variable, @code{make} does not expand the value you set
5640 for variable and function references immediately.  Instead it stores the text
5641 verbatim, and saves these variable and function references to be expanded
5642 later, when you refer to the new variable (@pxref{Flavors, ,The Two Flavors
5643 of Variables}).  When you use @samp{+=} on a recursively-expanded variable,
5644 it is this unexpanded text to which @code{make} appends the new text you
5645 specify.
5647 @example
5648 @group
5649 variable = value
5650 variable += more
5651 @end group
5652 @end example
5654 @noindent
5655 is roughly equivalent to:
5657 @example
5658 @group
5659 temp = value
5660 variable = $(temp) more
5661 @end group
5662 @end example
5664 @noindent
5665 except that of course it never defines a variable called @code{temp}.
5666 The importance of this comes when the variable's old value contains
5667 variable references.  Take this common example:
5669 @example
5670 CFLAGS = $(includes) -O
5671 @dots{}
5672 CFLAGS += -pg # enable profiling
5673 @end example
5675 @noindent
5676 The first line defines the @code{CFLAGS} variable with a reference to another
5677 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
5678 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
5679 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
5680 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
5681 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
5682 need not be defined yet for its value to take effect.  It only has to be
5683 defined before any reference to @code{CFLAGS}.  If we tried to append to the
5684 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
5686 @example
5687 CFLAGS := $(CFLAGS) -pg # enable profiling
5688 @end example
5690 @noindent
5691 This is pretty close, but not quite what we want.  Using @samp{:=}
5692 redefines @code{CFLAGS} as a simply-expanded variable; this means
5693 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
5694 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
5695 -pg}}, and a later definition of @code{includes} will have no effect.
5696 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
5697 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
5698 the reference to @code{includes}, so if that variable gets defined at
5699 any later point, a reference like @samp{$(CFLAGS)} still uses its
5700 value.
5702 @node Override Directive, Multi-Line, Appending, Using Variables
5703 @section The @code{override} Directive
5704 @findex override
5705 @cindex overriding with @code{override}
5706 @cindex variables, overriding
5708 If a variable has been set with a command argument
5709 (@pxref{Overriding, ,Overriding Variables}),
5710 then ordinary assignments in the makefile are ignored.  If you want to set
5711 the variable in the makefile even though it was set with a command
5712 argument, you can use an @code{override} directive, which is a line that
5713 looks like this:@refill
5715 @example
5716 override @var{variable} = @var{value}
5717 @end example
5719 @noindent
5722 @example
5723 override @var{variable} := @var{value}
5724 @end example
5726 To append more text to a variable defined on the command line, use:
5728 @example
5729 override @var{variable} += @var{more text}
5730 @end example
5732 @noindent
5733 @xref{Appending, ,Appending More Text to Variables}.
5735 Variable assignments marked with the @code{override} flag have a
5736 higher priority than all other assignments, except another
5737 @code{override}.  Subsequent assignments or appends to this variable
5738 which are not marked @code{override} will be ignored.
5740 The @code{override} directive was not invented for escalation in the war
5741 between makefiles and command arguments.  It was invented so you can alter
5742 and add to values that the user specifies with command arguments.
5744 For example, suppose you always want the @samp{-g} switch when you run the
5745 C compiler, but you would like to allow the user to specify the other
5746 switches with a command argument just as usual.  You could use this
5747 @code{override} directive:
5749 @example
5750 override CFLAGS += -g
5751 @end example
5753 You can also use @code{override} directives with @code{define} directives.
5754 This is done as you might expect:
5756 @example
5757 override define foo =
5759 endef
5760 @end example
5762 @noindent
5763 @iftex
5764 See the next section for information about @code{define}.
5765 @end iftex
5766 @ifnottex
5767 @xref{Multi-Line, ,Defining Multi-Line Variables}.
5768 @end ifnottex
5770 @node Multi-Line, Undefine Directive, Override Directive, Using Variables
5771 @section Defining Multi-Line Variables
5772 @findex define
5773 @findex endef
5774 @cindex multi-line variable definition
5775 @cindex variables, multi-line
5776 @cindex verbatim variable definition
5777 @cindex defining variables verbatim
5778 @cindex variables, defining verbatim
5780 Another way to set the value of a variable is to use the @code{define}
5781 directive.  This directive has an unusual syntax which allows newline
5782 characters to be included in the value, which is convenient for
5783 defining both canned sequences of commands (@pxref{Canned Recipes,
5784 ,Defining Canned Recipes}), and also sections of makefile syntax to
5785 use with @code{eval} (@pxref{Eval Function}).@refill
5787 The @code{define} directive is followed on the same line by the name
5788 of the variable being defined and an (optional) assignment operator,
5789 and nothing more.  The value to give the variable appears on the
5790 following lines.  The end of the value is marked by a line containing
5791 just the word @code{endef}.  Aside from this difference in syntax,
5792 @code{define} works just like any other variable definition.  The
5793 variable name may contain function and variable references, which are
5794 expanded when the directive is read to find the actual variable name
5795 to use.
5797 You may omit the variable assignment operator if you prefer.  If
5798 omitted, @code{make} assumes it to be @samp{=} and creates a
5799 recursively-expanded variable (@pxref{Flavors, ,The Two Flavors of Variables}).
5800 When using a @samp{+=} operator, the value is appended to the previous
5801 value as with any other append operation: with a single space
5802 separating the old and new values.
5804 You may nest @code{define} directives: @code{make} will keep track of
5805 nested directives and report an error if they are not all properly
5806 closed with @code{endef}.  Note that lines beginning with the recipe
5807 prefix character are considered part of a recipe, so any @code{define}
5808 or @code{endef} strings appearing on such a line will not be
5809 considered @code{make} directives.
5811 @example
5812 define two-lines =
5813 echo foo
5814 echo $(bar)
5815 endef
5816 @end example
5818 The value in an ordinary assignment cannot contain a newline; but the
5819 newlines that separate the lines of the value in a @code{define} become
5820 part of the variable's value (except for the final newline which precedes
5821 the @code{endef} and is not considered part of the value).@refill
5823 @need 800
5824 When used in a recipe, the previous example is functionally equivalent
5825 to this:
5827 @example
5828 two-lines = echo foo; echo $(bar)
5829 @end example
5831 @noindent
5832 since two commands separated by semicolon behave much like two separate
5833 shell commands.  However, note that using two separate lines means
5834 @code{make} will invoke the shell twice, running an independent sub-shell
5835 for each line.  @xref{Execution, ,Recipe Execution}.
5837 If you want variable definitions made with @code{define} to take
5838 precedence over command-line variable definitions, you can use the
5839 @code{override} directive together with @code{define}:
5841 @example
5842 override define two-lines =
5844 $(bar)
5845 endef
5846 @end example
5848 @noindent
5849 @xref{Override Directive, ,The @code{override} Directive}.
5851 @node Undefine Directive, Environment, Multi-Line, Using Variables
5852 @section Undefining Variables
5853 @findex undefine
5854 @cindex undefining variable
5856 If you want to clear a variable, setting its value to empty is usually
5857 sufficient. Expanding such a variable will yield the same result (empty
5858 string) regardless of whether it was set or not. However, if you are
5859 using the @code{flavor} (@pxref{Flavor Function}) and
5860 @code{origin} (@pxref{Origin Function}) functions, there is a difference
5861 between a variable that was never set and a variable with an empty value.
5862 In such situations you may want to use the @code{undefine} directive to
5863 make a variable appear as if it was never set. For example:
5865 @example
5866 foo := foo
5867 bar = bar
5869 undefine foo
5870 undefine bar
5872 $(info $(origin foo))
5873 $(info $(flavor bar))
5874 @end example
5876 This example will print ``undefined'' for both variables.
5878 If you want to undefine a command-line variable definition, you can use
5879 the @code{override} directive together with @code{undefine}, similar to
5880 how this is done for variable definitions:
5882 @example
5883 override undefine CFLAGS
5884 @end example
5886 @node Environment, Target-specific, Undefine Directive, Using Variables
5887 @section Variables from the Environment
5889 @cindex variables, environment
5890 @cindex environment
5891 Variables in @code{make} can come from the environment in which
5892 @code{make} is run.  Every environment variable that @code{make} sees
5893 when it starts up is transformed into a @code{make} variable with the
5894 same name and value.  However, an explicit assignment in the makefile,
5895 or with a command argument, overrides the environment.  (If the
5896 @samp{-e} flag is specified, then values from the environment override
5897 assignments in the makefile.  @xref{Options Summary, ,Summary of
5898 Options}.  But this is not recommended practice.)
5900 Thus, by setting the variable @code{CFLAGS} in your environment, you can
5901 cause all C compilations in most makefiles to use the compiler switches you
5902 prefer.  This is safe for variables with standard or conventional meanings
5903 because you know that no makefile will use them for other things.  (Note
5904 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
5905 and therefore are not affected by the value in the environment.)
5907 When @code{make} runs a recipe, variables defined in the
5908 makefile are placed into the environment of each shell.  This allows
5909 you to pass values to sub-@code{make} invocations (@pxref{Recursion,
5910 ,Recursive Use of @code{make}}).  By default, only variables that came
5911 from the environment or the command line are passed to recursive
5912 invocations.  You can use the @code{export} directive to pass other
5913 variables.  @xref{Variables/Recursion, , Communicating Variables to a
5914 Sub-@code{make}}, for full details.
5916 Other use of variables from the environment is not recommended.  It is not
5917 wise for makefiles to depend for their functioning on environment variables
5918 set up outside their control, since this would cause different users to get
5919 different results from the same makefile.  This is against the whole
5920 purpose of most makefiles.
5922 @cindex SHELL, import from environment
5923 Such problems would be especially likely with the variable
5924 @code{SHELL}, which is normally present in the environment to specify
5925 the user's choice of interactive shell.  It would be very undesirable
5926 for this choice to affect @code{make}; so, @code{make} handles the
5927 @code{SHELL} environment variable in a special way; see @ref{Choosing
5928 the Shell}.@refill
5930 @node Target-specific, Pattern-specific, Environment, Using Variables
5931 @section Target-specific Variable Values
5932 @cindex target-specific variables
5933 @cindex variables, target-specific
5935 Variable values in @code{make} are usually global; that is, they are the
5936 same regardless of where they are evaluated (unless they're reset, of
5937 course).  One exception to that is automatic variables
5938 (@pxref{Automatic Variables}).
5940 The other exception is @dfn{target-specific variable values}.  This
5941 feature allows you to define different values for the same variable,
5942 based on the target that @code{make} is currently building.  As with
5943 automatic variables, these values are only available within the context
5944 of a target's recipe (and in other target-specific assignments).
5946 Set a target-specific variable value like this:
5948 @example
5949 @var{target} @dots{} : @var{variable-assignment}
5950 @end example
5952 Target-specific variable assignments can be prefixed with any or all of the
5953 special keywords @code{export}, @code{override}, or @code{private};
5954 these apply their normal behavior to this instance of the variable only.
5956 Multiple @var{target} values create a target-specific variable value for
5957 each member of the target list individually.
5959 The @var{variable-assignment} can be any valid form of assignment;
5960 recursive (@samp{=}), simple (@samp{:=} or @samp{::=}), appending
5961 (@samp{+=}), or conditional (@samp{?=}).  All variables that appear
5962 within the @var{variable-assignment} are evaluated within the context
5963 of the target: thus, any previously-defined target-specific variable
5964 values will be in effect.  Note that this variable is actually
5965 distinct from any ``global'' value: the two variables do not have to
5966 have the same flavor (recursive vs.@: simple).
5968 Target-specific variables have the same priority as any other makefile
5969 variable.  Variables provided on the command line (and in the
5970 environment if the @samp{-e} option is in force) will take precedence.
5971 Specifying the @code{override} directive will allow the target-specific
5972 variable value to be preferred.
5974 There is one more special feature of target-specific variables: when
5975 you define a target-specific variable that variable value is also in
5976 effect for all prerequisites of this target, and all their
5977 prerequisites, etc.@: (unless those prerequisites override that variable
5978 with their own target-specific variable value).  So, for example, a
5979 statement like this:
5981 @example
5982 prog : CFLAGS = -g
5983 prog : prog.o foo.o bar.o
5984 @end example
5986 @noindent
5987 will set @code{CFLAGS} to @samp{-g} in the recipe for @file{prog}, but
5988 it will also set @code{CFLAGS} to @samp{-g} in the recipes that create
5989 @file{prog.o}, @file{foo.o}, and @file{bar.o}, and any recipes which
5990 create their prerequisites.
5992 Be aware that a given prerequisite will only be built once per
5993 invocation of make, at most.  If the same file is a prerequisite of
5994 multiple targets, and each of those targets has a different value for
5995 the same target-specific variable, then the first target to be built
5996 will cause that prerequisite to be built and the prerequisite will
5997 inherit the target-specific value from the first target.  It will
5998 ignore the target-specific values from any other targets.
6000 @node Pattern-specific, Suppressing Inheritance, Target-specific, Using Variables
6001 @section Pattern-specific Variable Values
6002 @cindex pattern-specific variables
6003 @cindex variables, pattern-specific
6005 In addition to target-specific variable values
6006 (@pxref{Target-specific, ,Target-specific Variable Values}), GNU
6007 @code{make} supports pattern-specific variable values.  In this form,
6008 the variable is defined for any target that matches the pattern
6009 specified.
6011 Set a pattern-specific variable value like this:
6013 @example
6014 @var{pattern} @dots{} : @var{variable-assignment}
6015 @end example
6016 where @var{pattern} is a %-pattern.  As with target-specific variable
6017 values, multiple @var{pattern} values create a pattern-specific variable
6018 value for each pattern individually.  The @var{variable-assignment} can
6019 be any valid form of assignment.  Any command line variable setting will
6020 take precedence, unless @code{override} is specified.
6022 For example:
6024 @example
6025 %.o : CFLAGS = -O
6026 @end example
6028 @noindent
6029 will assign @code{CFLAGS} the value of @samp{-O} for all targets
6030 matching the pattern @code{%.o}.
6032 If a target matches more than one pattern, the matching pattern-specific
6033 variables with longer stems are interpreted first. This results in more
6034 specific variables taking precedence over the more generic ones, for
6035 example:
6037 @example
6038 %.o: %.c
6039         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
6041 lib/%.o: CFLAGS := -fPIC -g
6042 %.o: CFLAGS := -g
6044 all: foo.o lib/bar.o
6045 @end example
6047 In this example the first definition of the @code{CFLAGS} variable
6048 will be used to update @file{lib/bar.o} even though the second one
6049 also applies to this target. Pattern-specific variables which result
6050 in the same stem length are considered in the order in which they
6051 were defined in the makefile.
6053 Pattern-specific variables are searched after any target-specific
6054 variables defined explicitly for that target, and before target-specific
6055 variables defined for the parent target.
6057 @node Suppressing Inheritance, Special Variables, Pattern-specific, Using Variables
6058 @section Suppressing Inheritance
6059 @findex private
6060 @cindex suppressing inheritance
6061 @cindex inheritance, suppressing
6063 As described in previous sections, @code{make} variables are inherited
6064 by prerequisites.  This capability allows you to modify the behavior
6065 of a prerequisite based on which targets caused it to be rebuilt.  For
6066 example, you might set a target-specific variable on a @code{debug}
6067 target, then running @samp{make debug} will cause that variable to be
6068 inherited by all prerequisites of @code{debug}, while just running
6069 @samp{make all} (for example) would not have that assignment.
6071 Sometimes, however, you may not want a variable to be inherited.  For
6072 these situations, @code{make} provides the @code{private} modifier.
6073 Although this modifier can be used with any variable assignment, it
6074 makes the most sense with target- and pattern-specific variables.  Any
6075 variable marked @code{private} will be visible to its local target but
6076 will not be inherited by prerequisites of that target.  A global
6077 variable marked @code{private} will be visible in the global scope but
6078 will not be inherited by any target, and hence will not be visible
6079 in any recipe.
6081 As an example, consider this makefile:
6082 @example
6083 EXTRA_CFLAGS =
6085 prog: private EXTRA_CFLAGS = -L/usr/local/lib
6086 prog: a.o b.o
6087 @end example
6089 Due to the @code{private} modifier, @code{a.o} and @code{b.o} will not
6090 inherit the @code{EXTRA_CFLAGS} variable assignment from the
6091 @code{prog} target.
6093 @node Special Variables,  , Suppressing Inheritance, Using Variables
6094 @comment  node-name,  next,  previous,  up
6095 @section Other Special Variables
6096 @cindex makefiles, and special variables
6097 @cindex special variables
6099 GNU @code{make} supports some variables that have special properties.
6101 @table @code
6103 @vindex MAKEFILE_LIST @r{(list of parsed makefiles)}
6104 @cindex makefiles, and @code{MAKEFILE_LIST} variable
6105 @cindex including (@code{MAKEFILE_LIST} variable)
6106 @item MAKEFILE_LIST
6107 Contains the name of each makefile that is parsed by @code{make}, in
6108 the order in which it was parsed.  The name is appended just
6109 before @code{make} begins to parse the makefile.  Thus, if the first
6110 thing a makefile does is examine the last word in this variable, it
6111 will be the name of the current makefile.  Once the current makefile
6112 has used @code{include}, however, the last word will be the
6113 just-included makefile.
6115 If a makefile named @code{Makefile} has this content:
6117 @example
6118 @group
6119 name1 := $(lastword $(MAKEFILE_LIST))
6121 include inc.mk
6123 name2 := $(lastword $(MAKEFILE_LIST))
6125 all:
6126         @@echo name1 = $(name1)
6127         @@echo name2 = $(name2)
6128 @end group
6129 @end example
6131 @noindent
6132 then you would expect to see this output:
6134 @example
6135 @group
6136 name1 = Makefile
6137 name2 = inc.mk
6138 @end group
6139 @end example
6141 @vindex .DEFAULT_GOAL @r{(define default goal)}
6142 @item .DEFAULT_GOAL
6143 Sets the default goal to be used if no targets were specified on the
6144 command line (@pxref{Goals, , Arguments to Specify the Goals}).  The
6145 @code{.DEFAULT_GOAL} variable allows you to discover the current
6146 default goal, restart the default goal selection algorithm by clearing
6147 its value, or to explicitly set the default goal.  The following
6148 example illustrates these cases:
6150 @example
6151 @group
6152 # Query the default goal.
6153 ifeq ($(.DEFAULT_GOAL),)
6154   $(warning no default goal is set)
6155 endif
6157 .PHONY: foo
6158 foo: ; @@echo $@@
6160 $(warning default goal is $(.DEFAULT_GOAL))
6162 # Reset the default goal.
6163 .DEFAULT_GOAL :=
6165 .PHONY: bar
6166 bar: ; @@echo $@@
6168 $(warning default goal is $(.DEFAULT_GOAL))
6170 # Set our own.
6171 .DEFAULT_GOAL := foo
6172 @end group
6173 @end example
6175 This makefile prints:
6177 @example
6178 @group
6179 no default goal is set
6180 default goal is foo
6181 default goal is bar
6183 @end group
6184 @end example
6186 Note that assigning more than one target name to @code{.DEFAULT_GOAL} is
6187 invalid and will result in an error.
6189 @vindex MAKE_RESTARTS @r{(number of times @code{make} has restarted)}
6190 @item MAKE_RESTARTS
6191 This variable is set only if this instance of @code{make} has
6192 restarted (@pxref{Remaking Makefiles, , How Makefiles Are Remade}): it
6193 will contain the number of times this instance has restarted.  Note
6194 this is not the same as recursion (counted by the @code{MAKELEVEL}
6195 variable).  You should not set, modify, or export this variable.
6197 @vindex .RECIPEPREFIX @r{(change the recipe prefix character)}
6198 @item .RECIPEPREFIX
6199 The first character of the value of this variable is used as the
6200 character make assumes is introducing a recipe line.  If the variable
6201 is empty (as it is by default) that character is the standard tab
6202 character.  For example, this is a valid makefile:
6204 @example
6205 @group
6206 .RECIPEPREFIX = >
6207 all:
6208 > @@echo Hello, world
6209 @end group
6210 @end example
6212 The value of @code{.RECIPEPREFIX} can be changed multiple times; once set
6213 it stays in effect for all rules parsed until it is modified.
6215 @vindex .VARIABLES @r{(list of variables)}
6216 @item .VARIABLES
6217 Expands to a list of the @emph{names} of all global variables defined
6218 so far.  This includes variables which have empty values, as well as
6219 built-in variables (@pxref{Implicit Variables, , Variables Used by
6220 Implicit Rules}), but does not include any variables which are only
6221 defined in a target-specific context.  Note that any value you assign
6222 to this variable will be ignored; it will always return its special
6223 value.
6225 @c @vindex .TARGETS @r{(list of targets)}
6226 @c @item .TARGETS
6227 @c The second special variable is @code{.TARGETS}.  When expanded, the
6228 @c value consists of a list of all targets defined in all makefiles read
6229 @c up until that point.  Note it's not enough for a file to be simply
6230 @c mentioned in the makefile to be listed in this variable, even if it
6231 @c would match an implicit rule and become an ``implicit target''.  The
6232 @c file must appear as a target, on the left-hand side of a ``:'', to be
6233 @c considered a target for the purposes of this variable.
6235 @vindex .FEATURES @r{(list of supported features)}
6236 @item .FEATURES
6237 Expands to a list of special features supported by this version of
6238 @code{make}.  Possible values include, but are not limited to:
6240 @table @samp
6242 @item archives
6243 Supports @code{ar} (archive) files using special file name syntax.
6244 @xref{Archives, ,Using @code{make} to Update Archive Files}.
6246 @item check-symlink
6247 Supports the @code{-L} (@code{--check-symlink-times}) flag.
6248 @xref{Options Summary, ,Summary of Options}.
6250 @item else-if
6251 Supports ``else if'' non-nested conditionals.  @xref{Conditional
6252 Syntax, ,Syntax of Conditionals}.
6254 @item jobserver
6255 Supports ``job server'' enhanced parallel builds.  @xref{Parallel,
6256 ,Parallel Execution}.
6258 @item oneshell
6259 Supports the @code{.ONESHELL} special target.  @xref{One Shell, ,Using
6260 One Shell}.
6262 @item order-only
6263 Supports order-only prerequisites.  @xref{Prerequisite Types, ,Types
6264 of Prerequisites}.
6266 @item second-expansion
6267 Supports secondary expansion of prerequisite lists.
6269 @item shortest-stem
6270 Uses the ``shortest stem'' method of choosing which pattern, of
6271 multiple applicable options, will be used.  @xref{Pattern Match, ,How
6272 Patterns Match}.
6274 @item target-specific
6275 Supports target-specific and pattern-specific variable assignments.
6276 @xref{Target-specific, ,Target-specific Variable Values}.
6278 @item undefine
6279 Supports the @code{undefine} directive.  @xref{Undefine Directive}.
6281 @item guile
6282 Has GNU Guile available as an embedded extension language.
6283 @xref{Guile Function}.
6285 @end table
6287 @vindex .INCLUDE_DIRS @r{(list of include directories)}
6288 @item .INCLUDE_DIRS
6289 Expands to a list of directories that @code{make} searches for
6290 included makefiles (@pxref{Include, , Including Other Makefiles}).
6292 @end table
6294 @node Conditionals, Functions, Using Variables, Top
6295 @chapter Conditional Parts of Makefiles
6297 @cindex conditionals
6298 A @dfn{conditional} directive causes part of a makefile to be obeyed
6299 or ignored depending on the values of variables.  Conditionals can
6300 compare the value of one variable to another, or the value of a
6301 variable to a constant string.  Conditionals control what @code{make}
6302 actually ``sees'' in the makefile, so they @emph{cannot} be used to
6303 control recipes at the time of execution.@refill
6305 @menu
6306 * Conditional Example::         Example of a conditional
6307 * Conditional Syntax::          The syntax of conditionals.
6308 * Testing Flags::               Conditionals that test flags.
6309 @end menu
6311 @node Conditional Example, Conditional Syntax, Conditionals, Conditionals
6312 @section Example of a Conditional
6314 The following example of a conditional tells @code{make} to use one
6315 set of libraries if the @code{CC} variable is @samp{gcc}, and a
6316 different set of libraries otherwise.  It works by controlling which
6317 of two recipe lines will be used for the rule.  The result is that
6318 @samp{CC=gcc} as an argument to @code{make} changes not only which
6319 compiler is used but also which libraries are linked.
6321 @example
6322 libs_for_gcc = -lgnu
6323 normal_libs =
6325 foo: $(objects)
6326 ifeq ($(CC),gcc)
6327         $(CC) -o foo $(objects) $(libs_for_gcc)
6328 else
6329         $(CC) -o foo $(objects) $(normal_libs)
6330 endif
6331 @end example
6333 This conditional uses three directives: one @code{ifeq}, one @code{else}
6334 and one @code{endif}.
6336 The @code{ifeq} directive begins the conditional, and specifies the
6337 condition.  It contains two arguments, separated by a comma and surrounded
6338 by parentheses.  Variable substitution is performed on both arguments and
6339 then they are compared.  The lines of the makefile following the
6340 @code{ifeq} are obeyed if the two arguments match; otherwise they are
6341 ignored.
6343 The @code{else} directive causes the following lines to be obeyed if the
6344 previous conditional failed.  In the example above, this means that the
6345 second alternative linking command is used whenever the first alternative
6346 is not used.  It is optional to have an @code{else} in a conditional.
6348 The @code{endif} directive ends the conditional.  Every conditional must
6349 end with an @code{endif}.  Unconditional makefile text follows.
6351 As this example illustrates, conditionals work at the textual level:
6352 the lines of the conditional are treated as part of the makefile, or
6353 ignored, according to the condition.  This is why the larger syntactic
6354 units of the makefile, such as rules, may cross the beginning or the
6355 end of the conditional.
6357 When the variable @code{CC} has the value @samp{gcc}, the above example has
6358 this effect:
6360 @example
6361 foo: $(objects)
6362         $(CC) -o foo $(objects) $(libs_for_gcc)
6363 @end example
6365 @noindent
6366 When the variable @code{CC} has any other value, the effect is this:
6368 @example
6369 foo: $(objects)
6370         $(CC) -o foo $(objects) $(normal_libs)
6371 @end example
6373 Equivalent results can be obtained in another way by conditionalizing a
6374 variable assignment and then using the variable unconditionally:
6376 @example
6377 libs_for_gcc = -lgnu
6378 normal_libs =
6380 ifeq ($(CC),gcc)
6381   libs=$(libs_for_gcc)
6382 else
6383   libs=$(normal_libs)
6384 endif
6386 foo: $(objects)
6387         $(CC) -o foo $(objects) $(libs)
6388 @end example
6390 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
6391 @section Syntax of Conditionals
6392 @findex ifdef
6393 @findex ifeq
6394 @findex ifndef
6395 @findex ifneq
6396 @findex else
6397 @findex endif
6399 The syntax of a simple conditional with no @code{else} is as follows:
6401 @example
6402 @var{conditional-directive}
6403 @var{text-if-true}
6404 endif
6405 @end example
6407 @noindent
6408 The @var{text-if-true} may be any lines of text, to be considered as part
6409 of the makefile if the condition is true.  If the condition is false, no
6410 text is used instead.
6412 The syntax of a complex conditional is as follows:
6414 @example
6415 @var{conditional-directive}
6416 @var{text-if-true}
6417 else
6418 @var{text-if-false}
6419 endif
6420 @end example
6424 @example
6425 @var{conditional-directive}
6426 @var{text-if-one-is-true}
6427 else @var{conditional-directive}
6428 @var{text-if-true}
6429 else
6430 @var{text-if-false}
6431 endif
6432 @end example
6434 @noindent
6435 There can be as many ``@code{else} @var{conditional-directive}''
6436 clauses as necessary.  Once a given condition is true,
6437 @var{text-if-true} is used and no other clause is used; if no
6438 condition is true then @var{text-if-false} is used.  The
6439 @var{text-if-true} and @var{text-if-false} can be any number of lines
6440 of text.
6442 The syntax of the @var{conditional-directive} is the same whether the
6443 conditional is simple or complex; after an @code{else} or not.  There
6444 are four different directives that test different conditions.  Here is
6445 a table of them:
6447 @table @code
6448 @item ifeq (@var{arg1}, @var{arg2})
6449 @itemx ifeq '@var{arg1}' '@var{arg2}'
6450 @itemx ifeq "@var{arg1}" "@var{arg2}"
6451 @itemx ifeq "@var{arg1}" '@var{arg2}'
6452 @itemx ifeq '@var{arg1}' "@var{arg2}"
6453 Expand all variable references in @var{arg1} and @var{arg2} and
6454 compare them.  If they are identical, the @var{text-if-true} is
6455 effective; otherwise, the @var{text-if-false}, if any, is effective.
6457 Often you want to test if a variable has a non-empty value.  When the
6458 value results from complex expansions of variables and functions,
6459 expansions you would consider empty may actually contain whitespace
6460 characters and thus are not seen as empty.  However, you can use the
6461 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
6462 whitespace as a non-empty value.  For example:
6464 @example
6465 @group
6466 ifeq ($(strip $(foo)),)
6467 @var{text-if-empty}
6468 endif
6469 @end group
6470 @end example
6472 @noindent
6473 will evaluate @var{text-if-empty} even if the expansion of
6474 @code{$(foo)} contains whitespace characters.
6476 @item ifneq (@var{arg1}, @var{arg2})
6477 @itemx ifneq '@var{arg1}' '@var{arg2}'
6478 @itemx ifneq "@var{arg1}" "@var{arg2}"
6479 @itemx ifneq "@var{arg1}" '@var{arg2}'
6480 @itemx ifneq '@var{arg1}' "@var{arg2}"
6481 Expand all variable references in @var{arg1} and @var{arg2} and
6482 compare them.  If they are different, the @var{text-if-true} is
6483 effective; otherwise, the @var{text-if-false}, if any, is effective.
6485 @item ifdef @var{variable-name}
6486 The @code{ifdef} form takes the @emph{name} of a variable as its
6487 argument, not a reference to a variable.  The value of that variable
6488 has a non-empty value, the @var{text-if-true} is effective; otherwise,
6489 the @var{text-if-false}, if any, is effective.  Variables that have
6490 never been defined have an empty value.  The text @var{variable-name}
6491 is expanded, so it could be a variable or function that expands
6492 to the name of a variable.  For example:
6494 @example
6495 bar = true
6496 foo = bar
6497 ifdef $(foo)
6498 frobozz = yes
6499 endif
6500 @end example
6502 The variable reference @code{$(foo)} is expanded, yielding @code{bar},
6503 which is considered to be the name of a variable.  The variable
6504 @code{bar} is not expanded, but its value is examined to determine if
6505 it is non-empty.
6507 Note that @code{ifdef} only tests whether a variable has a value.  It
6508 does not expand the variable to see if that value is nonempty.
6509 Consequently, tests using @code{ifdef} return true for all definitions
6510 except those like @code{foo =}.  To test for an empty value, use
6511 @w{@code{ifeq ($(foo),)}}.  For example,
6513 @example
6514 bar =
6515 foo = $(bar)
6516 ifdef foo
6517 frobozz = yes
6518 else
6519 frobozz = no
6520 endif
6521 @end example
6523 @noindent
6524 sets @samp{frobozz} to @samp{yes}, while:
6526 @example
6527 foo =
6528 ifdef foo
6529 frobozz = yes
6530 else
6531 frobozz = no
6532 endif
6533 @end example
6535 @noindent
6536 sets @samp{frobozz} to @samp{no}.
6538 @item ifndef @var{variable-name}
6539 If the variable @var{variable-name} has an empty value, the
6540 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
6541 if any, is effective.  The rules for expansion and testing of
6542 @var{variable-name} are identical to the @code{ifdef} directive.
6543 @end table
6545 Extra spaces are allowed and ignored at the beginning of the
6546 conditional directive line, but a tab is not allowed.  (If the line
6547 begins with a tab, it will be considered part of a recipe for a rule.)
6548 Aside from this, extra spaces or tabs may be inserted with no effect
6549 anywhere except within the directive name or within an argument.  A
6550 comment starting with @samp{#} may appear at the end of the line.
6552 The other two directives that play a part in a conditional are @code{else}
6553 and @code{endif}.  Each of these directives is written as one word, with no
6554 arguments.  Extra spaces are allowed and ignored at the beginning of the
6555 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
6556 appear at the end of the line.
6558 Conditionals affect which lines of the makefile @code{make} uses.  If
6559 the condition is true, @code{make} reads the lines of the
6560 @var{text-if-true} as part of the makefile; if the condition is false,
6561 @code{make} ignores those lines completely.  It follows that syntactic
6562 units of the makefile, such as rules, may safely be split across the
6563 beginning or the end of the conditional.@refill
6565 @code{make} evaluates conditionals when it reads a makefile.
6566 Consequently, you cannot use automatic variables in the tests of
6567 conditionals because they are not defined until recipes are run
6568 (@pxref{Automatic Variables}).
6570 To prevent intolerable confusion, it is not permitted to start a
6571 conditional in one makefile and end it in another.  However, you may
6572 write an @code{include} directive within a conditional, provided you do
6573 not attempt to terminate the conditional inside the included file.
6575 @node Testing Flags,  , Conditional Syntax, Conditionals
6576 @section Conditionals that Test Flags
6578 You can write a conditional that tests @code{make} command flags such as
6579 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
6580 @code{findstring} function
6581 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
6582 This is useful when @code{touch} is not enough to make a file appear up
6583 to date.
6585 The @code{findstring} function determines whether one string appears as a
6586 substring of another.  If you want to test for the @samp{-t} flag,
6587 use @samp{t} as the first string and the value of @code{MAKEFLAGS} as
6588 the other.
6590 For example, here is how to arrange to use @samp{ranlib -t} to finish
6591 marking an archive file up to date:
6593 @example
6594 archive.a: @dots{}
6595 ifneq (,$(findstring t,$(MAKEFLAGS)))
6596         +touch archive.a
6597         +ranlib -t archive.a
6598 else
6599         ranlib archive.a
6600 endif
6601 @end example
6603 @noindent
6604 The @samp{+} prefix marks those recipe lines as ``recursive'' so that
6605 they will be executed despite use of the @samp{-t} flag.
6606 @xref{Recursion, ,Recursive Use of @code{make}}.
6608 @node Functions, Running, Conditionals, Top
6609 @chapter Functions for Transforming Text
6610 @cindex functions
6612 @dfn{Functions} allow you to do text processing in the makefile to
6613 compute the files to operate on or the commands to use in recipes.
6614 You use a function in a @dfn{function call}, where you give the name
6615 of the function and some text (the @dfn{arguments}) for the function
6616 to operate on.  The result of the function's processing is substituted
6617 into the makefile at the point of the call, just as a variable might
6618 be substituted.
6620 @menu
6621 * Syntax of Functions::         How to write a function call.
6622 * Text Functions::              General-purpose text manipulation functions.
6623 * File Name Functions::         Functions for manipulating file names.
6624 * Conditional Functions::       Functions that implement conditions.
6625 * Foreach Function::            Repeat some text with controlled variation.
6626 * File Function::               Write text to a file.
6627 * Call Function::               Expand a user-defined function.
6628 * Value Function::              Return the un-expanded value of a variable.
6629 * Eval Function::               Evaluate the arguments as makefile syntax.
6630 * Origin Function::             Find where a variable got its value.
6631 * Flavor Function::             Find out the flavor of a variable.
6632 * Make Control Functions::      Functions that control how make runs.
6633 * Shell Function::              Substitute the output of a shell command.
6634 * Guile Function::              Call the GNU Guile embedded scripting language.
6635 @end menu
6637 @node Syntax of Functions, Text Functions, Functions, Functions
6638 @section Function Call Syntax
6639 @cindex @code{$}, in function call
6640 @cindex dollar sign (@code{$}), in function call
6641 @cindex arguments of functions
6642 @cindex functions, syntax of
6644 A function call resembles a variable reference.  It can appear
6645 anywhere a variable reference can appear, and it is expanded using the
6646 same rules as variable references.  A function call looks like this:
6648 @example
6649 $(@var{function} @var{arguments})
6650 @end example
6652 @noindent
6653 or like this:
6655 @example
6656 $@{@var{function} @var{arguments}@}
6657 @end example
6659 Here @var{function} is a function name; one of a short list of names
6660 that are part of @code{make}.  You can also essentially create your own
6661 functions by using the @code{call} built-in function.
6663 The @var{arguments} are the arguments of the function.  They are
6664 separated from the function name by one or more spaces or tabs, and if
6665 there is more than one argument, then they are separated by commas.
6666 Such whitespace and commas are not part of an argument's value.  The
6667 delimiters which you use to surround the function call, whether
6668 parentheses or braces, can appear in an argument only in matching pairs;
6669 the other kind of delimiters may appear singly.  If the arguments
6670 themselves contain other function calls or variable references, it is
6671 wisest to use the same kind of delimiters for all the references; write
6672 @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst a,b,$@{x@})}}.  This
6673 is because it is clearer, and because only one type of delimiter is
6674 matched to find the end of the reference.
6676 The text written for each argument is processed by substitution of
6677 variables and function calls to produce the argument value, which
6678 is the text on which the function acts.  The substitution is done in the
6679 order in which the arguments appear.
6681 Commas and unmatched parentheses or braces cannot appear in the text of an
6682 argument as written; leading spaces cannot appear in the text of the first
6683 argument as written.  These characters can be put into the argument value
6684 by variable substitution.  First define variables @code{comma} and
6685 @code{space} whose values are isolated comma and space characters, then
6686 substitute these variables where such characters are wanted, like this:
6688 @example
6689 @group
6690 comma:= ,
6691 empty:=
6692 space:= $(empty) $(empty)
6693 foo:= a b c
6694 bar:= $(subst $(space),$(comma),$(foo))
6695 # @r{bar is now `a,b,c'.}
6696 @end group
6697 @end example
6699 @noindent
6700 Here the @code{subst} function replaces each space with a comma, through
6701 the value of @code{foo}, and substitutes the result.
6703 @node Text Functions, File Name Functions, Syntax of Functions, Functions
6704 @section Functions for String Substitution and Analysis
6705 @cindex functions, for text
6707 Here are some functions that operate on strings:
6709 @table @code
6710 @item $(subst @var{from},@var{to},@var{text})
6711 @findex subst
6712 Performs a textual replacement on the text @var{text}: each occurrence
6713 of @var{from} is replaced by @var{to}.  The result is substituted for
6714 the function call.  For example,
6716 @example
6717 $(subst ee,EE,feet on the street)
6718 @end example
6720 substitutes the string @samp{fEEt on the strEEt}.
6722 @item $(patsubst @var{pattern},@var{replacement},@var{text})
6723 @findex patsubst
6724 Finds whitespace-separated words in @var{text} that match
6725 @var{pattern} and replaces them with @var{replacement}.  Here
6726 @var{pattern} may contain a @samp{%} which acts as a wildcard,
6727 matching any number of any characters within a word.  If
6728 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
6729 by the text that matched the @samp{%} in @var{pattern}.  Only the first
6730 @samp{%} in the @var{pattern} and @var{replacement} is treated this
6731 way; any subsequent @samp{%} is unchanged.@refill
6733 @cindex @code{%}, quoting in @code{patsubst}
6734 @cindex @code{%}, quoting with @code{\} (backslash)
6735 @cindex @code{\} (backslash), to quote @code{%}
6736 @cindex backslash (@code{\}), to quote @code{%}
6737 @cindex quoting @code{%}, in @code{patsubst}
6738 @samp{%} characters in @code{patsubst} function invocations can be
6739 quoted with preceding backslashes (@samp{\}).  Backslashes that would
6740 otherwise quote @samp{%} characters can be quoted with more backslashes.
6741 Backslashes that quote @samp{%} characters or other backslashes are
6742 removed from the pattern before it is compared file names or has a stem
6743 substituted into it.  Backslashes that are not in danger of quoting
6744 @samp{%} characters go unmolested.  For example, the pattern
6745 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
6746 operative @samp{%} character, and @samp{pattern\\} following it.  The
6747 final two backslashes are left alone because they cannot affect any
6748 @samp{%} character.@refill
6750 Whitespace between words is folded into single space characters;
6751 leading and trailing whitespace is discarded.
6753 For example,
6755 @example
6756 $(patsubst %.c,%.o,x.c.c bar.c)
6757 @end example
6759 @noindent
6760 produces the value @samp{x.c.o bar.o}.
6762 Substitution references (@pxref{Substitution Refs, ,Substitution
6763 References}) are a simpler way to get the effect of the @code{patsubst}
6764 function:
6766 @example
6767 $(@var{var}:@var{pattern}=@var{replacement})
6768 @end example
6770 @noindent
6771 is equivalent to
6773 @example
6774 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
6775 @end example
6777 The second shorthand simplifies one of the most common uses of
6778 @code{patsubst}: replacing the suffix at the end of file names.
6780 @example
6781 $(@var{var}:@var{suffix}=@var{replacement})
6782 @end example
6784 @noindent
6785 is equivalent to
6787 @example
6788 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
6789 @end example
6791 @noindent
6792 For example, you might have a list of object files:
6794 @example
6795 objects = foo.o bar.o baz.o
6796 @end example
6798 @noindent
6799 To get the list of corresponding source files, you could simply write:
6801 @example
6802 $(objects:.o=.c)
6803 @end example
6805 @noindent
6806 instead of using the general form:
6808 @example
6809 $(patsubst %.o,%.c,$(objects))
6810 @end example
6812 @item $(strip @var{string})
6813 @cindex stripping whitespace
6814 @cindex whitespace, stripping
6815 @cindex spaces, stripping
6816 @findex strip
6817 Removes leading and trailing whitespace from @var{string} and replaces
6818 each internal sequence of one or more whitespace characters with a
6819 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
6821 The function @code{strip} can be very useful when used in conjunction
6822 with conditionals.  When comparing something with the empty string
6823 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
6824 just whitespace to match the empty string (@pxref{Conditionals}).
6826 Thus, the following may fail to have the desired results:
6828 @example
6829 .PHONY: all
6830 ifneq   "$(needs_made)" ""
6831 all: $(needs_made)
6832 else
6833 all:;@@echo 'Nothing to make!'
6834 endif
6835 @end example
6837 @noindent
6838 Replacing the variable reference @w{@samp{$(needs_made)}} with the
6839 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
6840 directive would make it more robust.@refill
6842 @item $(findstring @var{find},@var{in})
6843 @findex findstring
6844 @cindex searching for strings
6845 @cindex finding strings
6846 @cindex strings, searching for
6847 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
6848 value is @var{find}; otherwise, the value is empty.  You can use this
6849 function in a conditional to test for the presence of a specific
6850 substring in a given string.  Thus, the two examples,
6852 @example
6853 $(findstring a,a b c)
6854 $(findstring a,b c)
6855 @end example
6857 @noindent
6858 produce the values @samp{a} and @samp{} (the empty string),
6859 respectively.  @xref{Testing Flags}, for a practical application of
6860 @code{findstring}.@refill
6862 @need 750
6863 @findex filter
6864 @cindex filtering words
6865 @cindex words, filtering
6866 @item $(filter @var{pattern}@dots{},@var{text})
6867 Returns all whitespace-separated words in @var{text} that @emph{do} match
6868 any of the @var{pattern} words, removing any words that @emph{do not}
6869 match.  The patterns are written using @samp{%}, just like the patterns
6870 used in the @code{patsubst} function above.@refill
6872 The @code{filter} function can be used to separate out different types
6873 of strings (such as file names) in a variable.  For example:
6875 @example
6876 sources := foo.c bar.c baz.s ugh.h
6877 foo: $(sources)
6878         cc $(filter %.c %.s,$(sources)) -o foo
6879 @end example
6881 @noindent
6882 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
6883 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
6884 @file{baz.s} should be specified in the command to the
6885 compiler.@refill
6887 @item $(filter-out @var{pattern}@dots{},@var{text})
6888 @findex filter-out
6889 @cindex filtering out words
6890 @cindex words, filtering out
6891 Returns all whitespace-separated words in @var{text} that @emph{do not}
6892 match any of the @var{pattern} words, removing the words that @emph{do}
6893 match one or more.  This is the exact opposite of the @code{filter}
6894 function.@refill
6896 For example, given:
6898 @example
6899 @group
6900 objects=main1.o foo.o main2.o bar.o
6901 mains=main1.o main2.o
6902 @end group
6903 @end example
6905 @noindent
6906 the following generates a list which contains all the object files not
6907 in @samp{mains}:
6909 @example
6910 $(filter-out $(mains),$(objects))
6911 @end example
6913 @need 1500
6914 @findex sort
6915 @cindex sorting words
6916 @item $(sort @var{list})
6917 Sorts the words of @var{list} in lexical order, removing duplicate
6918 words.  The output is a list of words separated by single spaces.
6919 Thus,
6921 @example
6922 $(sort foo bar lose)
6923 @end example
6925 @noindent
6926 returns the value @samp{bar foo lose}.
6928 @cindex removing duplicate words
6929 @cindex duplicate words, removing
6930 @cindex words, removing duplicates
6931 Incidentally, since @code{sort} removes duplicate words, you can use
6932 it for this purpose even if you don't care about the sort order.
6934 @item $(word @var{n},@var{text})
6935 @findex word
6936 @cindex word, selecting a
6937 @cindex selecting a word
6938 Returns the @var{n}th word of @var{text}.  The legitimate values of
6939 @var{n} start from 1.  If @var{n} is bigger than the number of words
6940 in @var{text}, the value is empty.  For example,
6942 @example
6943 $(word 2, foo bar baz)
6944 @end example
6946 @noindent
6947 returns @samp{bar}.
6949 @item $(wordlist @var{s},@var{e},@var{text})
6950 @findex wordlist
6951 @cindex words, selecting lists of
6952 @cindex selecting word lists
6953 Returns the list of words in @var{text} starting with word @var{s} and
6954 ending with word @var{e} (inclusive).  The legitimate values of @var{s}
6955 start from 1; @var{e} may start from 0.  If @var{s} is bigger than the
6956 number of words in @var{text}, the value is empty.  If @var{e} is
6957 bigger than the number of words in @var{text}, words up to the end of
6958 @var{text} are returned.  If @var{s} is greater than @var{e}, nothing
6959 is returned.  For example,
6961 @example
6962 $(wordlist 2, 3, foo bar baz)
6963 @end example
6965 @noindent
6966 returns @samp{bar baz}.
6968 @c Following item phrased to prevent overfull hbox.  --RJC 17 Jul 92
6969 @item $(words @var{text})
6970 @findex words
6971 @cindex words, finding number
6972 Returns the number of words in @var{text}.
6973 Thus, the last word of @var{text} is
6974 @w{@code{$(word $(words @var{text}),@var{text})}}.@refill
6976 @item $(firstword @var{names}@dots{})
6977 @findex firstword
6978 @cindex words, extracting first
6979 The argument @var{names} is regarded as a series of names, separated
6980 by whitespace.  The value is the first name in the series.  The rest
6981 of the names are ignored.
6983 For example,
6985 @example
6986 $(firstword foo bar)
6987 @end example
6989 @noindent
6990 produces the result @samp{foo}.  Although @code{$(firstword
6991 @var{text})} is the same as @code{$(word 1,@var{text})}, the
6992 @code{firstword} function is retained for its simplicity.@refill
6995 @item $(lastword @var{names}@dots{})
6996 @findex lastword
6997 @cindex words, extracting last
6998 The argument @var{names} is regarded as a series of names, separated
6999 by whitespace.  The value is the last name in the series.
7001 For example,
7003 @example
7004 $(lastword foo bar)
7005 @end example
7007 @noindent
7008 produces the result @samp{bar}.  Although @code{$(lastword
7009 @var{text})} is the same as @code{$(word $(words @var{text}),@var{text})},
7010 the @code{lastword} function was added for its simplicity and better
7011 performance.@refill
7012 @end table
7015 Here is a realistic example of the use of @code{subst} and
7016 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
7017 to specify a list of directories that @code{make} should search for
7018 prerequisite files
7019 (@pxref{General Search, , @code{VPATH} Search Path for All Prerequisites}).
7020 This example shows how to
7021 tell the C compiler to search for header files in the same list of
7022 directories.@refill
7024 The value of @code{VPATH} is a list of directories separated by colons,
7025 such as @samp{src:../headers}.  First, the @code{subst} function is used to
7026 change the colons to spaces:
7028 @example
7029 $(subst :, ,$(VPATH))
7030 @end example
7032 @noindent
7033 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
7034 each directory name into a @samp{-I} flag.  These can be added to the
7035 value of the variable @code{CFLAGS}, which is passed automatically to the C
7036 compiler, like this:
7038 @example
7039 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
7040 @end example
7042 @noindent
7043 The effect is to append the text @samp{-Isrc -I../headers} to the
7044 previously given value of @code{CFLAGS}.  The @code{override} directive is
7045 used so that the new value is assigned even if the previous value of
7046 @code{CFLAGS} was specified with a command argument (@pxref{Override
7047 Directive, , The @code{override} Directive}).
7049 @node File Name Functions, Conditional Functions, Text Functions, Functions
7050 @section Functions for File Names
7051 @cindex functions, for file names
7052 @cindex file name functions
7054 Several of the built-in expansion functions relate specifically to
7055 taking apart file names or lists of file names.
7057 Each of the following functions performs a specific transformation on a
7058 file name.  The argument of the function is regarded as a series of file
7059 names, separated by whitespace.  (Leading and trailing whitespace is
7060 ignored.)  Each file name in the series is transformed in the same way and
7061 the results are concatenated with single spaces between them.
7063 @table @code
7064 @item $(dir @var{names}@dots{})
7065 @findex dir
7066 @cindex directory part
7067 @cindex file name, directory part
7068 Extracts the directory-part of each file name in @var{names}.  The
7069 directory-part of the file name is everything up through (and
7070 including) the last slash in it.  If the file name contains no slash,
7071 the directory part is the string @samp{./}.  For example,
7073 @example
7074 $(dir src/foo.c hacks)
7075 @end example
7077 @noindent
7078 produces the result @samp{src/ ./}.
7080 @item $(notdir @var{names}@dots{})
7081 @findex notdir
7082 @cindex file name, nondirectory part
7083 @cindex nondirectory part
7084 Extracts all but the directory-part of each file name in @var{names}.
7085 If the file name contains no slash, it is left unchanged.  Otherwise,
7086 everything through the last slash is removed from it.
7088 A file name that ends with a slash becomes an empty string.  This is
7089 unfortunate, because it means that the result does not always have the
7090 same number of whitespace-separated file names as the argument had;
7091 but we do not see any other valid alternative.
7093 For example,
7095 @example
7096 $(notdir src/foo.c hacks)
7097 @end example
7099 @noindent
7100 produces the result @samp{foo.c hacks}.
7102 @item $(suffix @var{names}@dots{})
7103 @findex suffix
7104 @cindex suffix, function to find
7105 @cindex file name suffix
7106 Extracts the suffix of each file name in @var{names}.  If the file name
7107 contains a period, the suffix is everything starting with the last
7108 period.  Otherwise, the suffix is the empty string.  This frequently
7109 means that the result will be empty when @var{names} is not, and if
7110 @var{names} contains multiple file names, the result may contain fewer
7111 file names.
7113 For example,
7115 @example
7116 $(suffix src/foo.c src-1.0/bar.c hacks)
7117 @end example
7119 @noindent
7120 produces the result @samp{.c .c}.
7122 @item $(basename @var{names}@dots{})
7123 @findex basename
7124 @cindex basename
7125 @cindex file name, basename of
7126 Extracts all but the suffix of each file name in @var{names}.  If the
7127 file name contains a period, the basename is everything starting up to
7128 (and not including) the last period.  Periods in the directory part are
7129 ignored.  If there is no period, the basename is the entire file name.
7130 For example,
7132 @example
7133 $(basename src/foo.c src-1.0/bar hacks)
7134 @end example
7136 @noindent
7137 produces the result @samp{src/foo src-1.0/bar hacks}.
7139 @c plural convention with dots (be consistent)
7140 @item $(addsuffix @var{suffix},@var{names}@dots{})
7141 @findex addsuffix
7142 @cindex suffix, adding
7143 @cindex file name suffix, adding
7144 The argument @var{names} is regarded as a series of names, separated
7145 by whitespace; @var{suffix} is used as a unit.  The value of
7146 @var{suffix} is appended to the end of each individual name and the
7147 resulting larger names are concatenated with single spaces between
7148 them.  For example,
7150 @example
7151 $(addsuffix .c,foo bar)
7152 @end example
7154 @noindent
7155 produces the result @samp{foo.c bar.c}.
7157 @item $(addprefix @var{prefix},@var{names}@dots{})
7158 @findex addprefix
7159 @cindex prefix, adding
7160 @cindex file name prefix, adding
7161 The argument @var{names} is regarded as a series of names, separated
7162 by whitespace; @var{prefix} is used as a unit.  The value of
7163 @var{prefix} is prepended to the front of each individual name and the
7164 resulting larger names are concatenated with single spaces between
7165 them.  For example,
7167 @example
7168 $(addprefix src/,foo bar)
7169 @end example
7171 @noindent
7172 produces the result @samp{src/foo src/bar}.
7174 @item $(join @var{list1},@var{list2})
7175 @findex join
7176 @cindex joining lists of words
7177 @cindex words, joining lists
7178 Concatenates the two arguments word by word: the two first words (one
7179 from each argument) concatenated form the first word of the result, the
7180 two second words form the second word of the result, and so on.  So the
7181 @var{n}th word of the result comes from the @var{n}th word of each
7182 argument.  If one argument has more words that the other, the extra
7183 words are copied unchanged into the result.
7185 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
7187 Whitespace between the words in the lists is not preserved; it is
7188 replaced with a single space.
7190 This function can merge the results of the @code{dir} and
7191 @code{notdir} functions, to produce the original list of files which
7192 was given to those two functions.@refill
7194 @item $(wildcard @var{pattern})
7195 @findex wildcard
7196 @cindex wildcard, function
7197 The argument @var{pattern} is a file name pattern, typically containing
7198 wildcard characters (as in shell file name patterns).  The result of
7199 @code{wildcard} is a space-separated list of the names of existing files
7200 that match the pattern.
7201 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
7203 @item $(realpath @var{names}@dots{})
7204 @findex realpath
7205 @cindex realpath
7206 @cindex file name, realpath of
7207 For each file name in @var{names} return the canonical absolute name.
7208 A canonical name does not contain any @code{.} or @code{..} components,
7209 nor any repeated path separators (@code{/}) or symlinks.  In case of a
7210 failure the empty string is returned.  Consult the @code{realpath(3)}
7211 documentation for a list of possible failure causes.
7213 @item $(abspath @var{names}@dots{})
7214 @findex abspath
7215 @cindex abspath
7216 @cindex file name, abspath of
7217 For each file name in @var{names} return an absolute name that does
7218 not contain any @code{.} or @code{..} components, nor any repeated path
7219 separators (@code{/}).  Note that, in contrast to @code{realpath}
7220 function, @code{abspath} does not resolve symlinks and does not require
7221 the file names to refer to an existing file or directory.  Use the
7222 @code{wildcard} function to test for existence.
7223 @end table
7225 @node Conditional Functions, Foreach Function, File Name Functions, Functions
7226 @section Functions for Conditionals
7227 @findex if
7228 @cindex conditional expansion
7229 There are three functions that provide conditional expansion.  A key
7230 aspect of these functions is that not all of the arguments are
7231 expanded initially.  Only those arguments which need to be expanded,
7232 will be expanded.
7234 @table @code
7235 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
7236 @findex if
7237 The @code{if} function provides support for conditional expansion in a
7238 functional context (as opposed to the GNU @code{make} makefile
7239 conditionals such as @code{ifeq} (@pxref{Conditional Syntax, ,Syntax of
7240 Conditionals}).
7242 The first argument, @var{condition}, first has all preceding and
7243 trailing whitespace stripped, then is expanded.  If it expands to any
7244 non-empty string, then the condition is considered to be true.  If it
7245 expands to an empty string, the condition is considered to be false.
7247 If the condition is true then the second argument, @var{then-part}, is
7248 evaluated and this is used as the result of the evaluation of the entire
7249 @code{if} function.
7251 If the condition is false then the third argument, @var{else-part}, is
7252 evaluated and this is the result of the @code{if} function.  If there is
7253 no third argument, the @code{if} function evaluates to nothing (the
7254 empty string).
7256 Note that only one of the @var{then-part} or the @var{else-part} will be
7257 evaluated, never both.  Thus, either can contain side-effects (such as
7258 @code{shell} function calls, etc.)
7260 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
7261 @findex or
7262 The @code{or} function provides a ``short-circuiting'' OR operation.
7263 Each argument is expanded, in order.  If an argument expands to a
7264 non-empty string the processing stops and the result of the expansion
7265 is that string.  If, after all arguments are expanded, all of them are
7266 false (empty), then the result of the expansion is the empty string.
7268 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
7269 @findex and
7270 The @code{and} function provides a ``short-circuiting'' AND operation.
7271 Each argument is expanded, in order.  If an argument expands to an
7272 empty string the processing stops and the result of the expansion is
7273 the empty string.  If all arguments expand to a non-empty string then
7274 the result of the expansion is the expansion of the last argument.
7276 @end table
7278 @node Foreach Function, File Function, Conditional Functions, Functions
7279 @section The @code{foreach} Function
7280 @findex foreach
7281 @cindex words, iterating over
7283 The @code{foreach} function is very different from other functions.  It
7284 causes one piece of text to be used repeatedly, each time with a different
7285 substitution performed on it.  It resembles the @code{for} command in the
7286 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
7288 The syntax of the @code{foreach} function is:
7290 @example
7291 $(foreach @var{var},@var{list},@var{text})
7292 @end example
7294 @noindent
7295 The first two arguments, @var{var} and @var{list}, are expanded before
7296 anything else is done; note that the last argument, @var{text}, is
7297 @strong{not} expanded at the same time.  Then for each word of the expanded
7298 value of @var{list}, the variable named by the expanded value of @var{var}
7299 is set to that word, and @var{text} is expanded.  Presumably @var{text}
7300 contains references to that variable, so its expansion will be different
7301 each time.
7303 The result is that @var{text} is expanded as many times as there are
7304 whitespace-separated words in @var{list}.  The multiple expansions of
7305 @var{text} are concatenated, with spaces between them, to make the result
7306 of @code{foreach}.
7308 This simple example sets the variable @samp{files} to the list of all files
7309 in the directories in the list @samp{dirs}:
7311 @example
7312 dirs := a b c d
7313 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
7314 @end example
7316 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
7317 finds the value @samp{a} for @code{dir}, so it produces the same result
7318 as @samp{$(wildcard a/*)}; the second repetition produces the result
7319 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
7321 This example has the same result (except for setting @samp{dirs}) as
7322 the following example:
7324 @example
7325 files := $(wildcard a/* b/* c/* d/*)
7326 @end example
7328 When @var{text} is complicated, you can improve readability by giving it
7329 a name, with an additional variable:
7331 @example
7332 find_files = $(wildcard $(dir)/*)
7333 dirs := a b c d
7334 files := $(foreach dir,$(dirs),$(find_files))
7335 @end example
7337 @noindent
7338 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
7339 to define a recursively-expanding variable, so that its value contains an
7340 actual function call to be re-expanded under the control of @code{foreach};
7341 a simply-expanded variable would not do, since @code{wildcard} would be
7342 called only once at the time of defining @code{find_files}.
7344 The @code{foreach} function has no permanent effect on the variable
7345 @var{var}; its value and flavor after the @code{foreach} function call are
7346 the same as they were beforehand.  The other values which are taken from
7347 @var{list} are in effect only temporarily, during the execution of
7348 @code{foreach}.  The variable @var{var} is a simply-expanded variable
7349 during the execution of @code{foreach}.  If @var{var} was undefined
7350 before the @code{foreach} function call, it is undefined after the call.
7351 @xref{Flavors, ,The Two Flavors of Variables}.@refill
7353 You must take care when using complex variable expressions that result in
7354 variable names because many strange things are valid variable names, but
7355 are probably not what you intended.  For example,
7357 @smallexample
7358 files := $(foreach Esta-escrito-en-espanol!,b c ch,$(find_files))
7359 @end smallexample
7361 @noindent
7362 might be useful if the value of @code{find_files} references the variable
7363 whose name is @samp{Esta-escrito-en-espanol!} (es un nombre bastante largo,
7364 no?), but it is more likely to be a mistake.
7366 @node File Function, Call Function, Foreach Function, Functions
7367 @section The @code{file} Function
7368 @findex file
7369 @cindex writing to a file
7370 @cindex file, writing to
7372 The @code{file} function allows the makefile to write to a file.  Two
7373 modes of writing are supported: overwrite, where the text is written
7374 to the beginning of the file and any existing content is lost, and
7375 append, where the text is written to the end of the file, preserving
7376 the existing content.  In all cases the file is created if it does not
7377 exist.
7379 The syntax of the @code{file} function is:
7381 @example
7382 $(file @var{op} @var{filename},@var{text})
7383 @end example
7385 The operator @var{op} can be either @code{>} which indicates overwrite
7386 mode, or @code{>>} which indicates append mode.  The @var{filename}
7387 indicates the file to be written to.  There may optionally be
7388 whitespace between the operator and the file name.
7390 When the @code{file} function is expanded all its arguments are
7391 expanded first, then the file indicated by @var{filename} will be
7392 opened in the mode described by @var{op}.  Finally @var{text} will be
7393 written to the file.  If @var{text} does not already end in a newline,
7394 a final newline will be written.  The result of evaluating the
7395 @code{file} function is always the empty string.
7397 It is a fatal error if the file cannot be opened for writing, or if
7398 the write operation fails.
7400 For example, the @code{file} function can be useful if your build
7401 system has a limited command line size and your recipe runs a command
7402 that can accept arguments from a file as well.  Many commands use the
7403 convention that an argument prefixed with an @code{@@} specifies a
7404 file containing more arguments.  Then you might write your recipe in
7405 this way:
7407 @example
7408 @group
7409 program: $(OBJECTS)
7410         $(file >$@@.in,$^)
7411         $(CMD) $(CMDFLAGS) @@$@@.in
7412         @@rm $@@.in
7413 @end group
7414 @end example
7416 If the command required each argument to be on a separate line of the
7417 input file, you might write your recipe like this:
7419 @example
7420 @group
7421 program: $(OBJECTS)
7422         $(file >$@@.in,) $(foreach O,$^,$(file >>$@@.in,$O))
7423         $(CMD) $(CMDFLAGS) @@$@@.in
7424         @@rm $@@.in
7425 @end group
7426 @end example
7428 @node Call Function, Value Function, File Function, Functions
7429 @section The @code{call} Function
7430 @findex call
7431 @cindex functions, user defined
7432 @cindex user defined functions
7434 The @code{call} function is unique in that it can be used to create new
7435 parameterized functions.  You can write a complex expression as the
7436 value of a variable, then use @code{call} to expand it with different
7437 values.
7439 The syntax of the @code{call} function is:
7441 @example
7442 $(call @var{variable},@var{param},@var{param},@dots{})
7443 @end example
7445 When @code{make} expands this function, it assigns each @var{param} to
7446 temporary variables @code{$(1)}, @code{$(2)}, etc.  The variable
7447 @code{$(0)} will contain @var{variable}.  There is no maximum number of
7448 parameter arguments.  There is no minimum, either, but it doesn't make
7449 sense to use @code{call} with no parameters.
7451 Then @var{variable} is expanded as a @code{make} variable in the context
7452 of these temporary assignments.  Thus, any reference to @code{$(1)} in
7453 the value of @var{variable} will resolve to the first @var{param} in the
7454 invocation of @code{call}.
7456 Note that @var{variable} is the @emph{name} of a variable, not a
7457 @emph{reference} to that variable.  Therefore you would not normally use
7458 a @samp{$} or parentheses when writing it.  (You can, however, use a
7459 variable reference in the name if you want the name not to be a
7460 constant.)
7462 If @var{variable} is the name of a built-in function, the built-in function
7463 is always invoked (even if a @code{make} variable by that name also
7464 exists).
7466 The @code{call} function expands the @var{param} arguments before
7467 assigning them to temporary variables.  This means that @var{variable}
7468 values containing references to built-in functions that have special
7469 expansion rules, like @code{foreach} or @code{if}, may not work as you
7470 expect.
7472 Some examples may make this clearer.
7474 This macro simply reverses its arguments:
7476 @smallexample
7477 reverse = $(2) $(1)
7479 foo = $(call reverse,a,b)
7480 @end smallexample
7482 @noindent
7483 Here @var{foo} will contain @samp{b a}.
7485 This one is slightly more interesting: it defines a macro to search for
7486 the first instance of a program in @code{PATH}:
7488 @smallexample
7489 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
7491 LS := $(call pathsearch,ls)
7492 @end smallexample
7494 @noindent
7495 Now the variable LS contains @code{/bin/ls} or similar.
7497 The @code{call} function can be nested.  Each recursive invocation gets
7498 its own local values for @code{$(1)}, etc.@: that mask the values of
7499 higher-level @code{call}.  For example, here is an implementation of a
7500 @dfn{map} function:
7502 @smallexample
7503 map = $(foreach a,$(2),$(call $(1),$(a)))
7504 @end smallexample
7506 Now you can @var{map} a function that normally takes only one argument,
7507 such as @code{origin}, to multiple values in one step:
7509 @smallexample
7510 o = $(call map,origin,o map MAKE)
7511 @end smallexample
7513 and end up with @var{o} containing something like @samp{file file default}.
7515 A final caution: be careful when adding whitespace to the arguments to
7516 @code{call}.  As with other functions, any whitespace contained in the
7517 second and subsequent arguments is kept; this can cause strange
7518 effects.  It's generally safest to remove all extraneous whitespace when
7519 providing parameters to @code{call}.
7521 @node Value Function, Eval Function, Call Function, Functions
7522 @comment  node-name,  next,  previous,  up
7523 @section The @code{value} Function
7524 @findex value
7525 @cindex variables, unexpanded value
7527 The @code{value} function provides a way for you to use the value of a
7528 variable @emph{without} having it expanded.  Please note that this
7529 does not undo expansions which have already occurred; for example if
7530 you create a simply expanded variable its value is expanded during the
7531 definition; in that case the @code{value} function will return the
7532 same result as using the variable directly.
7534 The syntax of the @code{value} function is:
7536 @example
7537 $(value @var{variable})
7538 @end example
7540 Note that @var{variable} is the @emph{name} of a variable, not a
7541 @emph{reference} to that variable.  Therefore you would not normally
7542 use a @samp{$} or parentheses when writing it.  (You can, however, use
7543 a variable reference in the name if you want the name not to be a
7544 constant.)
7546 The result of this function is a string containing the value of
7547 @var{variable}, without any expansion occurring.  For example, in this
7548 makefile:
7550 @example
7551 @group
7552 FOO = $PATH
7554 all:
7555         @@echo $(FOO)
7556         @@echo $(value FOO)
7557 @end group
7558 @end example
7560 @noindent
7561 The first output line would be @code{ATH}, since the ``$P'' would be
7562 expanded as a @code{make} variable, while the second output line would
7563 be the current value of your @code{$PATH} environment variable, since
7564 the @code{value} function avoided the expansion.
7566 The @code{value} function is most often used in conjunction with the
7567 @code{eval} function (@pxref{Eval Function}).
7569 @node Eval Function, Origin Function, Value Function, Functions
7570 @comment  node-name,  next,  previous,  up
7571 @section The @code{eval} Function
7572 @findex eval
7573 @cindex evaluating makefile syntax
7574 @cindex makefile syntax, evaluating
7576 The @code{eval} function is very special: it allows you to define new
7577 makefile constructs that are not constant; which are the result of
7578 evaluating other variables and functions.  The argument to the
7579 @code{eval} function is expanded, then the results of that expansion
7580 are parsed as makefile syntax.  The expanded results can define new
7581 @code{make} variables, targets, implicit or explicit rules, etc.
7583 The result of the @code{eval} function is always the empty string;
7584 thus, it can be placed virtually anywhere in a makefile without
7585 causing syntax errors.
7587 It's important to realize that the @code{eval} argument is expanded
7588 @emph{twice}; first by the @code{eval} function, then the results of
7589 that expansion are expanded again when they are parsed as makefile
7590 syntax.  This means you may need to provide extra levels of escaping
7591 for ``$'' characters when using @code{eval}.  The @code{value}
7592 function (@pxref{Value Function}) can sometimes be useful in these
7593 situations, to circumvent unwanted expansions.
7595 Here is an example of how @code{eval} can be used; this example
7596 combines a number of concepts and other functions.  Although it might
7597 seem overly complex to use @code{eval} in this example, rather than
7598 just writing out the rules, consider two things: first, the template
7599 definition (in @code{PROGRAM_template}) could need to be much more
7600 complex than it is here; and second, you might put the complex,
7601 ``generic'' part of this example into another makefile, then include
7602 it in all the individual makefiles.  Now your individual makefiles are
7603 quite straightforward.
7605 @example
7606 @group
7607 PROGRAMS    = server client
7609 server_OBJS = server.o server_priv.o server_access.o
7610 server_LIBS = priv protocol
7612 client_OBJS = client.o client_api.o client_mem.o
7613 client_LIBS = protocol
7615 # Everything after this is generic
7617 .PHONY: all
7618 all: $(PROGRAMS)
7620 define PROGRAM_template =
7621  $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
7622  ALL_OBJS   += $$($(1)_OBJS)
7623 endef
7625 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
7627 $(PROGRAMS):
7628         $(LINK.o) $^ $(LDLIBS) -o $@@
7630 clean:
7631         rm -f $(ALL_OBJS) $(PROGRAMS)
7632 @end group
7633 @end example
7635 @node Origin Function, Flavor Function, Eval Function, Functions
7636 @section The @code{origin} Function
7637 @findex origin
7638 @cindex variables, origin of
7639 @cindex origin of variable
7641 The @code{origin} function is unlike most other functions in that it does
7642 not operate on the values of variables; it tells you something @emph{about}
7643 a variable.  Specifically, it tells you where it came from.
7645 The syntax of the @code{origin} function is:
7647 @example
7648 $(origin @var{variable})
7649 @end example
7651 Note that @var{variable} is the @emph{name} of a variable to inquire about,
7652 not a @emph{reference} to that variable.  Therefore you would not normally
7653 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7654 variable reference in the name if you want the name not to be a constant.)
7656 The result of this function is a string telling you how the variable
7657 @var{variable} was defined:
7659 @table @samp
7660 @item undefined
7662 if @var{variable} was never defined.
7664 @item default
7666 if @var{variable} has a default definition, as is usual with @code{CC}
7667 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
7668 Note that if you have redefined a default variable, the @code{origin}
7669 function will return the origin of the later definition.
7671 @item environment
7673 if @var{variable} was inherited from the environment provided to
7674 @code{make}.
7676 @item environment override
7678 if @var{variable} was inherited from the environment provided to
7679 @code{make}, and is overriding a setting for @var{variable} in the
7680 makefile as a result of the @w{@samp{-e}} option (@pxref{Options
7681 Summary, ,Summary of Options}).@refill
7683 @item file
7685 if @var{variable} was defined in a makefile.
7687 @item command line
7689 if @var{variable} was defined on the command line.
7691 @item override
7693 if @var{variable} was defined with an @code{override} directive in a
7694 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
7696 @item automatic
7698 if @var{variable} is an automatic variable defined for the execution
7699 of the recipe for each rule (@pxref{Automatic Variables}).
7700 @end table
7702 This information is primarily useful (other than for your curiosity) to
7703 determine if you want to believe the value of a variable.  For example,
7704 suppose you have a makefile @file{foo} that includes another makefile
7705 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
7706 if you run the command @w{@samp{make -f bar}}, even if the environment contains
7707 a definition of @code{bletch}.  However, if @file{foo} defined
7708 @code{bletch} before including @file{bar}, you do not want to override that
7709 definition.  This could be done by using an @code{override} directive in
7710 @file{foo}, giving that definition precedence over the later definition in
7711 @file{bar}; unfortunately, the @code{override} directive would also
7712 override any command line definitions.  So, @file{bar} could
7713 include:@refill
7715 @example
7716 @group
7717 ifdef bletch
7718 ifeq "$(origin bletch)" "environment"
7719 bletch = barf, gag, etc.
7720 endif
7721 endif
7722 @end group
7723 @end example
7725 @noindent
7726 If @code{bletch} has been defined from the environment, this will redefine
7729 If you want to override a previous definition of @code{bletch} if it came
7730 from the environment, even under @samp{-e}, you could instead write:
7732 @example
7733 @group
7734 ifneq "$(findstring environment,$(origin bletch))" ""
7735 bletch = barf, gag, etc.
7736 endif
7737 @end group
7738 @end example
7740 Here the redefinition takes place if @samp{$(origin bletch)} returns either
7741 @samp{environment} or @samp{environment override}.
7742 @xref{Text Functions, , Functions for String Substitution and Analysis}.
7744 @node Flavor Function, Make Control Functions, Origin Function, Functions
7745 @section The @code{flavor} Function
7746 @findex flavor
7747 @cindex variables, flavor of
7748 @cindex flavor of variable
7750 The @code{flavor} function, like the @code{origin} function, does not
7751 operate on the values of variables but rather it tells you something
7752 @emph{about} a variable.  Specifically, it tells you the flavor of a
7753 variable (@pxref{Flavors, ,The Two Flavors of Variables}).
7755 The syntax of the @code{flavor} function is:
7757 @example
7758 $(flavor @var{variable})
7759 @end example
7761 Note that @var{variable} is the @emph{name} of a variable to inquire about,
7762 not a @emph{reference} to that variable.  Therefore you would not normally
7763 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7764 variable reference in the name if you want the name not to be a constant.)
7766 The result of this function is a string that identifies the flavor of the
7767 variable @var{variable}:
7769 @table @samp
7770 @item undefined
7772 if @var{variable} was never defined.
7774 @item recursive
7776 if @var{variable} is a recursively expanded variable.
7778 @item simple
7780 if @var{variable} is a simply expanded variable.
7782 @end table
7784 @node Make Control Functions, Shell Function, Flavor Function, Functions
7785 @section Functions That Control Make
7786 @cindex functions, for controlling make
7787 @cindex controlling make
7789 These functions control the way make runs.  Generally, they are used to
7790 provide information to the user of the makefile or to cause make to stop
7791 if some sort of environmental error is detected.
7793 @table @code
7794 @item $(error @var{text}@dots{})
7795 @findex error
7796 @cindex error, stopping on
7797 @cindex stopping make
7798 Generates a fatal error where the message is @var{text}.  Note that
7799 the error is generated whenever this function is evaluated.  So, if
7800 you put it inside a recipe or on the right side of a recursive
7801 variable assignment, it won't be evaluated until later.  The
7802 @var{text} will be expanded before the error is generated.
7804 For example,
7806 @example
7807 ifdef ERROR1
7808 $(error error is $(ERROR1))
7809 endif
7810 @end example
7812 @noindent
7813 will generate a fatal error during the read of the makefile if the
7814 @code{make} variable @code{ERROR1} is defined.  Or,
7816 @example
7817 ERR = $(error found an error!)
7819 .PHONY: err
7820 err: ; $(ERR)
7821 @end example
7823 @noindent
7824 will generate a fatal error while @code{make} is running, if the
7825 @code{err} target is invoked.
7827 @item $(warning @var{text}@dots{})
7828 @findex warning
7829 @cindex warnings, printing
7830 @cindex printing user warnings
7831 This function works similarly to the @code{error} function, above,
7832 except that @code{make} doesn't exit.  Instead, @var{text} is expanded
7833 and the resulting message is displayed, but processing of the makefile
7834 continues.
7836 The result of the expansion of this function is the empty string.
7838 @item $(info @var{text}@dots{})
7839 @findex info
7840 @cindex printing messages
7841 This function does nothing more than print its (expanded) argument(s)
7842 to standard output.  No makefile name or line number is added.  The
7843 result of the expansion of this function is the empty string.
7844 @end table
7846 @node Shell Function, Guile Function, Make Control Functions, Functions
7847 @section The @code{shell} Function
7848 @findex shell
7849 @cindex command expansion
7850 @cindex backquotes
7851 @cindex shell command, function for
7853 The @code{shell} function is unlike any other function other than the
7854 @code{wildcard} function
7855 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
7856 communicates with the world outside of @code{make}.
7858 The @code{shell} function performs the same function that backquotes
7859 (@samp{`}) perform in most shells: it does @dfn{command expansion}.
7860 This means that it takes as an argument a shell command and evaluates
7861 to the output of the command.  The only processing @code{make} does on
7862 the result is to convert each newline (or carriage-return / newline
7863 pair) to a single space.  If there is a trailing (carriage-return
7864 and) newline it will simply be removed.@refill
7866 The commands run by calls to the @code{shell} function are run when the
7867 function calls are expanded (@pxref{Reading Makefiles, , How
7868 @code{make} Reads a Makefile}).  Because this function involves
7869 spawning a new shell, you should carefully consider the performance
7870 implications of using the @code{shell} function within recursively
7871 expanded variables vs.@: simply expanded variables (@pxref{Flavors, ,The
7872 Two Flavors of Variables}).
7874 Here are some examples of the use of the @code{shell} function:
7876 @example
7877 contents := $(shell cat foo)
7878 @end example
7880 @noindent
7881 sets @code{contents} to the contents of the file @file{foo}, with a space
7882 (rather than a newline) separating each line.
7884 @example
7885 files := $(shell echo *.c)
7886 @end example
7888 @noindent
7889 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
7890 using a very strange shell, this has the same result as
7891 @w{@samp{$(wildcard *.c)}} (as long as at least one @samp{.c} file
7892 exists).@refill
7894 @node Guile Function,  , Shell Function, Functions
7895 @section The @code{guile} Function
7896 @findex guile
7897 @cindex Guile
7899 GNU make may be built with support for GNU Guile as an embedded
7900 extension language.  You can check the @code{.FEATURES} variable for
7901 the word @samp{guile} to determine if your version of GNU make
7902 provides this capability.
7904 GNU Guile implements the Scheme language.  A review of GNU Guile and
7905 the Scheme language and its features is beyond the scope of this
7906 manual: see the documentation for GNU Guile and Scheme.
7908 If GNU Guile is available as an extension language, there will be one
7909 new @code{make} function available: @code{guile}.  The @code{guile}
7910 function takes one argument which is first expanded by @code{make} in
7911 the normal fashion, then passed to the GNU Guile evaluator.  The
7912 result of the evaluator is converted into a string and used as the
7913 expansion of the @code{guile} function in the makefile.
7915 Similarly, there are Guile procedures exposed by @code{make} for use
7916 in Guile scripts.
7918 @menu
7919 * Guile Types::                 Converting Guile types to @code{make} strings.
7920 * Guile Interface::             Invoking @code{make} functions from Guile.
7921 * Guile Example::               Example using Guile in @code{make}.
7922 @end menu
7924 @node Guile Types, Guile Interface, Guile Function, Guile Function
7925 @subsection Conversion of Guile Types
7926 @cindex convert guile types
7927 @cindex guile, conversion of types
7928 @cindex types, conversion of
7930 There is only one ``data type'' in @code{make}: a string.  GNU Guile,
7931 on the other hand, provides a rich variety of different data types.
7932 An important aspect of the interface between @code{make} and GNU Guile
7933 is the conversion of Guile data types into @code{make} strings.
7935 This conversion is relevant in two places: when a makefile invokes the
7936 @code{guile} function to evaluate a Guile expression, the result of
7937 that evaluation must be converted into a make string so it can be
7938 further evaluated by @code{make}.  And secondly, when a Guile script
7939 invokes one of the procedures exported by @code{make} the argument
7940 provided to the procedure must be converted into a string.
7942 The conversion of Guile types into @code{make} strings is as below:
7944 @table @code
7945 @item #f
7946 False is converted into the empty string: in @code{make} conditionals
7947 the empty string is considered false.
7949 @item #t
7950 True is converted to the string @samp{#t}: in @code{make} conditionals
7951 any non-empty string is considered true.
7953 @item symbol
7954 @item number
7955 A symbol or number is converted into the string representation of that
7956 symbol or number.
7958 @item character
7959 A printable character is converted to the same character.
7961 @item string
7962 A string containing only printable characters is converted to the same
7963 string.
7965 @item list
7966 A list is converted recursively according to the above rules.  This
7967 implies that any structured list will be flattened (that is, a result
7968 of @samp{'(a b (c d) e)} will be converted to the @code{make} string
7969 @samp{a b c d e}).
7971 @item other
7972 Any other Guile type results in an error.  In future versions of
7973 @code{make}, other Guile types may be converted.
7975 @end table
7977 The translation of @samp{#f} (to the empty string) and @samp{#t} (to
7978 the non-empty string @samp{#t}) is designed to allow you to use Guile
7979 boolean results directly as @code{make} boolean conditions.  For
7980 example:
7982 @example
7983 $(if $(guile (access? "myfile" R_OK)),$(info myfile exists))
7984 @end example
7986 As a consequence of these conversion rules you must consider the
7987 result of your Guile script, as that result will be converted into a
7988 string and parsed by @code{make}.  If there is no natural result for
7989 the script (that is, the script exists solely for its side-effects),
7990 you should add @samp{#f} as the final expression in order to avoid
7991 syntax errors in your makefile.
7993 @node Guile Interface, Guile Example, Guile Types, Guile Function
7994 @subsection Interfaces from Guile to @code{make}
7995 @cindex make interface to guile
7996 @cindex make procedures in guile
7998 In addition to the @code{guile} function available in makefiles,
7999 @code{make} exposes some procedures for use in your Guile scripts.  At
8000 startup @code{make} creates a new Guile module, @code{gnu make}, and
8001 exports these procedures as public interfaces from that module:
8003 @table @code
8004 @item gmk-expand
8005 This procedure takes a single argument which is converted into a
8006 string.  The string is expanded by @code{make} using normal
8007 @code{make} expansion rules.  The result of the expansion is converted
8008 into a Guile string and provided as the result of the procedure.
8010 @item gmk-eval
8011 This procedure takes a single argument which is converted into a
8012 string.  The string is evaluated by @code{make} as if it were a
8013 makefile.  This is the same capability available via the @code{eval}
8014 function (@pxref{Eval Function}).  The result of the @code{gmk-eval}
8015 procedure is always the empty string.
8017 @item gmk-var
8018 This procedure takes a single argument which is converted into a
8019 string.  The string is assumed to be the name of a @code{make}
8020 variable, which is then expanded.  The expansion is converted into a
8021 string and provided as the result of the procedure.
8023 @end table
8025 @node Guile Example,  , Guile Interface, Guile Function
8026 @subsection Example Using Guile in @code{make}
8027 @cindex Guile example
8028 @cindex example using Guile
8030 Here is a very simple example using GNU Guile to manage writing to a
8031 file.  These Guile procedures simply open a file, allow writing to the
8032 file (one string per line), and close the file.  Note that because we
8033 cannot store complex values such as Guile ports in @code{make}
8034 variables, we'll keep the port as a global variable in the Guile
8035 interpreter.
8037 You can create Guile functions easily using @code{define}/@code{endef}
8038 to create a Guile script, then use the @code{guile} function to
8039 internalize it:
8041 @example
8042 @group
8043 define GUILEIO
8044 ;; A simple Guile IO library for GNU make
8046 (define MKPORT #f)
8048 (define (mkopen name mode)
8049   (set! MKPORT (open-file name mode))
8050   #f)
8052 (define (mkwrite s)
8053   (display s MKPORT)
8054   (newline MKPORT)
8055   #f)
8057 (define (mkclose)
8058   (close-port MKPORT)
8059   #f)
8062 endef
8064 # Internalize the Guile IO functions
8065 $(guile $(GUILEIO))
8066 @end group
8067 @end example
8069 If you have a significant amount of Guile support code, you might
8070 consider keeping it in a different file (e.g., @file{guileio.scm}) and
8071 then loading it in your makefile using the @code{guile} function:
8073 @example
8074 $(guile (load "guileio.scm"))
8075 @end example
8077 An advantage to this method is that when editing @file{guileio.scm},
8078 your editor will understand that this file contains Scheme syntax
8079 rather than makefile syntax.
8081 Now you can use these Guile functions to create files.  Suppose you
8082 need to operate on a very large list, which cannot fit on the command
8083 line, but the utility you're using accepts the list as input as well:
8085 @example
8086 @group
8087 prog: $(PREREQS)
8088         @@$(guile (mkopen "tmp.out" "w")) \
8089          $(foreach X,$^,$(guile (mkwrite "$(X)"))) \
8090          $(guile (mkclose))
8091         $(LINK) < tmp.out
8092 @end group
8093 @end example
8095 A more comprehensive suite of file manipulation procedures is possible
8096 of course.  You could, for example, maintain multiple output files at
8097 the same time by choosing a symbol for each one and using it as the
8098 key to a hash table, where the value is a port, then returning the
8099 symbol to be stored in a @code{make} variable.
8102 @node Running, Implicit Rules, Functions, Top
8103 @chapter How to Run @code{make}
8105 A makefile that says how to recompile a program can be used in more
8106 than one way.  The simplest use is to recompile every file that is out
8107 of date.  Usually, makefiles are written so that if you run
8108 @code{make} with no arguments, it does just that.
8110 But you might want to update only some of the files; you might want to use
8111 a different compiler or different compiler options; you might want just to
8112 find out which files are out of date without changing them.
8114 By giving arguments when you run @code{make}, you can do any of these
8115 things and many others.
8117 @cindex exit status of make
8118 The exit status of @code{make} is always one of three values:
8119 @table @code
8120 @item 0
8121 The exit status is zero if @code{make} is successful.
8122 @item 2
8123 The exit status is two if @code{make} encounters any errors.
8124 It will print messages describing the particular errors.
8125 @item 1
8126 The exit status is one if you use the @samp{-q} flag and @code{make}
8127 determines that some target is not already up to date.
8128 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8129 @end table
8131 @menu
8132 * Makefile Arguments::          How to specify which makefile to use.
8133 * Goals::                       How to use goal arguments to specify which
8134                                   parts of the makefile to use.
8135 * Instead of Execution::        How to use mode flags to specify what
8136                                   kind of thing to do with the recipes
8137                                   in the makefile other than simply
8138                                   execute them.
8139 * Avoiding Compilation::        How to avoid recompiling certain files.
8140 * Overriding::                  How to override a variable to specify
8141                                   an alternate compiler and other things.
8142 * Testing::                     How to proceed past some errors, to
8143                                   test compilation.
8144 * Options Summary::             Summary of Options
8145 @end menu
8147 @node Makefile Arguments, Goals, Running, Running
8148 @section Arguments to Specify the Makefile
8149 @cindex @code{--file}
8150 @cindex @code{--makefile}
8151 @cindex @code{-f}
8153 The way to specify the name of the makefile is with the @samp{-f} or
8154 @samp{--file} option (@samp{--makefile} also works).  For example,
8155 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
8157 If you use the @samp{-f} flag several times and follow each @samp{-f}
8158 with an argument, all the specified files are used jointly as
8159 makefiles.
8161 If you do not use the @samp{-f} or @samp{--file} flag, the default is
8162 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
8163 that order, and use the first of these three which exists or can be made
8164 (@pxref{Makefiles, ,Writing Makefiles}).@refill
8166 @node Goals, Instead of Execution, Makefile Arguments, Running
8167 @section Arguments to Specify the Goals
8168 @cindex goal, how to specify
8170 The @dfn{goals} are the targets that @code{make} should strive ultimately
8171 to update.  Other targets are updated as well if they appear as
8172 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
8174 By default, the goal is the first target in the makefile (not counting
8175 targets that start with a period).  Therefore, makefiles are usually
8176 written so that the first target is for compiling the entire program or
8177 programs they describe.  If the first rule in the makefile has several
8178 targets, only the first target in the rule becomes the default goal, not
8179 the whole list.  You can manage the selection of the default goal from
8180 within your makefile using the @code{.DEFAULT_GOAL} variable
8181 (@pxref{Special Variables, , Other Special Variables}).
8183 You can also specify a different goal or goals with command line
8184 arguments to @code{make}.  Use the name of the goal as an argument.
8185 If you specify several goals, @code{make} processes each of them in
8186 turn, in the order you name them.
8188 Any target in the makefile may be specified as a goal (unless it
8189 starts with @samp{-} or contains an @samp{=}, in which case it will be
8190 parsed as a switch or variable definition, respectively).  Even
8191 targets not in the makefile may be specified, if @code{make} can find
8192 implicit rules that say how to make them.
8194 @vindex MAKECMDGOALS
8195 @code{Make} will set the special variable @code{MAKECMDGOALS} to the
8196 list of goals you specified on the command line.  If no goals were given
8197 on the command line, this variable is empty.  Note that this variable
8198 should be used only in special circumstances.
8200 An example of appropriate use is to avoid including @file{.d} files
8201 during @code{clean} rules (@pxref{Automatic Prerequisites}), so
8202 @code{make} won't create them only to immediately remove them
8203 again:@refill
8205 @example
8206 @group
8207 sources = foo.c bar.c
8209 ifneq ($(MAKECMDGOALS),clean)
8210 include $(sources:.c=.d)
8211 endif
8212 @end group
8213 @end example
8215 One use of specifying a goal is if you want to compile only a part of
8216 the program, or only one of several programs.  Specify as a goal each
8217 file that you wish to remake.  For example, consider a directory containing
8218 several programs, with a makefile that starts like this:
8220 @example
8221 .PHONY: all
8222 all: size nm ld ar as
8223 @end example
8225 If you are working on the program @code{size}, you might want to say
8226 @w{@samp{make size}} so that only the files of that program are recompiled.
8228 Another use of specifying a goal is to make files that are not normally
8229 made.  For example, there may be a file of debugging output, or a
8230 version of the program that is compiled specially for testing, which has
8231 a rule in the makefile but is not a prerequisite of the default goal.
8233 Another use of specifying a goal is to run the recipe associated with
8234 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
8235 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
8236 a phony target named @file{clean} which deletes everything except source
8237 files.  Naturally, this is done only if you request it explicitly with
8238 @w{@samp{make clean}}.  Following is a list of typical phony and empty
8239 target names.  @xref{Standard Targets}, for a detailed list of all the
8240 standard target names which GNU software packages use.
8242 @table @file
8243 @item all
8244 @cindex @code{all} @r{(standard target)}
8245 Make all the top-level targets the makefile knows about.
8247 @item clean
8248 @cindex @code{clean} @r{(standard target)}
8249 Delete all files that are normally created by running @code{make}.
8251 @item mostlyclean
8252 @cindex @code{mostlyclean} @r{(standard target)}
8253 Like @samp{clean}, but may refrain from deleting a few files that people
8254 normally don't want to recompile.  For example, the @samp{mostlyclean}
8255 target for GCC does not delete @file{libgcc.a}, because recompiling it
8256 is rarely necessary and takes a lot of time.
8258 @item distclean
8259 @cindex @code{distclean} @r{(standard target)}
8260 @itemx realclean
8261 @cindex @code{realclean} @r{(standard target)}
8262 @itemx clobber
8263 @cindex @code{clobber} @r{(standard target)}
8264 Any of these targets might be defined to delete @emph{more} files than
8265 @samp{clean} does.  For example, this would delete configuration files
8266 or links that you would normally create as preparation for compilation,
8267 even if the makefile itself cannot create these files.
8269 @item install
8270 @cindex @code{install} @r{(standard target)}
8271 Copy the executable file into a directory that users typically search
8272 for commands; copy any auxiliary files that the executable uses into
8273 the directories where it will look for them.
8275 @item print
8276 @cindex @code{print} @r{(standard target)}
8277 Print listings of the source files that have changed.
8279 @item tar
8280 @cindex @code{tar} @r{(standard target)}
8281 Create a tar file of the source files.
8283 @item shar
8284 @cindex @code{shar} @r{(standard target)}
8285 Create a shell archive (shar file) of the source files.
8287 @item dist
8288 @cindex @code{dist} @r{(standard target)}
8289 Create a distribution file of the source files.  This might
8290 be a tar file, or a shar file, or a compressed version of one of the
8291 above, or even more than one of the above.
8293 @item TAGS
8294 @cindex @code{TAGS} @r{(standard target)}
8295 Update a tags table for this program.
8297 @item check
8298 @cindex @code{check} @r{(standard target)}
8299 @itemx test
8300 @cindex @code{test} @r{(standard target)}
8301 Perform self tests on the program this makefile builds.
8302 @end table
8304 @node Instead of Execution, Avoiding Compilation, Goals, Running
8305 @section Instead of Executing Recipes
8306 @cindex execution, instead of
8307 @cindex recipes, instead of executing
8309 The makefile tells @code{make} how to tell whether a target is up to date,
8310 and how to update each target.  But updating the targets is not always
8311 what you want.  Certain options specify other activities for @code{make}.
8313 @comment Extra blank lines make it print better.
8314 @table @samp
8315 @item -n
8316 @itemx --just-print
8317 @itemx --dry-run
8318 @itemx --recon
8319 @cindex @code{--just-print}
8320 @cindex @code{--dry-run}
8321 @cindex @code{--recon}
8322 @cindex @code{-n}
8324 ``No-op''.  Causes @code{make} to print the recipes that are needed to
8325 make the targets up to date, but not actually execute them.  Note that
8326 some recipes are still executed, even with this flag (@pxref{MAKE
8327 Variable, ,How the @code{MAKE} Variable Works}).  Also any recipes
8328 needed to update included makefiles are still executed
8329 (@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).
8331 @item -t
8332 @itemx --touch
8333 @cindex @code{--touch}
8334 @cindex touching files
8335 @cindex target, touching
8336 @cindex @code{-t}
8338 ``Touch''.  Marks targets as up to date without actually changing
8339 them.  In other words, @code{make} pretends to update the targets but
8340 does not really change their contents; instead only their modified
8341 times are updated.
8343 @item -q
8344 @itemx --question
8345 @cindex @code{--question}
8346 @cindex @code{-q}
8347 @cindex question mode
8349 ``Question''.  Silently check whether the targets are up to date, but
8350 do not execute recipes; the exit code shows whether any updates are
8351 needed.
8353 @item -W @var{file}
8354 @itemx --what-if=@var{file}
8355 @itemx --assume-new=@var{file}
8356 @itemx --new-file=@var{file}
8357 @cindex @code{--what-if}
8358 @cindex @code{-W}
8359 @cindex @code{--assume-new}
8360 @cindex @code{--new-file}
8361 @cindex what if
8362 @cindex files, assuming new
8364 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
8365 files' modification times are recorded by @code{make} as being the present
8366 time, although the actual modification times remain the same.
8367 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
8368 to see what would happen if you were to modify specific files.@refill
8369 @end table
8371 With the @samp{-n} flag, @code{make} prints the recipe that it would
8372 normally execute but usually does not execute it.
8374 With the @samp{-t} flag, @code{make} ignores the recipes in the rules
8375 and uses (in effect) the command @code{touch} for each target that needs to
8376 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
8377 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
8378 the program @code{touch}.  It does the work directly.
8380 With the @samp{-q} flag, @code{make} prints nothing and executes no
8381 recipes, but the exit status code it returns is zero if and only if the
8382 targets to be considered are already up to date.  If the exit status is
8383 one, then some updating needs to be done.  If @code{make} encounters an
8384 error, the exit status is two, so you can distinguish an error from a
8385 target that is not up to date.
8387 It is an error to use more than one of these three flags in the same
8388 invocation of @code{make}.
8390 @cindex +, and recipe execution
8391 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect recipe
8392 lines that begin with @samp{+} characters or contain the strings
8393 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
8394 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
8395 is run regardless of these options.  Other lines in the same rule are
8396 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
8397 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
8399 @cindex phony targets and recipe execution
8400 The @samp{-t} flag prevents phony targets (@pxref{Phony Targets}) from
8401 being updated, unless there are recipe lines beginning with @samp{+}
8402 or containing @samp{$(MAKE)} or @samp{$@{MAKE@}}.
8404 The @samp{-W} flag provides two features:
8406 @itemize @bullet
8407 @item
8408 If you also use the @samp{-n} or @samp{-q} flag, you can see what
8409 @code{make} would do if you were to modify some files.
8411 @item
8412 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
8413 executing recipes, the @samp{-W} flag can direct @code{make} to act as
8414 if some files had been modified, without actually running the recipes
8415 for those files.@refill
8416 @end itemize
8418 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
8419 information about @code{make} or about the makefiles in use
8420 (@pxref{Options Summary, ,Summary of Options}).@refill
8422 @node Avoiding Compilation, Overriding, Instead of Execution, Running
8423 @section Avoiding Recompilation of Some Files
8424 @cindex @code{-o}
8425 @cindex @code{--old-file}
8426 @cindex @code{--assume-old}
8427 @cindex files, assuming old
8428 @cindex files, avoiding recompilation of
8429 @cindex recompilation, avoiding
8431 Sometimes you may have changed a source file but you do not want to
8432 recompile all the files that depend on it.  For example, suppose you add
8433 a macro or a declaration to a header file that many other files depend
8434 on.  Being conservative, @code{make} assumes that any change in the
8435 header file requires recompilation of all dependent files, but you know
8436 that they do not need to be recompiled and you would rather not waste
8437 the time waiting for them to compile.
8439 If you anticipate the problem before changing the header file, you can
8440 use the @samp{-t} flag.  This flag tells @code{make} not to run the
8441 recipes in the rules, but rather to mark the target up to date by
8442 changing its last-modification date.  You would follow this procedure:
8444 @enumerate
8445 @item
8446 Use the command @samp{make} to recompile the source files that really
8447 need recompilation, ensuring that the object files are up-to-date
8448 before you begin.
8450 @item
8451 Make the changes in the header files.
8453 @item
8454 Use the command @samp{make -t} to mark all the object files as
8455 up to date.  The next time you run @code{make}, the changes in the
8456 header files will not cause any recompilation.
8457 @end enumerate
8459 If you have already changed the header file at a time when some files
8460 do need recompilation, it is too late to do this.  Instead, you can
8461 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
8462 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
8463 that the file itself will not be remade, and nothing else will be
8464 remade on its account.  Follow this procedure:
8466 @enumerate
8467 @item
8468 Recompile the source files that need compilation for reasons independent
8469 of the particular header file, with @samp{make -o @var{headerfile}}.
8470 If several header files are involved, use a separate @samp{-o} option
8471 for each header file.
8473 @item
8474 Touch all the object files with @samp{make -t}.
8475 @end enumerate
8477 @node Overriding, Testing, Avoiding Compilation, Running
8478 @section Overriding Variables
8479 @cindex overriding variables with arguments
8480 @cindex variables, overriding with arguments
8481 @cindex command line variables
8482 @cindex variables, command line
8484 An argument that contains @samp{=} specifies the value of a variable:
8485 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
8486 If you specify a value in this way, all ordinary assignments of the same
8487 variable in the makefile are ignored; we say they have been
8488 @dfn{overridden} by the command line argument.
8490 The most common way to use this facility is to pass extra flags to
8491 compilers.  For example, in a properly written makefile, the variable
8492 @code{CFLAGS} is included in each recipe that runs the C compiler, so a
8493 file @file{foo.c} would be compiled something like this:
8495 @example
8496 cc -c $(CFLAGS) foo.c
8497 @end example
8499 Thus, whatever value you set for @code{CFLAGS} affects each compilation
8500 that occurs.  The makefile probably specifies the usual value for
8501 @code{CFLAGS}, like this:
8503 @example
8504 CFLAGS=-g
8505 @end example
8507 Each time you run @code{make}, you can override this value if you
8508 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
8509 compilation will be done with @samp{cc -c -g -O}.  (This also
8510 illustrates how you can use quoting in the shell to enclose spaces and
8511 other special characters in the value of a variable when you override
8512 it.)
8514 The variable @code{CFLAGS} is only one of many standard variables that
8515 exist just so that you can change them this way.  @xref{Implicit
8516 Variables, , Variables Used by Implicit Rules}, for a complete list.
8518 You can also program the makefile to look at additional variables of your
8519 own, giving the user the ability to control other aspects of how the
8520 makefile works by changing the variables.
8522 When you override a variable with a command line argument, you can
8523 define either a recursively-expanded variable or a simply-expanded
8524 variable.  The examples shown above make a recursively-expanded
8525 variable; to make a simply-expanded variable, write @samp{:=} or
8526 @samp{::=} instead of @samp{=}.  But, unless you want to include a
8527 variable reference or function call in the @emph{value} that you
8528 specify, it makes no difference which kind of variable you create.
8530 There is one way that the makefile can change a variable that you have
8531 overridden.  This is to use the @code{override} directive, which is a line
8532 that looks like this: @samp{override @var{variable} = @var{value}}
8533 (@pxref{Override Directive, ,The @code{override} Directive}).
8535 @node Testing, Options Summary, Overriding, Running
8536 @section Testing the Compilation of a Program
8537 @cindex testing compilation
8538 @cindex compilation, testing
8540 Normally, when an error happens in executing a shell command, @code{make}
8541 gives up immediately, returning a nonzero status.  No further recipes are
8542 executed for any target.  The error implies that the goal cannot be
8543 correctly remade, and @code{make} reports this as soon as it knows.
8545 When you are compiling a program that you have just changed, this is not
8546 what you want.  Instead, you would rather that @code{make} try compiling
8547 every file that can be tried, to show you as many compilation errors
8548 as possible.
8550 @cindex @code{-k}
8551 @cindex @code{--keep-going}
8552 On these occasions, you should use the @samp{-k} or
8553 @samp{--keep-going} flag.  This tells @code{make} to continue to
8554 consider the other prerequisites of the pending targets, remaking them
8555 if necessary, before it gives up and returns nonzero status.  For
8556 example, after an error in compiling one object file, @samp{make -k}
8557 will continue compiling other object files even though it already
8558 knows that linking them will be impossible.  In addition to continuing
8559 after failed shell commands, @samp{make -k} will continue as much as
8560 possible after discovering that it does not know how to make a target
8561 or prerequisite file.  This will always cause an error message, but
8562 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
8563 ,Summary of Options}).@refill
8565 The usual behavior of @code{make} assumes that your purpose is to get the
8566 goals up to date; once @code{make} learns that this is impossible, it might
8567 as well report the failure immediately.  The @samp{-k} flag says that the
8568 real purpose is to test as much as possible of the changes made in the
8569 program, perhaps to find several independent problems so that you can
8570 correct them all before the next attempt to compile.  This is why Emacs'
8571 @kbd{M-x compile} command passes the @samp{-k} flag by default.
8573 @node Options Summary,  , Testing, Running
8574 @section Summary of Options
8575 @cindex options
8576 @cindex flags
8577 @cindex switches
8579 Here is a table of all the options @code{make} understands:
8581 @table @samp
8582 @item -b
8583 @cindex @code{-b}
8584 @itemx -m
8585 @cindex @code{-m}
8586 These options are ignored for compatibility with other versions of @code{make}.
8588 @item -B
8589 @cindex @code{-B}
8590 @itemx --always-make
8591 @cindex @code{--always-make}
8592 Consider all targets out-of-date.  GNU @code{make} proceeds to
8593 consider targets and their prerequisites using the normal algorithms;
8594 however, all targets so considered are always remade regardless of the
8595 status of their prerequisites.  To avoid infinite recursion, if
8596 @code{MAKE_RESTARTS} (@pxref{Special Variables, , Other Special
8597 Variables}) is set to a number greater than 0 this option is disabled
8598 when considering whether to remake makefiles (@pxref{Remaking
8599 Makefiles, , How Makefiles Are Remade}).
8601 @item -C @var{dir}
8602 @cindex @code{-C}
8603 @itemx --directory=@var{dir}
8604 @cindex @code{--directory}
8605 Change to directory @var{dir} before reading the makefiles.  If multiple
8606 @samp{-C} options are specified, each is interpreted relative to the
8607 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
8608 This is typically used with recursive invocations of @code{make}
8609 (@pxref{Recursion, ,Recursive Use of @code{make}}).
8611 @item -d
8612 @cindex @code{-d}
8613 @c Extra blank line here makes the table look better.
8615 Print debugging information in addition to normal processing.  The
8616 debugging information says which files are being considered for
8617 remaking, which file-times are being compared and with what results,
8618 which files actually need to be remade, which implicit rules are
8619 considered and which are applied---everything interesting about how
8620 @code{make} decides what to do.  The @code{-d} option is equivalent to
8621 @samp{--debug=a} (see below).
8623 @item --debug[=@var{options}]
8624 @cindex @code{--debug}
8625 @c Extra blank line here makes the table look better.
8627 Print debugging information in addition to normal processing.  Various
8628 levels and types of output can be chosen.  With no arguments, print the
8629 ``basic'' level of debugging.  Possible arguments are below; only the
8630 first character is considered, and values must be comma- or
8631 space-separated.
8633 @table @code
8634 @item a (@i{all})
8635 All types of debugging output are enabled.  This is equivalent to using
8636 @samp{-d}.
8638 @item b (@i{basic})
8639 Basic debugging prints each target that was found to be out-of-date, and
8640 whether the build was successful or not.
8642 @item v (@i{verbose})
8643 A level above @samp{basic}; includes messages about which makefiles were
8644 parsed, prerequisites that did not need to be rebuilt, etc.  This option
8645 also enables @samp{basic} messages.
8647 @item i (@i{implicit})
8648 Prints messages describing the implicit rule searches for each target.
8649 This option also enables @samp{basic} messages.
8651 @item j (@i{jobs})
8652 Prints messages giving details on the invocation of specific sub-commands.
8654 @item m (@i{makefile})
8655 By default, the above messages are not enabled while trying to remake
8656 the makefiles.  This option enables messages while rebuilding makefiles,
8657 too.  Note that the @samp{all} option does enable this option.  This
8658 option also enables @samp{basic} messages.
8659 @end table
8661 @item -e
8662 @cindex @code{-e}
8663 @itemx --environment-overrides
8664 @cindex @code{--environment-overrides}
8665 Give variables taken from the environment precedence
8666 over variables from makefiles.
8667 @xref{Environment, ,Variables from the Environment}.
8669 @item --eval=@var{string}
8670 @cindex @code{--eval}
8671 @c Extra blank line here makes the table look better.
8673 Evaluate @var{string} as makefile syntax.  This is a command-line
8674 version of the @code{eval} function (@pxref{Eval Function}).  The
8675 evaluation is performed after the default rules and variables have
8676 been defined, but before any makefiles are read.
8678 @item -f @var{file}
8679 @cindex @code{-f}
8680 @itemx --file=@var{file}
8681 @cindex @code{--file}
8682 @itemx --makefile=@var{file}
8683 @cindex @code{--makefile}
8684 Read the file named @var{file} as a makefile.
8685 @xref{Makefiles, ,Writing Makefiles}.
8687 @item -h
8688 @cindex @code{-h}
8689 @itemx --help
8690 @cindex @code{--help}
8691 @c Extra blank line here makes the table look better.
8693 Remind you of the options that @code{make} understands and then exit.
8695 @item -i
8696 @cindex @code{-i}
8697 @itemx --ignore-errors
8698 @cindex @code{--ignore-errors}
8699 Ignore all errors in recipes executed to remake files.
8700 @xref{Errors, ,Errors in Recipes}.
8702 @item -I @var{dir}
8703 @cindex @code{-I}
8704 @itemx --include-dir=@var{dir}
8705 @cindex @code{--include-dir}
8706 Specifies a directory @var{dir} to search for included makefiles.
8707 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
8708 options are used to specify several directories, the directories are
8709 searched in the order specified.
8711 @item -j [@var{jobs}]
8712 @cindex @code{-j}
8713 @itemx --jobs[=@var{jobs}]
8714 @cindex @code{--jobs}
8715 Specifies the number of recipes (jobs) to run simultaneously.  With no
8716 argument, @code{make} runs as many recipes simultaneously as possible.
8717 If there is more than one @samp{-j} option, the last one is effective.
8718 @xref{Parallel, ,Parallel Execution}, for more information on how
8719 recipes are run.  Note that this option is ignored on MS-DOS.
8721 @item -k
8722 @cindex @code{-k}
8723 @itemx --keep-going
8724 @cindex @code{--keep-going}
8725 Continue as much as possible after an error.  While the target that
8726 failed, and those that depend on it, cannot be remade, the other
8727 prerequisites of these targets can be processed all the same.
8728 @xref{Testing, ,Testing the Compilation of a Program}.
8730 @item -l [@var{load}]
8731 @cindex @code{-l}
8732 @itemx --load-average[=@var{load}]
8733 @cindex @code{--load-average}
8734 @itemx --max-load[=@var{load}]
8735 @cindex @code{--max-load}
8736 Specifies that no new recipes should be started if there are other
8737 recipes running and the load average is at least @var{load} (a
8738 floating-point number).  With no argument, removes a previous load
8739 limit.  @xref{Parallel, ,Parallel Execution}.
8741 @item -L
8742 @cindex @code{-L}
8743 @itemx --check-symlink-times
8744 @cindex @code{--check-symlink-times}
8745 On systems that support symbolic links, this option causes @code{make}
8746 to consider the timestamps on any symbolic links in addition to the
8747 timestamp on the file referenced by those links.  When this option is
8748 provided, the most recent timestamp among the file and the symbolic
8749 links is taken as the modification time for this target file.
8751 @item -n
8752 @cindex @code{-n}
8753 @itemx --just-print
8754 @cindex @code{--just-print}
8755 @itemx --dry-run
8756 @cindex @code{--dry-run}
8757 @itemx --recon
8758 @cindex @code{--recon}
8759 @c Extra blank line here makes the table look better.
8761 Print the recipe that would be executed, but do not execute it (except
8762 in certain circumstances).
8763 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8765 @item -o @var{file}
8766 @cindex @code{-o}
8767 @itemx --old-file=@var{file}
8768 @cindex @code{--old-file}
8769 @itemx --assume-old=@var{file}
8770 @cindex @code{--assume-old}
8771 Do not remake the file @var{file} even if it is older than its
8772 prerequisites, and do not remake anything on account of changes in
8773 @var{file}.  Essentially the file is treated as very old and its rules
8774 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
8775 Some Files}.@refill
8777 @item -p
8778 @cindex @code{-p}
8779 @itemx --print-data-base
8780 @cindex @code{--print-data-base}
8781 @cindex data base of @code{make} rules
8782 @cindex predefined rules and variables, printing
8783 Print the data base (rules and variable values) that results from
8784 reading the makefiles; then execute as usual or as otherwise
8785 specified.  This also prints the version information given by the
8786 @samp{-v} switch (see below).  To print the data base without trying
8787 to remake any files, use @w{@samp{make -qp}}.  To print the data base
8788 of predefined rules and variables, use @w{@samp{make -p -f /dev/null}}.
8789 The data base output contains file name and line number information for
8790 recipe and variable definitions, so it can be a useful debugging tool
8791 in complex environments.
8793 @item -q
8794 @cindex @code{-q}
8795 @itemx --question
8796 @cindex @code{--question}
8797 ``Question mode''.  Do not run any recipes, or print anything; just
8798 return an exit status that is zero if the specified targets are already
8799 up to date, one if any remaking is required, or two if an error is
8800 encountered.  @xref{Instead of Execution, ,Instead of Executing
8801 Recipes}.@refill
8803 @item -r
8804 @cindex @code{-r}
8805 @itemx --no-builtin-rules
8806 @cindex @code{--no-builtin-rules}
8807 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
8808 ,Using Implicit Rules}).  You can still define your own by writing
8809 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
8810 Rules}).  The @samp{-r} option also clears out the default list of
8811 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
8812 Rules}).  But you can still define your own suffixes with a rule for
8813 @code{.SUFFIXES}, and then define your own suffix rules.  Note that only
8814 @emph{rules} are affected by the @code{-r} option; default variables
8815 remain in effect (@pxref{Implicit Variables, ,Variables Used by Implicit
8816 Rules}); see the @samp{-R} option below.
8818 @item -R
8819 @cindex @code{-R}
8820 @itemx --no-builtin-variables
8821 @cindex @code{--no-builtin-variables}
8822 Eliminate use of the built-in rule-specific variables (@pxref{Implicit
8823 Variables, ,Variables Used by Implicit Rules}).  You can still define
8824 your own, of course.  The @samp{-R} option also automatically enables
8825 the @samp{-r} option (see above), since it doesn't make sense to have
8826 implicit rules without any definitions for the variables that they use.
8828 @item -s
8829 @cindex @code{-s}
8830 @itemx --silent
8831 @cindex @code{--silent}
8832 @itemx --quiet
8833 @cindex @code{--quiet}
8834 @c Extra blank line here makes the table look better.
8836 Silent operation; do not print the recipes as they are executed.
8837 @xref{Echoing, ,Recipe Echoing}.
8839 @item -S
8840 @cindex @code{-S}
8841 @itemx --no-keep-going
8842 @cindex @code{--no-keep-going}
8843 @itemx --stop
8844 @cindex @code{--stop}
8845 @c Extra blank line here makes the table look better.
8847 Cancel the effect of the @samp{-k} option.  This is never necessary
8848 except in a recursive @code{make} where @samp{-k} might be inherited
8849 from the top-level @code{make} via @code{MAKEFLAGS}
8850 (@pxref{Recursion, ,Recursive Use of @code{make}})
8851 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.@refill
8853 @item -t
8854 @cindex @code{-t}
8855 @itemx --touch
8856 @cindex @code{--touch}
8857 @c Extra blank line here makes the table look better.
8859 Touch files (mark them up to date without really changing them)
8860 instead of running their recipes.  This is used to pretend that the
8861 recipes were done, in order to fool future invocations of
8862 @code{make}.  @xref{Instead of Execution, ,Instead of Executing Recipes}.
8864 @item --trace
8865 @cindex @code{--trace}
8866 @c Extra blank line here makes the table look better.
8868 Print the entire recipe to be executed, even for recipes that are
8869 normally silent (due to @code{.SILENT} or @samp{@@}).  Also print the
8870 makefile name and line number where the recipe was defined.
8872 @item -v
8873 @cindex @code{-v}
8874 @itemx --version
8875 @cindex @code{--version}
8876 Print the version of the @code{make} program plus a copyright, a list
8877 of authors, and a notice that there is no warranty; then exit.
8879 @item -w
8880 @cindex @code{-w}
8881 @itemx --print-directory
8882 @cindex @code{--print-directory}
8883 Print a message containing the working directory both before and after
8884 executing the makefile.  This may be useful for tracking down errors
8885 from complicated nests of recursive @code{make} commands.
8886 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
8887 rarely need to specify this option since @samp{make} does it for you;
8888 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
8890 @itemx --no-print-directory
8891 @cindex @code{--no-print-directory}
8892 Disable printing of the working directory under @code{-w}.
8893 This option is useful when @code{-w} is turned on automatically,
8894 but you do not want to see the extra messages.
8895 @xref{-w Option, ,The @samp{--print-directory} Option}.
8897 @item -W @var{file}
8898 @cindex @code{-W}
8899 @itemx --what-if=@var{file}
8900 @cindex @code{--what-if}
8901 @itemx --new-file=@var{file}
8902 @cindex @code{--new-file}
8903 @itemx --assume-new=@var{file}
8904 @cindex @code{--assume-new}
8905 Pretend that the target @var{file} has just been modified.  When used
8906 with the @samp{-n} flag, this shows you what would happen if you were
8907 to modify that file.  Without @samp{-n}, it is almost the same as
8908 running a @code{touch} command on the given file before running
8909 @code{make}, except that the modification time is changed only in the
8910 imagination of @code{make}.
8911 @xref{Instead of Execution, ,Instead of Executing Recipes}.
8913 @item --warn-undefined-variables
8914 @cindex @code{--warn-undefined-variables}
8915 @cindex variables, warning for undefined
8916 @cindex undefined variables, warning message
8917 Issue a warning message whenever @code{make} sees a reference to an
8918 undefined variable.  This can be helpful when you are trying to debug
8919 makefiles which use variables in complex ways.
8920 @end table
8922 @node Implicit Rules, Archives, Running, Top
8923 @chapter Using Implicit Rules
8924 @cindex implicit rule
8925 @cindex rule, implicit
8927 Certain standard ways of remaking target files are used very often.  For
8928 example, one customary way to make an object file is from a C source file
8929 using the C compiler, @code{cc}.
8931 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
8932 that you do not have to specify them in detail when you want to use
8933 them.  For example, there is an implicit rule for C compilation.  File
8934 names determine which implicit rules are run.  For example, C
8935 compilation typically takes a @file{.c} file and makes a @file{.o} file.
8936 So @code{make} applies the implicit rule for C compilation when it sees
8937 this combination of file name endings.@refill
8939 A chain of implicit rules can apply in sequence; for example, @code{make}
8940 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
8941 @iftex
8942 @xref{Chained Rules, ,Chains of Implicit Rules}.
8943 @end iftex
8945 The built-in implicit rules use several variables in their recipes so
8946 that, by changing the values of the variables, you can change the way the
8947 implicit rule works.  For example, the variable @code{CFLAGS} controls the
8948 flags given to the C compiler by the implicit rule for C compilation.
8949 @iftex
8950 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
8951 @end iftex
8953 You can define your own implicit rules by writing @dfn{pattern rules}.
8954 @iftex
8955 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
8956 @end iftex
8958 @dfn{Suffix rules} are a more limited way to define implicit rules.
8959 Pattern rules are more general and clearer, but suffix rules are
8960 retained for compatibility.
8961 @iftex
8962 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
8963 @end iftex
8965 @menu
8966 * Using Implicit::              How to use an existing implicit rule
8967                                   to get the recipes for updating a file.
8968 * Catalogue of Rules::          A list of built-in implicit rules.
8969 * Implicit Variables::          How to change what predefined rules do.
8970 * Chained Rules::               How to use a chain of implicit rules.
8971 * Pattern Rules::               How to define new implicit rules.
8972 * Last Resort::                 How to define a recipe for rules which
8973                                   cannot find any.
8974 * Suffix Rules::                The old-fashioned style of implicit rule.
8975 * Implicit Rule Search::        The precise algorithm for applying
8976                                   implicit rules.
8977 @end menu
8979 @node Using Implicit, Catalogue of Rules, Implicit Rules, Implicit Rules
8980 @section Using Implicit Rules
8981 @cindex implicit rule, how to use
8982 @cindex rule, implicit, how to use
8984 To allow @code{make} to find a customary method for updating a target
8985 file, all you have to do is refrain from specifying recipes yourself.
8986 Either write a rule with no recipe, or don't write a rule at all.
8987 Then @code{make} will figure out which implicit rule to use based on
8988 which kind of source file exists or can be made.
8990 For example, suppose the makefile looks like this:
8992 @example
8993 foo : foo.o bar.o
8994         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
8995 @end example
8997 @noindent
8998 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
8999 will automatically look for an implicit rule that tells how to update it.
9000 This happens whether or not the file @file{foo.o} currently exists.
9002 If an implicit rule is found, it can supply both a recipe and one or
9003 more prerequisites (the source files).  You would want to write a rule
9004 for @file{foo.o} with no recipe if you need to specify additional
9005 prerequisites, such as header files, that the implicit rule cannot
9006 supply.
9008 Each implicit rule has a target pattern and prerequisite patterns.  There may
9009 be many implicit rules with the same target pattern.  For example, numerous
9010 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
9011 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
9012 that actually applies is the one whose prerequisites exist or can be made.
9013 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
9014 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
9015 compiler; and so on.
9017 Of course, when you write the makefile, you know which implicit rule you
9018 want @code{make} to use, and you know it will choose that one because you
9019 know which possible prerequisite files are supposed to exist.
9020 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
9021 for a catalogue of all the predefined implicit rules.
9023 Above, we said an implicit rule applies if the required prerequisites ``exist
9024 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
9025 the makefile as a target or a prerequisite, or if an implicit rule can be
9026 recursively found for how to make it.  When an implicit prerequisite is the
9027 result of another implicit rule, we say that @dfn{chaining} is occurring.
9028 @xref{Chained Rules, ,Chains of Implicit Rules}.
9030 In general, @code{make} searches for an implicit rule for each target, and
9031 for each double-colon rule, that has no recipe.  A file that is mentioned
9032 only as a prerequisite is considered a target whose rule specifies nothing,
9033 so implicit rule search happens for it.  @xref{Implicit Rule Search, ,Implicit Rule Search Algorithm}, for the
9034 details of how the search is done.
9036 Note that explicit prerequisites do not influence implicit rule search.
9037 For example, consider this explicit rule:
9039 @example
9040 foo.o: foo.p
9041 @end example
9043 @noindent
9044 The prerequisite on @file{foo.p} does not necessarily mean that
9045 @code{make} will remake @file{foo.o} according to the implicit rule to
9046 make an object file, a @file{.o} file, from a Pascal source file, a
9047 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
9048 rule to make an object file from a C source file is used instead,
9049 because it appears before the Pascal rule in the list of predefined
9050 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
9051 Rules}).
9053 If you do not want an implicit rule to be used for a target that has no
9054 recipe, you can give that target an empty recipe by writing a semicolon
9055 (@pxref{Empty Recipes, ,Defining Empty Recipes}).
9057 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
9058 @section Catalogue of Implicit Rules
9059 @cindex implicit rule, predefined
9060 @cindex rule, implicit, predefined
9062 Here is a catalogue of predefined implicit rules which are always
9063 available unless the makefile explicitly overrides or cancels them.
9064 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
9065 canceling or overriding an implicit rule.  The @samp{-r} or
9066 @samp{--no-builtin-rules} option cancels all predefined rules.
9068 This manual only documents the default rules available on POSIX-based
9069 operating systems.  Other operating systems, such as VMS, Windows,
9070 OS/2, etc. may have different sets of default rules.  To see the full
9071 list of default rules and variables available in your version of GNU
9072 @code{make}, run @samp{make -p} in a directory with no makefile.
9074 Not all of these rules will always be defined, even when the @samp{-r}
9075 option is not given.  Many of the predefined implicit rules are
9076 implemented in @code{make} as suffix rules, so which ones will be
9077 defined depends on the @dfn{suffix list} (the list of prerequisites of
9078 the special target @code{.SUFFIXES}).  The default suffix list is:
9079 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
9080 @code{.C}, @code{.cpp}, @code{.p}, @code{.f}, @code{.F}, @code{.m},
9081 @code{.r}, @code{.y}, @code{.l}, @code{.ym}, @code{.lm}, @code{.s},
9082 @code{.S}, @code{.mod}, @code{.sym}, @code{.def}, @code{.h},
9083 @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo}, @code{.texi},
9084 @code{.txinfo}, @code{.w}, @code{.ch} @code{.web}, @code{.sh},
9085 @code{.elc}, @code{.el}.  All of the implicit rules described below
9086 whose prerequisites have one of these suffixes are actually suffix
9087 rules.  If you modify the suffix list, the only predefined suffix
9088 rules in effect will be those named by one or two of the suffixes that
9089 are on the list you specify; rules whose suffixes fail to be on the
9090 list are disabled.  @xref{Suffix Rules, ,Old-Fashioned Suffix Rules},
9091 for full details on suffix rules.
9093 @table @asis
9094 @item Compiling C programs
9095 @cindex C, rule to compile
9096 @pindex cc
9097 @pindex gcc
9098 @pindex .o
9099 @pindex .c
9100 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
9101 a recipe of the form @samp{$(CC) $(CPPFLAGS) $(CFLAGS) -c}.@refill
9103 @item Compiling C++ programs
9104 @cindex C++, rule to compile
9105 @pindex g++
9106 @pindex .cc
9107 @pindex .cpp
9108 @pindex .C
9109 @file{@var{n}.o} is made automatically from @file{@var{n}.cc},
9110 @file{@var{n}.cpp}, or @file{@var{n}.C} with a recipe of the form
9111 @samp{$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c}.  We encourage you to use the
9112 suffix @samp{.cc} for C++ source files instead of @samp{.C}.@refill
9114 @item Compiling Pascal programs
9115 @cindex Pascal, rule to compile
9116 @pindex pc
9117 @pindex .p
9118 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
9119 with the recipe @samp{$(PC) $(PFLAGS) -c}.@refill
9121 @item Compiling Fortran and Ratfor programs
9122 @cindex Fortran, rule to compile
9123 @cindex Ratfor, rule to compile
9124 @pindex f77
9125 @pindex .f
9126 @pindex .r
9127 @pindex .F
9128 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
9129 @file{@var{n}.F} or @file{@var{n}.f} by running the
9130 Fortran compiler.  The precise recipe used is as follows:@refill
9132 @table @samp
9133 @item .f
9134 @samp{$(FC) $(FFLAGS) -c}.
9135 @item .F
9136 @samp{$(FC) $(FFLAGS) $(CPPFLAGS) -c}.
9137 @item .r
9138 @samp{$(FC) $(FFLAGS) $(RFLAGS) -c}.
9139 @end table
9141 @item Preprocessing Fortran and Ratfor programs
9142 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
9143 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
9144 Ratfor or preprocessable Fortran program into a strict Fortran
9145 program.  The precise recipe used is as follows:@refill
9147 @table @samp
9148 @item .F
9149 @samp{$(FC) $(CPPFLAGS) $(FFLAGS) -F}.
9150 @item .r
9151 @samp{$(FC) $(FFLAGS) $(RFLAGS) -F}.
9152 @end table
9154 @item Compiling Modula-2 programs
9155 @cindex Modula-2, rule to compile
9156 @pindex m2c
9157 @pindex .sym
9158 @pindex .def
9159 @pindex .mod
9160 @file{@var{n}.sym} is made from @file{@var{n}.def} with a recipe
9161 of the form @samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}.  @file{@var{n}.o}
9162 is made from @file{@var{n}.mod}; the form is:
9163 @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.@refill
9165 @need 1200
9166 @item Assembling and preprocessing assembler programs
9167 @cindex assembly, rule to compile
9168 @pindex as
9169 @pindex .s
9170 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
9171 running the assembler, @code{as}.  The precise recipe is
9172 @samp{$(AS) $(ASFLAGS)}.@refill
9174 @pindex .S
9175 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
9176 running the C preprocessor, @code{cpp}.  The precise recipe is
9177 @w{@samp{$(CPP) $(CPPFLAGS)}}.
9179 @item Linking a single object file
9180 @cindex linking, predefined rule for
9181 @pindex ld
9182 @pindex .o
9183 @file{@var{n}} is made automatically from @file{@var{n}.o} by running
9184 the linker (usually called @code{ld}) via the C compiler.  The precise
9185 recipe used is @w{@samp{$(CC) $(LDFLAGS) @var{n}.o $(LOADLIBES) $(LDLIBS)}}.
9187 This rule does the right thing for a simple program with only one
9188 source file.  It will also do the right thing if there are multiple
9189 object files (presumably coming from various other source files), one
9190 of which has a name matching that of the executable file.  Thus,
9192 @example
9193 x: y.o z.o
9194 @end example
9196 @noindent
9197 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
9199 @example
9200 @group
9201 cc -c x.c -o x.o
9202 cc -c y.c -o y.o
9203 cc -c z.c -o z.o
9204 cc x.o y.o z.o -o x
9205 rm -f x.o
9206 rm -f y.o
9207 rm -f z.o
9208 @end group
9209 @end example
9211 @noindent
9212 In more complicated cases, such as when there is no object file whose
9213 name derives from the executable file name, you must write an explicit
9214 recipe for linking.
9216 Each kind of file automatically made into @samp{.o} object files will
9217 be automatically linked by using the compiler (@samp{$(CC)},
9218 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
9219 assemble @samp{.s} files) without the @samp{-c} option.  This could be
9220 done by using the @samp{.o} object files as intermediates, but it is
9221 faster to do the compiling and linking in one step, so that's how it's
9222 done.@refill
9224 @item Yacc for C programs
9225 @pindex yacc
9226 @cindex Yacc, rule to run
9227 @pindex .y
9228 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
9229 running Yacc with the recipe @samp{$(YACC) $(YFLAGS)}.
9231 @item Lex for C programs
9232 @pindex lex
9233 @cindex Lex, rule to run
9234 @pindex .l
9235 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
9236 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
9238 @item Lex for Ratfor programs
9239 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
9240 running Lex.  The actual recipe is @samp{$(LEX) $(LFLAGS)}.
9242 The convention of using the same suffix @samp{.l} for all Lex files
9243 regardless of whether they produce C code or Ratfor code makes it
9244 impossible for @code{make} to determine automatically which of the two
9245 languages you are using in any particular case.  If @code{make} is
9246 called upon to remake an object file from a @samp{.l} file, it must
9247 guess which compiler to use.  It will guess the C compiler, because
9248 that is more common.  If you are using Ratfor, make sure @code{make}
9249 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
9250 are using Ratfor exclusively, with no C files, remove @samp{.c} from
9251 the list of implicit rule suffixes with:@refill
9253 @example
9254 @group
9255 .SUFFIXES:
9256 .SUFFIXES: .o .r .f .l @dots{}
9257 @end group
9258 @end example
9260 @item Making Lint Libraries from C, Yacc, or Lex programs
9261 @pindex lint
9262 @cindex @code{lint}, rule to run
9263 @pindex .ln
9264 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
9265 The precise recipe is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.
9266 The same recipe is used on the C code produced from
9267 @file{@var{n}.y} or @file{@var{n}.l}.@refill
9269 @item @TeX{} and Web
9270 @cindex @TeX{}, rule to run
9271 @cindex Web, rule to run
9272 @pindex tex
9273 @pindex cweave
9274 @pindex weave
9275 @pindex tangle
9276 @pindex ctangle
9277 @pindex .dvi
9278 @pindex .tex
9279 @pindex .web
9280 @pindex .w
9281 @pindex .ch
9282 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the recipe
9283 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
9284 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
9285 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
9286 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
9287 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
9288 or can be made) with @samp{$(CTANGLE)}.@refill
9290 @item Texinfo and Info
9291 @cindex Texinfo, rule to format
9292 @cindex Info, rule to format
9293 @pindex texi2dvi
9294 @pindex makeinfo
9295 @pindex .texinfo
9296 @pindex .info
9297 @pindex .texi
9298 @pindex .txinfo
9299 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo},
9300 @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with the recipe
9301 @w{@samp{$(TEXI2DVI) $(TEXI2DVI_FLAGS)}}.  @file{@var{n}.info} is made from
9302 @file{@var{n}.texinfo}, @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with
9303 the recipe @w{@samp{$(MAKEINFO) $(MAKEINFO_FLAGS)}}.
9305 @item RCS
9306 @cindex RCS, rule to extract from
9307 @pindex co
9308 @pindex ,v @r{(RCS file extension)}
9309 Any file @file{@var{n}} is extracted if necessary from an RCS file
9310 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
9311 recipe used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
9312 extracted from RCS if it already exists, even if the RCS file is
9313 newer.  The rules for RCS are terminal
9314 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
9315 so RCS files cannot be generated from another source; they must
9316 actually exist.@refill
9318 @item SCCS
9319 @cindex SCCS, rule to extract from
9320 @pindex get
9321 @pindex s. @r{(SCCS file prefix)}
9322 Any file @file{@var{n}} is extracted if necessary from an SCCS file
9323 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
9324 recipe used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
9325 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
9326 so SCCS files cannot be generated from another source; they must
9327 actually exist.@refill
9329 @pindex .sh
9330 For the benefit of SCCS, a file @file{@var{n}} is copied from
9331 @file{@var{n}.sh} and made executable (by everyone).  This is for
9332 shell scripts that are checked into SCCS.  Since RCS preserves the
9333 execution permission of a file, you do not need to use this feature
9334 with RCS.@refill
9336 We recommend that you avoid using of SCCS.  RCS is widely held to be
9337 superior, and is also free.  By choosing free software in place of
9338 comparable (or inferior) proprietary software, you support the free
9339 software movement.
9340 @end table
9342 Usually, you want to change only the variables listed in the table
9343 above, which are documented in the following section.
9345 However, the recipes in built-in implicit rules actually use
9346 variables such as @code{COMPILE.c}, @code{LINK.p}, and
9347 @code{PREPROCESS.S}, whose values contain the recipes listed above.
9349 @code{make} follows the convention that the rule to compile a
9350 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
9351 Similarly, the rule to produce an executable from a @file{.@var{x}}
9352 file uses @code{LINK.@var{x}}; and the rule to preprocess a
9353 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
9355 @vindex OUTPUT_OPTION
9356 Every rule that produces an object file uses the variable
9357 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
9358 contain @samp{-o $@@}, or to be empty, depending on a compile-time
9359 option.  You need the @samp{-o} option to ensure that the output goes
9360 into the right file when the source file is in a different directory,
9361 as when using @code{VPATH} (@pxref{Directory Search}).  However,
9362 compilers on some systems do not accept a @samp{-o} switch for object
9363 files.  If you use such a system, and use @code{VPATH}, some
9364 compilations will put their output in the wrong place.
9365 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
9366 the value @w{@samp{; mv $*.o $@@}}.
9368 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
9369 @section Variables Used by Implicit Rules
9370 @cindex flags for compilers
9372 The recipes in built-in implicit rules make liberal use of certain
9373 predefined variables.  You can alter the values of these variables in
9374 the makefile, with arguments to @code{make}, or in the environment to
9375 alter how the implicit rules work without redefining the rules
9376 themselves.  You can cancel all variables used by implicit rules with
9377 the @samp{-R} or @samp{--no-builtin-variables} option.
9379 For example, the recipe used to compile a C source file actually says
9380 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
9381 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
9382 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
9383 used for all C compilations performed by the implicit rule.  By redefining
9384 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
9385 each compilation.  @emph{All} implicit rules that do C compilation use
9386 @samp{$(CC)} to get the program name for the compiler and @emph{all}
9387 include @samp{$(CFLAGS)} among the arguments given to the compiler.@refill
9389 The variables used in implicit rules fall into two classes: those that are
9390 names of programs (like @code{CC}) and those that contain arguments for the
9391 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
9392 some command arguments, but it must start with an actual executable program
9393 name.)  If a variable value contains more than one argument, separate them
9394 with spaces.
9396 The following tables describe of some of the more commonly-used predefined
9397 variables.  This list is not exhaustive, and the default values shown here may
9398 not be what @code{make} selects for your environment.  To see the
9399 complete list of predefined variables for your instance of GNU @code{make} you
9400 can run @samp{make -p} in a directory with no makefiles.
9402 Here is a table of some of the more common variables used as names of
9403 programs in built-in rules:
9405 @table @code
9406 @item AR
9407 @vindex AR
9408 Archive-maintaining program; default @samp{ar}.
9409 @pindex ar
9411 @item AS
9412 @vindex AS
9413 Program for compiling assembly files; default @samp{as}.
9414 @pindex as
9416 @item CC
9417 @vindex CC
9418 Program for compiling C programs; default @samp{cc}.
9419 @pindex cc
9421 @item CXX
9422 @vindex CXX
9423 Program for compiling C++ programs; default @samp{g++}.
9424 @pindex g++
9426 @item CPP
9427 @vindex CPP
9428 Program for running the C preprocessor, with results to standard output;
9429 default @samp{$(CC) -E}.
9431 @item FC
9432 @vindex FC
9433 Program for compiling or preprocessing Fortran and Ratfor programs;
9434 default @samp{f77}.
9435 @pindex f77
9437 @item M2C
9438 @vindex M2C
9439 Program to use to compile Modula-2 source code; default @samp{m2c}.
9440 @pindex m2c
9442 @item PC
9443 @vindex PC
9444 Program for compiling Pascal programs; default @samp{pc}.
9445 @pindex pc
9447 @item CO
9448 @vindex CO
9449 Program for extracting a file from RCS; default @samp{co}.
9450 @pindex co
9452 @item GET
9453 @vindex GET
9454 Program for extracting a file from SCCS; default @samp{get}.
9455 @pindex get
9457 @item LEX
9458 @vindex LEX
9459 Program to use to turn Lex grammars into source code; default @samp{lex}.
9460 @pindex lex
9462 @item YACC
9463 @vindex YACC
9464 Program to use to turn Yacc grammars into source code; default @samp{yacc}.
9465 @pindex yacc
9467 @item LINT
9468 @vindex LINT
9469 Program to use to run lint on source code; default @samp{lint}.
9470 @pindex lint
9472 @item MAKEINFO
9473 @vindex MAKEINFO
9474 Program to convert a Texinfo source file into an Info file; default
9475 @samp{makeinfo}.
9476 @pindex makeinfo
9478 @item TEX
9479 @vindex TEX
9480 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
9481 default @samp{tex}.
9482 @pindex tex
9484 @item TEXI2DVI
9485 @vindex TEXI2DVI
9486 Program to make @TeX{} @sc{dvi} files from Texinfo source;
9487 default @samp{texi2dvi}.
9488 @pindex texi2dvi
9490 @item WEAVE
9491 @vindex WEAVE
9492 Program to translate Web into @TeX{}; default @samp{weave}.
9493 @pindex weave
9495 @item CWEAVE
9496 @vindex CWEAVE
9497 Program to translate C Web into @TeX{}; default @samp{cweave}.
9498 @pindex cweave
9500 @item TANGLE
9501 @vindex TANGLE
9502 Program to translate Web into Pascal; default @samp{tangle}.
9503 @pindex tangle
9505 @item CTANGLE
9506 @vindex CTANGLE
9507 Program to translate C Web into C; default @samp{ctangle}.
9508 @pindex ctangle
9510 @item RM
9511 @vindex RM
9512 Command to remove a file; default @samp{rm -f}.
9513 @pindex rm
9514 @end table
9516 Here is a table of variables whose values are additional arguments for the
9517 programs above.  The default values for all of these is the empty
9518 string, unless otherwise noted.
9520 @table @code
9521 @item ARFLAGS
9522 @vindex ARFLAGS
9523 Flags to give the archive-maintaining program; default @samp{rv}.
9525 @item ASFLAGS
9526 @vindex ASFLAGS
9527 Extra flags to give to the assembler (when explicitly
9528 invoked on a @samp{.s} or @samp{.S} file).
9530 @item CFLAGS
9531 @vindex CFLAGS
9532 Extra flags to give to the C compiler.
9534 @item CXXFLAGS
9535 @vindex CXXFLAGS
9536 Extra flags to give to the C++ compiler.
9538 @item COFLAGS
9539 @vindex COFLAGS
9540 Extra flags to give to the RCS @code{co} program.
9542 @item CPPFLAGS
9543 @vindex CPPFLAGS
9544 Extra flags to give to the C preprocessor and programs
9545 that use it (the C and Fortran compilers).
9547 @item FFLAGS
9548 @vindex FFLAGS
9549 Extra flags to give to the Fortran compiler.
9551 @item GFLAGS
9552 @vindex GFLAGS
9553 Extra flags to give to the SCCS @code{get} program.
9555 @item LDFLAGS
9556 @vindex LDFLAGS
9557 Extra flags to give to compilers when they are supposed to invoke the linker,
9558 @samp{ld}.
9560 @item LDLIBS
9561 @vindex LDLIBS
9562 @vindex LOADLIBES
9563 Library flags or names given to compilers when they are supposed to
9564 invoke the linker, @samp{ld}.  @code{LOADLIBES} is a deprecated (but
9565 still supported) alternative to @code{LDLIBS}.
9567 @item LFLAGS
9568 @vindex LFLAGS
9569 Extra flags to give to Lex.
9571 @item YFLAGS
9572 @vindex YFLAGS
9573 Extra flags to give to Yacc.
9575 @item PFLAGS
9576 @vindex PFLAGS
9577 Extra flags to give to the Pascal compiler.
9579 @item RFLAGS
9580 @vindex RFLAGS
9581 Extra flags to give to the Fortran compiler for Ratfor programs.
9583 @item LINTFLAGS
9584 @vindex LINTFLAGS
9585 Extra flags to give to lint.
9586 @end table
9588 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
9589 @section Chains of Implicit Rules
9591 @cindex chains of rules
9592 @cindex rule, implicit, chains of
9593 Sometimes a file can be made by a sequence of implicit rules.  For example,
9594 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
9595 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
9597 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
9598 special searching is required: @code{make} finds that the object file can
9599 be made by C compilation from @file{@var{n}.c}; later on, when considering
9600 how to make @file{@var{n}.c}, the rule for running Yacc is
9601 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
9602 updated.@refill
9604 @cindex intermediate files
9605 @cindex files, intermediate
9606 However, even if @file{@var{n}.c} does not exist and is not mentioned,
9607 @code{make} knows how to envision it as the missing link between
9608 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
9609 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
9610 intermediate file, it is entered in the data base as if it had been
9611 mentioned in the makefile, along with the implicit rule that says how to
9612 create it.@refill
9614 Intermediate files are remade using their rules just like all other
9615 files.  But intermediate files are treated differently in two ways.
9617 The first difference is what happens if the intermediate file does not
9618 exist.  If an ordinary file @var{b} does not exist, and @code{make}
9619 considers a target that depends on @var{b}, it invariably creates
9620 @var{b} and then updates the target from @var{b}.  But if @var{b} is an
9621 intermediate file, then @code{make} can leave well enough alone.  It
9622 won't bother updating @var{b}, or the ultimate target, unless some
9623 prerequisite of @var{b} is newer than that target or there is some other
9624 reason to update that target.
9626 The second difference is that if @code{make} @emph{does} create @var{b}
9627 in order to update something else, it deletes @var{b} later on after it
9628 is no longer needed.  Therefore, an intermediate file which did not
9629 exist before @code{make} also does not exist after @code{make}.
9630 @code{make} reports the deletion to you by printing a @samp{rm -f}
9631 command showing which file it is deleting.
9633 Ordinarily, a file cannot be intermediate if it is mentioned in the
9634 makefile as a target or prerequisite.  However, you can explicitly mark a
9635 file as intermediate by listing it as a prerequisite of the special target
9636 @code{.INTERMEDIATE}.  This takes effect even if the file is mentioned
9637 explicitly in some other way.
9639 @cindex intermediate files, preserving
9640 @cindex preserving intermediate files
9641 @cindex secondary files
9642 You can prevent automatic deletion of an intermediate file by marking it
9643 as a @dfn{secondary} file.  To do this, list it as a prerequisite of the
9644 special target @code{.SECONDARY}.  When a file is secondary, @code{make}
9645 will not create the file merely because it does not already exist, but
9646 @code{make} does not automatically delete the file.  Marking a file as
9647 secondary also marks it as intermediate.
9649 You can list the target pattern of an implicit rule (such as @samp{%.o})
9650 as a prerequisite of the special target @code{.PRECIOUS} to preserve
9651 intermediate files made by implicit rules whose target patterns match
9652 that file's name; see @ref{Interrupts}.@refill
9653 @cindex preserving with @code{.PRECIOUS}
9654 @cindex @code{.PRECIOUS} intermediate files
9656 A chain can involve more than two implicit rules.  For example, it is
9657 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
9658 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
9659 intermediate files that are deleted at the end.@refill
9661 No single implicit rule can appear more than once in a chain.  This means
9662 that @code{make} will not even consider such a ridiculous thing as making
9663 @file{foo} from @file{foo.o.o} by running the linker twice.  This
9664 constraint has the added benefit of preventing any infinite loop in the
9665 search for an implicit rule chain.
9667 There are some special implicit rules to optimize certain cases that would
9668 otherwise be handled by rule chains.  For example, making @file{foo} from
9669 @file{foo.c} could be handled by compiling and linking with separate
9670 chained rules, using @file{foo.o} as an intermediate file.  But what
9671 actually happens is that a special rule for this case does the compilation
9672 and linking with a single @code{cc} command.  The optimized rule is used in
9673 preference to the step-by-step chain because it comes earlier in the
9674 ordering of rules.
9676 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
9677 @section Defining and Redefining Pattern Rules
9679 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
9680 rule looks like an ordinary rule, except that its target contains the
9681 character @samp{%} (exactly one of them).  The target is considered a
9682 pattern for matching file names; the @samp{%} can match any nonempty
9683 substring, while other characters match only themselves.  The prerequisites
9684 likewise use @samp{%} to show how their names relate to the target name.
9686 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
9687 @file{@var{stem}.o} from another file @file{@var{stem}.c}.@refill
9689 Note that expansion using @samp{%} in pattern rules occurs
9690 @strong{after} any variable or function expansions, which take place
9691 when the makefile is read.  @xref{Using Variables, , How to Use
9692 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
9694 @menu
9695 * Pattern Intro::               An introduction to pattern rules.
9696 * Pattern Examples::            Examples of pattern rules.
9697 * Automatic Variables::         How to use automatic variables in the
9698                                   recipe of implicit rules.
9699 * Pattern Match::               How patterns match.
9700 * Match-Anything Rules::        Precautions you should take prior to
9701                                   defining rules that can match any
9702                                   target file whatever.
9703 * Canceling Rules::             How to override or cancel built-in rules.
9704 @end menu
9706 @node Pattern Intro, Pattern Examples, Pattern Rules, Pattern Rules
9707 @subsection Introduction to Pattern Rules
9708 @cindex pattern rule
9709 @cindex rule, pattern
9711 A pattern rule contains the character @samp{%} (exactly one of them)
9712 in the target; otherwise, it looks exactly like an ordinary rule.  The
9713 target is a pattern for matching file names; the @samp{%} matches any
9714 nonempty substring, while other characters match only themselves.
9715 @cindex target pattern, implicit
9716 @cindex @code{%}, in pattern rules
9718 For example, @samp{%.c} as a pattern matches any file name that ends in
9719 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
9720 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
9721 (There must be at least one character to match the @samp{%}.)  The substring
9722 that the @samp{%} matches is called the @dfn{stem}.@refill
9724 @samp{%} in a prerequisite of a pattern rule stands for the same stem
9725 that was matched by the @samp{%} in the target.  In order for the
9726 pattern rule to apply, its target pattern must match the file name
9727 under consideration and all of its prerequisites (after pattern
9728 substitution) must name files that exist or can be made.  These files
9729 become prerequisites of the target.
9730 @cindex prerequisite pattern, implicit
9732 Thus, a rule of the form
9734 @example
9735 %.o : %.c ; @var{recipe}@dots{}
9736 @end example
9738 @noindent
9739 specifies how to make a file @file{@var{n}.o}, with another file
9740 @file{@var{n}.c} as its prerequisite, provided that @file{@var{n}.c}
9741 exists or can be made.
9743 There may also be prerequisites that do not use @samp{%}; such a prerequisite
9744 attaches to every file made by this pattern rule.  These unvarying
9745 prerequisites are useful occasionally.
9747 A pattern rule need not have any prerequisites that contain @samp{%}, or
9748 in fact any prerequisites at all.  Such a rule is effectively a general
9749 wildcard.  It provides a way to make any file that matches the target
9750 pattern.  @xref{Last Resort}.
9752 More than one pattern rule may match a target.  In this case
9753 @code{make} will choose the ``best fit'' rule.  @xref{Pattern Match,
9754 ,How Patterns Match}.
9756 @c !!! The end of of this paragraph should be rewritten.  --bob
9757 Pattern rules may have more than one target.  Unlike normal rules,
9758 this does not act as many different rules with the same prerequisites
9759 and recipe.  If a pattern rule has multiple targets, @code{make} knows
9760 that the rule's recipe is responsible for making all of the targets.
9761 The recipe is executed only once to make all the targets.  When
9762 searching for a pattern rule to match a target, the target patterns of
9763 a rule other than the one that matches the target in need of a rule
9764 are incidental: @code{make} worries only about giving a recipe and
9765 prerequisites to the file presently in question.  However, when this
9766 file's recipe is run, the other targets are marked as having been
9767 updated themselves.
9768 @cindex multiple targets, in pattern rule
9769 @cindex target, multiple in pattern rule
9771 @node Pattern Examples, Automatic Variables, Pattern Intro, Pattern Rules
9772 @subsection Pattern Rule Examples
9774 Here are some examples of pattern rules actually predefined in
9775 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
9776 files:@refill
9778 @example
9779 %.o : %.c
9780         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
9781 @end example
9783 @noindent
9784 defines a rule that can make any file @file{@var{x}.o} from
9785 @file{@var{x}.c}.  The recipe uses the automatic variables @samp{$@@} and
9786 @samp{$<} to substitute the names of the target file and the source file
9787 in each case where the rule applies (@pxref{Automatic Variables}).@refill
9789 Here is a second built-in rule:
9791 @example
9792 % :: RCS/%,v
9793         $(CO) $(COFLAGS) $<
9794 @end example
9796 @noindent
9797 defines a rule that can make any file @file{@var{x}} whatsoever from a
9798 corresponding file @file{@var{x},v} in the sub-directory @file{RCS}.  Since
9799 the target is @samp{%}, this rule will apply to any file whatever, provided
9800 the appropriate prerequisite file exists.  The double colon makes the rule
9801 @dfn{terminal}, which means that its prerequisite may not be an intermediate
9802 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).@refill
9804 @need 500
9805 This pattern rule has two targets:
9807 @example
9808 @group
9809 %.tab.c %.tab.h: %.y
9810         bison -d $<
9811 @end group
9812 @end example
9814 @noindent
9815 @c The following paragraph is rewritten to avoid overfull hboxes
9816 This tells @code{make} that the recipe @samp{bison -d @var{x}.y} will
9817 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
9818 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
9819 and the file @file{scan.o} depends on the file @file{parse.tab.h},
9820 when @file{parse.y} is changed, the recipe @samp{bison -d parse.y}
9821 will be executed only once, and the prerequisites of both
9822 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
9823 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
9824 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
9825 linked from @file{parse.tab.o}, @file{scan.o}, and its other
9826 prerequisites, and it will execute happily ever after.)@refill
9828 @node Automatic Variables, Pattern Match, Pattern Examples, Pattern Rules
9829 @subsection Automatic Variables
9830 @cindex automatic variables
9831 @cindex variables, automatic
9832 @cindex variables, and implicit rule
9834 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
9835 @samp{.o} file: how do you write the @samp{cc} command so that it operates
9836 on the right source file name?  You cannot write the name in the recipe,
9837 because the name is different each time the implicit rule is applied.
9839 What you do is use a special feature of @code{make}, the @dfn{automatic
9840 variables}.  These variables have values computed afresh for each rule that
9841 is executed, based on the target and prerequisites of the rule.  In this
9842 example, you would use @samp{$@@} for the object file name and @samp{$<}
9843 for the source file name.
9845 @cindex automatic variables in prerequisites
9846 @cindex prerequisites, and automatic variables
9847 It's very important that you recognize the limited scope in which
9848 automatic variable values are available: they only have values within
9849 the recipe.  In particular, you cannot use them anywhere
9850 within the target list of a rule; they have no value there and will
9851 expand to the empty string.  Also, they cannot be accessed directly
9852 within the prerequisite list of a rule.  A common mistake is
9853 attempting to use @code{$@@} within the prerequisites list; this will
9854 not work.  However, there is a special feature of GNU @code{make},
9855 secondary expansion (@pxref{Secondary Expansion}), which will allow
9856 automatic variable values to be used in prerequisite lists.
9858 Here is a table of automatic variables:
9860 @table @code
9861 @vindex $@@
9862 @vindex @@ @r{(automatic variable)}
9863 @item $@@
9864 The file name of the target of the rule.  If the target is an archive
9865 member, then @samp{$@@} is the name of the archive file.  In a pattern
9866 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
9867 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
9868 rule's recipe to be run.
9870 @vindex $%
9871 @vindex % @r{(automatic variable)}
9872 @item $%
9873 The target member name, when the target is an archive member.
9874 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
9875 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
9876 empty when the target is not an archive member.
9878 @vindex $<
9879 @vindex < @r{(automatic variable)}
9880 @item $<
9881 The name of the first prerequisite.  If the target got its recipe from
9882 an implicit rule, this will be the first prerequisite added by the
9883 implicit rule (@pxref{Implicit Rules}).
9885 @vindex $?
9886 @vindex ? @r{(automatic variable)}
9887 @item $?
9888 The names of all the prerequisites that are newer than the target, with
9889 spaces between them.  For prerequisites which are archive members, only
9890 the named member is used (@pxref{Archives}).
9891 @cindex prerequisites, list of changed
9892 @cindex list of changed prerequisites
9894 @vindex $^
9895 @vindex ^ @r{(automatic variable)}
9896 @item $^
9897 The names of all the prerequisites, with spaces between them.  For
9898 prerequisites which are archive members, only the named member is used
9899 (@pxref{Archives}).  A target has only one prerequisite on each other file
9900 it depends on, no matter how many times each file is listed as a
9901 prerequisite.  So if you list a prerequisite more than once for a target,
9902 the value of @code{$^} contains just one copy of the name.  This list
9903 does @strong{not} contain any of the order-only prerequisites; for those
9904 see the @samp{$|} variable, below.
9905 @cindex prerequisites, list of all
9906 @cindex list of all prerequisites
9908 @vindex $+
9909 @vindex + @r{(automatic variable)}
9910 @item $+
9911 This is like @samp{$^}, but prerequisites listed more than once are
9912 duplicated in the order they were listed in the makefile.  This is
9913 primarily useful for use in linking commands where it is meaningful to
9914 repeat library file names in a particular order.
9916 @vindex $|
9917 @vindex | @r{(automatic variable)}
9918 @item $|
9919 The names of all the order-only prerequisites, with spaces between
9920 them.
9922 @vindex $*
9923 @vindex * @r{(automatic variable)}
9924 @item $*
9925 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
9926 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
9927 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
9928 useful for constructing names of related files.@refill
9929 @cindex stem, variable for
9931 In a static pattern rule, the stem is part of the file name that matched
9932 the @samp{%} in the target pattern.
9934 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
9935 in that way.  Instead, if the target name ends with a recognized suffix
9936 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
9937 the target name minus the suffix.  For example, if the target name is
9938 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
9939 suffix.  GNU @code{make} does this bizarre thing only for compatibility
9940 with other implementations of @code{make}.  You should generally avoid
9941 using @samp{$*} except in implicit rules or static pattern rules.@refill
9943 If the target name in an explicit rule does not end with a recognized
9944 suffix, @samp{$*} is set to the empty string for that rule.
9945 @end table
9947 @samp{$?} is useful even in explicit rules when you wish to operate on only
9948 the prerequisites that have changed.  For example, suppose that an archive
9949 named @file{lib} is supposed to contain copies of several object files.
9950 This rule copies just the changed object files into the archive:
9952 @example
9953 @group
9954 lib: foo.o bar.o lose.o win.o
9955         ar r lib $?
9956 @end group
9957 @end example
9959 Of the variables listed above, four have values that are single file
9960 names, and three have values that are lists of file names.  These seven
9961 have variants that get just the file's directory name or just the file
9962 name within the directory.  The variant variables' names are formed by
9963 appending @samp{D} or @samp{F}, respectively.  These variants are
9964 semi-obsolete in GNU @code{make} since the functions @code{dir} and
9965 @code{notdir} can be used to get a similar effect (@pxref{File Name
9966 Functions, , Functions for File Names}).  Note, however, that the
9967 @samp{D} variants all omit the trailing slash which always appears in
9968 the output of the @code{dir} function.  Here is a table of the variants:
9970 @table @samp
9971 @vindex $(@@D)
9972 @vindex @@D @r{(automatic variable)}
9973 @item $(@@D)
9974 The directory part of the file name of the target, with the trailing
9975 slash removed.  If the value of @samp{$@@} is @file{dir/foo.o} then
9976 @samp{$(@@D)} is @file{dir}.  This value is @file{.} if @samp{$@@} does
9977 not contain a slash.
9979 @vindex $(@@F)
9980 @vindex @@F @r{(automatic variable)}
9981 @item $(@@F)
9982 The file-within-directory part of the file name of the target.  If the
9983 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
9984 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
9986 @vindex $(*D)
9987 @vindex *D @r{(automatic variable)}
9988 @item $(*D)
9989 @vindex $(*F)
9990 @vindex *F @r{(automatic variable)}
9991 @itemx $(*F)
9992 The directory part and the file-within-directory
9993 part of the stem; @file{dir} and @file{foo} in this example.
9995 @vindex $(%D)
9996 @vindex %D @r{(automatic variable)}
9997 @item $(%D)
9998 @vindex $(%F)
9999 @vindex %F @r{(automatic variable)}
10000 @itemx $(%F)
10001 The directory part and the file-within-directory part of the target
10002 archive member name.  This makes sense only for archive member targets
10003 of the form @file{@var{archive}(@var{member})} and is useful only when
10004 @var{member} may contain a directory name.  (@xref{Archive Members,
10005 ,Archive Members as Targets}.)
10007 @vindex $(<D)
10008 @vindex <D @r{(automatic variable)}
10009 @item $(<D)
10010 @vindex $(<F)
10011 @vindex <F @r{(automatic variable)}
10012 @itemx $(<F)
10013 The directory part and the file-within-directory
10014 part of the first prerequisite.
10016 @vindex $(^D)
10017 @vindex ^D @r{(automatic variable)}
10018 @item $(^D)
10019 @vindex $(^F)
10020 @vindex ^F @r{(automatic variable)}
10021 @itemx $(^F)
10022 Lists of the directory parts and the file-within-directory
10023 parts of all prerequisites.
10025 @vindex $(+D)
10026 @vindex +D @r{(automatic variable)}
10027 @item $(+D)
10028 @vindex $(+F)
10029 @vindex +F @r{(automatic variable)}
10030 @itemx $(+F)
10031 Lists of the directory parts and the file-within-directory
10032 parts of all prerequisites, including multiple instances of duplicated
10033 prerequisites.
10035 @vindex $(?D)
10036 @vindex ?D @r{(automatic variable)}
10037 @item $(?D)
10038 @vindex $(?F)
10039 @vindex ?F @r{(automatic variable)}
10040 @itemx $(?F)
10041 Lists of the directory parts and the file-within-directory parts of
10042 all prerequisites that are newer than the target.
10043 @end table
10045 Note that we use a special stylistic convention when we talk about these
10046 automatic variables; we write ``the value of @samp{$<}'', rather than
10047 @w{``the variable @code{<}''} as we would write for ordinary variables
10048 such as @code{objects} and @code{CFLAGS}.  We think this convention
10049 looks more natural in this special case.  Please do not assume it has a
10050 deep significance; @samp{$<} refers to the variable named @code{<} just
10051 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
10052 You could just as well use @samp{$(<)} in place of @samp{$<}.
10054 @node Pattern Match, Match-Anything Rules, Automatic Variables, Pattern Rules
10055 @subsection How Patterns Match
10057 @cindex stem
10058 A target pattern is composed of a @samp{%} between a prefix and a suffix,
10059 either or both of which may be empty.  The pattern matches a file name only
10060 if the file name starts with the prefix and ends with the suffix, without
10061 overlap.  The text between the prefix and the suffix is called the
10062 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
10063 @file{test.o}, the stem is @samp{test}.  The pattern rule prerequisites are
10064 turned into actual file names by substituting the stem for the character
10065 @samp{%}.  Thus, if in the same example one of the prerequisites is written
10066 as @samp{%.c}, it expands to @samp{test.c}.@refill
10068 When the target pattern does not contain a slash (and it usually does
10069 not), directory names in the file names are removed from the file name
10070 before it is compared with the target prefix and suffix.  After the
10071 comparison of the file name to the target pattern, the directory
10072 names, along with the slash that ends them, are added on to the
10073 prerequisite file names generated from the pattern rule's prerequisite
10074 patterns and the file name.  The directories are ignored only for the
10075 purpose of finding an implicit rule to use, not in the application of
10076 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
10077 with @samp{src/a} as the stem.  When prerequisites are turned into file
10078 names, the directories from the stem are added at the front, while the
10079 rest of the stem is substituted for the @samp{%}.  The stem
10080 @samp{src/a} with a prerequisite pattern @samp{c%r} gives the file name
10081 @file{src/car}.@refill
10083 @cindex pattern rules, order of
10084 @cindex order of pattern rules
10085 A pattern rule can be used to build a given file only if there is a
10086 target pattern that matches the file name, @emph{and} all
10087 prerequisites in that rule either exist or can be built.  The rules
10088 you write take precedence over those that are built in. Note however,
10089 that a rule whose prerequisites actually exist or are mentioned always
10090 takes priority over a rule with prerequisites that must be made by
10091 chaining other implicit rules.
10093 @cindex stem, shortest
10094 It is possible that more than one pattern rule will meet these
10095 criteria.  In that case, @code{make} will choose the rule with the
10096 shortest stem (that is, the pattern that matches most specifically).
10097 If more than one pattern rule has the shortest stem, @code{make} will
10098 choose the first one found in the makefile.
10100 This algorithm results in more specific rules being preferred over
10101 more generic ones; for example:
10103 @example
10104 %.o: %.c
10105         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
10107 %.o : %.f
10108         $(COMPILE.F) $(OUTPUT_OPTION) $<
10110 lib/%.o: lib/%.c
10111         $(CC) -fPIC -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
10112 @end example
10114 Given these rules and asked to build @file{bar.o} where both
10115 @file{bar.c} and @file{bar.f} exist, @code{make} will choose the first
10116 rule and compile @file{bar.c} into @file{bar.o}.  In the same
10117 situation where @file{bar.c} does not exist, then @code{make} will
10118 choose the second rule and compile @file{bar.f} into @file{bar.o}.
10120 If @code{make} is asked to build @file{lib/bar.o} and both
10121 @file{lib/bar.c} and @file{lib/bar.f} exist, then the third rule will
10122 be chosen since the stem for this rule (@samp{bar}) is shorter than
10123 the stem for the first rule (@samp{lib/bar}).  If @file{lib/bar.c}
10124 does not exist then the third rule is not eligible and the second rule
10125 will be used, even though the stem is longer.
10127 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
10128 @subsection Match-Anything Pattern Rules
10130 @cindex match-anything rule
10131 @cindex terminal rule
10132 When a pattern rule's target is just @samp{%}, it matches any file name
10133 whatever.  We call these rules @dfn{match-anything} rules.  They are very
10134 useful, but it can take a lot of time for @code{make} to think about them,
10135 because it must consider every such rule for each file name listed either
10136 as a target or as a prerequisite.
10138 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
10139 would have to consider making it by linking an object file @file{foo.c.o},
10140 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
10141 Pascal compilation-and-linking from @file{foo.c.p}, and many other
10142 possibilities.
10144 We know these possibilities are ridiculous since @file{foo.c} is a C source
10145 file, not an executable.  If @code{make} did consider these possibilities,
10146 it would ultimately reject them, because files such as @file{foo.c.o} and
10147 @file{foo.c.p} would not exist.  But these possibilities are so
10148 numerous that @code{make} would run very slowly if it had to consider
10149 them.@refill
10151 To gain speed, we have put various constraints on the way @code{make}
10152 considers match-anything rules.  There are two different constraints that
10153 can be applied, and each time you define a match-anything rule you must
10154 choose one or the other for that rule.
10156 One choice is to mark the match-anything rule as @dfn{terminal} by defining
10157 it with a double colon.  When a rule is terminal, it does not apply unless
10158 its prerequisites actually exist.  Prerequisites that could be made with
10159 other implicit rules are not good enough.  In other words, no further
10160 chaining is allowed beyond a terminal rule.
10162 For example, the built-in implicit rules for extracting sources from RCS
10163 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
10164 not exist, @code{make} will not even consider trying to make it as an
10165 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
10166 RCS and SCCS files are generally ultimate source files, which should not be
10167 remade from any other files; therefore, @code{make} can save time by not
10168 looking for ways to remake them.@refill
10170 If you do not mark the match-anything rule as terminal, then it is
10171 non-terminal.  A non-terminal match-anything rule cannot apply to a file name
10172 that indicates a specific type of data.  A file name indicates a specific
10173 type of data if some non-match-anything implicit rule target matches it.
10175 For example, the file name @file{foo.c} matches the target for the pattern
10176 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
10177 rule is actually applicable (which happens only if there is a file
10178 @file{foo.y}), the fact that its target matches is enough to prevent
10179 consideration of any non-terminal match-anything rules for the file
10180 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
10181 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
10182 @file{foo.c.p}, etc.@refill
10184 The motivation for this constraint is that non-terminal match-anything
10185 rules are used for making files containing specific types of data (such as
10186 executable files) and a file name with a recognized suffix indicates some
10187 other specific type of data (such as a C source file).
10189 Special built-in dummy pattern rules are provided solely to recognize
10190 certain file names so that non-terminal match-anything rules will not be
10191 considered.  These dummy rules have no prerequisites and no recipes, and
10192 they are ignored for all other purposes.  For example, the built-in
10193 implicit rule
10195 @example
10196 %.p :
10197 @end example
10199 @noindent
10200 exists to make sure that Pascal source files such as @file{foo.p} match a
10201 specific target pattern and thereby prevent time from being wasted looking
10202 for @file{foo.p.o} or @file{foo.p.c}.
10204 Dummy pattern rules such as the one for @samp{%.p} are made for every
10205 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
10207 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
10208 @subsection Canceling Implicit Rules
10210 You can override a built-in implicit rule (or one you have defined
10211 yourself) by defining a new pattern rule with the same target and
10212 prerequisites, but a different recipe.  When the new rule is defined, the
10213 built-in one is replaced.  The new rule's position in the sequence of
10214 implicit rules is determined by where you write the new rule.
10216 You can cancel a built-in implicit rule by defining a pattern rule with the
10217 same target and prerequisites, but no recipe.  For example, the following
10218 would cancel the rule that runs the assembler:
10220 @example
10221 %.o : %.s
10222 @end example
10224 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
10225 @section Defining Last-Resort Default Rules
10226 @cindex last-resort default rules
10227 @cindex default rules, last-resort
10229 You can define a last-resort implicit rule by writing a terminal
10230 match-anything pattern rule with no prerequisites (@pxref{Match-Anything
10231 Rules}).  This is just like any other pattern rule; the only thing
10232 special about it is that it will match any target.  So such a rule's
10233 recipe is used for all targets and prerequisites that have no recipe
10234 of their own and for which no other implicit rule applies.
10236 For example, when testing a makefile, you might not care if the source
10237 files contain real data, only that they exist.  Then you might do this:
10239 @example
10241         touch $@@
10242 @end example
10244 @noindent
10245 to cause all the source files needed (as prerequisites) to be created
10246 automatically.
10248 @findex .DEFAULT
10249 You can instead define a recipe to be used for targets for which there
10250 are no rules at all, even ones which don't specify recipes.  You do
10251 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
10252 recipe is used for all prerequisites which do not appear as targets in
10253 any explicit rule, and for which no implicit rule applies.  Naturally,
10254 there is no @code{.DEFAULT} rule unless you write one.
10256 If you use @code{.DEFAULT} with no recipe or prerequisites:
10258 @example
10259 .DEFAULT:
10260 @end example
10262 @noindent
10263 the recipe previously stored for @code{.DEFAULT} is cleared.  Then
10264 @code{make} acts as if you had never defined @code{.DEFAULT} at all.
10266 If you do not want a target to get the recipe from a match-anything
10267 pattern rule or @code{.DEFAULT}, but you also do not want any recipe
10268 to be run for the target, you can give it an empty recipe
10269 (@pxref{Empty Recipes, ,Defining Empty Recipes}).@refill
10271 You can use a last-resort rule to override part of another makefile.
10272 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
10274 @node Suffix Rules, Implicit Rule Search, Last Resort, Implicit Rules
10275 @section Old-Fashioned Suffix Rules
10276 @cindex old-fashioned suffix rules
10277 @cindex suffix rule
10279 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
10280 @code{make}.  Suffix rules are obsolete because pattern rules are more
10281 general and clearer.  They are supported in GNU @code{make} for
10282 compatibility with old makefiles.  They come in two kinds:
10283 @dfn{double-suffix} and @dfn{single-suffix}.@refill
10285 A double-suffix rule is defined by a pair of suffixes: the target suffix
10286 and the source suffix.  It matches any file whose name ends with the
10287 target suffix.  The corresponding implicit prerequisite is made by
10288 replacing the target suffix with the source suffix in the file name.  A
10289 two-suffix rule whose target and source suffixes are @samp{.o} and
10290 @samp{.c} is equivalent to the pattern rule @samp{%.o : %.c}.
10292 A single-suffix rule is defined by a single suffix, which is the source
10293 suffix.  It matches any file name, and the corresponding implicit
10294 prerequisite name is made by appending the source suffix.  A single-suffix
10295 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
10296 @samp{% : %.c}.
10298 Suffix rule definitions are recognized by comparing each rule's target
10299 against a defined list of known suffixes.  When @code{make} sees a rule
10300 whose target is a known suffix, this rule is considered a single-suffix
10301 rule.  When @code{make} sees a rule whose target is two known suffixes
10302 concatenated, this rule is taken as a double-suffix rule.
10304 For example, @samp{.c} and @samp{.o} are both on the default list of
10305 known suffixes.  Therefore, if you define a rule whose target is
10306 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
10307 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
10308 way to define the rule for compiling a C source file:@refill
10310 @example
10311 .c.o:
10312         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10313 @end example
10315 Suffix rules cannot have any prerequisites of their own.  If they have any,
10316 they are treated as normal files with funny names, not as suffix rules.
10317 Thus, the rule:
10319 @example
10320 .c.o: foo.h
10321         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10322 @end example
10324 @noindent
10325 tells how to make the file @file{.c.o} from the prerequisite file
10326 @file{foo.h}, and is not at all like the pattern rule:
10328 @example
10329 %.o: %.c foo.h
10330         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
10331 @end example
10333 @noindent
10334 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
10335 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
10337 Suffix rules with no recipe are also meaningless.  They do not remove
10338 previous rules as do pattern rules with no recipe (@pxref{Canceling
10339 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or
10340 pair of suffixes concatenated as a target in the data base.@refill
10342 @findex .SUFFIXES
10343 The known suffixes are simply the names of the prerequisites of the special
10344 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
10345 for @code{.SUFFIXES} that adds more prerequisites, as in:
10347 @example
10348 .SUFFIXES: .hack .win
10349 @end example
10351 @noindent
10352 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
10354 If you wish to eliminate the default known suffixes instead of just adding
10355 to them, write a rule for @code{.SUFFIXES} with no prerequisites.  By
10356 special dispensation, this eliminates all existing prerequisites of
10357 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
10358 want.  For example,
10360 @example
10361 @group
10362 .SUFFIXES:            # @r{Delete the default suffixes}
10363 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
10364 @end group
10365 @end example
10367 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
10368 list of suffixes to be empty.
10370 @vindex SUFFIXES
10371 The variable @code{SUFFIXES} is defined to the default list of suffixes
10372 before @code{make} reads any makefiles.  You can change the list of suffixes
10373 with a rule for the special target @code{.SUFFIXES}, but that does not alter
10374 this variable.
10376 @node Implicit Rule Search,  , Suffix Rules, Implicit Rules
10377 @section Implicit Rule Search Algorithm
10378 @cindex implicit rule, search algorithm
10379 @cindex search algorithm, implicit rule
10381 Here is the procedure @code{make} uses for searching for an implicit rule
10382 for a target @var{t}.  This procedure is followed for each double-colon
10383 rule with no recipe, for each target of ordinary rules none of which have
10384 a recipe, and for each prerequisite that is not the target of any rule.  It
10385 is also followed recursively for prerequisites that come from implicit
10386 rules, in the search for a chain of rules.
10388 Suffix rules are not mentioned in this algorithm because suffix rules are
10389 converted to equivalent pattern rules once the makefiles have been read in.
10391 For an archive member target of the form
10392 @samp{@var{archive}(@var{member})}, the following algorithm is run
10393 twice, first using the entire target name @var{t}, and second using
10394 @samp{(@var{member})} as the target @var{t} if the first run found no
10395 rule.@refill
10397 @enumerate
10398 @item
10399 Split @var{t} into a directory part, called @var{d}, and the rest,
10400 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
10401 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.@refill
10403 @item
10404 Make a list of all the pattern rules one of whose targets matches
10405 @var{t} or @var{n}.  If the target pattern contains a slash, it is
10406 matched against @var{t}; otherwise, against @var{n}.
10408 @item
10409 If any rule in that list is @emph{not} a match-anything rule, then
10410 remove all non-terminal match-anything rules from the list.
10412 @item
10413 Remove from the list all rules with no recipe.
10415 @item
10416 For each pattern rule in the list:
10418 @enumerate a
10419 @item
10420 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
10421 matched by the @samp{%} in the target pattern.@refill
10423 @item
10424 Compute the prerequisite names by substituting @var{s} for @samp{%}; if
10425 the target pattern does not contain a slash, append @var{d} to
10426 the front of each prerequisite name.@refill
10428 @item
10429 Test whether all the prerequisites exist or ought to exist.  (If a
10430 file name is mentioned in the makefile as a target or as an explicit
10431 prerequisite, then we say it ought to exist.)
10433 If all prerequisites exist or ought to exist, or there are no prerequisites,
10434 then this rule applies.
10435 @end enumerate
10437 @item
10438 If no pattern rule has been found so far, try harder.
10439 For each pattern rule in the list:
10441 @enumerate a
10442 @item
10443 If the rule is terminal, ignore it and go on to the next rule.
10445 @item
10446 Compute the prerequisite names as before.
10448 @item
10449 Test whether all the prerequisites exist or ought to exist.
10451 @item
10452 For each prerequisite that does not exist, follow this algorithm
10453 recursively to see if the prerequisite can be made by an implicit
10454 rule.
10456 @item
10457 If all prerequisites exist, ought to exist, or can be
10458 made by implicit rules, then this rule applies.
10459 @end enumerate
10461 @item
10462 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
10463 applies.  In that case, give @var{t} the same recipe that
10464 @code{.DEFAULT} has.  Otherwise, there is no recipe for @var{t}.
10465 @end enumerate
10467 Once a rule that applies has been found, for each target pattern of
10468 the rule other than the one that matched @var{t} or @var{n}, the
10469 @samp{%} in the pattern is replaced with @var{s} and the resultant
10470 file name is stored until the recipe to remake the target file @var{t}
10471 is executed.  After the recipe is executed, each of these stored file
10472 names are entered into the data base and marked as having been updated
10473 and having the same update status as the file @var{t}.
10475 When the recipe of a pattern rule is executed for @var{t}, the
10476 automatic variables are set corresponding to the target and
10477 prerequisites.  @xref{Automatic Variables}.
10479 @node Archives, Features, Implicit Rules, Top
10480 @chapter Using @code{make} to Update Archive Files
10481 @cindex archive
10483 @dfn{Archive files} are files containing named sub-files called
10484 @dfn{members}; they are maintained with the program @code{ar} and their
10485 main use is as subroutine libraries for linking.
10487 @menu
10488 * Archive Members::             Archive members as targets.
10489 * Archive Update::              The implicit rule for archive member targets.
10490 * Archive Pitfalls::            Dangers to watch out for when using archives.
10491 * Archive Suffix Rules::        You can write a special kind of suffix rule
10492                                   for updating archives.
10493 @end menu
10495 @node Archive Members, Archive Update, Archives, Archives
10496 @section Archive Members as Targets
10497 @cindex archive member targets
10499 An individual member of an archive file can be used as a target or
10500 prerequisite in @code{make}.  You specify the member named @var{member} in
10501 archive file @var{archive} as follows:
10503 @example
10504 @var{archive}(@var{member})
10505 @end example
10507 @noindent
10508 This construct is available only in targets and prerequisites, not in
10509 recipes!  Most programs that you might use in recipes do not support
10510 this syntax and cannot act directly on archive members.  Only
10511 @code{ar} and other programs specifically designed to operate on
10512 archives can do so.  Therefore, valid recipes to update an archive
10513 member target probably must use @code{ar}.  For example, this rule
10514 says to create a member @file{hack.o} in archive @file{foolib} by
10515 copying the file @file{hack.o}:
10517 @example
10518 foolib(hack.o) : hack.o
10519         ar cr foolib hack.o
10520 @end example
10522 In fact, nearly all archive member targets are updated in just this way
10523 and there is an implicit rule to do it for you.  @strong{Please note:} The
10524 @samp{c} flag to @code{ar} is required if the archive file does not
10525 already exist.
10527 To specify several members in the same archive, you can write all the
10528 member names together between the parentheses.  For example:
10530 @example
10531 foolib(hack.o kludge.o)
10532 @end example
10534 @noindent
10535 is equivalent to:
10537 @example
10538 foolib(hack.o) foolib(kludge.o)
10539 @end example
10541 @cindex wildcard, in archive member
10542 You can also use shell-style wildcards in an archive member reference.
10543 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
10544 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
10545 @file{foolib} archive whose names end in @samp{.o}; perhaps
10546 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
10548 @node Archive Update, Archive Pitfalls, Archive Members, Archives
10549 @section Implicit Rule for Archive Member Targets
10551 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
10552 member named @var{m} in the archive file @var{a}.
10554 When @code{make} looks for an implicit rule for such a target, as a special
10555 feature it considers implicit rules that match @file{(@var{m})}, as well as
10556 those that match the actual target @file{@var{a}(@var{m})}.
10558 This causes one special rule whose target is @file{(%)} to match.  This
10559 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
10560 into the archive.  For example, it will update the archive member target
10561 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
10562 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
10564 When this rule is chained with others, the result is very powerful.
10565 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
10566 @samp{(} and @samp{)} from being interpreted specially by the shell) in
10567 the presence of a file @file{bar.c} is enough to cause the following
10568 recipe to be run, even without a makefile:
10570 @example
10571 cc -c bar.c -o bar.o
10572 ar r foo.a bar.o
10573 rm -f bar.o
10574 @end example
10576 @noindent
10577 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
10578 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
10580 Implicit rules such as this one are written using the automatic variable
10581 @samp{$%}.  @xref{Automatic Variables}.
10583 An archive member name in an archive cannot contain a directory name, but
10584 it may be useful in a makefile to pretend that it does.  If you write an
10585 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
10586 automatic updating with this recipe:
10588 @example
10589 ar r foo.a dir/file.o
10590 @end example
10592 @noindent
10593 which has the effect of copying the file @file{dir/file.o} into a member
10594 named @file{file.o}.  In connection with such usage, the automatic variables
10595 @code{%D} and @code{%F} may be useful.
10597 @menu
10598 * Archive Symbols::             How to update archive symbol directories.
10599 @end menu
10601 @node Archive Symbols,  , Archive Update, Archive Update
10602 @subsection Updating Archive Symbol Directories
10603 @cindex @code{__.SYMDEF}
10604 @cindex updating archive symbol directories
10605 @cindex archive symbol directory updating
10606 @cindex symbol directories, updating archive
10607 @cindex directories, updating archive symbol
10609 An archive file that is used as a library usually contains a special member
10610 named @file{__.SYMDEF} that contains a directory of the external symbol
10611 names defined by all the other members.  After you update any other
10612 members, you need to update @file{__.SYMDEF} so that it will summarize the
10613 other members properly.  This is done by running the @code{ranlib} program:
10615 @example
10616 ranlib @var{archivefile}
10617 @end example
10619 Normally you would put this command in the rule for the archive file,
10620 and make all the members of the archive file prerequisites of that rule.
10621 For example,
10623 @example
10624 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
10625         ranlib libfoo.a
10626 @end example
10628 @noindent
10629 The effect of this is to update archive members @file{x.o}, @file{y.o},
10630 etc., and then update the symbol directory member @file{__.SYMDEF} by
10631 running @code{ranlib}.  The rules for updating the members are not shown
10632 here; most likely you can omit them and use the implicit rule which copies
10633 files into the archive, as described in the preceding section.
10635 This is not necessary when using the GNU @code{ar} program, which
10636 updates the @file{__.SYMDEF} member automatically.
10638 @node Archive Pitfalls, Archive Suffix Rules, Archive Update, Archives
10639 @section Dangers When Using Archives
10640 @cindex archive, and parallel execution
10641 @cindex parallel execution, and archive update
10642 @cindex archive, and @code{-j}
10643 @cindex @code{-j}, and archive update
10645 It is important to be careful when using parallel execution (the
10646 @code{-j} switch; @pxref{Parallel, ,Parallel Execution}) and archives.
10647 If multiple @code{ar} commands run at the same time on the same archive
10648 file, they will not know about each other and can corrupt the file.
10650 Possibly a future version of @code{make} will provide a mechanism to
10651 circumvent this problem by serializing all recipes that operate on the
10652 same archive file.  But for the time being, you must either write your
10653 makefiles to avoid this problem in some other way, or not use @code{-j}.
10655 @node Archive Suffix Rules,  , Archive Pitfalls, Archives
10656 @section Suffix Rules for Archive Files
10657 @cindex suffix rule, for archive
10658 @cindex archive, suffix rule for
10659 @cindex library archive, suffix rule for
10660 @cindex @code{.a} (archives)
10662 You can write a special kind of suffix rule for dealing with archive
10663 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
10664 Archive suffix rules are obsolete in GNU @code{make}, because pattern
10665 rules for archives are a more general mechanism (@pxref{Archive
10666 Update}).  But they are retained for compatibility with other
10667 @code{make}s.
10669 To write a suffix rule for archives, you simply write a suffix rule
10670 using the target suffix @samp{.a} (the usual suffix for archive files).
10671 For example, here is the old-fashioned suffix rule to update a library
10672 archive from C source files:
10674 @example
10675 @group
10676 .c.a:
10677         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
10678         $(AR) r $@@ $*.o
10679         $(RM) $*.o
10680 @end group
10681 @end example
10683 @noindent
10684 This works just as if you had written the pattern rule:
10686 @example
10687 @group
10688 (%.o): %.c
10689         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
10690         $(AR) r $@@ $*.o
10691         $(RM) $*.o
10692 @end group
10693 @end example
10695 In fact, this is just what @code{make} does when it sees a suffix rule
10696 with @samp{.a} as the target suffix.  Any double-suffix rule
10697 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
10698 pattern @samp{(%.o)} and a prerequisite pattern of @samp{%.@var{x}}.
10700 Since you might want to use @samp{.a} as the suffix for some other kind
10701 of file, @code{make} also converts archive suffix rules to pattern rules
10702 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
10703 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
10704 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
10706 @node Features, Missing, Archives, Top
10707 @chapter Features of GNU @code{make}
10708 @cindex features of GNU @code{make}
10709 @cindex portability
10710 @cindex compatibility
10712 Here is a summary of the features of GNU @code{make}, for comparison
10713 with and credit to other versions of @code{make}.  We consider the
10714 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
10715 concerned with writing portable makefiles, you should not use the
10716 features of @code{make} listed here, nor the ones in @ref{Missing}.
10718 Many features come from the version of @code{make} in System V.
10720 @itemize @bullet
10721 @item
10722 The @code{VPATH} variable and its special meaning.
10723 @xref{Directory Search, , Searching Directories for Prerequisites}.
10724 This feature exists in System V @code{make}, but is undocumented.
10725 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
10726 @code{VPATH} feature).@refill
10728 @item
10729 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
10730 Allowing multiple files to be included with a single directive is a GNU
10731 extension.
10733 @item
10734 Variables are read from and communicated via the environment.
10735 @xref{Environment, ,Variables from the Environment}.
10737 @item
10738 Options passed through the variable @code{MAKEFLAGS} to recursive
10739 invocations of @code{make}.
10740 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
10742 @item
10743 The automatic variable @code{$%} is set to the member name
10744 in an archive reference.  @xref{Automatic Variables}.
10746 @item
10747 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
10748 and @code{$?} have corresponding forms like @code{$(@@F)} and
10749 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
10750 extension.  @xref{Automatic Variables}.@refill
10752 @item
10753 Substitution variable references.
10754 @xref{Reference, ,Basics of Variable References}.
10756 @item
10757 The command line options @samp{-b} and @samp{-m}, accepted and
10758 ignored.  In System V @code{make}, these options actually do something.
10760 @item
10761 Execution of recursive commands to run @code{make} via the variable
10762 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
10763 @xref{Recursion, ,Recursive Use of @code{make}}.
10765 @item
10766 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
10767 Rules}.  This feature is obsolete in GNU @code{make}, because the
10768 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
10769 Implicit Rules}) allows one pattern rule for installing members in an
10770 archive (@pxref{Archive Update}) to be sufficient.
10772 @item
10773 The arrangement of lines and backslash/newline combinations in
10774 recipes is retained when the recipes are printed, so they appear as
10775 they do in the makefile, except for the stripping of initial
10776 whitespace.
10777 @end itemize
10779 The following features were inspired by various other versions of
10780 @code{make}.  In some cases it is unclear exactly which versions inspired
10781 which others.
10783 @itemize @bullet
10784 @item
10785 Pattern rules using @samp{%}.
10786 This has been implemented in several versions of @code{make}.
10787 We're not sure who invented it first, but it's been spread around a bit.
10788 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.@refill
10790 @item
10791 Rule chaining and implicit intermediate files.
10792 This was implemented by Stu Feldman in his version of @code{make}
10793 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
10794 AT&T Bell Labs in his @code{mk} program (where he terms it
10795 ``transitive closure'').  We do not really know if
10796 we got this from either of them or thought it up ourselves at the
10797 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
10799 @item
10800 The automatic variable @code{$^} containing a list of all prerequisites
10801 of the current target.  We did not invent this, but we have no idea who
10802 did.  @xref{Automatic Variables}.  The automatic variable
10803 @code{$+} is a simple extension of @code{$^}.
10805 @item
10806 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
10807 invented by Andrew Hume in @code{mk}.
10808 @xref{Instead of Execution, ,Instead of Executing Recipes}.
10810 @item
10811 The concept of doing several things at once (parallelism) exists in
10812 many incarnations of @code{make} and similar programs, though not in the
10813 System V or BSD implementations.  @xref{Execution, ,Recipe Execution}.
10815 @item
10816 Modified variable references using pattern substitution come from
10817 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
10818 This functionality was provided in GNU @code{make} by the
10819 @code{patsubst} function before the alternate syntax was implemented
10820 for compatibility with SunOS 4.  It is not altogether clear who
10821 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
10822 4 was released.@refill
10824 @item
10825 The special significance of @samp{+} characters preceding recipe lines
10826 (@pxref{Instead of Execution, ,Instead of Executing Recipes}) is
10827 mandated by @cite{IEEE Standard 1003.2-1992} (POSIX.2).
10829 @item
10830 The @samp{+=} syntax to append to the value of a variable comes from SunOS
10831 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
10833 @item
10834 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
10835 multiple members in a single archive file comes from SunOS 4 @code{make}.
10836 @xref{Archive Members}.
10838 @item
10839 The @code{-include} directive to include makefiles with no error for a
10840 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
10841 @code{make} does not allow multiple makefiles to be specified in one
10842 @code{-include} directive.)  The same feature appears with the name
10843 @code{sinclude} in SGI @code{make} and perhaps others.
10845 @item
10846 The @code{!=} shell assignment operator exists in many BSD of
10847 @code{make} and is purposefully implemented here to behave identically
10848 to those implementations.
10849 @end itemize
10851 The remaining features are inventions new in GNU @code{make}:
10853 @itemize @bullet
10854 @item
10855 Use the @samp{-v} or @samp{--version} option to print version and
10856 copyright information.
10858 @item
10859 Use the @samp{-h} or @samp{--help} option to summarize the options to
10860 @code{make}.
10862 @item
10863 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
10865 @item
10866 Pass command line variable assignments automatically through the
10867 variable @code{MAKE} to recursive @code{make} invocations.
10868 @xref{Recursion, ,Recursive Use of @code{make}}.
10870 @item
10871 Use the @samp{-C} or @samp{--directory} command option to change
10872 directory.  @xref{Options Summary, ,Summary of Options}.
10874 @item
10875 Make verbatim variable definitions with @code{define}.
10876 @xref{Multi-Line, ,Defining Multi-Line Variables}.
10878 @item
10879 Declare phony targets with the special target @code{.PHONY}.
10881 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
10882 different syntax in his @code{mk} program.  This seems to be a case of
10883 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
10885 @item
10886 Manipulate text by calling functions.
10887 @xref{Functions, ,Functions for Transforming Text}.
10889 @item
10890 Use the @samp{-o} or @samp{--old-file}
10891 option to pretend a file's modification-time is old.
10892 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
10894 @item
10895 Conditional execution.
10897 This feature has been implemented numerous times in various versions
10898 of @code{make}; it seems a natural extension derived from the features
10899 of the C preprocessor and similar macro languages and is not a
10900 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
10902 @item
10903 Specify a search path for included makefiles.
10904 @xref{Include, ,Including Other Makefiles}.
10906 @item
10907 Specify extra makefiles to read with an environment variable.
10908 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
10910 @item
10911 Strip leading sequences of @samp{./} from file names, so that
10912 @file{./@var{file}} and @file{@var{file}} are considered to be the
10913 same file.@refill
10915 @item
10916 Use a special search method for library prerequisites written in the
10917 form @samp{-l@var{name}}.
10918 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
10920 @item
10921 Allow suffixes for suffix rules
10922 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
10923 characters.  In other versions of @code{make}, they must begin with
10924 @samp{.} and not contain any @samp{/} characters.
10926 @item
10927 Keep track of the current level of @code{make} recursion using the
10928 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
10930 @item
10931 Provide any goals given on the command line in the variable
10932 @code{MAKECMDGOALS}.  @xref{Goals, ,Arguments to Specify the Goals}.
10934 @item
10935 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
10937 @item
10938 Provide selective @code{vpath} search.
10939 @xref{Directory Search, ,Searching Directories for Prerequisites}.
10941 @item
10942 Provide computed variable references.
10943 @xref{Reference, ,Basics of Variable References}.
10945 @item
10946 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
10947 System V @code{make} has a very, very limited form of this
10948 functionality in that it will check out SCCS files for makefiles.
10950 @item
10951 Various new built-in implicit rules.
10952 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
10954 @item
10955 The built-in variable @samp{MAKE_VERSION} gives the version number of
10956 @code{make}.
10957 @vindex MAKE_VERSION
10958 @end itemize
10960 @node Missing, Makefile Conventions, Features, Top
10961 @chapter Incompatibilities and Missing Features
10962 @cindex incompatibilities
10963 @cindex missing features
10964 @cindex features, missing
10966 The @code{make} programs in various other systems support a few features
10967 that are not implemented in GNU @code{make}.  The POSIX.2 standard
10968 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
10969 require any of these features.@refill
10971 @itemize @bullet
10972 @item
10973 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
10974 of archive file @var{file}.  The member is chosen, not by name, but by
10975 being an object file which defines the linker symbol @var{entry}.@refill
10977 This feature was not put into GNU @code{make} because of the
10978 non-modularity of putting knowledge into @code{make} of the internal
10979 format of archive file symbol tables.
10980 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
10982 @item
10983 Suffixes (used in suffix rules) that end with the character @samp{~}
10984 have a special meaning to System V @code{make};
10985 they refer to the SCCS file that corresponds
10986 to the file one would get without the @samp{~}.  For example, the
10987 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
10988 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
10989 series of such suffix rules is required.
10990 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
10992 In GNU @code{make}, this entire series of cases is handled by two
10993 pattern rules for extraction from SCCS, in combination with the
10994 general feature of rule chaining.
10995 @xref{Chained Rules, ,Chains of Implicit Rules}.
10997 @item
10998 In System V and 4.3 BSD @code{make}, files found by @code{VPATH}
10999 search (@pxref{Directory Search, ,Searching Directories for
11000 Prerequisites}) have their names changed inside recipes.  We feel it
11001 is much cleaner to always use automatic variables and thus make this
11002 feature obsolete.@refill
11004 @item
11005 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
11006 the prerequisites of a rule has the amazingly strange ``feature'' of
11007 expanding to the full name of the @emph{target of that rule}.  We cannot
11008 imagine what went on in the minds of Unix @code{make} developers to do
11009 this; it is utterly inconsistent with the normal definition of @code{$*}.
11010 @vindex * @r{(automatic variable), unsupported bizarre usage}
11012 @item
11013 In some Unix @code{make}s, implicit rule search (@pxref{Implicit
11014 Rules, ,Using Implicit Rules}) is apparently done for @emph{all}
11015 targets, not just those without recipes.  This means you can
11016 do:@refill
11018 @example
11019 @group
11020 foo.o:
11021         cc -c foo.c
11022 @end group
11023 @end example
11025 @noindent
11026 and Unix @code{make} will intuit that @file{foo.o} depends on
11027 @file{foo.c}.@refill
11029 We feel that such usage is broken.  The prerequisite properties of
11030 @code{make} are well-defined (for GNU @code{make}, at least),
11031 and doing such a thing simply does not fit the model.@refill
11033 @item
11034 GNU @code{make} does not include any built-in implicit rules for
11035 compiling or preprocessing EFL programs.  If we hear of anyone who is
11036 using EFL, we will gladly add them.
11038 @item
11039 It appears that in SVR4 @code{make}, a suffix rule can be specified
11040 with no recipe, and it is treated as if it had an empty recipe
11041 (@pxref{Empty Recipes}).  For example:
11043 @example
11044 .c.a:
11045 @end example
11047 @noindent
11048 will override the built-in @file{.c.a} suffix rule.
11050 We feel that it is cleaner for a rule without a recipe to always simply
11051 add to the prerequisite list for the target.  The above example can be
11052 easily rewritten to get the desired behavior in GNU @code{make}:
11054 @example
11055 .c.a: ;
11056 @end example
11058 @item
11059 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
11060 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
11061 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
11062 program it runs returns a nonzero status.  We feel it is cleaner to
11063 write each line of the recipe to stand on its own and not require this
11064 special treatment.
11065 @end itemize
11067 @comment The makefile standards are in a separate file that is also
11068 @comment included by standards.texi.
11069 @include make-stds.texi
11071 @node Quick Reference, Error Messages, Makefile Conventions, Top
11072 @appendix Quick Reference
11074 This appendix summarizes the directives, text manipulation functions,
11075 and special variables which GNU @code{make} understands.
11076 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
11077 and @ref{Options Summary, ,Summary of Options},
11078 for other summaries.
11080 Here is a summary of the directives GNU @code{make} recognizes:
11082 @table @code
11083 @item define @var{variable}
11084 @itemx define @var{variable} =
11085 @itemx define @var{variable} :=
11086 @itemx define @var{variable} ::=
11087 @itemx define @var{variable} +=
11088 @itemx define @var{variable} ?=
11089 @itemx endef
11090 Define multi-line variables.@*
11091 @xref{Multi-Line}.
11093 @item undefine @var{variable}
11094 Undefining variables.@*
11095 @xref{Undefine Directive}.
11097 @item ifdef @var{variable}
11098 @itemx ifndef @var{variable}
11099 @itemx ifeq (@var{a},@var{b})
11100 @itemx ifeq "@var{a}" "@var{b}"
11101 @itemx ifeq '@var{a}' '@var{b}'
11102 @itemx ifneq (@var{a},@var{b})
11103 @itemx ifneq "@var{a}" "@var{b}"
11104 @itemx ifneq '@var{a}' '@var{b}'
11105 @itemx else
11106 @itemx endif
11107 Conditionally evaluate part of the makefile.@*
11108 @xref{Conditionals}.
11110 @item include @var{file}
11111 @itemx -include @var{file}
11112 @itemx sinclude @var{file}
11113 Include another makefile.@*
11114 @xref{Include, ,Including Other Makefiles}.
11116 @item override @var{variable-assignment}
11117 Define a variable, overriding any previous definition, even one from
11118 the command line.@*
11119 @xref{Override Directive, ,The @code{override} Directive}.
11121 @item export
11122 Tell @code{make} to export all variables to child processes by default.@*
11123 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
11125 @item export @var{variable}
11126 @itemx export @var{variable-assignment}
11127 @itemx unexport @var{variable}
11128 Tell @code{make} whether or not to export a particular variable to child
11129 processes.@*
11130 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
11132 @item private @var{variable-assignment}
11133 Do not allow this variable assignment to be inherited by prerequisites.@*
11134 @xref{Suppressing Inheritance}.
11136 @item vpath @var{pattern} @var{path}
11137 Specify a search path for files matching a @samp{%} pattern.@*
11138 @xref{Selective Search, , The @code{vpath} Directive}.
11140 @item vpath @var{pattern}
11141 Remove all search paths previously specified for @var{pattern}.
11143 @item vpath
11144 Remove all search paths previously specified in any @code{vpath}
11145 directive.
11146 @end table
11148 Here is a summary of the built-in functions (@pxref{Functions}):
11150 @table @code
11151 @item $(subst @var{from},@var{to},@var{text})
11152 Replace @var{from} with @var{to} in @var{text}.@*
11153 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11155 @item $(patsubst @var{pattern},@var{replacement},@var{text})
11156 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
11157 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11159 @item $(strip @var{string})
11160 Remove excess whitespace characters from @var{string}.@*
11161 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11163 @item $(findstring @var{find},@var{text})
11164 Locate @var{find} in @var{text}.@*
11165 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11167 @item $(filter @var{pattern}@dots{},@var{text})
11168 Select words in @var{text} that match one of the @var{pattern} words.@*
11169 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11171 @item $(filter-out @var{pattern}@dots{},@var{text})
11172 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
11173 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11175 @item $(sort @var{list})
11176 Sort the words in @var{list} lexicographically, removing duplicates.@*
11177 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11179 @item $(word @var{n},@var{text})
11180 Extract the @var{n}th word (one-origin) of @var{text}.@*
11181 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11183 @item $(words @var{text})
11184 Count the number of words in @var{text}.@*
11185 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11187 @item $(wordlist @var{s},@var{e},@var{text})
11188 Returns the list of words in @var{text} from @var{s} to @var{e}.@*
11189 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11191 @item $(firstword @var{names}@dots{})
11192 Extract the first word of @var{names}.@*
11193 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11195 @item $(lastword @var{names}@dots{})
11196 Extract the last word of @var{names}.@*
11197 @xref{Text Functions, , Functions for String Substitution and Analysis}.
11199 @item $(dir @var{names}@dots{})
11200 Extract the directory part of each file name.@*
11201 @xref{File Name Functions, ,Functions for File Names}.
11203 @item $(notdir @var{names}@dots{})
11204 Extract the non-directory part of each file name.@*
11205 @xref{File Name Functions, ,Functions for File Names}.
11207 @item $(suffix @var{names}@dots{})
11208 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
11209 @xref{File Name Functions, ,Functions for File Names}.
11211 @item $(basename @var{names}@dots{})
11212 Extract the base name (name without suffix) of each file name.@*
11213 @xref{File Name Functions, ,Functions for File Names}.
11215 @item $(addsuffix @var{suffix},@var{names}@dots{})
11216 Append @var{suffix} to each word in @var{names}.@*
11217 @xref{File Name Functions, ,Functions for File Names}.
11219 @item $(addprefix @var{prefix},@var{names}@dots{})
11220 Prepend @var{prefix} to each word in @var{names}.@*
11221 @xref{File Name Functions, ,Functions for File Names}.
11223 @item $(join @var{list1},@var{list2})
11224 Join two parallel lists of words.@*
11225 @xref{File Name Functions, ,Functions for File Names}.
11227 @item $(wildcard @var{pattern}@dots{})
11228 Find file names matching a shell file name pattern (@emph{not} a
11229 @samp{%} pattern).@*
11230 @xref{Wildcard Function, ,The Function @code{wildcard}}.
11232 @item $(realpath @var{names}@dots{})
11233 For each file name in @var{names}, expand to an absolute name that
11234 does not contain any @code{.}, @code{..}, nor symlinks.@*
11235 @xref{File Name Functions, ,Functions for File Names}.
11237 @item $(abspath @var{names}@dots{})
11238 For each file name in @var{names}, expand to an absolute name that
11239 does not contain any @code{.} or @code{..} components, but preserves
11240 symlinks.@*
11241 @xref{File Name Functions, ,Functions for File Names}.
11243 @item $(error @var{text}@dots{})
11244 When this function is evaluated, @code{make} generates a fatal error
11245 with the message @var{text}.@*
11246 @xref{Make Control Functions, ,Functions That Control Make}.
11248 @item $(warning @var{text}@dots{})
11249 When this function is evaluated, @code{make} generates a warning with
11250 the message @var{text}.@*
11251 @xref{Make Control Functions, ,Functions That Control Make}.
11253 @item $(shell @var{command})
11254 Execute a shell command and return its output.@*
11255 @xref{Shell Function, , The @code{shell} Function}.
11257 @item $(origin @var{variable})
11258 Return a string describing how the @code{make} variable @var{variable} was
11259 defined.@*
11260 @xref{Origin Function, , The @code{origin} Function}.
11262 @item $(flavor @var{variable})
11263 Return a string describing the flavor of the @code{make} variable
11264 @var{variable}.@*
11265 @xref{Flavor Function, , The @code{flavor} Function}.
11267 @item $(foreach @var{var},@var{words},@var{text})
11268 Evaluate @var{text} with @var{var} bound to each word in @var{words},
11269 and concatenate the results.@*
11270 @xref{Foreach Function, ,The @code{foreach} Function}.
11272 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
11273 Evaluate the condition @var{condition}; if it's non-empty substitute
11274 the expansion of the @var{then-part} otherwise substitute the
11275 expansion of the @var{else-part}.@*
11276 @xref{Conditional Functions, ,Functions for Conditionals}.
11278 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
11279 Evaluate each condition @var{conditionN} one at a time; substitute the
11280 first non-empty expansion.  If all expansions are empty, substitute
11281 the empty string.@*
11282 @xref{Conditional Functions, ,Functions for Conditionals}.
11284 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
11285 Evaluate each condition @var{conditionN} one at a time; if any
11286 expansion results in the empty string substitute the empty string.  If
11287 all expansions result in a non-empty string, substitute the expansion
11288 of the last @var{condition}.@*
11289 @xref{Conditional Functions, ,Functions for Conditionals}.
11291 @item $(call @var{var},@var{param},@dots{})
11292 Evaluate the variable @var{var} replacing any references to @code{$(1)},
11293 @code{$(2)} with the first, second, etc.@: @var{param} values.@*
11294 @xref{Call Function, ,The @code{call} Function}.
11296 @item $(eval @var{text})
11297 Evaluate @var{text} then read the results as makefile commands.
11298 Expands to the empty string.@*
11299 @xref{Eval Function, ,The @code{eval} Function}.
11301 @item $(value @var{var})
11302 Evaluates to the contents of the variable @var{var}, with no expansion
11303 performed on it.@*
11304 @xref{Value Function, ,The @code{value} Function}.
11305 @end table
11307 Here is a summary of the automatic variables.
11308 @xref{Automatic Variables},
11309 for full information.
11311 @table @code
11312 @item $@@
11313 The file name of the target.
11315 @item $%
11316 The target member name, when the target is an archive member.
11318 @item $<
11319 The name of the first prerequisite.
11321 @item $?
11322 The names of all the prerequisites that are
11323 newer than the target, with spaces between them.
11324 For prerequisites which are archive members, only
11325 the named member is used (@pxref{Archives}).
11327 @item $^
11328 @itemx $+
11329 The names of all the prerequisites, with spaces between them.  For
11330 prerequisites which are archive members, only the named member is used
11331 (@pxref{Archives}).  The value of @code{$^} omits duplicate
11332 prerequisites, while @code{$+} retains them and preserves their order.
11334 @item $*
11335 The stem with which an implicit rule matches
11336 (@pxref{Pattern Match, ,How Patterns Match}).
11338 @item $(@@D)
11339 @itemx $(@@F)
11340 The directory part and the file-within-directory part of @code{$@@}.
11342 @item $(*D)
11343 @itemx $(*F)
11344 The directory part and the file-within-directory part of @code{$*}.
11346 @item $(%D)
11347 @itemx $(%F)
11348 The directory part and the file-within-directory part of @code{$%}.
11350 @item $(<D)
11351 @itemx $(<F)
11352 The directory part and the file-within-directory part of @code{$<}.
11354 @item $(^D)
11355 @itemx $(^F)
11356 The directory part and the file-within-directory part of @code{$^}.
11358 @item $(+D)
11359 @itemx $(+F)
11360 The directory part and the file-within-directory part of @code{$+}.
11362 @item $(?D)
11363 @itemx $(?F)
11364 The directory part and the file-within-directory part of @code{$?}.
11365 @end table
11367 These variables are used specially by GNU @code{make}:
11369 @table @code
11370 @item MAKEFILES
11372 Makefiles to be read on every invocation of @code{make}.@*
11373 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
11375 @item VPATH
11377 Directory search path for files not found in the current directory.@*
11378 @xref{General Search, , @code{VPATH} Search Path for All Prerequisites}.
11380 @item SHELL
11382 The name of the system default command interpreter, usually @file{/bin/sh}.
11383 You can set @code{SHELL} in the makefile to change the shell used to run
11384 recipes.  @xref{Execution, ,Recipe Execution}.  The @code{SHELL}
11385 variable is handled specially when importing from and exporting to the
11386 environment.  @xref{Choosing the Shell}.
11388 @item MAKESHELL
11390 On MS-DOS only, the name of the command interpreter that is to be used
11391 by @code{make}.  This value takes precedence over the value of
11392 @code{SHELL}.  @xref{Execution, ,MAKESHELL variable}.
11394 @item MAKE
11396 The name with which @code{make} was invoked.  Using this variable in
11397 recipes has special meaning.  @xref{MAKE Variable, ,How the
11398 @code{MAKE} Variable Works}.
11400 @item MAKELEVEL
11402 The number of levels of recursion (sub-@code{make}s).@*
11403 @xref{Variables/Recursion}.
11405 @item MAKEFLAGS
11407 The flags given to @code{make}.  You can set this in the environment or
11408 a makefile to set flags.@*
11409 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
11411 It is @emph{never} appropriate to use @code{MAKEFLAGS} directly in a
11412 recipe line: its contents may not be quoted correctly for use in the
11413 shell.  Always allow recursive @code{make}'s to obtain these values
11414 through the environment from its parent.
11416 @item MAKECMDGOALS
11418 The targets given to @code{make} on the command line.  Setting this
11419 variable has no effect on the operation of @code{make}.@*
11420 @xref{Goals, ,Arguments to Specify the Goals}.
11422 @item CURDIR
11424 Set to the pathname of the current working directory (after all
11425 @code{-C} options are processed, if any).  Setting this variable has no
11426 effect on the operation of @code{make}.@*
11427 @xref{Recursion, ,Recursive Use of @code{make}}.
11429 @item SUFFIXES
11431 The default list of suffixes before @code{make} reads any makefiles.
11433 @item .LIBPATTERNS
11434 Defines the naming of the libraries @code{make} searches for, and their
11435 order.@*
11436 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
11437 @end table
11439 @node Error Messages, Complex Makefile, Quick Reference, Top
11440 @comment  node-name,  next,  previous,  up
11441 @appendix Errors Generated by Make
11443 Here is a list of the more common errors you might see generated by
11444 @code{make}, and some information about what they mean and how to fix
11445 them.
11447 Sometimes @code{make} errors are not fatal, especially in the presence
11448 of a @code{-} prefix on a recipe line, or the @code{-k} command line
11449 option.  Errors that are fatal are prefixed with the string
11450 @code{***}.
11452 Error messages are all either prefixed with the name of the program
11453 (usually @samp{make}), or, if the error is found in a makefile, the name
11454 of the file and line number containing the problem.
11456 In the table below, these common prefixes are left off.
11458 @table @samp
11460 @item [@var{foo}] Error @var{NN}
11461 @itemx [@var{foo}] @var{signal description}
11462 These errors are not really @code{make} errors at all.  They mean that a
11463 program that @code{make} invoked as part of a recipe returned a
11464 non-0 error code (@samp{Error @var{NN}}), which @code{make} interprets
11465 as failure, or it exited in some other abnormal fashion (with a
11466 signal of some type).  @xref{Errors, ,Errors in Recipes}.
11468 If no @code{***} is attached to the message, then the sub-process failed
11469 but the rule in the makefile was prefixed with the @code{-} special
11470 character, so @code{make} ignored the error.
11472 @item missing separator.  Stop.
11473 @itemx missing separator (did you mean TAB instead of 8 spaces?).  Stop.
11474 This means that @code{make} could not understand much of anything
11475 about the makefile line it just read.  GNU @code{make} looks for
11476 various separators (@code{:}, @code{=}, recipe prefix characters,
11477 etc.) to indicate what kind of line it's parsing.  This message means
11478 it couldn't find a valid one.
11480 One of the most common reasons for this message is that you (or
11481 perhaps your oh-so-helpful editor, as is the case with many MS-Windows
11482 editors) have attempted to indent your recipe lines with spaces
11483 instead of a tab character.  In this case, @code{make} will use the
11484 second form of the error above.  Remember that every line in the
11485 recipe must begin with a tab character (unless you set
11486 @code{.RECIPEPREFIX}; @pxref{Special Variables}).  Eight spaces do not
11487 count.  @xref{Rule Syntax}.
11489 @item recipe commences before first target.  Stop.
11490 @itemx missing rule before recipe.  Stop.
11491 This means the first thing in the makefile seems to be part of a
11492 recipe: it begins with a recipe prefix character and doesn't appear to
11493 be a legal @code{make} directive (such as a variable assignment).
11494 Recipes must always be associated with a target.
11496 The second form is generated if the line has a semicolon as the first
11497 non-whitespace character; @code{make} interprets this to mean you left
11498 out the "target: prerequisite" section of a rule.  @xref{Rule Syntax}.
11500 @item No rule to make target `@var{xxx}'.
11501 @itemx No rule to make target `@var{xxx}', needed by `@var{yyy}'.
11502 This means that @code{make} decided it needed to build a target, but
11503 then couldn't find any instructions in the makefile on how to do that,
11504 either explicit or implicit (including in the default rules database).
11506 If you want that file to be built, you will need to add a rule to your
11507 makefile describing how that target can be built.  Other possible
11508 sources of this problem are typos in the makefile (if that file name is
11509 wrong) or a corrupted source tree (if that file is not supposed to be
11510 built, but rather only a prerequisite).
11512 @item No targets specified and no makefile found.  Stop.
11513 @itemx No targets.  Stop.
11514 The former means that you didn't provide any targets to be built on the
11515 command line, and @code{make} couldn't find any makefiles to read in.
11516 The latter means that some makefile was found, but it didn't contain any
11517 default goal and none was given on the command line.  GNU @code{make}
11518 has nothing to do in these situations.
11519 @xref{Makefile Arguments, ,Arguments to Specify the Makefile}.@refill
11521 @item Makefile `@var{xxx}' was not found.
11522 @itemx Included makefile `@var{xxx}' was not found.
11523 A makefile specified on the command line (first form) or included
11524 (second form) was not found.
11526 @item warning: overriding recipe for target `@var{xxx}'
11527 @itemx warning: ignoring old recipe for target `@var{xxx}'
11528 GNU @code{make} allows only one recipe to be specified per target
11529 (except for double-colon rules).  If you give a recipe for a target
11530 which already has been defined to have one, this warning is issued and
11531 the second recipe will overwrite the first.  @xref{Multiple Rules,
11532 ,Multiple Rules for One Target}.
11534 @item Circular @var{xxx} <- @var{yyy} dependency dropped.
11535 This means that @code{make} detected a loop in the dependency graph:
11536 after tracing the prerequisite @var{yyy} of target @var{xxx}, and its
11537 prerequisites, etc., one of them depended on @var{xxx} again.
11539 @item Recursive variable `@var{xxx}' references itself (eventually).  Stop.
11540 This means you've defined a normal (recursive) @code{make} variable
11541 @var{xxx} that, when it's expanded, will refer to itself (@var{xxx}).
11542 This is not allowed; either use simply-expanded variables (@samp{:=}
11543 or @samp{::=}) or use the append operator (@samp{+=}).  @xref{Using
11544 Variables, ,How to Use Variables}.
11546 @item Unterminated variable reference.  Stop.
11547 This means you forgot to provide the proper closing parenthesis
11548 or brace in your variable or function reference.
11550 @item insufficient arguments to function `@var{xxx}'.  Stop.
11551 This means you haven't provided the requisite number of arguments for
11552 this function.  See the documentation of the function for a description
11553 of its arguments.  @xref{Functions, ,Functions for Transforming Text}.
11555 @item missing target pattern.  Stop.
11556 @itemx multiple target patterns.  Stop.
11557 @itemx target pattern contains no `%'.  Stop.
11558 @itemx mixed implicit and static pattern rules.  Stop.
11559 These are generated for malformed static pattern rules.  The first means
11560 there's no pattern in the target section of the rule; the second means
11561 there are multiple patterns in the target section; the third means
11562 the target doesn't contain a pattern character (@code{%}); and the
11563 fourth means that all three parts of the static pattern rule contain
11564 pattern characters (@code{%})--only the first two parts should.
11565 @xref{Static Usage, ,Syntax of Static Pattern Rules}.
11567 @item warning: -jN forced in submake: disabling jobserver mode.
11568 This warning and the next are generated if @code{make} detects error
11569 conditions related to parallel processing on systems where
11570 sub-@code{make}s can communicate (@pxref{Options/Recursion,
11571 ,Communicating Options to a Sub-@code{make}}).  This warning is
11572 generated if a recursive invocation of a @code{make} process is forced
11573 to have @samp{-j@var{N}} in its argument list (where @var{N} is greater
11574 than one).  This could happen, for example, if you set the @code{MAKE}
11575 environment variable to @samp{make -j2}.  In this case, the
11576 sub-@code{make} doesn't communicate with other @code{make} processes and
11577 will simply pretend it has two jobs of its own.
11579 @item warning: jobserver unavailable: using -j1.  Add `+' to parent make rule.
11580 In order for @code{make} processes to communicate, the parent will pass
11581 information to the child.  Since this could result in problems if the
11582 child process isn't actually a @code{make}, the parent will only do this
11583 if it thinks the child is a @code{make}.  The parent uses the normal
11584 algorithms to determine this (@pxref{MAKE Variable, ,How the @code{MAKE}
11585 Variable Works}).  If the makefile is constructed such that the parent
11586 doesn't know the child is a @code{make} process, then the child will
11587 receive only part of the information necessary.  In this case, the child
11588 will generate this warning message and proceed with its build in a
11589 sequential manner.
11591 @end table
11593 @node Complex Makefile, GNU Free Documentation License, Error Messages, Top
11594 @appendix Complex Makefile Example
11596 Here is the makefile for the GNU @code{tar} program.  This is a
11597 moderately complex makefile.  The first line uses a @code{#!} setting
11598 to allow the makefile to be executed directly.
11600 Because it is the first target, the default goal is @samp{all}.  An
11601 interesting feature of this makefile is that @file{testpad.h} is a
11602 source file automatically created by the @code{testpad} program,
11603 itself compiled from @file{testpad.c}.
11605 If you type @samp{make} or @samp{make all}, then @code{make} creates
11606 the @file{tar} executable, the @file{rmt} daemon that provides
11607 remote tape access, and the @file{tar.info} Info file.
11609 If you type @samp{make install}, then @code{make} not only creates
11610 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
11611 them.
11613 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
11614 files, and the @file{tar}, @file{rmt}, @file{testpad},
11615 @file{testpad.h}, and @file{core} files.
11617 If you type @samp{make distclean}, then @code{make} not only removes
11618 the same files as does @samp{make clean} but also the
11619 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
11620 (Although it is not evident, this makefile (and
11621 @file{config.status}) is generated by the user with the
11622 @code{configure} program, which is provided in the @code{tar}
11623 distribution, but is not shown here.)
11625 If you type @samp{make realclean}, then @code{make} removes the same
11626 files as does @samp{make distclean} and also removes the Info files
11627 generated from @file{tar.texinfo}.
11629 In addition, there are targets @code{shar} and @code{dist} that create
11630 distribution kits.
11632 @example
11633 @group
11634 #!/usr/bin/make -f
11635 # Generated automatically from Makefile.in by configure.
11636 # Un*x Makefile for GNU tar program.
11637 # Copyright (C) 1991 Free Software Foundation, Inc.
11638 @end group
11640 @group
11641 # This program is free software; you can redistribute
11642 # it and/or modify it under the terms of the GNU
11643 # General Public License @dots{}
11644 @dots{}
11645 @dots{}
11646 @end group
11648 SHELL = /bin/sh
11650 #### Start of system configuration section. ####
11652 srcdir = .
11654 @group
11655 # If you use gcc, you should either run the
11656 # fixincludes script that comes with it or else use
11657 # gcc with the -traditional option.  Otherwise ioctl
11658 # calls will be compiled incorrectly on some systems.
11659 CC = gcc -O
11660 YACC = bison -y
11661 INSTALL = /usr/local/bin/install -c
11662 INSTALLDATA = /usr/local/bin/install -c -m 644
11663 @end group
11665 # Things you might add to DEFS:
11666 # -DSTDC_HEADERS        If you have ANSI C headers and
11667 #                       libraries.
11668 # -DPOSIX               If you have POSIX.1 headers and
11669 #                       libraries.
11670 # -DBSD42               If you have sys/dir.h (unless
11671 #                       you use -DPOSIX), sys/file.h,
11672 #                       and st_blocks in `struct stat'.
11673 # -DUSG                 If you have System V/ANSI C
11674 #                       string and memory functions
11675 #                       and headers, sys/sysmacros.h,
11676 #                       fcntl.h, getcwd, no valloc,
11677 #                       and ndir.h (unless
11678 #                       you use -DDIRENT).
11679 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not
11680 #                       include memory.h.
11681 # -DDIRENT              If USG and you have dirent.h
11682 #                       instead of ndir.h.
11683 # -DSIGTYPE=int         If your signal handlers
11684 #                       return int, not void.
11685 # -DNO_MTIO             If you lack sys/mtio.h
11686 #                       (magtape ioctls).
11687 # -DNO_REMOTE           If you do not have a remote shell
11688 #                       or rexec.
11689 # -DUSE_REXEC           To use rexec for remote tape
11690 #                       operations instead of
11691 #                       forking rsh or remsh.
11692 # -DVPRINTF_MISSING     If you lack vprintf function
11693 #                       (but have _doprnt).
11694 # -DDOPRNT_MISSING      If you lack _doprnt function.
11695 #                       Also need to define
11696 #                       -DVPRINTF_MISSING.
11697 # -DFTIME_MISSING       If you lack ftime system call.
11698 # -DSTRSTR_MISSING      If you lack strstr function.
11699 # -DVALLOC_MISSING      If you lack valloc function.
11700 # -DMKDIR_MISSING       If you lack mkdir and
11701 #                       rmdir system calls.
11702 # -DRENAME_MISSING      If you lack rename system call.
11703 # -DFTRUNCATE_MISSING   If you lack ftruncate
11704 #                       system call.
11705 # -DV7                  On Version 7 Unix (not
11706 #                       tested in a long time).
11707 # -DEMUL_OPEN3          If you lack a 3-argument version
11708 #                       of open, and want to emulate it
11709 #                       with system calls you do have.
11710 # -DNO_OPEN3            If you lack the 3-argument open
11711 #                       and want to disable the tar -k
11712 #                       option instead of emulating open.
11713 # -DXENIX               If you have sys/inode.h
11714 #                       and need it 94 to be included.
11716 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
11717         -DVPRINTF_MISSING -DBSD42
11718 # Set this to rtapelib.o unless you defined NO_REMOTE,
11719 # in which case make it empty.
11720 RTAPELIB = rtapelib.o
11721 LIBS =
11722 DEF_AR_FILE = /dev/rmt8
11723 DEFBLOCKING = 20
11725 @group
11726 CDEBUG = -g
11727 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
11728         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
11729         -DDEFBLOCKING=$(DEFBLOCKING)
11730 LDFLAGS = -g
11731 @end group
11733 @group
11734 prefix = /usr/local
11735 # Prefix for each installed program,
11736 # normally empty or `g'.
11737 binprefix =
11739 # The directory to install tar in.
11740 bindir = $(prefix)/bin
11742 # The directory to install the info files in.
11743 infodir = $(prefix)/info
11744 @end group
11746 #### End of system configuration section. ####
11748 @group
11749 SRCS_C  = tar.c create.c extract.c buffer.c   \
11750           getoldopt.c update.c gnu.c mangle.c \
11751           version.c list.c names.c diffarch.c \
11752           port.c wildmat.c getopt.c getopt1.c \
11753           regex.c
11754 SRCS_Y  = getdate.y
11755 SRCS    = $(SRCS_C) $(SRCS_Y)
11756 OBJS    = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB)
11757 @end group
11758 @group
11759 AUX =   README COPYING ChangeLog Makefile.in  \
11760         makefile.pc configure configure.in \
11761         tar.texinfo tar.info* texinfo.tex \
11762         tar.h port.h open3.h getopt.h regex.h \
11763         rmt.h rmt.c rtapelib.c alloca.c \
11764         msd_dir.h msd_dir.c tcexparg.c \
11765         level-0 level-1 backup-specs testpad.c
11766 @end group
11768 .PHONY: all
11769 all:    tar rmt tar.info
11771 @group
11772 tar:    $(OBJS)
11773         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
11774 @end group
11776 @group
11777 rmt:    rmt.c
11778         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
11779 @end group
11781 @group
11782 tar.info: tar.texinfo
11783         makeinfo tar.texinfo
11784 @end group
11786 @group
11787 .PHONY: install
11788 install: all
11789         $(INSTALL) tar $(bindir)/$(binprefix)tar
11790         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
11791         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
11792 @end group
11794 @group
11795 $(OBJS): tar.h port.h testpad.h
11796 regex.o buffer.o tar.o: regex.h
11797 # getdate.y has 8 shift/reduce conflicts.
11798 @end group
11800 @group
11801 testpad.h: testpad
11802         ./testpad
11803 @end group
11805 @group
11806 testpad: testpad.o
11807         $(CC) -o $@@ testpad.o
11808 @end group
11810 @group
11811 TAGS:   $(SRCS)
11812         etags $(SRCS)
11813 @end group
11815 @group
11816 .PHONY: clean
11817 clean:
11818         rm -f *.o tar rmt testpad testpad.h core
11819 @end group
11821 @group
11822 .PHONY: distclean
11823 distclean: clean
11824         rm -f TAGS Makefile config.status
11825 @end group
11827 @group
11828 .PHONY: realclean
11829 realclean: distclean
11830         rm -f tar.info*
11831 @end group
11833 @group
11834 .PHONY: shar
11835 shar: $(SRCS) $(AUX)
11836         shar $(SRCS) $(AUX) | compress \
11837           > tar-`sed -e '/version_string/!d' \
11838                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11839                      -e q
11840                      version.c`.shar.Z
11841 @end group
11843 @group
11844 .PHONY: dist
11845 dist: $(SRCS) $(AUX)
11846         echo tar-`sed \
11847              -e '/version_string/!d' \
11848              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11849              -e q
11850              version.c` > .fname
11851         -rm -rf `cat .fname`
11852         mkdir `cat .fname`
11853         ln $(SRCS) $(AUX) `cat .fname`
11854         tar chZf `cat .fname`.tar.Z `cat .fname`
11855         -rm -rf `cat .fname` .fname
11856 @end group
11858 @group
11859 tar.zoo: $(SRCS) $(AUX)
11860         -rm -rf tmp.dir
11861         -mkdir tmp.dir
11862         -rm tar.zoo
11863         for X in $(SRCS) $(AUX) ; do \
11864             echo $$X ; \
11865             sed 's/$$/^M/' $$X \
11866             > tmp.dir/$$X ; done
11867         cd tmp.dir ; zoo aM ../tar.zoo *
11868         -rm -rf tmp.dir
11869 @end group
11870 @end example
11872 @node GNU Free Documentation License, Concept Index, Complex Makefile, Top
11873 @appendixsec GNU Free Documentation License
11874 @cindex FDL, GNU Free Documentation License
11875 @include fdl.texi
11877 @node Concept Index, Name Index, GNU Free Documentation License, Top
11878 @unnumbered Index of Concepts
11880 @printindex cp
11882 @node Name Index,  , Concept Index, Top
11883 @unnumbered Index of Functions, Variables, & Directives
11885 @printindex fn
11887 @bye