Remove check for `sysconf (_SC_OPEN_MAX)'.
[make.git] / make.texinfo
blob04bd8a3a9299150b799b4e376c55a134b16e4cb8
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 RCSID $Id: make.texinfo,v 2.155 1995/10/10 20:18:24 roland Exp $
11 @set EDITION 0.49
12 @set VERSION 3.74 Beta
13 @set UPDATED 14 August 1995
14 @set UPDATE-MONTH August 1995
15 @comment The ISBN number might need to change on next publication.
16 @set ISBN 1-882114-78-7
18 @c finalout
20 @c ISPELL CHECK: done, 10 June 1993 --roland
22 @c Combine the variable and function indices:
23 @syncodeindex vr fn
24 @c Combine the program and concept indices:
25 @syncodeindex pg cp
27 @ifinfo
28 This file documents the GNU Make utility, which determines
29 automatically which pieces of a large program need to be recompiled,
30 and issues the commands to recompile them.
32 This is Edition @value{EDITION}, last updated @value{UPDATED},
33 of @cite{The GNU Make Manual}, for @code{make}, Version @value{VERSION}.
35 Copyright (C) 1988, '89, '90, '91, '92, '93, '94, '95
36         Free Software Foundation, Inc.
38 Permission is granted to make and distribute verbatim copies of
39 this manual provided the copyright notice and this permission notice
40 are preserved on all copies.
42 @ignore
43 Permission is granted to process this file through TeX and print the
44 results, provided the printed document carries copying permission
45 notice identical to this one except for the removal of this paragraph
46 (this paragraph not being relevant to the printed manual).
48 @end ignore
49 Permission is granted to copy and distribute modified versions of this
50 manual under the conditions for verbatim copying, provided that the entire
51 resulting derived work is distributed under the terms of a permission
52 notice identical to this one.
54 Permission is granted to copy and distribute translations of this manual
55 into another language, under the above conditions for modified versions,
56 except that this permission notice may be stated in a translation approved
57 by the Free Software Foundation.
58 @end ifinfo
60 @iftex
61 @shorttitlepage GNU Make
62 @end iftex
63 @titlepage
64 @title GNU Make
65 @subtitle A Program for Directing Recompilation
66 @subtitle Edition @value{EDITION}, for @code{make} Version @value{VERSION}.
67 @subtitle @value{UPDATE-MONTH}
68 @author Richard M. Stallman and Roland McGrath
69 @page
70 @vskip 0pt plus 1filll
71 Copyright @copyright{} 1988, '89, '90, '91, '92, '93, '94, '95 Free Software Foundation, Inc.
72 @sp 2
73 Published by the Free Software Foundation @*
74 59 Temple Place -- Suite 330, @*
75 Boston, MA 02111-1307 USA @*
76 Printed copies are available for $20 each. @*
77 ISBN @value{ISBN} @*
79 Permission is granted to make and distribute verbatim copies of
80 this manual provided the copyright notice and this permission notice
81 are preserved on all copies.
83 Permission is granted to copy and distribute modified versions of this
84 manual under the conditions for verbatim copying, provided that the entire
85 resulting derived work is distributed under the terms of a permission
86 notice identical to this one.
88 Permission is granted to copy and distribute translations of this manual
89 into another language, under the above conditions for modified versions,
90 except that this permission notice may be stated in a translation approved
91 by the Free Software Foundation.
92 @sp 2
93 Cover art by Etienne Suvasa.
94 @end titlepage
95 @page
97 @ifinfo
98 @node Top, Overview, (dir), (dir)
99 @top Make
101 The GNU @code{make} utility automatically determines which pieces of a
102 large program need to be recompiled, and issues the commands to
103 recompile them.@refill
105 This is Edition @value{EDITION} of the @cite{GNU Make Manual},
106 last updated @value{UPDATED}
107 for @code{make} Version @value{VERSION}.@refill
109 This manual describes @code{make} and contains the following chapters:@refill
110 @end ifinfo
112 @menu
113 * Overview::                    Overview of @code{make}.
114 * Introduction::                An introduction to @code{make}.
115 * Makefiles::                   Makefiles tell @code{make} what to do.
116 * Rules::                       Rules describe when a file must be remade.
117 * Commands::                    Commands say how to remake a file.
118 * Using Variables::             You can use variables to avoid repetition.
119 * Conditionals::                Use or ignore parts of the makefile based
120                                  on the values of variables.
121 * Functions::                   Many powerful ways to manipulate text.
122 * make Invocation: Running.     How to invoke @code{make} on the command line.
123 * Implicit Rules::              Use implicit rules to treat many files alike,
124                                  based on their file names.
125 * Archives::                    How @code{make} can update library archives.
126 * Features::                    Features GNU @code{make} has over other @code{make}s.
127 * Missing::                     What GNU @code{make} lacks from other @code{make}s.
128 * Makefile Conventions::        Conventions for makefiles in GNU programs.
129 * Quick Reference::             A quick reference for experienced users.
130 * Complex Makefile::            A real example of a straightforward,
131                                  but nontrivial, makefile.
132 * Concept Index::               Index of Concepts
133 * Name Index::                  Index of Functions, Variables, & Directives
135  --- The Detailed Node Listing ---
137 Overview of @code{make}
139 * Preparing::                   Preparing and Running Make
140 * Reading::                     On Reading this Text
141 * Bugs::                        Problems and Bugs
143 An Introduction to Makefiles
145 * Rule Introduction::           What a rule looks like.
146 * Simple Makefile::             A Simple Makefile
147 * How Make Works::              How @code{make} Processes This Makefile
148 * Variables Simplify::          Variables Make Makefiles Simpler
149 * make Deduces::                Letting @code{make} Deduce the Commands
150 * Combine By Dependency::       Another Style of Makefile
151 * Cleanup::                     Rules for Cleaning the Directory
153 Writing Makefiles
155 * Makefile Contents::           What makefiles contain.
156 * Makefile Names::              How to name your makefile.
157 * Include::                     How one makefile can use another makefile.
158 * MAKEFILES Variable::          The environment can specify extra makefiles.
159 * Remaking Makefiles::          How makefiles get remade.
160 * Overriding Makefiles::        How to override part of one makefile
161                                  with another makefile.
163 Writing Rules
165 * Rule Example::                An example explained.
166 * Rule Syntax::                 General syntax explained.
167 * Wildcards::                   Using wildcard characters such as `*'.
168 * Directory Search::            Searching other directories for source files.
169 * Phony Targets::               Using a target that is not a real file's name.
170 * Force Targets::               You can use a target without commands
171                                   or dependencies to mark other 
172                                   targets as phony.
173 * Empty Targets::               When only the date matters and the
174                                   files are empty.
175 * Special Targets::             Targets with special built-in meanings.
176 * Multiple Targets::            When to make use of several targets in a rule.
177 * Multiple Rules::              How to use several rules with the same target.
178 * Static Pattern::              Static pattern rules apply to multiple targets
179                                   and can vary the dependencies according to 
180                                   the target name.
181 * Double-Colon::                How to use a special kind of rule to allow
182                                   several independent rules for one target.
183 * Automatic Dependencies::      How to automatically generate rules giving
184                                  dependencies from the source files themselves.
186 Using Wildcard Characters in File Names
188 * Wildcard Examples::           Several examples
189 * Wildcard Pitfall::            Problems to avoid.
190 * Wildcard Function::           How to cause wildcard expansion where
191                                   it does not normally take place.
193 Searching Directories for Dependencies
195 * General Search::              Specifying a search path that applies 
196                                   to every dependency.
197 * Selective Search::            Specifying a search path 
198                                   for a specified class of names.
199 * Commands/Search::             How to write shell commands that work together
200                                   with search paths.
201 * Implicit/Search::             How search paths affect implicit rules.
202 * Libraries/Search::            Directory search for link libraries.
204 Static Pattern Rules
206 * Static Usage::                The syntax of static pattern rules.
207 * Static versus Implicit::      When are they better than implicit rules?
209 Writing the Commands in Rules
211 * Echoing::                     How to control when commands are echoed.
212 * Execution::                   How commands are executed.
213 * Parallel::                    How commands can be executed in parallel.
214 * Errors::                      What happens after a command execution error. 
215 * Interrupts::                  What happens when a command is interrupted.
216 * Recursion::                   Invoking @code{make} from makefiles.
217 * Sequences::                   Defining canned sequences of commands.
218 * Empty Commands::              Defining useful, do-nothing commands.
220 Recursive Use of @code{make}
222 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
223 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
224 * Options/Recursion::           How to communicate options to a sub-@code{make}.
225 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
226                                  helps debug use of recursive @code{make} commands.
228 How to Use Variables
230 * Reference::                   How to use the value of a variable.
231 * Flavors::                     Variables come in two flavors.
232 * Advanced::                    Advanced features for referencing a variable.
233 * Values::                      All the ways variables get their values.
234 * Setting::                     How to set a variable in the makefile.
235 * Appending::                   How to append more text to the old value
236                                   of a variable.
237 * Override Directive::          How to set a variable in the makefile even if
238                                   the user has set it with a command argument.
239 * Defining::                    An alternate way to set a variable 
240                                   to a verbatim string.
241 * Environment::                 Variable values can come from the environment.
243 Advanced Features for Reference to Variables
245 * Substitution Refs::           Referencing a variable with 
246                                   substitutions on the value.
247 * Computed Names::              Computing the name of the variable to refer to.
249 Conditional Parts of Makefiles
251 * Conditional Example::         Example of a conditional
252 * Conditional Syntax::          The syntax of conditionals.
253 * Testing Flags::               Conditionals that test flags.
255 Functions for Transforming Text
257 * Syntax of Functions::         How to write a function call.
258 * Text Functions::              General-purpose text manipulation functions.
259 * Filename Functions::          Functions for manipulating file names.
260 * Foreach Function::            Repeat some text with controlled variation.
261 * Origin Function::             Find where a variable got its value.
262 * Shell Function::              Substitute the output of a shell command.
264 How to Run @code{make}
266 * Makefile Arguments::          How to specify which makefile to use.
267 * Goals::                       How to use goal arguments to specify which 
268                                   parts of the makefile to use.
269 * Instead of Execution::        How to use mode flags to specify what
270                                   kind of thing to do with the commands 
271                                   in the makefile other than simply 
272                                   execute them.
273 * Avoiding Compilation::        How to avoid recompiling certain files.
274 * Overriding::                  How to override a variable to specify 
275                                   an alternate compiler and other things.
276 * Testing::                     How to proceed past some errors, to 
277                                   test compilation.
278 * Options Summary::             Summary of Options
280 Using Implicit Rules
282 * Using Implicit::              How to use an existing implicit rule
283                                   to get the commands for updating a file.
284 * Catalogue of Rules::          A list of built-in implicit rules.
285 * Implicit Variables::          How to change what predefined rules do.
286 * Chained Rules::               How to use a chain of implicit rules.
287 * Pattern Rules::               How to define new implicit rules.
288 * Last Resort::                 How to defining commands for rules 
289                                   which cannot find any.
290 * Suffix Rules::                The old-fashioned style of implicit rule.
291 * Search Algorithm::            The precise algorithm for applying 
292                                   implicit rules.
294 Defining and Redefining Pattern Rules
296 * Pattern Intro::               An introduction to pattern rules.
297 * Pattern Examples::            Examples of pattern rules.
298 * Automatic::                   How to use automatic variables in the
299                                   commands of implicit rules.
300 * Pattern Match::               How patterns match.
301 * Match-Anything Rules::        Precautions you should take prior to
302                                   defining rules that can match any
303                                   target file whatever.
304 * Canceling Rules::             How to override or cancel built-in rules.
306 Using @code{make} to Update Archive Files
308 * Archive Members::             Archive members as targets.
309 * Archive Update::              The implicit rule for archive member targets.
310 * Archive Suffix Rules::        You can write a special kind of suffix rule
311                                   for updating archives.
313 Implicit Rule for Archive Member Targets
315 * Archive Symbols::             How to update archive symbol directories.
316 @end menu
318 @node Overview, Introduction, Top, Top
319 @comment  node-name,  next,  previous,  up
320 @chapter Overview of @code{make}
322 The @code{make} utility automatically determines which pieces of a large
323 program need to be recompiled, and issues commands to recompile them.
324 This manual describes GNU @code{make}, which was implemented by Richard
325 Stallman and Roland McGrath.  GNU @code{make} conforms to section 6.2 of
326 @cite{IEEE Standard 1003.2-1992} (POSIX.2).
327 @cindex POSIX
328 @cindex IEEE Standard 1003.2
329 @cindex standards conformance
331 Our examples show C programs, since they are most common, but you can use
332 @code{make} with any programming language whose compiler can be run with a
333 shell command.  Indeed, @code{make} is not limited to programs.  You can
334 use it to describe any task where some files must be updated automatically
335 from others whenever the others change.
337 @menu
338 * Preparing::                   Preparing and Running Make
339 * Reading::                     On Reading this Text
340 * Bugs::                        Problems and Bugs
341 @end menu
343 @node Preparing, Reading,  , Overview
344 @ifinfo
345 @heading Preparing and Running Make
346 @end ifinfo
348 To prepare to use @code{make}, you must write a file called
349 the @dfn{makefile} that describes the relationships among files
350 in your program and provides commands for updating each file.
351 In a program, typically, the executable file is updated from object
352 files, which are in turn made by compiling source files.@refill
354 Once a suitable makefile exists, each time you change some source files,
355 this simple shell command:
357 @example
358 make
359 @end example
361 @noindent
362 suffices to perform all necessary recompilations.  The @code{make} program
363 uses the makefile data base and the last-modification times of the files to
364 decide which of the files need to be updated.  For each of those files, it
365 issues the commands recorded in the data base.
367 You can provide command line arguments to @code{make} to control which
368 files should be recompiled, or how.  @xref{Running, ,How to Run
369 @code{make}}.
371 @node Reading, Bugs, Preparing, Overview
372 @section How to Read This Manual
374 If you are new to @code{make}, or are looking for a general
375 introduction, read the first few sections of each chapter, skipping the
376 later sections.  In each chapter, the first few sections contain
377 introductory or general information and the later sections contain
378 specialized or technical information.
379 @ifinfo        
380 The exception is the second chapter, @ref{Introduction, ,An
381 Introduction to Makefiles}, all of which is introductory.
382 @end ifinfo
383 @iftex 
384 The exception is @ref{Introduction, ,An Introduction to Makefiles},
385 all of which is introductory.
386 @end iftex
388 If you are familiar with other @code{make} programs, see @ref{Features,
389 ,Features of GNU @code{make}}, which lists the enhancements GNU
390 @code{make} has, and @ref{Missing, ,Incompatibilities and Missing
391 Features}, which explains the few things GNU @code{make} lacks that
392 others have.
394 For a quick summary, see @ref{Options Summary}, @ref{Quick Reference},
395 and @ref{Special Targets}.
397 @node Bugs,  , Reading, Overview
398 @section Problems and Bugs
399 @cindex reporting bugs
400 @cindex bugs, reporting
401 @cindex problems and bugs, reporting
403 If you have problems with GNU @code{make} or think you've found a bug,
404 please report it to the developers; we cannot promise to do anything but
405 we might well want to fix it.
407 Before reporting a bug, make sure you've actually found a real bug.
408 Carefully reread the documentation and see if it really says you can do
409 what you're trying to do.  If it's not clear whether you should be able
410 to do something or not, report that too; it's a bug in the
411 documentation!
413 Before reporting a bug or trying to fix it yourself, try to isolate it
414 to the smallest possible makefile that reproduces the problem.  Then
415 send us the makefile and the exact results @code{make} gave you.  Also
416 say what you expected to occur; this will help us decide whether the
417 problem was really in the documentation.
419 Once you've got a precise problem, please send electronic mail either
420 through the Internet or via UUCP:
422 @example
423 @group
424 @r{Internet address:}
425     bug-gnu-utils@@prep.ai.mit.edu
427 @r{UUCP path:}
428     mit-eddie!prep.ai.mit.edu!bug-gnu-utils
429 @end group
430 @end example
432 @noindent
433 Please include the version number of @code{make} you are using.  You can
434 get this information with the command @samp{make --version}.
435 Be sure also to include the type of machine and operating system you are
436 using.  If possible, include the contents of the file @file{config.h}
437 that is generated by the configuration process.
439 @node Introduction, Makefiles, Overview, Top
440 @comment  node-name,  next,  previous,  up
441 @chapter An Introduction to Makefiles
443 You need a file called a @dfn{makefile} to tell @code{make} what to do.
444 Most often, the makefile tells @code{make} how to compile and link a
445 program.
446 @cindex makefile
448 In this chapter, we will discuss a simple makefile that describes how to
449 compile and link a text editor which consists of eight C source files
450 and three header files.  The makefile can also tell @code{make} how to
451 run miscellaneous commands when explicitly asked (for example, to remove
452 certain files as a clean-up operation).  To see a more complex example
453 of a makefile, see @ref{Complex Makefile}.
455 When @code{make} recompiles the editor, each changed C source file
456 must be recompiled.  If a header file has changed, each C source file
457 that includes the header file must be recompiled to be safe.  Each
458 compilation produces an object file corresponding to the source file.
459 Finally, if any source file has been recompiled, all the object files,
460 whether newly made or saved from previous compilations, must be linked
461 together to produce the new executable editor.
462 @cindex recompilation
463 @cindex editor
465 @menu
466 * Rule Introduction::           What a rule looks like.
467 * Simple Makefile::             A Simple Makefile
468 * How Make Works::              How @code{make} Processes This Makefile
469 * Variables Simplify::          Variables Make Makefiles Simpler
470 * make Deduces::                Letting @code{make} Deduce the Commands
471 * Combine By Dependency::       Another Style of Makefile
472 * Cleanup::                     Rules for Cleaning the Directory
473 @end menu
475 @node Rule Introduction, Simple Makefile,  , Introduction
476 @comment  node-name,  next,  previous,  up
477 @section What a Rule Looks Like
478 @cindex rule, introduction to
479 @cindex makefile rule parts
480 @cindex parts of makefile rule
482 A simple makefile consists of ``rules'' with the following shape:
484 @cindex targets, introduction to
485 @cindex dependencies, introduction to
486 @cindex commands, introduction to
487 @example
488 @group
489 @var{target} @dots{} : @var{dependencies} @dots{}
490         @var{command}
491         @dots{}
492         @dots{}
493 @end group
494 @end example
496 A @dfn{target} is usually the name of a file that is generated by a
497 program; examples of targets are executable or object files.  A target
498 can also be the name of an action to carry out, such as @samp{clean}
499 (@pxref{Phony Targets}).
501 A @dfn{dependency} is a file that is used as input to create the
502 target.  A target often depends on several files.  
504 @cindex tabs in rules
505 A @dfn{command} is an action that @code{make} carries out.
506 A rule may have more than one command, each on its own line.
507 @strong{Please note:} you need to put a tab character at the beginning of
508 every command line!  This is an obscurity that catches the unwary.
510 Usually a command is in a rule with dependencies and serves to create a
511 target file if any of the dependencies change.  However, the rule that
512 specifies commands for the target need not have dependencies.  For
513 example, the rule containing the delete command associated with the
514 target @samp{clean} does not have dependencies.
516 A @dfn{rule}, then, explains how and when to remake certain files
517 which are the targets of the particular rule.  @code{make} carries out
518 the commands on the dependencies to create or update the target.  A
519 rule can also explain how and when to carry out an action.
520 @xref{Rules, , Writing Rules}.
522 A makefile may contain other text besides rules, but a simple makefile
523 need only contain rules.  Rules may look somewhat more complicated
524 than shown in this template, but all fit the pattern more or less.
526 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
527 @section A Simple Makefile
528 @cindex simple makefile
529 @cindex makefile, simple
531 Here is a straightforward makefile that describes the way an
532 executable file called @code{edit} depends on eight object files
533 which, in turn, depend on eight C source and three header files.
535 In this example, all the C files include @file{defs.h}, but only those
536 defining editing commands include @file{command.h}, and only low
537 level files that change the editor buffer include @file{buffer.h}.
539 @example
540 @group
541 edit : main.o kbd.o command.o display.o \
542        insert.o search.o files.o utils.o
543         cc -o edit main.o kbd.o command.o display.o \
544                    insert.o search.o files.o utils.o
546 main.o : main.c defs.h
547         cc -c main.c
548 kbd.o : kbd.c defs.h command.h
549         cc -c kbd.c
550 command.o : command.c defs.h command.h
551         cc -c command.c
552 display.o : display.c defs.h buffer.h
553         cc -c display.c
554 insert.o : insert.c defs.h buffer.h
555         cc -c insert.c
556 search.o : search.c defs.h buffer.h
557         cc -c search.c
558 files.o : files.c defs.h buffer.h command.h
559         cc -c files.c
560 utils.o : utils.c defs.h
561         cc -c utils.c
562 clean :
563         rm edit main.o kbd.o command.o display.o \
564            insert.o search.o files.o utils.o
565 @end group
566 @end example
568 @noindent
569 We split each long line into two lines using backslash-newline; this is
570 like using one long line, but is easier to read.
571 @cindex continuation lines
572 @cindex @code{\} (backslash), for continuation lines
573 @cindex backslash (@code{\}), for continuation lines
574 @cindex quoting newline, in makefile
575 @cindex newline, quoting, in makefile
577 To use this makefile to create the executable file called @file{edit},
578 type:
580 @example
581 make
582 @end example
584 To use this makefile to delete the executable file and all the object
585 files from the directory, type:
587 @example
588 make clean
589 @end example
591 In the example makefile, the targets include the executable file
592 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
593 dependencies are files such as @samp{main.c} and @samp{defs.h}.
594 In fact, each @samp{.o} file is both a target and a dependency.
595 Commands include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
597 When a target is a file, it needs to be recompiled or relinked if any
598 of its dependencies change.  In addition, any dependencies that are
599 themselves automatically generated should be updated first.  In this
600 example, @file{edit} depends on each of the eight object files; the
601 object file @file{main.o} depends on the source file @file{main.c} and
602 on the header file @file{defs.h}.  
604 A shell command follows each line that contains a target and
605 dependencies.  These shell commands say how to update the target file.
606 A tab character must come at the beginning of every command line to
607 distinguish commands lines from other lines in the makefile.  (Bear in
608 mind that @code{make} does not know anything about how the commands
609 work.  It is up to you to supply commands that will update the target
610 file properly.  All @code{make} does is execute the commands in the rule
611 you have specified when the target file needs to be updated.)
612 @cindex shell command
614 The target @samp{clean} is not a file, but merely the name of an
615 action.  Since you 
616 normally
617 do not want to carry out the actions in this rule, @samp{clean} is not a dependency of any other rule.
618 Consequently, @code{make} never does anything with it unless you tell
619 it specifically.  Note that this rule not only is not a dependency, it
620 also does not have any dependencies, so the only purpose of the rule
621 is to run the specified commands.  Targets that do not refer to files
622 but are just actions are called @dfn{phony targets}.  @xref{Phony
623 Targets}, for information about this kind of target.  @xref{Errors, ,
624 Errors in Commands}, to see how to cause @code{make} to ignore errors
625 from @code{rm} or any other command.
626 @cindex @code{clean} target
627 @cindex @code{rm} (shell command)
629 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
630 @comment  node-name,  next,  previous,  up
631 @section How @code{make} Processes a Makefile
632 @cindex processing a makefile
633 @cindex makefile, how @code{make} processes
635 By default, @code{make} starts with the first target (not targets whose
636 names start with @samp{.}).  This is called the @dfn{default goal}.
637 (@dfn{Goals} are the targets that @code{make} strives ultimately to
638 update.  @xref{Goals, , Arguments to Specify the Goals}.)
639 @cindex default goal
640 @cindex goal, default
641 @cindex goal
643 In the simple example of the previous section, the default goal is to
644 update the executable program @file{edit}; therefore, we put that rule
645 first.
647 Thus, when you give the command:
649 @example
650 make
651 @end example
653 @noindent
654 @code{make} reads the makefile in the current directory and begins by
655 processing the first rule.  In the example, this rule is for relinking
656 @file{edit}; but before @code{make} can fully process this rule, it
657 must process the rules for the files that @file{edit} depends on,
658 which in this case are the object files.  Each of these files is
659 processed according to its own rule.  These rules say to update each
660 @samp{.o} file by compiling its source file.  The recompilation must
661 be done if the source file, or any of the header files named as
662 dependencies, is more recent than the object file, or if the object
663 file does not exist.
665 The other rules are processed because their targets appear as
666 dependencies of the goal.  If some other rule is not depended on by the
667 goal (or anything it depends on, etc.), that rule is not processed,
668 unless you tell @code{make} to do so (with a command such as
669 @w{@code{make clean}}).
671 Before recompiling an object file, @code{make} considers updating its
672 dependencies, the source file and header files.  This makefile does not
673 specify anything to be done for them---the @samp{.c} and @samp{.h} files
674 are not the targets of any rules---so @code{make} does nothing for these
675 files.  But @code{make} would update automatically generated C programs,
676 such as those made by Bison or Yacc, by their own rules at this time.
678 After recompiling whichever object files need it, @code{make} decides
679 whether to relink @file{edit}.  This must be done if the file
680 @file{edit} does not exist, or if any of the object files are newer than
681 it.  If an object file was just recompiled, it is now newer than
682 @file{edit}, so @file{edit} is relinked.
683 @cindex relinking
685 Thus, if we change the file @file{insert.c} and run @code{make},
686 @code{make} will compile that file to update @file{insert.o}, and then
687 link @file{edit}.  If we change the file @file{command.h} and run
688 @code{make}, @code{make} will recompile the object files @file{kbd.o},
689 @file{command.o} and @file{files.o} and then link the file @file{edit}.
691 @node Variables Simplify, make Deduces, How Make Works, Introduction
692 @section Variables Make Makefiles Simpler
693 @cindex variables
694 @cindex simplifying with variables
696 In our example, we had to list all the object files twice in the rule for
697 @file{edit} (repeated here):
699 @example
700 @group
701 edit : main.o kbd.o command.o display.o \
702               insert.o search.o files.o utils.o
703         cc -o edit main.o kbd.o command.o display.o \
704                    insert.o search.o files.o utils.o
705 @end group
706 @end example
708 @cindex @code{objects}
709 Such duplication is error-prone; if a new object file is added to the
710 system, we might add it to one list and forget the other.  We can eliminate
711 the risk and simplify the makefile by using a variable.  @dfn{Variables}
712 allow a text string to be defined once and substituted in multiple places
713 later (@pxref{Using Variables, ,How to Use Variables}).
715 @cindex @code{OBJECTS}
716 @cindex @code{objs}
717 @cindex @code{OBJS}
718 @cindex @code{obj}
719 @cindex @code{OBJ}
720 It is standard practice for every makefile to have a variable named
721 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
722 or @code{OBJ} which is a list of all object file names.  We would
723 define such a variable @code{objects} with a line like this in the
724 makefile:@refill
726 @example
727 @group
728 objects = main.o kbd.o command.o display.o \
729           insert.o search.o files.o utils.o
730 @end group
731 @end example
733 @noindent
734 Then, each place we want to put a list of the object file names, we can
735 substitute the variable's value by writing @samp{$(objects)}
736 (@pxref{Using Variables, ,How to Use Variables}).  
738 Here is how the complete simple makefile looks when you use a variable
739 for the object files:
741 @example
742 @group
743 objects = main.o kbd.o command.o display.o \
744           insert.o search.o files.o utils.o
746 edit : $(objects)
747         cc -o edit $(objects)
748 main.o : main.c defs.h
749         cc -c main.c
750 kbd.o : kbd.c defs.h command.h
751         cc -c kbd.c
752 command.o : command.c defs.h command.h
753         cc -c command.c
754 display.o : display.c defs.h buffer.h
755         cc -c display.c
756 insert.o : insert.c defs.h buffer.h
757         cc -c insert.c
758 search.o : search.c defs.h buffer.h
759         cc -c search.c
760 files.o : files.c defs.h buffer.h command.h
761         cc -c files.c
762 utils.o : utils.c defs.h
763         cc -c utils.c
764 clean :
765         rm edit $(objects)
766 @end group
767 @end example
769 @node make Deduces, Combine By Dependency, Variables Simplify, Introduction
770 @section Letting @code{make} Deduce the Commands
771 @cindex deducing commands (implicit rules)
772 @cindex implicit rule, introduction to
773 @cindex rule, implicit, introduction to
775 It is not necessary to spell out the commands for compiling the individual
776 C source files, because @code{make} can figure them out: it has an
777 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
778 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
779 use the command @samp{cc -c main.c -o main.o} to compile @file{main.c} into
780 @file{main.o}.  We can therefore omit the commands from the rules for the
781 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.@refill
783 When a @samp{.c} file is used automatically in this way, it is also
784 automatically added to the list of dependencies.  We can therefore omit
785 the @samp{.c} files from the dependencies, provided we omit the commands.
787 Here is the entire example, with both of these changes, and a variable
788 @code{objects} as suggested above:
790 @example
791 @group
792 objects = main.o kbd.o command.o display.o \
793           insert.o search.o files.o utils.o
795 edit : $(objects)
796         cc -o edit $(objects)
798 main.o : defs.h
799 kbd.o : defs.h command.h
800 command.o : defs.h command.h
801 display.o : defs.h buffer.h
802 insert.o : defs.h buffer.h
803 search.o : defs.h buffer.h
804 files.o : defs.h buffer.h command.h
805 utils.o : defs.h
807 .PHONY : clean
808 clean :
809         -rm edit $(objects)
810 @end group
811 @end example
813 @noindent
814 This is how we would write the makefile in actual practice.  (The
815 complications associated with @samp{clean} are described elsewhere.
816 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Commands}.)
818 Because implicit rules are so convenient, they are important.  You
819 will see them used frequently.@refill
821 @node Combine By Dependency, Cleanup, make Deduces, Introduction
822 @section Another Style of Makefile
823 @cindex combining rules by dependency
825 When the objects of a makefile are created only by implicit rules, an
826 alternative style of makefile is possible.  In this style of makefile,
827 you group entries by their dependencies instead of by their targets.
828 Here is what one looks like:
830 @example
831 @group
832 objects = main.o kbd.o command.o display.o \
833           insert.o search.o files.o utils.o
835 edit : $(objects)
836         cc -o edit $(objects)
838 $(objects) : defs.h
839 kbd.o command.o files.o : command.h
840 display.o insert.o search.o files.o : buffer.h
841 @end group
842 @end example
844 @noindent
845 Here @file{defs.h} is given as a dependency of all the object files;
846 @file{command.h} and @file{buffer.h} are dependencies of the specific
847 object files listed for them.
849 Whether this is better is a matter of taste: it is more compact, but some
850 people dislike it because they find it clearer to put all the information
851 about each target in one place.
853 @node Cleanup,  , Combine By Dependency, Introduction
854 @section Rules for Cleaning the Directory
855 @cindex cleaning up
856 @cindex removing, to clean up
858 Compiling a program is not the only thing you might want to write rules
859 for.  Makefiles commonly tell how to do a few other things besides
860 compiling a program: for example, how to delete all the object files
861 and executables so that the directory is @samp{clean}.
863 @cindex @code{clean} target
864 Here is how we
865 could write a @code{make} rule for cleaning our example editor:
867 @example
868 @group
869 clean:
870         rm edit $(objects)
871 @end group
872 @end example
874 In practice, we might want to write the rule in a somewhat more
875 complicated manner to handle unanticipated situations.  We would do this:
877 @example
878 @group
879 .PHONY : clean
880 clean :
881         -rm edit $(objects)
882 @end group
883 @end example
885 @noindent
886 This prevents @code{make} from getting confused by an actual file
887 called @file{clean} and causes it to continue in spite of errors from
888 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
889 Commands}.)
891 @noindent
892 A rule such as this should not be placed at the beginning of the
893 makefile, because we do not want it to run by default!  Thus, in the
894 example makefile, we want the rule for @code{edit}, which recompiles
895 the editor, to remain the default goal.
897 Since @code{clean} is not a dependency of @code{edit}, this rule will not
898 run at all if we give the command @samp{make} with no arguments.  In
899 order to make the rule run, we have to type @samp{make clean}.
900 @xref{Running, ,How to Run @code{make}}.
902 @node Makefiles, Rules, Introduction, Top
903 @chapter Writing Makefiles
905 @cindex makefile, how to write
906 The information that tells @code{make} how to recompile a system comes from
907 reading a data base called the @dfn{makefile}.
909 @menu
910 * Makefile Contents::           What makefiles contain.
911 * Makefile Names::              How to name your makefile.
912 * Include::                     How one makefile can use another makefile.
913 * MAKEFILES Variable::          The environment can specify extra makefiles.
914 * Remaking Makefiles::          How makefiles get remade.
915 * Overriding Makefiles::        How to override part of one makefile
916                                  with another makefile.
917 @end menu
919 @node Makefile Contents, Makefile Names,  , Makefiles
920 @section What Makefiles Contain
922 Makefiles contain five kinds of things: @dfn{explicit rules},
923 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
924 and @dfn{comments}.  Rules, variables, and directives are described at
925 length in later chapters.@refill
927 @itemize @bullet
928 @cindex rule, explicit, definition of
929 @cindex explicit rule, definition of
930 @item
931 An @dfn{explicit rule} says when and how to remake one or more files,
932 called the rule's targets.  It lists the other files that the targets
933 @dfn{depend on}, and may also give commands to use to create or update
934 the targets.  @xref{Rules, ,Writing Rules}.
936 @cindex rule, implicit, definition of
937 @cindex implicit rule, definition of
938 @item
939 An @dfn{implicit rule} says when and how to remake a class of files
940 based on their names.  It describes how a target may depend on a file
941 with a name similar to the target and gives commands to create or
942 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
944 @cindex variable definition
945 @item
946 A @dfn{variable definition} is a line that specifies a text string
947 value for a variable that can be substituted into the text later.  The
948 simple makefile example shows a variable definition for @code{objects}
949 as a list of all object files (@pxref{Variables Simplify, , Variables
950 Make Makefiles Simpler}).
952 @cindex directive
953 @item
954 A @dfn{directive} is a command for @code{make} to do something special while
955 reading the makefile.  These include:
957 @itemize @bullet
958 @item
959 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
961 @item
962 Deciding (based on the values of variables) whether to use or
963 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
965 @item
966 Defining a variable from a verbatim string containing multiple lines
967 (@pxref{Defining, ,Defining Variables Verbatim}).
968 @end itemize
970 @cindex comments, in makefile
971 @cindex @code{#} (comments), in makefile
972 @item
973 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the rest of
974 the line are ignored, except that a trailing backslash not escaped by
975 another backslash will continue the comment across multiple lines.
976 Comments may appear on any of the lines in the makefile, except within a
977 @code{define} directive, and perhaps within commands (where the shell
978 decides what is a comment).  A line containing just a comment (with
979 perhaps spaces before it) is effectively blank, and is ignored.@refill
980 @end itemize
982 @node Makefile Names, Include, Makefile Contents, Makefiles
983 @section What Name to Give Your Makefile
984 @cindex makefile name
985 @cindex name of makefile
986 @cindex default makefile name
987 @cindex file name of makefile
989 @c following paragraph rewritten to avoid overfull hbox
990 By default, when @code{make} looks for the makefile, it tries the
991 following names, in order: @file{GNUmakefile}, @file{makefile}
992 and @file{Makefile}.@refill
993 @findex Makefile
994 @findex GNUmakefile
995 @findex makefile
997 @cindex @code{README}
998 Normally you should call your makefile either @file{makefile} or
999 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1000 prominently near the beginning of a directory listing, right near other
1001 important files such as @file{README}.)  The first name checked,
1002 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1003 use this name if you have a makefile that is specific to GNU
1004 @code{make}, and will not be understood by other versions of
1005 @code{make}.  Other @code{make} programs look for @file{makefile} and
1006 @file{Makefile}, but not @file{GNUmakefile}.
1008 If @code{make} finds none of these names, it does not use any makefile.
1009 Then you must specify a goal with a command argument, and @code{make}
1010 will attempt to figure out how to remake it using only its built-in
1011 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1013 @cindex @code{-f}
1014 @cindex @code{--file}
1015 @cindex @code{--makefile}
1016 If you want to use a nonstandard name for your makefile, you can specify
1017 the makefile name with the @samp{-f} or @samp{--file} option.  The
1018 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1019 @code{make} to read the file @var{name} as the makefile.  If you use
1020 more than one @samp{-f} or @samp{--file} option, you can specify several
1021 makefiles.  All the makefiles are effectively concatenated in the order
1022 specified.  The default makefile names @file{GNUmakefile},
1023 @file{makefile} and @file{Makefile} are not checked automatically if you
1024 specify @samp{-f} or @samp{--file}.@refill
1025 @cindex specifying makefile name
1026 @cindex makefile name, how to specify
1027 @cindex name of makefile, how to specify
1028 @cindex file name of makefile, how to specify
1030 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1031 @section Including Other Makefiles
1032 @cindex including other makefiles
1033 @cindex makefile, including
1035 @findex include
1036 The @code{include} directive tells @code{make} to suspend reading the
1037 current makefile and read one or more other makefiles before continuing.
1038 The directive is a line in the makefile that looks like this:
1040 @example
1041 include @var{filenames}@dots{}
1042 @end example
1044 @noindent
1045 @var{filenames} can contain shell file name patterns.
1046 @cindex shell file name pattern (in @code{include})
1047 @cindex shell wildcards (in @code{include})
1048 @cindex wildcard, in @code{include}
1050 Extra spaces are allowed and ignored at the beginning of the line, but
1051 a tab is not allowed.  (If the line begins with a tab, it will be
1052 considered a command line.)  Whitespace is required between
1053 @code{include} and the file names, and between file names; extra
1054 whitespace is ignored there and at the end of the directive.  A
1055 comment starting with @samp{#} is allowed at the end of the line.  If
1056 the file names contain any variable or function references, they are
1057 expanded.  @xref{Using Variables, ,How to Use Variables}.
1059 For example, if you have three @file{.mk} files, @file{a.mk}, 
1060 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1061 @code{bish bash}, then the following expression
1063 @example
1064 include foo *.mk $(bar)
1065 @end example
1067 is equivalent to
1069 @example
1070 include foo a.mk b.mk c.mk bish bash
1071 @end example
1073 When @code{make} processes an @code{include} directive, it suspends
1074 reading of the containing makefile and reads from each listed file in
1075 turn.  When that is finished, @code{make} resumes reading the
1076 makefile in which the directive appears.
1078 One occasion for using @code{include} directives is when several programs,
1079 handled by individual makefiles in various directories, need to use a
1080 common set of variable definitions 
1081 (@pxref{Setting, ,Setting Variables}) or pattern rules
1082 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1084 Another such occasion is when you want to generate dependencies from
1085 source files automatically; the dependencies can be put in a file that
1086 is included by the main makefile.  This practice is generally cleaner
1087 than that of somehow appending the dependencies to the end of the main
1088 makefile as has been traditionally done with other versions of
1089 @code{make}.  @xref{Automatic Dependencies}.
1090 @cindex dependencies, automatic generation
1091 @cindex automatic generation of dependencies
1092 @cindex generating dependencies automatically
1094 @cindex @code{-I}
1095 @cindex @code{--include-dir}
1096 @findex /usr/gnu/include
1097 @findex /usr/local/include
1098 @findex /usr/include
1099 If the specified name does not start with a slash, and the file is not
1100 found in the current directory, several other directories are searched.
1101 First, any directories you have specified with the @samp{-I} or
1102 @samp{--include-dir} option are searched
1103 (@pxref{Options Summary, ,Summary of Options}).
1104 Then the following directories (if they exist)
1105 are searched, in this order: 
1106 @file{@var{prefix}/include} (normally @file{/usr/local/include})
1107 @file{/usr/gnu/include},
1108 @file{/usr/local/include}, @file{/usr/include}.  
1110 If an included makefile cannot be found in any of these directories, a
1111 warning message is generated, but it is not an immediately fatal error;
1112 processing of the makefile containing the @code{include} continues.
1113 Once it has finished reading makefiles, @code{make} will try to remake
1114 any that are out of date or don't exist.
1115 @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
1116 Only after it has tried to find a way to remake a makefile and failed,
1117 will @code{make} diagnose the missing makefile as a fatal error.
1119 If you want @code{make} to simply ignore a makefile which does not exist
1120 and cannot be remade, with no error message, use the @w{@code{-include}}
1121 directive instead of @code{include}, like this:
1123 @example
1124 -include @var{filenames}@dots{}
1125 @end example
1127 This is acts like @code{include} in every way except that there is no
1128 error (not even a warning) if any of the @var{filenames} do not exist.
1130 @node MAKEFILES Variable, Remaking Makefiles, Include, Makefiles
1131 @section The Variable @code{MAKEFILES}
1132 @cindex makefile, and @code{MAKEFILES} variable
1133 @cindex including (@code{MAKEFILES} variable)
1135 @vindex MAKEFILES
1136 If the environment variable @code{MAKEFILES} is defined, @code{make}
1137 considers its value as a list of names (separated by whitespace) of
1138 additional makefiles to be read before the others.  This works much like
1139 the @code{include} directive: various directories are searched for those
1140 files (@pxref{Include, ,Including Other Makefiles}).  In addition, the
1141 default goal is never taken from one of these makefiles and it is not an
1142 error if the files listed in @code{MAKEFILES} are not found.@refill
1144 @cindex recursion, and @code{MAKEFILES} variable
1145 The main use of @code{MAKEFILES} is in communication between recursive
1146 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1147 @code{make}}).  It usually is not desirable to set the environment
1148 variable before a top-level invocation of @code{make}, because it is
1149 usually better not to mess with a makefile from outside.  However, if
1150 you are running @code{make} without a specific makefile, a makefile in
1151 @code{MAKEFILES} can do useful things to help the built-in implicit
1152 rules work better, such as defining search paths (@pxref{Directory Search}).
1154 Some users are tempted to set @code{MAKEFILES} in the environment
1155 automatically on login, and program makefiles to expect this to be done.
1156 This is a very bad idea, because such makefiles will fail to work if run by
1157 anyone else.  It is much better to write explicit @code{include} directives
1158 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1160 @node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
1161 @section How Makefiles Are Remade
1163 @cindex updating makefiles
1164 @cindex remaking makefiles
1165 @cindex makefile, remaking of
1166 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1167 files.  If a makefile can be remade from other files, you probably want
1168 @code{make} to get an up-to-date version of the makefile to read in.
1170 To this end, after reading in all makefiles, @code{make} will consider
1171 each as a goal target and attempt to update it.  If a makefile has a
1172 rule which says how to update it (found either in that very makefile or
1173 in another one) or if an implicit rule applies to it (@pxref{Implicit
1174 Rules, ,Using Implicit Rules}), it will be updated if necessary.  After
1175 all makefiles have been checked, if any have actually been changed,
1176 @code{make} starts with a clean slate and reads all the makefiles over
1177 again.  (It will also attempt to update each of them over again, but
1178 normally this will not change them again, since they are already up to
1179 date.)@refill
1181 If the makefiles specify a double-colon rule to remake a file with
1182 commands but no dependencies, that file will always be remade
1183 (@pxref{Double-Colon}).  In the case of makefiles, a makefile that has a
1184 double-colon rule with commands but no dependencies will be remade every
1185 time @code{make} is run, and then again after @code{make} starts over
1186 and reads the makefiles in again.  This would cause an infinite loop:
1187 @code{make} would constantly remake the makefile, and never do anything
1188 else.  So, to avoid this, @code{make} will @strong{not} attempt to
1189 remake makefiles which are specified as double-colon targets but have no
1190 dependencies.@refill
1192 If you do not specify any makefiles to be read with @samp{-f} or
1193 @samp{--file} options, @code{make} will try the default makefile names;
1194 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1195 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1196 @code{make} is not certain that these makefiles should exist.  However,
1197 if a default makefile does not exist but can be created by running
1198 @code{make} rules, you probably want the rules to be run so that the
1199 makefile can be used.
1201 Therefore, if none of the default makefiles exists, @code{make} will try
1202 to make each of them in the same order in which they are searched for
1203 (@pxref{Makefile Names, ,What Name to Give Your Makefile})
1204 until it succeeds in making one, or it runs out of names to try.  Note
1205 that it is not an error if @code{make} cannot find or make any makefile;
1206 a makefile is not always necessary.@refill
1208 When you use the @samp{-t} or @samp{--touch} option
1209 (@pxref{Instead of Execution, ,Instead of Executing the Commands}),
1210 you would not want to use an out-of-date makefile to decide which
1211 targets to touch.  So the @samp{-t} option has no effect on updating
1212 makefiles; they are really updated even if @samp{-t} is specified.
1213 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1214 @samp{--just-print}) do not prevent updating of makefiles, because an
1215 out-of-date makefile would result in the wrong output for other targets.
1216 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1217 and then print the commands to update @file{foo} and its dependencies
1218 without running them.  The commands printed for @file{foo} will be those
1219 specified in the updated contents of @file{mfile}.
1221 However, on occasion you might actually wish to prevent updating of even
1222 the makefiles.  You can do this by specifying the makefiles as goals in
1223 the command line as well as specifying them as makefiles.  When the
1224 makefile name is specified explicitly as a goal, the options @samp{-t}
1225 and so on do apply to them.
1227 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1228 @file{mfile}, print the commands needed to update it without actually
1229 running them, and then print the commands needed to update @file{foo}
1230 without running them.  The commands for @file{foo} will be those
1231 specified by the existing contents of @file{mfile}.
1233 @node Overriding Makefiles,  , Remaking Makefiles, Makefiles
1234 @section Overriding Part of Another Makefile
1236 @cindex overriding makefiles
1237 @cindex makefile, overriding
1238 Sometimes it is useful to have a makefile that is mostly just like
1239 another makefile.  You can often use the @samp{include} directive to
1240 include one in the other, and add more targets or variable definitions.
1241 However, if the two makefiles give different commands for the same
1242 target, @code{make} will not let you just do this.  But there is another way.
1244 @cindex match-anything rule, used to override
1245 In the containing makefile (the one that wants to include the other),
1246 you can use a match-anything pattern rule to say that to remake any
1247 target that cannot be made from the information in the containing
1248 makefile, @code{make} should look in another makefile.
1249 @xref{Pattern Rules}, for more information on pattern rules.
1251 For example, if you have a makefile called @file{Makefile} that says how
1252 to make the target @samp{foo} (and other targets), you can write a
1253 makefile called @file{GNUmakefile} that contains:
1255 @example
1256 foo:
1257         frobnicate > foo
1259 %: force
1260         @@$(MAKE) -f Makefile $@@
1261 force: ;
1262 @end example
1264 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1265 read it, and see that to make @file{foo}, it needs to run the command
1266 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1267 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1268 commands from the pattern rule: @samp{make -f Makefile bar}.  If
1269 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1270 will apply the rule.  And likewise for any other target that
1271 @file{GNUmakefile} does not say how to make.
1273 The way this works is that the pattern rule has a pattern of just
1274 @samp{%}, so it matches any target whatever.  The rule specifies a
1275 dependency @file{force}, to guarantee that the commands will be run even
1276 if the target file already exists.  We give @file{force} target empty
1277 commands to prevent @code{make} from searching for an implicit rule to
1278 build it---otherwise it would apply the same match-anything rule to
1279 @file{force} itself and create a dependency loop!
1281 @node Rules, Commands, Makefiles, Top
1282 @chapter Writing Rules
1283 @cindex writing rules
1284 @cindex rule, how to write
1285 @cindex target
1286 @cindex dependency
1288 A @dfn{rule} appears in the makefile and says when and how to remake
1289 certain files, called the rule's @dfn{targets} (most often only one per rule).
1290 It lists the other files that are the @dfn{dependencies} of the target, and
1291 @dfn{commands} to use to create or update the target.
1293 @cindex default goal
1294 @cindex goal, default
1295 The order of rules is not significant, except for determining the
1296 @dfn{default goal}: the target for @code{make} to consider, if you do
1297 not otherwise specify one.  The default goal is the target of the first
1298 rule in the first makefile.  If the first rule has multiple targets,
1299 only the first target is taken as the default.  There are two
1300 exceptions: a target starting with a period is not a default unless it
1301 contains one or more slashes, @samp{/}, as well; and, a target that
1302 defines a pattern rule has no effect on the default goal.
1303 (@xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.)
1305 Therefore, we usually write the makefile so that the first rule is the
1306 one for compiling the entire program or all the programs described by
1307 the makefile (often with a target called @samp{all}).
1308 @xref{Goals, ,Arguments to Specify the Goals}.
1310 @menu
1311 * Rule Example::                An example explained.
1312 * Rule Syntax::                 General syntax explained.
1313 * Wildcards::                   Using wildcard characters such as `*'.
1314 * Directory Search::            Searching other directories for source files.
1315 * Phony Targets::               Using a target that is not a real file's name.
1316 * Force Targets::               You can use a target without commands
1317                                   or dependencies to mark other 
1318                                   targets as phony.
1319 * Empty Targets::               When only the date matters and the
1320                                   files are empty.
1321 * Special Targets::             Targets with special built-in meanings.
1322 * Multiple Targets::            When to make use of several targets in a rule.
1323 * Multiple Rules::              How to use several rules with the same target.
1324 * Static Pattern::              Static pattern rules apply to multiple targets
1325                                   and can vary the dependencies according to 
1326                                   the target name.
1327 * Double-Colon::                How to use a special kind of rule to allow
1328                                   several independent rules for one target.
1329 * Automatic Dependencies::      How to automatically generate rules giving
1330                                  dependencies from the source files themselves.
1331 @end menu
1333 @ifinfo
1334 @node Rule Example, Rule Syntax,  , Rules
1335 @section Rule Example
1337 Here is an example of a rule:
1339 @example
1340 foo.o : foo.c defs.h       # module for twiddling the frobs
1341         cc -c -g foo.c
1342 @end example
1344 Its target is @file{foo.o} and its dependencies are @file{foo.c} and
1345 @file{defs.h}.  It has one command, which is @samp{cc -c -g foo.c}.
1346 The command line starts with a tab to identify it as a command.
1348 This rule says two things:
1350 @itemize @bullet
1351 @item
1352 How to decide whether @file{foo.o} is out of date: it is out of date
1353 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1354 more recent than it.
1356 @item
1357 How to update the file @file{foo.o}: by running @code{cc} as stated.
1358 The command does not explicitly mention @file{defs.h}, but we presume
1359 that @file{foo.c} includes it, and that that is why @file{defs.h} was
1360 added to the dependencies.
1361 @end itemize
1362 @end ifinfo
1364 @node Rule Syntax, Wildcards, Rule Example, Rules
1365 @section Rule Syntax
1367 @cindex rule syntax
1368 @cindex syntax of rules
1369 In general, a rule looks like this:
1371 @example
1372 @var{targets} : @var{dependencies}
1373         @var{command}
1374         @dots{}
1375 @end example
1377 @noindent
1378 or like this:
1380 @example
1381 @var{targets} : @var{dependencies} ; @var{command}
1382         @var{command}
1383         @dots{}
1384 @end example
1386 @cindex targets
1387 @cindex rule targets
1388 The @var{targets} are file names, separated by spaces.  Wildcard
1389 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
1390 in File Names}) and a name of the form @file{@var{a}(@var{m})}
1391 represents member @var{m} in archive file @var{a} 
1392 (@pxref{Archive Members, ,Archive Members as Targets}).  
1393 Usually there is only one
1394 target per rule, but occasionally there is a reason to have more
1395 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).@refill
1397 @cindex commands
1398 @cindex tab character (in commands)
1399 The @var{command} lines start with a tab character.  The first command may
1400 appear on the line after the dependencies, with a tab character, or may
1401 appear on the same line, with a semicolon.  Either way, the effect is the
1402 same.  @xref{Commands, ,Writing the Commands in Rules}.
1404 @cindex dollar sign (@code{$}), in rules
1405 @cindex @code{$}, in rules
1406 @cindex rule, and @code{$}
1407 Because dollar signs are used to start variable references, if you really
1408 want a dollar sign in a rule you must write two of them, @samp{$$}
1409 (@pxref{Using Variables, ,How to Use Variables}).  
1410 You may split a long line by inserting a backslash
1411 followed by a newline, but this is not required, as @code{make} places no
1412 limit on the length of a line in a makefile.
1414 A rule tells @code{make} two things: when the targets are out of date,
1415 and how to update them when necessary.
1417 @cindex dependencies
1418 @cindex rule dependencies
1419 The criterion for being out of date is specified in terms of the
1420 @var{dependencies}, which consist of file names separated by spaces.
1421 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
1422 A target is out of date if it does not exist or if it is older than any
1423 of the dependencies (by comparison of last-modification times).  The
1424 idea is that the contents of the target file are computed based on
1425 information in the dependencies, so if any of the dependencies changes,
1426 the contents of the existing target file are no longer necessarily
1427 valid.
1429 How to update is specified by @var{commands}.  These are lines to be
1430 executed by the shell (normally @samp{sh}), but with some extra features
1431 (@pxref{Commands, ,Writing the Commands in Rules}).
1433 @node Wildcards, Directory Search, Rule Syntax, Rules
1434 @section Using Wildcard Characters in File Names
1435 @cindex wildcard
1436 @cindex file name with wildcards
1437 @cindex globbing (wildcards)
1439 @cindex @code{*} (wildcard character)
1440 @cindex @code{?} (wildcard character)
1441 @cindex @code{[@dots{}]} (wildcard characters)
1442 A single file name can specify many files using @dfn{wildcard characters}.
1443 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
1444 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
1445 specifies a list of all the files (in the working directory) whose names
1446 end in @samp{.c}.@refill
1448 @cindex @code{~} (tilde)
1449 @cindex tilde (@code{~})
1450 @cindex home directory
1451 The character @samp{~} at the beginning of a file name also has special
1452 significance.  If alone, or followed by a slash, it represents your home
1453 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
1454 If the @samp{~} is followed by a word, the string represents the home
1455 directory of the user named by that word.  For example @file{~john/bin}
1456 expands to @file{/home/john/bin}.@refill
1458 Wildcard expansion happens automatically in targets, in dependencies,
1459 and in commands (where the shell does the expansion).  In other
1460 contexts, wildcard expansion happens only if you request it explicitly
1461 with the @code{wildcard} function.
1463 The special significance of a wildcard character can be turned off by
1464 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
1465 specific file whose name consists of @samp{foo}, an asterisk, and
1466 @samp{bar}.@refill
1468 @menu
1469 * Wildcard Examples::           Several examples
1470 * Wildcard Pitfall::            Problems to avoid.
1471 * Wildcard Function::           How to cause wildcard expansion where
1472                                   it does not normally take place.
1473 @end menu
1475 @node Wildcard Examples, Wildcard Pitfall,  , Wildcards
1476 @subsection Wildcard Examples
1478 Wildcards can be used in the commands of a rule, where they are expanded
1479 by the shell.  For example, here is a rule to delete all the object files:
1481 @example
1482 @group
1483 clean:
1484         rm -f *.o
1485 @end group
1486 @end example
1487 @cindex @code{rm} (shell command)
1489 Wildcards are also useful in the dependencies of a rule.  With the
1490 following rule in the makefile, @samp{make print} will print all the
1491 @samp{.c} files that have changed since the last time you printed them:
1493 @example
1494 print: *.c
1495         lpr -p $?
1496         touch print
1497 @end example
1499 @cindex @code{print} target
1500 @cindex @code{lpr} (shell command)
1501 @cindex @code{touch} (shell command)
1502 @noindent
1503 This rule uses @file{print} as an empty target file; see @ref{Empty
1504 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
1505 @samp{$?} is used to print only those files that have changed; see
1506 @ref{Automatic, ,Automatic Variables}.)@refill
1508 Wildcard expansion does not happen when you define a variable.  Thus, if
1509 you write this:
1511 @example
1512 objects = *.o
1513 @end example
1515 @noindent
1516 then the value of the variable @code{objects} is the actual string
1517 @samp{*.o}.  However, if you use the value of @code{objects} in a target,
1518 dependency or command, wildcard expansion will take place at that time.
1519 To set @code{objects} to the expansion, instead use:
1521 @example
1522 objects := $(wildcard *.o)
1523 @end example
1525 @noindent
1526 @xref{Wildcard Function}.
1528 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
1529 @subsection Pitfalls of Using Wildcards
1530 @cindex wildcard pitfalls
1531 @cindex pitfalls of wildcards
1532 @cindex mistakes with wildcards
1533 @cindex errors with wildcards
1534 @cindex problems with wildcards
1536 Now here is an example of a naive way of using wildcard expansion, that
1537 does not do what you would intend.  Suppose you would like to say that the
1538 executable file @file{foo} is made from all the object files in the
1539 directory, and you write this:
1541 @example
1542 objects = *.o
1544 foo : $(objects)
1545         cc -o foo $(CFLAGS) $(objects)
1546 @end example
1548 @noindent
1549 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
1550 expansion happens in the rule for @file{foo}, so that each @emph{existing}
1551 @samp{.o} file becomes a dependency of @file{foo} and will be recompiled if
1552 necessary.
1554 But what if you delete all the @samp{.o} files?  When a wildcard matches
1555 no files, it is left as it is, so then @file{foo} will depend on the
1556 oddly-named file @file{*.o}.  Since no such file is likely to exist,
1557 @code{make} will give you an error saying it cannot figure out how to
1558 make @file{*.o}.  This is not what you want!
1560 Actually it is possible to obtain the desired result with wildcard
1561 expansion, but you need more sophisticated techniques, including the
1562 @code{wildcard} function and string substitution.
1563 @ifinfo
1564 @xref{Wildcard Function, ,The Function @code{wildcard}}.
1565 @end ifinfo
1566 @iftex
1567 These are described in the following section.
1568 @end iftex
1570 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
1571 @subsection The Function @code{wildcard}
1572 @findex wildcard
1574 Wildcard expansion happens automatically in rules.  But wildcard expansion
1575 does not normally take place when a variable is set, or inside the
1576 arguments of a function.  If you want to do wildcard expansion in such
1577 places, you need to use the @code{wildcard} function, like this:
1579 @example
1580 $(wildcard @var{pattern}@dots{})
1581 @end example
1583 @noindent
1584 This string, used anywhere in a makefile, is replaced by a
1585 space-separated list of names of existing files that match one of the
1586 given file name patterns.  If no existing file name matches a pattern,
1587 then that pattern is omitted from the output of the @code{wildcard}
1588 function.  Note that this is different from how unmatched wildcards
1589 behave in rules, where they are used verbatim rather than ignored
1590 (@pxref{Wildcard Pitfall}).
1592 One use of the @code{wildcard} function is to get a list of all the C source
1593 files in a directory, like this:
1595 @example
1596 $(wildcard *.c)
1597 @end example
1599 We can change the list of C source files into a list of object files by
1600 replacing the @samp{.o} suffix with @samp{.c} in the result, like this:
1602 @example
1603 $(patsubst %.c,%.o,$(wildcard *.c))
1604 @end example
1606 @noindent
1607 (Here we have used another function, @code{patsubst}.
1608 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)@refill
1610 Thus, a makefile to compile all C source files in the directory and then
1611 link them together could be written as follows:
1613 @example
1614 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1616 foo : $(objects)
1617         cc -o foo $(objects)
1618 @end example
1620 @noindent
1621 (This takes advantage of the implicit rule for compiling C programs, so
1622 there is no need to write explicit rules for compiling the files.
1623 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
1624 @samp{:=}, which is a variant of @samp{=}.)
1626 @node Directory Search, Phony Targets, Wildcards, Rules
1627 @section Searching Directories for Dependencies
1628 @vindex VPATH
1629 @findex vpath
1630 @cindex vpath 
1631 @cindex search path for dependencies (@code{VPATH})
1632 @cindex directory search (@code{VPATH})
1634 For large systems, it is often desirable to put sources in a separate
1635 directory from the binaries.  The @dfn{directory search} features of
1636 @code{make} facilitate this by searching several directories
1637 automatically to find a dependency.  When you redistribute the files
1638 among directories, you do not need to change the individual rules,
1639 just the search paths.
1641 @menu
1642 * General Search::              Specifying a search path that applies 
1643                                   to every dependency.
1644 * Selective Search::            Specifying a search path 
1645                                   for a specified class of names.
1646 * Commands/Search::             How to write shell commands that work together
1647                                   with search paths.
1648 * Implicit/Search::             How search paths affect implicit rules.
1649 * Libraries/Search::            Directory search for link libraries.
1650 @end menu
1652 @node General Search, Selective Search,  , Directory Search
1653 @subsection @code{VPATH}: Search Path for All Dependencies
1654 @vindex VPATH
1656 The value of the @code{make} variable @code{VPATH} specifies a list of
1657 directories that @code{make} should search.  Most often, the
1658 directories are expected to contain dependency files that are not in the
1659 current directory; however, @code{VPATH} specifies a search list that
1660 @code{make} applies for all files, including files which are targets of
1661 rules.
1663 Thus, if a file that is listed as a target or dependency does not exist
1664 in the current directory, @code{make} searches the directories listed in
1665 @code{VPATH} for a file with that name.  If a file is found in one of
1666 them, that file becomes the dependency.  Rules may then specify the
1667 names of source files in the dependencies as if they all existed in the
1668 current directory.  @xref{Commands/Search, ,Writing Shell Commands with
1669 Directory Search}.
1671 In the @code{VPATH} variable, directory names are separated by colons or
1672 blanks.  The order in which directories are listed is the order followed
1673 by @code{make} in its search.
1675 For example,
1677 @example
1678 VPATH = src:../headers
1679 @end example
1681 @noindent
1682 specifies a path containing two directories, @file{src} and
1683 @file{../headers}, which @code{make} searches in that order.
1685 With this value of @code{VPATH}, the following rule,
1687 @example
1688 foo.o : foo.c
1689 @end example
1691 @noindent
1692 is interpreted as if it were written like this:
1694 @example
1695 foo.o : src/foo.c
1696 @end example
1698 @noindent
1699 assuming the file @file{foo.c} does not exist in the current directory but
1700 is found in the directory @file{src}.
1702 @node Selective Search, Commands/Search, General Search, Directory Search
1703 @subsection The @code{vpath} Directive
1704 @findex vpath
1706 Similar to the @code{VPATH} variable but more selective is the @code{vpath}
1707 directive (note lower case), which allows you to specify a search path for a particular class
1708 of file names, those that match a particular pattern.  Thus you can supply
1709 certain search directories for one class of file names and other directories
1710 (or none) for other file names.
1712 There are three forms of the @code{vpath} directive:
1714 @table @code
1715 @item vpath @var{pattern} @var{directories}
1716 Specify the search path @var{directories} for file names that match
1717 @var{pattern}.  
1719 The search path, @var{directories}, is a list of directories to be
1720 searched, separated by colons or blanks, just like the search path used
1721 in the @code{VPATH} variable.
1723 @item vpath @var{pattern}
1724 Clear out the search path associated with @var{pattern}.
1726 @c Extra blank line makes sure this gets two lines.
1727 @item vpath
1729 Clear all search paths previously specified with @code{vpath} directives.
1730 @end table
1732 A @code{vpath} pattern is a string containing a @samp{%} character.  The
1733 string must match the file name of a dependency that is being searched
1734 for, the @samp{%} character matching any sequence of zero or more
1735 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
1736 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
1737 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
1738 dependency exactly, which is not useful very often.)
1740 @cindex @code{%}, quoting in @code{vpath}
1741 @cindex @code{%}, quoting with @code{\} (backslash)
1742 @cindex @code{\} (backslash), to quote @code{%}
1743 @cindex backslash (@code{\}), to quote @code{%}
1744 @cindex quoting @code{%}, in @code{vpath}
1745 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
1746 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
1747 quote @samp{%} characters can be quoted with more backslashes.
1748 Backslashes that quote @samp{%} characters or other backslashes are
1749 removed from the pattern before it is compared to file names.  Backslashes
1750 that are not in danger of quoting @samp{%} characters go unmolested.@refill
1752 When a dependency fails to exist in the current directory, if the
1753 @var{pattern} in a @code{vpath} directive matches the name of the
1754 dependency file, then the @var{directories} in that directive are searched
1755 just like (and before) the directories in the @code{VPATH} variable.  
1757 For example,
1759 @example
1760 vpath %.h ../headers
1761 @end example
1763 @noindent
1764 tells @code{make} to look for any dependency whose name ends in @file{.h}
1765 in the directory @file{../headers} if the file is not found in the current
1766 directory.
1768 If several @code{vpath} patterns match the dependency file's name, then
1769 @code{make} processes each matching @code{vpath} directive one by one,
1770 searching all the directories mentioned in each directive.  @code{make}
1771 handles multiple @code{vpath} directives in the order in which they
1772 appear in the makefile; multiple directives with the same pattern are
1773 independent of each other.
1775 @need 750
1776 Thus, 
1778 @example
1779 @group
1780 vpath %.c foo
1781 vpath %   blish
1782 vpath %.c bar
1783 @end group
1784 @end example
1786 @noindent
1787 will look for a file ending in @samp{.c} in @file{foo}, then
1788 @file{blish}, then @file{bar}, while
1790 @example
1791 @group
1792 vpath %.c foo:bar
1793 vpath %   blish
1794 @end group
1795 @end example
1797 @noindent
1798 will look for a file ending in @samp{.c} in @file{foo}, then
1799 @file{bar}, then @file{blish}.
1801 @node Commands/Search, Implicit/Search, Selective Search, Directory Search
1802 @subsection Writing Shell Commands with Directory Search
1803 @cindex shell command, and directory search
1804 @cindex directory search (@code{VPATH}), and shell commands
1806 When a dependency is found in another directory through directory search,
1807 this cannot change the commands of the rule; they will execute as written.
1808 Therefore, you must write the commands with care so that they will look for
1809 the dependency in the directory where @code{make} finds it.
1811 This is done with the @dfn{automatic variables} such as @samp{$^}
1812 (@pxref{Automatic, ,Automatic Variables}).  
1813 For instance, the value of @samp{$^} is a
1814 list of all the dependencies of the rule, including the names of
1815 the directories in which they were found, and the value of
1816 @samp{$@@} is the target.  Thus:@refill
1818 @example
1819 foo.o : foo.c
1820         cc -c $(CFLAGS) $^ -o $@@
1821 @end example
1823 @noindent
1824 (The variable @code{CFLAGS} exists so you can specify flags for C
1825 compilation by implicit rules; we use it here for consistency so it will
1826 affect all C compilations uniformly;
1827 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
1829 Often the dependencies include header files as well, which you do not
1830 want to mention in the commands.  The automatic variable @samp{$<} is
1831 just the first dependency:
1833 @example
1834 VPATH = src:../headers
1835 foo.o : foo.c defs.h hack.h
1836         cc -c $(CFLAGS) $< -o $@@
1837 @end example
1839 @node Implicit/Search, Libraries/Search, Commands/Search, Directory Search
1840 @subsection Directory Search and Implicit Rules
1841 @cindex @code{VPATH}, and implicit rules
1842 @cindex directory search (@code{VPATH}), and implicit rules
1843 @cindex search path for dependencies (@code{VPATH}), and implicit rules
1844 @cindex implicit rule, and directory search
1845 @cindex implicit rule, and @code{VPATH}
1846 @cindex rule, implicit, and directory search
1847 @cindex rule, implicit, and @code{VPATH}
1849 The search through the directories specified in @code{VPATH} or with
1850 @code{vpath} also happens during consideration of implicit rules
1851 (@pxref{Implicit Rules, ,Using Implicit Rules}).
1853 For example, when a file @file{foo.o} has no explicit rule, @code{make}
1854 considers implicit rules, such as the built-in rule to compile
1855 @file{foo.c} if that file exists.  If such a file is lacking in the
1856 current directory, the appropriate directories are searched for it.  If
1857 @file{foo.c} exists (or is mentioned in the makefile) in any of the
1858 directories, the implicit rule for C compilation is applied.
1860 The commands of implicit rules normally use automatic variables as a
1861 matter of necessity; consequently they will use the file names found by
1862 directory search with no extra effort.
1864 @node Libraries/Search,  , Implicit/Search, Directory Search
1865 @subsection Directory Search for Link Libraries
1866 @cindex link libraries, and directory search
1867 @cindex libraries for linking, directory search
1868 @cindex directory search (@code{VPATH}), and link libraries 
1869 @cindex @code{VPATH}, and link libraries 
1870 @cindex search path for dependencies (@code{VPATH}), and link libraries 
1871 @cindex @code{-l} (library search)
1873 Directory search applies in a special way to libraries used with the
1874 linker.  This special feature comes into play when you write a dependency
1875 whose name is of the form @samp{-l@var{name}}.  (You can tell something
1876 strange is going on here because the dependency is normally the name of a
1877 file, and the @emph{file name} of the library looks like
1878 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)@refill
1880 When a dependency's name has the form @samp{-l@var{name}}, @code{make}
1881 handles it specially by searching for the file @file{lib@var{name}.a} in
1882 the current directory, in directories specified by matching @code{vpath}
1883 search paths and the @code{VPATH} search path, and then in the
1884 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
1885 (normally @file{/usr/local/lib}).
1887 For example,
1889 @example
1890 @group
1891 foo : foo.c -lcurses
1892         cc $^ -o $@@
1893 @end group
1894 @end example
1896 @noindent
1897 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
1898 be executed when @file{foo} is older than @file{foo.c} or than
1899 @file{/usr/lib/libcurses.a}.@refill
1901 @node Phony Targets, Force Targets, Directory Search, Rules
1902 @section Phony Targets
1903 @cindex phony targets
1904 @cindex targets, phony
1905 @cindex targets without a file
1907 A phony target is one that is not really the name of a file.  It is just a
1908 name for some commands to be executed when you make an explicit request.
1909 There are two reasons to use a phony target: to avoid a conflict with
1910 a file of the same name, and to improve performance.
1912 If you write a rule whose commands will not create the target file, the
1913 commands will be executed every time the target comes up for remaking.
1914 Here is an example:
1916 @example
1917 @group
1918 clean:
1919         rm *.o temp
1920 @end group
1921 @end example
1923 @noindent
1924 Because the @code{rm} command does not create a file named @file{clean},
1925 probably no such file will ever exist.  Therefore, the @code{rm} command
1926 will be executed every time you say @samp{make clean}.
1927 @cindex @code{rm} (shell command)
1929 @findex .PHONY
1930 The phony target will cease to work if anything ever does create a file
1931 named @file{clean} in this directory.  Since it has no dependencies, the
1932 file @file{clean} would inevitably be considered up to date, and its
1933 commands would not be executed.  To avoid this problem, you can explicitly
1934 declare the target to be phony, using the special target @code{.PHONY}
1935 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
1937 @example
1938 .PHONY : clean
1939 @end example
1941 @noindent
1942 Once this is done, @samp{make clean} will run the commands regardless of
1943 whether there is a file named @file{clean}.
1945 Since it knows that phony targets do not name actual files that could be
1946 remade from other files, @code{make} skips the implicit rule search for
1947 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
1948 phony is good for performance, even if you are not worried about the
1949 actual file existing.
1951 Thus, you first write the line that states that @code{clean} is a
1952 phony target, then you write the rule, like this:
1954 @example
1955 @group
1956 .PHONY: clean
1957 clean:
1958         rm *.o temp
1959 @end group
1960 @end example
1962 A phony target should not be a dependency of a real target file; if it
1963 is, its commands are run every time @code{make} goes to update that
1964 file.  As long as a phony target is never a dependency of a real
1965 target, the phony target commands will be executed only when the phony
1966 target is a specified goal (@pxref{Goals, ,Arguments to Specify the
1967 Goals}).
1969 Phony targets can have dependencies.  When one directory contains multiple
1970 programs, it is most convenient to describe all of the programs in one
1971 makefile @file{./Makefile}.  Since the target remade by default will be the
1972 first one in the makefile, it is common to make this a phony target named
1973 @samp{all} and give it, as dependencies, all the individual programs.  For
1974 example:
1976 @example
1977 all : prog1 prog2 prog3
1978 .PHONY : all
1980 prog1 : prog1.o utils.o
1981         cc -o prog1 prog1.o utils.o
1983 prog2 : prog2.o
1984         cc -o prog2 prog2.o
1986 prog3 : prog3.o sort.o utils.o
1987         cc -o prog3 prog3.o sort.o utils.o
1988 @end example
1990 @noindent
1991 Now you can say just @samp{make} to remake all three programs, or specify
1992 as arguments the ones to remake (as in @samp{make prog1 prog3}).
1994 When one phony target is a dependency of another, it serves as a subroutine
1995 of the other.  For example, here @samp{make cleanall} will delete the
1996 object files, the difference files, and the file @file{program}:
1998 @example
1999 .PHONY: cleanall cleanobj cleandiff
2001 cleanall : cleanobj cleandiff
2002         rm program
2004 cleanobj :
2005         rm *.o
2007 cleandiff :
2008         rm *.diff
2009 @end example
2011 @node Force Targets, Empty Targets, Phony Targets, Rules
2012 @section Rules without Commands or Dependencies
2013 @cindex force targets
2014 @cindex targets, force
2015 @cindex @code{FORCE}
2016 @cindex rule, no commands or dependencies
2018 If a rule has no dependencies or commands, and the target of the rule
2019 is a nonexistent file, then @code{make} imagines this target to have
2020 been updated whenever its rule is run.  This implies that all targets
2021 depending on this one will always have their commands run.
2023 An example will illustrate this:
2025 @example
2026 @group
2027 clean: FORCE
2028         rm $(objects)
2029 FORCE:
2030 @end group
2031 @end example
2033 Here the target @samp{FORCE} satisfies the special conditions, so the
2034 target @file{clean} that depends on it is forced to run its commands.
2035 There is nothing special about the name @samp{FORCE}, but that is one name
2036 commonly used this way.
2038 As you can see, using @samp{FORCE} this way has the same results as using
2039 @samp{.PHONY: clean}.  
2041 Using @samp{.PHONY} is more explicit and more efficient.  However,
2042 other versions of @code{make} do not support @samp{.PHONY}; thus
2043 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2045 @node Empty Targets, Special Targets, Force Targets, Rules
2046 @section Empty Target Files to Record Events
2047 @cindex empty targets
2048 @cindex targets, empty
2049 @cindex recording events with empty targets
2051 The @dfn{empty target} is a variant of the phony target; it is used to hold
2052 commands for an action that you request explicitly from time to time.
2053 Unlike a phony target, this target file can really exist; but the file's
2054 contents do not matter, and usually are empty.
2056 The purpose of the empty target file is to record, with its
2057 last-modification time, when the rule's commands were last executed.  It
2058 does so because one of the commands is a @code{touch} command to update the
2059 target file.
2061 The empty target file must have some dependencies.  When you ask to remake
2062 the empty target, the commands are executed if any dependency is more
2063 recent than the target; in other words, if a dependency has changed since
2064 the last time you remade the target.  Here is an example:
2066 @example
2067 print: foo.c bar.c
2068         lpr -p $?
2069         touch print
2070 @end example
2071 @cindex @code{print} target
2072 @cindex @code{lpr} (shell command)
2073 @cindex @code{touch} (shell command)
2075 @noindent
2076 With this rule, @samp{make print} will execute the @code{lpr} command if
2077 either source file has changed since the last @samp{make print}.  The
2078 automatic variable @samp{$?} is used to print only those files that have
2079 changed (@pxref{Automatic, ,Automatic Variables}).
2081 @node Special Targets, Multiple Targets, Empty Targets, Rules
2082 @section Special Built-in Target Names
2083 @cindex special targets
2084 @cindex built-in special targets
2085 @cindex targets, built-in special
2087 Certain names have special meanings if they appear as targets.
2089 @table @code
2090 @findex .PHONY
2091 @item .PHONY
2093 The dependencies of the special target @code{.PHONY} are considered to
2094 be phony targets.  When it is time to consider such a target,
2095 @code{make} will run its commands unconditionally, regardless of
2096 whether a file with that name exists or what its last-modification
2097 time is.  @xref{Phony Targets, ,Phony Targets}.
2099 @findex .SUFFIXES
2100 @item .SUFFIXES
2102 The dependencies of the special target @code{.SUFFIXES} are the list
2103 of suffixes to be used in checking for suffix rules.  
2104 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
2106 @findex .DEFAULT
2107 @item .DEFAULT
2109 The commands specified for @code{.DEFAULT} are used for any target for
2110 which no rules are found (either explicit rules or implicit rules).
2111 @xref{Last Resort}.  If @code{.DEFAULT} commands are specified, every
2112 file mentioned as a dependency, but not as a target in a rule, will have
2113 these commands executed on its behalf.  @xref{Search Algorithm,
2114 ,Implicit Rule Search Algorithm}.
2116 @findex .PRECIOUS
2117 @item .PRECIOUS
2118 @cindex precious targets
2119 @cindex preserving with @code{.PRECIOUS}
2121 The targets which @code{.PRECIOUS} depends on are given the following
2122 special treatment: if @code{make} is killed or interrupted during the
2123 execution of their commands, the target is not deleted.
2124 @xref{Interrupts, ,Interrupting or Killing @code{make}}.
2125 Also, if the target is an intermediate file, it will not be deleted
2126 after it is no longer needed, as is normally done.
2127 @xref{Chained Rules, ,Chains of Implicit Rules}.
2129 You can also list the target pattern of an implicit rule (such as
2130 @samp{%.o}) as a dependency file of the special target @code{.PRECIOUS}
2131 to preserve intermediate files created by rules whose target patterns
2132 match that file's name.
2134 @findex .IGNORE
2135 @item .IGNORE
2137 If you specify dependencies for @code{.IGNORE}, then @code{make} will
2138 ignore errors in execution of the commands run for those particular
2139 files.  The commands for @code{.IGNORE} are not meaningful.
2141 If mentioned as a target with no dependencies, @code{.IGNORE} says to
2142 ignore errors in execution of commands for all files.  This usage of
2143 @samp{.IGNORE} is supported only for historical compatibility.  Since
2144 this affects every command in the makefile, it is not very useful; we
2145 recommend you use the more selective ways to ignore errors in specific
2146 commands.  @xref{Errors, ,Errors in Commands}.
2148 @findex .SILENT
2149 @item .SILENT
2151 If you specify dependencies for @code{.SILENT}, then @code{make} will
2152 not the print commands to remake those particular files before executing
2153 them.  The commands for @code{.SILENT} are not meaningful.
2155 If mentioned as a target with no dependencies, @code{.SILENT} says not
2156 to print any commands before executing them.  This usage of
2157 @samp{.SILENT} is supported only for historical compatibility.  We
2158 recommend you use the more selective ways to silence specific commands.
2159 @xref{Echoing, ,Command Echoing}.  If you want to silence all commands
2160 for a particular run of @code{make}, use the @samp{-s} or
2161 @w{@samp{--silent}} option (@pxref{Options Summary}).
2163 @findex .EXPORT_ALL_VARIABLES
2164 @item .EXPORT_ALL_VARIABLES
2166 Simply by being mentioned as a target, this tells @code{make} to
2167 export all variables to child processes by default.
2168 @xref{Variables/Recursion, ,Communicating Variables to a
2169 Sub-@code{make}}.
2170 @end table
2172 Any defined implicit rule suffix also counts as a special target if it
2173 appears as a target, and so does the concatenation of two suffixes, such
2174 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
2175 defining implicit rules (but a way still widely used).  In principle, any
2176 target name could be special in this way if you break it in two and add
2177 both pieces to the suffix list.  In practice, suffixes normally begin with
2178 @samp{.}, so these special target names also begin with @samp{.}.
2179 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
2181 @node Multiple Targets, Multiple Rules, Special Targets, Rules
2182 @section Multiple Targets in a Rule
2183 @cindex multiple targets
2184 @cindex several targets in a rule
2185 @cindex targets, multiple
2186 @cindex rule, with multiple targets
2188 A rule with multiple targets is equivalent to writing many rules, each with
2189 one target, and all identical aside from that.  The same commands apply to
2190 all the targets, but their effects may vary because you can substitute the
2191 actual target name into the command using @samp{$@@}.  The rule contributes
2192 the same dependencies to all the targets also.
2194 This is useful in two cases.
2196 @itemize @bullet
2197 @item
2198 You want just dependencies, no commands.  For example:
2200 @example
2201 kbd.o command.o files.o: command.h
2202 @end example
2204 @noindent
2205 gives an additional dependency to each of the three object files
2206 mentioned.
2208 @item
2209 Similar commands work for all the targets.  The commands do not need
2210 to be absolutely identical, since the automatic variable @samp{$@@}
2211 can be used to substitute the particular target to be remade into the
2212 commands (@pxref{Automatic, ,Automatic Variables}).  For example:
2214 @example
2215 @group
2216 bigoutput littleoutput : text.g
2217         generate text.g -$(subst output,,$@@) > $@@
2218 @end group
2219 @end example
2220 @findex subst
2222 @noindent
2223 is equivalent to
2225 @example
2226 bigoutput : text.g
2227         generate text.g -big > bigoutput
2228 littleoutput : text.g
2229         generate text.g -little > littleoutput
2230 @end example
2232 @noindent
2233 Here we assume the hypothetical program @code{generate} makes two
2234 types of output, one if given @samp{-big} and one if given
2235 @samp{-little}.
2236 @xref{Text Functions, ,Functions for String Substitution and Analysis},
2237 for an explanation of the @code{subst} function.
2238 @end itemize
2240 Suppose you would like to vary the dependencies according to the target,
2241 much as the variable @samp{$@@} allows you to vary the commands.
2242 You cannot do this with multiple targets in an ordinary rule, but you can
2243 do it with a @dfn{static pattern rule}.
2244 @xref{Static Pattern, ,Static Pattern Rules}.
2246 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
2247 @section Multiple Rules for One Target
2248 @cindex multiple rules for one target
2249 @cindex several rules for one target
2250 @cindex rule, multiple for one target
2251 @cindex target, multiple rules for one
2253 One file can be the target of several rules.  All the dependencies
2254 mentioned in all the rules are merged into one list of dependencies for
2255 the target.  If the target is older than any dependency from any rule,
2256 the commands are executed.
2258 There can only be one set of commands to be executed for a file.
2259 If more than one rule gives commands for the same file, 
2260 @code{make} uses the last set given and prints an error message.
2261 (As a special case, if the file's name begins with a dot, no
2262 error message is printed.  This odd behavior is only for
2263 compatibility with other implementations of @code{make}.)  
2264 There is no reason to
2265 write your makefiles this way; that is why @code{make} gives you
2266 an error message.@refill
2268 An extra rule with just dependencies can be used to give a few extra
2269 dependencies to many files at once.  For example, one usually has a
2270 variable named @code{objects} containing a list of all the compiler output
2271 files in the system being made.  An easy way to say that all of them must
2272 be recompiled if @file{config.h} changes is to write the following:
2274 @example
2275 objects = foo.o bar.o
2276 foo.o : defs.h
2277 bar.o : defs.h test.h
2278 $(objects) : config.h
2279 @end example
2281 This could be inserted or taken out without changing the rules that really
2282 specify how to make the object files, making it a convenient form to use if
2283 you wish to add the additional dependency intermittently.
2285 Another wrinkle is that the additional dependencies could be specified with
2286 a variable that you set with a command argument to @code{make}
2287 (@pxref{Overriding, ,Overriding Variables}).  For example,
2289 @example
2290 @group
2291 extradeps=
2292 $(objects) : $(extradeps)
2293 @end group
2294 @end example
2296 @noindent
2297 means that the command @samp{make extradeps=foo.h} will consider
2298 @file{foo.h} as a dependency of each object file, but plain @samp{make}
2299 will not.
2301 If none of the explicit rules for a target has commands, then @code{make}
2302 searches for an applicable implicit rule to find some commands
2303 @pxref{Implicit Rules, ,Using Implicit Rules}).
2305 @node Static Pattern, Double-Colon, Multiple Rules, Rules
2306 @section Static Pattern Rules
2307 @cindex static pattern rule
2308 @cindex rule, static pattern
2309 @cindex pattern rules, static (not implicit)
2310 @cindex varying dependencies
2311 @cindex dependencies, varying (static pattern)
2313 @dfn{Static pattern rules} are rules which specify multiple targets and
2314 construct the dependency names for each target based on the target name.
2315 They are more general than ordinary rules with multiple targets because the
2316 targets do not have to have identical dependencies.  Their dependencies must
2317 be @emph{analogous}, but not necessarily @emph{identical}.
2319 @menu
2320 * Static Usage::                The syntax of static pattern rules.
2321 * Static versus Implicit::      When are they better than implicit rules?
2322 @end menu
2324 @node Static Usage, Static versus Implicit,  , Static Pattern
2325 @subsection Syntax of Static Pattern Rules
2326 @cindex static pattern rule, syntax of
2327 @cindex pattern rules, static, syntax of
2329 Here is the syntax of a static pattern rule:
2331 @example
2332 @var{targets} @dots{}: @var{target-pattern}: @var{dep-patterns} @dots{}
2333         @var{commands}
2334         @dots{}
2335 @end example
2337 @noindent
2338 The @var{targets} list specifies the targets that the rule applies to.
2339 The targets can contain wildcard characters, just like the targets of
2340 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
2341 Names}).
2343 @cindex target pattern, static (not implicit)
2344 @cindex stem
2345 The @var{target-pattern} and @var{dep-patterns} say how to compute the
2346 dependencies of each target.  Each target is matched against the
2347 @var{target-pattern} to extract a part of the target name, called the
2348 @dfn{stem}.  This stem is substituted into each of the @var{dep-patterns}
2349 to make the dependency names (one from each @var{dep-pattern}).
2351 Each pattern normally contains the character @samp{%} just once.  When the
2352 @var{target-pattern} matches a target, the @samp{%} can match any part of
2353 the target name; this part is called the @dfn{stem}.  The rest of the
2354 pattern must match exactly.  For example, the target @file{foo.o} matches
2355 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
2356 @file{foo.c} and @file{foo.out} do not match that pattern.@refill
2358 @cindex dependency pattern, static (not implicit)
2359 The dependency names for each target are made by substituting the stem
2360 for the @samp{%} in each dependency pattern.  For example, if one
2361 dependency pattern is @file{%.c}, then substitution of the stem
2362 @samp{foo} gives the dependency name @file{foo.c}.  It is legitimate
2363 to write a dependency pattern that does not contain @samp{%}; then this
2364 dependency is the same for all targets.
2366 @cindex @code{%}, quoting in static pattern
2367 @cindex @code{%}, quoting with @code{\} (backslash)
2368 @cindex @code{\} (backslash), to quote @code{%}
2369 @cindex backslash (@code{\}), to quote @code{%}
2370 @cindex quoting @code{%}, in static pattern
2371 @samp{%} characters in pattern rules can be quoted with preceding
2372 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
2373 characters can be quoted with more backslashes.  Backslashes that quote
2374 @samp{%} characters or other backslashes are removed from the pattern
2375 before it is compared to file names or has a stem substituted into it.
2376 Backslashes that are not in danger of quoting @samp{%} characters go
2377 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
2378 @samp{the%weird\} preceding the operative @samp{%} character, and
2379 @samp{pattern\\} following it.  The final two backslashes are left alone
2380 because they cannot affect any @samp{%} character.@refill
2382 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
2383 from the corresponding @file{.c} file:
2385 @example
2386 @group
2387 objects = foo.o bar.o
2389 $(objects): %.o: %.c
2390         $(CC) -c $(CFLAGS) $< -o $@@
2391 @end group
2392 @end example
2394 @noindent
2395 Here @samp{$<} is the automatic variable that holds the name of the
2396 dependency and @samp{$@@} is the automatic variable that holds the name
2397 of the target; see @ref{Automatic, , Automatic Variables}.
2399 Each target specified must match the target pattern; a warning is issued
2400 for each target that does not.  If you have a list of files, only some of
2401 which will match the pattern, you can use the @code{filter} function to
2402 remove nonmatching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
2404 @example
2405 files = foo.elc bar.o lose.o
2407 $(filter %.o,$(files)): %.o: %.c
2408         $(CC) -c $(CFLAGS) $< -o $@@
2409 $(filter %.elc,$(files)): %.elc: %.el
2410         emacs -f batch-byte-compile $<
2411 @end example
2413 @noindent
2414 In this example the result of @samp{$(filter %.o,$(files))} is
2415 @file{bar.o lose.o}, and the first static pattern rule causes each of
2416 these object files to be updated by compiling the corresponding C source
2417 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
2418 @file{foo.elc}, so that file is made from @file{foo.el}.@refill
2420 Another example shows how to use @code{$*} in static pattern rules:
2421 @vindex $*@r{, and static pattern}
2423 @example
2424 @group
2425 bigoutput littleoutput : %output : text.g
2426         generate text.g -$* > $@@
2427 @end group
2428 @end example
2430 @noindent
2431 When the @code{generate} command is run, @code{$*} will expand to the
2432 stem, either @samp{big} or @samp{little}.
2434 @node Static versus Implicit,  , Static Usage, Static Pattern
2435 @subsection Static Pattern Rules versus Implicit Rules
2436 @cindex rule, static pattern versus implicit
2437 @cindex static pattern rule, versus implicit
2439 A static pattern rule has much in common with an implicit rule defined as a
2440 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
2441 Both have a pattern for the target and patterns for constructing the
2442 names of dependencies.  The difference is in how @code{make} decides
2443 @emph{when} the rule applies.
2445 An implicit rule @emph{can} apply to any target that matches its pattern,
2446 but it @emph{does} apply only when the target has no commands otherwise
2447 specified, and only when the dependencies can be found.  If more than one
2448 implicit rule appears applicable, only one applies; the choice depends on
2449 the order of rules.
2451 By contrast, a static pattern rule applies to the precise list of targets
2452 that you specify in the rule.  It cannot apply to any other target and it
2453 invariably does apply to each of the targets specified.  If two conflicting
2454 rules apply, and both have commands, that's an error.
2456 The static pattern rule can be better than an implicit rule for these
2457 reasons:
2459 @itemize @bullet
2460 @item
2461 You may wish to override the usual implicit rule for a few
2462 files whose names cannot be categorized syntactically but
2463 can be given in an explicit list.
2465 @item
2466 If you cannot be sure of the precise contents of the directories
2467 you are using, you may not be sure which other irrelevant files
2468 might lead @code{make} to use the wrong implicit rule.  The choice
2469 might depend on the order in which the implicit rule search is done.
2470 With static pattern rules, there is no uncertainty: each rule applies
2471 to precisely the targets specified.
2472 @end itemize
2474 @node Double-Colon, Automatic Dependencies, Static Pattern, Rules
2475 @section Double-Colon Rules
2476 @cindex double-colon rules
2477 @cindex rule, double-colon (@code{::})
2478 @cindex multiple rules for one target (@code{::})
2479 @cindex @code{::} rules (double-colon)
2481 @dfn{Double-colon} rules are rules written with @samp{::} instead of
2482 @samp{:} after the target names.  They are handled differently from
2483 ordinary rules when the same target appears in more than one rule.
2485 When a target appears in multiple rules, all the rules must be the same
2486 type: all ordinary, or all double-colon.  If they are double-colon, each of
2487 them is independent of the others.  Each double-colon rule's commands are
2488 executed if the target is older than any dependencies of that rule.  This
2489 can result in executing none, any, or all of the double-colon rules.
2491 Double-colon rules with the same target are in fact completely separate
2492 from one another.  Each double-colon rule is processed individually, just
2493 as rules with different targets are processed.
2495 The double-colon rules for a target are executed in the order they appear
2496 in the makefile.  However, the cases where double-colon rules really make
2497 sense are those where the order of executing the commands would not matter.
2499 Double-colon rules are somewhat obscure and not often very useful; they
2500 provide a mechanism for cases in which the method used to update a target
2501 differs depending on which dependency files caused the update, and such
2502 cases are rare.
2504 Each double-colon rule should specify commands; if it does not, an
2505 implicit rule will be used if one applies.  
2506 @xref{Implicit Rules, ,Using Implicit Rules}.
2508 @node Automatic Dependencies,  , Double-Colon, Rules
2509 @section Generating Dependencies Automatically
2510 @cindex dependencies, automatic generation
2511 @cindex automatic generation of dependencies
2512 @cindex generating dependencies automatically
2514 In the makefile for a program, many of the rules you need to write often
2515 say only that some object file depends on some header
2516 file.  For example, if @file{main.c} uses @file{defs.h} via an
2517 @code{#include}, you would write:
2519 @example
2520 main.o: defs.h
2521 @end example
2523 @noindent
2524 You need this rule so that @code{make} knows that it must remake
2525 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
2526 large program you would have to write dozens of such rules in your
2527 makefile.  And, you must always be very careful to update the makefile
2528 every time you add or remove an @code{#include}.
2529 @cindex @code{#include}
2531 @cindex @code{-M} (to compiler)
2532 To avoid this hassle, most modern C compilers can write these rules for
2533 you, by looking at the @code{#include} lines in the source files.
2534 Usually this is done with the @samp{-M} option to the compiler.
2535 For example, the command:
2537 @example
2538 cc -M main.c
2539 @end example
2541 @noindent
2542 generates the output:
2544 @example
2545 main.o : main.c defs.h
2546 @end example
2548 @noindent
2549 Thus you no longer have to write all those rules yourself.
2550 The compiler will do it for you.
2552 Note that such a dependency constitutes mentioning @file{main.o} in a
2553 makefile, so it can never be considered an intermediate file by implicit
2554 rule search.  This means that @code{make} won't ever remove the file
2555 after using it; @pxref{Chained Rules, ,Chains of Implicit Rules}.
2557 @cindex @code{make depend}
2558 With old @code{make} programs, it was traditional practice to use this
2559 compiler feature to generate dependencies on demand with a command like
2560 @samp{make depend}.  That command would create a file @file{depend}
2561 containing all the automatically-generated dependencies; then the
2562 makefile could use @code{include} to read them in (@pxref{Include}).
2564 In GNU @code{make}, the feature of remaking makefiles makes this
2565 practice obsolete---you need never tell @code{make} explicitly to
2566 regenerate the dependencies, because it always regenerates any makefile
2567 that is out of date.  @xref{Remaking Makefiles}.
2569 The practice we recommend for automatic dependency generation is to have
2570 one makefile corresponding to each source file.  For each source file
2571 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
2572 what files the object file @file{@var{name}.o} depends on.  That way
2573 only the source files that have changed need to be rescanned to produce
2574 the new dependencies.
2576 Here is the pattern rule to generate a file of dependencies (i.e., a makefile)
2577 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
2579 @smallexample
2580 @group
2581 %.d: %.c
2582         $(SHELL) -ec '$(CC) -M $(CPPFLAGS) $< \
2583                       | sed '\''s/$*\\.o[ :]*/& $@@/g'\'' > $@@'
2584 @end group
2585 @end smallexample
2587 @noindent
2588 @xref{Pattern Rules}, for information on defining pattern rules.  The
2589 @samp{-e} flag to the shell makes it exit immediately if the
2590 @code{$(CC)} command fails (exits with a nonzero status).  Normally the
2591 shell exits with the status of the last command in the pipeline
2592 (@code{sed} in this case), so @code{make} would not notice a nonzero
2593 status from the compiler.
2594 @cindex @code{-e} (shell flag)
2596 @cindex @code{-MM} (to GNU compiler)
2597 With the GNU C compiler, you may wish to use the @samp{-MM} flag instead
2598 of @samp{-M}.  This omits dependencies on system header files.
2599 @xref{Preprocessor Options, , Options Controlling the Preprocessor, 
2600 gcc.info, Using GNU CC}, for details.
2602 @cindex @code{sed} (shell command)
2603 The purpose of the @code{sed} command is to translate (for example):
2605 @example
2606 main.o : main.c defs.h
2607 @end example
2609 @noindent
2610 into:
2612 @example
2613 main.o main.d : main.c defs.h
2614 @end example
2616 @noindent
2617 @cindex @code{.d}
2618 This makes each @samp{.d} file depend on all the source and header files
2619 that the corresponding @samp{.o} file depends on.  @code{make} then
2620 knows it must regenerate the dependencies whenever any of the source or
2621 header files changes.
2623 Once you've defined the rule to remake the @samp{.d} files,
2624 you then use the @code{include} directive to read them all in.
2625 @xref{Include}.  For example:
2627 @example
2628 @group
2629 sources = foo.c bar.c
2631 include $(sources:.c=.d)
2632 @end group
2633 @end example
2635 @noindent
2636 (This example uses a substitution variable reference to translate the
2637 list of source files @samp{foo.c bar.c} into a list of dependency
2638 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
2639 information on substitution references.)  Since the @samp{.d} files are
2640 makefiles like any others, @code{make} will remake them as necessary
2641 with no further work from you.  @xref{Remaking Makefiles}.
2643 @node Commands, Using Variables, Rules, Top
2644 @chapter Writing the Commands in Rules
2645 @cindex commands, how to write
2646 @cindex rule commands
2647 @cindex writing rule commands
2649 The commands of a rule consist of shell command lines to be executed one
2650 by one.  Each command line must start with a tab, except that the first
2651 command line may be attached to the target-and-dependencies line with a
2652 semicolon in between.  Blank lines and lines of just comments may appear
2653 among the command lines; they are ignored.  (But beware, an apparently
2654 ``blank'' line that begins with a tab is @emph{not} blank!  It is an
2655 empty command; @pxref{Empty Commands}.)
2657 Users use many different shell programs, but commands in makefiles are
2658 always interpreted by @file{/bin/sh} unless the makefile specifies
2659 otherwise.  @xref{Execution, ,Command Execution}.
2661 @cindex comments, in commands
2662 @cindex commands, comments in
2663 @cindex @code{#} (comments), in commands
2664 The shell that is in use determines whether comments can be written on
2665 command lines, and what syntax they use.  When the shell is
2666 @file{/bin/sh}, a @samp{#} starts a comment that extends to the end of
2667 the line.  The @samp{#} does not have to be at the beginning of a line.
2668 Text on a line before a @samp{#} is not part of the comment.
2670 @menu
2671 * Echoing::                     How to control when commands are echoed.
2672 * Execution::                   How commands are executed.
2673 * Parallel::                    How commands can be executed in parallel.
2674 * Errors::                      What happens after a command execution error. 
2675 * Interrupts::                  What happens when a command is interrupted.
2676 * Recursion::                   Invoking @code{make} from makefiles.
2677 * Sequences::                   Defining canned sequences of commands.
2678 * Empty Commands::              Defining useful, do-nothing commands.
2679 @end menu
2681 @node Echoing, Execution,  , Commands
2682 @section Command Echoing
2683 @cindex echoing of commands
2684 @cindex silent operation
2685 @cindex @code{@@} (in commands)
2686 @cindex commands, echoing
2687 @cindex printing of commands
2689 Normally @code{make} prints each command line before it is executed.
2690 We call this @dfn{echoing} because it gives the appearance that you
2691 are typing the commands yourself.
2693 When a line starts with @samp{@@}, the echoing of that line is suppressed.
2694 The @samp{@@} is discarded before the command is passed to the shell.
2695 Typically you would use this for a command whose only effect is to print
2696 something, such as an @code{echo} command to indicate progress through
2697 the makefile:
2699 @example
2700 @@echo About to make distribution files
2701 @end example
2703 @cindex @code{-n}
2704 @cindex @code{--just-print}
2705 @cindex @code{--dry-run}
2706 @cindex @code{--recon}
2707 When @code{make} is given the flag @samp{-n} or @samp{--just-print},
2708 echoing is all that happens, no execution.  @xref{Options Summary,
2709 ,Summary of Options}.  In this case and only this case, even the
2710 commands starting with @samp{@@} are printed.  This flag is useful for
2711 finding out which commands @code{make} thinks are necessary without
2712 actually doing them.
2714 @cindex @code{-s}
2715 @cindex @code{--silent}
2716 @cindex @code{--quiet}
2717 @findex .SILENT
2718 The @samp{-s} or @samp{--silent}
2719 flag to @code{make} prevents all echoing, as if all commands
2720 started with @samp{@@}.  A rule in the makefile for the special target
2721 @code{.SILENT} without dependencies has the same effect 
2722 (@pxref{Special Targets, ,Special Built-in Target Names}).
2723 @code{.SILENT} is essentially obsolete since @samp{@@} is more flexible.@refill
2725 @node Execution, Parallel, Echoing, Commands
2726 @section Command Execution
2727 @cindex commands, execution
2728 @cindex execution, of commands
2729 @cindex shell command, execution
2730 @vindex SHELL @r{(command execution)}
2732 When it is time to execute commands to update a target, they are executed
2733 by making a new subshell for each line.  (In practice, @code{make} may
2734 take shortcuts that do not affect the results.)
2736 @cindex @code{cd} (shell command)
2737 @strong{Please note:} this implies that shell commands such as
2738 @code{cd} that set variables local to each process will not affect the
2739 following command lines.  If you want to use @code{cd} to affect the
2740 next command, put the two on a single line with a semicolon between
2741 them.  Then @code{make} will consider them a single command and pass
2742 them, together, to a shell which will execute them in sequence.  For
2743 example:
2745 @example
2746 foo : bar/lose
2747         cd bar; gobble lose > ../foo
2748 @end example
2750 @cindex commands, backslash (@code{\}) in
2751 @cindex commands, quoting newlines in
2752 @cindex backslash (@code{\}), in commands
2753 @cindex @code{\} (backslash), in commands
2754 @cindex quoting newline, in commands
2755 @cindex newline, quoting, in commands
2756 If you would like to split a single shell command into multiple lines of
2757 text, you must use a backslash at the end of all but the last subline.
2758 Such a sequence of lines is combined into a single line, by deleting the
2759 backslash-newline sequences, before passing it to the shell.  Thus, the
2760 following is equivalent to the preceding example:
2762 @example
2763 @group
2764 foo : bar/lose
2765         cd bar;  \
2766         gobble lose > ../foo
2767 @end group
2768 @end example
2770 @vindex SHELL
2771 The program used as the shell is taken from the variable @code{SHELL}.
2772 By default, the program @file{/bin/sh} is used.
2774 @cindex environment, @code{SHELL} in
2775 Unlike most variables, the variable @code{SHELL} is never set from the
2776 environment.  This is because the @code{SHELL} environment variable is
2777 used to specify your personal choice of shell program for interactive
2778 use.  It would be very bad for personal choices like this to affect
2779 the functioning of makefiles.  @xref{Environment, ,Variables from the
2780 Environment}.
2782 @node Parallel, Errors, Execution, Commands
2783 @section Parallel Execution
2784 @cindex commands, execution in parallel
2785 @cindex parallel execution
2786 @cindex execution, in parallel
2787 @cindex job slots
2788 @cindex @code{-j}
2789 @cindex @code{--jobs}
2791 GNU @code{make} knows how to execute several commands at once.
2792 Normally, @code{make} will execute only one command at a time, waiting
2793 for it to finish before executing the next.  However, the @samp{-j} or
2794 @samp{--jobs} option tells @code{make} to execute many commands
2795 simultaneously.@refill
2797 If the @samp{-j} option is followed by an integer, this is the number of
2798 commands to execute at once; this is called the number of @dfn{job slots}.
2799 If there is nothing looking like an integer after the @samp{-j} option,
2800 there is no limit on the number of job slots.  The default number of job
2801 slots is one, which means serial execution (one thing at a time).
2803 One unpleasant consequence of running several commands simultaneously is
2804 that output from all of the commands comes when the commands send it, so
2805 messages from different commands may be interspersed.
2807 Another problem is that two processes cannot both take input from the
2808 same device; so to make sure that only one command tries to take input
2809 from the terminal at once, @code{make} will invalidate the standard
2810 input streams of all but one running command.  This means that
2811 attempting to read from standard input will usually be a fatal error (a
2812 @samp{Broken pipe} signal) for most child processes if there are
2813 several.
2814 @cindex broken pipe
2815 @cindex standard input
2817 It is unpredictable which command will have a valid standard input stream
2818 (which will come from the terminal, or wherever you redirect the standard
2819 input of @code{make}).  The first command run will always get it first, and
2820 the first command started after that one finishes will get it next, and so
2823 We will change how this aspect of @code{make} works if we find a better
2824 alternative.  In the mean time, you should not rely on any command using
2825 standard input at all if you are using the parallel execution feature; but
2826 if you are not using this feature, then standard input works normally in
2827 all commands.
2829 If a command fails (is killed by a signal or exits with a nonzero
2830 status), and errors are not ignored for that command
2831 (@pxref{Errors, ,Errors in Commands}),
2832 the remaining command lines to remake the same target will not be run.
2833 If a command fails and the @samp{-k} or @samp{--keep-going}
2834 option was not given
2835 (@pxref{Options Summary, ,Summary of Options}), 
2836 @code{make} aborts execution.  If make
2837 terminates for any reason (including a signal) with child processes
2838 running, it waits for them to finish before actually exiting.@refill
2840 @cindex load average
2841 @cindex limiting jobs based on load
2842 @cindex jobs, limiting based on load
2843 @cindex @code{-l} (load average)
2844 @cindex @code{--max-load}
2845 @cindex @code{--load-average}
2846 When the system is heavily loaded, you will probably want to run fewer jobs
2847 than when it is lightly loaded.  You can use the @samp{-l} option to tell
2848 @code{make} to limit the number of jobs to run at once, based on the load
2849 average.  The @samp{-l} or @samp{--max-load}
2850 option is followed by a floating-point number.  For
2851 example,
2853 @example
2854 -l 2.5
2855 @end example
2857 @noindent
2858 will not let @code{make} start more than one job if the load average is
2859 above 2.5.  The @samp{-l} option with no following number removes the
2860 load limit, if one was given with a previous @samp{-l} option.@refill
2862 More precisely, when @code{make} goes to start up a job, and it already has
2863 at least one job running, it checks the current load average; if it is not
2864 lower than the limit given with @samp{-l}, @code{make} waits until the load
2865 average goes below that limit, or until all the other jobs finish.
2867 By default, there is no load limit.
2869 @node Errors, Interrupts, Parallel, Commands
2870 @section Errors in Commands
2871 @cindex errors (in commands)
2872 @cindex commands, errors in
2873 @cindex exit status (errors)
2875 After each shell command returns, @code{make} looks at its exit status.
2876 If the command completed successfully, the next command line is executed
2877 in a new shell; after the last command line is finished, the rule is
2878 finished. 
2880 If there is an error (the exit status is nonzero), @code{make} gives up on
2881 the current rule, and perhaps on all rules.
2883 Sometimes the failure of a certain command does not indicate a problem.
2884 For example, you may use the @code{mkdir} command to ensure that a
2885 directory exists.  If the directory already exists, @code{mkdir} will
2886 report an error, but you probably want @code{make} to continue regardless.
2888 @cindex @code{-} (in commands)
2889 To ignore errors in a command line, write a @samp{-} at the beginning of
2890 the line's text (after the initial tab).  The @samp{-} is discarded before
2891 the command is passed to the shell for execution.  
2893 For example,
2895 @example
2896 @group
2897 clean:
2898         -rm -f *.o
2899 @end group
2900 @end example
2901 @cindex @code{rm} (shell command)
2903 @noindent
2904 This causes @code{rm} to continue even if it is unable to remove a file.
2906 @cindex @code{-i}
2907 @cindex @code{--ignore-errors}
2908 @findex .IGNORE
2909 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
2910 flag, errors are ignored in all commands of all rules.  A rule in the
2911 makefile for the special target @code{.IGNORE} has the same effect, if
2912 there are no dependencies.  These ways of ignoring errors are obsolete
2913 because @samp{-} is more flexible.
2915 When errors are to be ignored, because of either a @samp{-} or the
2916 @samp{-i} flag, @code{make} treats an error return just like success,
2917 except that it prints out a message that tells you the status code
2918 the command exited with, and says that the error has been ignored.
2920 When an error happens that @code{make} has not been told to ignore,
2921 it implies that the current target cannot be correctly remade, and neither
2922 can any other that depends on it either directly or indirectly.  No further
2923 commands will be executed for these targets, since their preconditions
2924 have not been achieved.
2927 @cindex @code{-k}
2928 @cindex @code{--keep-going}
2929 Normally @code{make} gives up immediately in this circumstance, returning a
2930 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
2931 flag is specified, @code{make}
2932 continues to consider the other dependencies of the pending targets,
2933 remaking them if necessary, before it gives up and returns nonzero status.
2934 For example, after an error in compiling one object file, @samp{make -k}
2935 will continue compiling other object files even though it already knows
2936 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
2938 The usual behavior assumes that your purpose is to get the specified
2939 targets up to date; once @code{make} learns that this is impossible, it
2940 might as well report the failure immediately.  The @samp{-k} option says
2941 that the real purpose is to test as many of the changes made in the
2942 program as possible, perhaps to find several independent problems so
2943 that you can correct them all before the next attempt to compile.  This
2944 is why Emacs' @code{compile} command passes the @samp{-k} flag by
2945 default.
2946 @cindex Emacs (@code{M-x compile})
2948 @findex .DELETE_ON_ERROR
2949 @cindex deletion of target files
2950 @cindex removal of target files
2951 @cindex target, deleting on error
2952 Usually when a command fails, if it has changed the target file at all,
2953 the file is corrupted and cannot be used---or at least it is not
2954 completely updated.  Yet the file's timestamp says that it is now up to
2955 date, so the next time @code{make} runs, it will not try to update that
2956 file.  The situation is just the same as when the command is killed by a
2957 signal; @pxref{Interrupts}.  So generally the right thing to do is to
2958 delete the target file if the command fails after beginning to change
2959 the file.  @code{make} will do this if @code{.DELETE_ON_ERROR} appears
2960 as a target.  This is almost always what you want @code{make} to do, but
2961 it is not historical practice; so for compatibility, you must explicitly
2962 request it.
2964 @node Interrupts, Recursion, Errors, Commands
2965 @section Interrupting or Killing @code{make}
2966 @cindex interrupt
2967 @cindex signal
2968 @cindex deletion of target files
2969 @cindex removal of target files
2970 @cindex target, deleting on interrupt
2971 @cindex killing (interruption)
2973 If @code{make} gets a fatal signal while a command is executing, it may
2974 delete the target file that the command was supposed to update.  This is
2975 done if the target file's last-modification time has changed since
2976 @code{make} first checked it.
2978 The purpose of deleting the target is to make sure that it is remade from
2979 scratch when @code{make} is next run.  Why is this?  Suppose you type
2980 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
2981 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
2982 in an incomplete file whose last-modification time is newer than the source
2983 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
2984 and deletes this incomplete file.  If @code{make} did not do this, the next
2985 invocation of @code{make} would think that @file{foo.o} did not require
2986 updating---resulting in a strange error message from the linker when it
2987 tries to link an object file half of which is missing.
2989 @findex .PRECIOUS
2990 You can prevent the deletion of a target file in this way by making the
2991 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
2992 @code{make} checks to see whether it appears on the dependencies of
2993 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
2994 if a signal happens.  Some reasons why you might do this are that the
2995 target is updated in some atomic fashion, or exists only to record a
2996 modification-time (its contents do not matter), or must exist at all
2997 times to prevent other sorts of trouble.
2999 @node Recursion, Sequences, Interrupts, Commands
3000 @section Recursive Use of @code{make}
3001 @cindex recursion
3002 @cindex subdirectories, recursion for
3004 Recursive use of @code{make} means using @code{make} as a command in a
3005 makefile.  This technique is useful when you want separate makefiles for
3006 various subsystems that compose a larger system.  For example, suppose you
3007 have a subdirectory @file{subdir} which has its own makefile, and you would
3008 like the containing directory's makefile to run @code{make} on the
3009 subdirectory.  You can do it by writing this:
3011 @example
3012 subsystem:
3013         cd subdir; $(MAKE)
3014 @end example
3016 @noindent
3017 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
3019 @example
3020 subsystem:
3021         $(MAKE) -C subdir
3022 @end example
3023 @cindex @code{-C}
3024 @cindex @code{--directory}
3026 You can write recursive @code{make} commands just by copying this example,
3027 but there are many things to know about how they work and why, and about
3028 how the sub-@code{make} relates to the top-level @code{make}.
3030 @menu
3031 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
3032 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
3033 * Options/Recursion::           How to communicate options to a sub-@code{make}.
3034 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
3035                                  helps debug use of recursive @code{make} commands.
3036 @end menu
3038 @node MAKE Variable, Variables/Recursion,  , Recursion
3039 @subsection How the @code{MAKE} Variable Works
3040 @vindex MAKE
3041 @cindex recursion, and @code{MAKE} variable
3043 Recursive @code{make} commands should always use the variable @code{MAKE},
3044 not the explicit command name @samp{make}, as shown here:
3046 @example
3047 @group
3048 subsystem:
3049         cd subdir; $(MAKE)
3050 @end group
3051 @end example
3053 The value of this variable is the file name with which @code{make} was
3054 invoked.  If this file name was @file{/bin/make}, then the command executed
3055 is @samp{cd subdir; /bin/make}.  If you use a special version of
3056 @code{make} to run the top-level makefile, the same special version will be
3057 executed for recursive invocations.
3058 @cindex @code{cd} (shell command)
3060 As a special feature, using the variable @code{MAKE} in the commands of
3061 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
3062 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
3063 Using the @code{MAKE} variable has the same effect as using a @samp{+}
3064 character at the beginning of the command line.  @xref{Instead of
3065 Execution, ,Instead of Executing the Commands}.@refill
3067 Consider the command @samp{make -t} in the above example.  (The
3068 @samp{-t} option marks targets as up to date without actually running
3069 any commands; see @ref{Instead of Execution}.)  Following the usual
3070 definition of @samp{-t}, a @samp{make -t} command in the example would
3071 create a file named @file{subsystem} and do nothing else.  What you
3072 really want it to do is run @samp{@w{cd subdir;} @w{make -t}}; but that would
3073 require executing the command, and @samp{-t} says not to execute
3074 commands.@refill
3075 @cindex @code{-t}, and recursion
3076 @cindex recursion, and @code{-t}
3077 @cindex @code{--touch}, and recursion
3079 The special feature makes this do what you want: whenever a command
3080 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
3081 @samp{-n} and @samp{-q} do not apply to that line.  Command lines
3082 containing @code{MAKE} are executed normally despite the presence of a
3083 flag that causes most commands not to be run.  The usual
3084 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
3085 (@pxref{Options/Recursion, ,Communicating Options to a
3086 Sub-@code{make}}), so your request to touch the files, or print the
3087 commands, is propagated to the subsystem.@refill
3089 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
3090 @subsection Communicating Variables to a Sub-@code{make}
3091 @cindex sub-@code{make}
3092 @cindex environment, and recursion
3093 @cindex exporting variables
3094 @cindex variables, environment
3095 @cindex variables, exporting
3096 @cindex recursion, and environment
3097 @cindex recursion, and variables
3099 Variable values of the top-level @code{make} can be passed to the
3100 sub-@code{make} through the environment by explicit request.  These
3101 variables are defined in the sub-@code{make} as defaults, but do not
3102 override what is specified in the makefile used by the sub-@code{make}
3103 makefile unless you use the @samp{-e} switch (@pxref{Options Summary,
3104 ,Summary of Options}).@refill
3106 To pass down, or @dfn{export}, a variable, @code{make} adds the variable
3107 and its value to the environment for running each command.  The
3108 sub-@code{make}, in turn, uses the environment to initialize its table
3109 of variable values.  @xref{Environment, ,Variables from the
3110 Environment}.
3112 Except by explicit request, @code{make} exports a variable only if it
3113 is either defined in the environment initially or set on the command
3114 line, and if its name consists only of letters, numbers, and underscores.
3115 Some shells cannot cope with environment variable names consisting of
3116 characters other than letters, numbers, and underscores.
3118 The special variables @code{SHELL} and @code{MAKEFLAGS} are always
3119 exported (unless you unexport them).
3120 @code{MAKEFILES} is exported if you set it to anything.
3122 @code{make} automatically passes down variable values that were defined
3123 on the command line, by putting them in the @code{MAKEFLAGS} variable.
3124 @iftex
3125 See the next section.
3126 @end iftex
3127 @ifinfo
3128 @xref{Options/Recursion}.
3129 @end ifinfo
3131 Variables are @emph{not} normally passed down if they were created by
3132 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
3133 Implicit Rules}).  The sub-@code{make} will define these for
3134 itself.@refill
3136 @findex export
3137 If you want to export specific variables to a sub-@code{make}, use the
3138 @code{export} directive, like this:
3140 @example
3141 export @var{variable} @dots{}
3142 @end example
3144 @noindent
3145 @findex unexport
3146 If you want to @emph{prevent} a variable from being exported, use the
3147 @code{unexport} directive, like this:
3149 @example
3150 unexport @var{variable} @dots{}
3151 @end example
3153 @noindent
3154 As a convenience, you can define a variable and export it at the same
3155 time by doing:
3157 @example
3158 export @var{variable} = value
3159 @end example
3161 @noindent
3162 has the same result as:
3164 @example
3165 @var{variable} = value
3166 export @var{variable}
3167 @end example
3169 @noindent
3172 @example
3173 export @var{variable} := value
3174 @end example
3176 @noindent
3177 has the same result as:
3179 @example
3180 @var{variable} := value
3181 export @var{variable}
3182 @end example
3184 Likewise,
3186 @example
3187 export @var{variable} += value
3188 @end example
3190 @noindent
3191 is just like:
3193 @example
3194 @var{variable} += value
3195 export @var{variable}
3196 @end example
3198 @noindent
3199 @xref{Appending, ,Appending More Text to Variables}.
3201 You may notice that the @code{export} and @code{unexport} directives
3202 work in @code{make} in the same way they work in the shell, @code{sh}.
3204 If you want all variables to be exported by default, you can use
3205 @code{export} by itself:
3207 @example
3208 export
3209 @end example
3211 @noindent
3212 This tells @code{make} that variables which are not explicitly mentioned
3213 in an @code{export} or @code{unexport} directive should be exported.
3214 Any variable given in an @code{unexport} directive will still @emph{not}
3215 be exported.  If you use @code{export} by itself to export variables by
3216 default, variables whose names contain characters other than
3217 alphanumerics and underscores will not be exported unless specifically
3218 mentioned in an @code{export} directive.@refill
3220 @findex .EXPORT_ALL_VARIABLES
3221 The behavior elicited by an @code{export} directive by itself was the
3222 default in older versions of GNU @code{make}.  If your makefiles depend
3223 on this behavior and you want to be compatible with old versions of
3224 @code{make}, you can write a rule for the special target
3225 @code{.EXPORT_ALL_VARIABLES} instead of using the @code{export} directive.
3226 This will be ignored by old @code{make}s, while the @code{export}
3227 directive will cause a syntax error.@refill
3228 @cindex compatibility in exporting
3230 Likewise, you can use @code{unexport} by itself to tell @code{make}
3231 @emph{not} to export variables by default.  Since this is the default
3232 behavior, you would only need to do this if @code{export} had been used
3233 by itself earlier (in an included makefile, perhaps).  You
3234 @strong{cannot} use @code{export} and @code{unexport} by themselves to
3235 have variables exported for some commands and not for others.  The last
3236 @code{export} or @code{unexport} directive that appears by itself
3237 determines the behavior for the entire run of @code{make}.@refill
3239 @vindex MAKELEVEL
3240 @cindex recursion, level of
3241 As a special feature, the variable @code{MAKELEVEL} is changed when it
3242 is passed down from level to level.  This variable's value is a string
3243 which is the depth of the level as a decimal number.  The value is
3244 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
3245 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
3246 happens when @code{make} sets up the environment for a command.@refill
3248 The main use of @code{MAKELEVEL} is to test it in a conditional
3249 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
3250 way you can write a makefile that behaves one way if run recursively and
3251 another way if run directly by you.@refill
3253 @vindex MAKEFILES
3254 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
3255 commands to use additional makefiles.  The value of @code{MAKEFILES} is
3256 a whitespace-separated list of file names.  This variable, if defined in
3257 the outer-level makefile, is passed down through the environment; then
3258 it serves as a list of extra makefiles for the sub-@code{make} to read
3259 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
3260 Variable @code{MAKEFILES}}.@refill
3262 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
3263 @subsection Communicating Options to a Sub-@code{make}
3264 @cindex options, and recursion
3265 @cindex recursion, and options
3267 @vindex MAKEFLAGS
3268 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
3269 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
3270 set up automatically by @code{make} to contain the flag letters that
3271 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
3272 @code{MAKEFLAGS} gets the value @samp{ks}.@refill
3274 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
3275 in its environment.  In response, it takes the flags from that value and
3276 processes them as if they had been given as arguments.
3277 @xref{Options Summary, ,Summary of Options}.
3279 @cindex command line variable definitions, and recursion
3280 @cindex variables, command line, and recursion
3281 @cindex recursion, and command line variable definitions
3282 Likewise variables defined on the command line are passed to the
3283 sub-@code{make} through @code{MAKEFLAGS}.  Words in the value of
3284 @code{MAKEFLAGS} that contain @samp{=}, @code{make} treats as variable
3285 definitions just as if they appeared on the command line.
3286 @xref{Overriding, ,Overriding Variables}.
3288 @cindex @code{-C}, and recursion
3289 @cindex @code{-f}, and recursion
3290 @cindex @code{-o}, and recursion
3291 @cindex @code{-W}, and recursion
3292 @cindex @code{--directory}, and recursion
3293 @cindex @code{--file}, and recursion
3294 @cindex @code{--old-file}, and recursion
3295 @cindex @code{--assume-old}, and recursion
3296 @cindex @code{--assume-new}, and recursion
3297 @cindex @code{--new-file}, and recursion
3298 @cindex recursion, and @code{-C}
3299 @cindex recursion, and @code{-f}
3300 @cindex recursion, and @code{-o}
3301 @cindex recursion, and @code{-W}
3302 The options @samp{-C}, @samp{-f}, @samp{-o}, and @samp{-W} are not put
3303 into @code{MAKEFLAGS}; these options are not passed down.@refill
3305 @cindex @code{-j}, and recursion
3306 @cindex @code{--jobs}, and recursion
3307 @cindex recursion, and @code{-j}
3308 @cindex job slots, and recursion
3309 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
3310 If you set it to some numeric value, @samp{-j 1} is always put into
3311 @code{MAKEFLAGS} instead of the value you specified.  This is because if
3312 the @w{@samp{-j}} option were passed down to sub-@code{make}s, you would
3313 get many more jobs running in parallel than you asked for.  If you give
3314 @samp{-j} with no numeric argument, meaning to run as many jobs as
3315 possible in parallel, this is passed down, since multiple infinities are
3316 no more than one.@refill
3318 If you do not want to pass the other flags down, you must change the
3319 value of @code{MAKEFLAGS}, like this:
3321 @example
3322 MAKEFLAGS=
3323 subsystem:
3324         cd subdir; $(MAKE)
3325 @end example
3327 or like this:
3329 @example
3330 subsystem:
3331         cd subdir; $(MAKE) MAKEFLAGS=
3332 @end example
3334 @vindex MAKEOVERRIDES
3335 The command line variable definitions really appear in the variable
3336 @code{MAKEOVERRIDES}, and @code{MAKEFLAGS} contains a reference to this
3337 variable.  If you do want to pass flags down normally, but don't want to
3338 pass down the command line variable definitions, you can reset
3339 @code{MAKEOVERRIDES} to empty, like this:
3341 @example
3342 MAKEOVERRIDES =
3343 @end example
3345 @noindent
3346 @cindex Arg list too long
3347 @cindex E2BIG
3348 This is not usually useful to do.  However, some systems have a small
3349 fixed limit on the size of the environment, and putting so much
3350 information in into the value of @code{MAKEFLAGS} can exceed it.
3351 If you see the error message @samp{Arg list too long}, this may be the problem.
3352 @findex .POSIX
3353 @cindex POSIX.2
3354 (For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
3355 not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
3356 in the makefile.  You probably do not care about this.)
3358 @vindex MFLAGS
3359 A similar variable @code{MFLAGS} exists also, for historical
3360 compatibility.  It has the same value as @code{MAKEFLAGS} except that it
3361 does not contain the command line variable definitions, and it always
3362 begins with a hyphen unless it is empty (@code{MAKEFLAGS} begins with a
3363 hyphen only when it begins with an option that has no single-letter
3364 version, such as @samp{--warn-undefined-variables}).  @code{MFLAGS} was
3365 traditionally used explicitly in the recursive @code{make} command, like
3366 this:
3368 @example
3369 subsystem:
3370         cd subdir; $(MAKE) $(MFLAGS)
3371 @end example
3373 @noindent
3374 but now @code{MAKEFLAGS} makes this usage redundant.  If you want your
3375 makefiles to be compatible with old @code{make} programs, use this
3376 technique; it will work fine with more modern @code{make} versions too.
3378 @cindex setting options from environment
3379 @cindex options, setting from environment
3380 @cindex setting options in makefiles
3381 @cindex options, setting in makefiles
3382 The @code{MAKEFLAGS} variable can also be useful if you want to have
3383 certain options, such as @samp{-k} (@pxref{Options Summary, ,Summary of
3384 Options}), set each time you run @code{make}.  You simply put a value for
3385 @code{MAKEFLAGS} in your environment.  You can also set @code{MAKEFLAGS} in
3386 a makefile, to specify additional flags that should also be in effect for
3387 that makefile.  (Note that you cannot use @code{MFLAGS} this way.  That
3388 variable is set only for compatibility; @code{make} does not interpret a
3389 value you set for it in any way.)
3391 When @code{make} interprets the value of @code{MAKEFLAGS} (either from the
3392 environment or from a makefile), it first prepends a hyphen if the value
3393 does not already begin with one.  Then it chops the value into words
3394 separated by blanks, and parses these words as if they were options given
3395 on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
3396 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
3397 is no error for an invalid option).
3399 If you do put @code{MAKEFLAGS} in your environment, you should be sure not
3400 to include any options that will drastically affect the actions of
3401 @code{make} and undermine the purpose of makefiles and of @code{make}
3402 itself.  For instance, the @samp{-t}, @samp{-n}, and @samp{-q} options, if
3403 put in one of these variables, could have disastrous consequences and would
3404 certainly have at least surprising and probably annoying effects.@refill
3406 @node -w Option,  , Options/Recursion, Recursion
3407 @subsection The @samp{--print-directory} Option
3408 @cindex directories, printing them
3409 @cindex printing directories
3410 @cindex recursion, and printing directories
3412 If you use several levels of recursive @code{make} invocations, the
3413 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
3414 lot easier to understand by showing each directory as @code{make}
3415 starts processing it and as @code{make} finishes processing it.  For
3416 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
3417 @code{make} will print a line of the form:@refill
3419 @example
3420 make: Entering directory `/u/gnu/make'.
3421 @end example
3423 @noindent
3424 before doing anything else, and a line of the form:
3426 @example
3427 make: Leaving directory `/u/gnu/make'.
3428 @end example
3430 @noindent
3431 when processing is completed.
3433 @cindex @code{-C}, and @code{-w}
3434 @cindex @code{--directory}, and @code{--print-directory}
3435 @cindex recursion, and @code{-w}
3436 @cindex @code{-w}, and @code{-C}
3437 @cindex @code{-w}, and recursion
3438 @cindex @code{--print-directory}, and @code{--directory}
3439 @cindex @code{--print-directory}, and recursion
3440 @cindex @code{--no-print-directory}
3441 @cindex @code{--print-directory}, disabling
3442 @cindex @code{-w}, disabling
3443 Normally, you do not need to specify this option because @samp{make}
3444 does it for you: @samp{-w} is turned on automatically when you use the
3445 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
3446 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
3447 be silent, or if you use @samp{--no-print-directory} to explicitly
3448 disable it.
3450 @node Sequences, Empty Commands, Recursion, Commands
3451 @section Defining Canned Command Sequences
3452 @cindex sequences of commands
3453 @cindex commands, sequences of
3455 When the same sequence of commands is useful in making various targets, you
3456 can define it as a canned sequence with the @code{define} directive, and
3457 refer to the canned sequence from the rules for those targets.  The canned
3458 sequence is actually a variable, so the name must not conflict with other
3459 variable names.
3461 Here is an example of defining a canned sequence of commands:
3463 @example
3464 define run-yacc
3465 yacc $(firstword $^)
3466 mv y.tab.c $@@
3467 endef
3468 @end example
3469 @cindex @code{yacc}
3471 @noindent
3472 Here @code{run-yacc} is the name of the variable being defined;
3473 @code{endef} marks the end of the definition; the lines in between are the
3474 commands.  The @code{define} directive does not expand variable references
3475 and function calls in the canned sequence; the @samp{$} characters,
3476 parentheses, variable names, and so on, all become part of the value of the
3477 variable you are defining.
3478 @xref{Defining, ,Defining Variables Verbatim},
3479 for a complete explanation of @code{define}.
3481 The first command in this example runs Yacc on the first dependency of
3482 whichever rule uses the canned sequence.  The output file from Yacc is
3483 always named @file{y.tab.c}.  The second command moves the output to the
3484 rule's target file name.
3486 To use the canned sequence, substitute the variable into the commands of a
3487 rule.  You can substitute it like any other variable 
3488 (@pxref{Reference, ,Basics of Variable References}).
3489 Because variables defined by @code{define} are recursively expanded
3490 variables, all the variable references you wrote inside the @code{define}
3491 are expanded now.  For example:
3493 @example
3494 foo.c : foo.y
3495         $(run-yacc)
3496 @end example
3498 @noindent
3499 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
3500 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.@refill
3502 This is a realistic example, but this particular one is not needed in
3503 practice because @code{make} has an implicit rule to figure out these
3504 commands based on the file names involved 
3505 (@pxref{Implicit Rules, ,Using Implicit Rules}).
3507 @cindex @@, and @code{define}
3508 @cindex -, and @code{define}
3509 @cindex +, and @code{define}
3510 In command execution, each line of a canned sequence is treated just as
3511 if the line appeared on its own in the rule, preceded by a tab.  In
3512 particular, @code{make} invokes a separate subshell for each line.  You
3513 can use the special prefix characters that affect command lines
3514 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
3515 @xref{Commands, ,Writing the Commands in Rules}.
3516 For example, using this canned sequence:
3518 @example
3519 define frobnicate
3520 @@echo "frobnicating target $@@"
3521 frob-step-1 $< -o $@@-step-1
3522 frob-step-2 $@@-step-1 -o $@@
3523 endef
3524 @end example
3526 @noindent
3527 @code{make} will not echo the first line, the @code{echo} command.
3528 But it @emph{will} echo the following two command lines.
3530 On the other hand, prefix characters on the command line that refers to
3531 a canned sequence apply to every line in the sequence.  So the rule:
3533 @example
3534 frob.out: frob.in
3535         @@$(frobnicate)
3536 @end example
3538 @noindent
3539 does not echo @emph{any} commands.
3540 (@xref{Echoing, ,Command Echoing}, for a full explanation of @samp{@@}.)
3542 @node Empty Commands,  , Sequences, Commands
3543 @section Using Empty Commands
3544 @cindex empty commands
3545 @cindex commands, empty
3547 It is sometimes useful to define commands which do nothing.  This is done
3548 simply by giving a command that consists of nothing but whitespace.  For
3549 example:
3551 @example
3552 target: ;
3553 @end example
3555 @noindent
3556 defines an empty command string for @file{target}.  You could also use a
3557 line beginning with a tab character to define an empty command string,
3558 but this would be confusing because such a line looks empty.
3560 @findex .DEFAULT@r{, and empty commands}
3561 You may be wondering why you would want to define a command string that
3562 does nothing.  The only reason this is useful is to prevent a target
3563 from getting implicit commands (from implicit rules or the
3564 @code{.DEFAULT} special target; @pxref{Implicit Rules} and 
3565 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
3567 @c !!! another reason is for canonical stamp files:
3568 @ignore
3569 foo: stamp-foo ;
3570 stamp-foo: foo.in
3571         create foo frm foo.in
3572         touch $@
3573 @end ignore
3575 You may be inclined to define empty command strings for targets that are
3576 not actual files, but only exist so that their dependencies can be
3577 remade.  However, this is not the best way to do that, because the
3578 dependencies may not be remade properly if the target file actually does exist.
3579 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
3581 @node Using Variables, Conditionals, Commands, Top
3582 @chapter How to Use Variables
3583 @cindex variable
3584 @cindex value
3585 @cindex recursive variable expansion
3586 @cindex simple variable expansion
3588 A @dfn{variable} is a name defined in a makefile to represent a string
3589 of text, called the variable's @dfn{value}.  These values are
3590 substituted by explicit request into targets, dependencies, commands,
3591 and other parts of the makefile.  (In some other versions of @code{make},
3592 variables are called @dfn{macros}.)
3593 @cindex macro
3595 Variables and functions in all parts of a makefile are expanded when
3596 read, except for the shell commands in rules, the right-hand sides of
3597 variable definitions using @samp{=}, and the bodies of variable
3598 definitions using the @code{define} directive.@refill
3600 Variables can represent lists of file names, options to pass to compilers,
3601 programs to run, directories to look in for source files, directories to
3602 write output in, or anything else you can imagine.
3604 A variable name may be any sequence of characters not containing @samp{:},
3605 @samp{#}, @samp{=}, or leading or trailing whitespace.  However,
3606 variable names containing characters other than letters, numbers, and
3607 underscores should be avoided, as they may be given special meanings in the
3608 future, and with some shells they cannot be passed through the environment to a
3609 sub-@code{make} 
3610 (@pxref{Variables/Recursion, ,Communicating Variables to a Sub-@code{make}}).
3612 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
3613 and @samp{Foo} all refer to different variables.
3615 It is traditional to use upper case letters in variable names, but we
3616 recommend using lower case letters for variable names that serve internal
3617 purposes in the makefile, and reserving upper case for parameters that
3618 control implicit rules or for parameters that the user should override with
3619 command options (@pxref{Overriding, ,Overriding Variables}).
3621 A few variables have names that are a single punctuation character or
3622 just a few characters.  These are the @dfn{automatic variables}, and
3623 they have particular specialized uses.  @xref{Automatic, ,Automatic Variables}.
3625 @menu
3626 * Reference::                   How to use the value of a variable.
3627 * Flavors::                     Variables come in two flavors.
3628 * Advanced::                    Advanced features for referencing a variable.
3629 * Values::                      All the ways variables get their values.
3630 * Setting::                     How to set a variable in the makefile.
3631 * Appending::                   How to append more text to the old value
3632                                   of a variable.
3633 * Override Directive::          How to set a variable in the makefile even if
3634                                   the user has set it with a command argument.
3635 * Defining::                    An alternate way to set a variable 
3636                                   to a verbatim string.
3637 * Environment::                 Variable values can come from the environment.
3638 * Automatic::                   Some special variables have predefined
3639                                   meanings for use with implicit rules.
3640 @end menu
3642 @node Reference, Flavors,  , Using Variables
3643 @section Basics of Variable References
3644 @cindex variables, how to reference
3645 @cindex reference to variables
3646 @cindex @code{$}, in variable reference
3647 @cindex dollar sign (@code{$}), in variable reference
3649 To substitute a variable's value, write a dollar sign followed by the name
3650 of the variable in parentheses or braces: either @samp{$(foo)} or
3651 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
3652 special significance of @samp{$} is why you must write @samp{$$} to have
3653 the effect of a single dollar sign in a file name or command.
3655 Variable references can be used in any context: targets, dependencies,
3656 commands, most directives, and new variable values.  Here is an
3657 example of a common case, where a variable holds the names of all the
3658 object files in a program:
3660 @example
3661 @group
3662 objects = program.o foo.o utils.o
3663 program : $(objects)
3664         cc -o program $(objects)
3666 $(objects) : defs.h
3667 @end group
3668 @end example
3670 Variable references work by strict textual substitution.  Thus, the rule
3672 @example
3673 @group
3674 foo = c
3675 prog.o : prog.$(foo)
3676         $(foo)$(foo) -$(foo) prog.$(foo)
3677 @end group
3678 @end example
3680 @noindent
3681 could be used to compile a C program @file{prog.c}.  Since spaces before
3682 the variable value are ignored in variable assignments, the value of
3683 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
3684 this way!)
3686 A dollar sign followed by a character other than a dollar sign,
3687 open-parenthesis or open-brace treats that single character as the
3688 variable name.  Thus, you could reference the variable @code{x} with
3689 @samp{$x}.  However, this practice is strongly discouraged, except in
3690 the case of the automatic variables (@pxref{Automatic, ,Automatic Variables}).
3692 @node Flavors, Advanced, Reference, Using Variables
3693 @section The Two Flavors of Variables
3694 @cindex flavors of variables
3695 @cindex recursive variable expansion
3696 @cindex variables, flavors
3697 @cindex recursively expanded variables
3698 @cindex variables, recursively expanded
3700 There are two ways that a variable in GNU @code{make} can have a value;
3701 we call them the two @dfn{flavors} of variables.  The two flavors are
3702 distinguished in how they are defined and in what they do when expanded.
3704 @cindex =
3705 The first flavor of variable is a @dfn{recursively expanded} variable.
3706 Variables of this sort are defined by lines using @samp{=}
3707 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
3708 (@pxref{Defining, ,Defining Variables Verbatim}).  The value you specify
3709 is installed verbatim; if it contains references to other variables,
3710 these references are expanded whenever this variable is substituted (in
3711 the course of expanding some other string).  When this happens, it is
3712 called @dfn{recursive expansion}.@refill
3714 For example,
3716 @example
3717 foo = $(bar)
3718 bar = $(ugh)
3719 ugh = Huh?
3721 all:;echo $(foo)
3722 @end example
3724 @noindent
3725 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
3726 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
3728 This flavor of variable is the only sort supported by other versions of
3729 @code{make}.  It has its advantages and its disadvantages.  An advantage
3730 (most would say) is that:
3732 @example
3733 CFLAGS = $(include_dirs) -O
3734 include_dirs = -Ifoo -Ibar
3735 @end example
3737 @noindent
3738 will do what was intended: when @samp{CFLAGS} is expanded in a command,
3739 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
3740 cannot append something on the end of a variable, as in
3742 @example
3743 CFLAGS = $(CFLAGS) -O
3744 @end example
3746 @noindent
3747 because it will cause an infinite loop in the variable expansion.
3748 (Actually @code{make} detects the infinite loop and reports an error.)
3749 @cindex loops in variable expansion
3750 @cindex variables, loops in expansion
3752 Another disadvantage is that any functions 
3753 (@pxref{Functions, ,Functions for Transforming Text})
3754 referenced in the definition will be executed every time the variable is
3755 expanded.  This makes @code{make} run slower; worse, it causes the
3756 @code{wildcard} and @code{shell} functions to give unpredictable results
3757 because you cannot easily control when they are called, or even how many
3758 times.
3760 To avoid all the problems and inconveniences of recursively expanded
3761 variables, there is another flavor: simply expanded variables.
3763 @cindex simply expanded variables
3764 @cindex variables, simply expanded
3765 @cindex :=
3766 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
3767 (@pxref{Setting, ,Setting Variables}).  
3768 The value of a simply expanded variable is scanned
3769 once and for all, expanding any references to other variables and
3770 functions, when the variable is defined.  The actual value of the simply
3771 expanded variable is the result of expanding the text that you write.
3772 It does not contain any references to other variables; it contains their
3773 values @emph{as of the time this variable was defined}.  Therefore,
3775 @example
3776 x := foo
3777 y := $(x) bar
3778 x := later
3779 @end example
3781 @noindent
3782 is equivalent to
3784 @example
3785 y := foo bar
3786 x := later
3787 @end example
3789 When a simply expanded variable is referenced, its value is substituted
3790 verbatim.
3792 Here is a somewhat more complicated example, illustrating the use of
3793 @samp{:=} in conjunction with the @code{shell} function.
3794 (@xref{Shell Function, , The @code{shell} Function}.)  This example
3795 also shows use of the variable @code{MAKELEVEL}, which is changed
3796 when it is passed down from level to level.
3797 (@xref{Variables/Recursion, , Communicating Variables to a
3798 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
3800 @vindex MAKELEVEL
3801 @vindex MAKE
3802 @example
3803 @group
3804 ifeq (0,$@{MAKELEVEL@})
3805 cur-dir   := $(shell pwd)
3806 whoami    := $(shell whoami)
3807 host-type := $(shell arch)
3808 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
3809 endif
3810 @end group
3811 @end example
3813 @noindent 
3814 An advantage of this use of @samp{:=} is that a typical
3815 `descend into a directory' command then looks like this:
3817 @example
3818 @group
3819 $@{subdirs@}:
3820       $@{MAKE@} cur-dir=$@{cur-dir@}/$@@ -C $@@ all
3821 @end group
3822 @end example
3824 Simply expanded variables generally make complicated makefile programming
3825 more predictable because they work like variables in most programming
3826 languages.  They allow you to redefine a variable using its own value (or
3827 its value processed in some way by one of the expansion functions) and to
3828 use the expansion functions much more efficiently 
3829 (@pxref{Functions, ,Functions for Transforming Text}).
3831 @cindex spaces, in variable values
3832 @cindex whitespace, in variable values
3833 @cindex variables, spaces in values
3834 You can also use them to introduce controlled leading whitespace into
3835 variable values.  Leading whitespace characters are discarded from your
3836 input before substitution of variable references and function calls;
3837 this means you can include leading spaces in a variable value by
3838 protecting them with variable references, like this:
3840 @example
3841 nullstring :=
3842 space := $(nullstring) # end of the line
3843 @end example
3845 @noindent
3846 Here the value of the variable @code{space} is precisely one space.  The
3847 comment @w{@samp{# end of the line}} is included here just for clarity.
3848 Since trailing space characters are @emph{not} stripped from variable
3849 values, just a space at the end of the line would have the same effect
3850 (but be rather hard to read).  If you put whitespace at the end of a
3851 variable value, it is a good idea to put a comment like that at the end
3852 of the line to make your intent clear.  Conversely, if you do @emph{not}
3853 want any whitespace characters at the end of your variable value, you
3854 must remember not to put a random comment on the end of the line after
3855 some whitespace, such as this:
3857 @example
3858 dir := /foo/bar    # directory to put the frobs in
3859 @end example
3861 @noindent
3862 Here the value of the variable @code{dir} is @w{@samp{/foo/bar    }}
3863 (with four trailing spaces), which was probably not the intention.
3864 (Imagine something like @w{@samp{$(dir)/file}} with this definition!)
3866 @node Advanced, Values, Flavors, Using Variables
3867 @section Advanced Features for Reference to Variables
3868 @cindex reference to variables
3870 This section describes some advanced features you can use to reference
3871 variables in more flexible ways.
3873 @menu
3874 * Substitution Refs::           Referencing a variable with 
3875                                   substitutions on the value.
3876 * Computed Names::              Computing the name of the variable to refer to.
3877 @end menu
3879 @node Substitution Refs, Computed Names,  , Advanced
3880 @subsection Substitution References
3881 @cindex modified variable reference
3882 @cindex substitution variable reference
3883 @cindex variables, modified reference
3884 @cindex variables, substitution reference
3886 @cindex variables, substituting suffix in
3887 @cindex suffix, substituting in variables
3888 A @dfn{substitution reference} substitutes the value of a variable with
3889 alterations that you specify.  It has the form
3890 @samp{$(@var{var}:@var{a}=@var{b})} (or
3891 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
3892 of the variable @var{var}, replace every @var{a} at the end of a word with
3893 @var{b} in that value, and substitute the resulting string.
3895 When we say ``at the end of a word'', we mean that @var{a} must appear
3896 either followed by whitespace or at the end of the value in order to be
3897 replaced; other occurrences of @var{a} in the value are unaltered.  For
3898 example:@refill
3900 @example
3901 foo := a.o b.o c.o
3902 bar := $(foo:.o=.c)
3903 @end example
3905 @noindent
3906 sets @samp{bar} to @samp{a.c b.c c.c}.  @xref{Setting, ,Setting Variables}.
3908 A substitution reference is actually an abbreviation for use of the
3909 @code{patsubst} expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}).  We provide
3910 substitution references as well as @code{patsubst} for compatibility with
3911 other implementations of @code{make}.
3913 @findex patsubst
3914 Another type of substitution reference lets you use the full power of
3915 the @code{patsubst} function.  It has the same form
3916 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
3917 @var{a} must contain a single @samp{%} character.  This case is
3918 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
3919 @xref{Text Functions, ,Functions for String Substitution and Analysis},
3920 for a description of the @code{patsubst} function.@refill
3922 @example
3923 @group
3924 @exdent For example:
3926 foo := a.o b.o c.o
3927 bar := $(foo:%.o=%.c)
3928 @end group
3929 @end example
3931 @noindent
3932 sets @samp{bar} to @samp{a.c b.c c.c}.
3934 @node Computed Names,  , Substitution Refs, Advanced
3935 @subsection Computed Variable Names
3936 @cindex nested variable reference
3937 @cindex computed variable name
3938 @cindex variables, computed names
3939 @cindex variables, nested references
3940 @cindex variables, @samp{$} in name
3941 @cindex @code{$}, in variable name
3942 @cindex dollar sign (@code{$}), in variable name
3944 Computed variable names are a complicated concept needed only for
3945 sophisticated makefile programming.  For most purposes you need not
3946 consider them, except to know that making a variable with a dollar sign
3947 in its name might have strange results.  However, if you are the type
3948 that wants to understand everything, or you are actually interested in
3949 what they do, read on.
3951 Variables may be referenced inside the name of a variable.  This is
3952 called a @dfn{computed variable name} or a @dfn{nested variable
3953 reference}.  For example,
3955 @example
3956 x = y
3957 y = z
3958 a := $($(x))
3959 @end example
3961 @noindent
3962 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
3963 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
3964 to @samp{z}.  Here the name of the variable to reference is not stated
3965 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
3966 @samp{$(x)} here is nested within the outer variable reference.
3968 The previous example shows two levels of nesting, but any number of levels
3969 is possible.  For example, here are three levels:
3971 @example
3972 x = y
3973 y = z
3974 z = u
3975 a := $($($(x)))
3976 @end example
3978 @noindent
3979 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
3980 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
3981 @samp{$(z)}, which becomes @samp{u}.
3983 References to recursively-expanded variables within a variable name are
3984 reexpanded in the usual fashion.  For example:
3986 @example
3987 x = $(y)
3988 y = z
3989 z = Hello
3990 a := $($(x))
3991 @end example
3993 @noindent
3994 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
3995 which becomes @samp{$(z)} which becomes @samp{Hello}.
3997 Nested variable references can also contain modified references and
3998 function invocations (@pxref{Functions, ,Functions for Transforming Text}),
3999 just like any other reference.
4000 For example, using the @code{subst} function 
4001 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
4003 @example
4004 @group
4005 x = variable1
4006 variable2 := Hello
4007 y = $(subst 1,2,$(x))
4008 z = y
4009 a := $($($(z)))
4010 @end group
4011 @end example
4013 @noindent
4014 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
4015 would ever want to write a nested reference as convoluted as this one, but
4016 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
4017 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
4018 @code{x} and changes it by substitution to @samp{variable2}, so that the
4019 entire string becomes @samp{$(variable2)}, a simple variable reference
4020 whose value is @samp{Hello}.@refill
4022 A computed variable name need not consist entirely of a single variable
4023 reference.  It can contain several variable references, as well as some
4024 invariant text.  For example,
4026 @example
4027 @group
4028 a_dirs := dira dirb
4029 1_dirs := dir1 dir2
4030 @end group
4032 @group
4033 a_files := filea fileb
4034 1_files := file1 file2
4035 @end group
4037 @group
4038 ifeq "$(use_a)" "yes"
4039 a1 := a
4040 else
4041 a1 := 1
4042 endif
4043 @end group
4045 @group
4046 ifeq "$(use_dirs)" "yes"
4047 df := dirs
4048 else
4049 df := files
4050 endif
4052 dirs := $($(a1)_$(df))
4053 @end group
4054 @end example
4056 @noindent
4057 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
4058 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
4059 and @code{use_dirs}.@refill
4061 Computed variable names can also be used in substitution references:
4063 @example
4064 @group
4065 a_objects := a.o b.o c.o
4066 1_objects := 1.o 2.o 3.o
4068 sources := $($(a1)_objects:.o=.c)
4069 @end group
4070 @end example
4072 @noindent
4073 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
4074 depending on the value of @code{a1}.
4076 The only restriction on this sort of use of nested variable references
4077 is that they cannot specify part of the name of a function to be called.
4078 This is because the test for a recognized function name is done before
4079 the expansion of nested references.  For example,
4081 @example
4082 @group
4083 ifdef do_sort
4084 func := sort
4085 else
4086 func := strip
4087 endif
4088 @end group
4090 @group
4091 bar := a d b g q c
4092 @end group
4094 @group
4095 foo := $($(func) $(bar))
4096 @end group
4097 @end example
4099 @noindent
4100 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
4101 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
4102 as the argument to either the @code{sort} or the @code{strip} function.
4103 This restriction could be removed in the future if that change is shown
4104 to be a good idea.
4106 You can also use computed variable names in the left-hand side of a
4107 variable assignment, or in a @code{define} directive, as in:
4109 @example
4110 dir = foo
4111 $(dir)_sources := $(wildcard $(dir)/*.c)
4112 define $(dir)_print
4113 lpr $($(dir)_sources)
4114 endef
4115 @end example
4117 @noindent
4118 This example defines the variables @samp{dir}, @samp{foo_sources}, and
4119 @samp{foo_print}.
4121 Note that @dfn{nested variable references} are quite different from
4122 @dfn{recursively expanded variables}
4123 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
4124 used together in complex ways when doing makefile programming.@refill
4126 @node Values, Setting, Advanced, Using Variables
4127 @section How Variables Get Their Values
4128 @cindex variables, how they get their values
4129 @cindex value, how a variable gets it
4131 Variables can get values in several different ways:
4133 @itemize @bullet
4134 @item
4135 You can specify an overriding value when you run @code{make}.
4136 @xref{Overriding, ,Overriding Variables}.
4138 @item
4139 You can specify a value in the makefile, either
4140 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
4141 verbatim definition (@pxref{Defining, ,Defining Variables Verbatim}).@refill
4143 @item
4144 Variables in the environment become @code{make} variables.
4145 @xref{Environment, ,Variables from the Environment}.
4147 @item
4148 Several @dfn{automatic} variables are given new values for each rule.
4149 Each of these has a single conventional use.
4150 @xref{Automatic, ,Automatic Variables}.
4152 @item
4153 Several variables have constant initial values.
4154 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
4155 @end itemize
4157 @node Setting, Appending, Values, Using Variables
4158 @section Setting Variables
4159 @cindex setting variables
4160 @cindex variables, setting
4161 @cindex =
4162 @cindex :=
4164 To set a variable from the makefile, write a line starting with the
4165 variable name followed by @samp{=} or @samp{:=}.  Whatever follows the
4166 @samp{=} or @samp{:=} on the line becomes the value.  For example,
4168 @example
4169 objects = main.o foo.o bar.o utils.o
4170 @end example
4172 @noindent
4173 defines a variable named @code{objects}.  Whitespace around the variable
4174 name and immediately after the @samp{=} is ignored.
4176 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
4177 Variables defined with @samp{:=} are @dfn{simply expanded} variables; these
4178 definitions can contain variable references which will be expanded before
4179 the definition is made.  @xref{Flavors, ,The Two Flavors of Variables}.
4181 The variable name may contain function and variable references, which
4182 are expanded when the line is read to find the actual variable name to use.
4184 There is no limit on the length of the value of a variable except the
4185 amount of swapping space on the computer.  When a variable definition is
4186 long, it is a good idea to break it into several lines by inserting
4187 backslash-newline at convenient places in the definition.  This will not
4188 affect the functioning of @code{make}, but it will make the makefile easier
4189 to read.
4191 Most variable names are considered to have the empty string as a value if
4192 you have never set them.  Several variables have built-in initial values
4193 that are not empty, but you can set them in the usual ways
4194 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).  
4195 Several special variables are set
4196 automatically to a new value for each rule; these are called the
4197 @dfn{automatic} variables (@pxref{Automatic, ,Automatic Variables}).
4199 @node Appending, Override Directive, Setting, Using Variables
4200 @section Appending More Text to Variables
4201 @cindex +=
4202 @cindex appending to variables
4203 @cindex variables, appending to
4205 Often it is useful to add more text to the value of a variable already defined.
4206 You do this with a line containing @samp{+=}, like this:
4208 @example
4209 objects += another.o
4210 @end example
4212 @noindent
4213 This takes the value of the variable @code{objects}, and adds the text
4214 @samp{another.o} to it (preceded by a single space).  Thus:
4216 @example
4217 objects = main.o foo.o bar.o utils.o
4218 objects += another.o
4219 @end example
4221 @noindent
4222 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
4224 Using @samp{+=} is similar to:
4226 @example
4227 objects = main.o foo.o bar.o utils.o
4228 objects := $(objects) another.o
4229 @end example
4231 @noindent
4232 but differs in ways that become important when you use more complex values.
4234 When the variable in question has not been defined before, @samp{+=}
4235 acts just like normal @samp{=}: it defines a recursively-expanded
4236 variable.  However, when there @emph{is} a previous definition, exactly
4237 what @samp{+=} does depends on what flavor of variable you defined
4238 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
4239 explanation of the two flavors of variables.
4241 When you add to a variable's value with @samp{+=}, @code{make} acts
4242 essentially as if you had included the extra text in the initial
4243 definition of the variable.  If you defined it first with @samp{:=},
4244 making it a simply-expanded variable, @samp{+=} adds to that
4245 simply-expanded definition, and expands the new text before appending it
4246 to the old value just as @samp{:=} does
4247 (@pxref{Setting, ,Setting Variables}, for a full explanation of @samp{:=}).
4248 In fact,
4250 @example
4251 variable := value
4252 variable += more
4253 @end example
4255 @noindent
4256 is exactly equivalent to:
4258 @noindent
4259 @example
4260 variable := value
4261 variable := $(variable) more
4262 @end example
4264 On the other hand, when you use @samp{+=} with a variable that you defined
4265 first to be recursively-expanded using plain @samp{=}, @code{make} does
4266 something a bit different.  Recall that when you define a
4267 recursively-expanded variable, @code{make} does not expand the value you set
4268 for variable and function references immediately.  Instead it stores the text
4269 verbatim, and saves these variable and function references to be expanded
4270 later, when you refer to the new variable (@pxref{Flavors, ,The Two Flavors
4271 of Variables}).  When you use @samp{+=} on a recursively-expanded variable,
4272 it is this unexpanded text to which @code{make} appends the new text you
4273 specify.
4275 @example
4276 @group
4277 variable = value
4278 variable += more
4279 @end group
4280 @end example
4282 @noindent
4283 is roughly equivalent to:
4285 @example
4286 @group
4287 temp = value
4288 variable = $(temp) more
4289 @end group
4290 @end example
4292 @noindent
4293 except that of course it never defines a variable called @code{temp}.
4294 The importance of this comes when the variable's old value contains
4295 variable references.  Take this common example:
4297 @example
4298 CFLAGS = $(includes) -O
4299 @dots{}
4300 CFLAGS += -pg # enable profiling
4301 @end example
4303 @noindent
4304 The first line defines the @code{CFLAGS} variable with a reference to another
4305 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
4306 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
4307 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
4308 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
4309 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
4310 need not be defined yet for its value to take effect.  It only has to be
4311 defined before any reference to @code{CFLAGS}.  If we tried to append to the
4312 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
4314 @example
4315 CFLAGS := $(CFLAGS) -pg # enable profiling
4316 @end example
4318 @noindent
4319 This is pretty close, but not quite what we want.  Using @samp{:=}
4320 redefines @code{CFLAGS} as a simply-expanded variable; this means
4321 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
4322 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
4323 -pg}}, and a later definition of @code{includes} will have no effect.
4324 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
4325 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
4326 the reference to @code{includes}, so if that variable gets defined at
4327 any later point, a reference like @samp{$(CFLAGS)} still uses its
4328 value.
4330 @node Override Directive, Defining, Appending, Using Variables
4331 @section The @code{override} Directive
4332 @findex override
4333 @cindex overriding with @code{override}
4334 @cindex variables, overriding
4336 If a variable has been set with a command argument 
4337 (@pxref{Overriding, ,Overriding Variables}),
4338 then ordinary assignments in the makefile are ignored.  If you want to set
4339 the variable in the makefile even though it was set with a command
4340 argument, you can use an @code{override} directive, which is a line that
4341 looks like this:@refill
4343 @example
4344 override @var{variable} = @var{value}
4345 @end example
4347 @noindent
4350 @example
4351 override @var{variable} := @var{value}
4352 @end example
4354 To append more text to a variable defined on the command line, use:
4356 @example
4357 override @var{variable} += @var{more text}
4358 @end example
4360 @noindent
4361 @xref{Appending, ,Appending More Text to Variables}.
4363 The @code{override} directive was not invented for escalation in the war
4364 between makefiles and command arguments.  It was invented so you can alter
4365 and add to values that the user specifies with command arguments.
4367 For example, suppose you always want the @samp{-g} switch when you run the
4368 C compiler, but you would like to allow the user to specify the other
4369 switches with a command argument just as usual.  You could use this
4370 @code{override} directive:
4372 @example
4373 override CFLAGS += -g
4374 @end example
4376 You can also use @code{override} directives with @code{define} directives.
4377 This is done as you might expect:
4379 @example
4380 override define foo
4382 endef
4383 @end example
4385 @noindent
4386 @iftex
4387 See the next section for information about @code{define}.
4388 @end iftex
4389 @ifinfo
4390 @xref{Defining, ,Defining Variables Verbatim}.
4391 @end ifinfo
4393 @node Defining, Environment, Override Directive, Using Variables
4394 @section Defining Variables Verbatim
4395 @findex define
4396 @findex endef
4397 @cindex verbatim variable definition
4398 @cindex defining variables verbatim
4399 @cindex variables, defining verbatim
4401 Another way to set the value of a variable is to use the @code{define}
4402 directive.  This directive has an unusual syntax which allows newline
4403 characters to be included in the value, which is convenient for defining
4404 canned sequences of commands 
4405 (@pxref{Sequences, ,Defining Canned Command Sequences}).
4407 The @code{define} directive is followed on the same line by the name of the
4408 variable and nothing more.  The value to give the variable appears on the
4409 following lines.  The end of the value is marked by a line containing just
4410 the word @code{endef}.  Aside from this difference in syntax, @code{define}
4411 works just like @samp{=}: it creates a recursively-expanded variable
4412 (@pxref{Flavors, ,The Two Flavors of Variables}).
4413 The variable name may contain function and variable references, which
4414 are expanded when the directive is read to find the actual variable name
4415 to use.
4417 @example
4418 define two-lines
4419 echo foo
4420 echo $(bar)
4421 endef
4422 @end example
4424 The value in an ordinary assignment cannot contain a newline; but the
4425 newlines that separate the lines of the value in a @code{define} become
4426 part of the variable's value (except for the final newline which precedes
4427 the @code{endef} and is not considered part of the value).@refill
4429 @need 800
4430 The previous example is functionally equivalent to this:
4432 @example
4433 two-lines = echo foo; echo $(bar)
4434 @end example
4436 @noindent
4437 since two commands separated by semicolon behave much like two separate
4438 shell commands.  However, note that using two separate lines means
4439 @code{make} will invoke the shell twice, running an independent subshell
4440 for each line.  @xref{Execution, ,Command Execution}.
4442 If you want variable definitions made with @code{define} to take
4443 precedence over command-line variable definitions, you can use the
4444 @code{override} directive together with @code{define}:
4446 @example
4447 override define two-lines
4449 $(bar)
4450 endef
4451 @end example
4453 @noindent
4454 @xref{Override Directive, ,The @code{override} Directive}.
4456 @node Environment,  , Defining, Using Variables
4457 @section Variables from the Environment
4459 @cindex variables, environment
4460 @cindex environment
4461 Variables in @code{make} can come from the environment in which
4462 @code{make} is run.  Every environment variable that @code{make} sees when
4463 it starts up is transformed into a @code{make} variable with the same name
4464 and value.  But an explicit assignment in the makefile, or with a command
4465 argument, overrides the environment.  (If the @samp{-e} flag is specified,
4466 then values from the environment override assignments in the makefile.
4467 @xref{Options Summary, ,Summary of Options}.
4468 But this is not recommended practice.)
4470 Thus, by setting the variable @code{CFLAGS} in your environment, you can
4471 cause all C compilations in most makefiles to use the compiler switches you
4472 prefer.  This is safe for variables with standard or conventional meanings
4473 because you know that no makefile will use them for other things.  (But
4474 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
4475 and therefore are not affected by the value in the environment.)
4477 When @code{make} is invoked recursively, variables defined in the
4478 outer invocation can be passed to inner invocations through the
4479 environment (@pxref{Recursion, ,Recursive Use of @code{make}}).  By
4480 default, only variables that came from the environment or the command
4481 line are passed to recursive invocations.  You can use the
4482 @code{export} directive to pass other variables.
4483 @xref{Variables/Recursion, , Communicating Variables to a
4484 Sub-@code{make}}, for full details.
4486 Other use of variables from the environment is not recommended.  It is not
4487 wise for makefiles to depend for their functioning on environment variables
4488 set up outside their control, since this would cause different users to get
4489 different results from the same makefile.  This is against the whole
4490 purpose of most makefiles.
4492 Such problems would be especially likely with the variable @code{SHELL},
4493 which is normally present in the environment to specify the user's choice
4494 of interactive shell.  It would be very undesirable for this choice to
4495 affect @code{make}.  So @code{make} ignores the environment value of
4496 @code{SHELL}.@refill
4498 @node Conditionals, Functions, Using Variables, Top
4499 @chapter Conditional Parts of Makefiles
4501 @cindex conditionals
4502 A @dfn{conditional} causes part of a makefile to be obeyed or ignored
4503 depending on the values of variables.  Conditionals can compare the
4504 value of one variable to another, or the value of a variable to
4505 a constant string.  Conditionals control what @code{make} actually
4506 ``sees'' in the makefile, so they @emph{cannot} be used to control shell
4507 commands at the time of execution.@refill
4509 @menu
4510 * Conditional Example::         Example of a conditional
4511 * Conditional Syntax::          The syntax of conditionals.
4512 * Testing Flags::               Conditionals that test flags.
4513 @end menu
4515 @node Conditional Example, Conditional Syntax,  , Conditionals
4516 @section Example of a Conditional
4518 The following example of a conditional tells @code{make} to use one set
4519 of libraries if the @code{CC} variable is @samp{gcc}, and a different
4520 set of libraries otherwise.  It works by controlling which of two
4521 command lines will be used as the command for a rule.  The result is
4522 that @samp{CC=gcc} as an argument to @code{make} changes not only which
4523 compiler is used but also which libraries are linked.
4525 @example
4526 libs_for_gcc = -lgnu
4527 normal_libs =
4529 foo: $(objects)
4530 ifeq ($(CC),gcc)
4531         $(CC) -o foo $(objects) $(libs_for_gcc)
4532 else
4533         $(CC) -o foo $(objects) $(normal_libs)
4534 endif
4535 @end example
4537 This conditional uses three directives: one @code{ifeq}, one @code{else}
4538 and one @code{endif}.
4540 The @code{ifeq} directive begins the conditional, and specifies the
4541 condition.  It contains two arguments, separated by a comma and surrounded
4542 by parentheses.  Variable substitution is performed on both arguments and
4543 then they are compared.  The lines of the makefile following the
4544 @code{ifeq} are obeyed if the two arguments match; otherwise they are
4545 ignored.
4547 The @code{else} directive causes the following lines to be obeyed if the
4548 previous conditional failed.  In the example above, this means that the
4549 second alternative linking command is used whenever the first alternative
4550 is not used.  It is optional to have an @code{else} in a conditional.
4552 The @code{endif} directive ends the conditional.  Every conditional must
4553 end with an @code{endif}.  Unconditional makefile text follows.
4555 As this example illustrates, conditionals work at the textual level:
4556 the lines of the conditional are treated as part of the makefile, or
4557 ignored, according to the condition.  This is why the larger syntactic
4558 units of the makefile, such as rules, may cross the beginning or the
4559 end of the conditional.
4561 When the variable @code{CC} has the value @samp{gcc}, the above example has
4562 this effect:
4564 @example
4565 foo: $(objects)
4566         $(CC) -o foo $(objects) $(libs_for_gcc)
4567 @end example
4569 @noindent
4570 When the variable @code{CC} has any other value, the effect is this:
4572 @example
4573 foo: $(objects)
4574         $(CC) -o foo $(objects) $(normal_libs)
4575 @end example
4577 Equivalent results can be obtained in another way by conditionalizing a
4578 variable assignment and then using the variable unconditionally:
4580 @example
4581 libs_for_gcc = -lgnu
4582 normal_libs =
4584 ifeq ($(CC),gcc)
4585   libs=$(libs_for_gcc)
4586 else
4587   libs=$(normal_libs)
4588 endif
4590 foo: $(objects)
4591         $(CC) -o foo $(objects) $(libs)
4592 @end example
4594 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
4595 @section Syntax of Conditionals
4596 @findex ifdef
4597 @findex ifeq
4598 @findex ifndef
4599 @findex ifneq
4600 @findex else
4601 @findex endif
4603 The syntax of a simple conditional with no @code{else} is as follows:
4605 @example
4606 @var{conditional-directive}
4607 @var{text-if-true}
4608 endif
4609 @end example
4611 @noindent
4612 The @var{text-if-true} may be any lines of text, to be considered as part
4613 of the makefile if the condition is true.  If the condition is false, no
4614 text is used instead.
4616 The syntax of a complex conditional is as follows:
4618 @example
4619 @var{conditional-directive}
4620 @var{text-if-true}
4621 else
4622 @var{text-if-false}
4623 endif
4624 @end example
4626 @noindent
4627 If the condition is true, @var{text-if-true} is used; otherwise,
4628 @var{text-if-false} is used instead.  The @var{text-if-false} can be any
4629 number of lines of text.
4631 The syntax of the @var{conditional-directive} is the same whether the
4632 conditional is simple or complex.  There are four different directives that
4633 test different conditions.  Here is a table of them:
4635 @table @code
4636 @item ifeq (@var{arg1}, @var{arg2})
4637 @itemx ifeq '@var{arg1}' '@var{arg2}'
4638 @itemx ifeq "@var{arg1}" "@var{arg2}"
4639 @itemx ifeq "@var{arg1}" '@var{arg2}'
4640 @itemx ifeq '@var{arg1}' "@var{arg2}"
4641 Expand all variable references in @var{arg1} and @var{arg2} and
4642 compare them.  If they are identical, the @var{text-if-true} is
4643 effective; otherwise, the @var{text-if-false}, if any, is effective.
4645 Often you want to test if a variable has a non-empty value.  When the
4646 value results from complex expansions of variables and functions,
4647 expansions you would consider empty may actually contain whitespace
4648 characters and thus are not seen as empty.  However, you can use the
4649 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
4650 whitespace as a non-empty value.  For example:
4652 @example
4653 @group
4654 ifeq ($(strip $(foo)),)
4655 @var{text-if-empty}
4656 endif
4657 @end group
4658 @end example
4660 @noindent
4661 will evaluate @var{text-if-empty} even if the expansion of
4662 @code{$(foo)} contains whitespace characters.
4664 @item ifneq (@var{arg1}, @var{arg2})
4665 @itemx ifneq '@var{arg1}' '@var{arg2}'
4666 @itemx ifneq "@var{arg1}" "@var{arg2}"
4667 @itemx ifneq "@var{arg1}" '@var{arg2}'
4668 @itemx ifneq '@var{arg1}' "@var{arg2}"
4669 Expand all variable references in @var{arg1} and @var{arg2} and
4670 compare them.  If they are different, the @var{text-if-true} is
4671 effective; otherwise, the @var{text-if-false}, if any, is effective.
4673 @item ifdef @var{variable-name}
4674 If the variable @var{variable-name} has a non-empty value, the
4675 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
4676 if any, is effective.  Variables that have never been defined have an
4677 empty value.
4679 Note that @code{ifdef} only tests whether a variable has a value.  It
4680 does not expand the variable to see if that value is nonempty.
4681 Consequently, tests using @code{ifdef} return true for all definitions
4682 except those like @code{foo =}.  To test for an empty value, use
4683 @w{@code{ifeq ($(foo),)}}.  For example,
4685 @example
4686 bar =
4687 foo = $(bar)
4688 ifdef foo
4689 frobozz = yes
4690 else
4691 frobozz = no
4692 endif
4693 @end example
4695 @noindent
4696 sets @samp{frobozz} to @samp{yes}, while:
4698 @example
4699 foo =
4700 ifdef foo
4701 frobozz = yes
4702 else
4703 frobozz = no
4704 endif
4705 @end example
4707 @noindent
4708 sets @samp{frobozz} to @samp{no}.
4710 @item ifndef @var{variable-name}
4711 If the variable @var{variable-name} has an empty value, the
4712 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
4713 if any, is effective.
4714 @end table
4716 Extra spaces are allowed and ignored at the beginning of the conditional
4717 directive line, but a tab is not allowed.  (If the line begins with a tab,
4718 it will be considered a command for a rule.)  Aside from this, extra spaces
4719 or tabs may be inserted with no effect anywhere except within the directive
4720 name or within an argument.  A comment starting with @samp{#} may appear at
4721 the end of the line.
4723 The other two directives that play a part in a conditional are @code{else}
4724 and @code{endif}.  Each of these directives is written as one word, with no
4725 arguments.  Extra spaces are allowed and ignored at the beginning of the
4726 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
4727 appear at the end of the line.
4729 Conditionals affect which lines of the makefile @code{make} uses.  If
4730 the condition is true, @code{make} reads the lines of the
4731 @var{text-if-true} as part of the makefile; if the condition is false,
4732 @code{make} ignores those lines completely.  It follows that syntactic
4733 units of the makefile, such as rules, may safely be split across the
4734 beginning or the end of the conditional.@refill
4736 @code{make} evaluates conditionals when it reads a makefile.
4737 Consequently, you cannot use automatic variables in the tests of
4738 conditionals because they are not defined until commands are run
4739 (@pxref{Automatic, , Automatic Variables}).
4741 To prevent intolerable confusion, it is not permitted to start a
4742 conditional in one makefile and end it in another.  However, you may
4743 write an @code{include} directive within a conditional, provided you do
4744 not attempt to terminate the conditional inside the included file.
4746 @node Testing Flags,  , Conditional Syntax, Conditionals
4747 @section Conditionals that Test Flags
4749 You can write a conditional that tests @code{make} command flags such as
4750 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
4751 @code{findstring} function 
4752 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
4753 This is useful when @code{touch} is not enough to make a file appear up
4754 to date.
4756 The @code{findstring} function determines whether one string appears as a
4757 substring of another.  If you want to test for the @samp{-t} flag,
4758 use @samp{t} as the first string and the value of @code{MAKEFLAGS} as
4759 the other.
4761 For example, here is how to arrange to use @samp{ranlib -t} to finish
4762 marking an archive file up to date:
4764 @example
4765 archive.a: @dots{}
4766 ifneq (,$(findstring t,$(MAKEFLAGS)))
4767         +touch archive.a
4768         +ranlib -t archive.a
4769 else
4770         ranlib archive.a
4771 endif
4772 @end example
4774 @noindent
4775 The @samp{+} prefix marks those command lines as ``recursive'' so
4776 that they will be executed despite use of the @samp{-t} flag.
4777 @xref{Recursion, ,Recursive Use of @code{make}}.
4779 @node Functions, Running, Conditionals, Top
4780 @chapter Functions for Transforming Text
4781 @cindex functions
4783 @dfn{Functions} allow you to do text processing in the makefile to compute
4784 the files to operate on or the commands to use.  You use a function in a
4785 @dfn{function call}, where you give the name of the function and some text
4786 (the @dfn{arguments}) for the function to operate on.  The result of the
4787 function's processing is substituted into the makefile at the point of the
4788 call, just as a variable might be substituted.
4790 @menu
4791 * Syntax of Functions::         How to write a function call.
4792 * Text Functions::              General-purpose text manipulation functions.
4793 * Filename Functions::          Functions for manipulating file names.
4794 * Foreach Function::            Repeat some text with controlled variation.
4795 * Origin Function::             Find where a variable got its value.
4796 * Shell Function::              Substitute the output of a shell command.
4797 @end menu
4799 @node Syntax of Functions, Text Functions,  , Functions
4800 @section Function Call Syntax
4801 @cindex @code{$}, in function call
4802 @cindex dollar sign (@code{$}), in function call
4803 @cindex arguments of functions
4804 @cindex functions, syntax of
4806 A function call resembles a variable reference.  It looks like this:
4808 @example
4809 $(@var{function} @var{arguments})
4810 @end example
4812 @noindent
4813 or like this:
4815 @example
4816 $@{@var{function} @var{arguments}@}
4817 @end example
4819 Here @var{function} is a function name; one of a short list of names that
4820 are part of @code{make}.  There is no provision for defining new functions.
4822 The @var{arguments} are the arguments of the function.  They are
4823 separated from the function name by one or more spaces or tabs, and if
4824 there is more than one argument, then they are separated by commas.
4825 Such whitespace and commas are not part of an argument's value.  The
4826 delimiters which you use to surround the function call, whether
4827 parentheses or braces, can appear in an argument only in matching pairs;
4828 the other kind of delimiters may appear singly.  If the arguments
4829 themselves contain other function calls or variable references, it is
4830 wisest to use the same kind of delimiters for all the references; write
4831 @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst a,b,$@{x@})}}.  This
4832 is because it is clearer, and because only one type of delimiter is
4833 matched to find the end of the reference.
4835 The text written for each argument is processed by substitution of
4836 variables and function calls to produce the argument value, which
4837 is the text on which the function acts.  The substitution is done in the
4838 order in which the arguments appear.
4840 Commas and unmatched parentheses or braces cannot appear in the text of an
4841 argument as written; leading spaces cannot appear in the text of the first
4842 argument as written.  These characters can be put into the argument value
4843 by variable substitution.  First define variables @code{comma} and
4844 @code{space} whose values are isolated comma and space characters, then
4845 substitute these variables where such characters are wanted, like this:
4847 @example
4848 @group
4849 comma:= ,
4850 empty:=
4851 space:= $(empty) $(empty)
4852 foo:= a b c
4853 bar:= $(subst $(space),$(comma),$(foo))
4854 # @r{bar is now `a,b,c'.}
4855 @end group
4856 @end example
4858 @noindent
4859 Here the @code{subst} function replaces each space with a comma, through
4860 the value of @code{foo}, and substitutes the result.
4862 @node Text Functions, Filename Functions, Syntax of Functions, Functions
4863 @section Functions for String Substitution and Analysis
4864 @cindex functions, for text
4866 Here are some functions that operate on strings:
4868 @table @code
4869 @item $(subst @var{from},@var{to},@var{text})
4870 @findex subst
4871 Performs a textual replacement on the text @var{text}: each occurrence
4872 of @var{from} is replaced by @var{to}.  The result is substituted for
4873 the function call.  For example,
4875 @example
4876 $(subst ee,EE,feet on the street)
4877 @end example
4879 substitutes the string @samp{fEEt on the strEEt}.
4881 @item $(patsubst @var{pattern},@var{replacement},@var{text})
4882 @findex patsubst
4883 Finds whitespace-separated words in @var{text} that match
4884 @var{pattern} and replaces them with @var{replacement}.  Here
4885 @var{pattern} may contain a @samp{%} which acts as a wildcard,
4886 matching any number of any characters within a word.  If
4887 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
4888 by the text that matched the @samp{%} in @var{pattern}.@refill
4890 @cindex @code{%}, quoting in @code{patsubst}
4891 @cindex @code{%}, quoting with @code{\} (backslash)
4892 @cindex @code{\} (backslash), to quote @code{%}
4893 @cindex backslash (@code{\}), to quote @code{%}
4894 @cindex quoting @code{%}, in @code{patsubst}
4895 @samp{%} characters in @code{patsubst} function invocations can be
4896 quoted with preceding backslashes (@samp{\}).  Backslashes that would
4897 otherwise quote @samp{%} characters can be quoted with more backslashes.
4898 Backslashes that quote @samp{%} characters or other backslashes are
4899 removed from the pattern before it is compared file names or has a stem
4900 substituted into it.  Backslashes that are not in danger of quoting
4901 @samp{%} characters go unmolested.  For example, the pattern
4902 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
4903 operative @samp{%} character, and @samp{pattern\\} following it.  The
4904 final two backslashes are left alone because they cannot affect any
4905 @samp{%} character.@refill
4907 Whitespace between words is folded into single space characters;
4908 leading and trailing whitespace is discarded.
4910 For example,
4912 @example
4913 $(patsubst %.c,%.o,x.c.c bar.c)
4914 @end example
4916 @noindent
4917 produces the value @samp{x.c.o bar.o}.
4919 Substitution references (@pxref{Substitution Refs, ,Substitution
4920 References}) are a simpler way to get the effect of the @code{patsubst}
4921 function:
4923 @example
4924 $(@var{var}:@var{pattern}=@var{replacement})  
4925 @end example
4927 @noindent
4928 is equivalent to 
4930 @example
4931 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
4932 @end example
4934 The second shorthand simplifies one of the most common uses of
4935 @code{patsubst}: replacing the suffix at the end of file names.
4937 @example
4938 $(@var{var}:@var{suffix}=@var{replacement}) 
4939 @end example
4941 @noindent
4942 is equivalent to 
4944 @example
4945 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
4946 @end example
4948 @noindent
4949 For example, you might have a list of object files:
4951 @example
4952 objects = foo.o bar.o baz.o
4953 @end example
4955 @noindent
4956 To get the list of corresponding source files, you could simply write:
4958 @example
4959 $(objects:.o=.c)
4960 @end example
4962 @noindent
4963 instead of using the general form:
4965 @example
4966 $(patsubst %.o,%.c,$(objects))
4967 @end example
4969 @item $(strip @var{string})
4970 @cindex stripping whitespace
4971 @cindex whitespace, stripping
4972 @cindex spaces, stripping
4973 @findex strip
4974 Removes leading and trailing whitespace from @var{string} and replaces
4975 each internal sequence of one or more whitespace characters with a
4976 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
4978 The function @code{strip} can be very useful when used in conjunction
4979 with conditionals.  When comparing something with the empty string
4980 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
4981 just whitespace to match the empty string (@pxref{Conditionals}).
4983 Thus, the following may fail to have the desired results:
4985 @example
4986 .PHONY: all
4987 ifneq   "$(needs_made)" ""
4988 all: $(needs_made)
4989 else
4990 all:;@@echo 'Nothing to make!'
4991 endif
4992 @end example
4994 @noindent
4995 Replacing the variable reference @w{@samp{$(needs_made)}} with the
4996 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
4997 directive would make it more robust.@refill
4999 @item $(findstring @var{find},@var{in})
5000 @findex findstring
5001 @cindex searching for strings
5002 @cindex finding strings
5003 @cindex strings, searching for
5004 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
5005 value is @var{find}; otherwise, the value is empty.  You can use this
5006 function in a conditional to test for the presence of a specific
5007 substring in a given string.  Thus, the two examples,
5009 @example
5010 $(findstring a,a b c)
5011 $(findstring a,b c)
5012 @end example
5014 @noindent
5015 produce the values @samp{a} and @samp{} (the empty string),
5016 respectively.  @xref{Testing Flags}, for a practical application of
5017 @code{findstring}.@refill
5019 @need 750
5020 @findex filter
5021 @cindex filtering words
5022 @cindex words, filtering
5023 @item $(filter @var{pattern}@dots{},@var{text})
5024 Removes all whitespace-separated words in @var{text} that do
5025 @emph{not} match any of the @var{pattern} words, returning only
5026 matching words.  The patterns are written using @samp{%}, just like
5027 the patterns used in the @code{patsubst} function above.@refill
5029 The @code{filter} function can be used to separate out different types
5030 of strings (such as file names) in a variable.  For example:
5032 @example
5033 sources := foo.c bar.c baz.s ugh.h
5034 foo: $(sources)
5035         cc $(filter %.c %.s,$(sources)) -o foo
5036 @end example
5038 @noindent
5039 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
5040 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
5041 @file{baz.s} should be specified in the command to the
5042 compiler.@refill
5044 @item $(filter-out @var{pattern}@dots{},@var{text})
5045 @findex filter-out
5046 @cindex filtering out words
5047 @cindex words, filtering out
5048 Removes all whitespace-separated words in @var{text} that @emph{do}
5049 match the @var{pattern} words, returning only the words that @emph{do
5050 not} match.  This is the exact opposite of the @code{filter}
5051 function.@refill
5053 For example, given:
5055 @example
5056 @group
5057 objects=main1.o foo.o main2.o bar.o
5058 mains=main1.o main2.o
5059 @end group
5060 @end example
5062 @noindent
5063 the following generates a list which contains all the object files not
5064 in @samp{mains}:
5066 @example
5067 $(filter-out $(mains),$(objects))
5068 @end example
5070 @need 1500
5071 @findex sort
5072 @cindex sorting words
5073 @item $(sort @var{list})
5074 Sorts the words of @var{list} in lexical order, removing duplicate
5075 words.  The output is a list of words separated by single spaces.
5076 Thus,
5078 @example
5079 $(sort foo bar lose)
5080 @end example
5082 @noindent
5083 returns the value @samp{bar foo lose}.
5085 @cindex removing duplicate words
5086 @cindex duplicate words, removing
5087 @cindex words, removing duplicates
5088 Incidentally, since @code{sort} removes duplicate words, you can use
5089 it for this purpose even if you don't care about the sort order.
5090 @end table
5092 Here is a realistic example of the use of @code{subst} and
5093 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
5094 to specify a list of directories that @code{make} should search for
5095 dependency files 
5096 (@pxref{General Search, , @code{VPATH} Search Path for All Dependencies}).  
5097 This example shows how to
5098 tell the C compiler to search for header files in the same list of
5099 directories.@refill
5101 The value of @code{VPATH} is a list of directories separated by colons,
5102 such as @samp{src:../headers}.  First, the @code{subst} function is used to
5103 change the colons to spaces:
5105 @example
5106 $(subst :, ,$(VPATH))
5107 @end example
5109 @noindent
5110 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
5111 each directory name into a @samp{-I} flag.  These can be added to the
5112 value of the variable @code{CFLAGS}, which is passed automatically to the C
5113 compiler, like this:
5115 @example
5116 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
5117 @end example
5119 @noindent
5120 The effect is to append the text @samp{-Isrc -I../headers} to the
5121 previously given value of @code{CFLAGS}.  The @code{override} directive is
5122 used so that the new value is assigned even if the previous value of
5123 @code{CFLAGS} was specified with a command argument (@pxref{Override
5124 Directive, , The @code{override} Directive}).
5126 @node Filename Functions, Foreach Function, Text Functions, Functions
5127 @section Functions for File Names
5128 @cindex functions, for file names
5129 @cindex file name functions
5131 Several of the built-in expansion functions relate specifically to
5132 taking apart file names or lists of file names.
5134 Each of the following functions performs a specific transformation on a
5135 file name.  The argument of the function is regarded as a series of file
5136 names, separated by whitespace.  (Leading and trailing whitespace is
5137 ignored.)  Each file name in the series is transformed in the same way and
5138 the results are concatenated with single spaces between them.
5140 @table @code
5141 @item $(dir @var{names}@dots{})
5142 @findex dir
5143 @cindex directory part
5144 @cindex file name, directory part
5145 Extracts the directory-part of each file name in @var{names}.  The
5146 directory-part of the file name is everything up through (and
5147 including) the last slash in it.  If the file name contains no slash,
5148 the directory part is the string @samp{./}.  For example,
5150 @example
5151 $(dir src/foo.c hacks)
5152 @end example
5154 @noindent
5155 produces the result @samp{src/ ./}.
5157 @item $(notdir @var{names}@dots{})
5158 @findex notdir
5159 @cindex file name, nondirectory part
5160 @cindex nondirectory part
5161 Extracts all but the directory-part of each file name in @var{names}.
5162 If the file name contains no slash, it is left unchanged.  Otherwise,
5163 everything through the last slash is removed from it.
5165 A file name that ends with a slash becomes an empty string.  This is
5166 unfortunate, because it means that the result does not always have the
5167 same number of whitespace-separated file names as the argument had;
5168 but we do not see any other valid alternative.
5170 For example,
5172 @example
5173 $(notdir src/foo.c hacks)
5174 @end example
5176 @noindent
5177 produces the result @samp{foo.c hacks}.
5179 @item $(suffix @var{names}@dots{})
5180 @findex suffix
5181 @cindex suffix, function to find
5182 @cindex file name suffix
5183 Extracts the suffix of each file name in @var{names}.  If the file name
5184 contains a period, the suffix is everything starting with the last
5185 period.  Otherwise, the suffix is the empty string.  This frequently
5186 means that the result will be empty when @var{names} is not, and if
5187 @var{names} contains multiple file names, the result may contain fewer
5188 file names.
5190 For example,
5192 @example
5193 $(suffix src/foo.c hacks)
5194 @end example
5196 @noindent
5197 produces the result @samp{.c}.
5199 @item $(basename @var{names}@dots{})
5200 @findex basename
5201 @cindex basename
5202 @cindex file name, basename of
5203 Extracts all but the suffix of each file name in @var{names}.  If the
5204 file name contains a period, the basename is everything starting up to
5205 (and not including) the last period.  Otherwise, the basename is the
5206 entire file name.  For example,
5208 @example
5209 $(basename src/foo.c hacks)
5210 @end example
5212 @noindent
5213 produces the result @samp{src/foo hacks}.
5215 @c plural convention with dots (be consistent)
5216 @item $(addsuffix @var{suffix},@var{names}@dots{})
5217 @findex addsuffix
5218 @cindex suffix, adding
5219 @cindex file name suffix, adding
5220 The argument @var{names} is regarded as a series of names, separated
5221 by whitespace; @var{suffix} is used as a unit.  The value of
5222 @var{suffix} is appended to the end of each individual name and the
5223 resulting larger names are concatenated with single spaces between
5224 them.  For example,
5226 @example
5227 $(addsuffix .c,foo bar)
5228 @end example
5230 @noindent
5231 produces the result @samp{foo.c bar.c}.
5233 @item $(addprefix @var{prefix},@var{names}@dots{})
5234 @findex addprefix
5235 @cindex prefix, adding
5236 @cindex file name prefix, adding
5237 The argument @var{names} is regarded as a series of names, separated
5238 by whitespace; @var{prefix} is used as a unit.  The value of
5239 @var{prefix} is prepended to the front of each individual name and the
5240 resulting larger names are concatenated with single spaces between
5241 them.  For example,
5243 @example
5244 $(addprefix src/,foo bar)
5245 @end example
5247 @noindent
5248 produces the result @samp{src/foo src/bar}.
5250 @item $(join @var{list1},@var{list2})
5251 @findex join
5252 @cindex joining lists of words
5253 @cindex words, joining lists
5254 Concatenates the two arguments word by word: the two first words (one
5255 from each argument) concatenated form the first word of the result, the
5256 two second words form the second word of the result, and so on.  So the
5257 @var{n}th word of the result comes from the @var{n}th word of each
5258 argument.  If one argument has more words that the other, the extra
5259 words are copied unchanged into the result.
5261 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
5263 Whitespace between the words in the lists is not preserved; it is
5264 replaced with a single space.
5266 This function can merge the results of the @code{dir} and
5267 @code{notdir} functions, to produce the original list of files which
5268 was given to those two functions.@refill
5270 @item $(word @var{n},@var{text})
5271 @findex word
5272 @cindex words, selecting
5273 @cindex selecting words
5274 Returns the @var{n}th word of @var{text}.  The legitimate values of
5275 @var{n} start from 1.  If @var{n} is bigger than the number of words
5276 in @var{text}, the value is empty.  For example,
5278 @example
5279 $(word 2, foo bar baz)
5280 @end example
5282 @noindent
5283 returns @samp{bar}.
5285 @c Following item phrased to prevent overfull hbox.  --RJC 17 Jul 92
5286 @item $(words @var{text})
5287 @findex words
5288 @cindex words, finding number
5289 Returns the number of words in @var{text}.  
5290 Thus, the last word of @var{text} is
5291 @w{@code{$(word $(words @var{text}),@var{text})}}.@refill
5293 @item $(firstword @var{names}@dots{})
5294 @findex firstword
5295 @cindex words, extracting first
5296 The argument @var{names} is regarded as a series of names, separated
5297 by whitespace.  The value is the first name in the series.  The rest
5298 of the names are ignored.
5300 For example,
5302 @example
5303 $(firstword foo bar)
5304 @end example
5306 @noindent
5307 produces the result @samp{foo}.  Although @code{$(firstword
5308 @var{text})} is the same as @code{$(word 1,@var{text})}, the
5309 @code{firstword} function is retained for its simplicity.@refill
5311 @item $(wildcard @var{pattern})
5312 @findex wildcard
5313 @cindex wildcard, function
5314 The argument @var{pattern} is a file name pattern, typically containing
5315 wildcard characters (as in shell file name patterns).  The result of
5316 @code{wildcard} is a space-separated list of the names of existing files
5317 that match the pattern.
5318 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
5319 @end table
5321 @node Foreach Function, Origin Function, Filename Functions, Functions
5322 @section The @code{foreach} Function
5323 @findex foreach
5324 @cindex words, iterating over
5326 The @code{foreach} function is very different from other functions.  It
5327 causes one piece of text to be used repeatedly, each time with a different
5328 substitution performed on it.  It resembles the @code{for} command in the
5329 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
5331 The syntax of the @code{foreach} function is:
5333 @example
5334 $(foreach @var{var},@var{list},@var{text})
5335 @end example
5337 @noindent
5338 The first two arguments, @var{var} and @var{list}, are expanded before
5339 anything else is done; note that the last argument, @var{text}, is
5340 @strong{not} expanded at the same time.  Then for each word of the expanded
5341 value of @var{list}, the variable named by the expanded value of @var{var}
5342 is set to that word, and @var{text} is expanded.  Presumably @var{text}
5343 contains references to that variable, so its expansion will be different
5344 each time.
5346 The result is that @var{text} is expanded as many times as there are
5347 whitespace-separated words in @var{list}.  The multiple expansions of
5348 @var{text} are concatenated, with spaces between them, to make the result
5349 of @code{foreach}.
5351 This simple example sets the variable @samp{files} to the list of all files
5352 in the directories in the list @samp{dirs}:
5354 @example
5355 dirs := a b c d
5356 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
5357 @end example
5359 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
5360 finds the value @samp{a} for @code{dir}, so it produces the same result
5361 as @samp{$(wildcard a/*)}; the second repetition produces the result
5362 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
5364 This example has the same result (except for setting @samp{dirs}) as
5365 the following example:
5367 @example
5368 files := $(wildcard a/* b/* c/* d/*)
5369 @end example
5371 When @var{text} is complicated, you can improve readability by giving it
5372 a name, with an additional variable:
5374 @example
5375 find_files = $(wildcard $(dir)/*)
5376 dirs := a b c d
5377 files := $(foreach dir,$(dirs),$(find_files))
5378 @end example
5380 @noindent
5381 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
5382 to define a recursively-expanding variable, so that its value contains an
5383 actual function call to be reexpanded under the control of @code{foreach};
5384 a simply-expanded variable would not do, since @code{wildcard} would be
5385 called only once at the time of defining @code{find_files}.
5387 The @code{foreach} function has no permanent effect on the variable
5388 @var{var}; its value and flavor after the @code{foreach} function call are
5389 the same as they were beforehand.  The other values which are taken from
5390 @var{list} are in effect only temporarily, during the execution of
5391 @code{foreach}.  The variable @var{var} is a simply-expanded variable
5392 during the execution of @code{foreach}.  If @var{var} was undefined
5393 before the @code{foreach} function call, it is undefined after the call.
5394 @xref{Flavors, ,The Two Flavors of Variables}.@refill
5396 You must take care when using complex variable expressions that result in
5397 variable names because many strange things are valid variable names, but
5398 are probably not what you intended.  For example,
5400 @smallexample
5401 files := $(foreach Esta escrito en espanol!,b c ch,$(find_files))
5402 @end smallexample
5404 @noindent
5405 might be useful if the value of @code{find_files} references the variable
5406 whose name is @samp{Esta escrito en espanol!} (es un nombre bastante largo,
5407 no?), but it is more likely to be a mistake.
5409 @node Origin Function, Shell Function, Foreach Function, Functions
5410 @section The @code{origin} Function
5411 @findex origin
5412 @cindex variables, origin of
5413 @cindex origin of variable
5415 The @code{origin} function is unlike most other functions in that it does
5416 not operate on the values of variables; it tells you something @emph{about}
5417 a variable.  Specifically, it tells you where it came from.
5419 The syntax of the @code{origin} function is:
5421 @example
5422 $(origin @var{variable})
5423 @end example
5425 Note that @var{variable} is the @emph{name} of a variable to inquire about;
5426 not a @emph{reference} to that variable.  Therefore you would not normally
5427 use a @samp{$} or parentheses when writing it.  (You can, however, use a
5428 variable reference in the name if you want the name not to be a constant.)
5430 The result of this function is a string telling you how the variable
5431 @var{variable} was defined:
5433 @table @samp
5434 @item undefined
5436 if @var{variable} was never defined.
5438 @item default
5440 if @var{variable} has a default definition, as is usual with @code{CC}
5441 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
5442 Note that if you have redefined a default variable, the @code{origin}
5443 function will return the origin of the later definition.
5445 @item environment
5447 if @var{variable} was defined as an environment variable and the
5448 @samp{-e} option is @emph{not} turned on (@pxref{Options Summary, ,Summary of Options}).
5450 @item environment override
5452 if @var{variable} was defined as an environment variable and the
5453 @w{@samp{-e}} option @emph{is} turned on (@pxref{Options Summary,
5454 ,Summary of Options}).@refill
5456 @item file
5458 if @var{variable} was defined in a makefile.
5460 @item command line
5462 if @var{variable} was defined on the command line.
5464 @item override
5466 if @var{variable} was defined with an @code{override} directive in a
5467 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
5469 @item automatic
5471 if @var{variable} is an automatic variable defined for the
5472 execution of the commands for each rule
5473 (@pxref{Automatic, , Automatic Variables}).
5474 @end table
5476 This information is primarily useful (other than for your curiosity) to
5477 determine if you want to believe the value of a variable.  For example,
5478 suppose you have a makefile @file{foo} that includes another makefile
5479 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
5480 if you run the command @w{@samp{make -f bar}}, even if the environment contains
5481 a definition of @code{bletch}.  However, if @file{foo} defined
5482 @code{bletch} before including @file{bar}, you do not want to override that
5483 definition.  This could be done by using an @code{override} directive in
5484 @file{foo}, giving that definition precedence over the later definition in
5485 @file{bar}; unfortunately, the @code{override} directive would also
5486 override any command line definitions.  So, @file{bar} could
5487 include:@refill
5489 @example
5490 @group
5491 ifdef bletch
5492 ifeq "$(origin bletch)" "environment"
5493 bletch = barf, gag, etc.
5494 endif
5495 endif
5496 @end group
5497 @end example
5499 @noindent
5500 If @code{bletch} has been defined from the environment, this will redefine
5503 If you want to override a previous definition of @code{bletch} if it came
5504 from the environment, even under @samp{-e}, you could instead write:
5506 @example
5507 @group
5508 ifneq "$(findstring environment,$(origin bletch))" ""
5509 bletch = barf, gag, etc.
5510 endif
5511 @end group
5512 @end example
5514 Here the redefinition takes place if @samp{$(origin bletch)} returns either
5515 @samp{environment} or @samp{environment override}.
5516 @xref{Text Functions, , Functions for String Substitution and Analysis}.
5518 @node Shell Function,  , Origin Function, Functions
5519 @section The @code{shell} Function
5520 @findex shell
5521 @cindex commands, expansion
5522 @cindex backquotes
5523 @cindex shell command, function for
5525 The @code{shell} function is unlike any other function except the
5526 @code{wildcard} function 
5527 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
5528 communicates with the world outside of @code{make}.
5530 The @code{shell} function performs the same function that backquotes
5531 (@samp{`}) perform in most shells: it does @dfn{command expansion}.  This
5532 means that it takes an argument that is a shell command and returns the
5533 output of the command.  The only processing @code{make} does on the result,
5534 before substituting it into the surrounding text, is to convert newlines to
5535 spaces.@refill
5537 The commands run by calls to the @code{shell} function are run when the
5538 function calls are expanded.  In most cases, this is when the makefile is
5539 read in.  The exception is that function calls in the commands of the rules
5540 are expanded when the commands are run, and this applies to @code{shell}
5541 function calls like all others.
5543 Here are some examples of the use of the @code{shell} function:
5545 @example
5546 contents := $(shell cat foo)
5547 @end example
5549 @noindent
5550 sets @code{contents} to the contents of the file @file{foo}, with a space
5551 (rather than a newline) separating each line.
5553 @example
5554 files := $(shell echo *.c)
5555 @end example
5557 @noindent
5558 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
5559 using a very strange shell, this has the same result as
5560 @w{@samp{$(wildcard *.c)}}.@refill
5562 @node Running, Implicit Rules, Functions, Top
5563 @chapter How to Run @code{make}
5565 A makefile that says how to recompile a program can be used in more
5566 than one way.  The simplest use is to recompile every file that is out
5567 of date.  Usually, makefiles are written so that if you run
5568 @code{make} with no arguments, it does just that.
5570 But you might want to update only some of the files; you might want to use
5571 a different compiler or different compiler options; you might want just to
5572 find out which files are out of date without changing them.
5574 By giving arguments when you run @code{make}, you can do any of these
5575 things and many others.
5577 The exit status of @code{make} is always one of three values:
5578 @table @code
5579 @item 0
5580 The exit status is zero if @code{make} is successful.
5581 @item 2
5582 The exit status is two if @code{make} encounters any errors.
5583 It will print messages describing the particular errors.
5584 @item 1
5585 The exit status is one if you use the @samp{-q} flag and @code{make}
5586 determines that some target is not already up to date.
5587 @xref{Instead of Execution, ,Instead of Executing the Commands}.
5588 @end table
5590 @menu
5591 * Makefile Arguments::          How to specify which makefile to use.
5592 * Goals::                       How to use goal arguments to specify which 
5593                                   parts of the makefile to use.
5594 * Instead of Execution::        How to use mode flags to specify what
5595                                   kind of thing to do with the commands 
5596                                   in the makefile other than simply 
5597                                   execute them.
5598 * Avoiding Compilation::        How to avoid recompiling certain files.
5599 * Overriding::                  How to override a variable to specify 
5600                                   an alternate compiler and other things.
5601 * Testing::                     How to proceed past some errors, to 
5602                                   test compilation.
5603 * Options Summary::             Summary of Options
5604 @end menu
5606 @node Makefile Arguments, Goals,  , Running
5607 @section Arguments to Specify the Makefile
5608 @cindex @code{--file}
5609 @cindex @code{--makefile}
5610 @cindex @code{-f}
5612 The way to specify the name of the makefile is with the @samp{-f} or
5613 @samp{--file} option (@samp{--makefile} also works).  For example,
5614 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
5616 If you use the @samp{-f} flag several times and follow each @samp{-f}
5617 with an argument, all the specified files are used jointly as
5618 makefiles.
5620 If you do not use the @samp{-f} or @samp{--file} flag, the default is
5621 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
5622 that order, and use the first of these three which exists or can be made
5623 (@pxref{Makefiles, ,Writing Makefiles}).@refill
5625 @node Goals, Instead of Execution, Makefile Arguments, Running
5626 @section Arguments to Specify the Goals
5627 @cindex goal, how to specify
5629 The @dfn{goals} are the targets that @code{make} should strive ultimately
5630 to update.  Other targets are updated as well if they appear as
5631 dependencies of goals, or dependencies of dependencies of goals, etc.
5633 By default, the goal is the first target in the makefile (not counting
5634 targets that start with a period).  Therefore, makefiles are usually
5635 written so that the first target is for compiling the entire program or
5636 programs they describe.  If the first rule in the makefile has several
5637 targets, only the first target in the rule becomes the default goal, not
5638 the whole list.
5640 You can specify a different goal or goals with arguments to @code{make}.
5641 Use the name of the goal as an argument.  If you specify several goals,
5642 @code{make} processes each of them in turn, in the order you name them.
5644 Any target in the makefile may be specified as a goal (unless it
5645 starts with @samp{-} or contains an @samp{=}, in which case it will be
5646 parsed as a switch or variable definition, respectively).  Even
5647 targets not in the makefile may be specified, if @code{make} can find
5648 implicit rules that say how to make them.
5650 One use of specifying a goal is if you want to compile only a part of
5651 the program, or only one of several programs.  Specify as a goal each
5652 file that you wish to remake.  For example, consider a directory containing
5653 several programs, with a makefile that starts like this:
5655 @example
5656 .PHONY: all
5657 all: size nm ld ar as
5658 @end example
5660 If you are working on the program @code{size}, you might want to say
5661 @w{@samp{make size}} so that only the files of that program are recompiled.
5663 Another use of specifying a goal is to make files that are not normally
5664 made.  For example, there may be a file of debugging output, or a
5665 version of the program that is compiled specially for testing, which has
5666 a rule in the makefile but is not a dependency of the default goal.
5668 Another use of specifying a goal is to run the commands associated with
5669 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
5670 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
5671 a phony target named @file{clean} which deletes everything except source
5672 files.  Naturally, this is done only if you request it explicitly with
5673 @w{@samp{make clean}}.  Following is a list of typical phony and empty
5674 target names.  @xref{Standard Targets}, for a detailed list of all the
5675 standard target names which GNU software packages use.
5677 @table @file
5678 @item all
5679 @cindex @code{all} @r{(standard target)}
5680 Make all the top-level targets the makefile knows about.
5682 @item clean
5683 @cindex @code{clean} @r{(standard target)}
5684 Delete all files that are normally created by running @code{make}.
5686 @item mostlyclean
5687 @cindex @code{mostlyclean} @r{(standard target)}
5688 Like @samp{clean}, but may refrain from deleting a few files that people
5689 normally don't want to recompile.  For example, the @samp{mostlyclean}
5690 target for GCC does not delete @file{libgcc.a}, because recompiling it
5691 is rarely necessary and takes a lot of time.
5693 @item distclean
5694 @cindex @code{distclean} @r{(standard target)}
5695 @itemx realclean
5696 @cindex @code{realclean} @r{(standard target)}
5697 @itemx clobber
5698 @cindex @code{clobber} @r{(standard target)}
5699 Any of these targets might be defined to delete @emph{more} files than
5700 @samp{clean} does.  For example, this would delete configuration files
5701 or links that you would normally create as preparation for compilation,
5702 even if the makefile itself cannot create these files.
5704 @item install
5705 @cindex @code{install} @r{(standard target)}
5706 Copy the executable file into a directory that users typically search
5707 for commands; copy any auxiliary files that the executable uses into
5708 the directories where it will look for them.
5710 @item print
5711 @cindex @code{print} @r{(standard target)}
5712 Print listings of the source files that have changed.
5714 @item tar
5715 @cindex @code{tar} @r{(standard target)}
5716 Create a tar file of the source files.
5718 @item shar
5719 @cindex @code{shar} @r{(standard target)}
5720 Create a shell archive (shar file) of the source files.
5722 @item dist
5723 @cindex @code{dist} @r{(standard target)}
5724 Create a distribution file of the source files.  This might
5725 be a tar file, or a shar file, or a compressed version of one of the
5726 above, or even more than one of the above.
5728 @item TAGS
5729 @cindex @code{TAGS} @r{(standard target)}
5730 Update a tags table for this program.
5732 @item check
5733 @cindex @code{check} @r{(standard target)}
5734 @itemx test
5735 @cindex @code{test} @r{(standard target)}
5736 Perform self tests on the program this makefile builds.
5737 @end table
5739 @node Instead of Execution, Avoiding Compilation, Goals, Running
5740 @section Instead of Executing the Commands
5741 @cindex execution, instead of
5742 @cindex commands, instead of executing
5744 The makefile tells @code{make} how to tell whether a target is up to date,
5745 and how to update each target.  But updating the targets is not always
5746 what you want.  Certain options specify other activities for @code{make}.
5748 @comment Extra blank lines make it print better.
5749 @table @samp
5750 @item -n
5751 @itemx --just-print
5752 @itemx --dry-run
5753 @itemx --recon
5754 @cindex @code{--just-print}
5755 @cindex @code{--dry-run}
5756 @cindex @code{--recon}
5757 @cindex @code{-n}
5759 ``No-op''.  The activity is to print what commands would be used to make
5760 the targets up to date, but not actually execute them.
5762 @item -t
5763 @itemx --touch
5764 @cindex @code{--touch}
5765 @cindex touching files
5766 @cindex target, touching
5767 @cindex @code{-t}
5769 ``Touch''.  The activity is to mark the targets as up to date without
5770 actually changing them.  In other words, @code{make} pretends to compile
5771 the targets but does not really change their contents.
5773 @item -q
5774 @itemx --question
5775 @cindex @code{--question}
5776 @cindex @code{-q}
5777 @cindex question mode
5779 ``Question''.  The activity is to find out silently whether the targets
5780 are up to date already; but execute no commands in either case.  In other
5781 words, neither compilation nor output will occur.
5783 @item -W @var{file}
5784 @itemx --what-if=@var{file}
5785 @itemx --assume-new=@var{file}
5786 @itemx --new-file=@var{file}
5787 @cindex @code{--what-if}
5788 @cindex @code{-W}
5789 @cindex @code{--assume-new}
5790 @cindex @code{--new-file}
5791 @cindex what if
5792 @cindex files, assuming new
5794 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
5795 files' modification times are recorded by @code{make} as being the present
5796 time, although the actual modification times remain the same.  
5797 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
5798 to see what would happen if you were to modify specific files.@refill
5799 @end table
5801 With the @samp{-n} flag, @code{make} prints the commands that it would
5802 normally execute but does not execute them.
5804 With the @samp{-t} flag, @code{make} ignores the commands in the rules
5805 and uses (in effect) the command @code{touch} for each target that needs to
5806 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
5807 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
5808 the program @code{touch}.  It does the work directly.
5810 With the @samp{-q} flag, @code{make} prints nothing and executes no
5811 commands, but the exit status code it returns is zero if and only if the
5812 targets to be considered are already up to date.  If the exit status is
5813 one, then some updating needs to be done.  If @code{make} encounters an
5814 error, the exit status is two, so you can distinguish an error from a
5815 target that is not up to date.
5817 It is an error to use more than one of these three flags in the same
5818 invocation of @code{make}.
5820 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect command
5821 lines that begin with @samp{+} characters or contain the strings
5822 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
5823 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
5824 is run regardless of these options.  Other lines in the same rule are
5825 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
5826 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
5828 The @samp{-W} flag provides two features:
5830 @itemize @bullet
5831 @item
5832 If you also use the @samp{-n} or @samp{-q} flag, you can see what
5833 @code{make} would do if you were to modify some files.
5835 @item
5836 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
5837 executing commands, the @samp{-W} flag can direct @code{make} to act
5838 as if some files had been modified, without actually modifying the
5839 files.@refill
5840 @end itemize
5842 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
5843 information about @code{make} or about the makefiles in use
5844 (@pxref{Options Summary, ,Summary of Options}).@refill
5846 @node Avoiding Compilation, Overriding, Instead of Execution, Running
5847 @section Avoiding Recompilation of Some Files
5848 @cindex @code{-o}
5849 @cindex @code{--old-file}
5850 @cindex @code{--assume-old}
5851 @cindex files, assuming old
5852 @cindex files, avoiding recompilation of
5853 @cindex recompilation, avoiding
5855 Sometimes you may have changed a source file but you do not want to
5856 recompile all the files that depend on it.  For example, suppose you add a
5857 macro or a declaration to a header file that many other files depend on.
5858 Being conservative, @code{make} assumes that any change in the header file
5859 requires recompilation of all dependent files, but you know that they do not
5860 need to be recompiled and you would rather not waste the time waiting for
5861 them to compile.
5863 If you anticipate the problem before changing the header file, you can
5864 use the @samp{-t} flag.  This flag tells @code{make} not to run the
5865 commands in the rules, but rather to mark the target up to date by
5866 changing its last-modification date.  You would follow this procedure:
5868 @enumerate
5869 @item
5870 Use the command @samp{make} to recompile the source files that really
5871 need recompilation.
5873 @item
5874 Make the changes in the header files.
5876 @item
5877 Use the command @samp{make -t} to mark all the object files as
5878 up to date.  The next time you run @code{make}, the changes in the
5879 header files will not cause any recompilation.
5880 @end enumerate
5882 If you have already changed the header file at a time when some files
5883 do need recompilation, it is too late to do this.  Instead, you can
5884 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
5885 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
5886 that the file itself will not be remade, and nothing else will be
5887 remade on its account.  Follow this procedure:
5889 @enumerate
5890 @item
5891 Recompile the source files that need compilation for reasons independent
5892 of the particular header file, with @samp{make -o @var{headerfile}}.
5893 If several header files are involved, use a separate @samp{-o} option
5894 for each header file.
5896 @item
5897 Touch all the object files with @samp{make -t}.
5898 @end enumerate
5900 @node Overriding, Testing, Avoiding Compilation, Running
5901 @section Overriding Variables
5902 @cindex overriding variables with arguments
5903 @cindex variables, overriding with arguments
5904 @cindex command line variables
5905 @cindex variables, command line
5907 An argument that contains @samp{=} specifies the value of a variable:
5908 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
5909 If you specify a value in this way, all ordinary assignments of the same
5910 variable in the makefile are ignored; we say they have been
5911 @dfn{overridden} by the command line argument.
5913 The most common way to use this facility is to pass extra flags to
5914 compilers.  For example, in a properly written makefile, the variable
5915 @code{CFLAGS} is included in each command that runs the C compiler, so a
5916 file @file{foo.c} would be compiled something like this:
5918 @example
5919 cc -c $(CFLAGS) foo.c
5920 @end example
5922 Thus, whatever value you set for @code{CFLAGS} affects each compilation
5923 that occurs.  The makefile probably specifies the usual value for
5924 @code{CFLAGS}, like this:
5926 @example
5927 CFLAGS=-g
5928 @end example
5930 Each time you run @code{make}, you can override this value if you
5931 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
5932 compilation will be done with @samp{cc -c -g -O}.  (This illustrates
5933 how you can use quoting in the shell to enclose spaces and other
5934 special characters in the value of a variable when you override it.)
5936 The variable @code{CFLAGS} is only one of many standard variables that
5937 exist just so that you can change them this way.  @xref{Implicit
5938 Variables, , Variables Used by Implicit Rules}, for a complete list.
5940 You can also program the makefile to look at additional variables of your
5941 own, giving the user the ability to control other aspects of how the
5942 makefile works by changing the variables.
5944 When you override a variable with a command argument, you can define either
5945 a recursively-expanded variable or a simply-expanded variable.  The
5946 examples shown above make a recursively-expanded variable; to make a
5947 simply-expanded variable, write @samp{:=} instead of @samp{=}.  But, unless
5948 you want to include a variable reference or function call in the
5949 @emph{value} that you specify, it makes no difference which kind of
5950 variable you create.
5952 There is one way that the makefile can change a variable that you have
5953 overridden.  This is to use the @code{override} directive, which is a line
5954 that looks like this: @samp{override @var{variable} = @var{value}}
5955 (@pxref{Override Directive, ,The @code{override} Directive}).
5957 @node Testing, Options Summary, Overriding, Running
5958 @section Testing the Compilation of a Program
5959 @cindex testing compilation
5960 @cindex compilation, testing
5962 Normally, when an error happens in executing a shell command, @code{make}
5963 gives up immediately, returning a nonzero status.  No further commands are
5964 executed for any target.  The error implies that the goal cannot be
5965 correctly remade, and @code{make} reports this as soon as it knows.
5967 When you are compiling a program that you have just changed, this is not
5968 what you want.  Instead, you would rather that @code{make} try compiling
5969 every file that can be tried, to show you as many compilation errors
5970 as possible.
5972 @cindex @code{-k}
5973 @cindex @code{--keep-going}
5974 On these occasions, you should use the @samp{-k} or
5975 @samp{--keep-going} flag.  This tells @code{make} to continue to
5976 consider the other dependencies of the pending targets, remaking them
5977 if necessary, before it gives up and returns nonzero status.  For
5978 example, after an error in compiling one object file, @samp{make -k}
5979 will continue compiling other object files even though it already
5980 knows that linking them will be impossible.  In addition to continuing
5981 after failed shell commands, @samp{make -k} will continue as much as
5982 possible after discovering that it does not know how to make a target
5983 or dependency file.  This will always cause an error message, but
5984 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
5985 ,Summary of Options}).@refill
5987 The usual behavior of @code{make} assumes that your purpose is to get the
5988 goals up to date; once @code{make} learns that this is impossible, it might
5989 as well report the failure immediately.  The @samp{-k} flag says that the
5990 real purpose is to test as much as possible of the changes made in the
5991 program, perhaps to find several independent problems so that you can
5992 correct them all before the next attempt to compile.  This is why Emacs'
5993 @kbd{M-x compile} command passes the @samp{-k} flag by default.
5995 @node Options Summary,  , Testing, Running
5996 @section Summary of Options
5997 @cindex options
5998 @cindex flags
5999 @cindex switches
6001 Here is a table of all the options @code{make} understands:
6003 @table @samp
6004 @item -b
6005 @cindex @code{-b}
6006 @itemx -m
6007 @cindex @code{-m}
6008 These options are ignored for compatibility with other versions of @code{make}.
6010 @item -C @var{dir}
6011 @cindex @code{-C}
6012 @itemx --directory=@var{dir}
6013 @cindex @code{--directory}
6014 Change to directory @var{dir} before reading the makefiles.  If multiple
6015 @samp{-C} options are specified, each is interpreted relative to the
6016 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
6017 This is typically used with recursive invocations of @code{make}
6018 (@pxref{Recursion, ,Recursive Use of @code{make}}).
6020 @item -d
6021 @cindex @code{-d}
6022 @itemx --debug
6023 @cindex @code{--debug}
6024 @c Extra blank line here makes the table look better.
6026 Print debugging information in addition to normal processing.  The
6027 debugging information says which files are being considered for
6028 remaking, which file-times are being compared and with what results,
6029 which files actually need to be remade, which implicit rules are
6030 considered and which are applied---everything interesting about how
6031 @code{make} decides what to do.
6033 @item -e
6034 @cindex @code{-e}
6035 @itemx --environment-overrides
6036 @cindex @code{--environment-overrides}
6037 Give variables taken from the environment precedence
6038 over variables from makefiles.
6039 @xref{Environment, ,Variables from the Environment}.
6041 @item -f @var{file}
6042 @cindex @code{-f}
6043 @itemx --file=@var{file}
6044 @cindex @code{--file}
6045 @itemx --makefile=@var{file}
6046 @cindex @code{--makefile}
6047 Read the file named @var{file} as a makefile.
6048 @xref{Makefiles, ,Writing Makefiles}.
6050 @item -h
6051 @cindex @code{-h}
6052 @itemx --help
6053 @cindex @code{--help}
6054 @c Extra blank line here makes the table look better.
6056 Remind you of the options that @code{make} understands and then exit.
6058 @item -i
6059 @cindex @code{-i}
6060 @itemx --ignore-errors
6061 @cindex @code{--ignore-errors}
6062 Ignore all errors in commands executed to remake files.
6063 @xref{Errors, ,Errors in Commands}.
6065 @item -I @var{dir}
6066 @cindex @code{-I}
6067 @itemx --include-dir=@var{dir}
6068 @cindex @code{--include-dir}
6069 Specifies a directory @var{dir} to search for included makefiles.
6070 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
6071 options are used to specify several directories, the directories are
6072 searched in the order specified.
6074 @item -j [@var{jobs}]
6075 @cindex @code{-j}
6076 @itemx --jobs=[@var{jobs}]
6077 @cindex @code{--jobs}
6078 Specifies the number of jobs (commands) to run simultaneously.  With no
6079 argument, @code{make} runs as many jobs simultaneously as possible.  If
6080 there is more than one @samp{-j} option, the last one is effective.
6081 @xref{Parallel, ,Parallel Execution},
6082 for more information on how commands are run.
6084 @item -k
6085 @cindex @code{-k}
6086 @itemx --keep-going
6087 @cindex @code{--keep-going}
6088 Continue as much as possible after an error.  While the target that
6089 failed, and those that depend on it, cannot be remade, the other
6090 dependencies of these targets can be processed all the same.
6091 @xref{Testing, ,Testing the Compilation of a Program}.
6093 @item -l [@var{load}]
6094 @cindex @code{-l}
6095 @itemx --load-average[=@var{load}]
6096 @cindex @code{--load-average}
6097 @itemx --max-load[=@var{load}]
6098 @cindex @code{--max-load}
6099 Specifies that no new jobs (commands) should be started if there are
6100 other jobs running and the load average is at least @var{load} (a
6101 floating-point number).  With no argument, removes a previous load
6102 limit.  @xref{Parallel, ,Parallel Execution}.
6104 @item -n
6105 @cindex @code{-n}
6106 @itemx --just-print
6107 @cindex @code{--just-print}
6108 @itemx --dry-run
6109 @cindex @code{--dry-run}
6110 @itemx --recon
6111 @cindex @code{--recon}
6112 @c Extra blank line here makes the table look better.
6114 Print the commands that would be executed, but do not execute them.
6115 @xref{Instead of Execution, ,Instead of Executing the Commands}.
6117 @item -o @var{file}
6118 @cindex @code{-o}
6119 @itemx --old-file=@var{file}
6120 @cindex @code{--old-file}
6121 @itemx --assume-old=@var{file}
6122 @cindex @code{--assume-old}
6123 Do not remake the file @var{file} even if it is older than its
6124 dependencies, and do not remake anything on account of changes in
6125 @var{file}.  Essentially the file is treated as very old and its rules
6126 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
6127 Some Files}.@refill
6129 @item -p
6130 @cindex @code{-p}
6131 @itemx --print-data-base
6132 @cindex @code{--print-data-base}
6133 Print the data base (rules and variable values) that results from
6134 reading the makefiles; then execute as usual or as otherwise
6135 specified.  This also prints the version information given by
6136 the @samp{-v} switch (see below).  To print the data base without
6137 trying to remake any files, use @w{@samp{make -p -f /dev/null}}.
6139 @item -q
6140 @cindex @code{-q}
6141 @itemx --question
6142 @cindex @code{--question}
6143 ``Question mode''.  Do not run any commands, or print anything; just
6144 return an exit status that is zero if the specified targets are already
6145 up to date, one if any remaking is required, or two if an error is
6146 encountered.  @xref{Instead of Execution, ,Instead of Executing the
6147 Commands}.@refill
6149 @item -r
6150 @cindex @code{-r}
6151 @itemx --no-builtin-rules
6152 @cindex @code{--no-builtin-rules}
6153 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
6154 ,Using Implicit Rules}).  You can still define your own by writing
6155 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
6156 Rules}).  The @samp{-r} option also clears out the default list of
6157 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
6158 Rules}).  But you can still define your own suffixes with a rule for
6159 @code{.SUFFIXES}, and then define your own suffix rules.
6161 @item -s
6162 @cindex @code{-s}
6163 @itemx --silent
6164 @cindex @code{--silent}
6165 @itemx --quiet
6166 @cindex @code{--quiet}
6167 @c Extra blank line here makes the table look better.
6169 Silent operation; do not print the commands as they are executed.
6170 @xref{Echoing, ,Command Echoing}.
6172 @item -S
6173 @cindex @code{-S}
6174 @itemx --no-keep-going
6175 @cindex @code{--no-keep-going}
6176 @itemx --stop
6177 @cindex @code{--stop}
6178 @c Extra blank line here makes the table look better.
6180 Cancel the effect of the @samp{-k} option.  This is never necessary
6181 except in a recursive @code{make} where @samp{-k} might be inherited
6182 from the top-level @code{make} via @code{MAKEFLAGS}
6183 (@pxref{Recursion, ,Recursive Use of @code{make}})
6184 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.@refill
6186 @item -t
6187 @cindex @code{-t}
6188 @itemx --touch
6189 @cindex @code{--touch}
6190 @c Extra blank line here makes the table look better.
6192 Touch files (mark them up to date without really changing them)
6193 instead of running their commands.  This is used to pretend that the
6194 commands were done, in order to fool future invocations of
6195 @code{make}.  @xref{Instead of Execution, ,Instead of Executing the Commands}.
6197 @item -v
6198 @cindex @code{-v}
6199 @itemx --version
6200 @cindex @code{--version}
6201 Print the version of the @code{make} program plus a copyright, a list
6202 of authors, and a notice that there is no warranty; then exit.
6204 @item -w
6205 @cindex @code{-w}
6206 @itemx --print-directory
6207 @cindex @code{--print-directory}
6208 Print a message containing the working directory both before and after
6209 executing the makefile.  This may be useful for tracking down errors
6210 from complicated nests of recursive @code{make} commands.
6211 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
6212 rarely need to specify this option since @samp{make} does it for you;
6213 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
6215 @itemx --no-print-directory
6216 @cindex @code{--no-print-directory}
6217 Disable printing of the working directory under @code{-w}.
6218 This option is useful when @code{-w} is turned on automatically,
6219 but you do not want to see the extra messages.
6220 @xref{-w Option, ,The @samp{--print-directory} Option}.
6222 @item -W @var{file}
6223 @cindex @code{-W}
6224 @itemx --what-if=@var{file}
6225 @cindex @code{--what-if}
6226 @itemx --new-file=@var{file}
6227 @cindex @code{--new-file}
6228 @itemx --assume-new=@var{file}
6229 @cindex @code{--assume-new}
6230 Pretend that the target @var{file} has just been modified.  When used
6231 with the @samp{-n} flag, this shows you what would happen if you were
6232 to modify that file.  Without @samp{-n}, it is almost the same as
6233 running a @code{touch} command on the given file before running
6234 @code{make}, except that the modification time is changed only in the
6235 imagination of @code{make}.
6236 @xref{Instead of Execution, ,Instead of Executing the Commands}.
6238 @item --warn-undefined-variables
6239 @cindex @code{--warn-undefined-variables}
6240 @cindex variables, warning for undefined
6241 @cindex undefined variables, warning message
6242 Issue a warning message whenever @code{make} sees a reference to an
6243 undefined variable.  This can be helpful when you are trying to debug
6244 makefiles which use variables in complex ways.
6245 @end table
6247 @node Implicit Rules, Archives, Running, Top
6248 @chapter Using Implicit Rules
6249 @cindex implicit rule
6250 @cindex rule, implicit
6252 Certain standard ways of remaking target files are used very often.  For
6253 example, one customary way to make an object file is from a C source file
6254 using the C compiler, @code{cc}.
6256 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
6257 that you do not have to specify them in detail when you want to use
6258 them.  For example, there is an implicit rule for C compilation.  File
6259 names determine which implicit rules are run.  For example, C
6260 compilation typically takes a @file{.c} file and makes a @file{.o} file.
6261 So @code{make} applies the implicit rule for C compilation when it sees
6262 this combination of file name endings.@refill
6264 A chain of implicit rules can apply in sequence; for example, @code{make}
6265 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
6266 @iftex
6267 @xref{Chained Rules, ,Chains of Implicit Rules}.
6268 @end iftex
6270 The built-in implicit rules use several variables in their commands so
6271 that, by changing the values of the variables, you can change the way the
6272 implicit rule works.  For example, the variable @code{CFLAGS} controls the
6273 flags given to the C compiler by the implicit rule for C compilation.
6274 @iftex
6275 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
6276 @end iftex
6278 You can define your own implicit rules by writing @dfn{pattern rules}.
6279 @iftex
6280 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
6281 @end iftex
6283 @dfn{Suffix rules} are a more limited way to define implicit rules.
6284 Pattern rules are more general and clearer, but suffix rules are
6285 retained for compatibility.
6286 @iftex
6287 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
6288 @end iftex
6290 @menu
6291 * Using Implicit::              How to use an existing implicit rule
6292                                   to get the commands for updating a file.
6293 * Catalogue of Rules::          A list of built-in implicit rules.
6294 * Implicit Variables::          How to change what predefined rules do.
6295 * Chained Rules::               How to use a chain of implicit rules.
6296 * Pattern Rules::               How to define new implicit rules.
6297 * Last Resort::                 How to defining commands for rules 
6298                                   which cannot find any.
6299 * Suffix Rules::                The old-fashioned style of implicit rule.
6300 * Search Algorithm::            The precise algorithm for applying 
6301                                   implicit rules.
6302 @end menu
6304 @node Using Implicit, Catalogue of Rules,  , Implicit Rules
6305 @section Using Implicit Rules
6306 @cindex implicit rule, how to use
6307 @cindex rule, implicit, how to use
6309 To allow @code{make} to find a customary method for updating a target file,
6310 all you have to do is refrain from specifying commands yourself.  Either
6311 write a rule with no command lines, or don't write a rule at all.  Then
6312 @code{make} will figure out which implicit rule to use based on which
6313 kind of source file exists or can be made.
6315 For example, suppose the makefile looks like this:
6317 @example
6318 foo : foo.o bar.o
6319         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
6320 @end example
6322 @noindent
6323 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
6324 will automatically look for an implicit rule that tells how to update it.
6325 This happens whether or not the file @file{foo.o} currently exists.
6327 If an implicit rule is found, it can supply both commands and one or
6328 more dependencies (the source files).  You would want to write a rule
6329 for @file{foo.o} with no command lines if you need to specify additional
6330 dependencies, such as header files, that the implicit rule cannot
6331 supply.
6333 Each implicit rule has a target pattern and dependency patterns.  There may
6334 be many implicit rules with the same target pattern.  For example, numerous
6335 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
6336 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
6337 that actually applies is the one whose dependencies exist or can be made.
6338 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
6339 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
6340 compiler; and so on.
6342 Of course, when you write the makefile, you know which implicit rule you
6343 want @code{make} to use, and you know it will choose that one because you
6344 know which possible dependency files are supposed to exist.
6345 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
6346 for a catalogue of all the predefined implicit rules.
6348 Above, we said an implicit rule applies if the required dependencies ``exist
6349 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
6350 the makefile as a target or a dependency, or if an implicit rule can be
6351 recursively found for how to make it.  When an implicit dependency is the
6352 result of another implicit rule, we say that @dfn{chaining} is occurring.
6353 @xref{Chained Rules, ,Chains of Implicit Rules}.
6355 In general, @code{make} searches for an implicit rule for each target, and
6356 for each double-colon rule, that has no commands.  A file that is mentioned
6357 only as a dependency is considered a target whose rule specifies nothing,
6358 so implicit rule search happens for it.  @xref{Search Algorithm, ,Implicit Rule Search Algorithm}, for the
6359 details of how the search is done.
6361 Note that explicit dependencies do not influence implicit rule search.
6362 For example, consider this explicit rule:
6364 @example
6365 foo.o: foo.p
6366 @end example
6368 @noindent
6369 The dependency on @file{foo.p} does not necessarily mean that
6370 @code{make} will remake @file{foo.o} according to the implicit rule to
6371 make an object file, a @file{.o} file, from a Pascal source file, a
6372 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
6373 rule to make an object file from a C source file is used instead,
6374 because it appears before the Pascal rule in the list of predefined
6375 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
6376 Rules}).
6378 If you do not want an implicit rule to be used for a target that has no
6379 commands, you can give that target empty commands by writing a semicolon
6380 (@pxref{Empty Commands, ,Defining Empty Commands}).
6382 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
6383 @section Catalogue of Implicit Rules
6384 @cindex implicit rule, predefined
6385 @cindex rule, implicit, predefined
6387 Here is a catalogue of predefined implicit rules which are always
6388 available unless the makefile explicitly overrides or cancels them.
6389 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
6390 canceling or overriding an implicit rule.  The @samp{-r} or
6391 @samp{--no-builtin-rules} option cancels all predefined rules.
6393 Not all of these rules will always be defined, even when the @samp{-r}
6394 option is not given.  Many of the predefined implicit rules are
6395 implemented in @code{make} as suffix rules, so which ones will be
6396 defined depends on the @dfn{suffix list} (the list of dependencies of
6397 the special target @code{.SUFFIXES}).  The default suffix list is:
6398 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
6399 @code{.C}, @code{.p}, @code{.f}, @code{.F}, @code{.r}, @code{.y},
6400 @code{.l}, @code{.s}, @code{.S}, @code{.mod}, @code{.sym}, @code{.def},
6401 @code{.h}, @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo},
6402 @code{.texi}, @code{.txinfo}, @code{.w}, @code{.ch} @code{.web},
6403 @code{.sh}, @code{.elc}, @code{.el}.  All of the implicit rules
6404 described below whose dependencies have one of these suffixes are
6405 actually suffix rules.  If you modify the suffix list, the only
6406 predefined suffix rules in effect will be those named by one or two of
6407 the suffixes that are on the list you specify; rules whose suffixes fail
6408 to be on the list are disabled.  @xref{Suffix Rules, ,Old-Fashioned
6409 Suffix Rules}, for full details on suffix rules.
6411 @table @asis
6412 @item Compiling C programs
6413 @cindex C, rule to compile
6414 @pindex cc
6415 @pindex gcc
6416 @pindex .o
6417 @pindex .c
6418 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
6419 a command of the form @samp{$(CC) -c $(CPPFLAGS) $(CFLAGS)}.@refill
6421 @item Compiling C++ programs
6422 @cindex C++, rule to compile
6423 @pindex g++
6424 @pindex .C
6425 @pindex .cc
6426 @file{@var{n}.o} is made automatically from @file{@var{n}.cc} or
6427 @file{@var{n}.C} with a command of the form @samp{$(CXX) -c $(CPPFLAGS)
6428 $(CXXFLAGS)}.  We encourage you to use the suffix @samp{.cc} for C++
6429 source files instead of @samp{.C}.@refill
6431 @item Compiling Pascal programs
6432 @cindex Pascal, rule to compile
6433 @pindex pc
6434 @pindex .p
6435 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
6436 with the command @samp{$(PC) -c $(PFLAGS)}.@refill
6438 @item Compiling Fortran and Ratfor programs
6439 @cindex Fortran, rule to compile
6440 @cindex Ratfor, rule to compile
6441 @pindex f77
6442 @pindex .f
6443 @pindex .r
6444 @pindex .F
6445 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
6446 @file{@var{n}.F} or @file{@var{n}.f} by running the
6447 Fortran compiler.  The precise command used is as follows:@refill
6449 @table @samp
6450 @item .f
6451 @samp{$(FC) -c $(FFLAGS)}.
6452 @item .F
6453 @samp{$(FC) -c $(FFLAGS) $(CPPFLAGS)}.
6454 @item .r
6455 @samp{$(FC) -c $(FFLAGS) $(RFLAGS)}.
6456 @end table
6458 @item Preprocessing Fortran and Ratfor programs
6459 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
6460 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
6461 Ratfor or preprocessable Fortran program into a strict Fortran
6462 program.  The precise command used is as follows:@refill
6464 @table @samp
6465 @item .F
6466 @samp{$(FC) -F $(CPPFLAGS) $(FFLAGS)}.
6467 @item .r
6468 @samp{$(FC) -F $(FFLAGS) $(RFLAGS)}.
6469 @end table
6471 @item Compiling Modula-2 programs
6472 @cindex Modula-2, rule to compile
6473 @pindex m2c
6474 @pindex .sym
6475 @pindex .def
6476 @pindex .mod
6477 @file{@var{n}.sym} is made from @file{@var{n}.def} with a command
6478 of the form @samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}.  @file{@var{n}.o}
6479 is made from @file{@var{n}.mod}; the form is:
6480 @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.@refill
6482 @need 1200
6483 @item Assembling and preprocessing assembler programs
6484 @cindex assembly, rule to compile
6485 @pindex as
6486 @pindex .s
6487 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
6488 running the assembler, @code{as}.  The precise command is
6489 @samp{$(AS) $(ASFLAGS)}.@refill
6491 @pindex .S
6492 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
6493 running the C preprocessor, @code{cpp}.  The precise command is
6494 @w{@samp{$(CPP) $(CPPFLAGS)}}.
6496 @item Linking a single object file
6497 @cindex linking, predefined rule for
6498 @pindex ld
6499 @pindex .o
6500 @file{@var{n}} is made automatically from @file{@var{n}.o} by running
6501 the linker (usually called @code{ld}) via the C compiler.  The precise
6502 command used is @w{@samp{$(CC) $(LDFLAGS) @var{n}.o $(LOADLIBES)}}.
6504 This rule does the right thing for a simple program with only one
6505 source file.  It will also do the right thing if there are multiple
6506 object files (presumably coming from various other source files), one
6507 of which has a name matching that of the executable file.  Thus,
6509 @example
6510 x: y.o z.o
6511 @end example
6513 @noindent
6514 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
6516 @example
6517 @group
6518 cc -c x.c -o x.o
6519 cc -c y.c -o y.o
6520 cc -c z.c -o z.o
6521 cc x.o y.o z.o -o x
6522 rm -f x.o
6523 rm -f y.o
6524 rm -f z.o
6525 @end group
6526 @end example
6528 @noindent
6529 In more complicated cases, such as when there is no object file whose
6530 name derives from the executable file name, you must write an explicit
6531 command for linking.
6533 Each kind of file automatically made into @samp{.o} object files will
6534 be automatically linked by using the compiler (@samp{$(CC)},
6535 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
6536 assemble @samp{.s} files) without the @samp{-c} option.  This could be
6537 done by using the @samp{.o} object files as intermediates, but it is
6538 faster to do the compiling and linking in one step, so that's how it's
6539 done.@refill
6541 @item Yacc for C programs
6542 @pindex yacc
6543 @cindex Yacc, rule to run
6544 @pindex .y
6545 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
6546 running Yacc with the command @samp{$(YACC) $(YFLAGS)}.
6548 @item Lex for C programs
6549 @pindex lex
6550 @cindex Lex, rule to run
6551 @pindex .l
6552 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
6553 by running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
6555 @item Lex for Ratfor programs
6556 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
6557 by running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
6559 The convention of using the same suffix @samp{.l} for all Lex files
6560 regardless of whether they produce C code or Ratfor code makes it
6561 impossible for @code{make} to determine automatically which of the two
6562 languages you are using in any particular case.  If @code{make} is
6563 called upon to remake an object file from a @samp{.l} file, it must
6564 guess which compiler to use.  It will guess the C compiler, because
6565 that is more common.  If you are using Ratfor, make sure @code{make}
6566 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
6567 are using Ratfor exclusively, with no C files, remove @samp{.c} from
6568 the list of implicit rule suffixes with:@refill
6570 @example
6571 @group
6572 .SUFFIXES:
6573 .SUFFIXES: .o .r .f .l @dots{}
6574 @end group
6575 @end example
6577 @item Making Lint Libraries from C, Yacc, or Lex programs
6578 @pindex lint
6579 @cindex @code{lint}, rule to run
6580 @pindex .ln
6581 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
6582 The precise command is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.  
6583 The same command is used on the C code produced from 
6584 @file{@var{n}.y} or @file{@var{n}.l}.@refill
6586 @item @TeX{} and Web
6587 @cindex @TeX{}, rule to run
6588 @cindex Web, rule to run
6589 @pindex tex
6590 @pindex cweave
6591 @pindex weave
6592 @pindex tangle
6593 @pindex ctangle
6594 @pindex .dvi
6595 @pindex .tex
6596 @pindex .web
6597 @pindex .w
6598 @pindex .ch
6599 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the command
6600 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
6601 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
6602 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
6603 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
6604 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
6605 or can be made) with @samp{$(CTANGLE)}.@refill
6607 @item Texinfo and Info
6608 @cindex Texinfo, rule to format
6609 @cindex Info, rule to format
6610 @pindex texi2dvi
6611 @pindex makeinfo
6612 @pindex .texinfo
6613 @pindex .info
6614 @pindex .texi
6615 @pindex .txinfo
6616 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo},
6617 @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with the command
6618 @w{@samp{$(TEXI2DVI) $(TEXI2DVI_FLAGS)}}.  @file{@var{n}.info} is made from
6619 @file{@var{n}.texinfo}, @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with
6620 the command @w{@samp{$(MAKEINFO) $(MAKEINFO_FLAGS)}}.
6622 @item RCS
6623 @cindex RCS, rule to extract from
6624 @pindex co
6625 @pindex ,v @r{(RCS file extension)}
6626 Any file @file{@var{n}} is extracted if necessary from an RCS file
6627 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
6628 command used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
6629 extracted from RCS if it already exists, even if the RCS file is
6630 newer.  The rules for RCS are terminal 
6631 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}), 
6632 so RCS files cannot be generated from another source; they must
6633 actually exist.@refill
6635 @item SCCS
6636 @cindex SCCS, rule to extract from
6637 @pindex get
6638 @pindex s. @r{(SCCS file prefix)}
6639 Any file @file{@var{n}} is extracted if necessary from an SCCS file
6640 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
6641 command used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
6642 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
6643 so SCCS files cannot be generated from another source; they must
6644 actually exist.@refill
6646 @pindex .sh
6647 For the benefit of SCCS, a file @file{@var{n}} is copied from
6648 @file{@var{n}.sh} and made executable (by everyone).  This is for
6649 shell scripts that are checked into SCCS.  Since RCS preserves the
6650 execution permission of a file, you do not need to use this feature
6651 with RCS.@refill
6653 We recommend that you avoid using of SCCS.  RCS is widely held to be
6654 superior, and is also free.  By choosing free software in place of
6655 comparable (or inferior) proprietary software, you support the free
6656 software movement.
6657 @end table
6659 Usually, you want to change only the variables listed in the table
6660 above, which are documented in the following section.
6662 However, the commands in built-in implicit rules actually use
6663 variables such as @code{COMPILE.c}, @code{LINK.p}, and
6664 @code{PREPROCESS.S}, whose values contain the commands listed above.
6666 @code{make} follows the convention that the rule to compile a
6667 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
6668 Similarly, the rule to produce an executable from a @file{.@var{x}}
6669 file uses @code{LINK.@var{x}}; and the rule to preprocess a
6670 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
6672 @vindex OUTPUT_OPTION
6673 Every rule that produces an object file uses the variable
6674 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
6675 contain @samp{-o $@@}, or to be empty, depending on a compile-time
6676 option.  You need the @samp{-o} option to ensure that the output goes
6677 into the right file when the source file is in a different directory,
6678 as when using @code{VPATH} (@pxref{Directory Search}).  However,
6679 compilers on some systems do not accept a @samp{-o} switch for object
6680 files.  If you use such a system, and use @code{VPATH}, some
6681 compilations will put their output in the wrong place.
6682 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
6683 the value @w{@samp{; mv $*.o $@@}}.
6685 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
6686 @section Variables Used by Implicit Rules
6687 @cindex flags for compilers
6689 The commands in built-in implicit rules make liberal use of certain
6690 predefined variables.  You can alter these variables in the makefile,
6691 with arguments to @code{make}, or in the environment to alter how the
6692 implicit rules work without redefining the rules themselves.
6694 For example, the command used to compile a C source file actually says
6695 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
6696 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
6697 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
6698 used for all C compilations performed by the implicit rule.  By redefining
6699 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
6700 each compilation.  @emph{All} implicit rules that do C compilation use
6701 @samp{$(CC)} to get the program name for the compiler and @emph{all}
6702 include @samp{$(CFLAGS)} among the arguments given to the compiler.@refill
6704 The variables used in implicit rules fall into two classes: those that are
6705 names of programs (like @code{CC}) and those that contain arguments for the
6706 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
6707 some command arguments, but it must start with an actual executable program
6708 name.)  If a variable value contains more than one argument, separate them
6709 with spaces.
6711 Here is a table of variables used as names of programs in built-in rules:
6713 @table @code
6714 @item AR
6715 @vindex AR
6716 Archive-maintaining program; default @samp{ar}.
6717 @pindex ar
6719 @item AS
6720 @vindex AS
6721 Program for doing assembly; default @samp{as}.
6722 @pindex as
6724 @item CC
6725 @vindex CC
6726 Program for compiling C programs; default @samp{cc}.
6727 @pindex cc
6729 @item CXX
6730 @vindex CXX
6731 Program for compiling C++ programs; default @samp{g++}.
6732 @pindex g++
6734 @item CO
6735 @vindex CO
6736 Program for extracting a file from RCS; default @samp{co}.
6737 @pindex co
6739 @item CPP
6740 @vindex CPP
6741 Program for running the C preprocessor, with results to standard output;
6742 default @samp{$(CC) -E}.
6744 @item FC
6745 @vindex FC
6746 Program for compiling or preprocessing Fortran and Ratfor programs;
6747 default @samp{f77}.
6748 @pindex f77
6750 @item GET
6751 @vindex GET
6752 Program for extracting a file from SCCS; default @samp{get}.
6753 @pindex get
6755 @item LEX
6756 @vindex LEX
6757 Program to use to turn Lex grammars into C programs or Ratfor programs;
6758 default @samp{lex}.
6759 @pindex lex
6761 @item PC
6762 @vindex PC
6763 Program for compiling Pascal programs; default @samp{pc}.
6764 @pindex pc
6766 @item YACC
6767 @vindex YACC
6768 Program to use to turn Yacc grammars into C programs; default @samp{yacc}.
6769 @pindex yacc
6771 @item YACCR
6772 @vindex YACCR
6773 Program to use to turn Yacc grammars into Ratfor
6774 programs; default @samp{yacc -r}.
6776 @item MAKEINFO
6777 @vindex MAKEINFO
6778 Program to convert a Texinfo source file into an Info file; default
6779 @samp{makeinfo}.
6780 @pindex makeinfo
6782 @item TEX
6783 @vindex TEX
6784 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
6785 default @samp{tex}.
6786 @pindex tex
6788 @item TEXI2DVI
6789 @vindex TEXI2DVI
6790 Program to make @TeX{} @sc{dvi} files from Texinfo source;
6791 default @samp{texi2dvi}.
6792 @pindex texi2dvi
6794 @item WEAVE
6795 @vindex WEAVE
6796 Program to translate Web into @TeX{}; default @samp{weave}.
6797 @pindex weave
6799 @item CWEAVE
6800 @vindex CWEAVE
6801 Program to translate C Web into @TeX{}; default @samp{cweave}.
6802 @pindex cweave
6804 @item TANGLE
6805 @vindex TANGLE
6806 Program to translate Web into Pascal; default @samp{tangle}.
6807 @pindex tangle
6809 @item CTANGLE
6810 @vindex CTANGLE
6811 Program to translate C Web into C; default @samp{ctangle}.
6812 @pindex ctangle
6814 @item RM
6815 @vindex RM
6816 Command to remove a file; default @samp{rm -f}.
6817 @pindex rm
6818 @end table
6820 Here is a table of variables whose values are additional arguments for the
6821 programs above.  The default values for all of these is the empty
6822 string, unless otherwise noted.
6824 @table @code
6825 @item ARFLAGS
6826 @vindex ARFLAGS
6827 Flags to give the archive-maintaining program; default @samp{rv}.
6829 @item ASFLAGS
6830 @vindex ASFLAGS
6831 Extra flags to give to the assembler (when explicitly
6832 invoked on a @samp{.s} or @samp{.S} file).
6834 @item CFLAGS
6835 @vindex CFLAGS
6836 Extra flags to give to the C compiler.
6838 @item CXXFLAGS
6839 @vindex CXXFLAGS
6840 Extra flags to give to the C++ compiler.
6842 @item COFLAGS
6843 @vindex COFLAGS
6844 Extra flags to give to the RCS @code{co} program.
6846 @item CPPFLAGS
6847 @vindex CPPFLAGS
6848 Extra flags to give to the C preprocessor and programs
6849 that use it (the C and Fortran compilers).
6851 @item FFLAGS
6852 @vindex FFLAGS
6853 Extra flags to give to the Fortran compiler.
6855 @item GFLAGS
6856 @vindex GFLAGS
6857 Extra flags to give to the SCCS @code{get} program.
6859 @item LDFLAGS
6860 @vindex LDFLAGS
6861 Extra flags to give to compilers when they are
6862 supposed to invoke the linker, @samp{ld}.
6864 @item LFLAGS
6865 @vindex LFLAGS
6866 Extra flags to give to Lex.
6868 @item PFLAGS
6869 @vindex PFLAGS
6870 Extra flags to give to the Pascal compiler.
6872 @item RFLAGS
6873 @vindex RFLAGS
6874 Extra flags to give to the Fortran compiler for Ratfor programs.
6876 @item YFLAGS
6877 @vindex YFLAGS
6878 Extra flags to give to Yacc.
6879 @end table
6881 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
6882 @section Chains of Implicit Rules
6884 @cindex chains of rules
6885 @cindex rule, implicit, chains of
6886 Sometimes a file can be made by a sequence of implicit rules.  For example,
6887 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
6888 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
6890 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
6891 special searching is required: @code{make} finds that the object file can
6892 be made by C compilation from @file{@var{n}.c}; later on, when considering
6893 how to make @file{@var{n}.c}, the rule for running Yacc is
6894 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
6895 updated.@refill
6897 @cindex intermediate files
6898 @cindex files, intermediate
6899 However, even if @file{@var{n}.c} does not exist and is not mentioned,
6900 @code{make} knows how to envision it as the missing link between
6901 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
6902 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
6903 intermediate file, it is entered in the data base as if it had been
6904 mentioned in the makefile, along with the implicit rule that says how to
6905 create it.@refill
6907 Intermediate files are remade using their rules just like all other
6908 files.  The difference is that the intermediate file is deleted when
6909 @code{make} is finished.  Therefore, the intermediate file which did not
6910 exist before @code{make} also does not exist after @code{make}.  The
6911 deletion is reported to you by printing a @samp{rm -f} command that
6912 shows what @code{make} is doing.  (You can list the target pattern of an
6913 implicit rule (such as @samp{%.o}) as a dependency of the special
6914 target @code{.PRECIOUS} to preserve intermediate files made by implicit
6915 rules whose target patterns match that file's name; 
6916 see @ref{Interrupts}.)@refill
6917 @cindex intermediate files, preserving
6918 @cindex preserving intermediate files
6919 @cindex preserving with @code{.PRECIOUS}
6920 @cindex @code{.PRECIOUS} intermediate files
6922 A chain can involve more than two implicit rules.  For example, it is
6923 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
6924 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
6925 intermediate files that are deleted at the end.@refill
6927 No single implicit rule can appear more than once in a chain.  This means
6928 that @code{make} will not even consider such a ridiculous thing as making
6929 @file{foo} from @file{foo.o.o} by running the linker twice.  This
6930 constraint has the added benefit of preventing any infinite loop in the
6931 search for an implicit rule chain.
6933 There are some special implicit rules to optimize certain cases that would
6934 otherwise be handled by rule chains.  For example, making @file{foo} from
6935 @file{foo.c} could be handled by compiling and linking with separate
6936 chained rules, using @file{foo.o} as an intermediate file.  But what
6937 actually happens is that a special rule for this case does the compilation
6938 and linking with a single @code{cc} command.  The optimized rule is used in
6939 preference to the step-by-step chain because it comes earlier in the
6940 ordering of rules.
6942 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
6943 @section Defining and Redefining Pattern Rules
6945 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
6946 rule looks like an ordinary rule, except that its target contains the
6947 character @samp{%} (exactly one of them).  The target is considered a
6948 pattern for matching file names; the @samp{%} can match any nonempty
6949 substring, while other characters match only themselves.  The dependencies
6950 likewise use @samp{%} to show how their names relate to the target name.
6952 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
6953 @file{@var{stem}.o} from another file @file{@var{stem}.c}.@refill
6955 Note that expansion using @samp{%} in pattern rules occurs
6956 @strong{after} any variable or function expansions, which take place
6957 when the makefile is read.  @xref{Using Variables, , How to Use
6958 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
6960 @menu
6961 * Pattern Intro::               An introduction to pattern rules.
6962 * Pattern Examples::            Examples of pattern rules.
6963 * Automatic::                   How to use automatic variables in the
6964                                   commands of implicit rules.
6965 * Pattern Match::               How patterns match.
6966 * Match-Anything Rules::        Precautions you should take prior to
6967                                   defining rules that can match any
6968                                   target file whatever.
6969 * Canceling Rules::             How to override or cancel built-in rules.
6970 @end menu
6972 @node Pattern Intro, Pattern Examples,  , Pattern Rules
6973 @subsection Introduction to Pattern Rules
6974 @cindex pattern rule
6975 @cindex rule, pattern
6977 A pattern rule contains the character @samp{%} (exactly one of them)
6978 in the target; otherwise, it looks exactly like an ordinary rule.  The
6979 target is a pattern for matching file names; the @samp{%} matches any
6980 nonempty substring, while other characters match only themselves.
6981 @cindex target pattern, implicit
6982 @cindex @code{%}, in pattern rules
6984 For example, @samp{%.c} as a pattern matches any file name that ends in
6985 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
6986 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
6987 (There must be at least one character to match the @samp{%}.)  The substring
6988 that the @samp{%} matches is called the @dfn{stem}.@refill
6990 @samp{%} in a dependency of a pattern rule stands for the same stem
6991 that was matched by the @samp{%} in the target.  In order for
6992 the pattern rule to apply, its target pattern must match the file name
6993 under consideration, and its dependency patterns must name files that
6994 exist or can be made.  These files become dependencies of the target.
6995 @cindex dependency pattern, implicit
6997 Thus, a rule of the form
6999 @example
7000 %.o : %.c ; @var{command}@dots{}
7001 @end example
7003 @noindent
7004 specifies how to make a file @file{@var{n}.o}, with another file
7005 @file{@var{n}.c} as its dependency, provided that @file{@var{n}.c}
7006 exists or can be made.
7008 There may also be dependencies that do not use @samp{%}; such a dependency
7009 attaches to every file made by this pattern rule.  These unvarying
7010 dependencies are useful occasionally.
7012 A pattern rule need not have any dependencies that contain @samp{%}, or
7013 in fact any dependencies at all.  Such a rule is effectively a general
7014 wildcard.  It provides a way to make any file that matches the target
7015 pattern.  @xref{Last Resort}.
7017 @c !!! The end of of this paragraph should be rewritten.  --bob
7018 Pattern rules may have more than one target.  Unlike normal rules, this
7019 does not act as many different rules with the same dependencies and
7020 commands.  If a pattern rule has multiple targets, @code{make} knows that
7021 the rule's commands are responsible for making all of the targets.  The
7022 commands are executed only once to make all the targets.  When searching
7023 for a pattern rule to match a target, the target patterns of a rule other
7024 than the one that matches the target in need of a rule are incidental:
7025 @code{make} worries only about giving commands and dependencies to the file
7026 presently in question.  However, when this file's commands are run, the
7027 other targets are marked as having been updated themselves.
7028 @cindex multiple targets, in pattern rule
7029 @cindex target, multiple in pattern rule
7031 The order in which pattern rules appear in the makefile is important
7032 since this is the order in which they are considered.
7033 Of equally applicable
7034 rules, only the first one found is used.  The rules you write take precedence
7035 over those that are built in.  Note however, that a rule whose
7036 dependencies actually exist or are mentioned always takes priority over a
7037 rule with dependencies that must be made by chaining other implicit rules.
7038 @cindex pattern rules, order of
7039 @cindex order of pattern rules
7041 @node Pattern Examples, Automatic, Pattern Intro, Pattern Rules
7042 @subsection Pattern Rule Examples
7044 Here are some examples of pattern rules actually predefined in
7045 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
7046 files:@refill
7048 @example
7049 %.o : %.c
7050         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
7051 @end example
7053 @noindent
7054 defines a rule that can make any file @file{@var{x}.o} from
7055 @file{@var{x}.c}.  The command uses the automatic variables @samp{$@@} and
7056 @samp{$<} to substitute the names of the target file and the source file
7057 in each case where the rule applies (@pxref{Automatic, ,Automatic Variables}).@refill
7059 Here is a second built-in rule:
7061 @example
7062 % :: RCS/%,v
7063         $(CO) $(COFLAGS) $<
7064 @end example
7066 @noindent
7067 defines a rule that can make any file @file{@var{x}} whatsoever from a
7068 corresponding file @file{@var{x},v} in the subdirectory @file{RCS}.  Since
7069 the target is @samp{%}, this rule will apply to any file whatever, provided
7070 the appropriate dependency file exists.  The double colon makes the rule
7071 @dfn{terminal}, which means that its dependency may not be an intermediate
7072 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).@refill
7074 @need 500
7075 This pattern rule has two targets:
7077 @example
7078 @group
7079 %.tab.c %.tab.h: %.y
7080         bison -d $<
7081 @end group
7082 @end example
7084 @noindent
7085 @c The following paragraph is rewritten to avoid overfull hboxes
7086 This tells @code{make} that the command @samp{bison -d @var{x}.y} will
7087 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
7088 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
7089 and the file @file{scan.o} depends on the file @file{parse.tab.h},
7090 when @file{parse.y} is changed, the command @samp{bison -d parse.y}
7091 will be executed only once, and the dependencies of both
7092 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
7093 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
7094 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
7095 linked from @file{parse.tab.o}, @file{scan.o}, and its other
7096 dependencies, and it will execute happily ever after.)@refill
7098 @node Automatic, Pattern Match, Pattern Examples, Pattern Rules
7099 @subsection Automatic Variables
7100 @cindex automatic variables
7101 @cindex variables, automatic
7102 @cindex variables, and implicit rule
7104 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
7105 @samp{.o} file: how do you write the @samp{cc} command so that it operates
7106 on the right source file name?  You cannot write the name in the command,
7107 because the name is different each time the implicit rule is applied.
7109 What you do is use a special feature of @code{make}, the @dfn{automatic
7110 variables}.  These variables have values computed afresh for each rule that
7111 is executed, based on the target and dependencies of the rule.  In this
7112 example, you would use @samp{$@@} for the object file name and @samp{$<}
7113 for the source file name.
7115 Here is a table of automatic variables:
7117 @table @code
7118 @vindex $@@
7119 @vindex @@ @r{(automatic variable)}
7120 @item $@@
7121 The file name of the target of the rule.  If the target is an archive
7122 member, then @samp{$@@} is the name of the archive file.  In a pattern
7123 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
7124 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
7125 rule's commands to be run.
7127 @vindex $%
7128 @vindex % @r{(automatic variable)}
7129 @item $%
7130 The target member name, when the target is an archive member.
7131 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
7132 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
7133 empty when the target is not an archive member.
7135 @vindex $<
7136 @vindex < @r{(automatic variable)}
7137 @item $<
7138 The name of the first dependency.  If the target got its commands from
7139 an implicit rule, this will be the first dependency added by the
7140 implicit rule (@pxref{Implicit Rules}).
7142 @vindex $?
7143 @vindex ? @r{(automatic variable)}
7144 @item $?
7145 The names of all the dependencies that are newer than the target, with
7146 spaces between them.  For dependencies which are archive members, only
7147 the member named is used (@pxref{Archives}).
7148 @cindex dependencies, list of changed
7149 @cindex list of changed dependencies
7151 @vindex $^
7152 @vindex ^ @r{(automatic variable)}
7153 @item $^
7154 The names of all the dependencies, with spaces between them.  For
7155 dependencies which are archive members, only the member named is used
7156 (@pxref{Archives}).  A target has only one dependency on each other file
7157 it depends on, no matter how many times each file is listed as a
7158 dependency.  So if you list a dependency more than once for a target,
7159 the value of @code{$^} contains just one copy of the name.
7160 @cindex dependencies, list of all
7161 @cindex list of all dependencies
7163 @vindex $+
7164 @vindex + @r{(automatic variable)}
7165 @item $+
7166 This is like @samp{$^}, but dependencies listed more than once are
7167 duplicated in the order they were listed in the makefile.  This is
7168 primarily useful for use in linking commands where it is meaningful to
7169 repeat library file names in a particular order.
7171 @vindex $*
7172 @vindex * @r{(automatic variable)}
7173 @item $*
7174 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
7175 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
7176 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
7177 useful for constructing names of related files.@refill
7178 @cindex stem, variable for
7180 In a static pattern rule, the stem is part of the file name that matched
7181 the @samp{%} in the target pattern.
7183 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
7184 in that way.  Instead, if the target name ends with a recognized suffix
7185 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
7186 the target name minus the suffix.  For example, if the target name is
7187 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
7188 suffix.  GNU @code{make} does this bizarre thing only for compatibility
7189 with other implementations of @code{make}.  You should generally avoid
7190 using @samp{$*} except in implicit rules or static pattern rules.@refill
7192 If the target name in an explicit rule does not end with a recognized
7193 suffix, @samp{$*} is set to the empty string for that rule.
7194 @end table
7196 @samp{$?} is useful even in explicit rules when you wish to operate on only
7197 the dependencies that have changed.  For example, suppose that an archive
7198 named @file{lib} is supposed to contain copies of several object files.
7199 This rule copies just the changed object files into the archive:
7201 @example
7202 @group
7203 lib: foo.o bar.o lose.o win.o
7204         ar r lib $?
7205 @end group
7206 @end example
7208 Of the variables listed above, four have values that are single file
7209 names, and two have values that are lists of file names.  These six have
7210 variants that get just the file's directory name or just the file name
7211 within the directory.  The variant variables' names are formed by
7212 appending @samp{D} or @samp{F}, respectively.  These variants are
7213 semi-obsolete in GNU @code{make} since the functions @code{dir} and
7214 @code{notdir} can be used to get a similar effect (@pxref{Filename
7215 Functions, , Functions for File Names}).  Note, however, that the
7216 @samp{F} variants all omit the trailing slash which always appears in
7217 the output of the @code{dir} function.  Here is a table of the variants:
7219 @table @samp
7220 @vindex $(@@D)
7221 @vindex @@D @r{(automatic variable)}
7222 @item $(@@D)
7223 The directory part of the file name of the target, with the trailing
7224 slash removed.  If the value of @samp{$@@} is @file{dir/foo.o} then
7225 @samp{$(@@D)} is @file{dir}.  This value is @file{.} if @samp{$@@} does
7226 not contain a slash.
7228 @vindex $(@@F)
7229 @vindex @@F @r{(automatic variable)}
7230 @item $(@@F)
7231 The file-within-directory part of the file name of the target.  If the
7232 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
7233 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
7235 @vindex $(*D)
7236 @vindex *D @r{(automatic variable)}
7237 @item $(*D)
7238 @vindex $(*F)
7239 @vindex *F @r{(automatic variable)}
7240 @itemx $(*F)
7241 The directory part and the file-within-directory
7242 part of the stem; @file{dir} and @file{foo} in this example.
7244 @vindex $(%D)
7245 @vindex %D @r{(automatic variable)}
7246 @item $(%D)
7247 @vindex $(%F)
7248 @vindex %F @r{(automatic variable)}
7249 @itemx $(%F)
7250 The directory part and the file-within-directory part of the target
7251 archive member name.  This makes sense only for archive member targets
7252 of the form @file{@var{archive}(@var{member})} and is useful only when
7253 @var{member} may contain a directory name.  (@xref{Archive Members,
7254 ,Archive Members as Targets}.)
7256 @vindex $(<D)
7257 @vindex <D @r{(automatic variable)}
7258 @item $(<D)
7259 @vindex $(<F)
7260 @vindex <F @r{(automatic variable)}
7261 @itemx $(<F)
7262 The directory part and the file-within-directory
7263 part of the first dependency.
7265 @vindex $(^D)
7266 @vindex ^D @r{(automatic variable)}
7267 @item $(^D)
7268 @vindex $(^F)
7269 @vindex ^F @r{(automatic variable)}
7270 @itemx $(^F)
7271 Lists of the directory parts and the file-within-directory
7272 parts of all dependencies.
7274 @vindex $(?D)
7275 @vindex ?D @r{(automatic variable)}
7276 @item $(?D)
7277 @vindex $(?F)
7278 @vindex ?F @r{(automatic variable)}
7279 @itemx $(?F)
7280 Lists of the directory parts and the file-within-directory parts of
7281 all dependencies that are newer than the target.
7282 @end table
7284 Note that we use a special stylistic convention when we talk about these
7285 automatic variables; we write ``the value of @samp{$<}'', rather than
7286 @w{``the variable @code{<}''} as we would write for ordinary variables
7287 such as @code{objects} and @code{CFLAGS}.  We think this convention
7288 looks more natural in this special case.  Please do not assume it has a
7289 deep significance; @samp{$<} refers to the variable named @code{<} just
7290 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
7291 You could just as well use @samp{$(<)} in place of @samp{$<}.
7293 @node Pattern Match, Match-Anything Rules, Automatic, Pattern Rules
7294 @subsection How Patterns Match
7296 @cindex stem
7297 A target pattern is composed of a @samp{%} between a prefix and a suffix,
7298 either or both of which may be empty.  The pattern matches a file name only
7299 if the file name starts with the prefix and ends with the suffix, without
7300 overlap.  The text between the prefix and the suffix is called the
7301 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
7302 @file{test.o}, the stem is @samp{test}.  The pattern rule dependencies are
7303 turned into actual file names by substituting the stem for the character
7304 @samp{%}.  Thus, if in the same example one of the dependencies is written
7305 as @samp{%.c}, it expands to @samp{test.c}.@refill
7307 When the target pattern does not contain a slash (and it usually does
7308 not), directory names in the file names are removed from the file name
7309 before it is compared with the target prefix and suffix.  After the
7310 comparison of the file name to the target pattern, the directory
7311 names, along with the slash that ends them, are added on to the
7312 dependency file names generated from the pattern rule's dependency
7313 patterns and the file name. The directories are ignored only for the
7314 purpose of finding an implicit rule to use, not in the application of
7315 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
7316 with @samp{src/a} as the stem.  When dependencies are turned into file
7317 names, the directories from the stem are added at the front, while the
7318 rest of the stem is substituted for the @samp{%}.  The stem
7319 @samp{src/a} with a dependency pattern @samp{c%r} gives the file name
7320 @file{src/car}.@refill
7322 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
7323 @subsection Match-Anything Pattern Rules
7325 @cindex match-anything rule
7326 @cindex terminal rule
7327 When a pattern rule's target is just @samp{%}, it matches any file name
7328 whatever.  We call these rules @dfn{match-anything} rules.  They are very
7329 useful, but it can take a lot of time for @code{make} to think about them,
7330 because it must consider every such rule for each file name listed either
7331 as a target or as a dependency.
7333 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
7334 would have to consider making it by linking an object file @file{foo.c.o},
7335 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
7336 Pascal compilation-and-linking from @file{foo.c.p}, and many other
7337 possibilities.
7339 We know these possibilities are ridiculous since @file{foo.c} is a C source
7340 file, not an executable.  If @code{make} did consider these possibilities,
7341 it would ultimately reject them, because files such as @file{foo.c.o} and
7342 @file{foo.c.p} would not exist.  But these possibilities are so
7343 numerous that @code{make} would run very slowly if it had to consider
7344 them.@refill
7346 To gain speed, we have put various constraints on the way @code{make}
7347 considers match-anything rules.  There are two different constraints that
7348 can be applied, and each time you define a match-anything rule you must
7349 choose one or the other for that rule.
7351 One choice is to mark the match-anything rule as @dfn{terminal} by defining
7352 it with a double colon.  When a rule is terminal, it does not apply unless
7353 its dependencies actually exist.  Dependencies that could be made with
7354 other implicit rules are not good enough.  In other words, no further
7355 chaining is allowed beyond a terminal rule.
7357 For example, the built-in implicit rules for extracting sources from RCS
7358 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
7359 not exist, @code{make} will not even consider trying to make it as an
7360 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
7361 RCS and SCCS files are generally ultimate source files, which should not be
7362 remade from any other files; therefore, @code{make} can save time by not
7363 looking for ways to remake them.@refill
7365 If you do not mark the match-anything rule as terminal, then it is
7366 nonterminal.  A nonterminal match-anything rule cannot apply to a file name
7367 that indicates a specific type of data.  A file name indicates a specific
7368 type of data if some non-match-anything implicit rule target matches it.
7370 For example, the file name @file{foo.c} matches the target for the pattern
7371 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
7372 rule is actually applicable (which happens only if there is a file
7373 @file{foo.y}), the fact that its target matches is enough to prevent
7374 consideration of any nonterminal match-anything rules for the file
7375 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
7376 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
7377 @file{foo.c.p}, etc.@refill
7379 The motivation for this constraint is that nonterminal match-anything
7380 rules are used for making files containing specific types of data (such as
7381 executable files) and a file name with a recognized suffix indicates some
7382 other specific type of data (such as a C source file).
7384 Special built-in dummy pattern rules are provided solely to recognize
7385 certain file names so that nonterminal match-anything rules will not be
7386 considered.  These dummy rules have no dependencies and no commands, and
7387 they are ignored for all other purposes.  For example, the built-in
7388 implicit rule
7390 @example
7391 %.p :
7392 @end example
7394 @noindent
7395 exists to make sure that Pascal source files such as @file{foo.p} match a
7396 specific target pattern and thereby prevent time from being wasted looking
7397 for @file{foo.p.o} or @file{foo.p.c}.
7399 Dummy pattern rules such as the one for @samp{%.p} are made for every
7400 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
7402 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
7403 @subsection Canceling Implicit Rules
7405 You can override a built-in implicit rule (or one you have defined
7406 yourself) by defining a new pattern rule with the same target and
7407 dependencies, but different commands.  When the new rule is defined, the
7408 built-in one is replaced.  The new rule's position in the sequence of
7409 implicit rules is determined by where you write the new rule.
7411 You can cancel a built-in implicit rule by defining a pattern rule with the
7412 same target and dependencies, but no commands.  For example, the following
7413 would cancel the rule that runs the assembler:
7415 @example
7416 %.o : %.s
7417 @end example
7419 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
7420 @section Defining Last-Resort Default Rules
7421 @cindex last-resort default rules
7422 @cindex default rules, last-resort
7424 You can define a last-resort implicit rule by writing a terminal
7425 match-anything pattern rule with no dependencies (@pxref{Match-Anything
7426 Rules}).  This is just like any other pattern rule; the only thing
7427 special about it is that it will match any target.  So such a rule's
7428 commands are used for all targets and dependencies that have no commands
7429 of their own and for which no other implicit rule applies.
7431 For example, when testing a makefile, you might not care if the source
7432 files contain real data, only that they exist.  Then you might do this:
7434 @example
7436         touch $@@
7437 @end example
7439 @noindent
7440 to cause all the source files needed (as dependencies) to be created
7441 automatically.
7443 @findex .DEFAULT
7444 You can instead define commands to be used for targets for which there
7445 are no rules at all, even ones which don't specify commands.  You do
7446 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
7447 commands are used for all dependencies which do not appear as targets in
7448 any explicit rule, and for which no implicit rule applies.  Naturally,
7449 there is no @code{.DEFAULT} rule unless you write one.
7451 If you use @code{.DEFAULT} with no commands or dependencies:
7453 @example
7454 .DEFAULT:
7455 @end example
7457 @noindent
7458 the commands previously stored for @code{.DEFAULT} are cleared.
7459 Then @code{make} acts as if you had never defined @code{.DEFAULT} at all.
7461 If you do not want a target to get the commands from a match-anything
7462 pattern rule or @code{.DEFAULT}, but you also do not want any commands
7463 to be run for the target, you can give it empty commands (@pxref{Empty
7464 Commands, ,Defining Empty Commands}).@refill
7466 You can use a last-resort rule to override part of another makefile.
7467 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
7469 @node Suffix Rules, Search Algorithm, Last Resort, Implicit Rules
7470 @section Old-Fashioned Suffix Rules
7471 @cindex old-fashioned suffix rules
7472 @cindex suffix rule
7474 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
7475 @code{make}.  Suffix rules are obsolete because pattern rules are more
7476 general and clearer.  They are supported in GNU @code{make} for
7477 compatibility with old makefiles.  They come in two kinds:
7478 @dfn{double-suffix} and @dfn{single-suffix}.@refill
7480 A double-suffix rule is defined by a pair of suffixes: the target suffix
7481 and the source suffix.  It matches any file whose name ends with the
7482 target suffix.  The corresponding implicit dependency is made by
7483 replacing the target suffix with the source suffix in the file name.  A
7484 two-suffix rule whose target and source suffixes are @samp{.o} and
7485 @samp{.c} is equivalent to the pattern rule @samp{%.o : %.c}.
7487 A single-suffix rule is defined by a single suffix, which is the source
7488 suffix.  It matches any file name, and the corresponding implicit
7489 dependency name is made by appending the source suffix.  A single-suffix
7490 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
7491 @samp{% : %.c}.
7493 Suffix rule definitions are recognized by comparing each rule's target
7494 against a defined list of known suffixes.  When @code{make} sees a rule
7495 whose target is a known suffix, this rule is considered a single-suffix
7496 rule.  When @code{make} sees a rule whose target is two known suffixes
7497 concatenated, this rule is taken as a double-suffix rule.
7499 For example, @samp{.c} and @samp{.o} are both on the default list of
7500 known suffixes.  Therefore, if you define a rule whose target is
7501 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
7502 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
7503 way to define the rule for compiling a C source file:@refill
7505 @example
7506 .c.o:
7507         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7508 @end example
7510 Suffix rules cannot have any dependencies of their own.  If they have any,
7511 they are treated as normal files with funny names, not as suffix rules.
7512 Thus, the rule:
7514 @example
7515 .c.o: foo.h
7516         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7517 @end example
7519 @noindent
7520 tells how to make the file @file{.c.o} from the dependency file
7521 @file{foo.h}, and is not at all like the pattern rule:
7523 @example
7524 %.o: %.c foo.h
7525         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7526 @end example
7528 @noindent
7529 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
7530 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
7532 Suffix rules with no commands are also meaningless.  They do not remove
7533 previous rules as do pattern rules with no commands (@pxref{Canceling
7534 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or pair of suffixes concatenated as
7535 a target in the data base.@refill
7537 @findex .SUFFIXES
7538 The known suffixes are simply the names of the dependencies of the special
7539 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
7540 for @code{.SUFFIXES} that adds more dependencies, as in:
7542 @example
7543 .SUFFIXES: .hack .win
7544 @end example
7546 @noindent
7547 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
7549 If you wish to eliminate the default known suffixes instead of just adding
7550 to them, write a rule for @code{.SUFFIXES} with no dependencies.  By
7551 special dispensation, this eliminates all existing dependencies of
7552 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
7553 want.  For example,
7555 @example
7556 @group
7557 .SUFFIXES:            # @r{Delete the default suffixes}
7558 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
7559 @end group
7560 @end example
7562 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
7563 list of suffixes to be empty.
7565 @vindex SUFFIXES
7566 The variable @code{SUFFIXES} is defined to the default list of suffixes
7567 before @code{make} reads any makefiles.  You can change the list of suffixes
7568 with a rule for the special target @code{.SUFFIXES}, but that does not alter
7569 this variable.
7571 @node Search Algorithm,  , Suffix Rules, Implicit Rules
7572 @section Implicit Rule Search Algorithm
7573 @cindex implicit rule, search algorithm
7574 @cindex search algorithm, implicit rule
7576 Here is the procedure @code{make} uses for searching for an implicit rule
7577 for a target @var{t}.  This procedure is followed for each double-colon
7578 rule with no commands, for each target of ordinary rules none of which have
7579 commands, and for each dependency that is not the target of any rule.  It
7580 is also followed recursively for dependencies that come from implicit
7581 rules, in the search for a chain of rules.
7583 Suffix rules are not mentioned in this algorithm because suffix rules are
7584 converted to equivalent pattern rules once the makefiles have been read in.
7586 For an archive member target of the form
7587 @samp{@var{archive}(@var{member})}, the following algorithm is run
7588 twice, first using the entire target name @var{t}, and second using
7589 @samp{(@var{member})} as the target @var{t} if the first run found no
7590 rule.@refill
7592 @enumerate
7593 @item
7594 Split @var{t} into a directory part, called @var{d}, and the rest,
7595 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
7596 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.@refill
7598 @item
7599 Make a list of all the pattern rules one of whose targets matches
7600 @var{t} or @var{n}.  If the target pattern contains a slash, it is
7601 matched against @var{t}; otherwise, against @var{n}.
7603 @item
7604 If any rule in that list is @emph{not} a match-anything rule, then
7605 remove all nonterminal match-anything rules from the list.
7607 @item
7608 Remove from the list all rules with no commands.
7610 @item
7611 For each pattern rule in the list:
7613 @enumerate a
7614 @item
7615 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
7616 matched by the @samp{%} in the target pattern.@refill
7618 @item
7619 Compute the dependency names by substituting @var{s} for @samp{%}; if
7620 the target pattern does not contain a slash, append @var{d} to
7621 the front of each dependency name.@refill
7623 @item
7624 Test whether all the dependencies exist or ought to exist.  (If a
7625 file name is mentioned in the makefile as a target or as an explicit
7626 dependency, then we say it ought to exist.)
7628 If all dependencies exist or ought to exist, or there are no dependencies,
7629 then this rule applies.
7630 @end enumerate
7632 @item
7633 If no pattern rule has been found so far, try harder.
7634 For each pattern rule in the list:
7636 @enumerate a
7637 @item
7638 If the rule is terminal, ignore it and go on to the next rule.
7640 @item
7641 Compute the dependency names as before.
7643 @item
7644 Test whether all the dependencies exist or ought to exist.
7646 @item
7647 For each dependency that does not exist, follow this algorithm
7648 recursively to see if the dependency can be made by an implicit
7649 rule.
7651 @item
7652 If all dependencies exist, ought to exist, or can be
7653 made by implicit rules, then this rule applies.
7654 @end enumerate
7656 @item
7657 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
7658 applies.  In that case, give @var{t} the same commands that
7659 @code{.DEFAULT} has.  Otherwise, there are no commands for @var{t}.
7660 @end enumerate
7662 Once a rule that applies has been found, for each target pattern of the
7663 rule other than the one that matched @var{t} or @var{n}, the @samp{%} in
7664 the pattern is replaced with @var{s} and the resultant file name is stored
7665 until the commands to remake the target file @var{t} are executed.  After
7666 these commands are executed, each of these stored file names are entered
7667 into the data base and marked as having been updated and having the same
7668 update status as the file @var{t}.
7670 When the commands of a pattern rule are executed for @var{t}, the automatic
7671 variables are set corresponding to the target and dependencies.
7672 @xref{Automatic, ,Automatic Variables}.
7674 @node Archives, Features, Implicit Rules, Top
7675 @chapter Using @code{make} to Update Archive Files
7676 @cindex archive
7678 @dfn{Archive files} are files containing named subfiles called
7679 @dfn{members}; they are maintained with the program @code{ar} and their
7680 main use is as subroutine libraries for linking.
7682 @menu
7683 * Archive Members::             Archive members as targets.
7684 * Archive Update::              The implicit rule for archive member targets.
7685 * Archive Pitfalls::            Dangers to watch out for when using archives.
7686 * Archive Suffix Rules::        You can write a special kind of suffix rule
7687                                   for updating archives.
7688 @end menu
7690 @node Archive Members, Archive Update,  , Archives
7691 @section Archive Members as Targets
7692 @cindex archive member targets
7694 An individual member of an archive file can be used as a target or
7695 dependency in @code{make}.  You specify the member named @var{member} in
7696 archive file @var{archive} as follows:
7698 @example
7699 @var{archive}(@var{member})
7700 @end example
7702 @noindent
7703 This construct is available only in targets and dependencies, not in
7704 commands!  Most programs that you might use in commands do not support this
7705 syntax and cannot act directly on archive members.  Only @code{ar} and
7706 other programs specifically designed to operate on archives can do so.
7707 Therefore, valid commands to update an archive member target probably must
7708 use @code{ar}.  For example, this rule says to create a member
7709 @file{hack.o} in archive @file{foolib} by copying the file @file{hack.o}:
7711 @example
7712 foolib(hack.o) : hack.o
7713         ar cr foolib hack.o
7714 @end example
7716 In fact, nearly all archive member targets are updated in just this way
7717 and there is an implicit rule to do it for you.  @strong{Note:} The
7718 @samp{c} flag to @code{ar} is required if the archive file does not
7719 already exist.
7721 To specify several members in the same archive, you can write all the
7722 member names together between the parentheses.  For example:
7724 @example
7725 foolib(hack.o kludge.o)
7726 @end example
7728 @noindent
7729 is equivalent to:
7731 @example
7732 foolib(hack.o) foolib(kludge.o)
7733 @end example
7735 @cindex wildcard, in archive member
7736 You can also use shell-style wildcards in an archive member reference.
7737 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
7738 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
7739 @file{foolib} archive whose names end in @samp{.o}; perhaps
7740 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
7742 @node Archive Update
7743 @section Implicit Rule for Archive Member Targets
7745 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
7746 member named @var{m} in the archive file @var{a}.
7748 When @code{make} looks for an implicit rule for such a target, as a special
7749 feature it considers implicit rules that match @file{(@var{m})}, as well as
7750 those that match the actual target @file{@var{a}(@var{m})}.
7752 This causes one special rule whose target is @file{(%)} to match.  This
7753 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
7754 into the archive.  For example, it will update the archive member target
7755 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
7756 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
7758 When this rule is chained with others, the result is very powerful.
7759 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
7760 @samp{(} and @samp{)} from being interpreted specially by the shell) in
7761 the presence of a file @file{bar.c} is enough to cause the following
7762 commands to be run, even without a makefile:
7764 @example
7765 cc -c bar.c -o bar.o
7766 ar r foo.a bar.o
7767 rm -f bar.o
7768 @end example
7770 @noindent
7771 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
7772 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
7774 Implicit rules such as this one are written using the automatic variable
7775 @samp{$%}.  @xref{Automatic, ,Automatic Variables}.
7777 An archive member name in an archive cannot contain a directory name, but
7778 it may be useful in a makefile to pretend that it does.  If you write an
7779 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
7780 automatic updating with this command:
7782 @example
7783 ar r foo.a dir/file.o
7784 @end example
7786 @noindent
7787 which has the effect of copying the file @file{dir/file.o} into a member
7788 named @file{file.o}.  In connection with such usage, the automatic variables
7789 @code{%D} and @code{%F} may be useful.
7791 @menu
7792 * Archive Symbols::             How to update archive symbol directories.
7793 @end menu
7795 @node Archive Symbols,  ,  , Archive Update
7796 @subsection Updating Archive Symbol Directories
7797 @cindex @code{__.SYMDEF}
7798 @cindex updating archive symbol directories
7799 @cindex archive symbol directory updating
7800 @cindex symbol directories, updating archive 
7801 @cindex directories, updating archive symbol
7803 An archive file that is used as a library usually contains a special member
7804 named @file{__.SYMDEF} that contains a directory of the external symbol
7805 names defined by all the other members.  After you update any other
7806 members, you need to update @file{__.SYMDEF} so that it will summarize the
7807 other members properly.  This is done by running the @code{ranlib} program:
7809 @example
7810 ranlib @var{archivefile}
7811 @end example
7813 Normally you would put this command in the rule for the archive file,
7814 and make all the members of the archive file dependencies of that rule.
7815 For example,
7817 @example
7818 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
7819         ranlib libfoo.a
7820 @end example
7822 @noindent
7823 The effect of this is to update archive members @file{x.o}, @file{y.o},
7824 etc., and then update the symbol directory member @file{__.SYMDEF} by
7825 running @code{ranlib}.  The rules for updating the members are not shown
7826 here; most likely you can omit them and use the implicit rule which copies
7827 files into the archive, as described in the preceding section.
7829 This is not necessary when using the GNU @code{ar} program, which
7830 updates the @file{__.SYMDEF} member automatically.
7832 @node Archive Pitfalls
7833 @section Dangers When Using Archives
7834 @cindex archive, and parallel execution
7835 @cindex parallel execution, and archive update
7836 @cindex archive, and @code{-j}
7837 @cindex @code{-j}, and archive update
7839 It is important to be careful when using parallel execution (the
7840 @code{-j} switch; @pxref{Parallel, ,Parallel Execution}) and archives.
7841 If multiple @code{ar} commands run at the same time on the same archive
7842 file, they will not know about each other and can corrupt the file.
7844 Possibly a future version of @code{make} will provide a mechanism to
7845 circumvent this problem by serializing all commands that operate on the
7846 same archive file.  But for the time being, you must either write your
7847 makefiles to avoid this problem in some other way, or not use @code{-j}.
7849 @node Archive Suffix Rules, , Archive Pitfalls, Archives
7850 @section Suffix Rules for Archive Files
7851 @cindex suffix rule, for archive
7852 @cindex archive, suffix rule for
7853 @cindex library archive, suffix rule for
7854 @cindex @code{.a} (archives)
7856 You can write a special kind of suffix rule for dealing with archive
7857 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
7858 Archive suffix rules are obsolete in GNU @code{make}, because pattern
7859 rules for archives are a more general mechanism (@pxref{Archive
7860 Update}).  But they are retained for compatibility with other
7861 @code{make}s.
7863 To write a suffix rule for archives, you simply write a suffix rule
7864 using the target suffix @samp{.a} (the usual suffix for archive files).
7865 For example, here is the old-fashioned suffix rule to update a library
7866 archive from C source files:
7868 @example
7869 @group
7870 .c.a:
7871         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
7872         $(AR) r $@@ $*.o
7873         $(RM) $*.o
7874 @end group
7875 @end example
7877 @noindent
7878 This works just as if you had written the pattern rule:
7880 @example
7881 @group
7882 (%.o): %.c
7883         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
7884         $(AR) r $@@ $*.o
7885         $(RM) $*.o
7886 @end group
7887 @end example
7889 In fact, this is just what @code{make} does when it sees a suffix rule
7890 with @samp{.a} as the target suffix.  Any double-suffix rule
7891 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
7892 pattern @samp{(%.o)} and a dependency pattern of @samp{%.@var{x}}.
7894 Since you might want to use @samp{.a} as the suffix for some other kind
7895 of file, @code{make} also converts archive suffix rules to pattern rules
7896 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
7897 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
7898 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
7900 @node Features, Missing, Archives, Top
7901 @chapter Features of GNU @code{make}
7902 @cindex features of GNU @code{make}
7903 @cindex portability
7904 @cindex compatibility
7906 Here is a summary of the features of GNU @code{make}, for comparison
7907 with and credit to other versions of @code{make}.  We consider the
7908 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
7909 concerned with writing portable makefiles, you should use only the
7910 features of @code{make} @emph{not} listed here or in @ref{Missing}.
7912 Many features come from the version of @code{make} in System V.
7914 @itemize @bullet
7915 @item
7916 The @code{VPATH} variable and its special meaning. 
7917 @xref{Directory Search, , Searching Directories for Dependencies}.  
7918 This feature exists in System V @code{make}, but is undocumented.
7919 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
7920 @code{VPATH} feature).@refill
7922 @item
7923 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
7924 Allowing multiple files to be included with a single directive is a GNU
7925 extension.
7927 @item
7928 Variables are read from and communicated via the environment.
7929 @xref{Environment, ,Variables from the Environment}.
7931 @item
7932 Options passed through the variable @code{MAKEFLAGS} to recursive
7933 invocations of @code{make}.
7934 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
7936 @item
7937 The automatic variable @code{$%} is set to the member name
7938 in an archive reference.  @xref{Automatic, ,Automatic Variables}.
7940 @item
7941 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
7942 and @code{$?} have corresponding forms like @code{$(@@F)} and
7943 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
7944 extension.  @xref{Automatic, ,Automatic Variables}.@refill
7946 @item
7947 Substitution variable references.
7948 @xref{Reference, ,Basics of Variable References}.
7950 @item
7951 The command-line options @samp{-b} and @samp{-m}, accepted and
7952 ignored.  In System V @code{make}, these options actually do something.
7954 @item
7955 Execution of recursive commands to run @code{make} via the variable
7956 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
7957 @xref{Recursion, ,Recursive Use of @code{make}}.
7959 @item
7960 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
7961 Rules}.  This feature is obsolete in GNU @code{make}, because the
7962 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
7963 Implicit Rules}) allows one pattern rule for installing members in an
7964 archive (@pxref{Archive Update}) to be sufficient.
7966 @item
7967 The arrangement of lines and backslash-newline combinations in
7968 commands is retained when the commands are printed, so they appear as
7969 they do in the makefile, except for the stripping of initial
7970 whitespace.
7971 @end itemize
7973 The following features were inspired by various other versions of
7974 @code{make}.  In some cases it is unclear exactly which versions inspired
7975 which others.
7977 @itemize @bullet
7978 @item
7979 Pattern rules using @samp{%}.
7980 This has been implemented in several versions of @code{make}.
7981 We're not sure who invented it first, but it's been spread around a bit.
7982 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.@refill
7984 @item
7985 Rule chaining and implicit intermediate files.
7986 This was implemented by Stu Feldman in his version of @code{make}
7987 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
7988 AT&T Bell Labs in his @code{mk} program (where he terms it
7989 ``transitive closure'').  We do not really know if
7990 we got this from either of them or thought it up ourselves at the
7991 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
7993 @item
7994 The automatic variable @code{$^} containing a list of all dependencies
7995 of the current target.  We did not invent this, but we have no idea who
7996 did.  @xref{Automatic, ,Automatic Variables}.  The automatic variable
7997 @code{$+} is a simple extension of @code{$^}.
7999 @item
8000 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
8001 invented by Andrew Hume in @code{mk}.  
8002 @xref{Instead of Execution, ,Instead of Executing the Commands}.
8004 @item
8005 The concept of doing several things at once (parallelism) exists in
8006 many incarnations of @code{make} and similar programs, though not in the
8007 System V or BSD implementations.  @xref{Execution, ,Command Execution}.
8009 @item
8010 Modified variable references using pattern substitution come from
8011 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
8012 This functionality was provided in GNU @code{make} by the
8013 @code{patsubst} function before the alternate syntax was implemented
8014 for compatibility with SunOS 4.  It is not altogether clear who
8015 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
8016 4 was released.@refill
8018 @item
8019 The special significance of @samp{+} characters preceding command lines
8020 (@pxref{Instead of Execution, ,Instead of Executing the Commands}) is
8021 mandated by
8022 @cite{IEEE Standard 1003.2-1992} (POSIX.2).
8024 @item
8025 The @samp{+=} syntax to append to the value of a variable comes from SunOS
8026 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
8028 @item
8029 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
8030 multiple members in a single archive file comes from SunOS 4 @code{make}.
8031 @xref{Archive Members}.
8033 @item
8034 The @code{-include} directive to include makefiles with no error for a
8035 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
8036 @code{make} does not allow multiple makefiles to be specified in one
8037 @code{-include} directive.)
8038 @end itemize
8040 The remaining features are inventions new in GNU @code{make}:
8042 @itemize @bullet
8043 @item
8044 Use the @samp{-v} or @samp{--version} option to print version and
8045 copyright information.
8047 @item 
8048 Use the @samp{-h} or @samp{--help} option to summarize the options to
8049 @code{make}.
8051 @item
8052 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
8054 @item
8055 Pass command-line variable assignments automatically through the
8056 variable @code{MAKE} to recursive @code{make} invocations.
8057 @xref{Recursion, ,Recursive Use of @code{make}}.
8059 @item
8060 Use the @samp{-C} or @samp{--directory} command option to change
8061 directory.  @xref{Options Summary, ,Summary of Options}.
8063 @item
8064 Make verbatim variable definitions with @code{define}.  
8065 @xref{Defining, ,Defining Variables Verbatim}.
8067 @item
8068 Declare phony targets with the special target @code{.PHONY}.
8070 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
8071 different syntax in his @code{mk} program.  This seems to be a case of
8072 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
8074 @item
8075 Manipulate text by calling functions.  
8076 @xref{Functions, ,Functions for Transforming Text}.
8078 @item
8079 Use the @samp{-o} or @samp{--old-file}
8080 option to pretend a file's modification-time is old.
8081 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
8083 @item
8084 Conditional execution.
8086 This feature has been implemented numerous times in various versions
8087 of @code{make}; it seems a natural extension derived from the features
8088 of the C preprocessor and similar macro languages and is not a
8089 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
8091 @item
8092 Specify a search path for included makefiles.
8093 @xref{Include, ,Including Other Makefiles}.
8095 @item
8096 Specify extra makefiles to read with an environment variable.
8097 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
8099 @item
8100 Strip leading sequences of @samp{./} from file names, so that
8101 @file{./@var{file}} and @file{@var{file}} are considered to be the
8102 same file.@refill
8104 @item
8105 Use a special search method for library dependencies written in the
8106 form @samp{-l@var{name}}.  
8107 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
8109 @item
8110 Allow suffixes for suffix rules 
8111 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
8112 characters.  In other versions of @code{make}, they must begin with
8113 @samp{.} and not contain any @samp{/} characters.
8115 @item
8116 Keep track of the current level of @code{make} recursion using the
8117 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
8119 @item
8120 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
8122 @item
8123 Provide selective @code{vpath} search.  
8124 @xref{Directory Search, ,Searching Directories for Dependencies}.
8126 @item
8127 Provide computed variable references.  
8128 @xref{Reference, ,Basics of Variable References}.
8130 @item
8131 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
8132 System V @code{make} has a very, very limited form of this
8133 functionality in that it will check out SCCS files for makefiles.
8135 @item
8136 Various new built-in implicit rules.  
8137 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
8139 @item
8140 The built-in variable @samp{MAKE_VERSION} gives the version number of
8141 @code{make}.
8142 @end itemize
8144 @node Missing, Makefile Conventions, Features, Top
8145 @chapter Incompatibilities and Missing Features
8146 @cindex incompatibilities 
8147 @cindex missing features
8148 @cindex features, missing
8150 The @code{make} programs in various other systems support a few features
8151 that are not implemented in GNU @code{make}.  The POSIX.2 standard
8152 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
8153 require any of these features.@refill
8155 @itemize @bullet
8156 @item
8157 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
8158 of archive file @var{file}.  The member is chosen, not by name, but by
8159 being an object file which defines the linker symbol @var{entry}.@refill
8161 This feature was not put into GNU @code{make} because of the
8162 nonmodularity of putting knowledge into @code{make} of the internal
8163 format of archive file symbol tables.  
8164 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
8166 @item
8167 Suffixes (used in suffix rules) that end with the character @samp{~}
8168 have a special meaning to System V @code{make}; 
8169 they refer to the SCCS file that corresponds
8170 to the file one would get without the @samp{~}.  For example, the
8171 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
8172 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
8173 series of such suffix rules is required.  
8174 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
8176 In GNU @code{make}, this entire series of cases is handled by two
8177 pattern rules for extraction from SCCS, in combination with the
8178 general feature of rule chaining.  
8179 @xref{Chained Rules, ,Chains of Implicit Rules}.
8181 @item
8182 In System V @code{make}, the string @samp{$$@@} has the strange meaning
8183 that, in the dependencies of a rule with multiple targets, it stands
8184 for the particular target that is being processed.
8186 This is not defined in GNU @code{make} because @samp{$$} should always
8187 stand for an ordinary @samp{$}.
8189 It is possible to get this functionality through the use of static pattern
8190 rules (@pxref{Static Pattern, ,Static Pattern Rules}).  
8191 The System V @code{make} rule:
8193 @example
8194 $(targets): $$@@.o lib.a
8195 @end example
8197 @noindent
8198 can be replaced with the GNU @code{make} static pattern rule:
8200 @example
8201 $(targets): %: %.o lib.a
8202 @end example
8204 @item
8205 In System V and 4.3 BSD @code{make}, files found by @code{VPATH} search
8206 (@pxref{Directory Search, ,Searching Directories for Dependencies}) have their names changed inside command
8207 strings.  We feel it is much cleaner to always use automatic variables
8208 and thus make this feature obsolete.@refill
8210 @item
8211 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
8212 the dependencies of a rule has the amazingly strange ``feature'' of
8213 expanding to the full name of the @emph{target of that rule}.  We cannot
8214 imagine what went on in the minds of Unix @code{make} developers to do
8215 this; it is utterly inconsistent with the normal definition of @code{$*}.
8216 @vindex * @r{(automatic variable), unsupported bizarre usage}
8218 @item
8219 In some Unix @code{make}s, implicit rule search
8220 (@pxref{Implicit Rules, ,Using Implicit Rules}) is apparently done for
8221 @emph{all} targets, not just those without commands.  This means you can
8222 do:@refill
8224 @example
8225 @group
8226 foo.o:
8227         cc -c foo.c
8228 @end group
8229 @end example
8231 @noindent
8232 and Unix @code{make} will intuit that @file{foo.o} depends on
8233 @file{foo.c}.@refill
8235 We feel that such usage is broken.  The dependency properties of
8236 @code{make} are well-defined (for GNU @code{make}, at least),
8237 and doing such a thing simply does not fit the model.@refill
8239 @item
8240 GNU @code{make} does not include any built-in implicit rules for
8241 compiling or preprocessing EFL programs.  If we hear of anyone who is
8242 using EFL, we will gladly add them.
8244 @item
8245 It appears that in SVR4 @code{make}, a suffix rule can be specified with
8246 no commands, and it is treated as if it had empty commands
8247 (@pxref{Empty Commands}).  For example:
8249 @example
8250 .c.a:
8251 @end example
8253 @noindent
8254 will override the built-in @file{.c.a} suffix rule.
8256 We feel that it is cleaner for a rule without commands to always simply
8257 add to the dependency list for the target.  The above example can be
8258 easily rewritten to get the desired behavior in GNU @code{make}:
8260 @example
8261 .c.a: ;
8262 @end example
8264 @item
8265 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
8266 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
8267 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
8268 program it runs returns a nonzero status.  We feel it is cleaner to
8269 write each shell command line to stand on its own and not require this
8270 special treatment.
8271 @end itemize
8273 @comment The makefile standards are in a separate file that is also
8274 @comment included by standards.texi.
8275 @include make-stds.texi
8277 @node Quick Reference, Complex Makefile, Makefile Conventions, Top
8278 @appendix Quick Reference
8280 This appendix summarizes the directives, text manipulation functions,
8281 and special variables which GNU @code{make} understands.
8282 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
8283 and @ref{Options Summary, ,Summary of Options},
8284 for other summaries.
8286 Here is a summary of the directives GNU @code{make} recognizes:
8288 @table @code
8289 @item define @var{variable}
8290 @itemx endef
8292 Define a multi-line, recursively-expanded variable.@*
8293 @xref{Sequences}.
8295 @item ifdef @var{variable}
8296 @itemx ifndef @var{variable}
8297 @itemx ifeq (@var{a},@var{b})
8298 @itemx ifeq "@var{a}" "@var{b}"
8299 @itemx ifeq '@var{a}' '@var{b}'
8300 @itemx ifneq (@var{a},@var{b})
8301 @itemx ifneq "@var{a}" "@var{b}"
8302 @itemx ifneq '@var{a}' '@var{b}'
8303 @itemx else
8304 @itemx endif
8306 Conditionally evaluate part of the makefile.@*
8307 @xref{Conditionals}.
8309 @item include @var{file}
8311 Include another makefile.@*
8312 @xref{Include, ,Including Other Makefiles}.
8314 @item override @var{variable} = @var{value}
8315 @itemx override @var{variable} := @var{value}
8316 @itemx override @var{variable} += @var{value}
8317 @itemx override define @var{variable}
8318 @itemx endef
8320 Define a variable, overriding any previous definition, even one from
8321 the command line.@*
8322 @xref{Override Directive, ,The @code{override} Directive}.
8324 @item export
8326 Tell @code{make} to export all variables to child processes by default.@*
8327 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
8329 @item export @var{variable}
8330 @itemx export @var{variable} = @var{value}
8331 @itemx export @var{variable} := @var{value}
8332 @itemx export @var{variable} += @var{value}
8333 @itemx unexport @var{variable}
8334 Tell @code{make} whether or not to export a particular variable to child
8335 processes.@*
8336 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
8338 @item vpath @var{pattern} @var{path}
8339 Specify a search path for files matching a @samp{%} pattern.@*
8340 @xref{Selective Search, , The @code{vpath} Directive}.
8342 @item vpath @var{pattern}
8343 Remove all search paths previously specified for @var{pattern}.
8345 @item vpath
8346 Remove all search paths previously specified in any @code{vpath}
8347 directive.
8348 @end table
8350 Here is a summary of the text manipulation functions (@pxref{Functions}):
8352 @table @code
8353 @item $(subst @var{from},@var{to},@var{text})
8354 Replace @var{from} with @var{to} in @var{text}.@*
8355 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8357 @item $(patsubst @var{pattern},@var{replacement},@var{text})
8358 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
8359 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8361 @item $(strip @var{string})
8362 Remove excess whitespace characters from @var{string}.@*
8363 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8365 @item $(findstring @var{find},@var{text})
8366 Locate @var{find} in @var{text}.@*
8367 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8369 @item $(filter @var{pattern}@dots{},@var{text})
8370 Select words in @var{text} that match one of the @var{pattern} words.@*
8371 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8373 @item $(filter-out @var{pattern}@dots{},@var{text})
8374 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
8375 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8377 @item $(sort @var{list})
8378 Sort the words in @var{list} lexicographically, removing duplicates.@*
8379 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8381 @item $(dir @var{names}@dots{})
8382 Extract the directory part of each file name.@*
8383 @xref{Filename Functions, ,Functions for File Names}.
8385 @item $(notdir @var{names}@dots{})
8386 Extract the non-directory part of each file name.@*
8387 @xref{Filename Functions, ,Functions for File Names}.
8389 @item $(suffix @var{names}@dots{})
8390 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
8391 @xref{Filename Functions, ,Functions for File Names}.
8393 @item $(basename @var{names}@dots{})
8394 Extract the base name (name without suffix) of each file name.@*
8395 @xref{Filename Functions, ,Functions for File Names}.
8397 @item $(addsuffix @var{suffix},@var{names}@dots{})
8398 Append @var{suffix} to each word in @var{names}.@*
8399 @xref{Filename Functions, ,Functions for File Names}.
8401 @item $(addprefix @var{prefix},@var{names}@dots{})
8402 Prepend @var{prefix} to each word in @var{names}.@*
8403 @xref{Filename Functions, ,Functions for File Names}.
8405 @item $(join @var{list1},@var{list2})
8406 Join two parallel lists of words.@*
8407 @xref{Filename Functions, ,Functions for File Names}.
8409 @item $(word @var{n},@var{text})
8410 Extract the @var{n}th word (one-origin) of @var{text}.@*
8411 @xref{Filename Functions, ,Functions for File Names}.
8413 @item $(words @var{text})
8414 Count the number of words in @var{text}.@*
8415 @xref{Filename Functions, ,Functions for File Names}.
8417 @item $(firstword @var{names}@dots{})
8418 Extract the first word of @var{names}.@*
8419 @xref{Filename Functions, ,Functions for File Names}.
8421 @item $(wildcard @var{pattern}@dots{})
8422 Find file names matching a shell file name pattern (@emph{not} a
8423 @samp{%} pattern).@*
8424 @xref{Wildcard Function, ,The Function @code{wildcard}}.
8426 @item $(shell @var{command})
8428 Execute a shell command and return its output.@*
8429 @xref{Shell Function, , The @code{shell} Function}.
8431 @item $(origin @var{variable})
8433 Return a string describing how the @code{make} variable @var{variable} was
8434 defined.@*
8435 @xref{Origin Function, , The @code{origin} Function}.
8437 @item $(foreach @var{var},@var{words},@var{text})
8439 Evaluate @var{text} with @var{var} bound to each word in @var{words},
8440 and concatenate the results.@*
8441 @xref{Foreach Function, ,The @code{foreach} Function}.
8442 @end table
8444 Here is a summary of the automatic variables.
8445 @xref{Automatic, ,Automatic Variables},
8446 for full information.
8448 @table @code
8449 @item $@@
8450 The file name of the target.
8452 @item $%
8453 The target member name, when the target is an archive member.
8455 @item $<
8456 The name of the first dependency.
8458 @item $?
8459 The names of all the dependencies that are
8460 newer than the target, with spaces between them.
8461 For dependencies which are archive members, only
8462 the member named is used (@pxref{Archives}).
8464 @item $^
8465 @itemx $+
8466 The names of all the dependencies, with spaces between them.  For
8467 dependencies which are archive members, only the member named is used
8468 (@pxref{Archives}).  The value of @code{$^} omits duplicate
8469 dependencies, while @code{$+} retains them and preserves their order.
8471 @item $*
8472 The stem with which an implicit rule matches 
8473 (@pxref{Pattern Match, ,How Patterns Match}).
8475 @item $(@@D)
8476 @itemx $(@@F)
8477 The directory part and the file-within-directory part of @code{$@@}.
8479 @item $(*D)
8480 @itemx $(*F)
8481 The directory part and the file-within-directory part of @code{$*}.
8483 @item $(%D)
8484 @itemx $(%F)
8485 The directory part and the file-within-directory part of @code{$%}.
8487 @item $(<D)
8488 @itemx $(<F)
8489 The directory part and the file-within-directory part of @code{$<}.
8491 @item $(^D)
8492 @itemx $(^F)
8493 The directory part and the file-within-directory part of @code{$^}.
8495 @item $(+D)
8496 @itemx $(+F)
8497 The directory part and the file-within-directory part of @code{$+}.
8499 @item $(?D)
8500 @itemx $(?F)
8501 The directory part and the file-within-directory part of @code{$?}.
8502 @end table
8504 These variables are used specially by GNU @code{make}:
8506 @table @code
8507 @item MAKEFILES
8509 Makefiles to be read on every invocation of @code{make}.@*
8510 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
8512 @item VPATH
8514 Directory search path for files not found in the current directory.@*
8515 @xref{General Search, , @code{VPATH} Search Path for All Dependencies}.  
8517 @item SHELL
8519 The name of the system default command interpreter, usually @file{/bin/sh}.
8520 You can set @code{SHELL} in the makefile to change the shell used to run
8521 commands.  @xref{Execution, ,Command Execution}.
8523 @item MAKE
8525 The name with which @code{make} was invoked.
8526 Using this variable in commands has special meaning.
8527 @xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.
8529 @item MAKELEVEL
8531 The number of levels of recursion (sub-@code{make}s).@*
8532 @xref{Variables/Recursion}.
8534 @item MAKEFLAGS
8536 The flags given to @code{make}.  You can set this in the environment or
8537 a makefile to set flags.@*
8538 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
8540 @item SUFFIXES
8542 The default list of suffixes before @code{make} reads any makefiles.
8543 @end table
8545 @node Complex Makefile, Concept Index, Quick Reference, Top
8546 @appendix Complex Makefile Example
8548 Here is the makefile for the GNU @code{tar} program.  This is a
8549 moderately complex makefile.
8551 Because it is the first target, the default goal is @samp{all}.  An
8552 interesting feature of this makefile is that @file{testpad.h} is a
8553 source file automatically created by the @code{testpad} program,
8554 itself compiled from @file{testpad.c}.
8556 If you type @samp{make} or @samp{make all}, then @code{make} creates
8557 the @file{tar} executable, the @file{rmt} daemon that provides
8558 remote tape access, and the @file{tar.info} Info file.
8560 If you type @samp{make install}, then @code{make} not only creates
8561 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
8562 them.
8564 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
8565 files, and the @file{tar}, @file{rmt}, @file{testpad},
8566 @file{testpad.h}, and @file{core} files.
8568 If you type @samp{make distclean}, then @code{make} not only removes
8569 the same files as does @samp{make clean} but also the
8570 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
8571 (Although it is not evident, this makefile (and
8572 @file{config.status}) is generated by the user with the
8573 @code{configure} program, which is provided in the @code{tar}
8574 distribution, but is not shown here.)
8576 If you type @samp{make realclean}, then @code{make} removes the same
8577 files as does @samp{make distclean} and also removes the Info files
8578 generated from @file{tar.texinfo}.
8580 In addition, there are targets @code{shar} and @code{dist} that create
8581 distribution kits.
8583 @example
8584 @group
8585 # Generated automatically from Makefile.in by configure.
8586 # Un*x Makefile for GNU tar program.
8587 # Copyright (C) 1991 Free Software Foundation, Inc.
8588 @end group
8590 @group
8591 # This program is free software; you can redistribute
8592 # it and/or modify it under the terms of the GNU
8593 # General Public License @dots{}
8594 @dots{}
8595 @dots{}
8596 @end group
8598 SHELL = /bin/sh
8600 #### Start of system configuration section. ####
8602 srcdir = .
8604 @group
8605 # If you use gcc, you should either run the
8606 # fixincludes script that comes with it or else use
8607 # gcc with the -traditional option.  Otherwise ioctl
8608 # calls will be compiled incorrectly on some systems.
8609 CC = gcc -O
8610 YACC = bison -y
8611 INSTALL = /usr/local/bin/install -c
8612 INSTALLDATA = /usr/local/bin/install -c -m 644
8613 @end group
8615 # Things you might add to DEFS:
8616 # -DSTDC_HEADERS        If you have ANSI C headers and
8617 #                       libraries.
8618 # -DPOSIX               If you have POSIX.1 headers and 
8619 #                       libraries.
8620 # -DBSD42               If you have sys/dir.h (unless 
8621 #                       you use -DPOSIX), sys/file.h, 
8622 #                       and st_blocks in `struct stat'.
8623 # -DUSG                 If you have System V/ANSI C 
8624 #                       string and memory functions 
8625 #                       and headers, sys/sysmacros.h, 
8626 #                       fcntl.h, getcwd, no valloc, 
8627 #                       and ndir.h (unless 
8628 #                       you use -DDIRENT).
8629 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not 
8630 #                       include memory.h.
8631 # -DDIRENT              If USG and you have dirent.h 
8632 #                       instead of ndir.h.
8633 # -DSIGTYPE=int         If your signal handlers 
8634 #                       return int, not void.
8635 # -DNO_MTIO             If you lack sys/mtio.h 
8636 #                       (magtape ioctls).
8637 # -DNO_REMOTE           If you do not have a remote shell 
8638 #                       or rexec.
8639 # -DUSE_REXEC           To use rexec for remote tape
8640 #                       operations instead of 
8641 #                       forking rsh or remsh.
8642 # -DVPRINTF_MISSING     If you lack vprintf function 
8643 #                       (but have _doprnt).
8644 # -DDOPRNT_MISSING      If you lack _doprnt function.  
8645 #                       Also need to define 
8646 #                       -DVPRINTF_MISSING.
8647 # -DFTIME_MISSING       If you lack ftime system call.
8648 # -DSTRSTR_MISSING      If you lack strstr function.
8649 # -DVALLOC_MISSING      If you lack valloc function.
8650 # -DMKDIR_MISSING       If you lack mkdir and 
8651 #                       rmdir system calls.
8652 # -DRENAME_MISSING      If you lack rename system call.
8653 # -DFTRUNCATE_MISSING   If you lack ftruncate 
8654 #                       system call.
8655 # -DV7                  On Version 7 Unix (not 
8656 #                       tested in a long time).
8657 # -DEMUL_OPEN3          If you lack a 3-argument version 
8658 #                       of open, and want to emulate it 
8659 #                       with system calls you do have.
8660 # -DNO_OPEN3            If you lack the 3-argument open
8661 #                       and want to disable the tar -k 
8662 #                       option instead of emulating open.
8663 # -DXENIX               If you have sys/inode.h 
8664 #                       and need it 94 to be included.
8666 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
8667         -DVPRINTF_MISSING -DBSD42
8668 # Set this to rtapelib.o unless you defined NO_REMOTE, 
8669 # in which case make it empty.
8670 RTAPELIB = rtapelib.o
8671 LIBS = 
8672 DEF_AR_FILE = /dev/rmt8
8673 DEFBLOCKING = 20
8675 @group
8676 CDEBUG = -g
8677 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
8678         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
8679         -DDEFBLOCKING=$(DEFBLOCKING)
8680 LDFLAGS = -g
8681 @end group
8683 @group
8684 prefix = /usr/local
8685 # Prefix for each installed program, 
8686 # normally empty or `g'.
8687 binprefix = 
8689 # The directory to install tar in.
8690 bindir = $(prefix)/bin
8692 # The directory to install the info files in.
8693 infodir = $(prefix)/info
8694 @end group
8696 #### End of system configuration section. ####
8698 SRC1 =  tar.c create.c extract.c buffer.c \
8699         getoldopt.c update.c gnu.c mangle.c
8700 SRC2 =  version.c list.c names.c diffarch.c \
8701         port.c wildmat.c getopt.c
8702 SRC3 =  getopt1.c regex.c getdate.y
8703 SRCS =  $(SRC1) $(SRC2) $(SRC3)
8704 OBJ1 =  tar.o create.o extract.o buffer.o \
8705         getoldopt.o update.o gnu.o mangle.o
8706 OBJ2 =  version.o list.o names.o diffarch.o \
8707         port.o wildmat.o getopt.o
8708 OBJ3 =  getopt1.o regex.o getdate.o $(RTAPELIB)
8709 OBJS =  $(OBJ1) $(OBJ2) $(OBJ3)
8710 @group
8711 AUX =   README COPYING ChangeLog Makefile.in  \
8712         makefile.pc configure configure.in \
8713         tar.texinfo tar.info* texinfo.tex \
8714         tar.h port.h open3.h getopt.h regex.h \
8715         rmt.h rmt.c rtapelib.c alloca.c \
8716         msd_dir.h msd_dir.c tcexparg.c \
8717         level-0 level-1 backup-specs testpad.c
8718 @end group
8720 all:    tar rmt tar.info
8722 @group
8723 tar:    $(OBJS)
8724         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
8725 @end group
8727 @group
8728 rmt:    rmt.c
8729         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
8730 @end group
8732 @group
8733 tar.info: tar.texinfo
8734         makeinfo tar.texinfo
8735 @end group
8737 @group
8738 install: all
8739         $(INSTALL) tar $(bindir)/$(binprefix)tar
8740         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
8741         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
8742 @end group
8744 @group
8745 $(OBJS): tar.h port.h testpad.h
8746 regex.o buffer.o tar.o: regex.h
8747 # getdate.y has 8 shift/reduce conflicts.
8748 @end group
8750 @group
8751 testpad.h: testpad
8752         ./testpad
8753 @end group
8755 @group
8756 testpad: testpad.o
8757         $(CC) -o $@@ testpad.o
8758 @end group
8760 @group
8761 TAGS:   $(SRCS)
8762         etags $(SRCS)
8763 @end group
8765 @group
8766 clean:
8767         rm -f *.o tar rmt testpad testpad.h core
8768 @end group
8770 @group
8771 distclean: clean
8772         rm -f TAGS Makefile config.status
8773 @end group
8775 @group
8776 realclean: distclean
8777         rm -f tar.info*
8778 @end group
8780 @group
8781 shar: $(SRCS) $(AUX)
8782         shar $(SRCS) $(AUX) | compress \
8783           > tar-`sed -e '/version_string/!d' \
8784                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
8785                      -e q 
8786                      version.c`.shar.Z
8787 @end group
8789 @group
8790 dist: $(SRCS) $(AUX)
8791         echo tar-`sed \
8792              -e '/version_string/!d' \
8793              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
8794              -e q 
8795              version.c` > .fname
8796         -rm -rf `cat .fname`
8797         mkdir `cat .fname`
8798         ln $(SRCS) $(AUX) `cat .fname`
8799         -rm -rf `cat .fname` .fname
8800         tar chZf `cat .fname`.tar.Z `cat .fname`
8801 @end group
8803 @group
8804 tar.zoo: $(SRCS) $(AUX)
8805         -rm -rf tmp.dir
8806         -mkdir tmp.dir
8807         -rm tar.zoo
8808         for X in $(SRCS) $(AUX) ; do \
8809             echo $$X ; \
8810             sed 's/$$/^M/' $$X \
8811             > tmp.dir/$$X ; done
8812         cd tmp.dir ; zoo aM ../tar.zoo *
8813         -rm -rf tmp.dir
8814 @end group
8815 @end example
8817 @node Concept Index, Name Index, Complex Makefile, Top
8818 @unnumbered Index of Concepts
8820 @printindex cp
8822 @node Name Index,  , Concept Index, Top
8823 @unnumbered Index of Functions, Variables, & Directives
8825 @printindex fn
8827 @summarycontents
8828 @contents
8829 @bye