Formerly default.c.~31~
[make.git] / make.texinfo
blob55963c97494d59fc4d494e1f9208f06a02896e50
1 \input texinfo                @c -*- Texinfo -*-
2 @c %**start of header 
3 @setfilename make.info
4 @settitle GNU @code{make}
5 @setchapternewpage odd
6 @c %**end of header
8 @c FSF publishers: format makebook.texi instead of using this file directly.
10 @set EDITION 0.44
11 @set VERSION 3.69 Beta
12 @set UPDATED 3 November 1993
13 @set UPDATE-MONTH November 1993
15 @c finalout
17 @c ISPELL CHECK: done, 10 June 1993 --roland
19 @c Combine the variable and function indices:
20 @syncodeindex vr fn
21 @c Combine the program and concept indices:
22 @syncodeindex pg cp
24 @ifinfo
25 This file documents the GNU Make utility, which determines
26 automatically which pieces of a large program need to be recompiled,
27 and issues the commands to recompile them.
29 This is Edition @value{EDITION}, last updated @value{UPDATED},
30 of @cite{The GNU Make Manual}, for @code{make}, Version @value{VERSION}.
32 Copyright (C) 1988, '89, '90, '91, '92, '93 Free Software Foundation, Inc.
34 Permission is granted to make and distribute verbatim copies of
35 this manual provided the copyright notice and this permission notice
36 are preserved on all copies.
38 @ignore
39 Permission is granted to process this file through TeX and print the
40 results, provided the printed document carries copying permission
41 notice identical to this one except for the removal of this paragraph
42 (this paragraph not being relevant to the printed manual).
44 @end ignore
45 Permission is granted to copy and distribute modified versions of this
46 manual under the conditions for verbatim copying, provided that the entire
47 resulting derived work is distributed under the terms of a permission
48 notice identical to this one.
50 Permission is granted to copy and distribute translations of this manual
51 into another language, under the above conditions for modified versions,
52 except that this permission notice may be stated in a translation approved
53 by the Free Software Foundation.
54 @end ifinfo
56 @iftex
57 @shorttitlepage GNU Make
58 @end iftex
59 @titlepage
60 @title GNU Make
61 @subtitle A Program for Directing Recompilation
62 @subtitle Edition @value{EDITION}, for @code{make} Version @value{VERSION}.
63 @subtitle @value{UPDATE-MONTH}
64 @author Richard M. Stallman and Roland McGrath
65 @page
66 @vskip 0pt plus 1filll
67 Copyright @copyright{} 1988, '89, '90, '91, '92, '93 Free Software Foundation, Inc.
68 @sp 2
69 Published by the Free Software Foundation @*
70 675 Massachusetts Avenue, @*
71 Cambridge, MA 02139 USA @*
72 Printed copies are available for $20 each. @*
73 ISBN 1-882114-16-7 @*
75 Permission is granted to make and distribute verbatim copies of
76 this manual provided the copyright notice and this permission notice
77 are preserved on all copies.
79 Permission is granted to copy and distribute modified versions of this
80 manual under the conditions for verbatim copying, provided that the entire
81 resulting derived work is distributed under the terms of a permission
82 notice identical to this one.
84 Permission is granted to copy and distribute translations of this manual
85 into another language, under the above conditions for modified versions,
86 except that this permission notice may be stated in a translation approved
87 by the Free Software Foundation.
88 @sp 2
89 Cover art by Etienne Suvasa.
90 @end titlepage
91 @page
93 @ifinfo
94 @node Top, Overview, (dir), (dir)
95 @top Make
97 The GNU @code{make} utility automatically determines which pieces of a
98 large program need to be recompiled, and issues the commands to
99 recompile them.@refill
101 This is Edition @value{EDITION} of the @cite{GNU Make Manual},
102 last updated @value{UPDATED}
103 for @code{make} Version @value{VERSION}.@refill
105 This manual describes @code{make} and contains the following chapters:@refill
106 @end ifinfo
108 @menu
109 * Overview::                    Overview of @code{make}.
110 * Introduction::                An introduction to @code{make}.
111 * Makefiles::                   Makefiles tell @code{make} what to do.
112 * Rules::                       Rules describe when a file must be remade.
113 * Commands::                    Commands say how to remake a file.
114 * Using Variables::             You can use variables to avoid repetition.
115 * Conditionals::                Use or ignore parts of the makefile based
116                                  on the values of variables.
117 * Functions::                   Many powerful ways to manipulate text.
118 * make Invocation: Running.     How to invoke @code{make} on the command line.
119 * Implicit Rules::              Use implicit rules to treat many files alike,
120                                  based on their file names.
121 * Archives::                    How @code{make} can update library archives.
122 * Features::                    Features GNU @code{make} has over other @code{make}s.
123 * Missing::                     What GNU @code{make} lacks from other @code{make}s.
124 * Makefile Conventions::        Conventions for makefiles in GNU programs.
125 * Quick Reference::             A quick reference for experienced users.
126 * Complex Makefile::            A real example of a straightforward,
127                                  but nontrivial, makefile.
128 * Concept Index::               Index of Concepts
129 * Name Index::                  Index of Functions, Variables, & Directives
131  --- The Detailed Node Listing ---
133 Overview of @code{make}
135 * Preparing::                   Preparing and Running Make
136 * Reading::                     On Reading this Text
137 * Bugs::                        Problems and Bugs
139 An Introduction to Makefiles
141 * Rule Introduction::           What a rule looks like.
142 * Simple Makefile::             A Simple Makefile
143 * How Make Works::              How @code{make} Processes This Makefile
144 * Variables Simplify::          Variables Make Makefiles Simpler
145 * make Deduces::                Letting @code{make} Deduce the Commands
146 * Combine By Dependency::       Another Style of Makefile
147 * Cleanup::                     Rules for Cleaning the Directory
149 Writing Makefiles
151 * Makefile Contents::           What makefiles contain.
152 * Makefile Names::              How to name your makefile.
153 * Include::                     How one makefile can use another makefile.
154 * MAKEFILES Variable::          The environment can specify extra makefiles.
155 * Remaking Makefiles::          How makefiles get remade.
156 * Overriding Makefiles::        How to override part of one makefile
157                                  with another makefile.
159 Writing Rules
161 * Rule Example::                An example explained.
162 * Rule Syntax::                 General syntax explained.
163 * Wildcards::                   Using wildcard characters such as `*'.
164 * Directory Search::            Searching other directories for source files.
165 * Phony Targets::               Using a target that is not a real file's name.
166 * Force Targets::               You can use a target without commands
167                                   or dependencies to mark other 
168                                   targets as phony.
169 * Empty Targets::               When only the date matters and the
170                                   files are empty.
171 * Special Targets::             Targets with special built-in meanings.
172 * Multiple Targets::            When to make use of several targets in a rule.
173 * Multiple Rules::              How to use several rules with the same target.
174 * Static Pattern::              Static pattern rules apply to multiple targets
175                                   and can vary the dependencies according to 
176                                   the target name.
177 * Double-Colon::                How to use a special kind of rule to allow
178                                   several independent rules for one target.
179 * Automatic Dependencies::      How to automatically generate rules giving
180                                  dependencies from the source files themselves.
182 Using Wildcard Characters in File Names
184 * Wildcard Examples::           Several examples
185 * Wildcard Pitfall::            Problems to avoid.
186 * Wildcard Function::           How to cause wildcard expansion where
187                                   it does not normally take place.
189 Searching Directories for Dependencies
191 * General Search::              Specifying a search path that applies 
192                                   to every dependency.
193 * Selective Search::            Specifying a search path 
194                                   for a specified class of names.
195 * Commands/Search::             How to write shell commands that work together
196                                   with search paths.
197 * Implicit/Search::             How search paths affect implicit rules.
198 * Libraries/Search::            Directory search for link libraries.
200 Static Pattern Rules
202 * Static Usage::                The syntax of static pattern rules.
203 * Static versus Implicit::      When are they better than implicit rules?
205 Writing the Commands in Rules
207 * Echoing::                     How to control when commands are echoed.
208 * Execution::                   How commands are executed.
209 * Parallel::                    How commands can be executed in parallel.
210 * Errors::                      What happens after a command execution error. 
211 * Interrupts::                  What happens when a command is interrupted.
212 * Recursion::                   Invoking @code{make} from makefiles.
213 * Sequences::                   Defining canned sequences of commands.
214 * Empty Commands::              Defining useful, do-nothing commands.
216 Recursive Use of @code{make}
218 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
219 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
220 * Options/Recursion::           How to communicate options to a sub-@code{make}.
221 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
222                                  helps debug use of recursive @code{make} commands.
224 How to Use Variables
226 * Reference::                   How to use the value of a variable.
227 * Flavors::                     Variables come in two flavors.
228 * Advanced::                    Advanced features for referencing a variable.
229 * Values::                      All the ways variables get their values.
230 * Setting::                     How to set a variable in the makefile.
231 * Appending::                   How to append more text to the old value
232                                   of a variable.
233 * Override Directive::          How to set a variable in the makefile even if
234                                   the user has set it with a command argument.
235 * Defining::                    An alternate way to set a variable 
236                                   to a verbatim string.
237 * Environment::                 Variable values can come from the environment.
239 Advanced Features for Reference to Variables
241 * Substitution Refs::           Referencing a variable with 
242                                   substitutions on the value.
243 * Computed Names::              Computing the name of the variable to refer to.
245 Conditional Parts of Makefiles
247 * Conditional Example::         Example of a conditional
248 * Conditional Syntax::          The syntax of conditionals.
249 * Testing Flags::               Conditionals that test flags.
251 Functions for Transforming Text
253 * Syntax of Functions::         How to write a function call.
254 * Text Functions::              General-purpose text manipulation functions.
255 * Filename Functions::          Functions for manipulating file names.
256 * Foreach Function::            Repeat some text with controlled variation.
257 * Origin Function::             Find where a variable got its value.
258 * Shell Function::              Substitute the output of a shell command.
260 How to Run @code{make}
262 * Makefile Arguments::          How to specify which makefile to use.
263 * Goals::                       How to use goal arguments to specify which 
264                                   parts of the makefile to use.
265 * Instead of Execution::        How to use mode flags to specify what
266                                   kind of thing to do with the commands 
267                                   in the makefile other than simply 
268                                   execute them.
269 * Avoiding Compilation::        How to avoid recompiling certain files.
270 * Overriding::                  How to override a variable to specify 
271                                   an alternate compiler and other things.
272 * Testing::                     How to proceed past some errors, to 
273                                   test compilation.
274 * Options Summary::             Summary of Options
276 Using Implicit Rules
278 * Using Implicit::              How to use an existing implicit rule
279                                   to get the commands for updating a file.
280 * Catalogue of Rules::          A list of built-in implicit rules.
281 * Implicit Variables::          How to change what predefined rules do.
282 * Chained Rules::               How to use a chain of implicit rules.
283 * Pattern Rules::               How to define new implicit rules.
284 * Last Resort::                 How to defining commands for rules 
285                                   which cannot find any.
286 * Suffix Rules::                The old-fashioned style of implicit rule.
287 * Search Algorithm::            The precise algorithm for applying 
288                                   implicit rules.
290 Defining and Redefining Pattern Rules
292 * Pattern Intro::               An introduction to pattern rules.
293 * Pattern Examples::            Examples of pattern rules.
294 * Automatic::                   How to use automatic variables in the
295                                   commands of implicit rules.
296 * Pattern Match::               How patterns match.
297 * Match-Anything Rules::        Precautions you should take prior to
298                                   defining rules that can match any
299                                   target file whatever.
300 * Canceling Rules::             How to override or cancel built-in rules.
302 Using @code{make} to Update Archive Files
304 * Archive Members::             Archive members as targets.
305 * Archive Update::              The implicit rule for archive member targets.
306 * Archive Suffix Rules::        You can write a special kind of suffix rule
307                                   for updating archives.
309 Implicit Rule for Archive Member Targets
311 * Archive Symbols::             How to update archive symbol directories.
312 @end menu
314 @node Overview, Introduction, Top, Top
315 @comment  node-name,  next,  previous,  up
316 @chapter Overview of @code{make}
318 The @code{make} utility automatically determines which pieces of a large
319 program need to be recompiled, and issues commands to recompile them.
320 This manual describes GNU @code{make}, which was implemented by Richard
321 Stallman and Roland McGrath.  GNU @code{make} conforms to section 6.2 of
322 @cite{IEEE Standard 1003.2-1992} (POSIX.2).
323 @cindex POSIX
324 @cindex IEEE Standard 1003.2
325 @cindex standards conformance
327 Our examples show C programs, since they are most common, but you can use
328 @code{make} with any programming language whose compiler can be run with a
329 shell command.  Indeed, @code{make} is not limited to programs.  You can
330 use it to describe any task where some files must be updated automatically
331 from others whenever the others change.
333 @menu
334 * Preparing::                   Preparing and Running Make
335 * Reading::                     On Reading this Text
336 * Bugs::                        Problems and Bugs
337 @end menu
339 @node Preparing, Reading,  , Overview
340 @ifinfo
341 @heading Preparing and Running Make
342 @end ifinfo
344 To prepare to use @code{make}, you must write a file called
345 the @dfn{makefile} that describes the relationships among files
346 in your program and provides commands for updating each file.
347 In a program, typically, the executable file is updated from object
348 files, which are in turn made by compiling source files.@refill
350 Once a suitable makefile exists, each time you change some source files,
351 this simple shell command:
353 @example
354 make
355 @end example
357 @noindent
358 suffices to perform all necessary recompilations.  The @code{make} program
359 uses the makefile data base and the last-modification times of the files to
360 decide which of the files need to be updated.  For each of those files, it
361 issues the commands recorded in the data base.
363 You can provide command line arguments to @code{make} to control which
364 files should be recompiled, or how.  @xref{Running, ,How to Run
365 @code{make}}.
367 @node Reading, Bugs, Preparing, Overview
368 @section How to Read This Manual
370 If you are new to @code{make}, or are looking for a general
371 introduction, read the first few sections of each chapter, skipping the
372 later sections.  In each chapter, the first few sections contain
373 introductory or general information and the later sections contain
374 specialized or technical information.
375 @ifinfo        
376 The exception is the second chapter, @ref{Introduction, ,An
377 Introduction to Makefiles}, all of which is introductory.
378 @end ifinfo
379 @iftex 
380 The exception is @ref{Introduction, ,An Introduction to Makefiles},
381 all of which is introductory.
382 @end iftex
384 If you are familiar with other @code{make} programs, see @ref{Features,
385 ,Features of GNU @code{make}}, which lists the enhancements GNU
386 @code{make} has, and @ref{Missing, ,Incompatibilities and Missing
387 Features}, which explains the few things GNU @code{make} lacks that
388 others have.
390 For a quick summary, see @ref{Options Summary}, @ref{Quick Reference},
391 and @ref{Special Targets}.
393 @node Bugs,  , Reading, Overview
394 @section Problems and Bugs
395 @cindex reporting bugs
396 @cindex bugs, reporting
397 @cindex problems and bugs, reporting
399 If you have problems with GNU @code{make} or think you've found a bug,
400 please report it to the developers; we cannot promise to do anything but
401 we might well want to fix it.
403 Before reporting a bug, make sure you've actually found a real bug.
404 Carefully reread the documentation and see if it really says you can do
405 what you're trying to do.  If it's not clear whether you should be able
406 to do something or not, report that too; it's a bug in the
407 documentation!
409 Before reporting a bug or trying to fix it yourself, try to isolate it
410 to the smallest possible makefile that reproduces the problem.  Then
411 send us the makefile and the exact results @code{make} gave you.  Also
412 say what you expected to occur; this will help us decide whether the
413 problem was really in the documentation.
415 Once you've got a precise problem, please send electronic mail either
416 through the Internet or via UUCP:
418 @example
419 @group
420 @r{Internet address:}
421     bug-gnu-utils@@prep.ai.mit.edu
423 @r{UUCP path:}
424     mit-eddie!prep.ai.mit.edu!bug-gnu-utils
425 @end group
426 @end example
428 @noindent
429 Please include the version number of @code{make} you are using.  You can
430 get this information with the command @samp{make --version}.
431 Be sure also to include the type of machine and operating system you are
432 using.  If possible, include the contents of the file @file{config.h}
433 that is generated by the configuration process.
435 Non-bug suggestions are always welcome as well.  If you have questions
436 about things that are unclear in the documentation or are just obscure
437 features, contact Roland McGrath; he will try to help you out, although
438 he may not have time to fix the problem.@refill
440 You can send electronic mail to Roland McGrath either through the
441 @w{Internet} or via UUCP:
443 @example
444 @group
445 @r{Internet address:}
446     roland@@prep.ai.mit.edu
448 @r{UUCP path:}
449     mit-eddie!prep.ai.mit.edu!roland
450 @end group
451 @end example
453 @node Introduction, Makefiles, Overview, Top
454 @comment  node-name,  next,  previous,  up
455 @chapter An Introduction to Makefiles
457 You need a file called a @dfn{makefile} to tell @code{make} what to do.
458 Most often, the makefile tells @code{make} how to compile and link a
459 program.
460 @cindex makefile
462 In this chapter, we will discuss a simple makefile that describes how to
463 compile and link a text editor which consists of eight C source files
464 and three header files.  The makefile can also tell @code{make} how to
465 run miscellaneous commands when explicitly asked (for example, to remove
466 certain files as a clean-up operation).  To see a more complex example
467 of a makefile, see @ref{Complex Makefile}.
469 When @code{make} recompiles the editor, each changed C source file
470 must be recompiled.  If a header file has changed, each C source file
471 that includes the header file must be recompiled to be safe.  Each
472 compilation produces an object file corresponding to the source file.
473 Finally, if any source file has been recompiled, all the object files,
474 whether newly made or saved from previous compilations, must be linked
475 together to produce the new executable editor.
476 @cindex recompilation
477 @cindex editor
479 @menu
480 * Rule Introduction::           What a rule looks like.
481 * Simple Makefile::             A Simple Makefile
482 * How Make Works::              How @code{make} Processes This Makefile
483 * Variables Simplify::          Variables Make Makefiles Simpler
484 * make Deduces::                Letting @code{make} Deduce the Commands
485 * Combine By Dependency::       Another Style of Makefile
486 * Cleanup::                     Rules for Cleaning the Directory
487 @end menu
489 @node Rule Introduction, Simple Makefile,  , Introduction
490 @comment  node-name,  next,  previous,  up
491 @section What a Rule Looks Like
492 @cindex rule, introduction to
493 @cindex makefile rule parts
494 @cindex parts of makefile rule
496 A simple makefile consists of ``rules'' with the following shape:
498 @cindex targets, introduction to
499 @cindex dependencies, introduction to
500 @cindex commands, introduction to
501 @example
502 @group
503 @var{target} @dots{} : @var{dependencies} @dots{}
504         @var{command}
505         @dots{}
506         @dots{}
507 @end group
508 @end example
510 A @dfn{target} is usually the name of a file that is generated by a
511 program; examples of targets are executable or object files.  A target
512 can also be the name of an action to carry out, such as @samp{clean}
513 (@pxref{Phony Targets}).
515 A @dfn{dependency} is a file that is used as input to create the
516 target.  A target often depends on several files.  
518 @cindex tabs in rules
519 A @dfn{command} is an action that @code{make} carries out.
520 A rule may have more than one command, each on its own line.
521 @strong{Please note:} you need to put a tab character at the beginning of
522 every command line!  This is an obscurity that catches the unwary.
524 Usually a command is in a rule with dependencies and serves to create a
525 target file if any of the dependencies change.  However, the rule that
526 specifies commands for the target need not have dependencies.  For
527 example, the rule containing the delete command associated with the
528 target @samp{clean} does not have dependencies.
530 A @dfn{rule}, then, explains how and when to remake certain files
531 which are the targets of the particular rule.  @code{make} carries out
532 the commands on the dependencies to create or update the target.  A
533 rule can also explain how and when to carry out an action.
534 @xref{Rules, , Writing Rules}.
536 A makefile may contain other text besides rules, but a simple makefile
537 need only contain rules.  Rules may look somewhat more complicated
538 than shown in this template, but all fit the pattern more or less.
540 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
541 @section A Simple Makefile
542 @cindex simple makefile
543 @cindex makefile, simple
545 Here is a straightforward makefile that describes the way an
546 executable file called @code{edit} depends on eight object files
547 which, in turn, depend on eight C source and three header files.
549 In this example, all the C files include @file{defs.h}, but only those
550 defining editing commands include @file{command.h}, and only low
551 level files that change the editor buffer include @file{buffer.h}.
553 @example
554 @group
555 edit : main.o kbd.o command.o display.o \
556        insert.o search.o files.o utils.o
557         cc -o edit main.o kbd.o command.o display.o \
558                    insert.o search.o files.o utils.o
560 main.o : main.c defs.h
561         cc -c main.c
562 kbd.o : kbd.c defs.h command.h
563         cc -c kbd.c
564 command.o : command.c defs.h command.h
565         cc -c command.c
566 display.o : display.c defs.h buffer.h
567         cc -c display.c
568 insert.o : insert.c defs.h buffer.h
569         cc -c insert.c
570 search.o : search.c defs.h buffer.h
571         cc -c search.c
572 files.o : files.c defs.h buffer.h command.h
573         cc -c files.c
574 utils.o : utils.c defs.h
575         cc -c utils.c
576 clean :
577         rm edit main.o kbd.o command.o display.o \
578            insert.o search.o files.o utils.o
579 @end group
580 @end example
582 @noindent
583 We split each long line into two lines using backslash-newline; this is
584 like using one long line, but is easier to read.
585 @cindex continuation lines
586 @cindex @code{\} (backslash), for continuation lines
587 @cindex backslash (@code{\}), for continuation lines
588 @cindex quoting newline, in makefile
589 @cindex newline, quoting, in makefile
591 To use this makefile to create the executable file called @file{edit},
592 type:
594 @example
595 make
596 @end example
598 To use this makefile to delete the executable file and all the object
599 files from the directory, type:
601 @example
602 make clean
603 @end example
605 In the example makefile, the targets include the executable file
606 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
607 dependencies are files such as @samp{main.c} and @samp{defs.h}.
608 In fact, each @samp{.o} file is both a target and a dependency.
609 Commands include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
611 When a target is a file, it needs to be recompiled or relinked if any
612 of its dependencies change.  In addition, any dependencies that are
613 themselves automatically generated should be updated first.  In this
614 example, @file{edit} depends on each of the eight object files; the
615 object file @file{main.o} depends on the source file @file{main.c} and
616 on the header file @file{defs.h}.  
618 A shell command follows each line that contains a target and
619 dependencies.  These shell commands say how to update the target file.
620 A tab character must come at the beginning of every command line to
621 distinguish commands lines from other lines in the makefile.  (Bear in
622 mind that @code{make} does not know anything about how the commands
623 work.  It is up to you to supply commands that will update the target
624 file properly.  All @code{make} does is execute the commands in the rule
625 you have specified when the target file needs to be updated.)
626 @cindex shell command
628 The target @samp{clean} is not a file, but merely the name of an
629 action.  Since you 
630 normally
631 do not want to carry out the actions in this rule, @samp{clean} is not a dependency of any other rule.
632 Consequently, @code{make} never does anything with it unless you tell
633 it specifically.  Note that this rule not only is not a dependency, it
634 also does not have any dependencies, so the only purpose of the rule
635 is to run the specified commands.  Targets that do not refer to files
636 but are just actions are called @dfn{phony targets}.  @xref{Phony
637 Targets}, for information about this kind of target.  @xref{Errors, ,
638 Errors in Commands}, to see how to cause @code{make} to ignore errors
639 from @code{rm} or any other command.
640 @cindex @code{clean} target
641 @cindex @code{rm} (shell command)
643 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
644 @comment  node-name,  next,  previous,  up
645 @section How @code{make} Processes a Makefile
646 @cindex processing a makefile
647 @cindex makefile, how @code{make} processes
649 By default, @code{make} starts with the first rule (not counting rules
650 whose target names start with @samp{.}).  This is called the
651 @dfn{default goal}.  (@dfn{Goals} are the targets that @code{make}
652 strives ultimately to update.  @xref{Goals, , Arguments to Specify the
653 Goals}.)
654 @cindex default goal
655 @cindex goal, default
656 @cindex goal
658 In the simple example of the previous section, the default goal is to
659 update the executable program @file{edit}; therefore, we put that rule
660 first.
662 Thus, when you give the command:
664 @example
665 make
666 @end example
668 @noindent
669 @code{make} reads the makefile in the current directory and begins by
670 processing the first rule.  In the example, this rule is for relinking
671 @file{edit}; but before @code{make} can fully process this rule, it
672 must process the rules for the files that @file{edit} depends on,
673 which in this case are the object files.  Each of these files is
674 processed according to its own rule.  These rules say to update each
675 @samp{.o} file by compiling its source file.  The recompilation must
676 be done if the source file, or any of the header files named as
677 dependencies, is more recent than the object file, or if the object
678 file does not exist.
680 The other rules are processed because their targets appear as
681 dependencies of the goal.  If some other rule is not depended on by the
682 goal (or anything it depends on, etc.), that rule is not processed,
683 unless you tell @code{make} to do so (with a command such as
684 @w{@code{make clean}}).
686 Before recompiling an object file, @code{make} considers updating its
687 dependencies, the source file and header files.  This makefile does not
688 specify anything to be done for them---the @samp{.c} and @samp{.h} files
689 are not the targets of any rules---so @code{make} does nothing for these
690 files.  But @code{make} would update automatically generated C programs,
691 such as those made by Bison or Yacc, by their own rules at this time.
693 After recompiling whichever object files need it, @code{make} decides
694 whether to relink @file{edit}.  This must be done if the file
695 @file{edit} does not exist, or if any of the object files are newer than
696 it.  If an object file was just recompiled, it is now newer than
697 @file{edit}, so @file{edit} is relinked.
698 @cindex relinking
700 Thus, if we change the file @file{insert.c} and run @code{make},
701 @code{make} will compile that file to update @file{insert.o}, and then
702 link @file{edit}.  If we change the file @file{command.h} and run
703 @code{make}, @code{make} will recompile the object files @file{kbd.o},
704 @file{command.o} and @file{files.o} and then link the file @file{edit}.
706 @node Variables Simplify, make Deduces, How Make Works, Introduction
707 @section Variables Make Makefiles Simpler
708 @cindex variables
709 @cindex simplifying with variables
711 In our example, we had to list all the object files twice in the rule for
712 @file{edit} (repeated here):
714 @example
715 @group
716 edit : main.o kbd.o command.o display.o \
717               insert.o search.o files.o utils.o
718         cc -o edit main.o kbd.o command.o display.o \
719                    insert.o search.o files.o utils.o
720 @end group
721 @end example
723 @cindex @code{objects}
724 Such duplication is error-prone; if a new object file is added to the
725 system, we might add it to one list and forget the other.  We can eliminate
726 the risk and simplify the makefile by using a variable.  @dfn{Variables}
727 allow a text string to be defined once and substituted in multiple places
728 later (@pxref{Using Variables, ,How to Use Variables}).
730 @cindex @code{OBJECTS}
731 @cindex @code{objs}
732 @cindex @code{OBJS}
733 @cindex @code{obj}
734 @cindex @code{OBJ}
735 It is standard practice for every makefile to have a variable named
736 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
737 or @code{OBJ} which is a list of all object file names.  We would
738 define such a variable @code{objects} with a line like this in the
739 makefile:@refill
741 @example
742 @group
743 objects = main.o kbd.o command.o display.o \
744           insert.o search.o files.o utils.o
745 @end group
746 @end example
748 @noindent
749 Then, each place we want to put a list of the object file names, we can
750 substitute the variable's value by writing @samp{$(objects)}
751 (@pxref{Using Variables, ,How to Use Variables}).  
753 Here is how the complete simple makefile looks when you use a variable
754 for the object files:
756 @example
757 @group
758 objects = main.o kbd.o command.o display.o \
759           insert.o search.o files.o utils.o
761 edit : $(objects)
762         cc -o edit $(objects)
763 main.o : main.c defs.h
764         cc -c main.c
765 kbd.o : kbd.c defs.h command.h
766         cc -c kbd.c
767 command.o : command.c defs.h command.h
768         cc -c command.c
769 display.o : display.c defs.h buffer.h
770         cc -c display.c
771 insert.o : insert.c defs.h buffer.h
772         cc -c insert.c
773 search.o : search.c defs.h buffer.h
774         cc -c search.c
775 files.o : files.c defs.h buffer.h command.h
776         cc -c files.c
777 utils.o : utils.c defs.h
778         cc -c utils.c
779 clean :
780         rm edit $(objects)
781 @end group
782 @end example
784 @node make Deduces, Combine By Dependency, Variables Simplify, Introduction
785 @section Letting @code{make} Deduce the Commands
786 @cindex deducing commands (implicit rules)
787 @cindex implicit rule, introduction to
788 @cindex rule, implicit, introduction to
790 It is not necessary to spell out the commands for compiling the individual
791 C source files, because @code{make} can figure them out: it has an
792 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
793 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
794 use the command @samp{cc -c main.c -o main.o} to compile @file{main.c} into
795 @file{main.o}.  We can therefore omit the commands from the rules for the
796 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.@refill
798 When a @samp{.c} file is used automatically in this way, it is also
799 automatically added to the list of dependencies.  We can therefore omit
800 the @samp{.c} files from the dependencies, provided we omit the commands.
802 Here is the entire example, with both of these changes, and a variable
803 @code{objects} as suggested above:
805 @example
806 @group
807 objects = main.o kbd.o command.o display.o \
808           insert.o search.o files.o utils.o
810 edit : $(objects)
811         cc -o edit $(objects)
813 main.o : defs.h
814 kbd.o : defs.h command.h
815 command.o : defs.h command.h
816 display.o : defs.h buffer.h
817 insert.o : defs.h buffer.h
818 search.o : defs.h buffer.h
819 files.o : defs.h buffer.h command.h
820 utils.o : defs.h
822 .PHONY : clean
823 clean :
824         -rm edit $(objects)
825 @end group
826 @end example
828 @noindent
829 This is how we would write the makefile in actual practice.  (The
830 complications associated with @samp{clean} are described elsewhere.
831 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Commands}.)
833 Because implicit rules are so convenient, they are important.  You
834 will see them used frequently.@refill
836 @node Combine By Dependency, Cleanup, make Deduces, Introduction
837 @section Another Style of Makefile
838 @cindex combining rules by dependency
840 When the objects of a makefile are created only by implicit rules, an
841 alternative style of makefile is possible.  In this style of makefile,
842 you group entries by their dependencies instead of by their targets.
843 Here is what one looks like:
845 @example
846 @group
847 objects = main.o kbd.o command.o display.o \
848           insert.o search.o files.o utils.o
850 edit : $(objects)
851         cc -o edit $(objects)
853 $(objects) : defs.h
854 kbd.o command.o files.o : command.h
855 display.o insert.o search.o files.o : buffer.h
856 @end group
857 @end example
859 @noindent
860 Here @file{defs.h} is given as a dependency of all the object files;
861 @file{command.h} and @file{buffer.h} are dependencies of the specific
862 object files listed for them.
864 Whether this is better is a matter of taste: it is more compact, but some
865 people dislike it because they find it clearer to put all the information
866 about each target in one place.
868 @node Cleanup,  , Combine By Dependency, Introduction
869 @section Rules for Cleaning the Directory
870 @cindex cleaning up
871 @cindex removing, to clean up
873 Compiling a program is not the only thing you might want to write rules
874 for.  Makefiles commonly tell how to do a few other things besides
875 compiling a program: for example, how to delete all the object files
876 and executables so that the directory is @samp{clean}.
878 @cindex @code{clean} target
879 Here is how we
880 could write a @code{make} rule for cleaning our example editor:
882 @example
883 @group
884 clean:
885         rm edit $(objects)
886 @end group
887 @end example
889 In practice, we might want to write the rule in a somewhat more
890 complicated manner to handle unanticipated situations.  We would do this:
892 @example
893 @group
894 .PHONY : clean
895 clean :
896         -rm edit $(objects)
897 @end group
898 @end example
900 @noindent
901 This prevents @code{make} from getting confused by an actual file
902 called @file{clean} and causes it to continue in spite of errors from
903 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
904 Commands}.)
906 @noindent
907 A rule such as this should not be placed at the beginning of the
908 makefile, because we do not want it to run by default!  Thus, in the
909 example makefile, we want the rule for @code{edit}, which recompiles
910 the editor, to remain the default goal.
912 Since @code{clean} is not a dependency of @code{edit}, this rule will not
913 run at all if we give the command @samp{make} with no arguments.  In
914 order to make the rule run, we have to type @samp{make clean}.
915 @xref{Running, ,How to Run @code{make}}.
917 @node Makefiles, Rules, Introduction, Top
918 @chapter Writing Makefiles
920 @cindex makefile, how to write
921 The information that tells @code{make} how to recompile a system comes from
922 reading a data base called the @dfn{makefile}.
924 @menu
925 * Makefile Contents::           What makefiles contain.
926 * Makefile Names::              How to name your makefile.
927 * Include::                     How one makefile can use another makefile.
928 * MAKEFILES Variable::          The environment can specify extra makefiles.
929 * Remaking Makefiles::          How makefiles get remade.
930 * Overriding Makefiles::        How to override part of one makefile
931                                  with another makefile.
932 @end menu
934 @node Makefile Contents, Makefile Names,  , Makefiles
935 @section What Makefiles Contain
937 Makefiles contain five kinds of things: @dfn{explicit rules},
938 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
939 and @dfn{comments}.  Rules, variables, and directives are described at
940 length in later chapters.@refill
942 @itemize @bullet
943 @cindex rule, explicit, definition of
944 @cindex explicit rule, definition of
945 @item
946 An @dfn{explicit rule} says when and how to remake one or more files,
947 called the rule's targets.  It lists the other files that the targets
948 @dfn{depend on}, and may also give commands to use to create or update
949 the targets.  @xref{Rules, ,Writing Rules}.
951 @cindex rule, implicit, definition of
952 @cindex implicit rule, definition of
953 @item
954 An @dfn{implicit rule} says when and how to remake a class of files
955 based on their names.  It describes how a target may depend on a file
956 with a name similar to the target and gives commands to create or
957 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
959 @cindex variable definition
960 @item
961 A @dfn{variable definition} is a line that specifies a text string
962 value for a variable that can be substituted into the text later.  The
963 simple makefile example shows a variable definition for @code{objects}
964 as a list of all object files (@pxref{Variables Simplify, , Variables
965 Make Makefiles Simpler}).
967 @cindex directive
968 @item
969 A @dfn{directive} is a command for @code{make} to do something special while
970 reading the makefile.  These include:
972 @itemize @bullet
973 @item
974 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
976 @item
977 Deciding (based on the values of variables) whether to use or
978 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
980 @item
981 Defining a variable from a verbatim string containing multiple lines
982 (@pxref{Defining, ,Defining Variables Verbatim}).
983 @end itemize
985 @cindex comments, in makefile
986 @cindex @code{#} (comments), in makefile
987 @item
988 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the rest of
989 the line are ignored, except that a trailing backslash not escaped by
990 another backslash will continue the comment across multiple lines.
991 Comments may appear on any of the lines in the makefile, except within a
992 @code{define} directive, and perhaps within commands (where the shell
993 decides what is a comment).  A line containing just a comment (with
994 perhaps spaces before it) is effectively blank, and is ignored.@refill
995 @end itemize
997 @node Makefile Names, Include, Makefile Contents, Makefiles
998 @section What Name to Give Your Makefile
999 @cindex makefile name
1000 @cindex name of makefile
1001 @cindex default makefile name
1002 @cindex file name of makefile
1004 @c following paragraph rewritten to avoid overfull hbox
1005 By default, when @code{make} looks for the makefile, it tries the
1006 following names, in order: @file{GNUmakefile}, @file{makefile}
1007 and @file{Makefile}.@refill
1008 @findex Makefile
1009 @findex GNUmakefile
1010 @findex makefile
1012 @cindex @code{README}
1013 Normally you should call your makefile either @file{makefile} or
1014 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1015 prominently near the beginning of a directory listing, right near other
1016 important files such as @file{README}.)  The first name checked,
1017 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1018 use this name if you have a makefile that is specific to GNU
1019 @code{make}, and will not be understood by other versions of
1020 @code{make}.  Other @code{make} programs look for @file{makefile} and
1021 @file{Makefile}, but not @file{GNUmakefile}.
1023 If @code{make} finds none of these names, it does not use any makefile.
1024 Then you must specify a goal with a command argument, and @code{make}
1025 will attempt to figure out how to remake it using only its built-in
1026 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1028 @cindex @code{-f}
1029 @cindex @code{--file}
1030 @cindex @code{--makefile}
1031 If you want to use a nonstandard name for your makefile, you can specify
1032 the makefile name with the @samp{-f} or @samp{--file} option.  The
1033 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1034 @code{make} to read the file @var{name} as the makefile.  If you use
1035 more than one @samp{-f} or @samp{--file} option, you can specify several
1036 makefiles.  All the makefiles are effectively concatenated in the order
1037 specified.  The default makefile names @file{GNUmakefile},
1038 @file{makefile} and @file{Makefile} are not checked automatically if you
1039 specify @samp{-f} or @samp{--file}.@refill
1040 @cindex specifying makefile name
1041 @cindex makefile name, how to specify
1042 @cindex name of makefile, how to specify
1043 @cindex file name of makefile, how to specify
1045 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1046 @section Including Other Makefiles
1047 @cindex including other makefiles
1048 @cindex makefile, including
1050 @findex include
1051 The @code{include} directive tells @code{make} to suspend reading the
1052 current makefile and read one or more other makefiles before continuing.
1053 The directive is a line in the makefile that looks like this:
1055 @example
1056 include @var{filenames}@dots{}
1057 @end example
1059 @noindent
1060 @var{filenames} can contain shell file name patterns.
1061 @cindex shell file name pattern (in @code{include})
1062 @cindex shell wildcards (in @code{include})
1063 @cindex wildcard, in @code{include}
1065 Extra spaces are allowed and ignored at the beginning of the line, but
1066 a tab is not allowed.  (If the line begins with a tab, it will be
1067 considered a command line.)  Whitespace is required between
1068 @code{include} and the file names, and between file names; extra
1069 whitespace is ignored there and at the end of the directive.  A
1070 comment starting with @samp{#} is allowed at the end of the line.  If
1071 the file names contain any variable or function references, they are
1072 expanded.  @xref{Using Variables, ,How to Use Variables}.
1074 For example, if you have three @file{.mk} files, @file{a.mk}, 
1075 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1076 @code{bish bash}, then the following expression
1078 @example
1079 include foo *.mk $(bar)
1080 @end example
1082 is equivalent to
1084 @example
1085 include foo a.mk b.mk c.mk bish bash
1086 @end example
1088 When @code{make} processes an @code{include} directive, it suspends
1089 reading of the containing makefile and reads from each listed file in
1090 turn.  When that is finished, @code{make} resumes reading the
1091 makefile in which the directive appears.
1093 One occasion for using @code{include} directives is when several programs,
1094 handled by individual makefiles in various directories, need to use a
1095 common set of variable definitions 
1096 (@pxref{Setting, ,Setting Variables}) or pattern rules
1097 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1099 Another such occasion is when you want to generate dependencies from
1100 source files automatically; the dependencies can be put in a file that
1101 is included by the main makefile.  This practice is generally cleaner
1102 than that of somehow appending the dependencies to the end of the main
1103 makefile as has been traditionally done with other versions of
1104 @code{make}.  @xref{Automatic Dependencies}.
1105 @cindex dependencies, automatic generation
1106 @cindex automatic generation of dependencies
1107 @cindex generating dependencies automatically
1109 @cindex @code{-I}
1110 @cindex @code{--include-dir}
1111 @findex /usr/gnu/include
1112 @findex /usr/local/include
1113 @findex /usr/include
1114 If the specified name does not start with a slash, and the file is not
1115 found in the current directory, several other directories are searched.
1116 First, any directories you have specified with the @samp{-I} or
1117 @samp{--include-dir} option are searched
1118 (@pxref{Options Summary, ,Summary of Options}).
1119 Then the following directories (if they exist)
1120 are searched, in this order: 
1121 @file{@var{prefix}/include} (normally @file{/usr/local/include})
1122 @file{/usr/gnu/include},
1123 @file{/usr/local/include}, @file{/usr/include}.  
1125 If an included makefile cannot be found in any of these directories, a
1126 warning message is generated, but it is not an immediately fatal error;
1127 processing of the makefile containing the @code{include} continues.
1128 Once it has finished reading makefiles, @code{make} will try to remake
1129 any that are out of date or don't exist.
1130 @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
1131 Only after it has tried to find a way to remake a makefile and failed,
1132 will @code{make} diagnose the missing makefile as a fatal error.
1134 If you want @code{make} to simply ignore a makefile which does not exist
1135 and cannot be remade, with no error message, use the @w{@code{-include}}
1136 directive instead of @code{include}, like this:
1138 @example
1139 -include @var{filenames}@dots{}
1140 @end example
1142 This is acts like @code{include} in every way except that there is no
1143 error (not even a warning) if any of the @var{filenames} do not exist.
1145 @node MAKEFILES Variable, Remaking Makefiles, Include, Makefiles
1146 @section The Variable @code{MAKEFILES}
1147 @cindex makefile, and @code{MAKEFILES} variable
1148 @cindex including (@code{MAKEFILES} variable)
1150 @vindex MAKEFILES
1151 If the environment variable @code{MAKEFILES} is defined, @code{make}
1152 considers its value as a list of names (separated by whitespace) of
1153 additional makefiles to be read before the others.  This works much like
1154 the @code{include} directive: various directories are searched for those
1155 files (@pxref{Include, ,Including Other Makefiles}).  In addition, the
1156 default goal is never taken from one of these makefiles and it is not an
1157 error if the files listed in @code{MAKEFILES} are not found.@refill
1159 @cindex recursion, and @code{MAKEFILES} variable
1160 The main use of @code{MAKEFILES} is in communication between recursive
1161 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1162 @code{make}}).  It usually is not desirable to set the environment
1163 variable before a top-level invocation of @code{make}, because it is
1164 usually better not to mess with a makefile from outside.  However, if
1165 you are running @code{make} without a specific makefile, a makefile in
1166 @code{MAKEFILES} can do useful things to help the built-in implicit
1167 rules work better, such as defining search paths (@pxref{Directory Search}).
1169 Some users are tempted to set @code{MAKEFILES} in the environment
1170 automatically on login, and program makefiles to expect this to be done.
1171 This is a very bad idea, because such makefiles will fail to work if run by
1172 anyone else.  It is much better to write explicit @code{include} directives
1173 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1175 @node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
1176 @section How Makefiles Are Remade
1178 @cindex updating makefiles
1179 @cindex remaking makefiles
1180 @cindex makefile, remaking of
1181 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1182 files.  If a makefile can be remade from other files, you probably want
1183 @code{make} to get an up-to-date version of the makefile to read in.
1185 To this end, after reading in all makefiles, @code{make} will consider
1186 each as a goal target and attempt to update it.  If a makefile has a
1187 rule which says how to update it (found either in that very makefile or
1188 in another one) or if an implicit rule applies to it (@pxref{Implicit
1189 Rules, ,Using Implicit Rules}), it will be updated if necessary.  After
1190 all makefiles have been checked, if any have actually been changed,
1191 @code{make} starts with a clean slate and reads all the makefiles over
1192 again.  (It will also attempt to update each of them over again, but
1193 normally this will not change them again, since they are already up to
1194 date.)@refill
1196 If the makefiles specify a double-colon rule to remake a file with
1197 commands but no dependencies, that file will always be remade
1198 (@pxref{Double-Colon}).  In the case of makefiles, a makefile that has a
1199 double-colon rule with commands but no dependencies will be remade every
1200 time @code{make} is run, and then again after @code{make} starts over
1201 and reads the makefiles in again.  This would cause an infinite loop:
1202 @code{make} would constantly remake the makefile, and never do anything
1203 else.  So, to avoid this, @code{make} will @strong{not} attempt to
1204 remake makefiles which are specified as double-colon targets but have no
1205 dependencies.@refill
1207 If you do not specify any makefiles to be read with @samp{-f} or
1208 @samp{--file} options, @code{make} will try the default makefile names;
1209 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1210 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1211 @code{make} is not certain that these makefiles should exist.  However,
1212 if a default makefile does not exist but can be created by running
1213 @code{make} rules, you probably want the rules to be run so that the
1214 makefile can be used.
1216 Therefore, if none of the default makefiles exists, @code{make} will try
1217 to make each of them in the same order in which they are searched for
1218 (@pxref{Makefile Names, ,What Name to Give Your Makefile})
1219 until it succeeds in making one, or it runs out of names to try.  Note
1220 that it is not an error if @code{make} cannot find or make any makefile;
1221 a makefile is not always necessary.@refill
1223 When you use the @samp{-t} or @samp{--touch} option
1224 (@pxref{Instead of Execution, ,Instead of Executing the Commands}),
1225 you would not want to use an out-of-date makefile to decide which
1226 targets to touch.  So the @samp{-t} option has no effect on updating
1227 makefiles; they are really updated even if @samp{-t} is specified.
1228 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1229 @samp{--just-print}) do not prevent updating of makefiles, because an
1230 out-of-date makefile would result in the wrong output for other targets.
1231 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1232 and then print the commands to update @file{foo} and its dependencies
1233 without running them.  The commands printed for @file{foo} will be those
1234 specified in the updated contents of @file{mfile}.
1236 However, on occasion you might actually wish to prevent updating of even
1237 the makefiles.  You can do this by specifying the makefiles as goals in
1238 the command line as well as specifying them as makefiles.  When the
1239 makefile name is specified explicitly as a goal, the options @samp{-t}
1240 and so on do apply to them.
1242 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1243 @file{mfile}, print the commands needed to update it without actually
1244 running them, and then print the commands needed to update @file{foo}
1245 without running them.  The commands for @file{foo} will be those
1246 specified by the existing contents of @file{mfile}.
1248 @node Overriding Makefiles,  , Remaking Makefiles, Makefiles
1249 @section Overriding Part of Another Makefile
1251 @cindex overriding makefiles
1252 @cindex makefile, overriding
1253 Sometimes it is useful to have a makefile that is mostly just like
1254 another makefile.  You can often use the @samp{include} directive to
1255 include one in the other, and add more targets or variable definitions.
1256 However, if the two makefiles give different commands for the same
1257 target, @code{make} will not let you just do this.  But there is another way.
1259 @cindex @code{.DEFAULT}, used to override
1260 In the containing makefile (the one that wants to include the other),
1261 you can use the @code{.DEFAULT} special target to say that to remake
1262 any target that cannot be made from the information in the containing
1263 makefile, @code{make} should look in another makefile.  
1264 @xref{Last Resort, , Defining Last-Resort Default Rules}, 
1265 for more information on @code{.DEFAULT}.
1267 For example, if you have a makefile called @file{Makefile} that says how
1268 to make the target @samp{foo} (and other targets), you can write a
1269 makefile called @file{GNUmakefile} that contains:
1271 @example
1272 foo:
1273         frobnicate > foo
1275 .DEFAULT:
1276         @@$(MAKE) -f Makefile $@@
1277 @end example
1279 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1280 read it, and see that to make @file{foo}, it needs to run the command
1281 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1282 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1283 commands from @code{.DEFAULT}: @samp{make -f Makefile bar}.  If
1284 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1285 will apply the rule.  And likewise for any other target that
1286 @file{GNUmakefile} does not say how to make.@refill
1288 @node Rules, Commands, Makefiles, Top
1289 @chapter Writing Rules
1290 @cindex writing rules
1291 @cindex rule, how to write
1292 @cindex target
1293 @cindex dependency
1295 A @dfn{rule} appears in the makefile and says when and how to remake
1296 certain files, called the rule's @dfn{targets} (most often only one per rule).
1297 It lists the other files that are the @dfn{dependencies} of the target, and
1298 @dfn{commands} to use to create or update the target.
1300 @cindex default goal
1301 @cindex goal, default
1302 The order of rules is not significant, except for determining the
1303 @dfn{default goal}: the target for @code{make} to consider, if you do
1304 not otherwise specify one.  The default goal is the target of the first
1305 rule in the first makefile.  If the first rule has multiple targets,
1306 only the first target is taken as the default.  There are two
1307 exceptions: a target starting with a period is not a default unless it
1308 contains one or more slashes, @samp{/}, as well; and, a target that
1309 defines a pattern rule has no effect on the default goal.
1310 (@xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.)
1312 Therefore, we usually write the makefile so that the first rule is the
1313 one for compiling the entire program or all the programs described by
1314 the makefile (often with a target called @samp{all}).
1315 @xref{Goals, ,Arguments to Specify the Goals}.
1317 @menu
1318 * Rule Example::                An example explained.
1319 * Rule Syntax::                 General syntax explained.
1320 * Wildcards::                   Using wildcard characters such as `*'.
1321 * Directory Search::            Searching other directories for source files.
1322 * Phony Targets::               Using a target that is not a real file's name.
1323 * Force Targets::               You can use a target without commands
1324                                   or dependencies to mark other 
1325                                   targets as phony.
1326 * Empty Targets::               When only the date matters and the
1327                                   files are empty.
1328 * Special Targets::             Targets with special built-in meanings.
1329 * Multiple Targets::            When to make use of several targets in a rule.
1330 * Multiple Rules::              How to use several rules with the same target.
1331 * Static Pattern::              Static pattern rules apply to multiple targets
1332                                   and can vary the dependencies according to 
1333                                   the target name.
1334 * Double-Colon::                How to use a special kind of rule to allow
1335                                   several independent rules for one target.
1336 * Automatic Dependencies::      How to automatically generate rules giving
1337                                  dependencies from the source files themselves.
1338 @end menu
1340 @ifinfo
1341 @node Rule Example, Rule Syntax,  , Rules
1342 @section Rule Example
1344 Here is an example of a rule:
1346 @example
1347 foo.o : foo.c defs.h       # module for twiddling the frobs
1348         cc -c -g foo.c
1349 @end example
1351 Its target is @file{foo.o} and its dependencies are @file{foo.c} and
1352 @file{defs.h}.  It has one command, which is @samp{cc -c -g foo.c}.
1353 The command line starts with a tab to identify it as a command.
1355 This rule says two things:
1357 @itemize @bullet
1358 @item
1359 How to decide whether @file{foo.o} is out of date: it is out of date
1360 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1361 more recent than it.
1363 @item
1364 How to update the file @file{foo.o}: by running @code{cc} as stated.
1365 The command does not explicitly mention @file{defs.h}, but we presume
1366 that @file{foo.c} includes it, and that that is why @file{defs.h} was
1367 added to the dependencies.
1368 @end itemize
1369 @end ifinfo
1371 @node Rule Syntax, Wildcards, Rule Example, Rules
1372 @section Rule Syntax
1374 @cindex rule syntax
1375 @cindex syntax of rules
1376 In general, a rule looks like this:
1378 @example
1379 @var{targets} : @var{dependencies}
1380         @var{command}
1381         @dots{}
1382 @end example
1384 @noindent
1385 or like this:
1387 @example
1388 @var{targets} : @var{dependencies} ; @var{command}
1389         @var{command}
1390         @dots{}
1391 @end example
1393 @cindex targets
1394 @cindex rule targets
1395 The @var{targets} are file names, separated by spaces.  Wildcard
1396 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
1397 in File Names}) and a name of the form @file{@var{a}(@var{m})}
1398 represents member @var{m} in archive file @var{a} 
1399 (@pxref{Archive Members, ,Archive Members as Targets}).  
1400 Usually there is only one
1401 target per rule, but occasionally there is a reason to have more
1402 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).@refill
1404 @cindex commands
1405 @cindex tab character (in commands)
1406 The @var{command} lines start with a tab character.  The first command may
1407 appear on the line after the dependencies, with a tab character, or may
1408 appear on the same line, with a semicolon.  Either way, the effect is the
1409 same.  @xref{Commands, ,Writing the Commands in Rules}.
1411 @cindex dollar sign (@code{$}), in rules
1412 @cindex @code{$}, in rules
1413 @cindex rule, and @code{$}
1414 Because dollar signs are used to start variable references, if you really
1415 want a dollar sign in a rule you must write two of them, @samp{$$}
1416 (@pxref{Using Variables, ,How to Use Variables}).  
1417 You may split a long line by inserting a backslash
1418 followed by a newline, but this is not required, as @code{make} places no
1419 limit on the length of a line in a makefile.
1421 A rule tells @code{make} two things: when the targets are out of date,
1422 and how to update them when necessary.
1424 @cindex dependencies
1425 @cindex rule dependencies
1426 The criterion for being out of date is specified in terms of the
1427 @var{dependencies}, which consist of file names separated by spaces.
1428 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
1429 A target is out of date if it does not exist or if it is older than any
1430 of the dependencies (by comparison of last-modification times).  The
1431 idea is that the contents of the target file are computed based on
1432 information in the dependencies, so if any of the dependencies changes,
1433 the contents of the existing target file are no longer necessarily
1434 valid.
1436 How to update is specified by @var{commands}.  These are lines to be
1437 executed by the shell (normally @samp{sh}), but with some extra features
1438 (@pxref{Commands, ,Writing the Commands in Rules}).
1440 @node Wildcards, Directory Search, Rule Syntax, Rules
1441 @section Using Wildcard Characters in File Names
1442 @cindex wildcard
1443 @cindex file name with wildcards
1444 @cindex globbing (wildcards)
1446 @cindex @code{*} (wildcard character)
1447 @cindex @code{?} (wildcard character)
1448 @cindex @code{[@dots{}]} (wildcard characters)
1449 A single file name can specify many files using @dfn{wildcard characters}.
1450 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
1451 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
1452 specifies a list of all the files (in the working directory) whose names
1453 end in @samp{.c}.@refill
1455 @cindex @code{~} (tilde)
1456 @cindex tilde (@code{~})
1457 @cindex home directory
1458 The character @samp{~} at the beginning of a file name also has special
1459 significance.  If alone, or followed by a slash, it represents your home
1460 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
1461 If the @samp{~} is followed by a word, the string represents the home
1462 directory of the user named by that word.  For example @file{~john/bin}
1463 expands to @file{/home/john/bin}.@refill
1465 Wildcard expansion happens automatically in targets, in dependencies,
1466 and in commands (where the shell does the expansion).  In other
1467 contexts, wildcard expansion happens only if you request it explicitly
1468 with the @code{wildcard} function.
1470 The special significance of a wildcard character can be turned off by
1471 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
1472 specific file whose name consists of @samp{foo}, an asterisk, and
1473 @samp{bar}.@refill
1475 @menu
1476 * Wildcard Examples::           Several examples
1477 * Wildcard Pitfall::            Problems to avoid.
1478 * Wildcard Function::           How to cause wildcard expansion where
1479                                   it does not normally take place.
1480 @end menu
1482 @node Wildcard Examples, Wildcard Pitfall,  , Wildcards
1483 @subsection Wildcard Examples
1485 Wildcards can be used in the commands of a rule, where they are expanded
1486 by the shell.  For example, here is a rule to delete all the object files:
1488 @example
1489 @group
1490 clean:
1491         rm -f *.o
1492 @end group
1493 @end example
1494 @cindex @code{rm} (shell command)
1496 Wildcards are also useful in the dependencies of a rule.  With the
1497 following rule in the makefile, @samp{make print} will print all the
1498 @samp{.c} files that have changed since the last time you printed them:
1500 @example
1501 print: *.c
1502         lpr -p $?
1503         touch print
1504 @end example
1506 @cindex @code{print} target
1507 @cindex @code{lpr} (shell command)
1508 @cindex @code{touch} (shell command)
1509 @noindent
1510 This rule uses @file{print} as an empty target file; see @ref{Empty
1511 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
1512 @samp{$?} is used to print only those files that have changed; see
1513 @ref{Automatic, ,Automatic Variables}.)@refill
1515 Wildcard expansion does not happen when you define a variable.  Thus, if
1516 you write this:
1518 @example
1519 objects = *.o
1520 @end example
1522 @noindent
1523 then the value of the variable @code{objects} is the actual string
1524 @samp{*.o}.  However, if you use the value of @code{objects} in a target,
1525 dependency or command, wildcard expansion will take place at that time.
1526 To set @code{objects} to the expansion, instead use:
1528 @example
1529 objects := $(wildcard *.o)
1530 @end example
1532 @noindent
1533 @xref{Wildcard Function}.
1535 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
1536 @subsection Pitfalls of Using Wildcards
1537 @cindex wildcard pitfalls
1538 @cindex pitfalls of wildcards
1539 @cindex mistakes with wildcards
1540 @cindex errors with wildcards
1541 @cindex problems with wildcards
1543 Now here is an example of a naive way of using wildcard expansion, that
1544 does not do what you would intend.  Suppose you would like to say that the
1545 executable file @file{foo} is made from all the object files in the
1546 directory, and you write this:
1548 @example
1549 objects = *.o
1551 foo : $(objects)
1552         cc -o foo $(CFLAGS) $(objects)
1553 @end example
1555 @noindent
1556 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
1557 expansion happens in the rule for @file{foo}, so that each @emph{existing}
1558 @samp{.o} file becomes a dependency of @file{foo} and will be recompiled if
1559 necessary.
1561 But what if you delete all the @samp{.o} files?  When a wildcard matches
1562 no files, it is left as it is, so then @file{foo} will depend on the
1563 oddly-named file @file{*.o}.  Since so such file is likely to exist,
1564 @code{make} will give you an error saying it cannot figure out how to
1565 make @file{*.o}.  This is not what you want!
1567 Actually it is possible to obtain the desired result with wildcard
1568 expansion, but you need more sophisticated techniques, including the
1569 @code{wildcard} function and string substitution.
1570 @ifinfo
1571 @xref{Wildcard Function, ,The Function @code{wildcard}}.
1572 @end ifinfo
1573 @iftex
1574 These are described in the following section.
1575 @end iftex
1577 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
1578 @subsection The Function @code{wildcard}
1579 @findex wildcard
1581 Wildcard expansion happens automatically in rules.  But wildcard expansion
1582 does not normally take place when a variable is set, or inside the
1583 arguments of a function.  If you want to do wildcard expansion in such
1584 places, you need to use the @code{wildcard} function, like this:
1586 @example
1587 $(wildcard @var{pattern}@dots{})
1588 @end example
1590 @noindent
1591 This string, used anywhere in a makefile, is replaced by a
1592 space-separated list of names of existing files that match one of the
1593 given file name patterns.  If no existing file name matches a pattern,
1594 then that pattern is omitted from the output of the @code{wildcard}
1595 function.  Note that this is different from how unmatched wildcards
1596 behave in rules, where they are used verbatim rather than ignored
1597 (@pxref{Wildcard Pitfall}).
1599 One use of the @code{wildcard} function is to get a list of all the C source
1600 files in a directory, like this:
1602 @example
1603 $(wildcard *.c)
1604 @end example
1606 We can change the list of C source files into a list of object files by
1607 replacing the @samp{.o} suffix with @samp{.c} in the result, like this:
1609 @example
1610 $(patsubst %.c,%.o,$(wildcard *.c))
1611 @end example
1613 @noindent
1614 (Here we have used another function, @code{patsubst}.
1615 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)@refill
1617 Thus, a makefile to compile all C source files in the directory and then
1618 link them together could be written as follows:
1620 @example
1621 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1623 foo : $(objects)
1624         cc -o foo $(objects)
1625 @end example
1627 @noindent
1628 (This takes advantage of the implicit rule for compiling C programs, so
1629 there is no need to write explicit rules for compiling the files.
1630 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
1631 @samp{:=}, which is a variant of @samp{=}.)
1633 @node Directory Search, Phony Targets, Wildcards, Rules
1634 @section Searching Directories for Dependencies
1635 @vindex VPATH
1636 @findex vpath
1637 @cindex vpath 
1638 @cindex search path for dependencies (@code{VPATH})
1639 @cindex directory search (@code{VPATH})
1641 For large systems, it is often desirable to put sources in a separate
1642 directory from the binaries.  The @dfn{directory search} features of
1643 @code{make} facilitate this by searching several directories
1644 automatically to find a dependency.  When you redistribute the files
1645 among directories, you do not need to change the individual rules,
1646 just the search paths.
1648 @menu
1649 * General Search::              Specifying a search path that applies 
1650                                   to every dependency.
1651 * Selective Search::            Specifying a search path 
1652                                   for a specified class of names.
1653 * Commands/Search::             How to write shell commands that work together
1654                                   with search paths.
1655 * Implicit/Search::             How search paths affect implicit rules.
1656 * Libraries/Search::            Directory search for link libraries.
1657 @end menu
1659 @node General Search, Selective Search,  , Directory Search
1660 @subsection @code{VPATH}: Search Path for All Dependencies
1661 @vindex VPATH
1663 The value of the @code{make} variable @code{VPATH} specifies a list of
1664 directories that @code{make} should search.  Most often, the
1665 directories are expected to contain dependency files that are not in the
1666 current directory; however, @code{VPATH} specifies a search list that
1667 @code{make} applies for all files, including files which are targets of
1668 rules.
1670 Thus, if a file that is listed as a target or dependency does not exist
1671 in the current directory, @code{make} searches the directories listed in
1672 @code{VPATH} for a file with that name.  If a file is found in one of
1673 them, that file becomes the dependency.  Rules may then specify the
1674 names of source files in the dependencies as if they all existed in the
1675 current directory.  @xref{Commands/Search, ,Writing Shell Commands with
1676 Directory Search}.
1678 In the @code{VPATH} variable, directory names are separated by colons.
1679 The order in which directories are listed is the order followed by
1680 @code{make} in its search.
1682 For example,
1684 @example
1685 VPATH = src:../headers
1686 @end example
1688 @noindent
1689 specifies a path containing two directories, @file{src} and
1690 @file{../headers}, which @code{make} searches in that order.
1692 With this value of @code{VPATH}, the following rule,
1694 @example
1695 foo.o : foo.c
1696 @end example
1698 @noindent
1699 is interpreted as if it were written like this:
1701 @example
1702 foo.o : src/foo.c
1703 @end example
1705 @noindent
1706 assuming the file @file{foo.c} does not exist in the current directory but
1707 is found in the directory @file{src}.
1709 @node Selective Search, Commands/Search, General Search, Directory Search
1710 @subsection The @code{vpath} Directive
1711 @findex vpath
1713 Similar to the @code{VPATH} variable but more selective is the @code{vpath}
1714 directive (note lower case), which allows you to specify a search path for a particular class
1715 of file names, those that match a particular pattern.  Thus you can supply
1716 certain search directories for one class of file names and other directories
1717 (or none) for other file names.
1719 There are three forms of the @code{vpath} directive:
1721 @table @code
1722 @item vpath @var{pattern} @var{directories}
1723 Specify the search path @var{directories} for file names that match
1724 @var{pattern}.  
1726 The search path, @var{directories}, is a colon-separated list of
1727 directories to be searched, just like the search path used in the
1728 @code{VPATH} variable.
1730 @item vpath @var{pattern}
1731 Clear out the search path associated with @var{pattern}.
1733 @c Extra blank line makes sure this gets two lines.
1734 @item vpath
1736 Clear all search paths previously specified with @code{vpath} directives.
1737 @end table
1739 A @code{vpath} pattern is a string containing a @samp{%} character.  The
1740 string must match the file name of a dependency that is being searched
1741 for, the @samp{%} character matching any sequence of zero or more
1742 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
1743 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
1744 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
1745 dependency exactly, which is not useful very often.)
1747 @cindex @code{%}, quoting in @code{vpath}
1748 @cindex @code{%}, quoting with @code{\} (backslash)
1749 @cindex @code{\} (backslash), to quote @code{%}
1750 @cindex backslash (@code{\}), to quote @code{%}
1751 @cindex quoting @code{%}, in @code{vpath}
1752 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
1753 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
1754 quote @samp{%} characters can be quoted with more backslashes.
1755 Backslashes that quote @samp{%} characters or other backslashes are
1756 removed from the pattern before it is compared to file names.  Backslashes
1757 that are not in danger of quoting @samp{%} characters go unmolested.@refill
1759 When a dependency fails to exist in the current directory, if the
1760 @var{pattern} in a @code{vpath} directive matches the name of the
1761 dependency file, then the @var{directories} in that directive are searched
1762 just like (and before) the directories in the @code{VPATH} variable.  
1764 For example,
1766 @example
1767 vpath %.h ../headers
1768 @end example
1770 @noindent
1771 tells @code{make} to look for any dependency whose name ends in @file{.h}
1772 in the directory @file{../headers} if the file is not found in the current
1773 directory.
1775 If several @code{vpath} patterns match the dependency file's name, then
1776 @code{make} processes each matching @code{vpath} directive one by one,
1777 searching all the directories mentioned in each directive.  @code{make}
1778 handles multiple @code{vpath} directives in the order in which they
1779 appear in the makefile; multiple directives with the same pattern are
1780 independent of each other.
1782 @need 750
1783 Thus, 
1785 @example
1786 @group
1787 vpath %.c foo
1788 vpath %   blish
1789 vpath %.c bar
1790 @end group
1791 @end example
1793 @noindent
1794 will look for a file ending in @samp{.c} in @file{foo}, then
1795 @file{blish}, then @file{bar}, while
1797 @example
1798 @group
1799 vpath %.c foo:bar
1800 vpath %   blish
1801 @end group
1802 @end example
1804 @noindent
1805 will look for a file ending in @samp{.c} in @file{foo}, then
1806 @file{bar}, then @file{blish}.
1808 @node Commands/Search, Implicit/Search, Selective Search, Directory Search
1809 @subsection Writing Shell Commands with Directory Search
1810 @cindex shell command, and directory search
1811 @cindex directory search (@code{VPATH}), and shell commands
1813 When a dependency is found in another directory through directory search,
1814 this cannot change the commands of the rule; they will execute as written.
1815 Therefore, you must write the commands with care so that they will look for
1816 the dependency in the directory where @code{make} finds it.
1818 This is done with the @dfn{automatic variables} such as @samp{$^}
1819 (@pxref{Automatic, ,Automatic Variables}).  
1820 For instance, the value of @samp{$^} is a
1821 list of all the dependencies of the rule, including the names of
1822 the directories in which they were found, and the value of
1823 @samp{$@@} is the target.  Thus:@refill
1825 @example
1826 foo.o : foo.c
1827         cc -c $(CFLAGS) $^ -o $@@
1828 @end example
1830 @noindent
1831 (The variable @code{CFLAGS} exists so you can specify flags for C
1832 compilation by implicit rules; we use it here for consistency so it will
1833 affect all C compilations uniformly;
1834 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
1836 Often the dependencies include header files as well, which you do not
1837 want to mention in the commands.  The automatic variable @samp{$<} is
1838 just the first dependency:
1840 @example
1841 VPATH = src:../headers
1842 foo.o : foo.c defs.h hack.h
1843         cc -c $(CFLAGS) $< -o $@@
1844 @end example
1846 @node Implicit/Search, Libraries/Search, Commands/Search, Directory Search
1847 @subsection Directory Search and Implicit Rules
1848 @cindex @code{VPATH}, and implicit rules
1849 @cindex directory search (@code{VPATH}), and implicit rules
1850 @cindex search path for dependencies (@code{VPATH}), and implicit rules
1851 @cindex implicit rule, and directory search
1852 @cindex implicit rule, and @code{VPATH}
1853 @cindex rule, implicit, and directory search
1854 @cindex rule, implicit, and @code{VPATH}
1856 The search through the directories specified in @code{VPATH} or with
1857 @code{vpath} also happens during consideration of implicit rules
1858 (@pxref{Implicit Rules, ,Using Implicit Rules}).
1860 For example, when a file @file{foo.o} has no explicit rule, @code{make}
1861 considers implicit rules, such as the built-in rule to compile
1862 @file{foo.c} if that file exists.  If such a file is lacking in the
1863 current directory, the appropriate directories are searched for it.  If
1864 @file{foo.c} exists (or is mentioned in the makefile) in any of the
1865 directories, the implicit rule for C compilation is applied.
1867 The commands of implicit rules normally use automatic variables as a
1868 matter of necessity; consequently they will use the file names found by
1869 directory search with no extra effort.
1871 @node Libraries/Search,  , Implicit/Search, Directory Search
1872 @subsection Directory Search for Link Libraries
1873 @cindex link libraries, and directory search
1874 @cindex libraries for linking, directory search
1875 @cindex directory search (@code{VPATH}), and link libraries 
1876 @cindex @code{VPATH}, and link libraries 
1877 @cindex search path for dependencies (@code{VPATH}), and link libraries 
1878 @cindex @code{-l} (library search)
1880 Directory search applies in a special way to libraries used with the
1881 linker.  This special feature comes into play when you write a dependency
1882 whose name is of the form @samp{-l@var{name}}.  (You can tell something
1883 strange is going on here because the dependency is normally the name of a
1884 file, and the @emph{file name} of the library looks like
1885 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)@refill
1887 When a dependency's name has the form @samp{-l@var{name}}, @code{make}
1888 handles it specially by searching for the file @file{lib@var{name}.a} in
1889 the current directory, in directories specified by matching @code{vpath}
1890 search paths and the @code{VPATH} search path, and then in the
1891 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
1892 (normally @file{/usr/local/lib}).
1894 For example,
1896 @example
1897 @group
1898 foo : foo.c -lcurses
1899         cc $^ -o $@@
1900 @end group
1901 @end example
1903 @noindent
1904 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
1905 be executed when @file{foo} is older than @file{foo.c} or than
1906 @file{/usr/lib/libcurses.a}.@refill
1908 @node Phony Targets, Force Targets, Directory Search, Rules
1909 @section Phony Targets
1910 @cindex phony targets
1911 @cindex targets, phony
1912 @cindex targets without a file
1914 A phony target is one that is not really the name of a file.  It is just a
1915 name for some commands to be executed when you make an explicit request.
1916 There are two reasons to use a phony target: to avoid a conflict with
1917 a file of the same name, and to improve performance.
1919 If you write a rule whose commands will not create the target file, the
1920 commands will be executed every time the target comes up for remaking.
1921 Here is an example:
1923 @example
1924 @group
1925 clean:
1926         rm *.o temp
1927 @end group
1928 @end example
1930 @noindent
1931 Because the @code{rm} command does not create a file named @file{clean},
1932 probably no such file will ever exist.  Therefore, the @code{rm} command
1933 will be executed every time you say @samp{make clean}.
1934 @cindex @code{rm} (shell command)
1936 @findex .PHONY
1937 The phony target will cease to work if anything ever does create a file
1938 named @file{clean} in this directory.  Since it has no dependencies, the
1939 file @file{clean} would inevitably be considered up to date, and its
1940 commands would not be executed.  To avoid this problem, you can explicitly
1941 declare the target to be phony, using the special target @code{.PHONY}
1942 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
1944 @example
1945 .PHONY : clean
1946 @end example
1948 @noindent
1949 Once this is done, @samp{make clean} will run the commands regardless of
1950 whether there is a file named @file{clean}.
1952 Since it knows that phony targets do not name actual files that could be
1953 remade from other files, @code{make} skips the implicit rule search for
1954 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
1955 phony is good for performance, even if you are not worried about the
1956 actual file existing.
1958 Thus, you first write the line that states that @code{clean} is a
1959 phony target, then you write the rule, like this:
1961 @example
1962 @group
1963 .PHONY: clean
1964 clean:
1965         rm *.o temp
1966 @end group
1967 @end example
1969 A phony target should not be a dependency of a real target file; if it
1970 is, its commands are run every time @code{make} goes to update that
1971 file.  As long as a phony target is never a dependency of a real
1972 target, the phony target commands will be executed only when the phony
1973 target is a specified goal (@pxref{Goals, ,Arguments to Specify the
1974 Goals}).
1976 Phony targets can have dependencies.  When one directory contains multiple
1977 programs, it is most convenient to describe all of the programs in one
1978 makefile @file{./Makefile}.  Since the target remade by default will be the
1979 first one in the makefile, it is common to make this a phony target named
1980 @samp{all} and give it, as dependencies, all the individual programs.  For
1981 example:
1983 @example
1984 all : prog1 prog2 prog3
1985 .PHONY : all
1987 prog1 : prog1.o utils.o
1988         cc -o prog1 prog1.o utils.o
1990 prog2 : prog2.o
1991         cc -o prog2 prog2.o
1993 prog3 : prog3.o sort.o utils.o
1994         cc -o prog3 prog3.o sort.o utils.o
1995 @end example
1997 @noindent
1998 Now you can say just @samp{make} to remake all three programs, or specify
1999 as arguments the ones to remake (as in @samp{make prog1 prog3}).
2001 When one phony target is a dependency of another, it serves as a subroutine
2002 of the other.  For example, here @samp{make cleanall} will delete the
2003 object files, the difference files, and the file @file{program}:
2005 @example
2006 .PHONY: cleanall cleanobj cleandiff
2008 cleanall : cleanobj cleandiff
2009         rm program
2011 cleanobj :
2012         rm *.o
2014 cleandiff :
2015         rm *.diff
2016 @end example
2018 @node Force Targets, Empty Targets, Phony Targets, Rules
2019 @section Rules without Commands or Dependencies
2020 @cindex force targets
2021 @cindex targets, force
2022 @cindex @code{FORCE}
2023 @cindex rule, no commands or dependencies
2025 If a rule has no dependencies or commands, and the target of the rule
2026 is a nonexistent file, then @code{make} imagines this target to have
2027 been updated whenever its rule is run.  This implies that all targets
2028 depending on this one will always have their commands run.
2030 An example will illustrate this:
2032 @example
2033 @group
2034 clean: FORCE
2035         rm $(objects)
2036 FORCE:
2037 @end group
2038 @end example
2040 Here the target @samp{FORCE} satisfies the special conditions, so the
2041 target @file{clean} that depends on it is forced to run its commands.
2042 There is nothing special about the name @samp{FORCE}, but that is one name
2043 commonly used this way.
2045 As you can see, using @samp{FORCE} this way has the same results as using
2046 @samp{.PHONY: clean}.  
2048 Using @samp{.PHONY} is more explicit and more efficient.  However,
2049 other versions of @code{make} do not support @samp{.PHONY}; thus
2050 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2052 @node Empty Targets, Special Targets, Force Targets, Rules
2053 @section Empty Target Files to Record Events
2054 @cindex empty targets
2055 @cindex targets, empty
2056 @cindex recording events with empty targets
2058 The @dfn{empty target} is a variant of the phony target; it is used to hold
2059 commands for an action that you request explicitly from time to time.
2060 Unlike a phony target, this target file can really exist; but the file's
2061 contents do not matter, and usually are empty.
2063 The purpose of the empty target file is to record, with its
2064 last-modification time, when the rule's commands were last executed.  It
2065 does so because one of the commands is a @code{touch} command to update the
2066 target file.
2068 The empty target file must have some dependencies.  When you ask to remake
2069 the empty target, the commands are executed if any dependency is more
2070 recent than the target; in other words, if a dependency has changed since
2071 the last time you remade the target.  Here is an example:
2073 @example
2074 print: foo.c bar.c
2075         lpr -p $?
2076         touch print
2077 @end example
2078 @cindex @code{print} target
2079 @cindex @code{lpr} (shell command)
2080 @cindex @code{touch} (shell command)
2082 @noindent
2083 With this rule, @samp{make print} will execute the @code{lpr} command if
2084 either source file has changed since the last @samp{make print}.  The
2085 automatic variable @samp{$?} is used to print only those files that have
2086 changed (@pxref{Automatic, ,Automatic Variables}).
2088 @node Special Targets, Multiple Targets, Empty Targets, Rules
2089 @section Special Built-in Target Names
2090 @cindex special targets
2091 @cindex built-in special targets
2092 @cindex targets, built-in special
2094 Certain names have special meanings if they appear as targets.
2096 @table @code
2097 @findex .PHONY
2098 @item .PHONY
2100 The dependencies of the special target @code{.PHONY} are considered to
2101 be phony targets.  When it is time to consider such a target,
2102 @code{make} will run its commands unconditionally, regardless of
2103 whether a file with that name exists or what its last-modification
2104 time is.  @xref{Phony Targets, ,Phony Targets}.
2106 @findex .SUFFIXES
2107 @item .SUFFIXES
2109 The dependencies of the special target @code{.SUFFIXES} are the list
2110 of suffixes to be used in checking for suffix rules.  
2111 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
2113 @findex .DEFAULT
2114 @item .DEFAULT
2116 The commands specified for @code{.DEFAULT} are used for any target for
2117 which no rules are found (either explicit rules or implicit rules).
2118 @xref{Last Resort}.  If @code{.DEFAULT} commands are specified, every
2119 file mentioned as a dependency, but not as a target in a rule, will have
2120 these commands executed on its behalf.  @xref{Search Algorithm,
2121 ,Implicit Rule Search Algorithm}.
2123 @findex .PRECIOUS
2124 @item .PRECIOUS
2125 @cindex precious targets
2126 @cindex preserving with @code{.PRECIOUS}
2128 The targets which @code{.PRECIOUS} depends on are given the following
2129 special treatment: if @code{make} is killed or interrupted during the
2130 execution of their commands, the target is not deleted.
2131 @xref{Interrupts, ,Interrupting or Killing @code{make}}.
2132 Also, if the target is an intermediate file, it will not be deleted
2133 after it is no longer needed, as is normally done.
2134 @xref{Chained Rules, ,Chains of Implicit Rules}.
2136 You can also list the target pattern of an implicit rule (such as
2137 @samp{%.o}) as a dependency file of the special target @code{.PRECIOUS}
2138 to preserve intermediate files created by rules whose target patterns
2139 match that file's name.
2141 @findex .IGNORE
2142 @item .IGNORE
2144 Simply by being mentioned as a target, @code{.IGNORE} says to ignore
2145 errors in execution of commands.  The dependencies and commands for
2146 @code{.IGNORE} are not meaningful.
2148 @samp{.IGNORE} exists for historical compatibility.  Since
2149 @code{.IGNORE} affects every command in the makefile, it is not very
2150 useful; we recommend you use the more selective ways to ignore errors
2151 in specific commands.  @xref{Errors, ,Errors in Commands}.
2153 @findex .SILENT
2154 @item .SILENT
2156 Simply by being mentioned as a target, @code{.SILENT} says not to
2157 print commands before executing them.  The dependencies and commands
2158 for @code{.SILENT} are not meaningful.
2160 @samp{.SILENT} exists for historical compatibility.  We recommend you
2161 use the more selective ways to silence specific commands.
2162 @xref{Echoing, ,Command Echoing}.  If you want to silence all commands
2163 for a particular run of @code{make}, use the @samp{-s} or
2164 @w{@samp{--silent}} option (@pxref{Options Summary}).
2166 @findex .EXPORT_ALL_VARIABLES
2167 @item .EXPORT_ALL_VARIABLES
2169 Simply by being mentioned as a target, this tells @code{make} to
2170 export all variables to child processes by default.
2171 @xref{Variables/Recursion, ,Communicating Variables to a
2172 Sub-@code{make}}.
2173 @end table
2175 Any defined implicit rule suffix also counts as a special target if it
2176 appears as a target, and so does the concatenation of two suffixes, such
2177 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
2178 defining implicit rules (but a way still widely used).  In principle, any
2179 target name could be special in this way if you break it in two and add
2180 both pieces to the suffix list.  In practice, suffixes normally begin with
2181 @samp{.}, so these special target names also begin with @samp{.}.
2182 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
2184 @node Multiple Targets, Multiple Rules, Special Targets, Rules
2185 @section Multiple Targets in a Rule
2186 @cindex multiple targets
2187 @cindex several targets in a rule
2188 @cindex targets, multiple
2189 @cindex rule, with multiple targets
2191 A rule with multiple targets is equivalent to writing many rules, each with
2192 one target, and all identical aside from that.  The same commands apply to
2193 all the targets, but their effects may vary because you can substitute the
2194 actual target name into the command using @samp{$@@}.  The rule contributes
2195 the same dependencies to all the targets also.
2197 This is useful in two cases.
2199 @itemize @bullet
2200 @item
2201 You want just dependencies, no commands.  For example:
2203 @example
2204 kbd.o command.o files.o: command.h
2205 @end example
2207 @noindent
2208 gives an additional dependency to each of the three object files
2209 mentioned.
2211 @item
2212 Similar commands work for all the targets.  The commands do not need
2213 to be absolutely identical, since the automatic variable @samp{$@@}
2214 can be used to substitute the particular target to be remade into the
2215 commands (@pxref{Automatic, ,Automatic Variables}).  For example:
2217 @example
2218 @group
2219 bigoutput littleoutput : text.g
2220         generate text.g -$(subst output,,$@@) > $@@
2221 @end group
2222 @end example
2223 @findex subst
2225 @noindent
2226 is equivalent to
2228 @example
2229 bigoutput : text.g
2230         generate text.g -big > bigoutput
2231 littleoutput : text.g
2232         generate text.g -little > littleoutput
2233 @end example
2235 @noindent
2236 Here we assume the hypothetical program @code{generate} makes two
2237 types of output, one if given @samp{-big} and one if given
2238 @samp{-little}.
2239 @xref{Text Functions, ,Functions for String Substitution and Analysis},
2240 for an explanation of the @code{subst} function.
2241 @end itemize
2243 Suppose you would like to vary the dependencies according to the target,
2244 much as the variable @samp{$@@} allows you to vary the commands.
2245 You cannot do this with multiple targets in an ordinary rule, but you can
2246 do it with a @dfn{static pattern rule}.
2247 @xref{Static Pattern, ,Static Pattern Rules}.
2249 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
2250 @section Multiple Rules for One Target
2251 @cindex multiple rules for one target
2252 @cindex several rules for one target
2253 @cindex rule, multiple for one target
2254 @cindex target, multiple rules for one
2256 One file can be the target of several rules.  All the dependencies
2257 mentioned in all the rules are merged into one list of dependencies for
2258 the target.  If the target is older than any dependency from any rule,
2259 the commands are executed.
2261 There can only be one set of commands to be executed for a file.
2262 If more than one rule gives commands for the same file, 
2263 @code{make} uses the last set given and prints an error message.
2264 (As a special case, if the file's name begins with a dot, no
2265 error message is printed.  This odd behavior is only for
2266 compatibility with other implementations of @code{make}.)  
2267 There is no reason to
2268 write your makefiles this way; that is why @code{make} gives you
2269 an error message.@refill
2271 An extra rule with just dependencies can be used to give a few extra
2272 dependencies to many files at once.  For example, one usually has a
2273 variable named @code{objects} containing a list of all the compiler output
2274 files in the system being made.  An easy way to say that all of them must
2275 be recompiled if @file{config.h} changes is to write the following:
2277 @example
2278 objects = foo.o bar.o
2279 foo.o : defs.h
2280 bar.o : defs.h test.h
2281 $(objects) : config.h
2282 @end example
2284 This could be inserted or taken out without changing the rules that really
2285 specify how to make the object files, making it a convenient form to use if
2286 you wish to add the additional dependency intermittently.
2288 Another wrinkle is that the additional dependencies could be specified with
2289 a variable that you set with a command argument to @code{make}
2290 (@pxref{Overriding, ,Overriding Variables}).  For example,
2292 @example
2293 @group
2294 extradeps=
2295 $(objects) : $(extradeps)
2296 @end group
2297 @end example
2299 @noindent
2300 means that the command @samp{make extradeps=foo.h} will consider
2301 @file{foo.h} as a dependency of each object file, but plain @samp{make}
2302 will not.
2304 If none of the explicit rules for a target has commands, then @code{make}
2305 searches for an applicable implicit rule to find some commands
2306 @pxref{Implicit Rules, ,Using Implicit Rules}).
2308 @node Static Pattern, Double-Colon, Multiple Rules, Rules
2309 @section Static Pattern Rules
2310 @cindex static pattern rule
2311 @cindex rule, static pattern
2312 @cindex pattern rules, static (not implicit)
2313 @cindex varying dependencies
2314 @cindex dependencies, varying (static pattern)
2316 @dfn{Static pattern rules} are rules which specify multiple targets and
2317 construct the dependency names for each target based on the target name.
2318 They are more general than ordinary rules with multiple targets because the
2319 targets do not have to have identical dependencies.  Their dependencies must
2320 be @emph{analogous}, but not necessarily @emph{identical}.
2322 @menu
2323 * Static Usage::                The syntax of static pattern rules.
2324 * Static versus Implicit::      When are they better than implicit rules?
2325 @end menu
2327 @node Static Usage, Static versus Implicit,  , Static Pattern
2328 @subsection Syntax of Static Pattern Rules
2329 @cindex static pattern rule, syntax of
2330 @cindex pattern rules, static, syntax of
2332 Here is the syntax of a static pattern rule:
2334 @example
2335 @var{targets} @dots{}: @var{target-pattern}: @var{dep-patterns} @dots{}
2336         @var{commands}
2337         @dots{}
2338 @end example
2340 @noindent
2341 The @var{targets} list specifies the targets that the rule applies to.
2342 The targets can contain wildcard characters, just like the targets of
2343 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
2344 Names}).
2346 @cindex target pattern, static (not implicit)
2347 @cindex stem
2348 The @var{target-pattern} and @var{dep-patterns} say how to compute the
2349 dependencies of each target.  Each target is matched against the
2350 @var{target-pattern} to extract a part of the target name, called the
2351 @dfn{stem}.  This stem is substituted into each of the @var{dep-patterns}
2352 to make the dependency names (one from each @var{dep-pattern}).
2354 Each pattern normally contains the character @samp{%} just once.  When the
2355 @var{target-pattern} matches a target, the @samp{%} can match any part of
2356 the target name; this part is called the @dfn{stem}.  The rest of the
2357 pattern must match exactly.  For example, the target @file{foo.o} matches
2358 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
2359 @file{foo.c} and @file{foo.out} do not match that pattern.@refill
2361 @cindex dependency pattern, static (not implicit)
2362 The dependency names for each target are made by substituting the stem
2363 for the @samp{%} in each dependency pattern.  For example, if one
2364 dependency pattern is @file{%.c}, then substitution of the stem
2365 @samp{foo} gives the dependency name @file{foo.c}.  It is legitimate
2366 to write a dependency pattern that does not contain @samp{%}; then this
2367 dependency is the same for all targets.
2369 @cindex @code{%}, quoting in static pattern
2370 @cindex @code{%}, quoting with @code{\} (backslash)
2371 @cindex @code{\} (backslash), to quote @code{%}
2372 @cindex backslash (@code{\}), to quote @code{%}
2373 @cindex quoting @code{%}, in static pattern
2374 @samp{%} characters in pattern rules can be quoted with preceding
2375 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
2376 characters can be quoted with more backslashes.  Backslashes that quote
2377 @samp{%} characters or other backslashes are removed from the pattern
2378 before it is compared to file names or has a stem substituted into it.
2379 Backslashes that are not in danger of quoting @samp{%} characters go
2380 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
2381 @samp{the%weird\} preceding the operative @samp{%} character, and
2382 @samp{pattern\\} following it.  The final two backslashes are left alone
2383 because they cannot affect any @samp{%} character.@refill
2385 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
2386 from the corresponding @file{.c} file:
2388 @example
2389 @group
2390 objects = foo.o bar.o
2392 $(objects): %.o: %.c
2393         $(CC) -c $(CFLAGS) $< -o $@@
2394 @end group
2395 @end example
2397 @noindent
2398 Here @samp{$<} is the automatic variable that holds the name of the
2399 dependency and @samp{$@@} is the automatic variable that holds the name
2400 of the target; see @ref{Automatic, , Automatic Variables}.
2402 Each target specified must match the target pattern; a warning is issued
2403 for each target that does not.  If you have a list of files, only some of
2404 which will match the pattern, you can use the @code{filter} function to
2405 remove nonmatching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
2407 @example
2408 files = foo.elc bar.o lose.o
2410 $(filter %.o,$(files)): %.o: %.c
2411         $(CC) -c $(CFLAGS) $< -o $@@
2412 $(filter %.elc,$(files)): %.elc: %.el
2413         emacs -f batch-byte-compile $<
2414 @end example
2416 @noindent
2417 In this example the result of @samp{$(filter %.o,$(files))} is
2418 @file{bar.o lose.o}, and the first static pattern rule causes each of
2419 these object files to be updated by compiling the corresponding C source
2420 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
2421 @file{foo.elc}, so that file is made from @file{foo.el}.@refill
2423 Another example shows how to use @code{$*} in static pattern rules:
2424 @vindex $*@r{, and static pattern}
2426 @example
2427 @group
2428 bigoutput littleoutput : %output : text.g
2429         generate text.g -$* > $@@
2430 @end group
2431 @end example
2433 @noindent
2434 When the @code{generate} command is run, @code{$*} will expand to the
2435 stem, either @samp{big} or @samp{little}.
2437 @node Static versus Implicit,  , Static Usage, Static Pattern
2438 @subsection Static Pattern Rules versus Implicit Rules
2439 @cindex rule, static pattern versus implicit
2440 @cindex static pattern rule, versus implicit
2442 A static pattern rule has much in common with an implicit rule defined as a
2443 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
2444 Both have a pattern for the target and patterns for constructing the
2445 names of dependencies.  The difference is in how @code{make} decides
2446 @emph{when} the rule applies.
2448 An implicit rule @emph{can} apply to any target that matches its pattern,
2449 but it @emph{does} apply only when the target has no commands otherwise
2450 specified, and only when the dependencies can be found.  If more than one
2451 implicit rule appears applicable, only one applies; the choice depends on
2452 the order of rules.
2454 By contrast, a static pattern rule applies to the precise list of targets
2455 that you specify in the rule.  It cannot apply to any other target and it
2456 invariably does apply to each of the targets specified.  If two conflicting
2457 rules apply, and both have commands, that's an error.
2459 The static pattern rule can be better than an implicit rule for these
2460 reasons:
2462 @itemize @bullet
2463 @item
2464 You may wish to override the usual implicit rule for a few
2465 files whose names cannot be categorized syntactically but
2466 can be given in an explicit list.
2468 @item
2469 If you cannot be sure of the precise contents of the directories
2470 you are using, you may not be sure which other irrelevant files
2471 might lead @code{make} to use the wrong implicit rule.  The choice
2472 might depend on the order in which the implicit rule search is done.
2473 With static pattern rules, there is no uncertainty: each rule applies
2474 to precisely the targets specified.
2475 @end itemize
2477 @node Double-Colon, Automatic Dependencies, Static Pattern, Rules
2478 @section Double-Colon Rules
2479 @cindex double-colon rules
2480 @cindex rule, double-colon (@code{::})
2481 @cindex multiple rules for one target (@code{::})
2482 @cindex @code{::} rules (double-colon)
2484 @dfn{Double-colon} rules are rules written with @samp{::} instead of
2485 @samp{:} after the target names.  They are handled differently from
2486 ordinary rules when the same target appears in more than one rule.
2488 When a target appears in multiple rules, all the rules must be the same
2489 type: all ordinary, or all double-colon.  If they are double-colon, each of
2490 them is independent of the others.  Each double-colon rule's commands are
2491 executed if the target is older than any dependencies of that rule.  This
2492 can result in executing none, any, or all of the double-colon rules.
2494 Double-colon rules with the same target are in fact completely separate
2495 from one another.  Each double-colon rule is processed individually, just
2496 as rules with different targets are processed.
2498 The double-colon rules for a target are executed in the order they appear
2499 in the makefile.  However, the cases where double-colon rules really make
2500 sense are those where the order of executing the commands would not matter.
2502 Double-colon rules are somewhat obscure and not often very useful; they
2503 provide a mechanism for cases in which the method used to update a target
2504 differs depending on which dependency files caused the update, and such
2505 cases are rare.
2507 Each double-colon rule should specify commands; if it does not, an
2508 implicit rule will be used if one applies.  
2509 @xref{Implicit Rules, ,Using Implicit Rules}.
2511 @node Automatic Dependencies,  , Double-Colon, Rules
2512 @section Generating Dependencies Automatically
2513 @cindex dependencies, automatic generation
2514 @cindex automatic generation of dependencies
2515 @cindex generating dependencies automatically
2517 In the makefile for a program, many of the rules you need to write often
2518 say only that some object file depends on some header
2519 file.  For example, if @file{main.c} uses @file{defs.h} via an
2520 @code{#include}, you would write:
2522 @example
2523 main.o: defs.h
2524 @end example
2526 @noindent
2527 You need this rule so that @code{make} knows that it must remake
2528 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
2529 large program you would have to write dozens of such rules in your
2530 makefile.  And, you must always be very careful to update the makefile
2531 every time you add or remove an @code{#include}.
2532 @cindex @code{#include}
2534 @cindex @code{-M} (to compiler)
2535 To avoid this hassle, most modern C compilers can write these rules for
2536 you, by looking at the @code{#include} lines in the source files.
2537 Usually this is done with the @samp{-M} option to the compiler.
2538 For example, the command:
2540 @example
2541 cc -M main.c
2542 @end example
2544 @noindent
2545 generates the output:
2547 @example
2548 main.o : main.c defs.h
2549 @end example
2551 @noindent
2552 Thus you no longer have to write all those rules yourself.
2553 The compiler will do it for you.
2555 @cindex @code{make depend}
2556 With old @code{make} programs, it was traditional practice to use this
2557 compiler feature to generate dependencies on demand with a command like
2558 @samp{make depend}.  That command would create a file @file{depend}
2559 containing all the automatically-generated dependencies; then the
2560 makefile could use @code{include} to read them in (@pxref{Include}).
2562 In GNU @code{make}, the feature of remaking makefiles makes this
2563 practice obsolete---you need never tell @code{make} explicitly to
2564 regenerate the dependencies, because it always regenerates any makefile
2565 that is out of date.  @xref{Remaking Makefiles}.
2567 The practice we recommend for automatic dependency generation is to have
2568 one makefile corresponding to each source file.  For each source file
2569 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
2570 what files the object file @file{@var{name}.o} depends on.  That way
2571 only the source files that have changed need to be rescanned to produce
2572 the new dependencies.
2574 Here is the pattern rule to generate a file of dependencies (i.e., a makefile)
2575 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
2577 @example
2578 @group
2579 %.d: %.c
2580         $(SHELL) -ec '$(CC) -M $(CPPFLAGS) $< | sed '\''s/$*.o/& $@@/g'\'' > $@@'
2581 @end group
2582 @end example
2584 @noindent
2585 @xref{Pattern Rules}, for information on defining pattern rules.  The
2586 @samp{-e} flag to the shell makes it exit immediately if the
2587 @code{$(CC)} command fails (exits with a nonzero status).  Normally the
2588 shell exits with the status of the last command in the pipeline
2589 (@code{sed} in this case), so @code{make} would not notice a nonzero
2590 status from the compiler.
2591 @cindex @code{-e} (shell flag)
2593 @cindex @code{sed} (shell command)
2594 The purpose of the @code{sed} command is to translate (for example):
2596 @example
2597 main.o : main.c defs.h
2598 @end example
2600 @noindent
2601 into:
2603 @example
2604 main.o main.d : main.c defs.h
2605 @end example
2607 @noindent
2608 @cindex @code{.d}
2609 This makes each @samp{.d} file depend on all the source and header files
2610 that the corresponding @samp{.o} file depends on.  @code{make} then
2611 knows it must regenerate the dependencies whenever any of the source or
2612 header files changes.
2614 Once you've defined the rule to remake the @samp{.d} files,
2615 you then use the @code{include} directive to read them all in.
2616 @xref{Include}.  For example:
2618 @example
2619 @group
2620 sources = foo.c bar.c
2622 include $(sources:.c=.d)
2623 @end group
2624 @end example
2626 @noindent
2627 (This example uses a substitution variable reference to translate the
2628 list of source files @samp{foo.c bar.c} into a list of dependency
2629 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
2630 information on substitution references.)  Since the @samp{.d} files are
2631 makefiles like any others, @code{make} will remake them as necessary
2632 with no further work from you.  @xref{Remaking Makefiles}.
2634 @node Commands, Using Variables, Rules, Top
2635 @chapter Writing the Commands in Rules
2636 @cindex commands, how to write
2637 @cindex rule commands
2638 @cindex writing rule commands
2640 The commands of a rule consist of shell command lines to be executed one by
2641 one.  Each command line must start with a tab, except that the first
2642 command line may be attached to the target-and-dependencies line with a
2643 semicolon in between.  Blank lines and lines of just comments may appear
2644 among the command lines; they are ignored.
2646 Users use many different shell programs, but commands in makefiles are
2647 always interpreted by @file{/bin/sh} unless the makefile specifies
2648 otherwise.  @xref{Execution, ,Command Execution}.
2650 @cindex comments, in commands
2651 @cindex commands, comments in
2652 @cindex @code{#} (comments), in commands
2653 The shell that is in use determines whether comments can be written on
2654 command lines, and what syntax they use.  When the shell is
2655 @file{/bin/sh}, a @samp{#} starts a comment that extends to the end of
2656 the line.  The @samp{#} does not have to be at the beginning of a line.
2657 Text on a line before a @samp{#} is not part of the comment.
2659 @menu
2660 * Echoing::                     How to control when commands are echoed.
2661 * Execution::                   How commands are executed.
2662 * Parallel::                    How commands can be executed in parallel.
2663 * Errors::                      What happens after a command execution error. 
2664 * Interrupts::                  What happens when a command is interrupted.
2665 * Recursion::                   Invoking @code{make} from makefiles.
2666 * Sequences::                   Defining canned sequences of commands.
2667 * Empty Commands::              Defining useful, do-nothing commands.
2668 @end menu
2670 @node Echoing, Execution,  , Commands
2671 @section Command Echoing
2672 @cindex echoing of commands
2673 @cindex silent operation
2674 @cindex @code{@@} (in commands)
2675 @cindex commands, echoing
2676 @cindex printing of commands
2678 Normally @code{make} prints each command line before it is executed.
2679 We call this @dfn{echoing} because it gives the appearance that you
2680 are typing the commands yourself.
2682 When a line starts with @samp{@@}, the echoing of that line is suppressed.
2683 The @samp{@@} is discarded before the command is passed to the shell.
2684 Typically you would use this for a command whose only effect is to print
2685 something, such as an @code{echo} command to indicate progress through
2686 the makefile:
2688 @example
2689 @@echo About to make distribution files
2690 @end example
2692 @cindex @code{-n}
2693 @cindex @code{--just-print}
2694 @cindex @code{--dry-run}
2695 @cindex @code{--recon}
2696 When @code{make} is given the flag @samp{-n} or @samp{--just-print},
2697 echoing is all that happens, no execution.  @xref{Options Summary,
2698 ,Summary of Options}.  In this case and only this case, even the
2699 commands starting with @samp{@@} are printed.  This flag is useful for
2700 finding out which commands @code{make} thinks are necessary without
2701 actually doing them.
2703 @cindex @code{-s}
2704 @cindex @code{--silent}
2705 @cindex @code{--quiet}
2706 @findex .SILENT
2707 The @samp{-s} or @samp{--silent}
2708 flag to @code{make} prevents all echoing, as if all commands
2709 started with @samp{@@}.  A rule in the makefile for the special target
2710 @code{.SILENT} has the same effect 
2711 (@pxref{Special Targets, ,Special Built-in Target Names}).
2712 @code{.SILENT} is essentially obsolete since @samp{@@} is more flexible.@refill
2714 @node Execution, Parallel, Echoing, Commands
2715 @section Command Execution
2716 @cindex commands, execution
2717 @cindex execution, of commands
2718 @cindex shell command, execution
2719 @vindex SHELL @r{(command execution)}
2721 When it is time to execute commands to update a target, they are executed
2722 by making a new subshell for each line.  (In practice, @code{make} may
2723 take shortcuts that do not affect the results.)
2725 @cindex @code{cd} (shell command)
2726 @strong{Please note:} this implies that shell commands such as
2727 @code{cd} that set variables local to each process will not affect the
2728 following command lines.  If you want to use @code{cd} to affect the
2729 next command, put the two on a single line with a semicolon between
2730 them.  Then @code{make} will consider them a single command and pass
2731 them, together, to a shell which will execute them in sequence.  For
2732 example:
2734 @example
2735 foo : bar/lose
2736         cd bar; gobble lose > ../foo
2737 @end example
2739 @cindex commands, backslash (@code{\}) in
2740 @cindex commands, quoting newlines in
2741 @cindex backslash (@code{\}), in commands
2742 @cindex @code{\} (backslash), in commands
2743 @cindex quoting newline, in commands
2744 @cindex newline, quoting, in commands
2745 If you would like to split a single shell command into multiple lines of
2746 text, you must use a backslash at the end of all but the last subline.
2747 Such a sequence of lines is combined into a single line, by deleting the
2748 backslash-newline sequences, before passing it to the shell.  Thus, the
2749 following is equivalent to the preceding example:
2751 @example
2752 @group
2753 foo : bar/lose
2754         cd bar;  \
2755         gobble lose > ../foo
2756 @end group
2757 @end example
2759 @vindex SHELL
2760 The program used as the shell is taken from the variable @code{SHELL}.
2761 By default, the program @file{/bin/sh} is used.
2763 @cindex environment, @code{SHELL} in
2764 Unlike most variables, the variable @code{SHELL} is never set from the
2765 environment.  This is because the @code{SHELL} environment variable is
2766 used to specify your personal choice of shell program for interactive
2767 use.  It would be very bad for personal choices like this to affect
2768 the functioning of makefiles.  @xref{Environment, ,Variables from the
2769 Environment}.
2771 @node Parallel, Errors, Execution, Commands
2772 @section Parallel Execution
2773 @cindex commands, execution in parallel
2774 @cindex parallel execution
2775 @cindex execution, in parallel
2776 @cindex job slots
2777 @cindex @code{-j}
2778 @cindex @code{--jobs}
2780 GNU @code{make} knows how to execute several commands at once.
2781 Normally, @code{make} will execute only one command at a time, waiting
2782 for it to finish before executing the next.  However, the @samp{-j} or
2783 @samp{--jobs} option tells @code{make} to execute many commands
2784 simultaneously.@refill
2786 If the @samp{-j} option is followed by an integer, this is the number of
2787 commands to execute at once; this is called the number of @dfn{job slots}.
2788 If there is nothing looking like an integer after the @samp{-j} option,
2789 there is no limit on the number of job slots.  The default number of job
2790 slots is one, which means serial execution (one thing at a time).
2792 One unpleasant consequence of running several commands simultaneously is
2793 that output from all of the commands comes when the commands send it, so
2794 messages from different commands may be interspersed.
2796 Another problem is that two processes cannot both take input from the
2797 same device; so to make sure that only one command tries to take input
2798 from the terminal at once, @code{make} will invalidate the standard
2799 input streams of all but one running command.  This means that
2800 attempting to read from standard input will usually be a fatal error (a
2801 @samp{Broken pipe} signal) for most child processes if there are
2802 several.
2803 @cindex broken pipe
2804 @cindex standard input
2806 It is unpredictable which command will have a valid standard input stream
2807 (which will come from the terminal, or wherever you redirect the standard
2808 input of @code{make}).  The first command run will always get it first, and
2809 the first command started after that one finishes will get it next, and so
2812 We will change how this aspect of @code{make} works if we find a better
2813 alternative.  In the mean time, you should not rely on any command using
2814 standard input at all if you are using the parallel execution feature; but
2815 if you are not using this feature, then standard input works normally in
2816 all commands.
2818 If a command fails (is killed by a signal or exits with a nonzero
2819 status), and errors are not ignored for that command
2820 (@pxref{Errors, ,Errors in Commands}),
2821 the remaining command lines to remake the same target will not be run.
2822 If a command fails and the @samp{-k} or @samp{--keep-going}
2823 option was not given
2824 (@pxref{Options Summary, ,Summary of Options}), 
2825 @code{make} aborts execution.  If make
2826 terminates for any reason (including a signal) with child processes
2827 running, it waits for them to finish before actually exiting.@refill
2829 @cindex load average
2830 @cindex limiting jobs based on load
2831 @cindex jobs, limiting based on load
2832 @cindex @code{-l} (load average)
2833 @cindex @code{--max-load}
2834 @cindex @code{--load-average}
2835 When the system is heavily loaded, you will probably want to run fewer jobs
2836 than when it is lightly loaded.  You can use the @samp{-l} option to tell
2837 @code{make} to limit the number of jobs to run at once, based on the load
2838 average.  The @samp{-l} or @samp{--max-load}
2839 option is followed by a floating-point number.  For
2840 example,
2842 @example
2843 -l 2.5
2844 @end example
2846 @noindent
2847 will not let @code{make} start more than one job if the load average is
2848 above 2.5.  The @samp{-l} option with no following number removes the
2849 load limit, if one was given with a previous @samp{-l} option.@refill
2851 More precisely, when @code{make} goes to start up a job, and it already has
2852 at least one job running, it checks the current load average; if it is not
2853 lower than the limit given with @samp{-l}, @code{make} waits until the load
2854 average goes below that limit, or until all the other jobs finish.
2856 By default, there is no load limit.
2858 @node Errors, Interrupts, Parallel, Commands
2859 @section Errors in Commands
2860 @cindex errors (in commands)
2861 @cindex commands, errors in
2862 @cindex exit status (errors)
2864 After each shell command returns, @code{make} looks at its exit status.
2865 If the command completed successfully, the next command line is executed
2866 in a new shell; after the last command line is finished, the rule is
2867 finished. 
2869 If there is an error (the exit status is nonzero), @code{make} gives up on
2870 the current rule, and perhaps on all rules.
2872 Sometimes the failure of a certain command does not indicate a problem.
2873 For example, you may use the @code{mkdir} command to ensure that a
2874 directory exists.  If the directory already exists, @code{mkdir} will
2875 report an error, but you probably want @code{make} to continue regardless.
2877 @cindex @code{-} (in commands)
2878 To ignore errors in a command line, write a @samp{-} at the beginning of
2879 the line's text (after the initial tab).  The @samp{-} is discarded before
2880 the command is passed to the shell for execution.  
2882 For example,
2884 @example
2885 @group
2886 clean:
2887         -rm -f *.o
2888 @end group
2889 @end example
2890 @cindex @code{rm} (shell command)
2892 @noindent
2893 This causes @code{rm} to continue even if it is unable to remove a file.
2895 @cindex @code{-i}
2896 @cindex @code{--ignore-errors}
2897 @findex .IGNORE
2898 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
2899 flag, errors are ignored in
2900 all commands of all rules.  A rule in the makefile for the special target
2901 @code{.IGNORE} has the same effect.  These ways of ignoring errors are
2902 obsolete because @samp{-} is more flexible.
2904 When errors are to be ignored, because of either a @samp{-} or the
2905 @samp{-i} flag, @code{make} treats an error return just like success,
2906 except that it prints out a message that tells you the status code
2907 the command exited with, and says that the error has been ignored.
2909 When an error happens that @code{make} has not been told to ignore,
2910 it implies that the current target cannot be correctly remade, and neither
2911 can any other that depends on it either directly or indirectly.  No further
2912 commands will be executed for these targets, since their preconditions
2913 have not been achieved.
2915 @cindex @code{-k}
2916 @cindex @code{--keep-going}
2917 Normally @code{make} gives up immediately in this circumstance, returning a
2918 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
2919 flag is specified, @code{make}
2920 continues to consider the other dependencies of the pending targets,
2921 remaking them if necessary, before it gives up and returns nonzero status.
2922 For example, after an error in compiling one object file, @samp{make -k}
2923 will continue compiling other object files even though it already knows
2924 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
2926 The usual behavior assumes that your purpose is to get the specified
2927 targets up to date; once @code{make} learns that this is impossible, it
2928 might as well report the failure immediately.  The @samp{-k} option says
2929 that the real purpose is to test as many of the changes made in the
2930 program as possible, perhaps to find several independent problems so
2931 that you can correct them all before the next attempt to compile.  This
2932 is why Emacs' @code{compile} command passes the @samp{-k} flag by
2933 default.
2934 @cindex Emacs (@code{M-x compile})
2936 @node Interrupts, Recursion, Errors, Commands
2937 @section Interrupting or Killing @code{make}
2938 @cindex interrupt
2939 @cindex signal
2940 @cindex deletion of target files
2941 @cindex target, deleting on interrupt
2942 @cindex killing (interruption)
2944 If @code{make} gets a fatal signal while a command is executing, it may
2945 delete the target file that the command was supposed to update.  This is
2946 done if the target file's last-modification time has changed since
2947 @code{make} first checked it.
2949 The purpose of deleting the target is to make sure that it is remade from
2950 scratch when @code{make} is next run.  Why is this?  Suppose you type
2951 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
2952 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
2953 in an incomplete file whose last-modification time is newer than the source
2954 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
2955 and deletes this incomplete file.  If @code{make} did not do this, the next
2956 invocation of @code{make} would think that @file{foo.o} did not require
2957 updating---resulting in a strange error message from the linker when it
2958 tries to link an object file half of which is missing.
2960 @findex .PRECIOUS
2961 You can prevent the deletion of a target file in this way by making the
2962 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
2963 @code{make} checks to see whether it appears on the dependencies of
2964 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
2965 if a signal happens.  Some reasons why you might do this are that the
2966 target is updated in some atomic fashion, or exists only to record a
2967 modification-time (its contents do not matter), or must exist at all
2968 times to prevent other sorts of trouble.
2970 @node Recursion, Sequences, Interrupts, Commands
2971 @section Recursive Use of @code{make}
2972 @cindex recursion
2973 @cindex subdirectories, recursion for
2975 Recursive use of @code{make} means using @code{make} as a command in a
2976 makefile.  This technique is useful when you want separate makefiles for
2977 various subsystems that compose a larger system.  For example, suppose you
2978 have a subdirectory @file{subdir} which has its own makefile, and you would
2979 like the containing directory's makefile to run @code{make} on the
2980 subdirectory.  You can do it by writing this:
2982 @example
2983 subsystem:
2984         cd subdir; $(MAKE)
2985 @end example
2987 @noindent
2988 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
2990 @example
2991 subsystem:
2992         $(MAKE) -C subdir
2993 @end example
2994 @cindex @code{-C}
2995 @cindex @code{--directory}
2997 You can write recursive @code{make} commands just by copying this example,
2998 but there are many things to know about how they work and why, and about
2999 how the sub-@code{make} relates to the top-level @code{make}.
3001 @menu
3002 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
3003 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
3004 * Options/Recursion::           How to communicate options to a sub-@code{make}.
3005 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
3006                                  helps debug use of recursive @code{make} commands.
3007 @end menu
3009 @node MAKE Variable, Variables/Recursion,  , Recursion
3010 @subsection How the @code{MAKE} Variable Works
3011 @vindex MAKE
3012 @cindex recursion, and @code{MAKE} variable
3014 Recursive @code{make} commands should always use the variable @code{MAKE},
3015 not the explicit command name @samp{make}, as shown here:
3017 @example
3018 @group
3019 subsystem:
3020         cd subdir; $(MAKE)
3021 @end group
3022 @end example
3024 The value of this variable is the file name with which @code{make} was
3025 invoked.  If this file name was @file{/bin/make}, then the command executed
3026 is @samp{cd subdir; /bin/make}.  If you use a special version of
3027 @code{make} to run the top-level makefile, the same special version will be
3028 executed for recursive invocations.
3029 @cindex @code{cd} (shell command)
3031 Also, any arguments that define variable values are added to @code{MAKE},
3032 so the sub-@code{make} gets them too.  Thus, if you do @samp{make
3033 CFLAGS=-O}, so that all C compilations will be optimized, the
3034 sub-@code{make} is run with @samp{cd subdir; /bin/make CFLAGS=-O}.@refill
3036 @vindex MAKE_COMMAND
3037 @vindex MAKEOVERRIDES
3038 The @code{MAKE} variable actually just refers to two other variables
3039 which contain these special values.  In fact, @code{MAKE} is always
3040 defined as @samp{$(MAKE_COMMAND) $(MAKEOVERRIDES)}.  The variable
3041 @code{MAKE_COMMAND} is the file name with which @code{make} was invoked
3042 (such as @file{/bin/make}, above).  The variable @code{MAKEOVERRIDES}
3043 contains definitions for the variables defined on the command line; in
3044 the above example, its value is @samp{CFLAGS=-O}.  If you @emph{do not}
3045 want these variable definitions done in all recursive @code{make}
3046 invocations, you can redefine the @code{MAKEOVERRIDES} variable to
3047 remove them.  You do this in any of the normal ways for defining
3048 variables: in a makefile (@pxref{Setting, ,Setting Variables}); on the command
3049 line with an argument like @samp{MAKEOVERRIDES=} 
3050 (@pxref{Overriding, ,Overriding Variables}); or with an environment variable
3051 (@pxref{Environment, ,Variables from the Environment}).
3053 As a special feature, using the variable @code{MAKE} in the commands of
3054 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
3055 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
3056 Using the @code{MAKE} variable has the same effect as using a @samp{+}
3057 character at the beginning of the command line.  @xref{Instead of
3058 Execution, ,Instead of Executing the Commands}.@refill
3060 Consider the command @samp{make -t} in the above example.  (The
3061 @samp{-t} option marks targets as up to date without actually running
3062 any commands; see @ref{Instead of Execution}.)  Following the usual
3063 definition of @samp{-t}, a @samp{make -t} command in the example would
3064 create a file named @file{subsystem} and do nothing else.  What you
3065 really want it to do is run @samp{@w{cd subdir;} @w{make -t}}; but that would
3066 require executing the command, and @samp{-t} says not to execute
3067 commands.@refill
3068 @cindex @code{-t}, and recursion
3069 @cindex recursion, and @code{-t}
3070 @cindex @code{--touch}, and recursion
3072 The special feature makes this do what you want: whenever a command
3073 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
3074 @samp{-n} and @samp{-q} do not apply to that line.  Command lines
3075 containing @code{MAKE} are executed normally despite the presence of a
3076 flag that causes most commands not to be run.  The usual
3077 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
3078 (@pxref{Options/Recursion, ,Communicating Options to a
3079 Sub-@code{make}}), so your request to touch the files, or print the
3080 commands, is propagated to the subsystem.@refill
3082 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
3083 @subsection Communicating Variables to a Sub-@code{make}
3084 @cindex sub-@code{make}
3085 @cindex environment, and recursion
3086 @cindex exporting variables
3087 @cindex variables, environment
3088 @cindex variables, exporting
3089 @cindex recursion, and environment
3090 @cindex recursion, and variables
3092 Variable values of the top-level @code{make} can be passed to the
3093 sub-@code{make} through the environment by explicit request.  These
3094 variables are defined in the sub-@code{make} as defaults, but do not
3095 override what is specified in the sub-@code{make}'s makefile unless
3096 you use the @samp{-e} switch
3097 (@pxref{Options Summary, ,Summary of Options}).@refill
3099 To pass down, or @dfn{export}, a variable, @code{make} adds the variable
3100 and its value to the environment for running each command.  The
3101 sub-@code{make}, in turn, uses the environment to initialize its table
3102 of variable values.  @xref{Environment, ,Variables from the
3103 Environment}.
3105 Except by explicit request, @code{make} exports a variable only if it
3106 is either defined in the environment initially or set on the command
3107 line, and if its name consists only of letters, numbers, and underscores.
3108 Some shells cannot cope with environment variable names consisting of
3109 characters other than letters, numbers, and underscores.
3111 The special variables @code{SHELL} and @code{MAKEFLAGS} are always
3112 exported (unless you unexport them).
3113 @code{MAKEFILES} is exported if you set it to anything.
3115 Variables are @emph{not} normally passed down if they were created by
3116 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
3117 Implicit Rules}).  The sub-@code{make} will define these for
3118 itself.@refill
3120 @findex export
3121 If you want to export specific variables to a sub-@code{make}, use the
3122 @code{export} directive, like this:
3124 @example
3125 export @var{variable} @dots{}
3126 @end example
3128 @noindent
3129 @findex unexport
3130 If you want to @emph{prevent} a variable from being exported, use the
3131 @code{unexport} directive, like this:
3133 @example
3134 unexport @var{variable} @dots{}
3135 @end example
3137 @noindent
3138 As a convenience, you can define a variable and export it at the same
3139 time by doing:
3141 @example
3142 export @var{variable} = value
3143 @end example
3145 @noindent
3146 has the same result as:
3148 @example
3149 @var{variable} = value
3150 export @var{variable}
3151 @end example
3153 @noindent
3156 @example
3157 export @var{variable} := value
3158 @end example
3160 @noindent
3161 has the same result as:
3163 @example
3164 @var{variable} := value
3165 export @var{variable}
3166 @end example
3168 Likewise,
3170 @example
3171 export @var{variable} += value
3172 @end example
3174 @noindent
3175 is just like:
3177 @example
3178 @var{variable} += value
3179 export @var{variable}
3180 @end example
3182 @noindent
3183 @xref{Appending, ,Appending More Text to Variables}.
3185 You may notice that the @code{export} and @code{unexport} directives
3186 work in @code{make} in the same way they work in the shell, @code{sh}.
3188 If you want all variables to be exported by default, you can use
3189 @code{export} by itself:
3191 @example
3192 export
3193 @end example
3195 @noindent
3196 This tells @code{make} that variables which are not explicitly mentioned
3197 in an @code{export} or @code{unexport} directive should be exported.
3198 Any variable given in an @code{unexport} directive will still @emph{not}
3199 be exported.  If you use @code{export} by itself to export variables by
3200 default, variables whose names contain characters other than
3201 alphanumerics and underscores will not be exported unless specifically
3202 mentioned in an @code{export} directive.@refill
3204 @findex .EXPORT_ALL_VARIABLES
3205 The behavior elicited by an @code{export} directive by itself was the
3206 default in older versions of GNU @code{make}.  If your makefiles depend
3207 on this behavior and you want to be compatible with old versions of
3208 @code{make}, you can write a rule for the special target
3209 @code{.EXPORT_ALL_VARIABLES} instead of using the @code{export} directive.
3210 This will be ignored by old @code{make}s, while the @code{export}
3211 directive will cause a syntax error.@refill
3212 @cindex compatibility in exporting
3214 Likewise, you can use @code{unexport} by itself to tell @code{make}
3215 @emph{not} to export variables by default.  Since this is the default
3216 behavior, you would only need to do this if @code{export} had been used
3217 by itself earlier (in an included makefile, perhaps).  You
3218 @strong{cannot} use @code{export} and @code{unexport} by themselves to
3219 have variables exported for some commands and not for others.  The last
3220 @code{export} or @code{unexport} directive that appears by itself
3221 determines the behavior for the entire run of @code{make}.@refill
3223 @vindex MAKELEVEL
3224 @cindex recursion, level of
3225 As a special feature, the variable @code{MAKELEVEL} is changed when it
3226 is passed down from level to level.  This variable's value is a string
3227 which is the depth of the level as a decimal number.  The value is
3228 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
3229 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
3230 happens when @code{make} sets up the environment for a command.@refill
3232 The main use of @code{MAKELEVEL} is to test it in a conditional
3233 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
3234 way you can write a makefile that behaves one way if run recursively and
3235 another way if run directly by you.@refill
3237 @vindex MAKEFILES
3238 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
3239 commands to use additional makefiles.  The value of @code{MAKEFILES} is
3240 a whitespace-separated list of file names.  This variable, if defined in
3241 the outer-level makefile, is passed down through the environment; then
3242 it serves as a list of extra makefiles for the sub-@code{make} to read
3243 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
3244 Variable @code{MAKEFILES}}.@refill
3246 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
3247 @subsection Communicating Options to a Sub-@code{make}
3248 @cindex options, and recursion
3249 @cindex recursion, and options
3251 @vindex MAKEFLAGS
3252 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
3253 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
3254 set up automatically by @code{make} to contain the flag letters that
3255 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
3256 @code{MAKEFLAGS} gets the value @samp{ks}.@refill
3258 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
3259 in its environment.  In response, it takes the flags from that value and
3260 processes them as if they had been given as arguments.
3261 @xref{Options Summary, ,Summary of Options}.
3263 @cindex @code{-C}, and recursion
3264 @cindex @code{-f}, and recursion
3265 @cindex @code{-I}, and recursion
3266 @cindex @code{-o}, and recursion
3267 @cindex @code{-W}, and recursion
3268 @cindex @code{--directory}, and recursion
3269 @cindex @code{--file}, and recursion
3270 @cindex @code{--include-dir}, and recursion
3271 @cindex @code{--old-file}, and recursion
3272 @cindex @code{--assume-old}, and recursion
3273 @cindex @code{--assume-new}, and recursion
3274 @cindex @code{--new-file}, and recursion
3275 @cindex recursion, and @code{-C}
3276 @cindex recursion, and @code{-f}
3277 @cindex recursion, and @code{-I}
3278 @cindex recursion, and @code{-o}
3279 @cindex recursion, and @code{-W}
3280 The options @samp{-C}, @samp{-f}, @samp{-I}, @samp{-o}, and @samp{-W}
3281 are not put into @code{MAKEFLAGS}; these options are not passed down.@refill
3283 @cindex @code{-j}, and recursion
3284 @cindex @code{--jobs}, and recursion
3285 @cindex recursion, and @code{-j}
3286 @cindex job slots, and recursion
3287 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
3288 If you set it to some numeric value, @samp{-j 1} is always put into
3289 @code{MAKEFLAGS} instead of the value you specified.  This is because if
3290 the @w{@samp{-j}} option were passed down to sub-@code{make}s, you would
3291 get many more jobs running in parallel than you asked for.  If you give
3292 @samp{-j} with no numeric argument, meaning to run as many jobs as
3293 possible in parallel, this is passed down, since multiple infinities are
3294 no more than one.@refill
3296 If you do not want to pass the other flags down, you must change the
3297 value of @code{MAKEFLAGS}, like this:
3299 @example
3300 MAKEFLAGS=
3301 subsystem:
3302         cd subdir; $(MAKE)
3303 @end example
3305 or like this:
3307 @example
3308 subsystem:
3309         cd subdir; $(MAKE) MAKEFLAGS=
3310 @end example
3312 @vindex MFLAGS
3313 A similar variable @code{MFLAGS} exists also, for historical compatibility.
3314 It has the same value as @code{MAKEFLAGS} except that it always begins with
3315 a hyphen unless it is empty (@code{MAKEFLAGS} begins with a hyphen only when
3316 it begins with an option that has no single-letter version, such as
3317 @samp{--warn-undefined-variables}).  @code{MFLAGS} was traditionally used
3318 explicitly in the recursive @code{make} command, like this:
3320 @example
3321 subsystem:
3322         cd subdir; $(MAKE) $(MFLAGS)
3323 @end example
3325 @noindent
3326 but now @code{MAKEFLAGS} makes this usage redundant.
3328 @cindex setting options from environment
3329 @cindex options, setting from environment
3330 @cindex setting options in makefiles
3331 @cindex options, setting in makefiles
3332 The @code{MAKEFLAGS} and @code{MFLAGS} variables can also be useful if you
3333 want to have certain options, such as @samp{-k} (@pxref{Options Summary,
3334 ,Summary of Options}), set each time you run @code{make}.  You simply put a
3335 value for @code{MAKEFLAGS} or @code{MFLAGS} in your environment.  These
3336 variables may also be set in makefiles, so a makefile can specify additional
3337 flags that should also be in effect for that makefile.
3339 When @code{make} interprets the value of @code{MAKEFLAGS} or @code{MFLAGS}
3340 (either from the environment or from a makefile), it first prepends a hyphen
3341 if the value does not already begin with one.  Then it chops the value into
3342 words separated by blanks, and parses these words as if they were options
3343 given on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
3344 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
3345 is no error for an invalid option).
3347 If you do put @code{MAKEFLAGS} or @code{MFLAGS} in your environment, you
3348 should be sure not to include any options that will drastically affect
3349 the actions of @code{make} and undermine the purpose of makefiles and of
3350 @code{make} itself.  For instance, the @samp{-t}, @samp{-n}, and
3351 @samp{-q} options, if put in one of these variables, could have
3352 disastrous consequences and would certainly have at least surprising and
3353 probably annoying effects.@refill
3355 @node -w Option,  , Options/Recursion, Recursion
3356 @subsection The @samp{--print-directory} Option
3357 @cindex directories, printing them
3358 @cindex printing directories
3359 @cindex recursion, and printing directories
3361 If you use several levels of recursive @code{make} invocations, the
3362 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
3363 lot easier to understand by showing each directory as @code{make}
3364 starts processing it and as @code{make} finishes processing it.  For
3365 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
3366 @code{make} will print a line of the form:@refill
3368 @example
3369 make: Entering directory `/u/gnu/make'.
3370 @end example
3372 @noindent
3373 before doing anything else, and a line of the form:
3375 @example
3376 make: Leaving directory `/u/gnu/make'.
3377 @end example
3379 @noindent
3380 when processing is completed.
3382 @cindex @code{-C}, and @code{-w}
3383 @cindex @code{--directory}, and @code{--print-directory}
3384 @cindex recursion, and @code{-w}
3385 @cindex @code{-w}, and @code{-C}
3386 @cindex @code{-w}, and recursion
3387 @cindex @code{--print-directory}, and @code{--directory}
3388 @cindex @code{--print-directory}, and recursion
3389 @cindex @code{--no-print-directory}
3390 @cindex @code{--print-directory}, disabling
3391 @cindex @code{-w}, disabling
3392 Normally, you do not need to specify this option because @samp{make}
3393 does it for you: @samp{-w} is turned on automatically when you use the
3394 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
3395 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
3396 be silent, or if you use @samp{--no-print-directory} to explicitly
3397 disable it.
3399 @node Sequences, Empty Commands, Recursion, Commands
3400 @section Defining Canned Command Sequences
3401 @cindex sequences of commands
3402 @cindex commands, sequences of
3404 When the same sequence of commands is useful in making various targets, you
3405 can define it as a canned sequence with the @code{define} directive, and
3406 refer to the canned sequence from the rules for those targets.  The canned
3407 sequence is actually a variable, so the name must not conflict with other
3408 variable names.
3410 Here is an example of defining a canned sequence of commands:
3412 @example
3413 define run-yacc
3414 yacc $(firstword $^)
3415 mv y.tab.c $@@
3416 endef
3417 @end example
3418 @cindex @code{yacc}
3420 @noindent
3421 Here @code{run-yacc} is the name of the variable being defined;
3422 @code{endef} marks the end of the definition; the lines in between are the
3423 commands.  The @code{define} directive does not expand variable references
3424 and function calls in the canned sequence; the @samp{$} characters,
3425 parentheses, variable names, and so on, all become part of the value of the
3426 variable you are defining.
3427 @xref{Defining, ,Defining Variables Verbatim},
3428 for a complete explanation of @code{define}.
3430 The first command in this example runs Yacc on the first dependency of
3431 whichever rule uses the canned sequence.  The output file from Yacc is
3432 always named @file{y.tab.c}.  The second command moves the output to the
3433 rule's target file name.
3435 To use the canned sequence, substitute the variable into the commands of a
3436 rule.  You can substitute it like any other variable 
3437 (@pxref{Reference, ,Basics of Variable References}).
3438 Because variables defined by @code{define} are recursively expanded
3439 variables, all the variable references you wrote inside the @code{define}
3440 are expanded now.  For example:
3442 @example
3443 foo.c : foo.y
3444         $(run-yacc)
3445 @end example
3447 @noindent
3448 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
3449 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.@refill
3451 This is a realistic example, but this particular one is not needed in
3452 practice because @code{make} has an implicit rule to figure out these
3453 commands based on the file names involved 
3454 (@pxref{Implicit Rules, ,Using Implicit Rules}).
3456 @cindex @@, and @code{define}
3457 @cindex -, and @code{define}
3458 @cindex +, and @code{define}
3459 In command execution, each line of a canned sequence is treated just as
3460 if the line appeared on its own in the rule, preceded by a tab.  In
3461 particular, @code{make} invokes a separate subshell for each line.  You
3462 can use the special prefix characters that affect command lines
3463 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
3464 @xref{Commands, ,Writing the Commands in Rules}.
3465 For example, using this canned sequence:
3467 @example
3468 define frobnicate
3469 @@echo "frobnicating target $@@"
3470 frob-step-1 $< -o $@@-step-1
3471 frob-step-2 $@@-step-1 -o $@@
3472 endef
3473 @end example
3475 @noindent
3476 @code{make} will not echo the first line, the @code{echo} command.
3477 But it @emph{will} echo the following two command lines.
3479 On the other hand, prefix characters on the command line that refers to
3480 a canned sequence apply to every line in the sequence.  So the rule:
3482 @example
3483 frob.out: frob.in
3484         @@$(frobnicate)
3485 @end example
3487 @noindent
3488 does not echo @emph{any} commands.
3489 (@xref{Echoing, ,Command Echoing}, for a full explanation of @samp{@@}.)
3491 @node Empty Commands,  , Sequences, Commands
3492 @section Using Empty Commands
3493 @cindex empty commands
3494 @cindex commands, empty
3496 It is sometimes useful to define commands which do nothing.  This is done
3497 simply by giving a command that consists of nothing but whitespace.  For
3498 example:
3500 @example
3501 target: ;
3502 @end example
3504 @noindent
3505 defines an empty command string for @file{target}.  You could also use a
3506 line beginning with a tab character to define an empty command string,
3507 but this would be confusing because such a line looks empty.
3509 @findex .DEFAULT@r{, and empty commands}
3510 You may be wondering why you would want to define a command string that
3511 does nothing.  The only reason this is useful is to prevent a target
3512 from getting implicit commands (from implicit rules or the
3513 @code{.DEFAULT} special target; @pxref{Implicit Rules} and 
3514 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
3516 You may be inclined to define empty command strings for targets that are
3517 not actual files, but only exist so that their dependencies can be
3518 remade.  However, this is not the best way to do that, because the
3519 dependencies may not be remade properly if the target file actually does exist.
3520 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
3522 @node Using Variables, Conditionals, Commands, Top
3523 @chapter How to Use Variables
3524 @cindex variable
3525 @cindex value
3526 @cindex recursive variable expansion
3527 @cindex simple variable expansion
3529 A @dfn{variable} is a name defined in a makefile to represent a string
3530 of text, called the variable's @dfn{value}.  These values are
3531 substituted by explicit request into targets, dependencies, commands,
3532 and other parts of the makefile.  (In some other versions of @code{make},
3533 variables are called @dfn{macros}.)
3534 @cindex macro
3536 Variables and functions in all parts of a makefile are expanded when
3537 read, except for the shell commands in rules, the right-hand sides of
3538 variable definitions using @samp{=}, and the bodies of variable
3539 definitions using the @code{define} directive.@refill
3541 Variables can represent lists of file names, options to pass to compilers,
3542 programs to run, directories to look in for source files, directories to
3543 write output in, or anything else you can imagine.
3545 A variable name may be any sequence of characters not containing @samp{:},
3546 @samp{#}, @samp{=}, or leading or trailing whitespace.  However,
3547 variable names containing characters other than letters, numbers, and
3548 underscores should be avoided, as they may be given special meanings in the
3549 future, and with some shells they cannot be passed through the environment to a
3550 sub-@code{make} 
3551 (@pxref{Variables/Recursion, ,Communicating Variables to a Sub-@code{make}}).
3553 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
3554 and @samp{Foo} all refer to different variables.
3556 It is traditional to use upper case letters in variable names, but we
3557 recommend using lower case letters for variable names that serve internal
3558 purposes in the makefile, and reserving upper case for parameters that
3559 control implicit rules or for parameters that the user should override with
3560 command options (@pxref{Overriding, ,Overriding Variables}).
3562 @menu
3563 * Reference::                   How to use the value of a variable.
3564 * Flavors::                     Variables come in two flavors.
3565 * Advanced::                    Advanced features for referencing a variable.
3566 * Values::                      All the ways variables get their values.
3567 * Setting::                     How to set a variable in the makefile.
3568 * Appending::                   How to append more text to the old value
3569                                   of a variable.
3570 * Override Directive::          How to set a variable in the makefile even if
3571                                   the user has set it with a command argument.
3572 * Defining::                    An alternate way to set a variable 
3573                                   to a verbatim string.
3574 * Environment::                 Variable values can come from the environment.
3575 @end menu
3577 @node Reference, Flavors,  , Using Variables
3578 @section Basics of Variable References
3579 @cindex variables, how to reference
3580 @cindex reference to variables
3581 @cindex @code{$}, in variable reference
3582 @cindex dollar sign (@code{$}), in variable reference
3584 To substitute a variable's value, write a dollar sign followed by the name
3585 of the variable in parentheses or braces: either @samp{$(foo)} or
3586 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
3587 special significance of @samp{$} is why you must write @samp{$$} to have
3588 the effect of a single dollar sign in a file name or command.
3590 Variable references can be used in any context: targets, dependencies,
3591 commands, most directives, and new variable values.  Here is an
3592 example of a common case, where a variable holds the names of all the
3593 object files in a program:
3595 @example
3596 @group
3597 objects = program.o foo.o utils.o
3598 program : $(objects)
3599         cc -o program $(objects)
3601 $(objects) : defs.h
3602 @end group
3603 @end example
3605 Variable references work by strict textual substitution.  Thus, the rule
3607 @example
3608 @group
3609 foo = c
3610 prog.o : prog.$(foo)
3611         $(foo)$(foo) -$(foo) prog.$(foo)
3612 @end group
3613 @end example
3615 @noindent
3616 could be used to compile a C program @file{prog.c}.  Since spaces before
3617 the variable value are ignored in variable assignments, the value of
3618 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
3619 this way!)
3621 A dollar sign followed by a character other than a dollar sign,
3622 open-parenthesis or open-brace treats that single character as the
3623 variable name.  Thus, you could reference the variable @code{x} with
3624 @samp{$x}.  However, this practice is strongly discouraged, except in
3625 the case of the automatic variables (@pxref{Automatic, ,Automatic Variables}).
3627 @node Flavors, Advanced, Reference, Using Variables
3628 @section The Two Flavors of Variables
3629 @cindex flavors of variables
3630 @cindex recursive variable expansion
3631 @cindex variables, flavors
3632 @cindex recursively expanded variables
3633 @cindex variables, recursively expanded
3635 There are two ways that a variable in GNU @code{make} can have a value;
3636 we call them the two @dfn{flavors} of variables.  The two flavors are
3637 distinguished in how they are defined and in what they do when expanded.
3639 @cindex =
3640 The first flavor of variable is a @dfn{recursively expanded} variable.
3641 Variables of this sort are defined by lines using @samp{=}
3642 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
3643 (@pxref{Defining, ,Defining Variables Verbatim}).  The value you specify
3644 is installed verbatim; if it contains references to other variables,
3645 these references are expanded whenever this variable is substituted (in
3646 the course of expanding some other string).  When this happens, it is
3647 called @dfn{recursive expansion}.@refill
3649 For example,
3651 @example
3652 foo = $(bar)
3653 bar = $(ugh)
3654 ugh = Huh?
3656 all:;echo $(foo)
3657 @end example
3659 @noindent
3660 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
3661 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
3663 This flavor of variable is the only sort supported by other versions of
3664 @code{make}.  It has its advantages and its disadvantages.  An advantage
3665 (most would say) is that:
3667 @example
3668 CFLAGS = $(include_dirs) -O
3669 include_dirs = -Ifoo -Ibar
3670 @end example
3672 @noindent
3673 will do what was intended: when @samp{CFLAGS} is expanded in a command,
3674 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
3675 cannot append something on the end of a variable, as in
3677 @example
3678 CFLAGS = $(CFLAGS) -O
3679 @end example
3681 @noindent
3682 because it will cause an infinite loop in the variable expansion.
3683 (Actually @code{make} detects the infinite loop and reports an error.)
3684 @cindex loops in variable expansion
3685 @cindex variables, loops in expansion
3687 Another disadvantage is that any functions 
3688 (@pxref{Functions, ,Functions for Transforming Text})
3689 referenced in the definition will be executed every time the variable is
3690 expanded.  This makes @code{make} run slower; worse, it causes the
3691 @code{wildcard} and @code{shell} functions to give unpredictable results
3692 because you cannot easily control when they are called, or even how many
3693 times.
3695 To avoid all the problems and inconveniences of recursively expanded
3696 variables, there is another flavor: simply expanded variables.
3698 @cindex simply expanded variables
3699 @cindex variables, simply expanded
3700 @cindex :=
3701 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
3702 (@pxref{Setting, ,Setting Variables}).  
3703 The value of a simply expanded variable is scanned
3704 once and for all, expanding any references to other variables and
3705 functions, when the variable is defined.  The actual value of the simply
3706 expanded variable is the result of expanding the text that you write.
3707 It does not contain any references to other variables; it contains their
3708 values @emph{as of the time this variable was defined}.  Therefore,
3710 @example
3711 x := foo
3712 y := $(x) bar
3713 x := later
3714 @end example
3716 @noindent
3717 is equivalent to
3719 @example
3720 y := foo bar
3721 x := later
3722 @end example
3724 When a simply expanded variable is referenced, its value is substituted
3725 verbatim.
3727 Here is a somewhat more complicated example, illustrating the use of
3728 @samp{:=} in conjunction with the @code{shell} function.
3729 (@xref{Shell Function, , The @code{shell} Function}.)  This example
3730 also shows use of the variable @code{MAKELEVEL}, which is changed
3731 when it is passed down from level to level.
3732 (@xref{Variables/Recursion, , Communicating Variables to a
3733 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
3735 @vindex MAKELEVEL
3736 @vindex MAKE
3737 @example
3738 @group
3739 ifeq (0,$@{MAKELEVEL@})
3740 cur-dir   := $(shell pwd)
3741 whoami    := $(shell whoami)
3742 host-type := $(shell arch)
3743 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
3744 endif
3745 @end group
3746 @end example
3748 @noindent 
3749 An advantage of this use of @samp{:=} is that a typical
3750 `descend into a directory' command then looks like this:
3752 @example
3753 @group
3754 $@{subdirs@}:
3755       $@{MAKE@} cur-dir=$@{cur-dir@}/$@@ -C $@@ all
3756 @end group
3757 @end example
3759 Simply expanded variables generally make complicated makefile programming
3760 more predictable because they work like variables in most programming
3761 languages.  They allow you to redefine a variable using its own value (or
3762 its value processed in some way by one of the expansion functions) and to
3763 use the expansion functions much more efficiently 
3764 (@pxref{Functions, ,Functions for Transforming Text}).
3766 @cindex spaces, in variable values
3767 @cindex variables, spaces in values
3768 You can also use them to introduce controlled leading or trailing spaces
3769 into variable values.  Such spaces are discarded from your input before
3770 substitution of variable references and function calls; this means you can
3771 include leading or trailing spaces in a variable value by protecting them
3772 with variable references, like this:
3774 @example
3775 nullstring :=
3776 space := $(nullstring) $(nullstring)
3777 @end example
3779 @noindent
3780 Here the value of the variable @code{space} is precisely one space.
3782 @node Advanced, Values, Flavors, Using Variables
3783 @section Advanced Features for Reference to Variables
3784 @cindex reference to variables
3786 This section describes some advanced features you can use to reference
3787 variables in more flexible ways.
3789 @menu
3790 * Substitution Refs::           Referencing a variable with 
3791                                   substitutions on the value.
3792 * Computed Names::              Computing the name of the variable to refer to.
3793 @end menu
3795 @node Substitution Refs, Computed Names,  , Advanced
3796 @subsection Substitution References
3797 @cindex modified variable reference
3798 @cindex substitution variable reference
3799 @cindex variables, modified reference
3800 @cindex variables, substitution reference
3802 @cindex variables, substituting suffix in
3803 @cindex suffix, substituting in variables
3804 A @dfn{substitution reference} substitutes the value of a variable with
3805 alterations that you specify.  It has the form
3806 @samp{$(@var{var}:@var{a}=@var{b})} (or
3807 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
3808 of the variable @var{var}, replace every @var{a} at the end of a word with
3809 @var{b} in that value, and substitute the resulting string.
3811 When we say ``at the end of a word'', we mean that @var{a} must appear
3812 either followed by whitespace or at the end of the value in order to be
3813 replaced; other occurrences of @var{a} in the value are unaltered.  For
3814 example:@refill
3816 @example
3817 foo := a.o b.o c.o
3818 bar := $(foo:.o=.c)
3819 @end example
3821 @noindent
3822 sets @samp{bar} to @samp{a.c b.c c.c}.  @xref{Setting, ,Setting Variables}.
3824 A substitution reference is actually an abbreviation for use of the
3825 @code{patsubst} expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}).  We provide
3826 substitution references as well as @code{patsubst} for compatibility with
3827 other implementations of @code{make}.
3829 @findex patsubst
3830 Another type of substitution reference lets you use the full power of
3831 the @code{patsubst} function.  It has the same form
3832 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
3833 @var{a} must contain a single @samp{%} character.  This case is
3834 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
3835 @xref{Text Functions, ,Functions for String Substitution and Analysis},
3836 for a description of the @code{patsubst} function.@refill
3838 @example
3839 @group
3840 @exdent For example:
3842 foo := a.o b.o c.o
3843 bar := $(foo:%.o=%.c)
3844 @end group
3845 @end example
3847 @noindent
3848 sets @samp{bar} to @samp{a.c b.c c.c}.
3850 @node Computed Names,  , Substitution Refs, Advanced
3851 @subsection Computed Variable Names
3852 @cindex nested variable reference
3853 @cindex computed variable name
3854 @cindex variables, computed names
3855 @cindex variables, nested references
3856 @cindex variables, @samp{$} in name
3857 @cindex @code{$}, in variable name
3858 @cindex dollar sign (@code{$}), in variable name
3860 Computed variable names are a complicated concept needed only for
3861 sophisticated makefile programming.  For most purposes you need not
3862 consider them, except to know that making a variable with a dollar sign
3863 in its name might have strange results.  However, if you are the type
3864 that wants to understand everything, or you are actually interested in
3865 what they do, read on.
3867 Variables may be referenced inside the name of a variable.  This is
3868 called a @dfn{computed variable name} or a @dfn{nested variable
3869 reference}.  For example,
3871 @example
3872 x = y
3873 y = z
3874 a := $($(x))
3875 @end example
3877 @noindent
3878 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
3879 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
3880 to @samp{z}.  Here the name of the variable to reference is not stated
3881 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
3882 @samp{$(x)} here is nested within the outer variable reference.
3884 The previous example shows two levels of nesting, but any number of levels
3885 is possible.  For example, here are three levels:
3887 @example
3888 x = y
3889 y = z
3890 z = u
3891 a := $($($(x)))
3892 @end example
3894 @noindent
3895 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
3896 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
3897 @samp{$(z)}, which becomes @samp{u}.
3899 References to recursively-expanded variables within a variable name are
3900 reexpanded in the usual fashion.  For example:
3902 @example
3903 x = $(y)
3904 y = z
3905 z = Hello
3906 a := $($(x))
3907 @end example
3909 @noindent
3910 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
3911 which becomes @samp{$(z)} which becomes @samp{Hello}.
3913 Nested variable references can also contain modified references and
3914 function invocations (@pxref{Functions, ,Functions for Transforming Text}),
3915 just like any other reference.
3916 For example, using the @code{subst} function 
3917 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
3919 @example
3920 @group
3921 x = variable1
3922 variable2 := Hello
3923 y = $(subst 1,2,$(x))
3924 z = y
3925 a := $($($(z)))
3926 @end group
3927 @end example
3929 @noindent
3930 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
3931 would ever want to write a nested reference as convoluted as this one, but
3932 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
3933 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
3934 @code{x} and changes it by substitution to @samp{variable2}, so that the
3935 entire string becomes @samp{$(variable2)}, a simple variable reference
3936 whose value is @samp{Hello}.@refill
3938 A computed variable name need not consist entirely of a single variable
3939 reference.  It can contain several variable references, as well as some
3940 invariant text.  For example,
3942 @example
3943 @group
3944 a_dirs := dira dirb
3945 1_dirs := dir1 dir2
3946 @end group
3948 @group
3949 a_files := filea fileb
3950 1_files := file1 file2
3951 @end group
3953 @group
3954 ifeq "$(use_a)" "yes"
3955 a1 := a
3956 else
3957 a1 := 1
3958 endif
3959 @end group
3961 @group
3962 ifeq "$(use_dirs)" "yes"
3963 df := dirs
3964 else
3965 df := files
3966 endif
3968 dirs := $($(a1)_$(df))
3969 @end group
3970 @end example
3972 @noindent
3973 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
3974 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
3975 and @code{use_dirs}.@refill
3977 Computed variable names can also be used in substitution references:
3979 @example
3980 @group
3981 a_objects := a.o b.o c.o
3982 1_objects := 1.o 2.o 3.o
3984 sources := $($(a1)_objects:.o=.c)
3985 @end group
3986 @end example
3988 @noindent
3989 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
3990 depending on the value of @code{a1}.
3992 The only restriction on this sort of use of nested variable references
3993 is that they cannot specify part of the name of a function to be called.
3994 This is because the test for a recognized function name is done before
3995 the expansion of nested references.  For example,
3997 @example
3998 @group
3999 ifdef do_sort
4000 func := sort
4001 else
4002 func := strip
4003 endif
4004 @end group
4006 @group
4007 bar := a d b g q c
4008 @end group
4010 @group
4011 foo := $($(func) $(bar))
4012 @end group
4013 @end example
4015 @noindent
4016 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
4017 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
4018 as the argument to either the @code{sort} or the @code{strip} function.
4019 This restriction could be removed in the future if that change is shown
4020 to be a good idea.
4022 You can also use computed variable names in the left-hand side of a
4023 variable assignment, or in a @code{define} directive, as in:
4025 @example
4026 dir = foo
4027 $(dir)_sources := $(wildcard $(dir)/*.c)
4028 define $(dir)_print
4029 lpr $($(dir)_sources)
4030 endef
4031 @end example
4033 @noindent
4034 This example defines the variables @samp{dir}, @samp{foo_sources}, and
4035 @samp{foo_print}.
4037 Note that @dfn{nested variable references} are quite different from
4038 @dfn{recursively expanded variables}
4039 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
4040 used together in complex ways when doing makefile programming.@refill
4042 @node Values, Setting, Advanced, Using Variables
4043 @section How Variables Get Their Values
4044 @cindex variables, how they get their values
4045 @cindex value, how a variable gets it
4047 Variables can get values in several different ways:
4049 @itemize @bullet
4050 @item
4051 You can specify an overriding value when you run @code{make}.
4052 @xref{Overriding, ,Overriding Variables}.
4054 @item
4055 You can specify a value in the makefile, either
4056 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
4057 verbatim definition (@pxref{Defining, ,Defining Variables Verbatim}).@refill
4059 @item
4060 Variables in the environment become @code{make} variables.
4061 @xref{Environment, ,Variables from the Environment}.
4063 @item
4064 Several @dfn{automatic} variables are given new values for each rule.
4065 Each of these has a single conventional use.
4066 @xref{Automatic, ,Automatic Variables}.
4068 @item
4069 Several variables have constant initial values.
4070 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
4071 @end itemize
4073 @node Setting, Appending, Values, Using Variables
4074 @section Setting Variables
4075 @cindex setting variables
4076 @cindex variables, setting
4077 @cindex =
4078 @cindex :=
4080 To set a variable from the makefile, write a line starting with the
4081 variable name followed by @samp{=} or @samp{:=}.  Whatever follows the
4082 @samp{=} or @samp{:=} on the line becomes the value.  For example,
4084 @example
4085 objects = main.o foo.o bar.o utils.o
4086 @end example
4088 @noindent
4089 defines a variable named @code{objects}.  Whitespace around the variable
4090 name and immediately after the @samp{=} is ignored.
4092 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
4093 Variables defined with @samp{:=} are @dfn{simply expanded} variables; these
4094 definitions can contain variable references which will be expanded before
4095 the definition is made.  @xref{Flavors, ,The Two Flavors of Variables}.
4097 The variable name may contain function and variable references, which
4098 are expanded when the line is read to find the actual variable name to use.
4100 There is no limit on the length of the value of a variable except the
4101 amount of swapping space on the computer.  When a variable definition is
4102 long, it is a good idea to break it into several lines by inserting
4103 backslash-newline at convenient places in the definition.  This will not
4104 affect the functioning of @code{make}, but it will make the makefile easier
4105 to read.
4107 Most variable names are considered to have the empty string as a value if
4108 you have never set them.  Several variables have built-in initial values
4109 that are not empty, but you can set them in the usual ways
4110 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).  
4111 Several special variables are set
4112 automatically to a new value for each rule; these are called the
4113 @dfn{automatic} variables (@pxref{Automatic, ,Automatic Variables}).
4115 @node Appending, Override Directive, Setting, Using Variables
4116 @section Appending More Text to Variables
4117 @cindex +=
4118 @cindex appending to variables
4119 @cindex variables, appending to
4121 Often it is useful to add more text to the value of a variable already defined.
4122 You do this with a line containing @samp{+=}, like this:
4124 @example
4125 objects += another.o
4126 @end example
4128 @noindent
4129 This takes the value of the variable @code{objects}, and adds the text
4130 @samp{another.o} to it (preceded by a single space).  Thus:
4132 @example
4133 objects = main.o foo.o bar.o utils.o
4134 objects += another.o
4135 @end example
4137 @noindent
4138 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
4140 Using @samp{+=} is similar to:
4142 @example
4143 objects = main.o foo.o bar.o utils.o
4144 objects := $(objects) another.o
4145 @end example
4147 @noindent
4148 but differs in ways that become important when you use more complex values.
4150 When the variable in question has not been defined before, @samp{+=}
4151 acts just like normal @samp{=}: it defines a recursively-expanded
4152 variable.  However, when there @emph{is} a previous definition, exactly
4153 what @samp{+=} does depends on what flavor of variable you defined
4154 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
4155 explanation of the two flavors of variables.
4157 When you add to a variable's value with @samp{+=}, @code{make} acts
4158 essentially as if you had included the extra text in the initial
4159 definition of the variable.  If you defined it first with @samp{:=},
4160 making it a simply-expanded variable, @samp{+=} adds to that
4161 simply-expanded definition, and expands the new text before appending it
4162 to the old value just as @samp{:=} does
4163 (@pxref{Setting, ,Setting Variables}, for a full explanation of @samp{:=}).
4164 In fact,
4166 @example
4167 variable := value
4168 variable += more
4169 @end example
4171 @noindent
4172 is exactly equivalent to:
4174 @noindent
4175 @example
4176 variable := value
4177 variable := $(variable) more
4178 @end example
4180 On the other hand, when you use @samp{+=} with a variable that you defined
4181 first to be recursively-expanded using plain @samp{=}, @code{make} does
4182 something a bit different.  Recall that when you define a
4183 recursively-expanded variable, @code{make} does not expand the value you set
4184 for variable and function references immediately.  Instead it stores the text
4185 verbatim, and saves these variable and function references to be expanded
4186 later, when you refer to the new variable (@pxref{Flavors, ,The Two Flavors
4187 of Variables}).  When you use @samp{+=} on a recursively-expanded variable,
4188 it is this unexpanded text to which @code{make} appends the new text you
4189 specify.
4191 @example
4192 @group
4193 variable = value
4194 variable += more
4195 @end group
4196 @end example
4198 @noindent
4199 is roughly equivalent to:
4201 @example
4202 @group
4203 temp = value
4204 variable = $(temp) more
4205 @end group
4206 @end example
4208 @noindent
4209 except that of course it never defines a variable called @code{temp}.
4210 The importance of this comes when the variable's old value contains
4211 variable references.  Take this common example:
4213 @example
4214 CFLAGS = $(includes) -O
4215 @dots{}
4216 CFLAGS += -pg # enable profiling
4217 @end example
4219 @noindent
4220 The first line defines the @code{CFLAGS} variable with a reference to another
4221 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
4222 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
4223 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
4224 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
4225 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
4226 need not be defined yet for its value to take effect.  It only has to be
4227 defined before any reference to @code{CFLAGS}.  If we tried to append to the
4228 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
4230 @example
4231 CFLAGS := $(CFLAGS) -pg # enable profiling
4232 @end example
4234 @noindent
4235 This is pretty close, but not quite what we want.  Using @samp{:=}
4236 redefines @code{CFLAGS} as a simply-expanded variable; this means
4237 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
4238 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
4239 -pg}}, and a later definition of @code{includes} will have no effect.
4240 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
4241 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
4242 the reference to @code{includes}, so if that variable gets defined at
4243 any later point, a reference like @samp{$(CFLAGS)} still uses its
4244 value.
4246 @node Override Directive, Defining, Appending, Using Variables
4247 @section The @code{override} Directive
4248 @findex override
4249 @cindex overriding with @code{override}
4250 @cindex variables, overriding
4252 If a variable has been set with a command argument 
4253 (@pxref{Overriding, ,Overriding Variables}),
4254 then ordinary assignments in the makefile are ignored.  If you want to set
4255 the variable in the makefile even though it was set with a command
4256 argument, you can use an @code{override} directive, which is a line that
4257 looks like this:@refill
4259 @example
4260 override @var{variable} = @var{value}
4261 @end example
4263 @noindent
4266 @example
4267 override @var{variable} := @var{value}
4268 @end example
4270 To append more text to a variable defined on the command line, use:
4272 @example
4273 override @var{variable} += @var{more text}
4274 @end example
4276 @noindent
4277 @xref{Appending, ,Appending More Text to Variables}.
4279 The @code{override} directive was not invented for escalation in the war
4280 between makefiles and command arguments.  It was invented so you can alter
4281 and add to values that the user specifies with command arguments.
4283 For example, suppose you always want the @samp{-g} switch when you run the
4284 C compiler, but you would like to allow the user to specify the other
4285 switches with a command argument just as usual.  You could use this
4286 @code{override} directive:
4288 @example
4289 override CFLAGS += -g
4290 @end example
4292 You can also use @code{override} directives with @code{define} directives.
4293 This is done as you might expect:
4295 @example
4296 override define foo
4298 endef
4299 @end example
4301 @noindent
4302 @iftex
4303 See the next section for information about @code{define}.
4304 @end iftex
4305 @ifinfo
4306 @xref{Defining, ,Defining Variables Verbatim}.
4307 @end ifinfo
4309 @node Defining, Environment, Override Directive, Using Variables
4310 @section Defining Variables Verbatim
4311 @findex define
4312 @findex endef
4313 @cindex verbatim variable definition
4314 @cindex defining variables verbatim
4315 @cindex variables, defining verbatim
4317 Another way to set the value of a variable is to use the @code{define}
4318 directive.  This directive has an unusual syntax which allows newline
4319 characters to be included in the value, which is convenient for defining
4320 canned sequences of commands 
4321 (@pxref{Sequences, ,Defining Canned Command Sequences}).
4323 The @code{define} directive is followed on the same line by the name of the
4324 variable and nothing more.  The value to give the variable appears on the
4325 following lines.  The end of the value is marked by a line containing just
4326 the word @code{endef}.  Aside from this difference in syntax, @code{define}
4327 works just like @samp{=}: it creates a recursively-expanded variable
4328 (@pxref{Flavors, ,The Two Flavors of Variables}).
4329 The variable name may contain function and variable references, which
4330 are expanded when the directive is read to find the actual variable name
4331 to use.
4333 @example
4334 define two-lines
4335 echo foo
4336 echo $(bar)
4337 endef
4338 @end example
4340 The value in an ordinary assignment cannot contain a newline; but the
4341 newlines that separate the lines of the value in a @code{define} become
4342 part of the variable's value (except for the final newline which precedes
4343 the @code{endef} and is not considered part of the value).@refill
4345 @need 800
4346 The previous example is functionally equivalent to this:
4348 @example
4349 two-lines = echo foo; echo $(bar)
4350 @end example
4352 @noindent
4353 since two commands separated by semicolon behave much like two separate
4354 shell commands.  However, note that using two separate lines means
4355 @code{make} will invoke the shell twice, running an independent subshell
4356 for each line.  @xref{Execution, ,Command Execution}.
4358 If you want variable definitions made with @code{define} to take
4359 precedence over command-line variable definitions, you can use the
4360 @code{override} directive together with @code{define}:
4362 @example
4363 override define two-lines
4365 $(bar)
4366 endef
4367 @end example
4369 @noindent
4370 @xref{Override Directive, ,The @code{override} Directive}.
4372 @node Environment,  , Defining, Using Variables
4373 @section Variables from the Environment
4375 @cindex variables, environment
4376 @cindex environment
4377 Variables in @code{make} can come from the environment in which
4378 @code{make} is run.  Every environment variable that @code{make} sees when
4379 it starts up is transformed into a @code{make} variable with the same name
4380 and value.  But an explicit assignment in the makefile, or with a command
4381 argument, overrides the environment.  (If the @samp{-e} flag is specified,
4382 then values from the environment override assignments in the makefile.
4383 @xref{Options Summary, ,Summary of Options}.
4384 But this is not recommended practice.)
4386 Thus, by setting the variable @code{CFLAGS} in your environment, you can
4387 cause all C compilations in most makefiles to use the compiler switches you
4388 prefer.  This is safe for variables with standard or conventional meanings
4389 because you know that no makefile will use them for other things.  (But
4390 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
4391 and therefore are not affected by the value in the environment.)
4393 When @code{make} is invoked recursively, variables defined in the
4394 outer invocation can be passed to inner invocations through the
4395 environment (@pxref{Recursion, ,Recursive Use of @code{make}}).  By
4396 default, only variables that came from the environment or the command
4397 line are passed to recursive invocations.  You can use the
4398 @code{export} directive to pass other variables.
4399 @xref{Variables/Recursion, , Communicating Variables to a
4400 Sub-@code{make}}, for full details.
4402 Other use of variables from the environment is not recommended.  It is not
4403 wise for makefiles to depend for their functioning on environment variables
4404 set up outside their control, since this would cause different users to get
4405 different results from the same makefile.  This is against the whole
4406 purpose of most makefiles.
4408 Such problems would be especially likely with the variable @code{SHELL},
4409 which is normally present in the environment to specify the user's choice
4410 of interactive shell.  It would be very undesirable for this choice to
4411 affect @code{make}.  So @code{make} ignores the environment value of
4412 @code{SHELL}.@refill
4414 @node Conditionals, Functions, Using Variables, Top
4415 @chapter Conditional Parts of Makefiles
4417 @cindex conditionals
4418 A @dfn{conditional} causes part of a makefile to be obeyed or ignored
4419 depending on the values of variables.  Conditionals can compare the
4420 value of one variable to another, or the value of a variable to
4421 a constant string.  Conditionals control what @code{make} actually
4422 ``sees'' in the makefile, so they @emph{cannot} be used to control shell
4423 commands at the time of execution.@refill
4425 @menu
4426 * Conditional Example::         Example of a conditional
4427 * Conditional Syntax::          The syntax of conditionals.
4428 * Testing Flags::               Conditionals that test flags.
4429 @end menu
4431 @node Conditional Example, Conditional Syntax,  , Conditionals
4432 @section Example of a Conditional
4434 The following example of a conditional tells @code{make} to use one set
4435 of libraries if the @code{CC} variable is @samp{gcc}, and a different
4436 set of libraries otherwise.  It works by controlling which of two
4437 command lines will be used as the command for a rule.  The result is
4438 that @samp{CC=gcc} as an argument to @code{make} changes not only which
4439 compiler is used but also which libraries are linked.
4441 @example
4442 libs_for_gcc = -lgnu
4443 normal_libs =
4445 foo: $(objects)
4446 ifeq ($(CC),gcc)
4447         $(CC) -o foo $(objects) $(libs_for_gcc)
4448 else
4449         $(CC) -o foo $(objects) $(normal_libs)
4450 endif
4451 @end example
4453 This conditional uses three directives: one @code{ifeq}, one @code{else}
4454 and one @code{endif}.
4456 The @code{ifeq} directive begins the conditional, and specifies the
4457 condition.  It contains two arguments, separated by a comma and surrounded
4458 by parentheses.  Variable substitution is performed on both arguments and
4459 then they are compared.  The lines of the makefile following the
4460 @code{ifeq} are obeyed if the two arguments match; otherwise they are
4461 ignored.
4463 The @code{else} directive causes the following lines to be obeyed if the
4464 previous conditional failed.  In the example above, this means that the
4465 second alternative linking command is used whenever the first alternative
4466 is not used.  It is optional to have an @code{else} in a conditional.
4468 The @code{endif} directive ends the conditional.  Every conditional must
4469 end with an @code{endif}.  Unconditional makefile text follows.
4471 As this example illustrates, conditionals work at the textual level:
4472 the lines of the conditional are treated as part of the makefile, or
4473 ignored, according to the condition.  This is why the larger syntactic
4474 units of the makefile, such as rules, may cross the beginning or the
4475 end of the conditional.
4477 When the variable @code{CC} has the value @samp{gcc}, the above example has
4478 this effect:
4480 @example
4481 foo: $(objects)
4482         $(CC) -o foo $(objects) $(libs_for_gcc)
4483 @end example
4485 @noindent
4486 When the variable @code{CC} has any other value, the effect is this:
4488 @example
4489 foo: $(objects)
4490         $(CC) -o foo $(objects) $(normal_libs)
4491 @end example
4493 Equivalent results can be obtained in another way by conditionalizing a
4494 variable assignment and then using the variable unconditionally:
4496 @example
4497 libs_for_gcc = -lgnu
4498 normal_libs =
4500 ifeq ($(CC),gcc)
4501   libs=$(libs_for_gcc)
4502 else
4503   libs=$(normal_libs)
4504 endif
4506 foo: $(objects)
4507         $(CC) -o foo $(objects) $(libs)
4508 @end example
4510 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
4511 @section Syntax of Conditionals
4512 @findex ifdef
4513 @findex ifeq
4514 @findex ifndef
4515 @findex ifneq
4516 @findex else
4517 @findex endif
4519 The syntax of a simple conditional with no @code{else} is as follows:
4521 @example
4522 @var{conditional-directive}
4523 @var{text-if-true}
4524 endif
4525 @end example
4527 @noindent
4528 The @var{text-if-true} may be any lines of text, to be considered as part
4529 of the makefile if the condition is true.  If the condition is false, no
4530 text is used instead.
4532 The syntax of a complex conditional is as follows:
4534 @example
4535 @var{conditional-directive}
4536 @var{text-if-true}
4537 else
4538 @var{text-if-false}
4539 endif
4540 @end example
4542 @noindent
4543 If the condition is true, @var{text-if-true} is used; otherwise,
4544 @var{text-if-false} is used instead.  The @var{text-if-false} can be any
4545 number of lines of text.
4547 The syntax of the @var{conditional-directive} is the same whether the
4548 conditional is simple or complex.  There are four different directives that
4549 test different conditions.  Here is a table of them:
4551 @table @code
4552 @item ifeq (@var{arg1}, @var{arg2})
4553 @itemx ifeq '@var{arg1}' '@var{arg2}'
4554 @itemx ifeq "@var{arg1}" "@var{arg2}"
4555 @itemx ifeq "@var{arg1}" '@var{arg2}'
4556 @itemx ifeq '@var{arg1}' "@var{arg2}"
4557 Expand all variable references in @var{arg1} and @var{arg2} and
4558 compare them.  If they are identical, the @var{text-if-true} is
4559 effective; otherwise, the @var{text-if-false}, if any, is effective.
4561 Often you want to test if a variable has a non-empty value.  When the
4562 value results from complex expansions of variables and functions,
4563 expansions you would consider empty may actually contain whitespace
4564 characters and thus are not seen as empty.  However, you can use the
4565 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
4566 whitespace as a non-empty value.  For example:
4568 @example
4569 @group
4570 ifeq ($(strip $(foo)),)
4571 @var{text-if-empty}
4572 endif
4573 @end group
4574 @end example
4576 @noindent
4577 will evaluate @var{text-if-empty} even if the expansion of
4578 @code{$(foo)} contains whitespace characters.
4580 @item ifneq (@var{arg1}, @var{arg2})
4581 @itemx ifneq '@var{arg1}' '@var{arg2}'
4582 @itemx ifneq "@var{arg1}" "@var{arg2}"
4583 @itemx ifneq "@var{arg1}" '@var{arg2}'
4584 @itemx ifneq '@var{arg1}' "@var{arg2}"
4585 Expand all variable references in @var{arg1} and @var{arg2} and
4586 compare them.  If they are different, the @var{text-if-true} is
4587 effective; otherwise, the @var{text-if-false}, if any, is effective.
4589 @item ifdef @var{variable-name}
4590 If the variable @var{variable-name} has a non-empty value, the
4591 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
4592 if any, is effective.  Variables that have never been defined have an
4593 empty value.
4595 Note that @code{ifdef} only tests whether a variable has a value.  It
4596 does not expand the variable to see if that value is nonempty.
4597 Consequently, tests using @code{ifdef} return true for all definitions
4598 except those like @code{foo =}.  To test for an empty value, use
4599 @w{@code{ifeq ($(foo),)}}.  For example,
4601 @example
4602 bar =
4603 foo = $(bar)
4604 ifdef foo
4605 frobozz = yes
4606 else
4607 frobozz = no
4608 endif
4609 @end example
4611 @noindent
4612 sets @samp{frobozz} to @samp{yes}, while:
4614 @example
4615 foo =
4616 ifdef foo
4617 frobozz = yes
4618 else
4619 frobozz = no
4620 endif
4621 @end example
4623 @noindent
4624 sets @samp{frobozz} to @samp{no}.
4626 @item ifndef @var{variable-name}
4627 If the variable @var{variable-name} has an empty value, the
4628 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
4629 if any, is effective.
4630 @end table
4632 Extra spaces are allowed and ignored at the beginning of the conditional
4633 directive line, but a tab is not allowed.  (If the line begins with a tab,
4634 it will be considered a command for a rule.)  Aside from this, extra spaces
4635 or tabs may be inserted with no effect anywhere except within the directive
4636 name or within an argument.  A comment starting with @samp{#} may appear at
4637 the end of the line.
4639 The other two directives that play a part in a conditional are @code{else}
4640 and @code{endif}.  Each of these directives is written as one word, with no
4641 arguments.  Extra spaces are allowed and ignored at the beginning of the
4642 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
4643 appear at the end of the line.
4645 Conditionals affect which lines of the makefile @code{make} uses.  If
4646 the condition is true, @code{make} reads the lines of the
4647 @var{text-if-true} as part of the makefile; if the condition is false,
4648 @code{make} ignores those lines completely.  It follows that syntactic
4649 units of the makefile, such as rules, may safely be split across the
4650 beginning or the end of the conditional.@refill
4652 @code{make} evaluates conditionals when it reads a makefile.
4653 Consequently, you cannot use automatic variables in the tests of
4654 conditionals because they are not defined until commands are run
4655 (@pxref{Automatic, , Automatic Variables}).
4657 To prevent intolerable confusion, it is not permitted to start a
4658 conditional in one makefile and end it in another.  However, you may
4659 write an @code{include} directive within a conditional, provided you do
4660 not attempt to terminate the conditional inside the included file.
4662 @node Testing Flags,  , Conditional Syntax, Conditionals
4663 @section Conditionals that Test Flags
4665 You can write a conditional that tests @code{make} command flags such as
4666 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
4667 @code{findstring} function 
4668 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
4669 This is useful when @code{touch} is not enough to make a file appear up
4670 to date.
4672 The @code{findstring} function determines whether one string appears as a
4673 substring of another.  If you want to test for the @samp{-t} flag,
4674 use @samp{t} as the first string and the value of @code{MAKEFLAGS} as
4675 the other.
4677 For example, here is how to arrange to use @samp{ranlib -t} to finish
4678 marking an archive file up to date:
4680 @example
4681 archive.a: @dots{}
4682 ifneq (,$(findstring t,$(MAKEFLAGS)))
4683         +touch archive.a
4684         +ranlib -t archive.a
4685 else
4686         ranlib archive.a
4687 endif
4688 @end example
4690 @noindent
4691 The @samp{+} prefix marks those command lines as ``recursive'' so
4692 that they will be executed despite use of the @samp{-t} flag.
4693 @xref{Recursion, ,Recursive Use of @code{make}}.
4695 @node Functions, Running, Conditionals, Top
4696 @chapter Functions for Transforming Text
4697 @cindex functions
4699 @dfn{Functions} allow you to do text processing in the makefile to compute
4700 the files to operate on or the commands to use.  You use a function in a
4701 @dfn{function call}, where you give the name of the function and some text
4702 (the @dfn{arguments}) for the function to operate on.  The result of the
4703 function's processing is substituted into the makefile at the point of the
4704 call, just as a variable might be substituted.
4706 @menu
4707 * Syntax of Functions::         How to write a function call.
4708 * Text Functions::              General-purpose text manipulation functions.
4709 * Filename Functions::          Functions for manipulating file names.
4710 * Foreach Function::            Repeat some text with controlled variation.
4711 * Origin Function::             Find where a variable got its value.
4712 * Shell Function::              Substitute the output of a shell command.
4713 @end menu
4715 @node Syntax of Functions, Text Functions,  , Functions
4716 @section Function Call Syntax
4717 @cindex @code{$}, in function call
4718 @cindex dollar sign (@code{$}), in function call
4719 @cindex arguments of functions
4720 @cindex functions, syntax of
4722 A function call resembles a variable reference.  It looks like this:
4724 @example
4725 $(@var{function} @var{arguments})
4726 @end example
4728 @noindent
4729 or like this:
4731 @example
4732 $@{@var{function} @var{arguments}@}
4733 @end example
4735 Here @var{function} is a function name; one of a short list of names that
4736 are part of @code{make}.  There is no provision for defining new functions.
4738 The @var{arguments} are the arguments of the function.  They are
4739 separated from the function name by one or more spaces or tabs, and if
4740 there is more than one argument, then they are separated by commas.
4741 Such whitespace and commas are not part of an argument's value.  The
4742 delimiters which you use to surround the function call, whether
4743 parentheses or braces, can appear in an argument only in matching pairs;
4744 the other kind of delimiters may appear singly.  If the arguments
4745 themselves contain other function calls or variable references, it is
4746 wisest to use the same kind of delimiters for all the references; write
4747 @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst a,b,$@{x@})}}.  This
4748 is because it is clearer, and because only one type of delimiter is
4749 matched to find the end of the reference.
4751 The text written for each argument is processed by substitution of
4752 variables and function calls to produce the argument value, which
4753 is the text on which the function acts.  The substitution is done in the
4754 order in which the arguments appear.
4756 Commas and unmatched parentheses or braces cannot appear in the text of an
4757 argument as written; leading spaces cannot appear in the text of the first
4758 argument as written.  These characters can be put into the argument value
4759 by variable substitution.  First define variables @code{comma} and
4760 @code{space} whose values are isolated comma and space characters, then
4761 substitute these variables where such characters are wanted, like this:
4763 @example
4764 @group
4765 comma:= ,
4766 empty:=
4767 space:= $(empty) $(empty)
4768 foo:= a b c
4769 bar:= $(subst $(space),$(comma),$(foo))
4770 # @r{bar is now `a,b,c'.}
4771 @end group
4772 @end example
4774 @noindent
4775 Here the @code{subst} function replaces each space with a comma, through
4776 the value of @code{foo}, and substitutes the result.
4778 @node Text Functions, Filename Functions, Syntax of Functions, Functions
4779 @section Functions for String Substitution and Analysis
4780 @cindex functions, for text
4782 Here are some functions that operate on strings:
4784 @table @code
4785 @item $(subst @var{from},@var{to},@var{text})
4786 @findex subst
4787 Performs a textual replacement on the text @var{text}: each occurrence
4788 of @var{from} is replaced by @var{to}.  The result is substituted for
4789 the function call.  For example,
4791 @example
4792 $(subst ee,EE,feet on the street)
4793 @end example
4795 substitutes the string @samp{fEEt on the strEEt}.
4797 @item $(patsubst @var{pattern},@var{replacement},@var{text})
4798 @findex patsubst
4799 Finds whitespace-separated words in @var{text} that match
4800 @var{pattern} and replaces them with @var{replacement}.  Here
4801 @var{pattern} may contain a @samp{%} which acts as a wildcard,
4802 matching any number of any characters within a word.  If
4803 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
4804 by the text that matched the @samp{%} in @var{pattern}.@refill
4806 @cindex @code{%}, quoting in @code{patsubst}
4807 @cindex @code{%}, quoting with @code{\} (backslash)
4808 @cindex @code{\} (backslash), to quote @code{%}
4809 @cindex backslash (@code{\}), to quote @code{%}
4810 @cindex quoting @code{%}, in @code{patsubst}
4811 @samp{%} characters in @code{patsubst} function invocations can be
4812 quoted with preceding backslashes (@samp{\}).  Backslashes that would
4813 otherwise quote @samp{%} characters can be quoted with more backslashes.
4814 Backslashes that quote @samp{%} characters or other backslashes are
4815 removed from the pattern before it is compared file names or has a stem
4816 substituted into it.  Backslashes that are not in danger of quoting
4817 @samp{%} characters go unmolested.  For example, the pattern
4818 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
4819 operative @samp{%} character, and @samp{pattern\\} following it.  The
4820 final two backslashes are left alone because they cannot affect any
4821 @samp{%} character.@refill
4823 Whitespace between words is folded into single space characters;
4824 leading and trailing whitespace is discarded.
4826 For example,
4828 @example
4829 $(patsubst %.c,%.o,x.c.c bar.c)
4830 @end example
4832 @noindent
4833 produces the value @samp{x.c.o bar.o}.
4835 Substitution references (@pxref{Substitution Refs, ,Substitution
4836 References}) are a simpler way to get the effect of the @code{patsubst}
4837 function:
4839 @example
4840 $(@var{var}:@var{pattern}=@var{replacement})  
4841 @end example
4843 @noindent
4844 is equivalent to 
4846 @example
4847 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
4848 @end example
4850 The second shorthand simplifies one of the most common uses of
4851 @code{patsubst}: replacing the suffix at the end of file names.
4853 @example
4854 $(@var{var}:@var{suffix}=@var{replacement}) 
4855 @end example
4857 @noindent
4858 is equivalent to 
4860 @example
4861 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
4862 @end example
4864 @noindent
4865 For example, you might have a list of object files:
4867 @example
4868 objects = foo.o bar.o baz.o
4869 @end example
4871 @noindent
4872 To get the list of corresponding source files, you could simply write:
4874 @example
4875 $(objects:.o=.c)
4876 @end example
4878 @noindent
4879 instead of using the general form:
4881 @example
4882 $(patsubst %.o,%.c,$(objects))
4883 @end example
4885 @item $(strip @var{string})
4886 @cindex stripping whitespace
4887 @cindex whitespace, stripping
4888 @cindex spaces, stripping
4889 @findex strip
4890 Removes leading and trailing whitespace from @var{string} and replaces
4891 each internal sequence of one or more whitespace characters with a
4892 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
4894 The function @code{strip} can be very useful when used in conjunction
4895 with conditionals.  When comparing something with the empty string
4896 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
4897 just whitespace to match the empty string (@pxref{Conditionals}).
4899 Thus, the following may fail to have the desired results:
4901 @example
4902 .PHONY: all
4903 ifneq   "$(needs_made)" ""
4904 all: $(needs_made)
4905 else
4906 all:;@@echo 'Nothing to make!'
4907 endif
4908 @end example
4910 @noindent
4911 Replacing the variable reference @w{@samp{$(needs_made)}} with the
4912 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
4913 directive would make it more robust.@refill
4915 @item $(findstring @var{find},@var{in})
4916 @findex findstring
4917 @cindex searching for strings
4918 @cindex finding strings
4919 @cindex strings, searching for
4920 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
4921 value is @var{find}; otherwise, the value is empty.  You can use this
4922 function in a conditional to test for the presence of a specific
4923 substring in a given string.  Thus, the two examples,
4925 @example
4926 $(findstring a,a b c)
4927 $(findstring a,b c)
4928 @end example
4930 @noindent
4931 produce the values @samp{a} and @samp{} (the empty string),
4932 respectively.  @xref{Testing Flags}, for a practical application of
4933 @code{findstring}.@refill
4935 @need 750
4936 @findex filter
4937 @cindex filtering words
4938 @cindex words, filtering
4939 @item $(filter @var{pattern}@dots{},@var{text})
4940 Removes all whitespace-separated words in @var{text} that do
4941 @emph{not} match any of the @var{pattern} words, returning only
4942 matching words.  The patterns are written using @samp{%}, just like
4943 the patterns used in the @code{patsubst} function above.@refill
4945 The @code{filter} function can be used to separate out different types
4946 of strings (such as file names) in a variable.  For example:
4948 @example
4949 sources := foo.c bar.c baz.s ugh.h
4950 foo: $(sources)
4951         cc $(filter %.c %.s,$(sources)) -o foo
4952 @end example
4954 @noindent
4955 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
4956 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
4957 @file{baz.s} should be specified in the command to the
4958 compiler.@refill
4960 @item $(filter-out @var{pattern}@dots{},@var{text})
4961 @findex filter-out
4962 @cindex filtering out words
4963 @cindex words, filtering out
4964 Removes all whitespace-separated words in @var{text} that @emph{do}
4965 match the @var{pattern} words, returning only the words that @emph{do
4966 not} match.  This is the exact opposite of the @code{filter}
4967 function.@refill
4969 For example, given:
4971 @example
4972 @group
4973 objects=main1.o foo.o main2.o bar.o
4974 mains=main1.o main2.o
4975 @end group
4976 @end example
4978 @noindent
4979 the following generates a list which contains all the object files not
4980 in @samp{mains}:
4982 @example
4983 $(filter-out $(mains),$(objects))
4984 @end example
4986 @need 1500
4987 @findex sort
4988 @cindex sorting words
4989 @item $(sort @var{list})
4990 Sorts the words of @var{list} in lexical order, removing duplicate
4991 words.  The output is a list of words separated by single spaces.
4992 Thus,
4994 @example
4995 $(sort foo bar lose)
4996 @end example
4998 @noindent
4999 returns the value @samp{bar foo lose}.
5001 @cindex removing duplicate words
5002 @cindex duplicate words, removing
5003 @cindex words, removing duplicates
5004 Incidentally, since @code{sort} removes duplicate words, you can use
5005 it for this purpose even if you don't care about the sort order.
5006 @end table
5008 Here is a realistic example of the use of @code{subst} and
5009 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
5010 to specify a list of directories that @code{make} should search for
5011 dependency files 
5012 (@pxref{General Search, , @code{VPATH} Search Path for All Dependencies}).  
5013 This example shows how to
5014 tell the C compiler to search for header files in the same list of
5015 directories.@refill
5017 The value of @code{VPATH} is a list of directories separated by colons,
5018 such as @samp{src:../headers}.  First, the @code{subst} function is used to
5019 change the colons to spaces:
5021 @example
5022 $(subst :, ,$(VPATH))
5023 @end example
5025 @noindent
5026 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
5027 each directory name into a @samp{-I} flag.  These can be added to the
5028 value of the variable @code{CFLAGS}, which is passed automatically to the C
5029 compiler, like this:
5031 @example
5032 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
5033 @end example
5035 @noindent
5036 The effect is to append the text @samp{-Isrc -I../headers} to the
5037 previously given value of @code{CFLAGS}.  The @code{override} directive is
5038 used so that the new value is assigned even if the previous value of
5039 @code{CFLAGS} was specified with a command argument (@pxref{Override
5040 Directive, , The @code{override} Directive}).
5042 @node Filename Functions, Foreach Function, Text Functions, Functions
5043 @section Functions for File Names
5044 @cindex functions, for file names
5045 @cindex file name functions
5047 Several of the built-in expansion functions relate specifically to
5048 taking apart file names or lists of file names.
5050 Each of the following functions performs a specific transformation on a
5051 file name.  The argument of the function is regarded as a series of file
5052 names, separated by whitespace.  (Leading and trailing whitespace is
5053 ignored.)  Each file name in the series is transformed in the same way and
5054 the results are concatenated with single spaces between them.
5056 @table @code
5057 @item $(dir @var{names}@dots{})
5058 @findex dir
5059 @cindex directory part
5060 @cindex file name, directory part
5061 Extracts the directory-part of each file name in @var{names}.  The
5062 directory-part of the file name is everything up through (and
5063 including) the last slash in it.  If the file name contains no slash,
5064 the directory part is the string @samp{./}.  For example,
5066 @example
5067 $(dir src/foo.c hacks)
5068 @end example
5070 @noindent
5071 produces the result @samp{src/ ./}.
5073 @item $(notdir @var{names}@dots{})
5074 @findex notdir
5075 @cindex file name, nondirectory part
5076 @cindex nondirectory part
5077 Extracts all but the directory-part of each file name in @var{names}.
5078 If the file name contains no slash, it is left unchanged.  Otherwise,
5079 everything through the last slash is removed from it.
5081 A file name that ends with a slash becomes an empty string.  This is
5082 unfortunate, because it means that the result does not always have the
5083 same number of whitespace-separated file names as the argument had;
5084 but we do not see any other valid alternative.
5086 For example,
5088 @example
5089 $(notdir src/foo.c hacks)
5090 @end example
5092 @noindent
5093 produces the result @samp{foo.c hacks}.
5095 @item $(suffix @var{names}@dots{})
5096 @findex suffix
5097 @cindex suffix, function to find
5098 @cindex file name suffix
5099 Extracts the suffix of each file name in @var{names}.  If the file name
5100 contains a period, the suffix is everything starting with the last
5101 period.  Otherwise, the suffix is the empty string.  This frequently
5102 means that the result will be empty when @var{names} is not, and if
5103 @var{names} contains multiple file names, the result may contain fewer
5104 file names.
5106 For example,
5108 @example
5109 $(suffix src/foo.c hacks)
5110 @end example
5112 @noindent
5113 produces the result @samp{.c}.
5115 @item $(basename @var{names}@dots{})
5116 @findex basename
5117 @cindex basename
5118 @cindex file name, basename of
5119 Extracts all but the suffix of each file name in @var{names}.  If the
5120 file name contains a period, the basename is everything starting up to
5121 (and not including) the last period.  Otherwise, the basename is the
5122 entire file name.  For example,
5124 @example
5125 $(basename src/foo.c hacks)
5126 @end example
5128 @noindent
5129 produces the result @samp{src/foo hacks}.
5131 @c plural convention with dots (be consistent)
5132 @item $(addsuffix @var{suffix},@var{names}@dots{})
5133 @findex addsuffix
5134 @cindex suffix, adding
5135 @cindex file name suffix, adding
5136 The argument @var{names} is regarded as a series of names, separated
5137 by whitespace; @var{suffix} is used as a unit.  The value of
5138 @var{suffix} is appended to the end of each individual name and the
5139 resulting larger names are concatenated with single spaces between
5140 them.  For example,
5142 @example
5143 $(addsuffix .c,foo bar)
5144 @end example
5146 @noindent
5147 produces the result @samp{foo.c bar.c}.
5149 @item $(addprefix @var{prefix},@var{names}@dots{})
5150 @findex addprefix
5151 @cindex prefix, adding
5152 @cindex file name prefix, adding
5153 The argument @var{names} is regarded as a series of names, separated
5154 by whitespace; @var{prefix} is used as a unit.  The value of
5155 @var{prefix} is prepended to the front of each individual name and the
5156 resulting larger names are concatenated with single spaces between
5157 them.  For example,
5159 @example
5160 $(addprefix src/,foo bar)
5161 @end example
5163 @noindent
5164 produces the result @samp{src/foo src/bar}.
5166 @item $(join @var{list1},@var{list2})
5167 @findex join
5168 @cindex joining lists of words
5169 @cindex words, joining lists
5170 Concatenates the two arguments word by word: the two first words (one
5171 from each argument) concatenated form the first word of the result, the
5172 two second words form the second word of the result, and so on.  So the
5173 @var{n}th word of the result comes from the @var{n}th word of each
5174 argument.  If one argument has more words that the other, the extra
5175 words are copied unchanged into the result.
5177 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
5179 Whitespace between the words in the lists is not preserved; it is
5180 replaced with a single space.
5182 This function can merge the results of the @code{dir} and
5183 @code{notdir} functions, to produce the original list of files which
5184 was given to those two functions.@refill
5186 @item $(word @var{n},@var{text})
5187 @findex word
5188 @cindex words, selecting
5189 @cindex selecting words
5190 Returns the @var{n}th word of @var{text}.  The legitimate values of
5191 @var{n} start from 1.  If @var{n} is bigger than the number of words
5192 in @var{text}, the value is empty.  For example,
5194 @example
5195 $(word 2, foo bar baz)
5196 @end example
5198 @noindent
5199 returns @samp{bar}.
5201 @c Following item phrased to prevent overfull hbox.  --RJC 17 Jul 92
5202 @item $(words @var{text})
5203 @findex words
5204 @cindex words, finding number
5205 Returns the number of words in @var{text}.  
5206 Thus, the last word of @var{text} is
5207 @w{@code{$(word $(words @var{text}),@var{text})}}.@refill
5209 @item $(firstword @var{names}@dots{})
5210 @findex firstword
5211 @cindex words, extracting first
5212 The argument @var{names} is regarded as a series of names, separated
5213 by whitespace.  The value is the first name in the series.  The rest
5214 of the names are ignored.
5216 For example,
5218 @example
5219 $(firstword foo bar)
5220 @end example
5222 @noindent
5223 produces the result @samp{foo}.  Although @code{$(firstword
5224 @var{text})} is the same as @code{$(word 1,@var{text})}, the
5225 @code{firstword} function is retained for its simplicity.@refill
5227 @item $(wildcard @var{pattern})
5228 @findex wildcard
5229 @cindex wildcard, function
5230 The argument @var{pattern} is a file name pattern, typically containing
5231 wildcard characters (as in shell file name patterns).  The result of
5232 @code{wildcard} is a space-separated list of the names of existing files
5233 that match the pattern.
5234 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
5235 @end table
5237 @node Foreach Function, Origin Function, Filename Functions, Functions
5238 @section The @code{foreach} Function
5239 @findex foreach
5240 @cindex words, iterating over
5242 The @code{foreach} function is very different from other functions.  It
5243 causes one piece of text to be used repeatedly, each time with a different
5244 substitution performed on it.  It resembles the @code{for} command in the
5245 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
5247 The syntax of the @code{foreach} function is:
5249 @example
5250 $(foreach @var{var},@var{list},@var{text})
5251 @end example
5253 @noindent
5254 The first two arguments, @var{var} and @var{list}, are expanded before
5255 anything else is done; note that the last argument, @var{text}, is
5256 @strong{not} expanded at the same time.  Then for each word of the expanded
5257 value of @var{list}, the variable named by the expanded value of @var{var}
5258 is set to that word, and @var{text} is expanded.  Presumably @var{text}
5259 contains references to that variable, so its expansion will be different
5260 each time.
5262 The result is that @var{text} is expanded as many times as there are
5263 whitespace-separated words in @var{list}.  The multiple expansions of
5264 @var{text} are concatenated, with spaces between them, to make the result
5265 of @code{foreach}.
5267 This simple example sets the variable @samp{files} to the list of all files
5268 in the directories in the list @samp{dirs}:
5270 @example
5271 dirs := a b c d
5272 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
5273 @end example
5275 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
5276 finds the value @samp{a} for @code{dir}, so it produces the same result
5277 as @samp{$(wildcard a/*)}; the second repetition produces the result
5278 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
5280 This example has the same result (except for setting @samp{dirs}) as
5281 the following example:
5283 @example
5284 files := $(wildcard a/* b/* c/* d/*)
5285 @end example
5287 When @var{text} is complicated, you can improve readability by giving it
5288 a name, with an additional variable:
5290 @example
5291 find_files = $(wildcard $(dir)/*)
5292 dirs := a b c d
5293 files := $(foreach dir,$(dirs),$(find_files))
5294 @end example
5296 @noindent
5297 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
5298 to define a recursively-expanding variable, so that its value contains an
5299 actual function call to be reexpanded under the control of @code{foreach};
5300 a simply-expanded variable would not do, since @code{wildcard} would be
5301 called only once at the time of defining @code{find_files}.
5303 The @code{foreach} function has no permanent effect on the variable
5304 @var{var}; its value and flavor after the @code{foreach} function call are
5305 the same as they were beforehand.  The other values which are taken from
5306 @var{list} are in effect only temporarily, during the execution of
5307 @code{foreach}.  The variable @var{var} is a simply-expanded variable
5308 during the execution of @code{foreach}.  If @var{var} was undefined
5309 before the @code{foreach} function call, it is undefined after the call.
5310 @xref{Flavors, ,The Two Flavors of Variables}.@refill
5312 You must take care when using complex variable expressions that result in
5313 variable names because many strange things are valid variable names, but
5314 are probably not what you intended.  For example,
5316 @smallexample
5317 files := $(foreach Es escrito en espanol!,b c ch,$(find_files))
5318 @end smallexample
5320 @noindent
5321 might be useful if the value of @code{find_files} references the variable
5322 whose name is @samp{Es escrito en espanol!} (es un nombre bastante largo,
5323 no?), but it is more likely to be a mistake.
5325 @node Origin Function, Shell Function, Foreach Function, Functions
5326 @section The @code{origin} Function
5327 @findex origin
5328 @cindex variables, origin of
5329 @cindex origin of variable
5331 The @code{origin} function is unlike most other functions in that it does
5332 not operate on the values of variables; it tells you something @emph{about}
5333 a variable.  Specifically, it tells you where it came from.
5335 The syntax of the @code{origin} function is:
5337 @example
5338 $(origin @var{variable})
5339 @end example
5341 Note that @var{variable} is the @emph{name} of a variable to inquire about;
5342 not a @emph{reference} to that variable.  Therefore you would not normally
5343 use a @samp{$} or parentheses when writing it.  (You can, however, use a
5344 variable reference in the name if you want the name not to be a constant.)
5346 The result of this function is a string telling you how the variable
5347 @var{variable} was defined:
5349 @table @samp
5350 @item undefined
5352 if @var{variable} was never defined.
5354 @item default
5356 if @var{variable} has a default definition, as is usual with @code{CC}
5357 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
5358 Note that if you have redefined a default variable, the @code{origin}
5359 function will return the origin of the later definition.
5361 @item environment
5363 if @var{variable} was defined as an environment variable and the
5364 @samp{-e} option is @emph{not} turned on (@pxref{Options Summary, ,Summary of Options}).
5366 @item environment override
5368 if @var{variable} was defined as an environment variable and the
5369 @w{@samp{-e}} option @emph{is} turned on (@pxref{Options Summary,
5370 ,Summary of Options}).@refill
5372 @item file
5374 if @var{variable} was defined in a makefile.
5376 @item command line
5378 if @var{variable} was defined on the command line.
5380 @item override
5382 if @var{variable} was defined with an @code{override} directive in a
5383 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
5385 @item automatic
5387 if @var{variable} is an automatic variable defined for the
5388 execution of the commands for each rule
5389 (@pxref{Automatic, , Automatic Variables}).
5390 @end table
5392 This information is primarily useful (other than for your curiosity) to
5393 determine if you want to believe the value of a variable.  For example,
5394 suppose you have a makefile @file{foo} that includes another makefile
5395 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
5396 if you run the command @w{@samp{make -f bar}}, even if the environment contains
5397 a definition of @code{bletch}.  However, if @file{foo} defined
5398 @code{bletch} before including @file{bar}, you do not want to override that
5399 definition.  This could be done by using an @code{override} directive in
5400 @file{foo}, giving that definition precedence over the later definition in
5401 @file{bar}; unfortunately, the @code{override} directive would also
5402 override any command line definitions.  So, @file{bar} could
5403 include:@refill
5405 @example
5406 @group
5407 ifdef bletch
5408 ifeq "$(origin bletch)" "environment"
5409 bletch = barf, gag, etc.
5410 endif
5411 endif
5412 @end group
5413 @end example
5415 @noindent
5416 If @code{bletch} has been defined from the environment, this will redefine
5419 If you want to override a previous definition of @code{bletch} if it came
5420 from the environment, even under @samp{-e}, you could instead write:
5422 @example
5423 @group
5424 ifneq "$(findstring environment,$(origin bletch))" ""
5425 bletch = barf, gag, etc.
5426 endif
5427 @end group
5428 @end example
5430 Here the redefinition takes place if @samp{$(origin bletch)} returns either
5431 @samp{environment} or @samp{environment override}.
5432 @xref{Text Functions, , Functions for String Substitution and Analysis}.
5434 @node Shell Function,  , Origin Function, Functions
5435 @section The @code{shell} Function
5436 @findex shell
5437 @cindex commands, expansion
5438 @cindex backquotes
5439 @cindex shell command, function for
5441 The @code{shell} function is unlike any other function except the
5442 @code{wildcard} function 
5443 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
5444 communicates with the world outside of @code{make}.
5446 The @code{shell} function performs the same function that backquotes
5447 (@samp{`}) perform in most shells: it does @dfn{command expansion}.  This
5448 means that it takes an argument that is a shell command and returns the
5449 output of the command.  The only processing @code{make} does on the result,
5450 before substituting it into the surrounding text, is to convert newlines to
5451 spaces.@refill
5453 The commands run by calls to the @code{shell} function are run when the
5454 function calls are expanded.  In most cases, this is when the makefile is
5455 read in.  The exception is that function calls in the commands of the rules
5456 are expanded when the commands are run, and this applies to @code{shell}
5457 function calls like all others.
5459 Here are some examples of the use of the @code{shell} function:
5461 @example
5462 contents := $(shell cat foo)
5463 @end example
5465 @noindent
5466 sets @code{contents} to the contents of the file @file{foo}, with a space
5467 (rather than a newline) separating each line.
5469 @example
5470 files := $(shell echo *.c)
5471 @end example
5473 @noindent
5474 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
5475 using a very strange shell, this has the same result as
5476 @w{@samp{$(wildcard *.c)}}.@refill
5478 @node Running, Implicit Rules, Functions, Top
5479 @chapter How to Run @code{make}
5481 A makefile that says how to recompile a program can be used in more
5482 than one way.  The simplest use is to recompile every file that is out
5483 of date.  Usually, makefiles are written so that if you run
5484 @code{make} with no arguments, it does just that.
5486 But you might want to update only some of the files; you might want to use
5487 a different compiler or different compiler options; you might want just to
5488 find out which files are out of date without changing them.
5490 By giving arguments when you run @code{make}, you can do any of these
5491 things and many others.
5493 @menu
5494 * Makefile Arguments::          How to specify which makefile to use.
5495 * Goals::                       How to use goal arguments to specify which 
5496                                   parts of the makefile to use.
5497 * Instead of Execution::        How to use mode flags to specify what
5498                                   kind of thing to do with the commands 
5499                                   in the makefile other than simply 
5500                                   execute them.
5501 * Avoiding Compilation::        How to avoid recompiling certain files.
5502 * Overriding::                  How to override a variable to specify 
5503                                   an alternate compiler and other things.
5504 * Testing::                     How to proceed past some errors, to 
5505                                   test compilation.
5506 * Options Summary::             Summary of Options
5507 @end menu
5509 @node Makefile Arguments, Goals,  , Running
5510 @section Arguments to Specify the Makefile
5511 @cindex @code{--file}
5512 @cindex @code{--makefile}
5513 @cindex @code{-f}
5515 The way to specify the name of the makefile is with the @samp{-f} or
5516 @samp{--file} option (@samp{--makefile} also works).  For example,
5517 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
5519 If you use the @samp{-f} flag several times and follow each @samp{-f}
5520 with an argument, all the specified files are used jointly as
5521 makefiles.
5523 If you do not use the @samp{-f} or @samp{--file} flag, the default is
5524 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
5525 that order, and use the first of these three which exists or can be made
5526 (@pxref{Makefiles, ,Writing Makefiles}).@refill
5528 @node Goals, Instead of Execution, Makefile Arguments, Running
5529 @section Arguments to Specify the Goals
5530 @cindex goal, how to specify
5532 The @dfn{goals} are the targets that @code{make} should strive ultimately
5533 to update.  Other targets are updated as well if they appear as
5534 dependencies of goals, or dependencies of dependencies of goals, etc.
5536 By default, the goal is the first target in the makefile (not counting
5537 targets that start with a period).  Therefore, makefiles are usually
5538 written so that the first target is for compiling the entire program or
5539 programs they describe.
5541 You can specify a different goal or goals with arguments to @code{make}.
5542 Use the name of the goal as an argument.  If you specify several goals,
5543 @code{make} processes each of them in turn, in the order you name them.
5545 Any target in the makefile may be specified as a goal (unless it
5546 starts with @samp{-} or contains an @samp{=}, in which case it will be
5547 parsed as a switch or variable definition, respectively).  Even
5548 targets not in the makefile may be specified, if @code{make} can find
5549 implicit rules that say how to make them.
5551 One use of specifying a goal is if you want to compile only a part of
5552 the program, or only one of several programs.  Specify as a goal each
5553 file that you wish to remake.  For example, consider a directory containing
5554 several programs, with a makefile that starts like this:
5556 @example
5557 .PHONY: all
5558 all: size nm ld ar as
5559 @end example
5561 If you are working on the program @code{size}, you might want to say
5562 @w{@samp{make size}} so that only the files of that program are recompiled.
5564 Another use of specifying a goal is to make files that are not normally
5565 made.  For example, there may be a file of debugging output, or a
5566 version of the program that is compiled specially for testing, which has
5567 a rule in the makefile but is not a dependency of the default goal.
5569 Another use of specifying a goal is to run the commands associated with
5570 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
5571 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
5572 a phony target named @file{clean} which deletes everything except source
5573 files.  Naturally, this is done only if you request it explicitly with
5574 @w{@samp{make clean}}.  Here is a list of typical phony and empty target
5575 names:@refill
5577 @table @file
5578 @item all
5579 @cindex @code{all} @r{(standard target)}
5580 Make all the top-level targets the makefile knows about.
5582 @item clean
5583 @cindex @code{clean} @r{(standard target)}
5584 Delete all files that are normally created by running @code{make}.
5586 @item mostlyclean
5587 @cindex @code{mostlyclean} @r{(standard target)}
5588 Like @samp{clean}, but may refrain from deleting a few files that people
5589 normally don't want to recompile.  For example, the @samp{mostlyclean}
5590 target for GCC does not delete @file{libgcc.a}, because recompiling it
5591 is rarely necessary and takes a lot of time.
5593 @item distclean
5594 @cindex @code{distclean} @r{(standard target)}
5595 @itemx realclean
5596 @cindex @code{realclean} @r{(standard target)}
5597 @itemx clobber
5598 @cindex @code{clobber} @r{(standard target)}
5599 Any of these three might be defined to delete everything that would
5600 not be part of a standard distribution.  For example, this would
5601 delete configuration files or links that you would normally create as
5602 preparation for compilation, even if the makefile itself cannot create
5603 these files.
5605 @item install
5606 @cindex @code{install} @r{(standard target)}
5607 Copy the executable file into a directory that users typically search
5608 for commands; copy any auxiliary files that the executable uses into
5609 the directories where it will look for them.
5611 @item print
5612 @cindex @code{print} @r{(standard target)}
5613 Print listings of the source files that have changed.
5615 @item tar
5616 @cindex @code{tar} @r{(standard target)}
5617 Create a tar file of the source files.
5619 @item shar
5620 @cindex @code{shar} @r{(standard target)}
5621 Create a shell archive (shar file) of the source files.
5623 @item dist
5624 @cindex @code{dist} @r{(standard target)}
5625 Create a distribution file of the source files.  This might
5626 be a tar file, or a shar file, or a compressed version of one of the
5627 above, or even more than one of the above.
5629 @item TAGS
5630 @cindex @code{TAGS} @r{(standard target)}
5631 Update a tags table for this program.
5633 @item check
5634 @cindex @code{check} @r{(standard target)}
5635 @itemx test
5636 @cindex @code{test} @r{(standard target)}
5637 Perform self tests on the program this makefile builds.
5638 @end table
5640 @node Instead of Execution, Avoiding Compilation, Goals, Running
5641 @section Instead of Executing the Commands
5642 @cindex execution, instead of
5643 @cindex commands, instead of executing
5645 The makefile tells @code{make} how to tell whether a target is up to date,
5646 and how to update each target.  But updating the targets is not always
5647 what you want.  Certain options specify other activities for @code{make}.
5649 @comment Extra blank lines make it print better.
5650 @table @samp
5651 @item -n
5652 @itemx --just-print
5653 @itemx --dry-run
5654 @itemx --recon
5655 @cindex @code{--just-print}
5656 @cindex @code{--dry-run}
5657 @cindex @code{--recon}
5658 @cindex @code{-n}
5660 ``No-op''.  The activity is to print what commands would be used to make
5661 the targets up to date, but not actually execute them.
5663 @item -t
5664 @itemx --touch
5665 @cindex @code{--touch}
5666 @cindex touching files
5667 @cindex target, touching
5668 @cindex @code{-t}
5670 ``Touch''.  The activity is to mark the targets as up to date without
5671 actually changing them.  In other words, @code{make} pretends to compile
5672 the targets but does not really change their contents.
5674 @item -q
5675 @itemx --question
5676 @cindex @code{--question}
5677 @cindex @code{-q}
5678 @cindex question mode
5680 ``Question''.  The activity is to find out silently whether the targets
5681 are up to date already; but execute no commands in either case.  In other
5682 words, neither compilation nor output will occur.
5684 @item -W @var{file}
5685 @itemx --what-if=@var{file}
5686 @itemx --assume-new=@var{file}
5687 @itemx --new-file=@var{file}
5688 @cindex @code{--what-if}
5689 @cindex @code{-W}
5690 @cindex @code{--assume-new}
5691 @cindex @code{--new-file}
5692 @cindex what if
5693 @cindex files, assuming new
5695 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
5696 files' modification times are recorded by @code{make} as being the present
5697 time, although the actual modification times remain the same.  
5698 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
5699 to see what would happen if you were to modify specific files.@refill
5700 @end table
5702 With the @samp{-n} flag, @code{make} prints the commands that it would
5703 normally execute but does not execute them.
5705 With the @samp{-t} flag, @code{make} ignores the commands in the rules
5706 and uses (in effect) the command @code{touch} for each target that needs to
5707 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
5708 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
5709 the program @code{touch}.  It does the work directly.
5711 With the @samp{-q} flag, @code{make} prints nothing and executes no
5712 commands, but the exit status code it returns is zero if and only if the
5713 targets to be considered are already up to date.
5715 It is an error to use more than one of these three flags in the same
5716 invocation of @code{make}.
5718 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect command
5719 lines that begin with @samp{+} characters or contain the strings
5720 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
5721 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
5722 is run regardless of these options.  Other lines in the same rule are
5723 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
5724 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
5726 The @samp{-W} flag provides two features:
5728 @itemize @bullet
5729 @item
5730 If you also use the @samp{-n} or @samp{-q} flag, you can see what
5731 @code{make} would do if you were to modify some files.
5733 @item
5734 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
5735 executing commands, the @samp{-W} flag can direct @code{make} to act
5736 as if some files had been modified, without actually modifying the
5737 files.@refill
5738 @end itemize
5740 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
5741 information about @code{make} or about the makefiles in use
5742 (@pxref{Options Summary, ,Summary of Options}).@refill
5744 @node Avoiding Compilation, Overriding, Instead of Execution, Running
5745 @section Avoiding Recompilation of Some Files
5746 @cindex @code{-o}
5747 @cindex @code{--old-file}
5748 @cindex @code{--assume-old}
5749 @cindex files, assuming old
5750 @cindex files, avoiding recompilation of
5751 @cindex recompilation, avoiding
5753 Sometimes you may have changed a source file but you do not want to
5754 recompile all the files that depend on it.  For example, suppose you add a
5755 macro or a declaration to a header file that many other files depend on.
5756 Being conservative, @code{make} assumes that any change in the header file
5757 requires recompilation of all dependent files, but you know that they do not
5758 need to be recompiled and you would rather not waste the time waiting for
5759 them to compile.
5761 If you anticipate the problem before changing the header file, you can
5762 use the @samp{-t} flag.  This flag tells @code{make} not to run the
5763 commands in the rules, but rather to mark the target up to date by
5764 changing its last-modification date.  You would follow this procedure:
5766 @enumerate
5767 @item
5768 Use the command @samp{make} to recompile the source files that really
5769 need recompilation.
5771 @item
5772 Make the changes in the header files.
5774 @item
5775 Use the command @samp{make -t} to mark all the object files as
5776 up to date.  The next time you run @code{make}, the changes in the
5777 header files will not cause any recompilation.
5778 @end enumerate
5780 If you have already changed the header file at a time when some files
5781 do need recompilation, it is too late to do this.  Instead, you can
5782 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
5783 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
5784 that the file itself will not be remade, and nothing else will be
5785 remade on its account.  Follow this procedure:
5787 @enumerate
5788 @item
5789 Recompile the source files that need compilation for reasons independent
5790 of the particular header file, with @samp{make -o @var{headerfile}}.
5791 If several header files are involved, use a separate @samp{-o} option
5792 for each header file.
5794 @item
5795 Touch all the object files with @samp{make -t}.
5796 @end enumerate
5798 @node Overriding, Testing, Avoiding Compilation, Running
5799 @section Overriding Variables
5800 @cindex overriding variables with arguments
5801 @cindex variables, overriding with arguments
5802 @cindex command line variables
5803 @cindex variables, command line
5805 An argument that contains @samp{=} specifies the value of a variable:
5806 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
5807 If you specify a value in this way, all ordinary assignments of the same
5808 variable in the makefile are ignored; we say they have been
5809 @dfn{overridden} by the command line argument.
5811 The most common way to use this facility is to pass extra flags to
5812 compilers.  For example, in a properly written makefile, the variable
5813 @code{CFLAGS} is included in each command that runs the C compiler, so a
5814 file @file{foo.c} would be compiled something like this:
5816 @example
5817 cc -c $(CFLAGS) foo.c
5818 @end example
5820 Thus, whatever value you set for @code{CFLAGS} affects each compilation
5821 that occurs.  The makefile probably specifies the usual value for
5822 @code{CFLAGS}, like this:
5824 @example
5825 CFLAGS=-g
5826 @end example
5828 Each time you run @code{make}, you can override this value if you
5829 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
5830 compilation will be done with @samp{cc -c -g -O}.  (This illustrates
5831 how you can use quoting in the shell to enclose spaces and other
5832 special characters in the value of a variable when you override it.)
5834 The variable @code{CFLAGS} is only one of many standard variables that
5835 exist just so that you can change them this way.  @xref{Implicit
5836 Variables, , Variables Used by Implicit Rules}, for a complete list.
5838 You can also program the makefile to look at additional variables of your
5839 own, giving the user the ability to control other aspects of how the
5840 makefile works by changing the variables.
5842 When you override a variable with a command argument, you can define either
5843 a recursively-expanded variable or a simply-expanded variable.  The
5844 examples shown above make a recursively-expanded variable; to make a
5845 simply-expanded variable, write @samp{:=} instead of @samp{=}.  But, unless
5846 you want to include a variable reference or function call in the
5847 @emph{value} that you specify, it makes no difference which kind of
5848 variable you create.
5850 There is one way that the makefile can change a variable that you have
5851 overridden.  This is to use the @code{override} directive, which is a line
5852 that looks like this: @samp{override @var{variable} = @var{value}}
5853 (@pxref{Override Directive, ,The @code{override} Directive}).
5855 @node Testing, Options Summary, Overriding, Running
5856 @section Testing the Compilation of a Program
5857 @cindex testing compilation
5858 @cindex compilation, testing
5860 Normally, when an error happens in executing a shell command, @code{make}
5861 gives up immediately, returning a nonzero status.  No further commands are
5862 executed for any target.  The error implies that the goal cannot be
5863 correctly remade, and @code{make} reports this as soon as it knows.
5865 When you are compiling a program that you have just changed, this is not
5866 what you want.  Instead, you would rather that @code{make} try compiling
5867 every file that can be tried, to show you as many compilation errors
5868 as possible.
5870 @cindex @code{-k}
5871 @cindex @code{--keep-going}
5872 On these occasions, you should use the @samp{-k} or
5873 @samp{--keep-going} flag.  This tells @code{make} to continue to
5874 consider the other dependencies of the pending targets, remaking them
5875 if necessary, before it gives up and returns nonzero status.  For
5876 example, after an error in compiling one object file, @samp{make -k}
5877 will continue compiling other object files even though it already
5878 knows that linking them will be impossible.  In addition to continuing
5879 after failed shell commands, @samp{make -k} will continue as much as
5880 possible after discovering that it does not know how to make a target
5881 or dependency file.  This will always cause an error message, but
5882 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
5883 ,Summary of Options}).@refill
5885 The usual behavior of @code{make} assumes that your purpose is to get the
5886 goals up to date; once @code{make} learns that this is impossible, it might
5887 as well report the failure immediately.  The @samp{-k} flag says that the
5888 real purpose is to test as much as possible of the changes made in the
5889 program, perhaps to find several independent problems so that you can
5890 correct them all before the next attempt to compile.  This is why Emacs'
5891 @kbd{M-x compile} command passes the @samp{-k} flag by default.
5893 @node Options Summary,  , Testing, Running
5894 @section Summary of Options
5895 @cindex options
5896 @cindex flags
5897 @cindex switches
5899 Here is a table of all the options @code{make} understands:
5901 @table @samp
5902 @item -b
5903 @cindex @code{-b}
5904 @itemx -m
5905 @cindex @code{-m}
5906 These options are ignored for compatibility with other versions of @code{make}.
5908 @item -C @var{dir}
5909 @cindex @code{-C}
5910 @itemx --directory=@var{dir}
5911 @cindex @code{--directory}
5912 Change to directory @var{dir} before reading the makefiles.  If multiple
5913 @samp{-C} options are specified, each is interpreted relative to the
5914 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
5915 This is typically used with recursive invocations of @code{make}
5916 (@pxref{Recursion, ,Recursive Use of @code{make}}).
5918 @item -d
5919 @cindex @code{-d}
5920 @itemx --debug
5921 @cindex @code{--debug}
5922 @c Extra blank line here makes the table look better.
5924 Print debugging information in addition to normal processing.  The
5925 debugging information says which files are being considered for
5926 remaking, which file-times are being compared and with what results,
5927 which files actually need to be remade, which implicit rules are
5928 considered and which are applied---everything interesting about how
5929 @code{make} decides what to do.
5931 @item -e
5932 @cindex @code{-e}
5933 @itemx --environment-overrides
5934 @cindex @code{--environment-overrides}
5935 Give variables taken from the environment precedence
5936 over variables from makefiles.
5937 @xref{Environment, ,Variables from the Environment}.
5939 @item -f @var{file}
5940 @cindex @code{-f}
5941 @itemx --file=@var{file}
5942 @cindex @code{--file}
5943 @itemx --makefile=@var{file}
5944 @cindex @code{--makefile}
5945 Read the file named @var{file} as a makefile.
5946 @xref{Makefiles, ,Writing Makefiles}.
5948 @item -h
5949 @cindex @code{-h}
5950 @itemx --help
5951 @cindex @code{--help}
5952 @c Extra blank line here makes the table look better.
5954 Remind you of the options that @code{make} understands and then exit.
5956 @item -i
5957 @cindex @code{-i}
5958 @itemx --ignore-errors
5959 @cindex @code{--ignore-errors}
5960 Ignore all errors in commands executed to remake files.
5961 @xref{Errors, ,Errors in Commands}.
5963 @item -I @var{dir}
5964 @cindex @code{-I}
5965 @itemx --include-dir=@var{dir}
5966 @cindex @code{--include-dir}
5967 Specifies a directory @var{dir} to search for included makefiles.
5968 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
5969 options are used to specify several directories, the directories are
5970 searched in the order specified.
5972 @item -j [@var{jobs}]
5973 @cindex @code{-j}
5974 @itemx --jobs=[@var{jobs}]
5975 @cindex @code{--jobs}
5976 Specifies the number of jobs (commands) to run simultaneously.  With no
5977 argument, @code{make} runs as many jobs simultaneously as possible.  If
5978 there is more than one @samp{-j} option, the last one is effective.
5979 @xref{Parallel, ,Parallel Execution},
5980 for more information on how commands are run.
5982 @item -k
5983 @cindex @code{-k}
5984 @itemx --keep-going
5985 @cindex @code{--keep-going}
5986 Continue as much as possible after an error.  While the target that
5987 failed, and those that depend on it, cannot be remade, the other
5988 dependencies of these targets can be processed all the same.
5989 @xref{Testing, ,Testing the Compilation of a Program}.
5991 @item -l [@var{load}]
5992 @cindex @code{-l}
5993 @itemx --load-average[=@var{load}]
5994 @cindex @code{--load-average}
5995 @itemx --max-load[=@var{load}]
5996 @cindex @code{--max-load}
5997 Specifies that no new jobs (commands) should be started if there are
5998 other jobs running and the load average is at least @var{load} (a
5999 floating-point number).  With no argument, removes a previous load
6000 limit.  @xref{Parallel, ,Parallel Execution}.
6002 @item -n
6003 @cindex @code{-n}
6004 @itemx --just-print
6005 @cindex @code{--just-print}
6006 @itemx --dry-run
6007 @cindex @code{--dry-run}
6008 @itemx --recon
6009 @cindex @code{--recon}
6010 @c Extra blank line here makes the table look better.
6012 Print the commands that would be executed, but do not execute them.
6013 @xref{Instead of Execution, ,Instead of Executing the Commands}.
6015 @item -o @var{file}
6016 @cindex @code{-o}
6017 @itemx --old-file=@var{file}
6018 @cindex @code{--old-file}
6019 @itemx --assume-old=@var{file}
6020 @cindex @code{--assume-old}
6021 Do not remake the file @var{file} even if it is older than its
6022 dependencies, and do not remake anything on account of changes in
6023 @var{file}.  Essentially the file is treated as very old and its rules
6024 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
6025 Some Files}.@refill
6027 @item -p
6028 @cindex @code{-p}
6029 @itemx --print-data-base
6030 @cindex @code{--print-data-base}
6031 Print the data base (rules and variable values) that results from
6032 reading the makefiles; then execute as usual or as otherwise
6033 specified.  This also prints the version information given by
6034 the @samp{-v} switch (see below).  To print the data base without
6035 trying to remake any files, use @w{@samp{make -p -f /dev/null}}.
6037 @item -q
6038 @cindex @code{-q}
6039 @itemx --question
6040 @cindex @code{--question}
6041 ``Question mode''.  Do not run any commands, or print anything; just
6042 return an exit status that is zero if the specified targets are already
6043 up to date, nonzero otherwise.  @xref{Instead of Execution, ,Instead of
6044 Executing the Commands}.@refill
6046 @item -r
6047 @cindex @code{-r}
6048 @itemx --no-builtin-rules
6049 @cindex @code{--no-builtin-rules}
6050 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
6051 ,Using Implicit Rules}).  You can still define your own by writing
6052 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
6053 Rules}).  The @samp{-r} option also clears out the default list of
6054 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
6055 Rules}).  But you can still define your own suffixes with a rule for
6056 @code{.SUFFIXES}, and then define your own suffix rules.
6058 @item -s
6059 @cindex @code{-s}
6060 @itemx --silent
6061 @cindex @code{--silent}
6062 @itemx --quiet
6063 @cindex @code{--quiet}
6064 @c Extra blank line here makes the table look better.
6066 Silent operation; do not print the commands as they are executed.
6067 @xref{Echoing, ,Command Echoing}.
6069 @item -S
6070 @cindex @code{-S}
6071 @itemx --no-keep-going
6072 @cindex @code{--no-keep-going}
6073 @itemx --stop
6074 @cindex @code{--stop}
6075 @c Extra blank line here makes the table look better.
6077 Cancel the effect of the @samp{-k} option.  This is never necessary
6078 except in a recursive @code{make} where @samp{-k} might be inherited
6079 from the top-level @code{make} via @code{MAKEFLAGS} (@pxref{Recursion, ,Recursive Use of @code{make}})
6080 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.@refill
6082 @item -t
6083 @cindex @code{-t}
6084 @itemx --touch
6085 @cindex @code{--touch}
6086 @c Extra blank line here makes the table look better.
6088 Touch files (mark them up to date without really changing them)
6089 instead of running their commands.  This is used to pretend that the
6090 commands were done, in order to fool future invocations of
6091 @code{make}.  @xref{Instead of Execution, ,Instead of Executing the Commands}.
6093 @item -v
6094 @cindex @code{-v}
6095 @itemx --version
6096 @cindex @code{--version}
6097 Print the version of the @code{make} program plus a copyright, a list
6098 of authors, and a notice that there is no warranty; then exit.
6100 @item -w
6101 @cindex @code{-w}
6102 @itemx --print-directory
6103 @cindex @code{--print-directory}
6104 Print a message containing the working directory both before and after
6105 executing the makefile.  This may be useful for tracking down errors
6106 from complicated nests of recursive @code{make} commands.
6107 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
6108 rarely need to specify this option since @samp{make} does it for you;
6109 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
6111 @itemx --no-print-directory
6112 @cindex @code{--no-print-directory}
6113 Disable printing of the working directory under @code{-w}.
6114 This option is useful when @code{-w} is turned on automatically,
6115 but you do not want to see the extra messages.
6116 @xref{-w Option, ,The @samp{--print-directory} Option}.
6118 @item -W @var{file}
6119 @cindex @code{-W}
6120 @itemx --what-if=@var{file}
6121 @cindex @code{--what-if}
6122 @itemx --new-file=@var{file}
6123 @cindex @code{--new-file}
6124 @itemx --assume-new=@var{file}
6125 @cindex @code{--assume-new}
6126 Pretend that the target @var{file} has just been modified.  When used
6127 with the @samp{-n} flag, this shows you what would happen if you were
6128 to modify that file.  Without @samp{-n}, it is almost the same as
6129 running a @code{touch} command on the given file before running
6130 @code{make}, except that the modification time is changed only in the
6131 imagination of @code{make}.
6132 @xref{Instead of Execution, ,Instead of Executing the Commands}.
6134 @item --warn-undefined-variables
6135 @cindex @code{--warn-undefined-variables}
6136 @cindex variables, warning for undefined
6137 @cindex undefined variables, warning message
6138 Issue a warning message whenever @code{make} sees a reference to an
6139 undefined variable.  This can be helpful when you are trying to debug
6140 makefiles which use variables in complex ways.
6141 @end table
6143 @node Implicit Rules, Archives, Running, Top
6144 @chapter Using Implicit Rules
6145 @cindex implicit rule
6146 @cindex rule, implicit
6148 Certain standard ways of remaking target files are used very often.  For
6149 example, one customary way to make an object file is from a C source file
6150 using the C compiler, @code{cc}.
6152 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
6153 that you do not have to specify them in detail when you want to use
6154 them.  For example, there is an implicit rule for C compilation.  File
6155 names determine which implicit rules are run.  For example, C
6156 compilation typically takes a @file{.c} file and makes a @file{.o} file.
6157 So @code{make} applies the implicit rule for C compilation when it sees
6158 this combination of file name endings.@refill
6160 A chain of implicit rules can apply in sequence; for example, @code{make}
6161 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
6162 @iftex
6163 @xref{Chained Rules, ,Chains of Implicit Rules}.
6164 @end iftex
6166 The built-in implicit rules use several variables in their commands so
6167 that, by changing the values of the variables, you can change the way the
6168 implicit rule works.  For example, the variable @code{CFLAGS} controls the
6169 flags given to the C compiler by the implicit rule for C compilation.
6170 @iftex
6171 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
6172 @end iftex
6174 You can define your own implicit rules by writing @dfn{pattern rules}.
6175 @iftex
6176 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
6177 @end iftex
6179 @dfn{Suffix rules} are a more limited way to define implicit rules.
6180 Pattern rules are more general and clearer, but suffix rules are
6181 retained for compatibility.
6182 @iftex
6183 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
6184 @end iftex
6186 @menu
6187 * Using Implicit::              How to use an existing implicit rule
6188                                   to get the commands for updating a file.
6189 * Catalogue of Rules::          A list of built-in implicit rules.
6190 * Implicit Variables::          How to change what predefined rules do.
6191 * Chained Rules::               How to use a chain of implicit rules.
6192 * Pattern Rules::               How to define new implicit rules.
6193 * Last Resort::                 How to defining commands for rules 
6194                                   which cannot find any.
6195 * Suffix Rules::                The old-fashioned style of implicit rule.
6196 * Search Algorithm::            The precise algorithm for applying 
6197                                   implicit rules.
6198 @end menu
6200 @node Using Implicit, Catalogue of Rules,  , Implicit Rules
6201 @section Using Implicit Rules
6202 @cindex implicit rule, how to use
6203 @cindex rule, implicit, how to use
6205 To allow @code{make} to find a customary method for updating a target file,
6206 all you have to do is refrain from specifying commands yourself.  Either
6207 write a rule with no command lines, or don't write a rule at all.  Then
6208 @code{make} will figure out which implicit rule to use based on which
6209 kind of source file exists or can be made.
6211 For example, suppose the makefile looks like this:
6213 @example
6214 foo : foo.o bar.o
6215         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
6216 @end example
6218 @noindent
6219 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
6220 will automatically look for an implicit rule that tells how to update it.
6221 This happens whether or not the file @file{foo.o} currently exists.
6223 If an implicit rule is found, it can supply both commands and one or
6224 more dependencies (the source files).  You would want to write a rule
6225 for @file{foo.o} with no command lines if you need to specify additional
6226 dependencies, such as header files, that the implicit rule cannot
6227 supply.
6229 Each implicit rule has a target pattern and dependency patterns.  There may
6230 be many implicit rules with the same target pattern.  For example, numerous
6231 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
6232 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
6233 that actually applies is the one whose dependencies exist or can be made.
6234 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
6235 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
6236 compiler; and so on.
6238 Of course, when you write the makefile, you know which implicit rule you
6239 want @code{make} to use, and you know it will choose that one because you
6240 know which possible dependency files are supposed to exist.
6241 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
6242 for a catalogue of all the predefined implicit rules.
6244 Above, we said an implicit rule applies if the required dependencies ``exist
6245 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
6246 the makefile as a target or a dependency, or if an implicit rule can be
6247 recursively found for how to make it.  When an implicit dependency is the
6248 result of another implicit rule, we say that @dfn{chaining} is occurring.
6249 @xref{Chained Rules, ,Chains of Implicit Rules}.
6251 In general, @code{make} searches for an implicit rule for each target, and
6252 for each double-colon rule, that has no commands.  A file that is mentioned
6253 only as a dependency is considered a target whose rule specifies nothing,
6254 so implicit rule search happens for it.  @xref{Search Algorithm, ,Implicit Rule Search Algorithm}, for the
6255 details of how the search is done.
6257 Note that explicit dependencies do not influence implicit rule search.
6258 For example, consider this explicit rule:
6260 @example
6261 foo.o: foo.p
6262 @end example
6264 @noindent
6265 The dependency on @file{foo.p} does not necessarily mean that
6266 @code{make} will remake @file{foo.o} according to the implicit rule to
6267 make an object file, a @file{.o} file, from a Pascal source file, a
6268 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
6269 rule to make an object file from a C source file is used instead,
6270 because it appears before the Pascal rule in the list of predefined
6271 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
6272 Rules}).
6274 If you do not want an implicit rule to be used for a target that has no
6275 commands, you can give that target empty commands by writing a semicolon
6276 (@pxref{Empty Commands, ,Defining Empty Commands}).
6278 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
6279 @section Catalogue of Implicit Rules
6280 @cindex implicit rule, predefined
6281 @cindex rule, implicit, predefined
6283 Here is a catalogue of predefined implicit rules which are always
6284 available unless the makefile explicitly overrides or cancels them.
6285 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
6286 canceling or overriding an implicit rule.  The @samp{-r} or
6287 @samp{--no-builtin-rules} option cancels all predefined rules.
6289 Not all of these rules will always be defined, even when the @samp{-r}
6290 option is not given.  Many of the predefined implicit rules are
6291 implemented in @code{make} as suffix rules, so which ones will be
6292 defined depends on the @dfn{suffix list} (the list of dependencies of
6293 the special target @code{.SUFFIXES}).  The default suffix list is:
6294 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
6295 @code{.C}, @code{.p}, @code{.f}, @code{.F}, @code{.r}, @code{.y},
6296 @code{.l}, @code{.s}, @code{.S}, @code{.mod}, @code{.sym}, @code{.def},
6297 @code{.h}, @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo},
6298 @code{.texi}, @code{.txinfo}, @code{.w}, @code{.ch} @code{.web},
6299 @code{.sh}, @code{.elc}, @code{.el}.  All of the implicit rules
6300 described below whose dependencies have one of these suffixes are
6301 actually suffix rules.  If you modify the suffix list, the only
6302 predefined suffix rules in effect will be those named by one or two of
6303 the suffixes that are on the list you specify; rules whose suffixes fail
6304 to be on the list are disabled.  @xref{Suffix Rules, ,Old-Fashioned
6305 Suffix Rules}, for full details on suffix rules.
6307 @table @asis
6308 @item Compiling C programs
6309 @cindex C, rule to compile
6310 @pindex cc
6311 @pindex gcc
6312 @pindex .o
6313 @pindex .c
6314 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
6315 a command of the form @samp{$(CC) -c $(CPPFLAGS) $(CFLAGS)}.@refill
6317 @item Compiling C++ programs
6318 @cindex C++, rule to compile
6319 @pindex g++
6320 @pindex .C
6321 @pindex .cc
6322 @file{@var{n}.o} is made automatically from @file{@var{n}.cc} or
6323 @file{@var{n}.C} with a command of the form @samp{$(CXX) -c $(CPPFLAGS)
6324 $(CXXFLAGS)}.  We encourage you to use the suffix @samp{.cc} for C++
6325 source files instead of @samp{.C}.@refill
6327 @item Compiling Pascal programs
6328 @cindex Pascal, rule to compile
6329 @pindex pc
6330 @pindex .p
6331 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
6332 with the command @samp{$(PC) -c $(PFLAGS)}.@refill
6334 @item Compiling Fortran and Ratfor programs
6335 @cindex Fortran, rule to compile
6336 @cindex Ratfor, rule to compile
6337 @pindex f77
6338 @pindex .f
6339 @pindex .r
6340 @pindex .F
6341 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
6342 @file{@var{n}.F} or @file{@var{n}.f} by running the
6343 Fortran compiler.  The precise command used is as follows:@refill
6345 @table @samp
6346 @item .f
6347 @samp{$(FC) -c $(FFLAGS)}.
6348 @item .F
6349 @samp{$(FC) -c $(FFLAGS) $(CPPFLAGS)}.
6350 @item .r
6351 @samp{$(FC) -c $(FFLAGS) $(RFLAGS)}.
6352 @end table
6354 @item Preprocessing Fortran and Ratfor programs
6355 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
6356 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
6357 Ratfor or preprocessable Fortran program into a strict Fortran
6358 program.  The precise command used is as follows:@refill
6360 @table @samp
6361 @item .F
6362 @samp{$(FC) -F $(CPPFLAGS) $(FFLAGS)}.
6363 @item .r
6364 @samp{$(FC) -F $(FFLAGS) $(RFLAGS)}.
6365 @end table
6367 @item Compiling Modula-2 programs
6368 @cindex Modula-2, rule to compile
6369 @pindex m2c
6370 @pindex .sym
6371 @pindex .def
6372 @pindex .mod
6373 @file{@var{n}.sym} is made from @file{@var{n}.def} with a command
6374 of the form @samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}.  @file{@var{n}.o}
6375 is made from @file{@var{n}.mod}; the form is:
6376 @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.@refill
6378 @need 1200
6379 @item Assembling and preprocessing assembler programs
6380 @cindex assembly, rule to compile
6381 @pindex as
6382 @pindex .s
6383 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
6384 running the assembler, @code{as}.  The precise command is
6385 @samp{$(AS) $(ASFLAGS)}.@refill
6387 @pindex .S
6388 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
6389 running the C preprocessor, @code{cpp}.  The precise command is
6390 @w{@samp{$(CPP) $(CPPFLAGS)}}.
6392 @item Linking a single object file
6393 @cindex linking, predefined rule for
6394 @pindex ld
6395 @pindex .o
6396 @file{@var{n}} is made automatically from @file{@var{n}.o} by running
6397 the linker (usually called @code{ld}) via the C compiler.  The precise
6398 command used is @w{@samp{$(CC) $(LDFLAGS) @var{n}.o $(LOADLIBES)}}.
6400 This rule does the right thing for a simple program with only one
6401 source file.  It will also do the right thing if there are multiple
6402 object files (presumably coming from various other source files), one
6403 of which has a name matching that of the executable file.  Thus,
6405 @example
6406 x: y.o z.o
6407 @end example
6409 @noindent
6410 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
6412 @example
6413 @group
6414 cc -c x.c -o x.o
6415 cc -c y.c -o y.o
6416 cc -c z.c -o z.o
6417 cc x.o y.o z.o -o x
6418 rm -f x.o
6419 rm -f y.o
6420 rm -f z.o
6421 @end group
6422 @end example
6424 @noindent
6425 In more complicated cases, such as when there is no object file whose
6426 name derives from the executable file name, you must write an explicit
6427 command for linking.
6429 Each kind of file automatically made into @samp{.o} object files will
6430 be automatically linked by using the compiler (@samp{$(CC)},
6431 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
6432 assemble @samp{.s} files) without the @samp{-c} option.  This could be
6433 done by using the @samp{.o} object files as intermediates, but it is
6434 faster to do the compiling and linking in one step, so that's how it's
6435 done.@refill
6437 @item Yacc for C programs
6438 @pindex yacc
6439 @cindex Yacc, rule to run
6440 @pindex .y
6441 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
6442 running Yacc with the command @samp{$(YACC) $(YFLAGS)}.
6444 @item Lex for C programs
6445 @pindex lex
6446 @cindex Lex, rule to run
6447 @pindex .l
6448 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
6449 by running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
6451 @item Lex for Ratfor programs
6452 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
6453 by running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
6455 The convention of using the same suffix @samp{.l} for all Lex files
6456 regardless of whether they produce C code or Ratfor code makes it
6457 impossible for @code{make} to determine automatically which of the two
6458 languages you are using in any particular case.  If @code{make} is
6459 called upon to remake an object file from a @samp{.l} file, it must
6460 guess which compiler to use.  It will guess the C compiler, because
6461 that is more common.  If you are using Ratfor, make sure @code{make}
6462 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
6463 are using Ratfor exclusively, with no C files, remove @samp{.c} from
6464 the list of implicit rule suffixes with:@refill
6466 @example
6467 @group
6468 .SUFFIXES:
6469 .SUFFIXES: .o .r .f .l @dots{}
6470 @end group
6471 @end example
6473 @item Making Lint Libraries from C, Yacc, or Lex programs
6474 @pindex lint
6475 @cindex @code{lint}, rule to run
6476 @pindex .ln
6477 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
6478 The precise command is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.  
6479 The same command is used on the C code produced from 
6480 @file{@var{n}.y} or @file{@var{n}.l}.@refill
6482 @item @TeX{} and Web
6483 @cindex @TeX{}, rule to run
6484 @cindex Web, rule to run
6485 @pindex tex
6486 @pindex cweave
6487 @pindex weave
6488 @pindex tangle
6489 @pindex ctangle
6490 @pindex .dvi
6491 @pindex .tex
6492 @pindex .web
6493 @pindex .w
6494 @pindex .ch
6495 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the command
6496 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
6497 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
6498 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
6499 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
6500 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
6501 or can be made) with @samp{$(CTANGLE)}.@refill
6503 @item Texinfo and Info
6504 @cindex Texinfo, rule to format
6505 @cindex Info, rule to format
6506 @pindex texi2dvi
6507 @pindex makeinfo
6508 @pindex .texinfo
6509 @pindex .info
6510 @pindex .texi
6511 @pindex .txinfo
6512 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo}, @file{@var{n}.texi},
6513 or @file{@var{n}.txinfo}, with the @samp{$(TEXI2DVI)} command.
6514 @file{@var{n}.info} is made from @file{@var{n}.texinfo}, @file{@var{n}.texi},
6515 or @file{@var{n}.txinfo}, with the @samp{$(MAKEINFO)} command.@refill
6517 @item RCS
6518 @cindex RCS, rule to extract from
6519 @pindex co
6520 @pindex ,v @r{(RCS file extension)}
6521 Any file @file{@var{n}} is extracted if necessary from an RCS file
6522 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
6523 command used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
6524 extracted from RCS if it already exists, even if the RCS file is
6525 newer.  The rules for RCS are terminal 
6526 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}), 
6527 so RCS files cannot be generated from another source; they must
6528 actually exist.@refill
6530 @item SCCS
6531 @cindex SCCS, rule to extract from
6532 @pindex get
6533 @pindex s. @r{(SCCS file prefix)}
6534 Any file @file{@var{n}} is extracted if necessary from an SCCS file
6535 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
6536 command used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
6537 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
6538 so SCCS files cannot be generated from another source; they must
6539 actually exist.@refill
6541 @pindex .sh
6542 For the benefit of SCCS, a file @file{@var{n}} is copied from
6543 @file{@var{n}.sh} and made executable (by everyone).  This is for
6544 shell scripts that are checked into SCCS.  Since RCS preserves the
6545 execution permission of a file, you do not need to use this feature
6546 with RCS.@refill
6548 We recommend that you avoid using of SCCS.  RCS is widely held to be
6549 superior, and is also free.  By choosing free software in place of
6550 comparable (or inferior) proprietary software, you support the free
6551 software movement.
6552 @end table
6554 Usually, you want to change only the variables listed in the table
6555 above, which are documented in the following section.
6557 However, the commands in built-in implicit rules actually use
6558 variables such as @code{COMPILE.c}, @code{LINK.p}, and
6559 @code{PREPROCESS.S}, whose values contain the commands listed above.
6561 @code{make} follows the convention that the rule to compile a
6562 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
6563 Similarly, the rule to produce an executable from a @file{.@var{x}}
6564 file uses @code{LINK.@var{x}}; and the rule to preprocess a
6565 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
6567 @vindex OUTPUT_OPTION
6568 Every rule that produces an object file uses the variable
6569 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
6570 contain @samp{-o $@@}, or to be empty, depending on a compile-time
6571 option.  You need the @samp{-o} option to ensure that the output goes
6572 into the right file when the source file is in a different directory,
6573 as when using @code{VPATH} (@pxref{Directory Search}).  However,
6574 compilers on some systems do not accept a @samp{-o} switch for object
6575 files.  If you use such a system, and use @code{VPATH}, some
6576 compilations will put their output in the wrong place.
6577 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
6578 the value @w{@samp{; mv $*.o $@@}}.
6580 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
6581 @section Variables Used by Implicit Rules
6582 @cindex flags for compilers
6584 The commands in built-in implicit rules make liberal use of certain
6585 predefined variables.  You can alter these variables in the makefile,
6586 with arguments to @code{make}, or in the environment to alter how the
6587 implicit rules work without redefining the rules themselves.
6589 For example, the command used to compile a C source file actually says
6590 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
6591 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
6592 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
6593 used for all C compilations performed by the implicit rule.  By redefining
6594 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
6595 each compilation.  @emph{All} implicit rules that do C compilation use
6596 @samp{$(CC)} to get the program name for the compiler and @emph{all}
6597 include @samp{$(CFLAGS)} among the arguments given to the compiler.@refill
6599 The variables used in implicit rules fall into two classes: those that are
6600 names of programs (like @code{CC}) and those that contain arguments for the
6601 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
6602 some command arguments, but it must start with an actual executable program
6603 name.)  If a variable value contains more than one argument, separate them
6604 with spaces.
6606 Here is a table of variables used as names of programs in built-in rules:
6608 @table @code
6609 @item AR
6610 @vindex AR
6611 Archive-maintaining program; default @samp{ar}.
6612 @pindex ar
6614 @item AS
6615 @vindex AS
6616 Program for doing assembly; default @samp{as}.
6617 @pindex as
6619 @item CC
6620 @vindex CC
6621 Program for compiling C programs; default @samp{cc}.
6622 @pindex cc
6624 @item CXX
6625 @vindex CXX
6626 Program for compiling C++ programs; default @samp{g++}.
6627 @pindex g++
6629 @item CO
6630 @vindex CO
6631 Program for extracting a file from RCS; default @samp{co}.
6632 @pindex co
6634 @item CPP
6635 @vindex CPP
6636 Program for running the C preprocessor, with results to standard output;
6637 default @samp{$(CC) -E}.
6639 @item FC
6640 @vindex FC
6641 Program for compiling or preprocessing Fortran and Ratfor programs;
6642 default @samp{f77}.
6643 @pindex f77
6645 @item GET
6646 @vindex GET
6647 Program for extracting a file from SCCS; default @samp{get}.
6648 @pindex get
6650 @item LEX
6651 @vindex LEX
6652 Program to use to turn Lex grammars into C programs or Ratfor programs;
6653 default @samp{lex}.
6654 @pindex lex
6656 @item PC
6657 @vindex PC
6658 Program for compiling Pascal programs; default @samp{pc}.
6659 @pindex pc
6661 @item YACC
6662 @vindex YACC
6663 Program to use to turn Yacc grammars into C programs; default @samp{yacc}.
6664 @pindex yacc
6666 @item YACCR
6667 @vindex YACCR
6668 Program to use to turn Yacc grammars into Ratfor
6669 programs; default @samp{yacc -r}.
6671 @item MAKEINFO
6672 @vindex MAKEINFO
6673 Program to convert a Texinfo source file into an Info file; default
6674 @samp{makeinfo}.
6675 @pindex makeinfo
6677 @item TEX
6678 @vindex TEX
6679 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
6680 default @samp{tex}.
6681 @pindex tex
6683 @item TEXI2DVI
6684 @vindex TEXI2DVI
6685 Program to make @TeX{} @sc{dvi} files from Texinfo source;
6686 default @samp{texi2dvi}.
6687 @pindex texi2dvi
6689 @item WEAVE
6690 @vindex WEAVE
6691 Program to translate Web into @TeX{}; default @samp{weave}.
6692 @pindex weave
6694 @item CWEAVE
6695 @vindex CWEAVE
6696 Program to translate C Web into @TeX{}; default @samp{cweave}.
6697 @pindex cweave
6699 @item TANGLE
6700 @vindex TANGLE
6701 Program to translate Web into Pascal; default @samp{tangle}.
6702 @pindex tangle
6704 @item CTANGLE
6705 @vindex CTANGLE
6706 Program to translate C Web into C; default @samp{ctangle}.
6707 @pindex ctangle
6709 @item RM
6710 @vindex RM
6711 Command to remove a file; default @samp{rm -f}.
6712 @pindex rm
6713 @end table
6715 Here is a table of variables whose values are additional arguments for the
6716 programs above.  The default values for all of these is the empty
6717 string, unless otherwise noted.
6719 @table @code
6720 @item ARFLAGS
6721 @vindex ARFLAGS
6722 Flags to give the archive-maintaining program; default @samp{rv}.
6724 @item ASFLAGS
6725 @vindex ASFLAGS
6726 Extra flags to give to the assembler (when explicitly
6727 invoked on a @samp{.s} or @samp{.S} file).
6729 @item CFLAGS
6730 @vindex CFLAGS
6731 Extra flags to give to the C compiler.
6733 @item CXXFLAGS
6734 @vindex CXXFLAGS
6735 Extra flags to give to the C++ compiler.
6737 @item COFLAGS
6738 @vindex COFLAGS
6739 Extra flags to give to the RCS @code{co} program.
6741 @item CPPFLAGS
6742 @vindex CPPFLAGS
6743 Extra flags to give to the C preprocessor and programs
6744 that use it (the C and Fortran compilers).
6746 @item FFLAGS
6747 @vindex FFLAGS
6748 Extra flags to give to the Fortran compiler.
6750 @item GFLAGS
6751 @vindex GFLAGS
6752 Extra flags to give to the SCCS @code{get} program.
6754 @item LDFLAGS
6755 @vindex LDFLAGS
6756 Extra flags to give to compilers when they are
6757 supposed to invoke the linker, @samp{ld}.
6759 @item LFLAGS
6760 @vindex LFLAGS
6761 Extra flags to give to Lex.
6763 @item PFLAGS
6764 @vindex PFLAGS
6765 Extra flags to give to the Pascal compiler.
6767 @item RFLAGS
6768 @vindex RFLAGS
6769 Extra flags to give to the Fortran compiler for Ratfor programs.
6771 @item YFLAGS
6772 @vindex YFLAGS
6773 Extra flags to give to Yacc.
6774 @end table
6776 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
6777 @section Chains of Implicit Rules
6779 @cindex chains of rules
6780 @cindex rule, implicit, chains of
6781 Sometimes a file can be made by a sequence of implicit rules.  For example,
6782 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
6783 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
6785 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
6786 special searching is required: @code{make} finds that the object file can
6787 be made by C compilation from @file{@var{n}.c}; later on, when considering
6788 how to make @file{@var{n}.c}, the rule for running Yacc is
6789 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
6790 updated.@refill
6792 @cindex intermediate files
6793 @cindex files, intermediate
6794 However, even if @file{@var{n}.c} does not exist and is not mentioned,
6795 @code{make} knows how to envision it as the missing link between
6796 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
6797 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
6798 intermediate file, it is entered in the data base as if it had been
6799 mentioned in the makefile, along with the implicit rule that says how to
6800 create it.@refill
6802 Intermediate files are remade using their rules just like all other
6803 files.  The difference is that the intermediate file is deleted when
6804 @code{make} is finished.  Therefore, the intermediate file which did not
6805 exist before @code{make} also does not exist after @code{make}.  The
6806 deletion is reported to you by printing a @samp{rm -f} command that
6807 shows what @code{make} is doing.  (You can list the target pattern of an
6808 implicit rule (such as @samp{%.o}) as a dependency of the special
6809 target @code{.PRECIOUS} to preserve intermediate files made by implicit
6810 rules whose target patterns match that file's name; 
6811 see @ref{Interrupts}.)@refill
6812 @cindex intermediate files, preserving
6813 @cindex preserving intermediate files
6814 @cindex preserving with @code{.PRECIOUS}
6815 @cindex @code{.PRECIOUS} intermediate files
6817 A chain can involve more than two implicit rules.  For example, it is
6818 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
6819 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
6820 intermediate files that are deleted at the end.@refill
6822 No single implicit rule can appear more than once in a chain.  This means
6823 that @code{make} will not even consider such a ridiculous thing as making
6824 @file{foo} from @file{foo.o.o} by running the linker twice.  This
6825 constraint has the added benefit of preventing any infinite loop in the
6826 search for an implicit rule chain.
6828 There are some special implicit rules to optimize certain cases that would
6829 otherwise be handled by rule chains.  For example, making @file{foo} from
6830 @file{foo.c} could be handled by compiling and linking with separate
6831 chained rules, using @file{foo.o} as an intermediate file.  But what
6832 actually happens is that a special rule for this case does the compilation
6833 and linking with a single @code{cc} command.  The optimized rule is used in
6834 preference to the step-by-step chain because it comes earlier in the
6835 ordering of rules.
6837 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
6838 @section Defining and Redefining Pattern Rules
6840 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
6841 rule looks like an ordinary rule, except that its target contains the
6842 character @samp{%} (exactly one of them).  The target is considered a
6843 pattern for matching file names; the @samp{%} can match any nonempty
6844 substring, while other characters match only themselves.  The dependencies
6845 likewise use @samp{%} to show how their names relate to the target name.
6847 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
6848 @file{@var{stem}.o} from another file @file{@var{stem}.c}.@refill
6850 Note that expansion using @samp{%} in pattern rules occurs
6851 @strong{after} any variable or function expansions, which take place
6852 when the makefile is read.  @xref{Using Variables, , How to Use
6853 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
6855 @menu
6856 * Pattern Intro::               An introduction to pattern rules.
6857 * Pattern Examples::            Examples of pattern rules.
6858 * Automatic::                   How to use automatic variables in the
6859                                   commands of implicit rules.
6860 * Pattern Match::               How patterns match.
6861 * Match-Anything Rules::        Precautions you should take prior to
6862                                   defining rules that can match any
6863                                   target file whatever.
6864 * Canceling Rules::             How to override or cancel built-in rules.
6865 @end menu
6867 @node Pattern Intro, Pattern Examples,  , Pattern Rules
6868 @subsection Introduction to Pattern Rules
6869 @cindex pattern rule
6870 @cindex rule, pattern
6872 A pattern rule contains the character @samp{%} (exactly one of them)
6873 in the target; otherwise, it looks exactly like an ordinary rule.  The
6874 target is a pattern for matching file names; the @samp{%} matches any
6875 nonempty substring, while other characters match only themselves.
6876 @cindex target pattern, implicit
6877 @cindex @code{%}, in pattern rules
6879 For example, @samp{%.c} as a pattern matches any file name that ends in
6880 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
6881 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
6882 (There must be at least one character to match the @samp{%}.)  The substring
6883 that the @samp{%} matches is called the @dfn{stem}.@refill
6885 @samp{%} in a dependency of a pattern rule stands for the same stem
6886 that was matched by the @samp{%} in the target.  In order for
6887 the pattern rule to apply, its target pattern must match the file name
6888 under consideration, and its dependency patterns must name files that
6889 exist or can be made.  These files become dependencies of the target.
6890 @cindex dependency pattern, implicit
6892 Thus, a rule of the form
6894 @example
6895 %.o : %.c ; @var{command}@dots{}
6896 @end example
6898 @noindent
6899 specifies how to make a file @file{@var{n}.o}, with another file
6900 @file{@var{n}.c} as its dependency, provided that @file{@var{n}.c}
6901 exists or can be made.
6903 There may also be dependencies that do not use @samp{%}; such a dependency
6904 attaches to every file made by this pattern rule.  These unvarying
6905 dependencies are useful occasionally.
6907 A pattern rule need not have any dependencies that contain @samp{%}, or
6908 in fact any dependencies at all.  Such a rule is effectively a general
6909 wildcard.  It provides a way to make any file that matches the target
6910 pattern.  @xref{Last Resort}.
6912 @c !!! The end of of this paragraph should be rewritten.  --bob
6913 Pattern rules may have more than one target.  Unlike normal rules, this
6914 does not act as many different rules with the same dependencies and
6915 commands.  If a pattern rule has multiple targets, @code{make} knows that
6916 the rule's commands are responsible for making all of the targets.  The
6917 commands are executed only once to make all the targets.  When searching
6918 for a pattern rule to match a target, the target patterns of a rule other
6919 than the one that matches the target in need of a rule are incidental:
6920 @code{make} worries only about giving commands and dependencies to the file
6921 presently in question.  However, when this file's commands are run, the
6922 other targets are marked as having been updated themselves.
6923 @cindex multiple targets, in pattern rule
6924 @cindex target, multiple in pattern rule
6926 The order in which pattern rules appear in the makefile is important
6927 since this is the order in which they are considered.
6928 Of equally applicable
6929 rules, only the first one found is used.  The rules you write take precedence
6930 over those that are built in.  Note however, that a rule whose
6931 dependencies actually exist or are mentioned always takes priority over a
6932 rule with dependencies that must be made by chaining other implicit rules.
6933 @cindex pattern rules, order of
6934 @cindex order of pattern rules
6936 @node Pattern Examples, Automatic, Pattern Intro, Pattern Rules
6937 @subsection Pattern Rule Examples
6939 Here are some examples of pattern rules actually predefined in
6940 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
6941 files:@refill
6943 @example
6944 %.o : %.c
6945         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
6946 @end example
6948 @noindent
6949 defines a rule that can make any file @file{@var{x}.o} from
6950 @file{@var{x}.c}.  The command uses the automatic variables @samp{$@@} and
6951 @samp{$<} to substitute the names of the target file and the source file
6952 in each case where the rule applies (@pxref{Automatic, ,Automatic Variables}).@refill
6954 Here is a second built-in rule:
6956 @example
6957 % :: RCS/%,v
6958         $(CO) $(COFLAGS) $<
6959 @end example
6961 @noindent
6962 defines a rule that can make any file @file{@var{x}} whatsoever from a
6963 corresponding file @file{@var{x},v} in the subdirectory @file{RCS}.  Since
6964 the target is @samp{%}, this rule will apply to any file whatever, provided
6965 the appropriate dependency file exists.  The double colon makes the rule
6966 @dfn{terminal}, which means that its dependency may not be an intermediate
6967 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).@refill
6969 @need 500
6970 This pattern rule has two targets:
6972 @example
6973 @group
6974 %.tab.c %.tab.h: %.y
6975         bison -d $<
6976 @end group
6977 @end example
6979 @noindent
6980 @c The following paragraph is rewritten to avoid overfull hboxes
6981 This tells @code{make} that the command @samp{bison -d @var{x}.y} will
6982 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
6983 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
6984 and the file @file{scan.o} depends on the file @file{parse.tab.h},
6985 when @file{parse.y} is changed, the command @samp{bison -d parse.y}
6986 will be executed only once, and the dependencies of both
6987 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
6988 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
6989 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
6990 linked from @file{parse.tab.o}, @file{scan.o}, and its other
6991 dependencies, and it will execute happily ever after.)@refill
6993 @node Automatic, Pattern Match, Pattern Examples, Pattern Rules
6994 @subsection Automatic Variables
6995 @cindex automatic variables
6996 @cindex variables, automatic
6997 @cindex variables, and implicit rule
6999 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
7000 @samp{.o} file: how do you write the @samp{cc} command so that it operates
7001 on the right source file name?  You cannot write the name in the command,
7002 because the name is different each time the implicit rule is applied.
7004 What you do is use a special feature of @code{make}, the @dfn{automatic
7005 variables}.  These variables have values computed afresh for each rule that
7006 is executed, based on the target and dependencies of the rule.  In this
7007 example, you would use @samp{$@@} for the object file name and @samp{$<}
7008 for the source file name.
7010 Here is a table of automatic variables:
7012 @table @code
7013 @vindex $@@
7014 @vindex @@ @r{(automatic variable)}
7015 @item $@@
7016 The file name of the target of the rule.  If the target is an archive
7017 member, then @samp{$@@} is the name of the archive file.  In a pattern
7018 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
7019 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
7020 rule's commands to be run.
7022 @vindex $%
7023 @vindex % @r{(automatic variable)}
7024 @item $%
7025 The target member name, when the target is an archive member.
7026 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
7027 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
7028 empty when the target is not an archive member.
7030 @vindex $<
7031 @vindex < @r{(automatic variable)}
7032 @item $<
7033 The name of the first dependency.  If the target got its commands from
7034 an implicit rule, this will be the first dependency added by the
7035 implicit rule (@pxref{Implicit Rules}).
7037 @vindex $?
7038 @vindex ? @r{(automatic variable)}
7039 @item $?
7040 The names of all the dependencies that are newer than the target, with
7041 spaces between them.  For dependencies which are archive members, only
7042 the member named is used (@pxref{Archives}).
7043 @cindex dependencies, list of changed
7044 @cindex list of changed dependencies
7046 @vindex $^
7047 @vindex ^ @r{(automatic variable)}
7048 @item $^
7049 The names of all the dependencies, with spaces between them.  For
7050 dependencies which are archive members, only the member named is used
7051 (@pxref{Archives}).
7052 @cindex dependencies, list of all
7053 @cindex list of all dependencies
7055 @vindex $*
7056 @vindex * @r{(automatic variable)}
7057 @item $*
7058 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
7059 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
7060 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
7061 useful for constructing names of related files.@refill
7062 @cindex stem, variable for
7064 In a static pattern rule, the stem is part of the file name that matched
7065 the @samp{%} in the target pattern.
7067 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
7068 in that way.  Instead, if the target name ends with a recognized suffix
7069 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
7070 the target name minus the suffix.  For example, if the target name is
7071 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
7072 suffix.  GNU @code{make} does this bizarre thing only for compatibility
7073 with other implementations of @code{make}.  You should generally avoid
7074 using @samp{$*} except in implicit rules or static pattern rules.@refill
7076 If the target name in an explicit rule does not end with a recognized
7077 suffix, @samp{$*} is set to the empty string for that rule.
7078 @end table
7080 @samp{$?} is useful even in explicit rules when you wish to operate on only
7081 the dependencies that have changed.  For example, suppose that an archive
7082 named @file{lib} is supposed to contain copies of several object files.
7083 This rule copies just the changed object files into the archive:
7085 @example
7086 @group
7087 lib: foo.o bar.o lose.o win.o
7088         ar r lib $?
7089 @end group
7090 @end example
7092 Of the variables listed above, four have values that are single file
7093 names, and two have values that are lists of file names.  These six
7094 have variants that get just the file's directory name or just the file
7095 name within the directory.  The variant variables' names are formed by
7096 appending @samp{D} or @samp{F}, respectively.  These variants are
7097 semi-obsolete in GNU @code{make} since the functions @code{dir} and
7098 @code{notdir} can be used to get an equivalent effect (@pxref{Filename
7099 Functions, , Functions for File Names}).  Here is a table of the
7100 variants:@refill
7102 @table @samp
7103 @vindex $(@@D)
7104 @vindex @@D @r{(automatic variable)}
7105 @item $(@@D)
7106 The directory part of the file name of the target.  If the value of
7107 @samp{$@@} is @file{dir/foo.o} then @samp{$(@@D)} is @file{dir/}.
7108 This value is @file{./} if @samp{$@@} does not contain a slash.
7109 @samp{$(@@D)} is equivalent to @w{@samp{$(dir $@@)}}.@refill
7111 @vindex $(@@F)
7112 @vindex @@F @r{(automatic variable)}
7113 @item $(@@F)
7114 The file-within-directory part of the file name of the target.  If the
7115 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
7116 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
7118 @vindex $(*D)
7119 @vindex *D @r{(automatic variable)}
7120 @item $(*D)
7121 @vindex $(*F)
7122 @vindex *F @r{(automatic variable)}
7123 @itemx $(*F)
7124 The directory part and the file-within-directory
7125 part of the stem; @file{dir/} and @file{foo} in this example.
7127 @vindex $(%D)
7128 @vindex %D @r{(automatic variable)}
7129 @item $(%D)
7130 @vindex $(%F)
7131 @vindex %F @r{(automatic variable)}
7132 @itemx $(%F)
7133 The directory part and the file-within-directory part of the target
7134 archive member name.  This makes sense only for archive member targets
7135 of the form @file{@var{archive}(@var{member})} and is useful only when
7136 @var{member} may contain a directory name.  (@xref{Archive Members,
7137 ,Archive Members as Targets}.)
7139 @vindex $(<D)
7140 @vindex <D @r{(automatic variable)}
7141 @item $(<D)
7142 @vindex $(<F)
7143 @vindex <F @r{(automatic variable)}
7144 @itemx $(<F)
7145 The directory part and the file-within-directory
7146 part of the first dependency.
7148 @vindex $(^D)
7149 @vindex ^D @r{(automatic variable)}
7150 @item $(^D)
7151 @vindex $(^F)
7152 @vindex ^F @r{(automatic variable)}
7153 @itemx $(^F)
7154 Lists of the directory parts and the file-within-directory
7155 parts of all dependencies.
7157 @vindex $(?D)
7158 @vindex ?D @r{(automatic variable)}
7159 @item $(?D)
7160 @vindex $(?F)
7161 @vindex ?F @r{(automatic variable)}
7162 @itemx $(?F)
7163 Lists of the directory parts and the file-within-directory parts of
7164 all dependencies that are newer than the target.
7165 @end table
7167 Note that we use a special stylistic convention when we talk about these
7168 automatic variables; we write ``the value of @samp{$<}'', rather than
7169 @w{``the variable @code{<}''} as we would write for ordinary variables
7170 such as @code{objects} and @code{CFLAGS}.  We think this convention
7171 looks more natural in this special case.  Please do not assume it has a
7172 deep significance; @samp{$<} refers to the variable named @code{<} just
7173 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
7174 You could just as well use @samp{$(<)} in place of @samp{$<}.
7176 @node Pattern Match, Match-Anything Rules, Automatic, Pattern Rules
7177 @subsection How Patterns Match
7179 @cindex stem
7180 A target pattern is composed of a @samp{%} between a prefix and a suffix,
7181 either or both of which may be empty.  The pattern matches a file name only
7182 if the file name starts with the prefix and ends with the suffix, without
7183 overlap.  The text between the prefix and the suffix is called the
7184 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
7185 @file{test.o}, the stem is @samp{test}.  The pattern rule dependencies are
7186 turned into actual file names by substituting the stem for the character
7187 @samp{%}.  Thus, if in the same example one of the dependencies is written
7188 as @samp{%.c}, it expands to @samp{test.c}.@refill
7190 When the target pattern does not contain a slash (and it usually does
7191 not), directory names in the file names are removed from the file name
7192 before it is compared with the target prefix and suffix.  After the
7193 comparison of the file name to the target pattern, the directory
7194 names, along with the slash that ends them, are added on to the
7195 dependency file names generated from the pattern rule's dependency
7196 patterns and the file name. The directories are ignored only for the
7197 purpose of finding an implicit rule to use, not in the application of
7198 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
7199 with @samp{src/a} as the stem.  When dependencies are turned into file
7200 names, the directories from the stem are added at the front, while the
7201 rest of the stem is substituted for the @samp{%}.  The stem
7202 @samp{src/a} with a dependency pattern @samp{c%r} gives the file name
7203 @file{src/car}.@refill
7205 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
7206 @subsection Match-Anything Pattern Rules
7208 @cindex match-anything rule
7209 @cindex terminal rule
7210 When a pattern rule's target is just @samp{%}, it matches any file name
7211 whatever.  We call these rules @dfn{match-anything} rules.  They are very
7212 useful, but it can take a lot of time for @code{make} to think about them,
7213 because it must consider every such rule for each file name listed either
7214 as a target or as a dependency.
7216 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
7217 would have to consider making it by linking an object file @file{foo.c.o},
7218 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
7219 Pascal compilation-and-linking from @file{foo.c.p}, and many other
7220 possibilities.
7222 We know these possibilities are ridiculous since @file{foo.c} is a C source
7223 file, not an executable.  If @code{make} did consider these possibilities,
7224 it would ultimately reject them, because files such as @file{foo.c.o} and
7225 @file{foo.c.p} would not exist.  But these possibilities are so
7226 numerous that @code{make} would run very slowly if it had to consider
7227 them.@refill
7229 To gain speed, we have put various constraints on the way @code{make}
7230 considers match-anything rules.  There are two different constraints that
7231 can be applied, and each time you define a match-anything rule you must
7232 choose one or the other for that rule.
7234 One choice is to mark the match-anything rule as @dfn{terminal} by defining
7235 it with a double colon.  When a rule is terminal, it does not apply unless
7236 its dependencies actually exist.  Dependencies that could be made with
7237 other implicit rules are not good enough.  In other words, no further
7238 chaining is allowed beyond a terminal rule.
7240 For example, the built-in implicit rules for extracting sources from RCS
7241 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
7242 not exist, @code{make} will not even consider trying to make it as an
7243 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
7244 RCS and SCCS files are generally ultimate source files, which should not be
7245 remade from any other files; therefore, @code{make} can save time by not
7246 looking for ways to remake them.@refill
7248 If you do not mark the match-anything rule as terminal, then it is
7249 nonterminal.  A nonterminal match-anything rule cannot apply to a file name
7250 that indicates a specific type of data.  A file name indicates a specific
7251 type of data if some non-match-anything implicit rule target matches it.
7253 For example, the file name @file{foo.c} matches the target for the pattern
7254 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
7255 rule is actually applicable (which happens only if there is a file
7256 @file{foo.y}), the fact that its target matches is enough to prevent
7257 consideration of any nonterminal match-anything rules for the file
7258 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
7259 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
7260 @file{foo.c.p}, etc.@refill
7262 The motivation for this constraint is that nonterminal match-anything
7263 rules are used for making files containing specific types of data (such as
7264 executable files) and a file name with a recognized suffix indicates some
7265 other specific type of data (such as a C source file).
7267 Special built-in dummy pattern rules are provided solely to recognize
7268 certain file names so that nonterminal match-anything rules will not be
7269 considered.  These dummy rules have no dependencies and no commands, and
7270 they are ignored for all other purposes.  For example, the built-in
7271 implicit rule
7273 @example
7274 %.p :
7275 @end example
7277 @noindent
7278 exists to make sure that Pascal source files such as @file{foo.p} match a
7279 specific target pattern and thereby prevent time from being wasted looking
7280 for @file{foo.p.o} or @file{foo.p.c}.
7282 Dummy pattern rules such as the one for @samp{%.p} are made for every
7283 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
7285 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
7286 @subsection Canceling Implicit Rules
7288 You can override a built-in implicit rule (or one you have defined
7289 yourself) by defining a new pattern rule with the same target and
7290 dependencies, but different commands.  When the new rule is defined, the
7291 built-in one is replaced.  The new rule's position in the sequence of
7292 implicit rules is determined by where you write the new rule.
7294 You can cancel a built-in implicit rule by defining a pattern rule with the
7295 same target and dependencies, but no commands.  For example, the following
7296 would cancel the rule that runs the assembler:
7298 @example
7299 %.o : %.s
7300 @end example
7302 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
7303 @section Defining Last-Resort Default Rules
7304 @cindex last-resort default rules
7305 @cindex default rules, last-resort
7307 You can define a last-resort implicit rule by writing a terminal
7308 match-anything pattern rule with no dependencies (@pxref{Match-Anything
7309 Rules}).  This is just like any other pattern rule; the only thing
7310 special about it is that it will match any target.  So such a rule's
7311 commands are used for all targets and dependencies that have no commands
7312 of their own and for which no other implicit rule applies.
7314 For example, when testing a makefile, you might not care if the source
7315 files contain real data, only that they exist.  Then you might do this:
7317 @example
7319         touch $@@
7320 @end example
7322 @noindent
7323 to cause all the source files needed (as dependencies) to be created
7324 automatically.
7326 @findex .DEFAULT
7327 You can instead define commands to be used for targets for which there
7328 are no rules at all, even ones which don't specify commands.  You do
7329 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
7330 commands are used for all dependencies which do not appear as targets in
7331 any explicit rule, and for which no implicit rule applies.  Naturally,
7332 there is no @code{.DEFAULT} rule unless you write one.
7334 If you use @code{.DEFAULT} with no commands or dependencies:
7336 @example
7337 .DEFAULT:
7338 @end example
7340 @noindent
7341 the commands previously stored for @code{.DEFAULT} are cleared.
7342 Then @code{make} acts as if you had never defined @code{.DEFAULT} at all.
7344 If you do not want a target to get the commands from a match-anything
7345 pattern rule or @code{.DEFAULT}, but you also do not want any commands
7346 to be run for the target, you can give it empty commands (@pxref{Empty
7347 Commands, ,Defining Empty Commands}).@refill
7349 You can use a last-resort rule to override part of another makefile.
7350 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
7352 @node Suffix Rules, Search Algorithm, Last Resort, Implicit Rules
7353 @section Old-Fashioned Suffix Rules
7354 @cindex old-fashioned suffix rules
7355 @cindex suffix rule
7357 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
7358 @code{make}.  Suffix rules are obsolete because pattern rules are more
7359 general and clearer.  They are supported in GNU @code{make} for
7360 compatibility with old makefiles.  They come in two kinds:
7361 @dfn{double-suffix} and @dfn{single-suffix}.@refill
7363 A double-suffix rule is defined by a pair of suffixes: the target suffix
7364 and the source suffix.  It matches any file whose name ends with the
7365 target suffix.  The corresponding implicit dependency is made by
7366 replacing the target suffix with the source suffix in the file name.  A
7367 two-suffix rule whose target and source suffixes are @samp{.o} and
7368 @samp{.c} is equivalent to the pattern rule @samp{%.o : %.c}.
7370 A single-suffix rule is defined by a single suffix, which is the source
7371 suffix.  It matches any file name, and the corresponding implicit
7372 dependency name is made by appending the source suffix.  A single-suffix
7373 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
7374 @samp{% : %.c}.
7376 Suffix rule definitions are recognized by comparing each rule's target
7377 against a defined list of known suffixes.  When @code{make} sees a rule
7378 whose target is a known suffix, this rule is considered a single-suffix
7379 rule.  When @code{make} sees a rule whose target is two known suffixes
7380 concatenated, this rule is taken as a double-suffix rule.
7382 For example, @samp{.c} and @samp{.o} are both on the default list of
7383 known suffixes.  Therefore, if you define a rule whose target is
7384 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
7385 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
7386 way to define the rule for compiling a C source file:@refill
7388 @example
7389 .c.o:
7390         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7391 @end example
7393 Suffix rules cannot have any dependencies of their own.  If they have any,
7394 they are treated as normal files with funny names, not as suffix rules.
7395 Thus, the rule:
7397 @example
7398 .c.o: foo.h
7399         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7400 @end example
7402 @noindent
7403 tells how to make the file @file{.c.o} from the dependency file
7404 @file{foo.h}, and is not at all like the pattern rule:
7406 @example
7407 %.o: %.c foo.h
7408         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7409 @end example
7411 @noindent
7412 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
7413 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
7415 Suffix rules with no commands are also meaningless.  They do not remove
7416 previous rules as do pattern rules with no commands (@pxref{Canceling
7417 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or pair of suffixes concatenated as
7418 a target in the data base.@refill
7420 @findex .SUFFIXES
7421 The known suffixes are simply the names of the dependencies of the special
7422 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
7423 for @code{.SUFFIXES} that adds more dependencies, as in:
7425 @example
7426 .SUFFIXES: .hack .win
7427 @end example
7429 @noindent
7430 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
7432 If you wish to eliminate the default known suffixes instead of just adding
7433 to them, write a rule for @code{.SUFFIXES} with no dependencies.  By
7434 special dispensation, this eliminates all existing dependencies of
7435 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
7436 want.  For example,
7438 @example
7439 @group
7440 .SUFFIXES:            # @r{Delete the default suffixes}
7441 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
7442 @end group
7443 @end example
7445 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
7446 list of suffixes to be empty.
7448 @vindex SUFFIXES
7449 The variable @code{SUFFIXES} is defined to the default list of suffixes
7450 before @code{make} reads any makefiles.  You can change the list of suffixes
7451 with a rule for the special target @code{.SUFFIXES}, but that does not alter
7452 this variable.
7454 @node Search Algorithm,  , Suffix Rules, Implicit Rules
7455 @section Implicit Rule Search Algorithm
7456 @cindex implicit rule, search algorithm
7457 @cindex search algorithm, implicit rule
7459 Here is the procedure @code{make} uses for searching for an implicit rule
7460 for a target @var{t}.  This procedure is followed for each double-colon
7461 rule with no commands, for each target of ordinary rules none of which have
7462 commands, and for each dependency that is not the target of any rule.  It
7463 is also followed recursively for dependencies that come from implicit
7464 rules, in the search for a chain of rules.
7466 Suffix rules are not mentioned in this algorithm because suffix rules are
7467 converted to equivalent pattern rules once the makefiles have been read in.
7469 For an archive member target of the form
7470 @samp{@var{archive}(@var{member})}, the following algorithm is run
7471 twice, first using the entire target name @var{t}, and second using
7472 @samp{(@var{member})} as the target @var{t} if the first run found no
7473 rule.@refill
7475 @enumerate
7476 @item
7477 Split @var{t} into a directory part, called @var{d}, and the rest,
7478 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
7479 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.@refill
7481 @item
7482 Make a list of all the pattern rules one of whose targets matches
7483 @var{t} or @var{n}.  If the target pattern contains a slash, it is
7484 matched against @var{t}; otherwise, against @var{n}.
7486 @item
7487 If any rule in that list is @emph{not} a match-anything rule, then
7488 remove all nonterminal match-anything rules from the list.
7490 @item
7491 Remove from the list all rules with no commands.
7493 @item
7494 For each pattern rule in the list:
7496 @enumerate a
7497 @item
7498 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
7499 matched by the @samp{%} in the target pattern.@refill
7501 @item
7502 Compute the dependency names by substituting @var{s} for @samp{%}; if
7503 the target pattern does not contain a slash, append @var{d} to
7504 the front of each dependency name.@refill
7506 @item
7507 Test whether all the dependencies exist or ought to exist.  (If a
7508 file name is mentioned in the makefile as a target or as an explicit
7509 dependency, then we say it ought to exist.)
7511 If all dependencies exist or ought to exist, or there are no dependencies,
7512 then this rule applies.
7513 @end enumerate
7515 @item
7516 If no pattern rule has been found so far, try harder.
7517 For each pattern rule in the list:
7519 @enumerate a
7520 @item
7521 If the rule is terminal, ignore it and go on to the next rule.
7523 @item
7524 Compute the dependency names as before.
7526 @item
7527 Test whether all the dependencies exist or ought to exist.
7529 @item
7530 For each dependency that does not exist, follow this algorithm
7531 recursively to see if the dependency can be made by an implicit
7532 rule.
7534 @item
7535 If all dependencies exist, ought to exist, or can be
7536 made by implicit rules, then this rule applies.
7537 @end enumerate
7539 @item
7540 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
7541 applies.  In that case, give @var{t} the same commands that
7542 @code{.DEFAULT} has.  Otherwise, there are no commands for @var{t}.
7543 @end enumerate
7545 Once a rule that applies has been found, for each target pattern of the
7546 rule other than the one that matched @var{t} or @var{n}, the @samp{%} in
7547 the pattern is replaced with @var{s} and the resultant file name is stored
7548 until the commands to remake the target file @var{t} are executed.  After
7549 these commands are executed, each of these stored file names are entered
7550 into the data base and marked as having been updated and having the same
7551 update status as the file @var{t}.
7553 When the commands of a pattern rule are executed for @var{t}, the automatic
7554 variables are set corresponding to the target and dependencies.
7555 @xref{Automatic, ,Automatic Variables}.
7557 @node Archives, Features, Implicit Rules, Top
7558 @chapter Using @code{make} to Update Archive Files
7559 @cindex archive
7561 @dfn{Archive files} are files containing named subfiles called
7562 @dfn{members}; they are maintained with the program @code{ar} and their
7563 main use is as subroutine libraries for linking.
7565 @menu
7566 * Archive Members::             Archive members as targets.
7567 * Archive Update::              The implicit rule for archive member targets.
7568 * Archive Suffix Rules::        You can write a special kind of suffix rule
7569                                   for updating archives.
7570 @end menu
7572 @node Archive Members, Archive Update,  , Archives
7573 @section Archive Members as Targets
7574 @cindex archive member targets
7576 An individual member of an archive file can be used as a target or
7577 dependency in @code{make}.  The archive file must already exist, but the
7578 member need not exist.  You specify the member named @var{member} in
7579 archive file @var{archive} as follows:
7581 @example
7582 @var{archive}(@var{member})
7583 @end example
7585 @noindent
7586 This construct is available only in targets and dependencies, not in
7587 commands!  Most programs that you might use in commands do not support this
7588 syntax and cannot act directly on archive members.  Only @code{ar} and
7589 other programs specifically designed to operate on archives can do so.
7590 Therefore, valid commands to update an archive member target probably must
7591 use @code{ar}.  For example, this rule says to create a member
7592 @file{hack.o} in archive @file{foolib} by copying the file @file{hack.o}:
7594 @example
7595 foolib(hack.o) : hack.o
7596         ar r foolib hack.o
7597 @end example
7599 In fact, nearly all archive member targets are updated in just this way
7600 and there is an implicit rule to do it for you.
7602 To specify several members in the same archive, you can write all the
7603 member names together between the parentheses.  For example:
7605 @example
7606 foolib(hack.o kludge.o)
7607 @end example
7609 @noindent
7610 is equivalent to:
7612 @example
7613 foolib(hack.o) foolib(kludge.o)
7614 @end example
7616 @cindex wildcard, in archive member
7617 You can also use shell-style wildcards in an archive member reference.
7618 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
7619 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
7620 @file{foolib} archive whose names end in @samp{.o}; perhaps
7621 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
7623 @node Archive Update, Archive Suffix Rules, Archive Members, Archives
7624 @section Implicit Rule for Archive Member Targets
7626 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
7627 member named @var{m} in the archive file @var{a}.
7629 When @code{make} looks for an implicit rule for such a target, as a special
7630 feature it considers implicit rules that match @file{(@var{m})}, as well as
7631 those that match the actual target @file{@var{a}(@var{m})}.
7633 This causes one special rule whose target is @file{(%)} to match.  This
7634 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
7635 into the archive.  For example, it will update the archive member target
7636 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
7637 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
7639 When this rule is chained with others, the result is very powerful.
7640 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
7641 @samp{(} and @samp{)} from being interpreted specially by the shell) in
7642 the presence of a file @file{bar.c} is enough to cause the following
7643 commands to be run, even without a makefile:
7645 @example
7646 cc -c bar.c -o bar.o
7647 ar r foo.a bar.o
7648 rm -f bar.o
7649 @end example
7651 @noindent
7652 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
7653 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
7655 Implicit rules such as this one are written using the automatic variable
7656 @samp{$%}.  @xref{Automatic, ,Automatic Variables}.
7658 An archive member name in an archive cannot contain a directory name, but
7659 it may be useful in a makefile to pretend that it does.  If you write an
7660 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
7661 automatic updating with this command:
7663 @example
7664 ar r foo.a dir/file.o
7665 @end example
7667 @noindent
7668 which has the effect of copying the file @file{dir/foo.o} into a member
7669 named @file{foo.o}.  In connection with such usage, the automatic variables
7670 @code{%D} and @code{%F} may be useful.
7672 @menu
7673 * Archive Symbols::             How to update archive symbol directories.
7674 @end menu
7676 @node Archive Symbols,  ,  , Archive Update
7677 @subsection Updating Archive Symbol Directories
7678 @cindex @code{__.SYMDEF}
7679 @cindex updating archive symbol directories
7680 @cindex archive symbol directory updating
7681 @cindex symbol directories, updating archive 
7682 @cindex directories, updating archive symbol
7684 An archive file that is used as a library usually contains a special member
7685 named @file{__.SYMDEF} that contains a directory of the external symbol
7686 names defined by all the other members.  After you update any other
7687 members, you need to update @file{__.SYMDEF} so that it will summarize the
7688 other members properly.  This is done by running the @code{ranlib} program:
7690 @example
7691 ranlib @var{archivefile}
7692 @end example
7694 Normally you would put this command in the rule for the archive file,
7695 and make all the members of the archive file dependencies of that rule.
7696 For example,
7698 @example
7699 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
7700         ranlib libfoo.a
7701 @end example
7703 @noindent
7704 The effect of this is to update archive members @file{x.o}, @file{y.o},
7705 etc., and then update the symbol directory member @file{__.SYMDEF} by
7706 running @code{ranlib}.  The rules for updating the members are not shown
7707 here; most likely you can omit them and use the implicit rule which copies
7708 files into the archive, as described in the preceding section.
7710 This is not necessary when using the GNU @code{ar} program, which
7711 updates the @file{__.SYMDEF} member automatically.
7713 @node Archive Suffix Rules,  , Archive Update, Archives
7714 @section Suffix Rules for Archive Files
7715 @cindex suffix rule, for archive
7716 @cindex archive, suffix rule for
7717 @cindex library archive, suffix rule for
7718 @cindex @code{.a} (archives)
7720 You can write a special kind of suffix rule for dealing with archive
7721 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
7722 Archive suffix rules are obsolete in GNU @code{make}, because pattern
7723 rules for archives are a more general mechanism (@pxref{Archive
7724 Update}).  But they are retained for compatibility with other
7725 @code{make}s.
7727 To write a suffix rule for archives, you simply write a suffix rule
7728 using the target suffix @samp{.a} (the usual suffix for archive files).
7729 For example, here is the old-fashioned suffix rule to update a library
7730 archive from C source files:
7732 @example
7733 @group
7734 .c.a:
7735         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
7736         $(AR) r $@@ $*.o
7737         $(RM) $*.o
7738 @end group
7739 @end example
7741 @noindent
7742 This works just as if you had written the pattern rule:
7744 @example
7745 @group
7746 (%.o): %.c
7747         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
7748         $(AR) r $@@ $*.o
7749         $(RM) $*.o
7750 @end group
7751 @end example
7753 In fact, this is just what @code{make} does when it sees a suffix rule
7754 with @samp{.a} as the target suffix.  Any double-suffix rule
7755 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
7756 pattern @samp{(%.o)} and a dependency pattern of @samp{%.@var{x}}.
7758 Since you might want to use @samp{.a} as the suffix for some other kind
7759 of file, @code{make} also converts archive suffix rules to pattern rules
7760 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
7761 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
7762 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
7764 @node Features, Missing, Archives, Top
7765 @chapter Features of GNU @code{make}
7766 @cindex features of GNU @code{make}
7767 @cindex portability
7768 @cindex compatibility
7770 Here is a summary of the features of GNU @code{make}, for comparison
7771 with and credit to other versions of @code{make}.  We consider the
7772 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
7773 concerned with writing portable makefiles, you should use only the
7774 features of @code{make} @emph{not} listed here or in @ref{Missing}.
7776 Many features come from the version of @code{make} in System V.
7778 @itemize @bullet
7779 @item
7780 The @code{VPATH} variable and its special meaning. 
7781 @xref{Directory Search, , Searching Directories for Dependencies}.  
7782 This feature exists in System V @code{make}, but is undocumented.
7783 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
7784 @code{VPATH} feature).@refill
7786 @item
7787 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
7788 Allowing multiple files to be included with a single directive is a GNU
7789 extension.
7791 @item
7792 Variables are read from and communicated via the environment.
7793 @xref{Environment, ,Variables from the Environment}.
7795 @item
7796 Options passed through the variable @code{MAKEFLAGS} to recursive
7797 invocations of @code{make}.
7798 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
7800 @item
7801 The automatic variable @code{$%} is set to the member name
7802 in an archive reference.  @xref{Automatic, ,Automatic Variables}.
7804 @item
7805 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
7806 and @code{$?} have corresponding forms like @code{$(@@F)} and
7807 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
7808 extension.  @xref{Automatic, ,Automatic Variables}.@refill
7810 @item
7811 Substitution variable references.
7812 @xref{Reference, ,Basics of Variable References}.
7814 @item
7815 The command-line options @samp{-b} and @samp{-m}, accepted and
7816 ignored.  In System V @code{make}, these options actually do something.
7818 @item
7819 Execution of recursive commands to run @code{make} via the variable
7820 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
7821 @xref{Recursion, ,Recursive Use of @code{make}}.
7823 @item
7824 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
7825 Rules}.  This feature is obsolete in GNU @code{make}, because the
7826 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
7827 Implicit Rules}) allows one pattern rule for installing members in an
7828 archive (@pxref{Archive Update}) to be sufficient.
7830 @item
7831 The arrangement of lines and backslash-newline combinations in
7832 commands is retained when the commands are printed, so they appear as
7833 they do in the makefile, except for the stripping of initial
7834 whitespace.
7835 @end itemize
7837 The following features were inspired by various other versions of
7838 @code{make}.  In some cases it is unclear exactly which versions inspired
7839 which others.
7841 @itemize @bullet
7842 @item
7843 Pattern rules using @samp{%}.
7844 This has been implemented in several versions of @code{make}.
7845 We're not sure who invented it first, but it's been spread around a bit.
7846 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.@refill
7848 @item
7849 Rule chaining and implicit intermediate files.
7850 This was implemented by Stu Feldman in his version of @code{make}
7851 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
7852 AT&T Bell Labs in his @code{mk} program (where he terms it
7853 ``transitive closure'').  We do not really know if
7854 we got this from either of them or thought it up ourselves at the
7855 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
7857 @item
7858 The automatic variable @code{$^} containing a list of all dependencies
7859 of the current target.  We did not invent this, but we have no idea who did.
7860 @xref{Automatic, ,Automatic Variables}.
7862 @item
7863 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
7864 invented by Andrew Hume in @code{mk}.  
7865 @xref{Instead of Execution, ,Instead of Executing the Commands}.
7867 @item
7868 The concept of doing several things at once (parallelism) exists in
7869 many incarnations of @code{make} and similar programs, though not in the
7870 System V or BSD implementations.  @xref{Execution, ,Command Execution}.
7872 @item
7873 Modified variable references using pattern substitution come from
7874 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
7875 This functionality was provided in GNU @code{make} by the
7876 @code{patsubst} function before the alternate syntax was implemented
7877 for compatibility with SunOS 4.  It is not altogether clear who
7878 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
7879 4 was released.@refill
7881 @item
7882 The special significance of @samp{+} characters preceding command lines
7883 (@pxref{Instead of Execution, ,Instead of Executing the Commands}) is
7884 mandated by
7885 @cite{IEEE Standard 1003.2-1992} (POSIX.2).
7887 @item
7888 The @samp{+=} syntax to append to the value of a variable comes from SunOS
7889 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
7891 @item
7892 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
7893 multiple members in a single archive file comes from SunOS 4 @code{make}.
7894 @xref{Archive Members}.
7896 @item
7897 The @code{-include} directive to include makefiles with no error for a
7898 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
7899 @code{make} does not allow multiple makefiles to be specified in one
7900 @code{-include} directive.)
7901 @end itemize
7903 The remaining features are inventions new in GNU @code{make}:
7905 @itemize @bullet
7906 @item
7907 Use the @samp{-v} or @samp{--version} option to print version and
7908 copyright information.
7910 @item 
7911 Use the @samp{-h} or @samp{--help} option to summarize the options to
7912 @code{make}.
7914 @item
7915 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
7917 @item
7918 Pass command-line variable assignments automatically through the
7919 variable @code{MAKE} to recursive @code{make} invocations.
7920 @xref{Recursion, ,Recursive Use of @code{make}}.
7922 @item
7923 Use the @samp{-C} or @samp{--directory} command option to change
7924 directory.  @xref{Options Summary, ,Summary of Options}.
7926 @item
7927 Make verbatim variable definitions with @code{define}.  
7928 @xref{Defining, ,Defining Variables Verbatim}.
7930 @item
7931 Declare phony targets with the special target @code{.PHONY}.
7933 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
7934 different syntax in his @code{mk} program.  This seems to be a case of
7935 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
7937 @item
7938 Manipulate text by calling functions.  
7939 @xref{Functions, ,Functions for Transforming Text}.
7941 @item
7942 Use the @samp{-o} or @samp{--old-file}
7943 option to pretend a file's modification-time is old.
7944 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
7946 @item
7947 Conditional execution.
7949 This feature has been implemented numerous times in various versions
7950 of @code{make}; it seems a natural extension derived from the features
7951 of the C preprocessor and similar macro languages and is not a
7952 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
7954 @item
7955 Specify a search path for included makefiles.
7956 @xref{Include, ,Including Other Makefiles}.
7958 @item
7959 Specify extra makefiles to read with an environment variable.
7960 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
7962 @item
7963 Strip leading sequences of @samp{./} from file names, so that
7964 @file{./@var{file}} and @file{@var{file}} are considered to be the
7965 same file.@refill
7967 @item
7968 Use a special search method for library dependencies written in the
7969 form @samp{-l@var{name}}.  
7970 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
7972 @item
7973 Allow suffixes for suffix rules 
7974 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
7975 characters.  In other versions of @code{make}, they must begin with
7976 @samp{.} and not contain any @samp{/} characters.
7978 @item
7979 Keep track of the current level of @code{make} recursion using the
7980 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
7982 @item
7983 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
7985 @item
7986 Provide selective @code{vpath} search.  
7987 @xref{Directory Search, ,Searching Directories for Dependencies}.
7989 @item
7990 Provide computed variable references.  
7991 @xref{Reference, ,Basics of Variable References}.
7993 @item
7994 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
7995 System V @code{make} has a very, very limited form of this
7996 functionality in that it will check out SCCS files for makefiles.
7998 @item
7999 Various new built-in implicit rules.  
8000 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
8002 @item
8003 The built-in variable @samp{MAKE_VERSION} gives the version number of
8004 @code{make}.
8005 @end itemize
8007 @node Missing, Makefile Conventions, Features, Top
8008 @chapter Incompatibilities and Missing Features
8009 @cindex incompatibilities 
8010 @cindex missing features
8011 @cindex features, missing
8013 The @code{make} programs in various other systems support a few features
8014 that are not implemented in GNU @code{make}.  The POSIX.2 standard
8015 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
8016 require any of these features.@refill
8018 @itemize @bullet
8019 @item
8020 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
8021 of archive file @var{file}.  The member is chosen, not by name, but by
8022 being an object file which defines the linker symbol @var{entry}.@refill
8024 This feature was not put into GNU @code{make} because of the
8025 nonmodularity of putting knowledge into @code{make} of the internal
8026 format of archive file symbol tables.  
8027 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
8029 @item
8030 Suffixes (used in suffix rules) that end with the character @samp{~}
8031 have a special meaning to System V @code{make}; 
8032 they refer to the SCCS file that corresponds
8033 to the file one would get without the @samp{~}.  For example, the
8034 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
8035 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
8036 series of such suffix rules is required.  
8037 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
8039 In GNU @code{make}, this entire series of cases is handled by two
8040 pattern rules for extraction from SCCS, in combination with the
8041 general feature of rule chaining.  
8042 @xref{Chained Rules, ,Chains of Implicit Rules}.
8044 @item
8045 In System V @code{make}, the string @samp{$$@@} has the strange meaning
8046 that, in the dependencies of a rule with multiple targets, it stands
8047 for the particular target that is being processed.
8049 This is not defined in GNU @code{make} because @samp{$$} should always
8050 stand for an ordinary @samp{$}.
8052 It is possible to get this functionality through the use of static pattern
8053 rules (@pxref{Static Pattern, ,Static Pattern Rules}).  
8054 The System V @code{make} rule:
8056 @example
8057 $(targets): $$@@.o lib.a
8058 @end example
8060 @noindent
8061 can be replaced with the GNU @code{make} static pattern rule:
8063 @example
8064 $(targets): %: %.o lib.a
8065 @end example
8067 @item
8068 In System V and 4.3 BSD @code{make}, files found by @code{VPATH} search
8069 (@pxref{Directory Search, ,Searching Directories for Dependencies}) have their names changed inside command
8070 strings.  We feel it is much cleaner to always use automatic variables
8071 and thus make this feature obsolete.@refill
8073 @item
8074 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
8075 the dependencies of a rule has the amazingly strange ``feature'' of
8076 expanding to the full name of the @emph{target of that rule}.  We cannot
8077 imagine what went on in the minds of Unix @code{make} developers to do
8078 this; it is utterly inconsistent with the normal definition of @code{$*}.
8079 @vindex * @r{(automatic variable), unsupported bizarre usage}
8081 @item
8082 In some Unix @code{make}s, implicit rule search
8083 (@pxref{Implicit Rules, ,Using Implicit Rules}) is apparently done for
8084 @emph{all} targets, not just those without commands.  This means you can
8085 do:@refill
8087 @example
8088 @group
8089 foo.o:
8090         cc -c foo.c
8091 @end group
8092 @end example
8094 @noindent
8095 and Unix @code{make} will intuit that @file{foo.o} depends on
8096 @file{foo.c}.@refill
8098 We feel that such usage is broken.  The dependency properties of
8099 @code{make} are well-defined (for GNU @code{make}, at least),
8100 and doing such a thing simply does not fit the model.@refill
8102 @item
8103 GNU @code{make} does not include any built-in implicit rules for
8104 compiling or preprocessing EFL programs.  If we hear of anyone who is
8105 using EFL, we will gladly add them.
8107 @item
8108 It appears that in SVR4 @code{make}, a suffix rule can be specified with
8109 no commands, and it is treated as if it had empty commands
8110 (@pxref{Empty Commands}).  For example:
8112 @example
8113 .c.a:
8114 @end example
8116 @noindent
8117 will override the built-in @file{.c.a} suffix rule.
8119 We feel that it is cleaner for a rule without commands to always simply
8120 add to the dependency list for the target.  The above example can be
8121 easily rewritten to get the desired behavior in GNU @code{make}:
8123 @example
8124 .c.a: ;
8125 @end example
8127 @item
8128 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
8129 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
8130 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
8131 program it runs returns a nonzero status.  We feel it is cleaner to
8132 write each shell command line to stand on its own and not require this
8133 special treatment.
8134 @end itemize
8136 @comment The makefile standards are in a separate file that is also
8137 @comment included by standards.texi.
8138 @include make-stds.texi
8140 @node Quick Reference, Complex Makefile, Makefile Conventions, Top
8141 @appendix Quick Reference
8143 This appendix summarizes the directives, text manipulation functions,
8144 and special variables which GNU @code{make} understands.
8145 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
8146 and @ref{Options Summary, ,Summary of Options},
8147 for other summaries.
8149 Here is a summary of the directives GNU @code{make} recognizes:
8151 @table @code
8152 @item define @var{variable}
8153 @itemx endef
8155 Define a multi-line, recursively-expanded variable.@*
8156 @xref{Sequences}.
8158 @item ifdef @var{variable}
8159 @itemx ifndef @var{variable}
8160 @itemx ifeq (@var{a},@var{b})
8161 @itemx ifeq "@var{a}" "@var{b}"
8162 @itemx ifeq '@var{a}' '@var{b}'
8163 @itemx ifneq (@var{a},@var{b})
8164 @itemx ifneq "@var{a}" "@var{b}"
8165 @itemx ifneq '@var{a}' '@var{b}'
8166 @itemx else
8167 @itemx endif
8169 Conditionally evaluate part of the makefile.@*
8170 @xref{Conditionals}.
8172 @item include @var{file}
8174 Include another makefile.@*
8175 @xref{Include, ,Including Other Makefiles}.
8177 @item override @var{variable} = @var{value}
8178 @itemx override @var{variable} := @var{value}
8179 @itemx override @var{variable} += @var{value}
8180 @itemx override define @var{variable}
8181 @itemx endef
8183 Define a variable, overriding any previous definition, even one from
8184 the command line.@*
8185 @xref{Override Directive, ,The @code{override} Directive}.
8187 @item export
8189 Tell @code{make} to export all variables to child processes by default.@*
8190 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
8192 @item export @var{variable}
8193 @itemx export @var{variable} = @var{value}
8194 @itemx export @var{variable} := @var{value}
8195 @itemx export @var{variable} += @var{value}
8196 @itemx unexport @var{variable}
8197 Tell @code{make} whether or not to export a particular variable to child
8198 processes.@*
8199 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
8201 @item vpath @var{pattern} @var{path}
8202 Specify a search path for files matching a @samp{%} pattern.@*
8203 @xref{Selective Search, , The @code{vpath} Directive}.
8205 @item vpath @var{pattern}
8206 Remove all search paths previously specified for @var{pattern}.
8208 @item vpath
8209 Remove all search paths previously specified in any @code{vpath}
8210 directive.
8211 @end table
8213 Here is a summary of the text manipulation functions (@pxref{Functions}):
8215 @table @code
8216 @item $(subst @var{from},@var{to},@var{text})
8217 Replace @var{from} with @var{to} in @var{text}.@*
8218 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8220 @item $(patsubst @var{pattern},@var{replacement},@var{text})
8221 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
8222 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8224 @item $(strip @var{string})
8225 Remove excess whitespace characters from @var{string}.@*
8226 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8228 @item $(findstring @var{find},@var{text})
8229 Locate @var{find} in @var{text}.@*
8230 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8232 @item $(filter @var{pattern}@dots{},@var{text})
8233 Select words in @var{text} that match one of the @var{pattern} words.@*
8234 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8236 @item $(filter-out @var{pattern}@dots{},@var{text})
8237 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
8238 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8240 @item $(sort @var{list})
8241 Sort the words in @var{list} lexicographically, removing duplicates.@*
8242 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8244 @item $(dir @var{names}@dots{})
8245 Extract the directory part of each file name.@*
8246 @xref{Filename Functions, ,Functions for File Names}.
8248 @item $(notdir @var{names}@dots{})
8249 Extract the non-directory part of each file name.@*
8250 @xref{Filename Functions, ,Functions for File Names}.
8252 @item $(suffix @var{names}@dots{})
8253 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
8254 @xref{Filename Functions, ,Functions for File Names}.
8256 @item $(basename @var{names}@dots{})
8257 Extract the base name (name without suffix) of each file name.@*
8258 @xref{Filename Functions, ,Functions for File Names}.
8260 @item $(addsuffix @var{suffix},@var{names}@dots{})
8261 Append @var{suffix} to each word in @var{names}.@*
8262 @xref{Filename Functions, ,Functions for File Names}.
8264 @item $(addprefix @var{prefix},@var{names}@dots{})
8265 Prepend @var{prefix} to each word in @var{names}.@*
8266 @xref{Filename Functions, ,Functions for File Names}.
8268 @item $(join @var{list1},@var{list2})
8269 Join two parallel lists of words.@*
8270 @xref{Filename Functions, ,Functions for File Names}.
8272 @item $(word @var{n},@var{text})
8273 Extract the @var{n}th word (one-origin) of @var{text}.@*
8274 @xref{Filename Functions, ,Functions for File Names}.
8276 @item $(words @var{text})
8277 Count the number of words in @var{text}.@*
8278 @xref{Filename Functions, ,Functions for File Names}.
8280 @item $(firstword @var{names}@dots{})
8281 Extract the first word of @var{names}.@*
8282 @xref{Filename Functions, ,Functions for File Names}.
8284 @item $(wildcard @var{pattern}@dots{})
8285 Find file names matching a shell file name pattern (@emph{not} a
8286 @samp{%} pattern).@*
8287 @xref{Wildcard Function, ,The Function @code{wildcard}}.
8289 @item $(shell @var{command})
8291 Execute a shell command and return its output.@*
8292 @xref{Shell Function, , The @code{shell} Function}.
8294 @item $(origin @var{variable})
8296 Return a string describing how the @code{make} variable @var{variable} was
8297 defined.@*
8298 @xref{Origin Function, , The @code{origin} Function}.
8300 @item $(foreach @var{var},@var{words},@var{text})
8302 Evaluate @var{text} with @var{var} bound to each word in @var{words},
8303 and concatenate the results.@*
8304 @xref{Foreach Function, ,The @code{foreach} Function}.
8305 @end table
8307 Here is a summary of the automatic variables.
8308 @xref{Automatic, ,Automatic Variables},
8309 for full information.
8311 @table @code
8312 @item $@@
8313 The file name of the target.
8315 @item $%
8316 The target member name, when the target is an archive member.
8318 @item $<
8319 The name of the first dependency.
8321 @item $?
8322 The names of all the dependencies that are
8323 newer than the target, with spaces between them.
8324 For dependencies which are archive members, only
8325 the member named is used (@pxref{Archives}).
8327 @item $^
8328 The names of all the dependencies, with spaces between them.  For
8329 dependencies which are archive members, only the member named is used
8330 (@pxref{Archives}).
8332 @item $*
8333 The stem with which an implicit rule matches 
8334 (@pxref{Pattern Match, ,How Patterns Match}).
8336 @item $(@@D)
8337 @itemx $(@@F)
8338 The directory part and the file-within-directory part of @code{$@@}.
8340 @item $(*D)
8341 @itemx $(*F)
8342 The directory part and the file-within-directory part of @code{$*}.
8344 @item $(%D)
8345 @itemx $(%F)
8346 The directory part and the file-within-directory part of @code{$%}.
8348 @item $(<D)
8349 @itemx $(<F)
8350 The directory part and the file-within-directory part of @code{$<}.
8352 @item $(^D)
8353 @itemx $(^F)
8354 The directory part and the file-within-directory part of @code{$^}.
8356 @item $(?D)
8357 @itemx $(?F)
8358 The directory part and the file-within-directory part of @code{$?}.
8359 @end table
8361 These variables are used specially by GNU @code{make}:
8363 @table @code
8364 @item MAKEFILES
8366 Makefiles to be read on every invocation of @code{make}.@*
8367 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
8369 @item VPATH
8371 Directory search path for files not found in the current directory.@*
8372 @xref{General Search, , @code{VPATH} Search Path for All Dependencies}.  
8374 @item SHELL
8376 The name of the system default command interpreter, usually @file{/bin/sh}.
8377 You can set @code{SHELL} in the makefile to change the shell used to run
8378 commands.  @xref{Execution, ,Command Execution}.
8380 @item MAKE
8382 The name with which @code{make} was invoked.
8383 Using this variable in commands has special meaning.
8384 @xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.
8386 @item MAKELEVEL
8388 The number of levels of recursion (sub-@code{make}s).@*
8389 @xref{Variables/Recursion}.
8391 @item MAKEFLAGS
8392 @itemx MFLAGS
8394 The flags given to @code{make}.  You can set this in the environment or
8395 a makefile to set flags.@*
8396 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
8398 @item SUFFIXES
8400 The default list of suffixes before @code{make} reads any makefiles.
8401 @end table
8403 @node Complex Makefile, Concept Index, Quick Reference, Top
8404 @appendix Complex Makefile Example
8406 Here is the makefile for the GNU @code{tar} program.  This is a
8407 moderately complex makefile.
8409 Because it is the first target, the default goal is @samp{all}.  An
8410 interesting feature of this makefile is that @file{testpad.h} is a
8411 source file automatically created by the @code{testpad} program,
8412 itself compiled from @file{testpad.c}.
8414 If you type @samp{make} or @samp{make all}, then @code{make} creates
8415 the @file{tar} executable, the @file{rmt} daemon that provides
8416 remote tape access, and the @file{tar.info} Info file.
8418 If you type @samp{make install}, then @code{make} not only creates
8419 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
8420 them.
8422 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
8423 files, and the @file{tar}, @file{rmt}, @file{testpad},
8424 @file{testpad.h}, and @file{core} files.
8426 If you type @samp{make distclean}, then @code{make} not only removes
8427 the same files as does @samp{make clean} but also the
8428 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
8429 (Although it is not evident, this makefile (and
8430 @file{config.status}) is generated by the user with the
8431 @code{configure} program, which is provided in the @code{tar}
8432 distribution, but is not shown here.)
8434 If you type @samp{make realclean}, then @code{make} removes the same
8435 files as does @samp{make distclean} and also removes the Info files
8436 generated from @file{tar.texinfo}.
8438 In addition, there are targets @code{shar} and @code{dist} that create
8439 distribution kits.
8441 @example
8442 @group
8443 # Generated automatically from Makefile.in by configure.
8444 # Un*x Makefile for GNU tar program.
8445 # Copyright (C) 1991 Free Software Foundation, Inc.
8446 @end group
8448 @group
8449 # This program is free software; you can redistribute
8450 # it and/or modify it under the terms of the GNU
8451 # General Public License @dots{}
8452 @dots{}
8453 @dots{}
8454 @end group
8456 SHELL = /bin/sh
8458 #### Start of system configuration section. ####
8460 srcdir = .
8462 @group
8463 # If you use gcc, you should either run the
8464 # fixincludes script that comes with it or else use
8465 # gcc with the -traditional option.  Otherwise ioctl
8466 # calls will be compiled incorrectly on some systems.
8467 CC = gcc -O
8468 YACC = bison -y
8469 INSTALL = /usr/local/bin/install -c
8470 INSTALLDATA = /usr/local/bin/install -c -m 644
8471 @end group
8473 # Things you might add to DEFS:
8474 # -DSTDC_HEADERS        If you have ANSI C headers and
8475 #                       libraries.
8476 # -DPOSIX               If you have POSIX.1 headers and 
8477 #                       libraries.
8478 # -DBSD42               If you have sys/dir.h (unless 
8479 #                       you use -DPOSIX), sys/file.h, 
8480 #                       and st_blocks in `struct stat'.
8481 # -DUSG                 If you have System V/ANSI C 
8482 #                       string and memory functions 
8483 #                       and headers, sys/sysmacros.h, 
8484 #                       fcntl.h, getcwd, no valloc, 
8485 #                       and ndir.h (unless 
8486 #                       you use -DDIRENT).
8487 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not 
8488 #                       include memory.h.
8489 # -DDIRENT              If USG and you have dirent.h 
8490 #                       instead of ndir.h.
8491 # -DSIGTYPE=int         If your signal handlers 
8492 #                       return int, not void.
8493 # -DNO_MTIO             If you lack sys/mtio.h 
8494 #                       (magtape ioctls).
8495 # -DNO_REMOTE           If you do not have a remote shell 
8496 #                       or rexec.
8497 # -DUSE_REXEC           To use rexec for remote tape
8498 #                       operations instead of 
8499 #                       forking rsh or remsh.
8500 # -DVPRINTF_MISSING     If you lack vprintf function 
8501 #                       (but have _doprnt).
8502 # -DDOPRNT_MISSING      If you lack _doprnt function.  
8503 #                       Also need to define 
8504 #                       -DVPRINTF_MISSING.
8505 # -DFTIME_MISSING       If you lack ftime system call.
8506 # -DSTRSTR_MISSING      If you lack strstr function.
8507 # -DVALLOC_MISSING      If you lack valloc function.
8508 # -DMKDIR_MISSING       If you lack mkdir and 
8509 #                       rmdir system calls.
8510 # -DRENAME_MISSING      If you lack rename system call.
8511 # -DFTRUNCATE_MISSING   If you lack ftruncate 
8512 #                       system call.
8513 # -DV7                  On Version 7 Unix (not 
8514 #                       tested in a long time).
8515 # -DEMUL_OPEN3          If you lack a 3-argument version 
8516 #                       of open, and want to emulate it 
8517 #                       with system calls you do have.
8518 # -DNO_OPEN3            If you lack the 3-argument open
8519 #                       and want to disable the tar -k 
8520 #                       option instead of emulating open.
8521 # -DXENIX               If you have sys/inode.h 
8522 #                       and need it 94 to be included.
8524 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
8525         -DVPRINTF_MISSING -DBSD42
8526 # Set this to rtapelib.o unless you defined NO_REMOTE, 
8527 # in which case make it empty.
8528 RTAPELIB = rtapelib.o
8529 LIBS = 
8530 DEF_AR_FILE = /dev/rmt8
8531 DEFBLOCKING = 20
8533 @group
8534 CDEBUG = -g
8535 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
8536         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
8537         -DDEFBLOCKING=$(DEFBLOCKING)
8538 LDFLAGS = -g
8539 @end group
8541 @group
8542 prefix = /usr/local
8543 # Prefix for each installed program, 
8544 # normally empty or `g'.
8545 binprefix = 
8547 # The directory to install tar in.
8548 bindir = $(prefix)/bin
8550 # The directory to install the info files in.
8551 infodir = $(prefix)/info
8552 @end group
8554 #### End of system configuration section. ####
8556 SRC1 =  tar.c create.c extract.c buffer.c \
8557         getoldopt.c update.c gnu.c mangle.c
8558 SRC2 =  version.c list.c names.c diffarch.c \
8559         port.c wildmat.c getopt.c
8560 SRC3 =  getopt1.c regex.c getdate.y
8561 SRCS =  $(SRC1) $(SRC2) $(SRC3)
8562 OBJ1 =  tar.o create.o extract.o buffer.o \
8563         getoldopt.o update.o gnu.o mangle.o
8564 OBJ2 =  version.o list.o names.o diffarch.o \
8565         port.o wildmat.o getopt.o
8566 OBJ3 =  getopt1.o regex.o getdate.o $(RTAPELIB)
8567 OBJS =  $(OBJ1) $(OBJ2) $(OBJ3)
8568 @group
8569 AUX =   README COPYING ChangeLog Makefile.in  \
8570         makefile.pc configure configure.in \
8571         tar.texinfo tar.info* texinfo.tex \
8572         tar.h port.h open3.h getopt.h regex.h \
8573         rmt.h rmt.c rtapelib.c alloca.c \
8574         msd_dir.h msd_dir.c tcexparg.c \
8575         level-0 level-1 backup-specs testpad.c
8576 @end group
8578 all:    tar rmt tar.info
8580 @group
8581 tar:    $(OBJS)
8582         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
8583 @end group
8585 @group
8586 rmt:    rmt.c
8587         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
8588 @end group
8590 @group
8591 tar.info: tar.texinfo
8592         makeinfo tar.texinfo
8593 @end group
8595 @group
8596 install: all
8597         $(INSTALL) tar $(bindir)/$(binprefix)tar
8598         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
8599         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
8600 @end group
8602 @group
8603 $(OBJS): tar.h port.h testpad.h
8604 regex.o buffer.o tar.o: regex.h
8605 # getdate.y has 8 shift/reduce conflicts.
8606 @end group
8608 @group
8609 testpad.h: testpad
8610         ./testpad
8611 @end group
8613 @group
8614 testpad: testpad.o
8615         $(CC) -o $@@ testpad.o
8616 @end group
8618 @group
8619 TAGS:   $(SRCS)
8620         etags $(SRCS)
8621 @end group
8623 @group
8624 clean:
8625         rm -f *.o tar rmt testpad testpad.h core
8626 @end group
8628 @group
8629 distclean: clean
8630         rm -f TAGS Makefile config.status
8631 @end group
8633 @group
8634 realclean: distclean
8635         rm -f tar.info*
8636 @end group
8638 @group
8639 shar: $(SRCS) $(AUX)
8640         shar $(SRCS) $(AUX) | compress \
8641           > tar-`sed -e '/version_string/!d' \
8642                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
8643                      -e q 
8644                      version.c`.shar.Z
8645 @end group
8647 @group
8648 dist: $(SRCS) $(AUX)
8649         echo tar-`sed \
8650              -e '/version_string/!d' \
8651              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
8652              -e q 
8653              version.c` > .fname
8654         -rm -rf `cat .fname`
8655         mkdir `cat .fname`
8656         ln $(SRCS) $(AUX) `cat .fname`
8657         -rm -rf `cat .fname` .fname
8658         tar chZf `cat .fname`.tar.Z `cat .fname`
8659 @end group
8661 @group
8662 tar.zoo: $(SRCS) $(AUX)
8663         -rm -rf tmp.dir
8664         -mkdir tmp.dir
8665         -rm tar.zoo
8666         for X in $(SRCS) $(AUX) ; do \
8667             echo $$X ; \
8668             sed 's/$$/^M/' $$X \
8669             > tmp.dir/$$X ; done
8670         cd tmp.dir ; zoo aM ../tar.zoo *
8671         -rm -rf tmp.dir
8672 @end group
8673 @end example
8675 @node Concept Index, Name Index, Complex Makefile, Top
8676 @unnumbered Index of Concepts
8678 @printindex cp
8680 @node Name Index,  , Concept Index, Top
8681 @unnumbered Index of Functions, Variables, & Directives
8683 @printindex fn
8685 @summarycontents
8686 @contents
8687 @bye