Updated from libc
[make.git] / make.texinfo
blob89ce52fdf93232395727a3535e2079a58abadfae
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.152 1995/04/05 03:32:21 roland Exp $
11 @set EDITION 0.48
12 @set VERSION 3.73 Beta
13 @set UPDATED 4 April 1995
14 @set UPDATE-MONTH April 1995
15 @comment The ISBN number might need to change on next publication.
16 @set ISBN 1-882114-50-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 675 Massachusetts Avenue, @*
75 Cambridge, MA 02139 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 Non-bug suggestions are always welcome as well.  If you have questions
440 about things that are unclear in the documentation or are just obscure
441 features, send a message to the bug reporting address.  We cannot
442 guarantee you'll get help with your problem, but many seasoned
443 @code{make} users read the mailing list and they will probably try to
444 help you out.  The maintainers sometimes answer such questions as well,
445 when time permits.
447 @node Introduction, Makefiles, Overview, Top
448 @comment  node-name,  next,  previous,  up
449 @chapter An Introduction to Makefiles
451 You need a file called a @dfn{makefile} to tell @code{make} what to do.
452 Most often, the makefile tells @code{make} how to compile and link a
453 program.
454 @cindex makefile
456 In this chapter, we will discuss a simple makefile that describes how to
457 compile and link a text editor which consists of eight C source files
458 and three header files.  The makefile can also tell @code{make} how to
459 run miscellaneous commands when explicitly asked (for example, to remove
460 certain files as a clean-up operation).  To see a more complex example
461 of a makefile, see @ref{Complex Makefile}.
463 When @code{make} recompiles the editor, each changed C source file
464 must be recompiled.  If a header file has changed, each C source file
465 that includes the header file must be recompiled to be safe.  Each
466 compilation produces an object file corresponding to the source file.
467 Finally, if any source file has been recompiled, all the object files,
468 whether newly made or saved from previous compilations, must be linked
469 together to produce the new executable editor.
470 @cindex recompilation
471 @cindex editor
473 @menu
474 * Rule Introduction::           What a rule looks like.
475 * Simple Makefile::             A Simple Makefile
476 * How Make Works::              How @code{make} Processes This Makefile
477 * Variables Simplify::          Variables Make Makefiles Simpler
478 * make Deduces::                Letting @code{make} Deduce the Commands
479 * Combine By Dependency::       Another Style of Makefile
480 * Cleanup::                     Rules for Cleaning the Directory
481 @end menu
483 @node Rule Introduction, Simple Makefile,  , Introduction
484 @comment  node-name,  next,  previous,  up
485 @section What a Rule Looks Like
486 @cindex rule, introduction to
487 @cindex makefile rule parts
488 @cindex parts of makefile rule
490 A simple makefile consists of ``rules'' with the following shape:
492 @cindex targets, introduction to
493 @cindex dependencies, introduction to
494 @cindex commands, introduction to
495 @example
496 @group
497 @var{target} @dots{} : @var{dependencies} @dots{}
498         @var{command}
499         @dots{}
500         @dots{}
501 @end group
502 @end example
504 A @dfn{target} is usually the name of a file that is generated by a
505 program; examples of targets are executable or object files.  A target
506 can also be the name of an action to carry out, such as @samp{clean}
507 (@pxref{Phony Targets}).
509 A @dfn{dependency} is a file that is used as input to create the
510 target.  A target often depends on several files.  
512 @cindex tabs in rules
513 A @dfn{command} is an action that @code{make} carries out.
514 A rule may have more than one command, each on its own line.
515 @strong{Please note:} you need to put a tab character at the beginning of
516 every command line!  This is an obscurity that catches the unwary.
518 Usually a command is in a rule with dependencies and serves to create a
519 target file if any of the dependencies change.  However, the rule that
520 specifies commands for the target need not have dependencies.  For
521 example, the rule containing the delete command associated with the
522 target @samp{clean} does not have dependencies.
524 A @dfn{rule}, then, explains how and when to remake certain files
525 which are the targets of the particular rule.  @code{make} carries out
526 the commands on the dependencies to create or update the target.  A
527 rule can also explain how and when to carry out an action.
528 @xref{Rules, , Writing Rules}.
530 A makefile may contain other text besides rules, but a simple makefile
531 need only contain rules.  Rules may look somewhat more complicated
532 than shown in this template, but all fit the pattern more or less.
534 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
535 @section A Simple Makefile
536 @cindex simple makefile
537 @cindex makefile, simple
539 Here is a straightforward makefile that describes the way an
540 executable file called @code{edit} depends on eight object files
541 which, in turn, depend on eight C source and three header files.
543 In this example, all the C files include @file{defs.h}, but only those
544 defining editing commands include @file{command.h}, and only low
545 level files that change the editor buffer include @file{buffer.h}.
547 @example
548 @group
549 edit : main.o kbd.o command.o display.o \
550        insert.o search.o files.o utils.o
551         cc -o edit main.o kbd.o command.o display.o \
552                    insert.o search.o files.o utils.o
554 main.o : main.c defs.h
555         cc -c main.c
556 kbd.o : kbd.c defs.h command.h
557         cc -c kbd.c
558 command.o : command.c defs.h command.h
559         cc -c command.c
560 display.o : display.c defs.h buffer.h
561         cc -c display.c
562 insert.o : insert.c defs.h buffer.h
563         cc -c insert.c
564 search.o : search.c defs.h buffer.h
565         cc -c search.c
566 files.o : files.c defs.h buffer.h command.h
567         cc -c files.c
568 utils.o : utils.c defs.h
569         cc -c utils.c
570 clean :
571         rm edit main.o kbd.o command.o display.o \
572            insert.o search.o files.o utils.o
573 @end group
574 @end example
576 @noindent
577 We split each long line into two lines using backslash-newline; this is
578 like using one long line, but is easier to read.
579 @cindex continuation lines
580 @cindex @code{\} (backslash), for continuation lines
581 @cindex backslash (@code{\}), for continuation lines
582 @cindex quoting newline, in makefile
583 @cindex newline, quoting, in makefile
585 To use this makefile to create the executable file called @file{edit},
586 type:
588 @example
589 make
590 @end example
592 To use this makefile to delete the executable file and all the object
593 files from the directory, type:
595 @example
596 make clean
597 @end example
599 In the example makefile, the targets include the executable file
600 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
601 dependencies are files such as @samp{main.c} and @samp{defs.h}.
602 In fact, each @samp{.o} file is both a target and a dependency.
603 Commands include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
605 When a target is a file, it needs to be recompiled or relinked if any
606 of its dependencies change.  In addition, any dependencies that are
607 themselves automatically generated should be updated first.  In this
608 example, @file{edit} depends on each of the eight object files; the
609 object file @file{main.o} depends on the source file @file{main.c} and
610 on the header file @file{defs.h}.  
612 A shell command follows each line that contains a target and
613 dependencies.  These shell commands say how to update the target file.
614 A tab character must come at the beginning of every command line to
615 distinguish commands lines from other lines in the makefile.  (Bear in
616 mind that @code{make} does not know anything about how the commands
617 work.  It is up to you to supply commands that will update the target
618 file properly.  All @code{make} does is execute the commands in the rule
619 you have specified when the target file needs to be updated.)
620 @cindex shell command
622 The target @samp{clean} is not a file, but merely the name of an
623 action.  Since you 
624 normally
625 do not want to carry out the actions in this rule, @samp{clean} is not a dependency of any other rule.
626 Consequently, @code{make} never does anything with it unless you tell
627 it specifically.  Note that this rule not only is not a dependency, it
628 also does not have any dependencies, so the only purpose of the rule
629 is to run the specified commands.  Targets that do not refer to files
630 but are just actions are called @dfn{phony targets}.  @xref{Phony
631 Targets}, for information about this kind of target.  @xref{Errors, ,
632 Errors in Commands}, to see how to cause @code{make} to ignore errors
633 from @code{rm} or any other command.
634 @cindex @code{clean} target
635 @cindex @code{rm} (shell command)
637 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
638 @comment  node-name,  next,  previous,  up
639 @section How @code{make} Processes a Makefile
640 @cindex processing a makefile
641 @cindex makefile, how @code{make} processes
643 By default, @code{make} starts with the first rule (not counting rules
644 whose target names start with @samp{.}).  This is called the
645 @dfn{default goal}.  (@dfn{Goals} are the targets that @code{make}
646 strives ultimately to update.  @xref{Goals, , Arguments to Specify the
647 Goals}.)
648 @cindex default goal
649 @cindex goal, default
650 @cindex goal
652 In the simple example of the previous section, the default goal is to
653 update the executable program @file{edit}; therefore, we put that rule
654 first.
656 Thus, when you give the command:
658 @example
659 make
660 @end example
662 @noindent
663 @code{make} reads the makefile in the current directory and begins by
664 processing the first rule.  In the example, this rule is for relinking
665 @file{edit}; but before @code{make} can fully process this rule, it
666 must process the rules for the files that @file{edit} depends on,
667 which in this case are the object files.  Each of these files is
668 processed according to its own rule.  These rules say to update each
669 @samp{.o} file by compiling its source file.  The recompilation must
670 be done if the source file, or any of the header files named as
671 dependencies, is more recent than the object file, or if the object
672 file does not exist.
674 The other rules are processed because their targets appear as
675 dependencies of the goal.  If some other rule is not depended on by the
676 goal (or anything it depends on, etc.), that rule is not processed,
677 unless you tell @code{make} to do so (with a command such as
678 @w{@code{make clean}}).
680 Before recompiling an object file, @code{make} considers updating its
681 dependencies, the source file and header files.  This makefile does not
682 specify anything to be done for them---the @samp{.c} and @samp{.h} files
683 are not the targets of any rules---so @code{make} does nothing for these
684 files.  But @code{make} would update automatically generated C programs,
685 such as those made by Bison or Yacc, by their own rules at this time.
687 After recompiling whichever object files need it, @code{make} decides
688 whether to relink @file{edit}.  This must be done if the file
689 @file{edit} does not exist, or if any of the object files are newer than
690 it.  If an object file was just recompiled, it is now newer than
691 @file{edit}, so @file{edit} is relinked.
692 @cindex relinking
694 Thus, if we change the file @file{insert.c} and run @code{make},
695 @code{make} will compile that file to update @file{insert.o}, and then
696 link @file{edit}.  If we change the file @file{command.h} and run
697 @code{make}, @code{make} will recompile the object files @file{kbd.o},
698 @file{command.o} and @file{files.o} and then link the file @file{edit}.
700 @node Variables Simplify, make Deduces, How Make Works, Introduction
701 @section Variables Make Makefiles Simpler
702 @cindex variables
703 @cindex simplifying with variables
705 In our example, we had to list all the object files twice in the rule for
706 @file{edit} (repeated here):
708 @example
709 @group
710 edit : main.o kbd.o command.o display.o \
711               insert.o search.o files.o utils.o
712         cc -o edit main.o kbd.o command.o display.o \
713                    insert.o search.o files.o utils.o
714 @end group
715 @end example
717 @cindex @code{objects}
718 Such duplication is error-prone; if a new object file is added to the
719 system, we might add it to one list and forget the other.  We can eliminate
720 the risk and simplify the makefile by using a variable.  @dfn{Variables}
721 allow a text string to be defined once and substituted in multiple places
722 later (@pxref{Using Variables, ,How to Use Variables}).
724 @cindex @code{OBJECTS}
725 @cindex @code{objs}
726 @cindex @code{OBJS}
727 @cindex @code{obj}
728 @cindex @code{OBJ}
729 It is standard practice for every makefile to have a variable named
730 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
731 or @code{OBJ} which is a list of all object file names.  We would
732 define such a variable @code{objects} with a line like this in the
733 makefile:@refill
735 @example
736 @group
737 objects = main.o kbd.o command.o display.o \
738           insert.o search.o files.o utils.o
739 @end group
740 @end example
742 @noindent
743 Then, each place we want to put a list of the object file names, we can
744 substitute the variable's value by writing @samp{$(objects)}
745 (@pxref{Using Variables, ,How to Use Variables}).  
747 Here is how the complete simple makefile looks when you use a variable
748 for the object files:
750 @example
751 @group
752 objects = main.o kbd.o command.o display.o \
753           insert.o search.o files.o utils.o
755 edit : $(objects)
756         cc -o edit $(objects)
757 main.o : main.c defs.h
758         cc -c main.c
759 kbd.o : kbd.c defs.h command.h
760         cc -c kbd.c
761 command.o : command.c defs.h command.h
762         cc -c command.c
763 display.o : display.c defs.h buffer.h
764         cc -c display.c
765 insert.o : insert.c defs.h buffer.h
766         cc -c insert.c
767 search.o : search.c defs.h buffer.h
768         cc -c search.c
769 files.o : files.c defs.h buffer.h command.h
770         cc -c files.c
771 utils.o : utils.c defs.h
772         cc -c utils.c
773 clean :
774         rm edit $(objects)
775 @end group
776 @end example
778 @node make Deduces, Combine By Dependency, Variables Simplify, Introduction
779 @section Letting @code{make} Deduce the Commands
780 @cindex deducing commands (implicit rules)
781 @cindex implicit rule, introduction to
782 @cindex rule, implicit, introduction to
784 It is not necessary to spell out the commands for compiling the individual
785 C source files, because @code{make} can figure them out: it has an
786 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
787 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
788 use the command @samp{cc -c main.c -o main.o} to compile @file{main.c} into
789 @file{main.o}.  We can therefore omit the commands from the rules for the
790 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.@refill
792 When a @samp{.c} file is used automatically in this way, it is also
793 automatically added to the list of dependencies.  We can therefore omit
794 the @samp{.c} files from the dependencies, provided we omit the commands.
796 Here is the entire example, with both of these changes, and a variable
797 @code{objects} as suggested above:
799 @example
800 @group
801 objects = main.o kbd.o command.o display.o \
802           insert.o search.o files.o utils.o
804 edit : $(objects)
805         cc -o edit $(objects)
807 main.o : defs.h
808 kbd.o : defs.h command.h
809 command.o : defs.h command.h
810 display.o : defs.h buffer.h
811 insert.o : defs.h buffer.h
812 search.o : defs.h buffer.h
813 files.o : defs.h buffer.h command.h
814 utils.o : defs.h
816 .PHONY : clean
817 clean :
818         -rm edit $(objects)
819 @end group
820 @end example
822 @noindent
823 This is how we would write the makefile in actual practice.  (The
824 complications associated with @samp{clean} are described elsewhere.
825 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Commands}.)
827 Because implicit rules are so convenient, they are important.  You
828 will see them used frequently.@refill
830 @node Combine By Dependency, Cleanup, make Deduces, Introduction
831 @section Another Style of Makefile
832 @cindex combining rules by dependency
834 When the objects of a makefile are created only by implicit rules, an
835 alternative style of makefile is possible.  In this style of makefile,
836 you group entries by their dependencies instead of by their targets.
837 Here is what one looks like:
839 @example
840 @group
841 objects = main.o kbd.o command.o display.o \
842           insert.o search.o files.o utils.o
844 edit : $(objects)
845         cc -o edit $(objects)
847 $(objects) : defs.h
848 kbd.o command.o files.o : command.h
849 display.o insert.o search.o files.o : buffer.h
850 @end group
851 @end example
853 @noindent
854 Here @file{defs.h} is given as a dependency of all the object files;
855 @file{command.h} and @file{buffer.h} are dependencies of the specific
856 object files listed for them.
858 Whether this is better is a matter of taste: it is more compact, but some
859 people dislike it because they find it clearer to put all the information
860 about each target in one place.
862 @node Cleanup,  , Combine By Dependency, Introduction
863 @section Rules for Cleaning the Directory
864 @cindex cleaning up
865 @cindex removing, to clean up
867 Compiling a program is not the only thing you might want to write rules
868 for.  Makefiles commonly tell how to do a few other things besides
869 compiling a program: for example, how to delete all the object files
870 and executables so that the directory is @samp{clean}.
872 @cindex @code{clean} target
873 Here is how we
874 could write a @code{make} rule for cleaning our example editor:
876 @example
877 @group
878 clean:
879         rm edit $(objects)
880 @end group
881 @end example
883 In practice, we might want to write the rule in a somewhat more
884 complicated manner to handle unanticipated situations.  We would do this:
886 @example
887 @group
888 .PHONY : clean
889 clean :
890         -rm edit $(objects)
891 @end group
892 @end example
894 @noindent
895 This prevents @code{make} from getting confused by an actual file
896 called @file{clean} and causes it to continue in spite of errors from
897 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
898 Commands}.)
900 @noindent
901 A rule such as this should not be placed at the beginning of the
902 makefile, because we do not want it to run by default!  Thus, in the
903 example makefile, we want the rule for @code{edit}, which recompiles
904 the editor, to remain the default goal.
906 Since @code{clean} is not a dependency of @code{edit}, this rule will not
907 run at all if we give the command @samp{make} with no arguments.  In
908 order to make the rule run, we have to type @samp{make clean}.
909 @xref{Running, ,How to Run @code{make}}.
911 @node Makefiles, Rules, Introduction, Top
912 @chapter Writing Makefiles
914 @cindex makefile, how to write
915 The information that tells @code{make} how to recompile a system comes from
916 reading a data base called the @dfn{makefile}.
918 @menu
919 * Makefile Contents::           What makefiles contain.
920 * Makefile Names::              How to name your makefile.
921 * Include::                     How one makefile can use another makefile.
922 * MAKEFILES Variable::          The environment can specify extra makefiles.
923 * Remaking Makefiles::          How makefiles get remade.
924 * Overriding Makefiles::        How to override part of one makefile
925                                  with another makefile.
926 @end menu
928 @node Makefile Contents, Makefile Names,  , Makefiles
929 @section What Makefiles Contain
931 Makefiles contain five kinds of things: @dfn{explicit rules},
932 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
933 and @dfn{comments}.  Rules, variables, and directives are described at
934 length in later chapters.@refill
936 @itemize @bullet
937 @cindex rule, explicit, definition of
938 @cindex explicit rule, definition of
939 @item
940 An @dfn{explicit rule} says when and how to remake one or more files,
941 called the rule's targets.  It lists the other files that the targets
942 @dfn{depend on}, and may also give commands to use to create or update
943 the targets.  @xref{Rules, ,Writing Rules}.
945 @cindex rule, implicit, definition of
946 @cindex implicit rule, definition of
947 @item
948 An @dfn{implicit rule} says when and how to remake a class of files
949 based on their names.  It describes how a target may depend on a file
950 with a name similar to the target and gives commands to create or
951 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
953 @cindex variable definition
954 @item
955 A @dfn{variable definition} is a line that specifies a text string
956 value for a variable that can be substituted into the text later.  The
957 simple makefile example shows a variable definition for @code{objects}
958 as a list of all object files (@pxref{Variables Simplify, , Variables
959 Make Makefiles Simpler}).
961 @cindex directive
962 @item
963 A @dfn{directive} is a command for @code{make} to do something special while
964 reading the makefile.  These include:
966 @itemize @bullet
967 @item
968 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
970 @item
971 Deciding (based on the values of variables) whether to use or
972 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
974 @item
975 Defining a variable from a verbatim string containing multiple lines
976 (@pxref{Defining, ,Defining Variables Verbatim}).
977 @end itemize
979 @cindex comments, in makefile
980 @cindex @code{#} (comments), in makefile
981 @item
982 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the rest of
983 the line are ignored, except that a trailing backslash not escaped by
984 another backslash will continue the comment across multiple lines.
985 Comments may appear on any of the lines in the makefile, except within a
986 @code{define} directive, and perhaps within commands (where the shell
987 decides what is a comment).  A line containing just a comment (with
988 perhaps spaces before it) is effectively blank, and is ignored.@refill
989 @end itemize
991 @node Makefile Names, Include, Makefile Contents, Makefiles
992 @section What Name to Give Your Makefile
993 @cindex makefile name
994 @cindex name of makefile
995 @cindex default makefile name
996 @cindex file name of makefile
998 @c following paragraph rewritten to avoid overfull hbox
999 By default, when @code{make} looks for the makefile, it tries the
1000 following names, in order: @file{GNUmakefile}, @file{makefile}
1001 and @file{Makefile}.@refill
1002 @findex Makefile
1003 @findex GNUmakefile
1004 @findex makefile
1006 @cindex @code{README}
1007 Normally you should call your makefile either @file{makefile} or
1008 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1009 prominently near the beginning of a directory listing, right near other
1010 important files such as @file{README}.)  The first name checked,
1011 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1012 use this name if you have a makefile that is specific to GNU
1013 @code{make}, and will not be understood by other versions of
1014 @code{make}.  Other @code{make} programs look for @file{makefile} and
1015 @file{Makefile}, but not @file{GNUmakefile}.
1017 If @code{make} finds none of these names, it does not use any makefile.
1018 Then you must specify a goal with a command argument, and @code{make}
1019 will attempt to figure out how to remake it using only its built-in
1020 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1022 @cindex @code{-f}
1023 @cindex @code{--file}
1024 @cindex @code{--makefile}
1025 If you want to use a nonstandard name for your makefile, you can specify
1026 the makefile name with the @samp{-f} or @samp{--file} option.  The
1027 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1028 @code{make} to read the file @var{name} as the makefile.  If you use
1029 more than one @samp{-f} or @samp{--file} option, you can specify several
1030 makefiles.  All the makefiles are effectively concatenated in the order
1031 specified.  The default makefile names @file{GNUmakefile},
1032 @file{makefile} and @file{Makefile} are not checked automatically if you
1033 specify @samp{-f} or @samp{--file}.@refill
1034 @cindex specifying makefile name
1035 @cindex makefile name, how to specify
1036 @cindex name of makefile, how to specify
1037 @cindex file name of makefile, how to specify
1039 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1040 @section Including Other Makefiles
1041 @cindex including other makefiles
1042 @cindex makefile, including
1044 @findex include
1045 The @code{include} directive tells @code{make} to suspend reading the
1046 current makefile and read one or more other makefiles before continuing.
1047 The directive is a line in the makefile that looks like this:
1049 @example
1050 include @var{filenames}@dots{}
1051 @end example
1053 @noindent
1054 @var{filenames} can contain shell file name patterns.
1055 @cindex shell file name pattern (in @code{include})
1056 @cindex shell wildcards (in @code{include})
1057 @cindex wildcard, in @code{include}
1059 Extra spaces are allowed and ignored at the beginning of the line, but
1060 a tab is not allowed.  (If the line begins with a tab, it will be
1061 considered a command line.)  Whitespace is required between
1062 @code{include} and the file names, and between file names; extra
1063 whitespace is ignored there and at the end of the directive.  A
1064 comment starting with @samp{#} is allowed at the end of the line.  If
1065 the file names contain any variable or function references, they are
1066 expanded.  @xref{Using Variables, ,How to Use Variables}.
1068 For example, if you have three @file{.mk} files, @file{a.mk}, 
1069 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1070 @code{bish bash}, then the following expression
1072 @example
1073 include foo *.mk $(bar)
1074 @end example
1076 is equivalent to
1078 @example
1079 include foo a.mk b.mk c.mk bish bash
1080 @end example
1082 When @code{make} processes an @code{include} directive, it suspends
1083 reading of the containing makefile and reads from each listed file in
1084 turn.  When that is finished, @code{make} resumes reading the
1085 makefile in which the directive appears.
1087 One occasion for using @code{include} directives is when several programs,
1088 handled by individual makefiles in various directories, need to use a
1089 common set of variable definitions 
1090 (@pxref{Setting, ,Setting Variables}) or pattern rules
1091 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1093 Another such occasion is when you want to generate dependencies from
1094 source files automatically; the dependencies can be put in a file that
1095 is included by the main makefile.  This practice is generally cleaner
1096 than that of somehow appending the dependencies to the end of the main
1097 makefile as has been traditionally done with other versions of
1098 @code{make}.  @xref{Automatic Dependencies}.
1099 @cindex dependencies, automatic generation
1100 @cindex automatic generation of dependencies
1101 @cindex generating dependencies automatically
1103 @cindex @code{-I}
1104 @cindex @code{--include-dir}
1105 @findex /usr/gnu/include
1106 @findex /usr/local/include
1107 @findex /usr/include
1108 If the specified name does not start with a slash, and the file is not
1109 found in the current directory, several other directories are searched.
1110 First, any directories you have specified with the @samp{-I} or
1111 @samp{--include-dir} option are searched
1112 (@pxref{Options Summary, ,Summary of Options}).
1113 Then the following directories (if they exist)
1114 are searched, in this order: 
1115 @file{@var{prefix}/include} (normally @file{/usr/local/include})
1116 @file{/usr/gnu/include},
1117 @file{/usr/local/include}, @file{/usr/include}.  
1119 If an included makefile cannot be found in any of these directories, a
1120 warning message is generated, but it is not an immediately fatal error;
1121 processing of the makefile containing the @code{include} continues.
1122 Once it has finished reading makefiles, @code{make} will try to remake
1123 any that are out of date or don't exist.
1124 @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
1125 Only after it has tried to find a way to remake a makefile and failed,
1126 will @code{make} diagnose the missing makefile as a fatal error.
1128 If you want @code{make} to simply ignore a makefile which does not exist
1129 and cannot be remade, with no error message, use the @w{@code{-include}}
1130 directive instead of @code{include}, like this:
1132 @example
1133 -include @var{filenames}@dots{}
1134 @end example
1136 This is acts like @code{include} in every way except that there is no
1137 error (not even a warning) if any of the @var{filenames} do not exist.
1139 @node MAKEFILES Variable, Remaking Makefiles, Include, Makefiles
1140 @section The Variable @code{MAKEFILES}
1141 @cindex makefile, and @code{MAKEFILES} variable
1142 @cindex including (@code{MAKEFILES} variable)
1144 @vindex MAKEFILES
1145 If the environment variable @code{MAKEFILES} is defined, @code{make}
1146 considers its value as a list of names (separated by whitespace) of
1147 additional makefiles to be read before the others.  This works much like
1148 the @code{include} directive: various directories are searched for those
1149 files (@pxref{Include, ,Including Other Makefiles}).  In addition, the
1150 default goal is never taken from one of these makefiles and it is not an
1151 error if the files listed in @code{MAKEFILES} are not found.@refill
1153 @cindex recursion, and @code{MAKEFILES} variable
1154 The main use of @code{MAKEFILES} is in communication between recursive
1155 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1156 @code{make}}).  It usually is not desirable to set the environment
1157 variable before a top-level invocation of @code{make}, because it is
1158 usually better not to mess with a makefile from outside.  However, if
1159 you are running @code{make} without a specific makefile, a makefile in
1160 @code{MAKEFILES} can do useful things to help the built-in implicit
1161 rules work better, such as defining search paths (@pxref{Directory Search}).
1163 Some users are tempted to set @code{MAKEFILES} in the environment
1164 automatically on login, and program makefiles to expect this to be done.
1165 This is a very bad idea, because such makefiles will fail to work if run by
1166 anyone else.  It is much better to write explicit @code{include} directives
1167 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1169 @node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
1170 @section How Makefiles Are Remade
1172 @cindex updating makefiles
1173 @cindex remaking makefiles
1174 @cindex makefile, remaking of
1175 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1176 files.  If a makefile can be remade from other files, you probably want
1177 @code{make} to get an up-to-date version of the makefile to read in.
1179 To this end, after reading in all makefiles, @code{make} will consider
1180 each as a goal target and attempt to update it.  If a makefile has a
1181 rule which says how to update it (found either in that very makefile or
1182 in another one) or if an implicit rule applies to it (@pxref{Implicit
1183 Rules, ,Using Implicit Rules}), it will be updated if necessary.  After
1184 all makefiles have been checked, if any have actually been changed,
1185 @code{make} starts with a clean slate and reads all the makefiles over
1186 again.  (It will also attempt to update each of them over again, but
1187 normally this will not change them again, since they are already up to
1188 date.)@refill
1190 If the makefiles specify a double-colon rule to remake a file with
1191 commands but no dependencies, that file will always be remade
1192 (@pxref{Double-Colon}).  In the case of makefiles, a makefile that has a
1193 double-colon rule with commands but no dependencies will be remade every
1194 time @code{make} is run, and then again after @code{make} starts over
1195 and reads the makefiles in again.  This would cause an infinite loop:
1196 @code{make} would constantly remake the makefile, and never do anything
1197 else.  So, to avoid this, @code{make} will @strong{not} attempt to
1198 remake makefiles which are specified as double-colon targets but have no
1199 dependencies.@refill
1201 If you do not specify any makefiles to be read with @samp{-f} or
1202 @samp{--file} options, @code{make} will try the default makefile names;
1203 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1204 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1205 @code{make} is not certain that these makefiles should exist.  However,
1206 if a default makefile does not exist but can be created by running
1207 @code{make} rules, you probably want the rules to be run so that the
1208 makefile can be used.
1210 Therefore, if none of the default makefiles exists, @code{make} will try
1211 to make each of them in the same order in which they are searched for
1212 (@pxref{Makefile Names, ,What Name to Give Your Makefile})
1213 until it succeeds in making one, or it runs out of names to try.  Note
1214 that it is not an error if @code{make} cannot find or make any makefile;
1215 a makefile is not always necessary.@refill
1217 When you use the @samp{-t} or @samp{--touch} option
1218 (@pxref{Instead of Execution, ,Instead of Executing the Commands}),
1219 you would not want to use an out-of-date makefile to decide which
1220 targets to touch.  So the @samp{-t} option has no effect on updating
1221 makefiles; they are really updated even if @samp{-t} is specified.
1222 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1223 @samp{--just-print}) do not prevent updating of makefiles, because an
1224 out-of-date makefile would result in the wrong output for other targets.
1225 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1226 and then print the commands to update @file{foo} and its dependencies
1227 without running them.  The commands printed for @file{foo} will be those
1228 specified in the updated contents of @file{mfile}.
1230 However, on occasion you might actually wish to prevent updating of even
1231 the makefiles.  You can do this by specifying the makefiles as goals in
1232 the command line as well as specifying them as makefiles.  When the
1233 makefile name is specified explicitly as a goal, the options @samp{-t}
1234 and so on do apply to them.
1236 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1237 @file{mfile}, print the commands needed to update it without actually
1238 running them, and then print the commands needed to update @file{foo}
1239 without running them.  The commands for @file{foo} will be those
1240 specified by the existing contents of @file{mfile}.
1242 @node Overriding Makefiles,  , Remaking Makefiles, Makefiles
1243 @section Overriding Part of Another Makefile
1245 @cindex overriding makefiles
1246 @cindex makefile, overriding
1247 Sometimes it is useful to have a makefile that is mostly just like
1248 another makefile.  You can often use the @samp{include} directive to
1249 include one in the other, and add more targets or variable definitions.
1250 However, if the two makefiles give different commands for the same
1251 target, @code{make} will not let you just do this.  But there is another way.
1253 @cindex match-anything rule, used to override
1254 In the containing makefile (the one that wants to include the other),
1255 you can use a match-anything pattern rule to say that to remake any
1256 target that cannot be made from the information in the containing
1257 makefile, @code{make} should look in another makefile.
1258 @xref{Pattern Rules}, for more information on pattern rules.
1260 For example, if you have a makefile called @file{Makefile} that says how
1261 to make the target @samp{foo} (and other targets), you can write a
1262 makefile called @file{GNUmakefile} that contains:
1264 @example
1265 foo:
1266         frobnicate > foo
1268 %: force
1269         @@$(MAKE) -f Makefile $@@
1270 force: ;
1271 @end example
1273 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1274 read it, and see that to make @file{foo}, it needs to run the command
1275 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1276 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1277 commands from the pattern rule: @samp{make -f Makefile bar}.  If
1278 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1279 will apply the rule.  And likewise for any other target that
1280 @file{GNUmakefile} does not say how to make.
1282 The way this works is that the pattern rule has a pattern of just
1283 @samp{%}, so it matches any target whatever.  The rule specifies a
1284 dependency @file{force}, to guarantee that the commands will be run even
1285 if the target file already exists.  We give @file{force} target empty
1286 commands to prevent @code{make} from searching for an implicit rule to
1287 build it---otherwise it would apply the same match-anything rule to
1288 @file{force} itself and create a dependency loop!
1290 @node Rules, Commands, Makefiles, Top
1291 @chapter Writing Rules
1292 @cindex writing rules
1293 @cindex rule, how to write
1294 @cindex target
1295 @cindex dependency
1297 A @dfn{rule} appears in the makefile and says when and how to remake
1298 certain files, called the rule's @dfn{targets} (most often only one per rule).
1299 It lists the other files that are the @dfn{dependencies} of the target, and
1300 @dfn{commands} to use to create or update the target.
1302 @cindex default goal
1303 @cindex goal, default
1304 The order of rules is not significant, except for determining the
1305 @dfn{default goal}: the target for @code{make} to consider, if you do
1306 not otherwise specify one.  The default goal is the target of the first
1307 rule in the first makefile.  If the first rule has multiple targets,
1308 only the first target is taken as the default.  There are two
1309 exceptions: a target starting with a period is not a default unless it
1310 contains one or more slashes, @samp{/}, as well; and, a target that
1311 defines a pattern rule has no effect on the default goal.
1312 (@xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.)
1314 Therefore, we usually write the makefile so that the first rule is the
1315 one for compiling the entire program or all the programs described by
1316 the makefile (often with a target called @samp{all}).
1317 @xref{Goals, ,Arguments to Specify the Goals}.
1319 @menu
1320 * Rule Example::                An example explained.
1321 * Rule Syntax::                 General syntax explained.
1322 * Wildcards::                   Using wildcard characters such as `*'.
1323 * Directory Search::            Searching other directories for source files.
1324 * Phony Targets::               Using a target that is not a real file's name.
1325 * Force Targets::               You can use a target without commands
1326                                   or dependencies to mark other 
1327                                   targets as phony.
1328 * Empty Targets::               When only the date matters and the
1329                                   files are empty.
1330 * Special Targets::             Targets with special built-in meanings.
1331 * Multiple Targets::            When to make use of several targets in a rule.
1332 * Multiple Rules::              How to use several rules with the same target.
1333 * Static Pattern::              Static pattern rules apply to multiple targets
1334                                   and can vary the dependencies according to 
1335                                   the target name.
1336 * Double-Colon::                How to use a special kind of rule to allow
1337                                   several independent rules for one target.
1338 * Automatic Dependencies::      How to automatically generate rules giving
1339                                  dependencies from the source files themselves.
1340 @end menu
1342 @ifinfo
1343 @node Rule Example, Rule Syntax,  , Rules
1344 @section Rule Example
1346 Here is an example of a rule:
1348 @example
1349 foo.o : foo.c defs.h       # module for twiddling the frobs
1350         cc -c -g foo.c
1351 @end example
1353 Its target is @file{foo.o} and its dependencies are @file{foo.c} and
1354 @file{defs.h}.  It has one command, which is @samp{cc -c -g foo.c}.
1355 The command line starts with a tab to identify it as a command.
1357 This rule says two things:
1359 @itemize @bullet
1360 @item
1361 How to decide whether @file{foo.o} is out of date: it is out of date
1362 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1363 more recent than it.
1365 @item
1366 How to update the file @file{foo.o}: by running @code{cc} as stated.
1367 The command does not explicitly mention @file{defs.h}, but we presume
1368 that @file{foo.c} includes it, and that that is why @file{defs.h} was
1369 added to the dependencies.
1370 @end itemize
1371 @end ifinfo
1373 @node Rule Syntax, Wildcards, Rule Example, Rules
1374 @section Rule Syntax
1376 @cindex rule syntax
1377 @cindex syntax of rules
1378 In general, a rule looks like this:
1380 @example
1381 @var{targets} : @var{dependencies}
1382         @var{command}
1383         @dots{}
1384 @end example
1386 @noindent
1387 or like this:
1389 @example
1390 @var{targets} : @var{dependencies} ; @var{command}
1391         @var{command}
1392         @dots{}
1393 @end example
1395 @cindex targets
1396 @cindex rule targets
1397 The @var{targets} are file names, separated by spaces.  Wildcard
1398 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
1399 in File Names}) and a name of the form @file{@var{a}(@var{m})}
1400 represents member @var{m} in archive file @var{a} 
1401 (@pxref{Archive Members, ,Archive Members as Targets}).  
1402 Usually there is only one
1403 target per rule, but occasionally there is a reason to have more
1404 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).@refill
1406 @cindex commands
1407 @cindex tab character (in commands)
1408 The @var{command} lines start with a tab character.  The first command may
1409 appear on the line after the dependencies, with a tab character, or may
1410 appear on the same line, with a semicolon.  Either way, the effect is the
1411 same.  @xref{Commands, ,Writing the Commands in Rules}.
1413 @cindex dollar sign (@code{$}), in rules
1414 @cindex @code{$}, in rules
1415 @cindex rule, and @code{$}
1416 Because dollar signs are used to start variable references, if you really
1417 want a dollar sign in a rule you must write two of them, @samp{$$}
1418 (@pxref{Using Variables, ,How to Use Variables}).  
1419 You may split a long line by inserting a backslash
1420 followed by a newline, but this is not required, as @code{make} places no
1421 limit on the length of a line in a makefile.
1423 A rule tells @code{make} two things: when the targets are out of date,
1424 and how to update them when necessary.
1426 @cindex dependencies
1427 @cindex rule dependencies
1428 The criterion for being out of date is specified in terms of the
1429 @var{dependencies}, which consist of file names separated by spaces.
1430 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
1431 A target is out of date if it does not exist or if it is older than any
1432 of the dependencies (by comparison of last-modification times).  The
1433 idea is that the contents of the target file are computed based on
1434 information in the dependencies, so if any of the dependencies changes,
1435 the contents of the existing target file are no longer necessarily
1436 valid.
1438 How to update is specified by @var{commands}.  These are lines to be
1439 executed by the shell (normally @samp{sh}), but with some extra features
1440 (@pxref{Commands, ,Writing the Commands in Rules}).
1442 @node Wildcards, Directory Search, Rule Syntax, Rules
1443 @section Using Wildcard Characters in File Names
1444 @cindex wildcard
1445 @cindex file name with wildcards
1446 @cindex globbing (wildcards)
1448 @cindex @code{*} (wildcard character)
1449 @cindex @code{?} (wildcard character)
1450 @cindex @code{[@dots{}]} (wildcard characters)
1451 A single file name can specify many files using @dfn{wildcard characters}.
1452 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
1453 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
1454 specifies a list of all the files (in the working directory) whose names
1455 end in @samp{.c}.@refill
1457 @cindex @code{~} (tilde)
1458 @cindex tilde (@code{~})
1459 @cindex home directory
1460 The character @samp{~} at the beginning of a file name also has special
1461 significance.  If alone, or followed by a slash, it represents your home
1462 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
1463 If the @samp{~} is followed by a word, the string represents the home
1464 directory of the user named by that word.  For example @file{~john/bin}
1465 expands to @file{/home/john/bin}.@refill
1467 Wildcard expansion happens automatically in targets, in dependencies,
1468 and in commands (where the shell does the expansion).  In other
1469 contexts, wildcard expansion happens only if you request it explicitly
1470 with the @code{wildcard} function.
1472 The special significance of a wildcard character can be turned off by
1473 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
1474 specific file whose name consists of @samp{foo}, an asterisk, and
1475 @samp{bar}.@refill
1477 @menu
1478 * Wildcard Examples::           Several examples
1479 * Wildcard Pitfall::            Problems to avoid.
1480 * Wildcard Function::           How to cause wildcard expansion where
1481                                   it does not normally take place.
1482 @end menu
1484 @node Wildcard Examples, Wildcard Pitfall,  , Wildcards
1485 @subsection Wildcard Examples
1487 Wildcards can be used in the commands of a rule, where they are expanded
1488 by the shell.  For example, here is a rule to delete all the object files:
1490 @example
1491 @group
1492 clean:
1493         rm -f *.o
1494 @end group
1495 @end example
1496 @cindex @code{rm} (shell command)
1498 Wildcards are also useful in the dependencies of a rule.  With the
1499 following rule in the makefile, @samp{make print} will print all the
1500 @samp{.c} files that have changed since the last time you printed them:
1502 @example
1503 print: *.c
1504         lpr -p $?
1505         touch print
1506 @end example
1508 @cindex @code{print} target
1509 @cindex @code{lpr} (shell command)
1510 @cindex @code{touch} (shell command)
1511 @noindent
1512 This rule uses @file{print} as an empty target file; see @ref{Empty
1513 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
1514 @samp{$?} is used to print only those files that have changed; see
1515 @ref{Automatic, ,Automatic Variables}.)@refill
1517 Wildcard expansion does not happen when you define a variable.  Thus, if
1518 you write this:
1520 @example
1521 objects = *.o
1522 @end example
1524 @noindent
1525 then the value of the variable @code{objects} is the actual string
1526 @samp{*.o}.  However, if you use the value of @code{objects} in a target,
1527 dependency or command, wildcard expansion will take place at that time.
1528 To set @code{objects} to the expansion, instead use:
1530 @example
1531 objects := $(wildcard *.o)
1532 @end example
1534 @noindent
1535 @xref{Wildcard Function}.
1537 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
1538 @subsection Pitfalls of Using Wildcards
1539 @cindex wildcard pitfalls
1540 @cindex pitfalls of wildcards
1541 @cindex mistakes with wildcards
1542 @cindex errors with wildcards
1543 @cindex problems with wildcards
1545 Now here is an example of a naive way of using wildcard expansion, that
1546 does not do what you would intend.  Suppose you would like to say that the
1547 executable file @file{foo} is made from all the object files in the
1548 directory, and you write this:
1550 @example
1551 objects = *.o
1553 foo : $(objects)
1554         cc -o foo $(CFLAGS) $(objects)
1555 @end example
1557 @noindent
1558 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
1559 expansion happens in the rule for @file{foo}, so that each @emph{existing}
1560 @samp{.o} file becomes a dependency of @file{foo} and will be recompiled if
1561 necessary.
1563 But what if you delete all the @samp{.o} files?  When a wildcard matches
1564 no files, it is left as it is, so then @file{foo} will depend on the
1565 oddly-named file @file{*.o}.  Since no such file is likely to exist,
1566 @code{make} will give you an error saying it cannot figure out how to
1567 make @file{*.o}.  This is not what you want!
1569 Actually it is possible to obtain the desired result with wildcard
1570 expansion, but you need more sophisticated techniques, including the
1571 @code{wildcard} function and string substitution.
1572 @ifinfo
1573 @xref{Wildcard Function, ,The Function @code{wildcard}}.
1574 @end ifinfo
1575 @iftex
1576 These are described in the following section.
1577 @end iftex
1579 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
1580 @subsection The Function @code{wildcard}
1581 @findex wildcard
1583 Wildcard expansion happens automatically in rules.  But wildcard expansion
1584 does not normally take place when a variable is set, or inside the
1585 arguments of a function.  If you want to do wildcard expansion in such
1586 places, you need to use the @code{wildcard} function, like this:
1588 @example
1589 $(wildcard @var{pattern}@dots{})
1590 @end example
1592 @noindent
1593 This string, used anywhere in a makefile, is replaced by a
1594 space-separated list of names of existing files that match one of the
1595 given file name patterns.  If no existing file name matches a pattern,
1596 then that pattern is omitted from the output of the @code{wildcard}
1597 function.  Note that this is different from how unmatched wildcards
1598 behave in rules, where they are used verbatim rather than ignored
1599 (@pxref{Wildcard Pitfall}).
1601 One use of the @code{wildcard} function is to get a list of all the C source
1602 files in a directory, like this:
1604 @example
1605 $(wildcard *.c)
1606 @end example
1608 We can change the list of C source files into a list of object files by
1609 replacing the @samp{.o} suffix with @samp{.c} in the result, like this:
1611 @example
1612 $(patsubst %.c,%.o,$(wildcard *.c))
1613 @end example
1615 @noindent
1616 (Here we have used another function, @code{patsubst}.
1617 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)@refill
1619 Thus, a makefile to compile all C source files in the directory and then
1620 link them together could be written as follows:
1622 @example
1623 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1625 foo : $(objects)
1626         cc -o foo $(objects)
1627 @end example
1629 @noindent
1630 (This takes advantage of the implicit rule for compiling C programs, so
1631 there is no need to write explicit rules for compiling the files.
1632 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
1633 @samp{:=}, which is a variant of @samp{=}.)
1635 @node Directory Search, Phony Targets, Wildcards, Rules
1636 @section Searching Directories for Dependencies
1637 @vindex VPATH
1638 @findex vpath
1639 @cindex vpath 
1640 @cindex search path for dependencies (@code{VPATH})
1641 @cindex directory search (@code{VPATH})
1643 For large systems, it is often desirable to put sources in a separate
1644 directory from the binaries.  The @dfn{directory search} features of
1645 @code{make} facilitate this by searching several directories
1646 automatically to find a dependency.  When you redistribute the files
1647 among directories, you do not need to change the individual rules,
1648 just the search paths.
1650 @menu
1651 * General Search::              Specifying a search path that applies 
1652                                   to every dependency.
1653 * Selective Search::            Specifying a search path 
1654                                   for a specified class of names.
1655 * Commands/Search::             How to write shell commands that work together
1656                                   with search paths.
1657 * Implicit/Search::             How search paths affect implicit rules.
1658 * Libraries/Search::            Directory search for link libraries.
1659 @end menu
1661 @node General Search, Selective Search,  , Directory Search
1662 @subsection @code{VPATH}: Search Path for All Dependencies
1663 @vindex VPATH
1665 The value of the @code{make} variable @code{VPATH} specifies a list of
1666 directories that @code{make} should search.  Most often, the
1667 directories are expected to contain dependency files that are not in the
1668 current directory; however, @code{VPATH} specifies a search list that
1669 @code{make} applies for all files, including files which are targets of
1670 rules.
1672 Thus, if a file that is listed as a target or dependency does not exist
1673 in the current directory, @code{make} searches the directories listed in
1674 @code{VPATH} for a file with that name.  If a file is found in one of
1675 them, that file becomes the dependency.  Rules may then specify the
1676 names of source files in the dependencies as if they all existed in the
1677 current directory.  @xref{Commands/Search, ,Writing Shell Commands with
1678 Directory Search}.
1680 In the @code{VPATH} variable, directory names are separated by colons or
1681 blanks.  The order in which directories are listed is the order followed
1682 by @code{make} in its search.
1684 For example,
1686 @example
1687 VPATH = src:../headers
1688 @end example
1690 @noindent
1691 specifies a path containing two directories, @file{src} and
1692 @file{../headers}, which @code{make} searches in that order.
1694 With this value of @code{VPATH}, the following rule,
1696 @example
1697 foo.o : foo.c
1698 @end example
1700 @noindent
1701 is interpreted as if it were written like this:
1703 @example
1704 foo.o : src/foo.c
1705 @end example
1707 @noindent
1708 assuming the file @file{foo.c} does not exist in the current directory but
1709 is found in the directory @file{src}.
1711 @node Selective Search, Commands/Search, General Search, Directory Search
1712 @subsection The @code{vpath} Directive
1713 @findex vpath
1715 Similar to the @code{VPATH} variable but more selective is the @code{vpath}
1716 directive (note lower case), which allows you to specify a search path for a particular class
1717 of file names, those that match a particular pattern.  Thus you can supply
1718 certain search directories for one class of file names and other directories
1719 (or none) for other file names.
1721 There are three forms of the @code{vpath} directive:
1723 @table @code
1724 @item vpath @var{pattern} @var{directories}
1725 Specify the search path @var{directories} for file names that match
1726 @var{pattern}.  
1728 The search path, @var{directories}, is a list of directories to be
1729 searched, separated by colons or blanks, just like the search path used
1730 in the @code{VPATH} variable.
1732 @item vpath @var{pattern}
1733 Clear out the search path associated with @var{pattern}.
1735 @c Extra blank line makes sure this gets two lines.
1736 @item vpath
1738 Clear all search paths previously specified with @code{vpath} directives.
1739 @end table
1741 A @code{vpath} pattern is a string containing a @samp{%} character.  The
1742 string must match the file name of a dependency that is being searched
1743 for, the @samp{%} character matching any sequence of zero or more
1744 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
1745 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
1746 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
1747 dependency exactly, which is not useful very often.)
1749 @cindex @code{%}, quoting in @code{vpath}
1750 @cindex @code{%}, quoting with @code{\} (backslash)
1751 @cindex @code{\} (backslash), to quote @code{%}
1752 @cindex backslash (@code{\}), to quote @code{%}
1753 @cindex quoting @code{%}, in @code{vpath}
1754 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
1755 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
1756 quote @samp{%} characters can be quoted with more backslashes.
1757 Backslashes that quote @samp{%} characters or other backslashes are
1758 removed from the pattern before it is compared to file names.  Backslashes
1759 that are not in danger of quoting @samp{%} characters go unmolested.@refill
1761 When a dependency fails to exist in the current directory, if the
1762 @var{pattern} in a @code{vpath} directive matches the name of the
1763 dependency file, then the @var{directories} in that directive are searched
1764 just like (and before) the directories in the @code{VPATH} variable.  
1766 For example,
1768 @example
1769 vpath %.h ../headers
1770 @end example
1772 @noindent
1773 tells @code{make} to look for any dependency whose name ends in @file{.h}
1774 in the directory @file{../headers} if the file is not found in the current
1775 directory.
1777 If several @code{vpath} patterns match the dependency file's name, then
1778 @code{make} processes each matching @code{vpath} directive one by one,
1779 searching all the directories mentioned in each directive.  @code{make}
1780 handles multiple @code{vpath} directives in the order in which they
1781 appear in the makefile; multiple directives with the same pattern are
1782 independent of each other.
1784 @need 750
1785 Thus, 
1787 @example
1788 @group
1789 vpath %.c foo
1790 vpath %   blish
1791 vpath %.c bar
1792 @end group
1793 @end example
1795 @noindent
1796 will look for a file ending in @samp{.c} in @file{foo}, then
1797 @file{blish}, then @file{bar}, while
1799 @example
1800 @group
1801 vpath %.c foo:bar
1802 vpath %   blish
1803 @end group
1804 @end example
1806 @noindent
1807 will look for a file ending in @samp{.c} in @file{foo}, then
1808 @file{bar}, then @file{blish}.
1810 @node Commands/Search, Implicit/Search, Selective Search, Directory Search
1811 @subsection Writing Shell Commands with Directory Search
1812 @cindex shell command, and directory search
1813 @cindex directory search (@code{VPATH}), and shell commands
1815 When a dependency is found in another directory through directory search,
1816 this cannot change the commands of the rule; they will execute as written.
1817 Therefore, you must write the commands with care so that they will look for
1818 the dependency in the directory where @code{make} finds it.
1820 This is done with the @dfn{automatic variables} such as @samp{$^}
1821 (@pxref{Automatic, ,Automatic Variables}).  
1822 For instance, the value of @samp{$^} is a
1823 list of all the dependencies of the rule, including the names of
1824 the directories in which they were found, and the value of
1825 @samp{$@@} is the target.  Thus:@refill
1827 @example
1828 foo.o : foo.c
1829         cc -c $(CFLAGS) $^ -o $@@
1830 @end example
1832 @noindent
1833 (The variable @code{CFLAGS} exists so you can specify flags for C
1834 compilation by implicit rules; we use it here for consistency so it will
1835 affect all C compilations uniformly;
1836 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
1838 Often the dependencies include header files as well, which you do not
1839 want to mention in the commands.  The automatic variable @samp{$<} is
1840 just the first dependency:
1842 @example
1843 VPATH = src:../headers
1844 foo.o : foo.c defs.h hack.h
1845         cc -c $(CFLAGS) $< -o $@@
1846 @end example
1848 @node Implicit/Search, Libraries/Search, Commands/Search, Directory Search
1849 @subsection Directory Search and Implicit Rules
1850 @cindex @code{VPATH}, and implicit rules
1851 @cindex directory search (@code{VPATH}), and implicit rules
1852 @cindex search path for dependencies (@code{VPATH}), and implicit rules
1853 @cindex implicit rule, and directory search
1854 @cindex implicit rule, and @code{VPATH}
1855 @cindex rule, implicit, and directory search
1856 @cindex rule, implicit, and @code{VPATH}
1858 The search through the directories specified in @code{VPATH} or with
1859 @code{vpath} also happens during consideration of implicit rules
1860 (@pxref{Implicit Rules, ,Using Implicit Rules}).
1862 For example, when a file @file{foo.o} has no explicit rule, @code{make}
1863 considers implicit rules, such as the built-in rule to compile
1864 @file{foo.c} if that file exists.  If such a file is lacking in the
1865 current directory, the appropriate directories are searched for it.  If
1866 @file{foo.c} exists (or is mentioned in the makefile) in any of the
1867 directories, the implicit rule for C compilation is applied.
1869 The commands of implicit rules normally use automatic variables as a
1870 matter of necessity; consequently they will use the file names found by
1871 directory search with no extra effort.
1873 @node Libraries/Search,  , Implicit/Search, Directory Search
1874 @subsection Directory Search for Link Libraries
1875 @cindex link libraries, and directory search
1876 @cindex libraries for linking, directory search
1877 @cindex directory search (@code{VPATH}), and link libraries 
1878 @cindex @code{VPATH}, and link libraries 
1879 @cindex search path for dependencies (@code{VPATH}), and link libraries 
1880 @cindex @code{-l} (library search)
1882 Directory search applies in a special way to libraries used with the
1883 linker.  This special feature comes into play when you write a dependency
1884 whose name is of the form @samp{-l@var{name}}.  (You can tell something
1885 strange is going on here because the dependency is normally the name of a
1886 file, and the @emph{file name} of the library looks like
1887 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)@refill
1889 When a dependency's name has the form @samp{-l@var{name}}, @code{make}
1890 handles it specially by searching for the file @file{lib@var{name}.a} in
1891 the current directory, in directories specified by matching @code{vpath}
1892 search paths and the @code{VPATH} search path, and then in the
1893 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
1894 (normally @file{/usr/local/lib}).
1896 For example,
1898 @example
1899 @group
1900 foo : foo.c -lcurses
1901         cc $^ -o $@@
1902 @end group
1903 @end example
1905 @noindent
1906 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
1907 be executed when @file{foo} is older than @file{foo.c} or than
1908 @file{/usr/lib/libcurses.a}.@refill
1910 @node Phony Targets, Force Targets, Directory Search, Rules
1911 @section Phony Targets
1912 @cindex phony targets
1913 @cindex targets, phony
1914 @cindex targets without a file
1916 A phony target is one that is not really the name of a file.  It is just a
1917 name for some commands to be executed when you make an explicit request.
1918 There are two reasons to use a phony target: to avoid a conflict with
1919 a file of the same name, and to improve performance.
1921 If you write a rule whose commands will not create the target file, the
1922 commands will be executed every time the target comes up for remaking.
1923 Here is an example:
1925 @example
1926 @group
1927 clean:
1928         rm *.o temp
1929 @end group
1930 @end example
1932 @noindent
1933 Because the @code{rm} command does not create a file named @file{clean},
1934 probably no such file will ever exist.  Therefore, the @code{rm} command
1935 will be executed every time you say @samp{make clean}.
1936 @cindex @code{rm} (shell command)
1938 @findex .PHONY
1939 The phony target will cease to work if anything ever does create a file
1940 named @file{clean} in this directory.  Since it has no dependencies, the
1941 file @file{clean} would inevitably be considered up to date, and its
1942 commands would not be executed.  To avoid this problem, you can explicitly
1943 declare the target to be phony, using the special target @code{.PHONY}
1944 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
1946 @example
1947 .PHONY : clean
1948 @end example
1950 @noindent
1951 Once this is done, @samp{make clean} will run the commands regardless of
1952 whether there is a file named @file{clean}.
1954 Since it knows that phony targets do not name actual files that could be
1955 remade from other files, @code{make} skips the implicit rule search for
1956 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
1957 phony is good for performance, even if you are not worried about the
1958 actual file existing.
1960 Thus, you first write the line that states that @code{clean} is a
1961 phony target, then you write the rule, like this:
1963 @example
1964 @group
1965 .PHONY: clean
1966 clean:
1967         rm *.o temp
1968 @end group
1969 @end example
1971 A phony target should not be a dependency of a real target file; if it
1972 is, its commands are run every time @code{make} goes to update that
1973 file.  As long as a phony target is never a dependency of a real
1974 target, the phony target commands will be executed only when the phony
1975 target is a specified goal (@pxref{Goals, ,Arguments to Specify the
1976 Goals}).
1978 Phony targets can have dependencies.  When one directory contains multiple
1979 programs, it is most convenient to describe all of the programs in one
1980 makefile @file{./Makefile}.  Since the target remade by default will be the
1981 first one in the makefile, it is common to make this a phony target named
1982 @samp{all} and give it, as dependencies, all the individual programs.  For
1983 example:
1985 @example
1986 all : prog1 prog2 prog3
1987 .PHONY : all
1989 prog1 : prog1.o utils.o
1990         cc -o prog1 prog1.o utils.o
1992 prog2 : prog2.o
1993         cc -o prog2 prog2.o
1995 prog3 : prog3.o sort.o utils.o
1996         cc -o prog3 prog3.o sort.o utils.o
1997 @end example
1999 @noindent
2000 Now you can say just @samp{make} to remake all three programs, or specify
2001 as arguments the ones to remake (as in @samp{make prog1 prog3}).
2003 When one phony target is a dependency of another, it serves as a subroutine
2004 of the other.  For example, here @samp{make cleanall} will delete the
2005 object files, the difference files, and the file @file{program}:
2007 @example
2008 .PHONY: cleanall cleanobj cleandiff
2010 cleanall : cleanobj cleandiff
2011         rm program
2013 cleanobj :
2014         rm *.o
2016 cleandiff :
2017         rm *.diff
2018 @end example
2020 @node Force Targets, Empty Targets, Phony Targets, Rules
2021 @section Rules without Commands or Dependencies
2022 @cindex force targets
2023 @cindex targets, force
2024 @cindex @code{FORCE}
2025 @cindex rule, no commands or dependencies
2027 If a rule has no dependencies or commands, and the target of the rule
2028 is a nonexistent file, then @code{make} imagines this target to have
2029 been updated whenever its rule is run.  This implies that all targets
2030 depending on this one will always have their commands run.
2032 An example will illustrate this:
2034 @example
2035 @group
2036 clean: FORCE
2037         rm $(objects)
2038 FORCE:
2039 @end group
2040 @end example
2042 Here the target @samp{FORCE} satisfies the special conditions, so the
2043 target @file{clean} that depends on it is forced to run its commands.
2044 There is nothing special about the name @samp{FORCE}, but that is one name
2045 commonly used this way.
2047 As you can see, using @samp{FORCE} this way has the same results as using
2048 @samp{.PHONY: clean}.  
2050 Using @samp{.PHONY} is more explicit and more efficient.  However,
2051 other versions of @code{make} do not support @samp{.PHONY}; thus
2052 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2054 @node Empty Targets, Special Targets, Force Targets, Rules
2055 @section Empty Target Files to Record Events
2056 @cindex empty targets
2057 @cindex targets, empty
2058 @cindex recording events with empty targets
2060 The @dfn{empty target} is a variant of the phony target; it is used to hold
2061 commands for an action that you request explicitly from time to time.
2062 Unlike a phony target, this target file can really exist; but the file's
2063 contents do not matter, and usually are empty.
2065 The purpose of the empty target file is to record, with its
2066 last-modification time, when the rule's commands were last executed.  It
2067 does so because one of the commands is a @code{touch} command to update the
2068 target file.
2070 The empty target file must have some dependencies.  When you ask to remake
2071 the empty target, the commands are executed if any dependency is more
2072 recent than the target; in other words, if a dependency has changed since
2073 the last time you remade the target.  Here is an example:
2075 @example
2076 print: foo.c bar.c
2077         lpr -p $?
2078         touch print
2079 @end example
2080 @cindex @code{print} target
2081 @cindex @code{lpr} (shell command)
2082 @cindex @code{touch} (shell command)
2084 @noindent
2085 With this rule, @samp{make print} will execute the @code{lpr} command if
2086 either source file has changed since the last @samp{make print}.  The
2087 automatic variable @samp{$?} is used to print only those files that have
2088 changed (@pxref{Automatic, ,Automatic Variables}).
2090 @node Special Targets, Multiple Targets, Empty Targets, Rules
2091 @section Special Built-in Target Names
2092 @cindex special targets
2093 @cindex built-in special targets
2094 @cindex targets, built-in special
2096 Certain names have special meanings if they appear as targets.
2098 @table @code
2099 @findex .PHONY
2100 @item .PHONY
2102 The dependencies of the special target @code{.PHONY} are considered to
2103 be phony targets.  When it is time to consider such a target,
2104 @code{make} will run its commands unconditionally, regardless of
2105 whether a file with that name exists or what its last-modification
2106 time is.  @xref{Phony Targets, ,Phony Targets}.
2108 @findex .SUFFIXES
2109 @item .SUFFIXES
2111 The dependencies of the special target @code{.SUFFIXES} are the list
2112 of suffixes to be used in checking for suffix rules.  
2113 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
2115 @findex .DEFAULT
2116 @item .DEFAULT
2118 The commands specified for @code{.DEFAULT} are used for any target for
2119 which no rules are found (either explicit rules or implicit rules).
2120 @xref{Last Resort}.  If @code{.DEFAULT} commands are specified, every
2121 file mentioned as a dependency, but not as a target in a rule, will have
2122 these commands executed on its behalf.  @xref{Search Algorithm,
2123 ,Implicit Rule Search Algorithm}.
2125 @findex .PRECIOUS
2126 @item .PRECIOUS
2127 @cindex precious targets
2128 @cindex preserving with @code{.PRECIOUS}
2130 The targets which @code{.PRECIOUS} depends on are given the following
2131 special treatment: if @code{make} is killed or interrupted during the
2132 execution of their commands, the target is not deleted.
2133 @xref{Interrupts, ,Interrupting or Killing @code{make}}.
2134 Also, if the target is an intermediate file, it will not be deleted
2135 after it is no longer needed, as is normally done.
2136 @xref{Chained Rules, ,Chains of Implicit Rules}.
2138 You can also list the target pattern of an implicit rule (such as
2139 @samp{%.o}) as a dependency file of the special target @code{.PRECIOUS}
2140 to preserve intermediate files created by rules whose target patterns
2141 match that file's name.
2143 @findex .IGNORE
2144 @item .IGNORE
2146 If you specify dependencies for @code{.IGNORE}, then @code{make} will
2147 ignore errors in execution of the commands run for those particular
2148 files.  The commands for @code{.IGNORE} are not meaningful.
2150 If mentioned as a target with no dependencies, @code{.IGNORE} says to
2151 ignore errors in execution of commands for all files.  This usage of
2152 @samp{.IGNORE} is supported only for historical compatibility.  Since
2153 this affects every command in the makefile, it is not very useful; we
2154 recommend you use the more selective ways to ignore errors in specific
2155 commands.  @xref{Errors, ,Errors in Commands}.
2157 @findex .SILENT
2158 @item .SILENT
2160 If you specify dependencies for @code{.SILENT}, then @code{make} will
2161 not the print commands to remake those particular files before executing
2162 them.  The commands for @code{.SILENT} are not meaningful.
2164 If mentioned as a target with no dependencies, @code{.SILENT} says not
2165 to print any commands before executing them.  This usage of
2166 @samp{.SILENT} is supported only for historical compatibility.  We
2167 recommend you use the more selective ways to silence specific commands.
2168 @xref{Echoing, ,Command Echoing}.  If you want to silence all commands
2169 for a particular run of @code{make}, use the @samp{-s} or
2170 @w{@samp{--silent}} option (@pxref{Options Summary}).
2172 @findex .EXPORT_ALL_VARIABLES
2173 @item .EXPORT_ALL_VARIABLES
2175 Simply by being mentioned as a target, this tells @code{make} to
2176 export all variables to child processes by default.
2177 @xref{Variables/Recursion, ,Communicating Variables to a
2178 Sub-@code{make}}.
2179 @end table
2181 Any defined implicit rule suffix also counts as a special target if it
2182 appears as a target, and so does the concatenation of two suffixes, such
2183 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
2184 defining implicit rules (but a way still widely used).  In principle, any
2185 target name could be special in this way if you break it in two and add
2186 both pieces to the suffix list.  In practice, suffixes normally begin with
2187 @samp{.}, so these special target names also begin with @samp{.}.
2188 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
2190 @node Multiple Targets, Multiple Rules, Special Targets, Rules
2191 @section Multiple Targets in a Rule
2192 @cindex multiple targets
2193 @cindex several targets in a rule
2194 @cindex targets, multiple
2195 @cindex rule, with multiple targets
2197 A rule with multiple targets is equivalent to writing many rules, each with
2198 one target, and all identical aside from that.  The same commands apply to
2199 all the targets, but their effects may vary because you can substitute the
2200 actual target name into the command using @samp{$@@}.  The rule contributes
2201 the same dependencies to all the targets also.
2203 This is useful in two cases.
2205 @itemize @bullet
2206 @item
2207 You want just dependencies, no commands.  For example:
2209 @example
2210 kbd.o command.o files.o: command.h
2211 @end example
2213 @noindent
2214 gives an additional dependency to each of the three object files
2215 mentioned.
2217 @item
2218 Similar commands work for all the targets.  The commands do not need
2219 to be absolutely identical, since the automatic variable @samp{$@@}
2220 can be used to substitute the particular target to be remade into the
2221 commands (@pxref{Automatic, ,Automatic Variables}).  For example:
2223 @example
2224 @group
2225 bigoutput littleoutput : text.g
2226         generate text.g -$(subst output,,$@@) > $@@
2227 @end group
2228 @end example
2229 @findex subst
2231 @noindent
2232 is equivalent to
2234 @example
2235 bigoutput : text.g
2236         generate text.g -big > bigoutput
2237 littleoutput : text.g
2238         generate text.g -little > littleoutput
2239 @end example
2241 @noindent
2242 Here we assume the hypothetical program @code{generate} makes two
2243 types of output, one if given @samp{-big} and one if given
2244 @samp{-little}.
2245 @xref{Text Functions, ,Functions for String Substitution and Analysis},
2246 for an explanation of the @code{subst} function.
2247 @end itemize
2249 Suppose you would like to vary the dependencies according to the target,
2250 much as the variable @samp{$@@} allows you to vary the commands.
2251 You cannot do this with multiple targets in an ordinary rule, but you can
2252 do it with a @dfn{static pattern rule}.
2253 @xref{Static Pattern, ,Static Pattern Rules}.
2255 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
2256 @section Multiple Rules for One Target
2257 @cindex multiple rules for one target
2258 @cindex several rules for one target
2259 @cindex rule, multiple for one target
2260 @cindex target, multiple rules for one
2262 One file can be the target of several rules.  All the dependencies
2263 mentioned in all the rules are merged into one list of dependencies for
2264 the target.  If the target is older than any dependency from any rule,
2265 the commands are executed.
2267 There can only be one set of commands to be executed for a file.
2268 If more than one rule gives commands for the same file, 
2269 @code{make} uses the last set given and prints an error message.
2270 (As a special case, if the file's name begins with a dot, no
2271 error message is printed.  This odd behavior is only for
2272 compatibility with other implementations of @code{make}.)  
2273 There is no reason to
2274 write your makefiles this way; that is why @code{make} gives you
2275 an error message.@refill
2277 An extra rule with just dependencies can be used to give a few extra
2278 dependencies to many files at once.  For example, one usually has a
2279 variable named @code{objects} containing a list of all the compiler output
2280 files in the system being made.  An easy way to say that all of them must
2281 be recompiled if @file{config.h} changes is to write the following:
2283 @example
2284 objects = foo.o bar.o
2285 foo.o : defs.h
2286 bar.o : defs.h test.h
2287 $(objects) : config.h
2288 @end example
2290 This could be inserted or taken out without changing the rules that really
2291 specify how to make the object files, making it a convenient form to use if
2292 you wish to add the additional dependency intermittently.
2294 Another wrinkle is that the additional dependencies could be specified with
2295 a variable that you set with a command argument to @code{make}
2296 (@pxref{Overriding, ,Overriding Variables}).  For example,
2298 @example
2299 @group
2300 extradeps=
2301 $(objects) : $(extradeps)
2302 @end group
2303 @end example
2305 @noindent
2306 means that the command @samp{make extradeps=foo.h} will consider
2307 @file{foo.h} as a dependency of each object file, but plain @samp{make}
2308 will not.
2310 If none of the explicit rules for a target has commands, then @code{make}
2311 searches for an applicable implicit rule to find some commands
2312 @pxref{Implicit Rules, ,Using Implicit Rules}).
2314 @node Static Pattern, Double-Colon, Multiple Rules, Rules
2315 @section Static Pattern Rules
2316 @cindex static pattern rule
2317 @cindex rule, static pattern
2318 @cindex pattern rules, static (not implicit)
2319 @cindex varying dependencies
2320 @cindex dependencies, varying (static pattern)
2322 @dfn{Static pattern rules} are rules which specify multiple targets and
2323 construct the dependency names for each target based on the target name.
2324 They are more general than ordinary rules with multiple targets because the
2325 targets do not have to have identical dependencies.  Their dependencies must
2326 be @emph{analogous}, but not necessarily @emph{identical}.
2328 @menu
2329 * Static Usage::                The syntax of static pattern rules.
2330 * Static versus Implicit::      When are they better than implicit rules?
2331 @end menu
2333 @node Static Usage, Static versus Implicit,  , Static Pattern
2334 @subsection Syntax of Static Pattern Rules
2335 @cindex static pattern rule, syntax of
2336 @cindex pattern rules, static, syntax of
2338 Here is the syntax of a static pattern rule:
2340 @example
2341 @var{targets} @dots{}: @var{target-pattern}: @var{dep-patterns} @dots{}
2342         @var{commands}
2343         @dots{}
2344 @end example
2346 @noindent
2347 The @var{targets} list specifies the targets that the rule applies to.
2348 The targets can contain wildcard characters, just like the targets of
2349 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
2350 Names}).
2352 @cindex target pattern, static (not implicit)
2353 @cindex stem
2354 The @var{target-pattern} and @var{dep-patterns} say how to compute the
2355 dependencies of each target.  Each target is matched against the
2356 @var{target-pattern} to extract a part of the target name, called the
2357 @dfn{stem}.  This stem is substituted into each of the @var{dep-patterns}
2358 to make the dependency names (one from each @var{dep-pattern}).
2360 Each pattern normally contains the character @samp{%} just once.  When the
2361 @var{target-pattern} matches a target, the @samp{%} can match any part of
2362 the target name; this part is called the @dfn{stem}.  The rest of the
2363 pattern must match exactly.  For example, the target @file{foo.o} matches
2364 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
2365 @file{foo.c} and @file{foo.out} do not match that pattern.@refill
2367 @cindex dependency pattern, static (not implicit)
2368 The dependency names for each target are made by substituting the stem
2369 for the @samp{%} in each dependency pattern.  For example, if one
2370 dependency pattern is @file{%.c}, then substitution of the stem
2371 @samp{foo} gives the dependency name @file{foo.c}.  It is legitimate
2372 to write a dependency pattern that does not contain @samp{%}; then this
2373 dependency is the same for all targets.
2375 @cindex @code{%}, quoting in static pattern
2376 @cindex @code{%}, quoting with @code{\} (backslash)
2377 @cindex @code{\} (backslash), to quote @code{%}
2378 @cindex backslash (@code{\}), to quote @code{%}
2379 @cindex quoting @code{%}, in static pattern
2380 @samp{%} characters in pattern rules can be quoted with preceding
2381 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
2382 characters can be quoted with more backslashes.  Backslashes that quote
2383 @samp{%} characters or other backslashes are removed from the pattern
2384 before it is compared to file names or has a stem substituted into it.
2385 Backslashes that are not in danger of quoting @samp{%} characters go
2386 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
2387 @samp{the%weird\} preceding the operative @samp{%} character, and
2388 @samp{pattern\\} following it.  The final two backslashes are left alone
2389 because they cannot affect any @samp{%} character.@refill
2391 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
2392 from the corresponding @file{.c} file:
2394 @example
2395 @group
2396 objects = foo.o bar.o
2398 $(objects): %.o: %.c
2399         $(CC) -c $(CFLAGS) $< -o $@@
2400 @end group
2401 @end example
2403 @noindent
2404 Here @samp{$<} is the automatic variable that holds the name of the
2405 dependency and @samp{$@@} is the automatic variable that holds the name
2406 of the target; see @ref{Automatic, , Automatic Variables}.
2408 Each target specified must match the target pattern; a warning is issued
2409 for each target that does not.  If you have a list of files, only some of
2410 which will match the pattern, you can use the @code{filter} function to
2411 remove nonmatching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
2413 @example
2414 files = foo.elc bar.o lose.o
2416 $(filter %.o,$(files)): %.o: %.c
2417         $(CC) -c $(CFLAGS) $< -o $@@
2418 $(filter %.elc,$(files)): %.elc: %.el
2419         emacs -f batch-byte-compile $<
2420 @end example
2422 @noindent
2423 In this example the result of @samp{$(filter %.o,$(files))} is
2424 @file{bar.o lose.o}, and the first static pattern rule causes each of
2425 these object files to be updated by compiling the corresponding C source
2426 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
2427 @file{foo.elc}, so that file is made from @file{foo.el}.@refill
2429 Another example shows how to use @code{$*} in static pattern rules:
2430 @vindex $*@r{, and static pattern}
2432 @example
2433 @group
2434 bigoutput littleoutput : %output : text.g
2435         generate text.g -$* > $@@
2436 @end group
2437 @end example
2439 @noindent
2440 When the @code{generate} command is run, @code{$*} will expand to the
2441 stem, either @samp{big} or @samp{little}.
2443 @node Static versus Implicit,  , Static Usage, Static Pattern
2444 @subsection Static Pattern Rules versus Implicit Rules
2445 @cindex rule, static pattern versus implicit
2446 @cindex static pattern rule, versus implicit
2448 A static pattern rule has much in common with an implicit rule defined as a
2449 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
2450 Both have a pattern for the target and patterns for constructing the
2451 names of dependencies.  The difference is in how @code{make} decides
2452 @emph{when} the rule applies.
2454 An implicit rule @emph{can} apply to any target that matches its pattern,
2455 but it @emph{does} apply only when the target has no commands otherwise
2456 specified, and only when the dependencies can be found.  If more than one
2457 implicit rule appears applicable, only one applies; the choice depends on
2458 the order of rules.
2460 By contrast, a static pattern rule applies to the precise list of targets
2461 that you specify in the rule.  It cannot apply to any other target and it
2462 invariably does apply to each of the targets specified.  If two conflicting
2463 rules apply, and both have commands, that's an error.
2465 The static pattern rule can be better than an implicit rule for these
2466 reasons:
2468 @itemize @bullet
2469 @item
2470 You may wish to override the usual implicit rule for a few
2471 files whose names cannot be categorized syntactically but
2472 can be given in an explicit list.
2474 @item
2475 If you cannot be sure of the precise contents of the directories
2476 you are using, you may not be sure which other irrelevant files
2477 might lead @code{make} to use the wrong implicit rule.  The choice
2478 might depend on the order in which the implicit rule search is done.
2479 With static pattern rules, there is no uncertainty: each rule applies
2480 to precisely the targets specified.
2481 @end itemize
2483 @node Double-Colon, Automatic Dependencies, Static Pattern, Rules
2484 @section Double-Colon Rules
2485 @cindex double-colon rules
2486 @cindex rule, double-colon (@code{::})
2487 @cindex multiple rules for one target (@code{::})
2488 @cindex @code{::} rules (double-colon)
2490 @dfn{Double-colon} rules are rules written with @samp{::} instead of
2491 @samp{:} after the target names.  They are handled differently from
2492 ordinary rules when the same target appears in more than one rule.
2494 When a target appears in multiple rules, all the rules must be the same
2495 type: all ordinary, or all double-colon.  If they are double-colon, each of
2496 them is independent of the others.  Each double-colon rule's commands are
2497 executed if the target is older than any dependencies of that rule.  This
2498 can result in executing none, any, or all of the double-colon rules.
2500 Double-colon rules with the same target are in fact completely separate
2501 from one another.  Each double-colon rule is processed individually, just
2502 as rules with different targets are processed.
2504 The double-colon rules for a target are executed in the order they appear
2505 in the makefile.  However, the cases where double-colon rules really make
2506 sense are those where the order of executing the commands would not matter.
2508 Double-colon rules are somewhat obscure and not often very useful; they
2509 provide a mechanism for cases in which the method used to update a target
2510 differs depending on which dependency files caused the update, and such
2511 cases are rare.
2513 Each double-colon rule should specify commands; if it does not, an
2514 implicit rule will be used if one applies.  
2515 @xref{Implicit Rules, ,Using Implicit Rules}.
2517 @node Automatic Dependencies,  , Double-Colon, Rules
2518 @section Generating Dependencies Automatically
2519 @cindex dependencies, automatic generation
2520 @cindex automatic generation of dependencies
2521 @cindex generating dependencies automatically
2523 In the makefile for a program, many of the rules you need to write often
2524 say only that some object file depends on some header
2525 file.  For example, if @file{main.c} uses @file{defs.h} via an
2526 @code{#include}, you would write:
2528 @example
2529 main.o: defs.h
2530 @end example
2532 @noindent
2533 You need this rule so that @code{make} knows that it must remake
2534 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
2535 large program you would have to write dozens of such rules in your
2536 makefile.  And, you must always be very careful to update the makefile
2537 every time you add or remove an @code{#include}.
2538 @cindex @code{#include}
2540 @cindex @code{-M} (to compiler)
2541 To avoid this hassle, most modern C compilers can write these rules for
2542 you, by looking at the @code{#include} lines in the source files.
2543 Usually this is done with the @samp{-M} option to the compiler.
2544 For example, the command:
2546 @example
2547 cc -M main.c
2548 @end example
2550 @noindent
2551 generates the output:
2553 @example
2554 main.o : main.c defs.h
2555 @end example
2557 @noindent
2558 Thus you no longer have to write all those rules yourself.
2559 The compiler will do it for you.
2561 Note that such a dependency constitutes mentioning @file{main.o} in a
2562 makefile, so it can never be considered an intermediate file by implicit
2563 rule search.  This means that @code{make} won't ever remove the file
2564 after using it; @pxref{Chained Rules, ,Chains of Implicit Rules}.
2566 @cindex @code{make depend}
2567 With old @code{make} programs, it was traditional practice to use this
2568 compiler feature to generate dependencies on demand with a command like
2569 @samp{make depend}.  That command would create a file @file{depend}
2570 containing all the automatically-generated dependencies; then the
2571 makefile could use @code{include} to read them in (@pxref{Include}).
2573 In GNU @code{make}, the feature of remaking makefiles makes this
2574 practice obsolete---you need never tell @code{make} explicitly to
2575 regenerate the dependencies, because it always regenerates any makefile
2576 that is out of date.  @xref{Remaking Makefiles}.
2578 The practice we recommend for automatic dependency generation is to have
2579 one makefile corresponding to each source file.  For each source file
2580 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
2581 what files the object file @file{@var{name}.o} depends on.  That way
2582 only the source files that have changed need to be rescanned to produce
2583 the new dependencies.
2585 Here is the pattern rule to generate a file of dependencies (i.e., a makefile)
2586 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
2588 @example
2589 @group
2590 %.d: %.c
2591         $(SHELL) -ec '$(CC) -M $(CPPFLAGS) $< \
2592                       | sed '\''s/$*\\.o[ :]*/& $@@/g'\'' > $@@'
2593 @end group
2594 @end example
2596 @noindent
2597 @xref{Pattern Rules}, for information on defining pattern rules.  The
2598 @samp{-e} flag to the shell makes it exit immediately if the
2599 @code{$(CC)} command fails (exits with a nonzero status).  Normally the
2600 shell exits with the status of the last command in the pipeline
2601 (@code{sed} in this case), so @code{make} would not notice a nonzero
2602 status from the compiler.
2603 @cindex @code{-e} (shell flag)
2605 @cindex @code{-MM} (to GNU compiler)
2606 With the GNU C compiler, you may wish to use the @samp{-MM} flag instead
2607 of @samp{-M}.  This omits dependencies on system header files.
2608 @xref{Preprocessor Options, , Options Controlling the Preprocessor, 
2609 gcc.info, Using GNU CC}, for details.
2611 @cindex @code{sed} (shell command)
2612 The purpose of the @code{sed} command is to translate (for example):
2614 @example
2615 main.o : main.c defs.h
2616 @end example
2618 @noindent
2619 into:
2621 @example
2622 main.o main.d : main.c defs.h
2623 @end example
2625 @noindent
2626 @cindex @code{.d}
2627 This makes each @samp{.d} file depend on all the source and header files
2628 that the corresponding @samp{.o} file depends on.  @code{make} then
2629 knows it must regenerate the dependencies whenever any of the source or
2630 header files changes.
2632 Once you've defined the rule to remake the @samp{.d} files,
2633 you then use the @code{include} directive to read them all in.
2634 @xref{Include}.  For example:
2636 @example
2637 @group
2638 sources = foo.c bar.c
2640 include $(sources:.c=.d)
2641 @end group
2642 @end example
2644 @noindent
2645 (This example uses a substitution variable reference to translate the
2646 list of source files @samp{foo.c bar.c} into a list of dependency
2647 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
2648 information on substitution references.)  Since the @samp{.d} files are
2649 makefiles like any others, @code{make} will remake them as necessary
2650 with no further work from you.  @xref{Remaking Makefiles}.
2652 @node Commands, Using Variables, Rules, Top
2653 @chapter Writing the Commands in Rules
2654 @cindex commands, how to write
2655 @cindex rule commands
2656 @cindex writing rule commands
2658 The commands of a rule consist of shell command lines to be executed one
2659 by one.  Each command line must start with a tab, except that the first
2660 command line may be attached to the target-and-dependencies line with a
2661 semicolon in between.  Blank lines and lines of just comments may appear
2662 among the command lines; they are ignored.  (But beware, an apparently
2663 ``blank'' line that begins with a tab is @emph{not} blank!  It is an
2664 empty command; @pxref{Empty Commands}.)
2666 Users use many different shell programs, but commands in makefiles are
2667 always interpreted by @file{/bin/sh} unless the makefile specifies
2668 otherwise.  @xref{Execution, ,Command Execution}.
2670 @cindex comments, in commands
2671 @cindex commands, comments in
2672 @cindex @code{#} (comments), in commands
2673 The shell that is in use determines whether comments can be written on
2674 command lines, and what syntax they use.  When the shell is
2675 @file{/bin/sh}, a @samp{#} starts a comment that extends to the end of
2676 the line.  The @samp{#} does not have to be at the beginning of a line.
2677 Text on a line before a @samp{#} is not part of the comment.
2679 @menu
2680 * Echoing::                     How to control when commands are echoed.
2681 * Execution::                   How commands are executed.
2682 * Parallel::                    How commands can be executed in parallel.
2683 * Errors::                      What happens after a command execution error. 
2684 * Interrupts::                  What happens when a command is interrupted.
2685 * Recursion::                   Invoking @code{make} from makefiles.
2686 * Sequences::                   Defining canned sequences of commands.
2687 * Empty Commands::              Defining useful, do-nothing commands.
2688 @end menu
2690 @node Echoing, Execution,  , Commands
2691 @section Command Echoing
2692 @cindex echoing of commands
2693 @cindex silent operation
2694 @cindex @code{@@} (in commands)
2695 @cindex commands, echoing
2696 @cindex printing of commands
2698 Normally @code{make} prints each command line before it is executed.
2699 We call this @dfn{echoing} because it gives the appearance that you
2700 are typing the commands yourself.
2702 When a line starts with @samp{@@}, the echoing of that line is suppressed.
2703 The @samp{@@} is discarded before the command is passed to the shell.
2704 Typically you would use this for a command whose only effect is to print
2705 something, such as an @code{echo} command to indicate progress through
2706 the makefile:
2708 @example
2709 @@echo About to make distribution files
2710 @end example
2712 @cindex @code{-n}
2713 @cindex @code{--just-print}
2714 @cindex @code{--dry-run}
2715 @cindex @code{--recon}
2716 When @code{make} is given the flag @samp{-n} or @samp{--just-print},
2717 echoing is all that happens, no execution.  @xref{Options Summary,
2718 ,Summary of Options}.  In this case and only this case, even the
2719 commands starting with @samp{@@} are printed.  This flag is useful for
2720 finding out which commands @code{make} thinks are necessary without
2721 actually doing them.
2723 @cindex @code{-s}
2724 @cindex @code{--silent}
2725 @cindex @code{--quiet}
2726 @findex .SILENT
2727 The @samp{-s} or @samp{--silent}
2728 flag to @code{make} prevents all echoing, as if all commands
2729 started with @samp{@@}.  A rule in the makefile for the special target
2730 @code{.SILENT} without dependencies has the same effect 
2731 (@pxref{Special Targets, ,Special Built-in Target Names}).
2732 @code{.SILENT} is essentially obsolete since @samp{@@} is more flexible.@refill
2734 @node Execution, Parallel, Echoing, Commands
2735 @section Command Execution
2736 @cindex commands, execution
2737 @cindex execution, of commands
2738 @cindex shell command, execution
2739 @vindex SHELL @r{(command execution)}
2741 When it is time to execute commands to update a target, they are executed
2742 by making a new subshell for each line.  (In practice, @code{make} may
2743 take shortcuts that do not affect the results.)
2745 @cindex @code{cd} (shell command)
2746 @strong{Please note:} this implies that shell commands such as
2747 @code{cd} that set variables local to each process will not affect the
2748 following command lines.  If you want to use @code{cd} to affect the
2749 next command, put the two on a single line with a semicolon between
2750 them.  Then @code{make} will consider them a single command and pass
2751 them, together, to a shell which will execute them in sequence.  For
2752 example:
2754 @example
2755 foo : bar/lose
2756         cd bar; gobble lose > ../foo
2757 @end example
2759 @cindex commands, backslash (@code{\}) in
2760 @cindex commands, quoting newlines in
2761 @cindex backslash (@code{\}), in commands
2762 @cindex @code{\} (backslash), in commands
2763 @cindex quoting newline, in commands
2764 @cindex newline, quoting, in commands
2765 If you would like to split a single shell command into multiple lines of
2766 text, you must use a backslash at the end of all but the last subline.
2767 Such a sequence of lines is combined into a single line, by deleting the
2768 backslash-newline sequences, before passing it to the shell.  Thus, the
2769 following is equivalent to the preceding example:
2771 @example
2772 @group
2773 foo : bar/lose
2774         cd bar;  \
2775         gobble lose > ../foo
2776 @end group
2777 @end example
2779 @vindex SHELL
2780 The program used as the shell is taken from the variable @code{SHELL}.
2781 By default, the program @file{/bin/sh} is used.
2783 @cindex environment, @code{SHELL} in
2784 Unlike most variables, the variable @code{SHELL} is never set from the
2785 environment.  This is because the @code{SHELL} environment variable is
2786 used to specify your personal choice of shell program for interactive
2787 use.  It would be very bad for personal choices like this to affect
2788 the functioning of makefiles.  @xref{Environment, ,Variables from the
2789 Environment}.
2791 @node Parallel, Errors, Execution, Commands
2792 @section Parallel Execution
2793 @cindex commands, execution in parallel
2794 @cindex parallel execution
2795 @cindex execution, in parallel
2796 @cindex job slots
2797 @cindex @code{-j}
2798 @cindex @code{--jobs}
2800 GNU @code{make} knows how to execute several commands at once.
2801 Normally, @code{make} will execute only one command at a time, waiting
2802 for it to finish before executing the next.  However, the @samp{-j} or
2803 @samp{--jobs} option tells @code{make} to execute many commands
2804 simultaneously.@refill
2806 If the @samp{-j} option is followed by an integer, this is the number of
2807 commands to execute at once; this is called the number of @dfn{job slots}.
2808 If there is nothing looking like an integer after the @samp{-j} option,
2809 there is no limit on the number of job slots.  The default number of job
2810 slots is one, which means serial execution (one thing at a time).
2812 One unpleasant consequence of running several commands simultaneously is
2813 that output from all of the commands comes when the commands send it, so
2814 messages from different commands may be interspersed.
2816 Another problem is that two processes cannot both take input from the
2817 same device; so to make sure that only one command tries to take input
2818 from the terminal at once, @code{make} will invalidate the standard
2819 input streams of all but one running command.  This means that
2820 attempting to read from standard input will usually be a fatal error (a
2821 @samp{Broken pipe} signal) for most child processes if there are
2822 several.
2823 @cindex broken pipe
2824 @cindex standard input
2826 It is unpredictable which command will have a valid standard input stream
2827 (which will come from the terminal, or wherever you redirect the standard
2828 input of @code{make}).  The first command run will always get it first, and
2829 the first command started after that one finishes will get it next, and so
2832 We will change how this aspect of @code{make} works if we find a better
2833 alternative.  In the mean time, you should not rely on any command using
2834 standard input at all if you are using the parallel execution feature; but
2835 if you are not using this feature, then standard input works normally in
2836 all commands.
2838 If a command fails (is killed by a signal or exits with a nonzero
2839 status), and errors are not ignored for that command
2840 (@pxref{Errors, ,Errors in Commands}),
2841 the remaining command lines to remake the same target will not be run.
2842 If a command fails and the @samp{-k} or @samp{--keep-going}
2843 option was not given
2844 (@pxref{Options Summary, ,Summary of Options}), 
2845 @code{make} aborts execution.  If make
2846 terminates for any reason (including a signal) with child processes
2847 running, it waits for them to finish before actually exiting.@refill
2849 @cindex load average
2850 @cindex limiting jobs based on load
2851 @cindex jobs, limiting based on load
2852 @cindex @code{-l} (load average)
2853 @cindex @code{--max-load}
2854 @cindex @code{--load-average}
2855 When the system is heavily loaded, you will probably want to run fewer jobs
2856 than when it is lightly loaded.  You can use the @samp{-l} option to tell
2857 @code{make} to limit the number of jobs to run at once, based on the load
2858 average.  The @samp{-l} or @samp{--max-load}
2859 option is followed by a floating-point number.  For
2860 example,
2862 @example
2863 -l 2.5
2864 @end example
2866 @noindent
2867 will not let @code{make} start more than one job if the load average is
2868 above 2.5.  The @samp{-l} option with no following number removes the
2869 load limit, if one was given with a previous @samp{-l} option.@refill
2871 More precisely, when @code{make} goes to start up a job, and it already has
2872 at least one job running, it checks the current load average; if it is not
2873 lower than the limit given with @samp{-l}, @code{make} waits until the load
2874 average goes below that limit, or until all the other jobs finish.
2876 By default, there is no load limit.
2878 @node Errors, Interrupts, Parallel, Commands
2879 @section Errors in Commands
2880 @cindex errors (in commands)
2881 @cindex commands, errors in
2882 @cindex exit status (errors)
2884 After each shell command returns, @code{make} looks at its exit status.
2885 If the command completed successfully, the next command line is executed
2886 in a new shell; after the last command line is finished, the rule is
2887 finished. 
2889 If there is an error (the exit status is nonzero), @code{make} gives up on
2890 the current rule, and perhaps on all rules.
2892 Sometimes the failure of a certain command does not indicate a problem.
2893 For example, you may use the @code{mkdir} command to ensure that a
2894 directory exists.  If the directory already exists, @code{mkdir} will
2895 report an error, but you probably want @code{make} to continue regardless.
2897 @cindex @code{-} (in commands)
2898 To ignore errors in a command line, write a @samp{-} at the beginning of
2899 the line's text (after the initial tab).  The @samp{-} is discarded before
2900 the command is passed to the shell for execution.  
2902 For example,
2904 @example
2905 @group
2906 clean:
2907         -rm -f *.o
2908 @end group
2909 @end example
2910 @cindex @code{rm} (shell command)
2912 @noindent
2913 This causes @code{rm} to continue even if it is unable to remove a file.
2915 @cindex @code{-i}
2916 @cindex @code{--ignore-errors}
2917 @findex .IGNORE
2918 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
2919 flag, errors are ignored in all commands of all rules.  A rule in the
2920 makefile for the special target @code{.IGNORE} has the same effect, if
2921 there are no dependencies.  These ways of ignoring errors are obsolete
2922 because @samp{-} is more flexible.
2924 When errors are to be ignored, because of either a @samp{-} or the
2925 @samp{-i} flag, @code{make} treats an error return just like success,
2926 except that it prints out a message that tells you the status code
2927 the command exited with, and says that the error has been ignored.
2929 When an error happens that @code{make} has not been told to ignore,
2930 it implies that the current target cannot be correctly remade, and neither
2931 can any other that depends on it either directly or indirectly.  No further
2932 commands will be executed for these targets, since their preconditions
2933 have not been achieved.
2936 @cindex @code{-k}
2937 @cindex @code{--keep-going}
2938 Normally @code{make} gives up immediately in this circumstance, returning a
2939 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
2940 flag is specified, @code{make}
2941 continues to consider the other dependencies of the pending targets,
2942 remaking them if necessary, before it gives up and returns nonzero status.
2943 For example, after an error in compiling one object file, @samp{make -k}
2944 will continue compiling other object files even though it already knows
2945 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
2947 The usual behavior assumes that your purpose is to get the specified
2948 targets up to date; once @code{make} learns that this is impossible, it
2949 might as well report the failure immediately.  The @samp{-k} option says
2950 that the real purpose is to test as many of the changes made in the
2951 program as possible, perhaps to find several independent problems so
2952 that you can correct them all before the next attempt to compile.  This
2953 is why Emacs' @code{compile} command passes the @samp{-k} flag by
2954 default.
2955 @cindex Emacs (@code{M-x compile})
2957 @findex .DELETE_ON_ERROR
2958 @cindex deletion of target files
2959 @cindex removal of target files
2960 @cindex target, deleting on error
2961 Usually when a command fails, if it has changed the target file at all,
2962 the file is corrupted and cannot be used---or at least it is not
2963 completely updated.  Yet the file's timestamp says that it is now up to
2964 date, so the next time @code{make} runs, it will not try to update that
2965 file.  The situation is just the same as when the command is killed by a
2966 signal; @pxref{Interrupts}.  So generally the right thing to do is to
2967 delete the target file if the command fails after beginning to change
2968 the file.  @code{make} will do this if @code{.DELETE_ON_ERROR} appears
2969 as a target.  This is almost always what you want @code{make} to do, but
2970 it is not historical practice; so for compatibility, you must explicitly
2971 request it.
2973 @node Interrupts, Recursion, Errors, Commands
2974 @section Interrupting or Killing @code{make}
2975 @cindex interrupt
2976 @cindex signal
2977 @cindex deletion of target files
2978 @cindex removal of target files
2979 @cindex target, deleting on interrupt
2980 @cindex killing (interruption)
2982 If @code{make} gets a fatal signal while a command is executing, it may
2983 delete the target file that the command was supposed to update.  This is
2984 done if the target file's last-modification time has changed since
2985 @code{make} first checked it.
2987 The purpose of deleting the target is to make sure that it is remade from
2988 scratch when @code{make} is next run.  Why is this?  Suppose you type
2989 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
2990 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
2991 in an incomplete file whose last-modification time is newer than the source
2992 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
2993 and deletes this incomplete file.  If @code{make} did not do this, the next
2994 invocation of @code{make} would think that @file{foo.o} did not require
2995 updating---resulting in a strange error message from the linker when it
2996 tries to link an object file half of which is missing.
2998 @findex .PRECIOUS
2999 You can prevent the deletion of a target file in this way by making the
3000 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
3001 @code{make} checks to see whether it appears on the dependencies of
3002 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
3003 if a signal happens.  Some reasons why you might do this are that the
3004 target is updated in some atomic fashion, or exists only to record a
3005 modification-time (its contents do not matter), or must exist at all
3006 times to prevent other sorts of trouble.
3008 @node Recursion, Sequences, Interrupts, Commands
3009 @section Recursive Use of @code{make}
3010 @cindex recursion
3011 @cindex subdirectories, recursion for
3013 Recursive use of @code{make} means using @code{make} as a command in a
3014 makefile.  This technique is useful when you want separate makefiles for
3015 various subsystems that compose a larger system.  For example, suppose you
3016 have a subdirectory @file{subdir} which has its own makefile, and you would
3017 like the containing directory's makefile to run @code{make} on the
3018 subdirectory.  You can do it by writing this:
3020 @example
3021 subsystem:
3022         cd subdir; $(MAKE)
3023 @end example
3025 @noindent
3026 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
3028 @example
3029 subsystem:
3030         $(MAKE) -C subdir
3031 @end example
3032 @cindex @code{-C}
3033 @cindex @code{--directory}
3035 You can write recursive @code{make} commands just by copying this example,
3036 but there are many things to know about how they work and why, and about
3037 how the sub-@code{make} relates to the top-level @code{make}.
3039 @menu
3040 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
3041 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
3042 * Options/Recursion::           How to communicate options to a sub-@code{make}.
3043 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
3044                                  helps debug use of recursive @code{make} commands.
3045 @end menu
3047 @node MAKE Variable, Variables/Recursion,  , Recursion
3048 @subsection How the @code{MAKE} Variable Works
3049 @vindex MAKE
3050 @cindex recursion, and @code{MAKE} variable
3052 Recursive @code{make} commands should always use the variable @code{MAKE},
3053 not the explicit command name @samp{make}, as shown here:
3055 @example
3056 @group
3057 subsystem:
3058         cd subdir; $(MAKE)
3059 @end group
3060 @end example
3062 The value of this variable is the file name with which @code{make} was
3063 invoked.  If this file name was @file{/bin/make}, then the command executed
3064 is @samp{cd subdir; /bin/make}.  If you use a special version of
3065 @code{make} to run the top-level makefile, the same special version will be
3066 executed for recursive invocations.
3067 @cindex @code{cd} (shell command)
3069 As a special feature, using the variable @code{MAKE} in the commands of
3070 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
3071 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
3072 Using the @code{MAKE} variable has the same effect as using a @samp{+}
3073 character at the beginning of the command line.  @xref{Instead of
3074 Execution, ,Instead of Executing the Commands}.@refill
3076 Consider the command @samp{make -t} in the above example.  (The
3077 @samp{-t} option marks targets as up to date without actually running
3078 any commands; see @ref{Instead of Execution}.)  Following the usual
3079 definition of @samp{-t}, a @samp{make -t} command in the example would
3080 create a file named @file{subsystem} and do nothing else.  What you
3081 really want it to do is run @samp{@w{cd subdir;} @w{make -t}}; but that would
3082 require executing the command, and @samp{-t} says not to execute
3083 commands.@refill
3084 @cindex @code{-t}, and recursion
3085 @cindex recursion, and @code{-t}
3086 @cindex @code{--touch}, and recursion
3088 The special feature makes this do what you want: whenever a command
3089 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
3090 @samp{-n} and @samp{-q} do not apply to that line.  Command lines
3091 containing @code{MAKE} are executed normally despite the presence of a
3092 flag that causes most commands not to be run.  The usual
3093 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
3094 (@pxref{Options/Recursion, ,Communicating Options to a
3095 Sub-@code{make}}), so your request to touch the files, or print the
3096 commands, is propagated to the subsystem.@refill
3098 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
3099 @subsection Communicating Variables to a Sub-@code{make}
3100 @cindex sub-@code{make}
3101 @cindex environment, and recursion
3102 @cindex exporting variables
3103 @cindex variables, environment
3104 @cindex variables, exporting
3105 @cindex recursion, and environment
3106 @cindex recursion, and variables
3108 Variable values of the top-level @code{make} can be passed to the
3109 sub-@code{make} through the environment by explicit request.  These
3110 variables are defined in the sub-@code{make} as defaults, but do not
3111 override what is specified in the makefile used by the sub-@code{make}
3112 makefile unless you use the @samp{-e} switch (@pxref{Options Summary,
3113 ,Summary of Options}).@refill
3115 To pass down, or @dfn{export}, a variable, @code{make} adds the variable
3116 and its value to the environment for running each command.  The
3117 sub-@code{make}, in turn, uses the environment to initialize its table
3118 of variable values.  @xref{Environment, ,Variables from the
3119 Environment}.
3121 Except by explicit request, @code{make} exports a variable only if it
3122 is either defined in the environment initially or set on the command
3123 line, and if its name consists only of letters, numbers, and underscores.
3124 Some shells cannot cope with environment variable names consisting of
3125 characters other than letters, numbers, and underscores.
3127 The special variables @code{SHELL} and @code{MAKEFLAGS} are always
3128 exported (unless you unexport them).
3129 @code{MAKEFILES} is exported if you set it to anything.
3131 @code{make} automatically passes down variable values that were defined
3132 on the command line, by putting them in the @code{MAKEFLAGS} variable.
3133 @iftex
3134 See the next section.
3135 @end iftex
3136 @ifinfo
3137 @xref{Options/Recursion}.
3138 @end ifinfo
3140 Variables are @emph{not} normally passed down if they were created by
3141 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
3142 Implicit Rules}).  The sub-@code{make} will define these for
3143 itself.@refill
3145 @findex export
3146 If you want to export specific variables to a sub-@code{make}, use the
3147 @code{export} directive, like this:
3149 @example
3150 export @var{variable} @dots{}
3151 @end example
3153 @noindent
3154 @findex unexport
3155 If you want to @emph{prevent} a variable from being exported, use the
3156 @code{unexport} directive, like this:
3158 @example
3159 unexport @var{variable} @dots{}
3160 @end example
3162 @noindent
3163 As a convenience, you can define a variable and export it at the same
3164 time by doing:
3166 @example
3167 export @var{variable} = value
3168 @end example
3170 @noindent
3171 has the same result as:
3173 @example
3174 @var{variable} = value
3175 export @var{variable}
3176 @end example
3178 @noindent
3181 @example
3182 export @var{variable} := value
3183 @end example
3185 @noindent
3186 has the same result as:
3188 @example
3189 @var{variable} := value
3190 export @var{variable}
3191 @end example
3193 Likewise,
3195 @example
3196 export @var{variable} += value
3197 @end example
3199 @noindent
3200 is just like:
3202 @example
3203 @var{variable} += value
3204 export @var{variable}
3205 @end example
3207 @noindent
3208 @xref{Appending, ,Appending More Text to Variables}.
3210 You may notice that the @code{export} and @code{unexport} directives
3211 work in @code{make} in the same way they work in the shell, @code{sh}.
3213 If you want all variables to be exported by default, you can use
3214 @code{export} by itself:
3216 @example
3217 export
3218 @end example
3220 @noindent
3221 This tells @code{make} that variables which are not explicitly mentioned
3222 in an @code{export} or @code{unexport} directive should be exported.
3223 Any variable given in an @code{unexport} directive will still @emph{not}
3224 be exported.  If you use @code{export} by itself to export variables by
3225 default, variables whose names contain characters other than
3226 alphanumerics and underscores will not be exported unless specifically
3227 mentioned in an @code{export} directive.@refill
3229 @findex .EXPORT_ALL_VARIABLES
3230 The behavior elicited by an @code{export} directive by itself was the
3231 default in older versions of GNU @code{make}.  If your makefiles depend
3232 on this behavior and you want to be compatible with old versions of
3233 @code{make}, you can write a rule for the special target
3234 @code{.EXPORT_ALL_VARIABLES} instead of using the @code{export} directive.
3235 This will be ignored by old @code{make}s, while the @code{export}
3236 directive will cause a syntax error.@refill
3237 @cindex compatibility in exporting
3239 Likewise, you can use @code{unexport} by itself to tell @code{make}
3240 @emph{not} to export variables by default.  Since this is the default
3241 behavior, you would only need to do this if @code{export} had been used
3242 by itself earlier (in an included makefile, perhaps).  You
3243 @strong{cannot} use @code{export} and @code{unexport} by themselves to
3244 have variables exported for some commands and not for others.  The last
3245 @code{export} or @code{unexport} directive that appears by itself
3246 determines the behavior for the entire run of @code{make}.@refill
3248 @vindex MAKELEVEL
3249 @cindex recursion, level of
3250 As a special feature, the variable @code{MAKELEVEL} is changed when it
3251 is passed down from level to level.  This variable's value is a string
3252 which is the depth of the level as a decimal number.  The value is
3253 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
3254 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
3255 happens when @code{make} sets up the environment for a command.@refill
3257 The main use of @code{MAKELEVEL} is to test it in a conditional
3258 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
3259 way you can write a makefile that behaves one way if run recursively and
3260 another way if run directly by you.@refill
3262 @vindex MAKEFILES
3263 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
3264 commands to use additional makefiles.  The value of @code{MAKEFILES} is
3265 a whitespace-separated list of file names.  This variable, if defined in
3266 the outer-level makefile, is passed down through the environment; then
3267 it serves as a list of extra makefiles for the sub-@code{make} to read
3268 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
3269 Variable @code{MAKEFILES}}.@refill
3271 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
3272 @subsection Communicating Options to a Sub-@code{make}
3273 @cindex options, and recursion
3274 @cindex recursion, and options
3276 @vindex MAKEFLAGS
3277 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
3278 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
3279 set up automatically by @code{make} to contain the flag letters that
3280 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
3281 @code{MAKEFLAGS} gets the value @samp{ks}.@refill
3283 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
3284 in its environment.  In response, it takes the flags from that value and
3285 processes them as if they had been given as arguments.
3286 @xref{Options Summary, ,Summary of Options}.
3288 @cindex command line variable definitions, and recursion
3289 @cindex variables, command line, and recursion
3290 @cindex recursion, and command line variable definitions
3291 Likewise variables defined on the command line are passed to the
3292 sub-@code{make} through @code{MAKEFLAGS}.  Words in the value of
3293 @code{MAKEFLAGS} that contain @samp{=}, @code{make} treats as variable
3294 definitions just as if they appeared on the command line.
3295 @xref{Overriding, ,Overriding Variables}.
3297 @cindex @code{-C}, and recursion
3298 @cindex @code{-f}, and recursion
3299 @cindex @code{-o}, and recursion
3300 @cindex @code{-W}, and recursion
3301 @cindex @code{--directory}, and recursion
3302 @cindex @code{--file}, and recursion
3303 @cindex @code{--old-file}, and recursion
3304 @cindex @code{--assume-old}, and recursion
3305 @cindex @code{--assume-new}, and recursion
3306 @cindex @code{--new-file}, and recursion
3307 @cindex recursion, and @code{-C}
3308 @cindex recursion, and @code{-f}
3309 @cindex recursion, and @code{-o}
3310 @cindex recursion, and @code{-W}
3311 The options @samp{-C}, @samp{-f}, @samp{-o}, and @samp{-W} are not put
3312 into @code{MAKEFLAGS}; these options are not passed down.@refill
3314 @cindex @code{-j}, and recursion
3315 @cindex @code{--jobs}, and recursion
3316 @cindex recursion, and @code{-j}
3317 @cindex job slots, and recursion
3318 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
3319 If you set it to some numeric value, @samp{-j 1} is always put into
3320 @code{MAKEFLAGS} instead of the value you specified.  This is because if
3321 the @w{@samp{-j}} option were passed down to sub-@code{make}s, you would
3322 get many more jobs running in parallel than you asked for.  If you give
3323 @samp{-j} with no numeric argument, meaning to run as many jobs as
3324 possible in parallel, this is passed down, since multiple infinities are
3325 no more than one.@refill
3327 If you do not want to pass the other flags down, you must change the
3328 value of @code{MAKEFLAGS}, like this:
3330 @example
3331 MAKEFLAGS=
3332 subsystem:
3333         cd subdir; $(MAKE)
3334 @end example
3336 or like this:
3338 @example
3339 subsystem:
3340         cd subdir; $(MAKE) MAKEFLAGS=
3341 @end example
3343 @vindex MAKEOVERRIDES
3344 The command line variable definitions really appear in the variable
3345 @code{MAKEOVERRIDES}, and @code{MAKEFLAGS} contains a reference to this
3346 variable.  If you do want to pass flags down normally, but don't want to
3347 pass down the command line variable definitions, you can reset
3348 @code{MAKEOVERRIDES} to empty, like this:
3350 @example
3351 MAKEOVERRIDES =
3352 @end example
3354 @noindent
3355 @cindex Arg list too long
3356 @cindex E2BIG
3357 This is not usually useful to do.  However, some systems have a small
3358 fixed limit on the size of the environment, and putting so much
3359 information in into the value of @code{MAKEFLAGS} can exceed it.
3360 If you see the error message @samp{Arg list too long}, this may be the problem.
3361 @findex .POSIX
3362 @cindex POSIX.2
3363 (For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
3364 not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
3365 in the makefile.  You probably do not care about this.)
3367 @vindex MFLAGS
3368 A similar variable @code{MFLAGS} exists also, for historical
3369 compatibility.  It has the same value as @code{MAKEFLAGS} except that it
3370 does not contain the command line variable definitions, and it always
3371 begins with a hyphen unless it is empty (@code{MAKEFLAGS} begins with a
3372 hyphen only when it begins with an option that has no single-letter
3373 version, such as @samp{--warn-undefined-variables}).  @code{MFLAGS} was
3374 traditionally used explicitly in the recursive @code{make} command, like
3375 this:
3377 @example
3378 subsystem:
3379         cd subdir; $(MAKE) $(MFLAGS)
3380 @end example
3382 @noindent
3383 but now @code{MAKEFLAGS} makes this usage redundant.  If you want your
3384 makefiles to be compatible with old @code{make} programs, use this
3385 technique; it will work fine with more modern @code{make} versions too.
3387 @cindex setting options from environment
3388 @cindex options, setting from environment
3389 @cindex setting options in makefiles
3390 @cindex options, setting in makefiles
3391 The @code{MAKEFLAGS} variable can also be useful if you want to have
3392 certain options, such as @samp{-k} (@pxref{Options Summary, ,Summary of
3393 Options}), set each time you run @code{make}.  You simply put a value for
3394 @code{MAKEFLAGS} in your environment.  You can also set @code{MAKEFLAGS} in
3395 a makefile, to specify additional flags that should also be in effect for
3396 that makefile.  (Note that you cannot use @code{MFLAGS} this way.  That
3397 variable is set only for compatibility; @code{make} does not interpret a
3398 value you set for it in any way.)
3400 When @code{make} interprets the value of @code{MAKEFLAGS} (either from the
3401 environment or from a makefile), it first prepends a hyphen if the value
3402 does not already begin with one.  Then it chops the value into words
3403 separated by blanks, and parses these words as if they were options given
3404 on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
3405 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
3406 is no error for an invalid option).
3408 If you do put @code{MAKEFLAGS} in your environment, you should be sure not
3409 to include any options that will drastically affect the actions of
3410 @code{make} and undermine the purpose of makefiles and of @code{make}
3411 itself.  For instance, the @samp{-t}, @samp{-n}, and @samp{-q} options, if
3412 put in one of these variables, could have disastrous consequences and would
3413 certainly have at least surprising and probably annoying effects.@refill
3415 @node -w Option,  , Options/Recursion, Recursion
3416 @subsection The @samp{--print-directory} Option
3417 @cindex directories, printing them
3418 @cindex printing directories
3419 @cindex recursion, and printing directories
3421 If you use several levels of recursive @code{make} invocations, the
3422 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
3423 lot easier to understand by showing each directory as @code{make}
3424 starts processing it and as @code{make} finishes processing it.  For
3425 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
3426 @code{make} will print a line of the form:@refill
3428 @example
3429 make: Entering directory `/u/gnu/make'.
3430 @end example
3432 @noindent
3433 before doing anything else, and a line of the form:
3435 @example
3436 make: Leaving directory `/u/gnu/make'.
3437 @end example
3439 @noindent
3440 when processing is completed.
3442 @cindex @code{-C}, and @code{-w}
3443 @cindex @code{--directory}, and @code{--print-directory}
3444 @cindex recursion, and @code{-w}
3445 @cindex @code{-w}, and @code{-C}
3446 @cindex @code{-w}, and recursion
3447 @cindex @code{--print-directory}, and @code{--directory}
3448 @cindex @code{--print-directory}, and recursion
3449 @cindex @code{--no-print-directory}
3450 @cindex @code{--print-directory}, disabling
3451 @cindex @code{-w}, disabling
3452 Normally, you do not need to specify this option because @samp{make}
3453 does it for you: @samp{-w} is turned on automatically when you use the
3454 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
3455 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
3456 be silent, or if you use @samp{--no-print-directory} to explicitly
3457 disable it.
3459 @node Sequences, Empty Commands, Recursion, Commands
3460 @section Defining Canned Command Sequences
3461 @cindex sequences of commands
3462 @cindex commands, sequences of
3464 When the same sequence of commands is useful in making various targets, you
3465 can define it as a canned sequence with the @code{define} directive, and
3466 refer to the canned sequence from the rules for those targets.  The canned
3467 sequence is actually a variable, so the name must not conflict with other
3468 variable names.
3470 Here is an example of defining a canned sequence of commands:
3472 @example
3473 define run-yacc
3474 yacc $(firstword $^)
3475 mv y.tab.c $@@
3476 endef
3477 @end example
3478 @cindex @code{yacc}
3480 @noindent
3481 Here @code{run-yacc} is the name of the variable being defined;
3482 @code{endef} marks the end of the definition; the lines in between are the
3483 commands.  The @code{define} directive does not expand variable references
3484 and function calls in the canned sequence; the @samp{$} characters,
3485 parentheses, variable names, and so on, all become part of the value of the
3486 variable you are defining.
3487 @xref{Defining, ,Defining Variables Verbatim},
3488 for a complete explanation of @code{define}.
3490 The first command in this example runs Yacc on the first dependency of
3491 whichever rule uses the canned sequence.  The output file from Yacc is
3492 always named @file{y.tab.c}.  The second command moves the output to the
3493 rule's target file name.
3495 To use the canned sequence, substitute the variable into the commands of a
3496 rule.  You can substitute it like any other variable 
3497 (@pxref{Reference, ,Basics of Variable References}).
3498 Because variables defined by @code{define} are recursively expanded
3499 variables, all the variable references you wrote inside the @code{define}
3500 are expanded now.  For example:
3502 @example
3503 foo.c : foo.y
3504         $(run-yacc)
3505 @end example
3507 @noindent
3508 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
3509 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.@refill
3511 This is a realistic example, but this particular one is not needed in
3512 practice because @code{make} has an implicit rule to figure out these
3513 commands based on the file names involved 
3514 (@pxref{Implicit Rules, ,Using Implicit Rules}).
3516 @cindex @@, and @code{define}
3517 @cindex -, and @code{define}
3518 @cindex +, and @code{define}
3519 In command execution, each line of a canned sequence is treated just as
3520 if the line appeared on its own in the rule, preceded by a tab.  In
3521 particular, @code{make} invokes a separate subshell for each line.  You
3522 can use the special prefix characters that affect command lines
3523 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
3524 @xref{Commands, ,Writing the Commands in Rules}.
3525 For example, using this canned sequence:
3527 @example
3528 define frobnicate
3529 @@echo "frobnicating target $@@"
3530 frob-step-1 $< -o $@@-step-1
3531 frob-step-2 $@@-step-1 -o $@@
3532 endef
3533 @end example
3535 @noindent
3536 @code{make} will not echo the first line, the @code{echo} command.
3537 But it @emph{will} echo the following two command lines.
3539 On the other hand, prefix characters on the command line that refers to
3540 a canned sequence apply to every line in the sequence.  So the rule:
3542 @example
3543 frob.out: frob.in
3544         @@$(frobnicate)
3545 @end example
3547 @noindent
3548 does not echo @emph{any} commands.
3549 (@xref{Echoing, ,Command Echoing}, for a full explanation of @samp{@@}.)
3551 @node Empty Commands,  , Sequences, Commands
3552 @section Using Empty Commands
3553 @cindex empty commands
3554 @cindex commands, empty
3556 It is sometimes useful to define commands which do nothing.  This is done
3557 simply by giving a command that consists of nothing but whitespace.  For
3558 example:
3560 @example
3561 target: ;
3562 @end example
3564 @noindent
3565 defines an empty command string for @file{target}.  You could also use a
3566 line beginning with a tab character to define an empty command string,
3567 but this would be confusing because such a line looks empty.
3569 @findex .DEFAULT@r{, and empty commands}
3570 You may be wondering why you would want to define a command string that
3571 does nothing.  The only reason this is useful is to prevent a target
3572 from getting implicit commands (from implicit rules or the
3573 @code{.DEFAULT} special target; @pxref{Implicit Rules} and 
3574 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
3576 You may be inclined to define empty command strings for targets that are
3577 not actual files, but only exist so that their dependencies can be
3578 remade.  However, this is not the best way to do that, because the
3579 dependencies may not be remade properly if the target file actually does exist.
3580 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
3582 @node Using Variables, Conditionals, Commands, Top
3583 @chapter How to Use Variables
3584 @cindex variable
3585 @cindex value
3586 @cindex recursive variable expansion
3587 @cindex simple variable expansion
3589 A @dfn{variable} is a name defined in a makefile to represent a string
3590 of text, called the variable's @dfn{value}.  These values are
3591 substituted by explicit request into targets, dependencies, commands,
3592 and other parts of the makefile.  (In some other versions of @code{make},
3593 variables are called @dfn{macros}.)
3594 @cindex macro
3596 Variables and functions in all parts of a makefile are expanded when
3597 read, except for the shell commands in rules, the right-hand sides of
3598 variable definitions using @samp{=}, and the bodies of variable
3599 definitions using the @code{define} directive.@refill
3601 Variables can represent lists of file names, options to pass to compilers,
3602 programs to run, directories to look in for source files, directories to
3603 write output in, or anything else you can imagine.
3605 A variable name may be any sequence of characters not containing @samp{:},
3606 @samp{#}, @samp{=}, or leading or trailing whitespace.  However,
3607 variable names containing characters other than letters, numbers, and
3608 underscores should be avoided, as they may be given special meanings in the
3609 future, and with some shells they cannot be passed through the environment to a
3610 sub-@code{make} 
3611 (@pxref{Variables/Recursion, ,Communicating Variables to a Sub-@code{make}}).
3613 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
3614 and @samp{Foo} all refer to different variables.
3616 It is traditional to use upper case letters in variable names, but we
3617 recommend using lower case letters for variable names that serve internal
3618 purposes in the makefile, and reserving upper case for parameters that
3619 control implicit rules or for parameters that the user should override with
3620 command options (@pxref{Overriding, ,Overriding Variables}).
3622 A few variables have names that are a single punctuation character or
3623 just a few characters.  These are the @dfn{automatic variables}, and
3624 they have particular specialized uses.  @xref{Automatic, ,Automatic Variables}.
3626 @menu
3627 * Reference::                   How to use the value of a variable.
3628 * Flavors::                     Variables come in two flavors.
3629 * Advanced::                    Advanced features for referencing a variable.
3630 * Values::                      All the ways variables get their values.
3631 * Setting::                     How to set a variable in the makefile.
3632 * Appending::                   How to append more text to the old value
3633                                   of a variable.
3634 * Override Directive::          How to set a variable in the makefile even if
3635                                   the user has set it with a command argument.
3636 * Defining::                    An alternate way to set a variable 
3637                                   to a verbatim string.
3638 * Environment::                 Variable values can come from the environment.
3639 * Automatic::                   Some special variables have predefined
3640                                   meanings for use with implicit rules.
3641 @end menu
3643 @node Reference, Flavors,  , Using Variables
3644 @section Basics of Variable References
3645 @cindex variables, how to reference
3646 @cindex reference to variables
3647 @cindex @code{$}, in variable reference
3648 @cindex dollar sign (@code{$}), in variable reference
3650 To substitute a variable's value, write a dollar sign followed by the name
3651 of the variable in parentheses or braces: either @samp{$(foo)} or
3652 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
3653 special significance of @samp{$} is why you must write @samp{$$} to have
3654 the effect of a single dollar sign in a file name or command.
3656 Variable references can be used in any context: targets, dependencies,
3657 commands, most directives, and new variable values.  Here is an
3658 example of a common case, where a variable holds the names of all the
3659 object files in a program:
3661 @example
3662 @group
3663 objects = program.o foo.o utils.o
3664 program : $(objects)
3665         cc -o program $(objects)
3667 $(objects) : defs.h
3668 @end group
3669 @end example
3671 Variable references work by strict textual substitution.  Thus, the rule
3673 @example
3674 @group
3675 foo = c
3676 prog.o : prog.$(foo)
3677         $(foo)$(foo) -$(foo) prog.$(foo)
3678 @end group
3679 @end example
3681 @noindent
3682 could be used to compile a C program @file{prog.c}.  Since spaces before
3683 the variable value are ignored in variable assignments, the value of
3684 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
3685 this way!)
3687 A dollar sign followed by a character other than a dollar sign,
3688 open-parenthesis or open-brace treats that single character as the
3689 variable name.  Thus, you could reference the variable @code{x} with
3690 @samp{$x}.  However, this practice is strongly discouraged, except in
3691 the case of the automatic variables (@pxref{Automatic, ,Automatic Variables}).
3693 @node Flavors, Advanced, Reference, Using Variables
3694 @section The Two Flavors of Variables
3695 @cindex flavors of variables
3696 @cindex recursive variable expansion
3697 @cindex variables, flavors
3698 @cindex recursively expanded variables
3699 @cindex variables, recursively expanded
3701 There are two ways that a variable in GNU @code{make} can have a value;
3702 we call them the two @dfn{flavors} of variables.  The two flavors are
3703 distinguished in how they are defined and in what they do when expanded.
3705 @cindex =
3706 The first flavor of variable is a @dfn{recursively expanded} variable.
3707 Variables of this sort are defined by lines using @samp{=}
3708 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
3709 (@pxref{Defining, ,Defining Variables Verbatim}).  The value you specify
3710 is installed verbatim; if it contains references to other variables,
3711 these references are expanded whenever this variable is substituted (in
3712 the course of expanding some other string).  When this happens, it is
3713 called @dfn{recursive expansion}.@refill
3715 For example,
3717 @example
3718 foo = $(bar)
3719 bar = $(ugh)
3720 ugh = Huh?
3722 all:;echo $(foo)
3723 @end example
3725 @noindent
3726 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
3727 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
3729 This flavor of variable is the only sort supported by other versions of
3730 @code{make}.  It has its advantages and its disadvantages.  An advantage
3731 (most would say) is that:
3733 @example
3734 CFLAGS = $(include_dirs) -O
3735 include_dirs = -Ifoo -Ibar
3736 @end example
3738 @noindent
3739 will do what was intended: when @samp{CFLAGS} is expanded in a command,
3740 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
3741 cannot append something on the end of a variable, as in
3743 @example
3744 CFLAGS = $(CFLAGS) -O
3745 @end example
3747 @noindent
3748 because it will cause an infinite loop in the variable expansion.
3749 (Actually @code{make} detects the infinite loop and reports an error.)
3750 @cindex loops in variable expansion
3751 @cindex variables, loops in expansion
3753 Another disadvantage is that any functions 
3754 (@pxref{Functions, ,Functions for Transforming Text})
3755 referenced in the definition will be executed every time the variable is
3756 expanded.  This makes @code{make} run slower; worse, it causes the
3757 @code{wildcard} and @code{shell} functions to give unpredictable results
3758 because you cannot easily control when they are called, or even how many
3759 times.
3761 To avoid all the problems and inconveniences of recursively expanded
3762 variables, there is another flavor: simply expanded variables.
3764 @cindex simply expanded variables
3765 @cindex variables, simply expanded
3766 @cindex :=
3767 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
3768 (@pxref{Setting, ,Setting Variables}).  
3769 The value of a simply expanded variable is scanned
3770 once and for all, expanding any references to other variables and
3771 functions, when the variable is defined.  The actual value of the simply
3772 expanded variable is the result of expanding the text that you write.
3773 It does not contain any references to other variables; it contains their
3774 values @emph{as of the time this variable was defined}.  Therefore,
3776 @example
3777 x := foo
3778 y := $(x) bar
3779 x := later
3780 @end example
3782 @noindent
3783 is equivalent to
3785 @example
3786 y := foo bar
3787 x := later
3788 @end example
3790 When a simply expanded variable is referenced, its value is substituted
3791 verbatim.
3793 Here is a somewhat more complicated example, illustrating the use of
3794 @samp{:=} in conjunction with the @code{shell} function.
3795 (@xref{Shell Function, , The @code{shell} Function}.)  This example
3796 also shows use of the variable @code{MAKELEVEL}, which is changed
3797 when it is passed down from level to level.
3798 (@xref{Variables/Recursion, , Communicating Variables to a
3799 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
3801 @vindex MAKELEVEL
3802 @vindex MAKE
3803 @example
3804 @group
3805 ifeq (0,$@{MAKELEVEL@})
3806 cur-dir   := $(shell pwd)
3807 whoami    := $(shell whoami)
3808 host-type := $(shell arch)
3809 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
3810 endif
3811 @end group
3812 @end example
3814 @noindent 
3815 An advantage of this use of @samp{:=} is that a typical
3816 `descend into a directory' command then looks like this:
3818 @example
3819 @group
3820 $@{subdirs@}:
3821       $@{MAKE@} cur-dir=$@{cur-dir@}/$@@ -C $@@ all
3822 @end group
3823 @end example
3825 Simply expanded variables generally make complicated makefile programming
3826 more predictable because they work like variables in most programming
3827 languages.  They allow you to redefine a variable using its own value (or
3828 its value processed in some way by one of the expansion functions) and to
3829 use the expansion functions much more efficiently 
3830 (@pxref{Functions, ,Functions for Transforming Text}).
3832 @cindex spaces, in variable values
3833 @cindex whitespace, in variable values
3834 @cindex variables, spaces in values
3835 You can also use them to introduce controlled leading whitespace into
3836 variable values.  Leading whitespace characters are discarded from your
3837 input before substitution of variable references and function calls;
3838 this means you can include leading spaces in a variable value by
3839 protecting them with variable references, like this:
3841 @example
3842 nullstring :=
3843 space := $(nullstring) # end of the line
3844 @end example
3846 @noindent
3847 Here the value of the variable @code{space} is precisely one space.  The
3848 comment @w{@samp{# end of the line}} is included here just for clarity.
3849 Since trailing space characters are @emph{not} stripped from variable
3850 values, just a space at the end of the line would have the same effect
3851 (but be rather hard to read).  If you put whitespace at the end of a
3852 variable value, it is a good idea to put a comment like that at the end
3853 of the line to make your intent clear.  Conversely, if you do @emph{not}
3854 want any whitespace characters at the end of your variable value, you
3855 must remember not to put a random comment on the end of the line after
3856 some whitespace, such as this:
3858 @example
3859 dir := /foo/bar    # directory to put the frobs in
3860 @end example
3862 @noindent
3863 Here the value of the variable @code{dir} is @w{@samp{/foo/bar    }}
3864 (with four trailing spaces), which was probably not the intention.
3865 (Imagine something like @w{@samp{$(dir)/file}} with this definition!)
3867 @node Advanced, Values, Flavors, Using Variables
3868 @section Advanced Features for Reference to Variables
3869 @cindex reference to variables
3871 This section describes some advanced features you can use to reference
3872 variables in more flexible ways.
3874 @menu
3875 * Substitution Refs::           Referencing a variable with 
3876                                   substitutions on the value.
3877 * Computed Names::              Computing the name of the variable to refer to.
3878 @end menu
3880 @node Substitution Refs, Computed Names,  , Advanced
3881 @subsection Substitution References
3882 @cindex modified variable reference
3883 @cindex substitution variable reference
3884 @cindex variables, modified reference
3885 @cindex variables, substitution reference
3887 @cindex variables, substituting suffix in
3888 @cindex suffix, substituting in variables
3889 A @dfn{substitution reference} substitutes the value of a variable with
3890 alterations that you specify.  It has the form
3891 @samp{$(@var{var}:@var{a}=@var{b})} (or
3892 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
3893 of the variable @var{var}, replace every @var{a} at the end of a word with
3894 @var{b} in that value, and substitute the resulting string.
3896 When we say ``at the end of a word'', we mean that @var{a} must appear
3897 either followed by whitespace or at the end of the value in order to be
3898 replaced; other occurrences of @var{a} in the value are unaltered.  For
3899 example:@refill
3901 @example
3902 foo := a.o b.o c.o
3903 bar := $(foo:.o=.c)
3904 @end example
3906 @noindent
3907 sets @samp{bar} to @samp{a.c b.c c.c}.  @xref{Setting, ,Setting Variables}.
3909 A substitution reference is actually an abbreviation for use of the
3910 @code{patsubst} expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}).  We provide
3911 substitution references as well as @code{patsubst} for compatibility with
3912 other implementations of @code{make}.
3914 @findex patsubst
3915 Another type of substitution reference lets you use the full power of
3916 the @code{patsubst} function.  It has the same form
3917 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
3918 @var{a} must contain a single @samp{%} character.  This case is
3919 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
3920 @xref{Text Functions, ,Functions for String Substitution and Analysis},
3921 for a description of the @code{patsubst} function.@refill
3923 @example
3924 @group
3925 @exdent For example:
3927 foo := a.o b.o c.o
3928 bar := $(foo:%.o=%.c)
3929 @end group
3930 @end example
3932 @noindent
3933 sets @samp{bar} to @samp{a.c b.c c.c}.
3935 @node Computed Names,  , Substitution Refs, Advanced
3936 @subsection Computed Variable Names
3937 @cindex nested variable reference
3938 @cindex computed variable name
3939 @cindex variables, computed names
3940 @cindex variables, nested references
3941 @cindex variables, @samp{$} in name
3942 @cindex @code{$}, in variable name
3943 @cindex dollar sign (@code{$}), in variable name
3945 Computed variable names are a complicated concept needed only for
3946 sophisticated makefile programming.  For most purposes you need not
3947 consider them, except to know that making a variable with a dollar sign
3948 in its name might have strange results.  However, if you are the type
3949 that wants to understand everything, or you are actually interested in
3950 what they do, read on.
3952 Variables may be referenced inside the name of a variable.  This is
3953 called a @dfn{computed variable name} or a @dfn{nested variable
3954 reference}.  For example,
3956 @example
3957 x = y
3958 y = z
3959 a := $($(x))
3960 @end example
3962 @noindent
3963 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
3964 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
3965 to @samp{z}.  Here the name of the variable to reference is not stated
3966 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
3967 @samp{$(x)} here is nested within the outer variable reference.
3969 The previous example shows two levels of nesting, but any number of levels
3970 is possible.  For example, here are three levels:
3972 @example
3973 x = y
3974 y = z
3975 z = u
3976 a := $($($(x)))
3977 @end example
3979 @noindent
3980 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
3981 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
3982 @samp{$(z)}, which becomes @samp{u}.
3984 References to recursively-expanded variables within a variable name are
3985 reexpanded in the usual fashion.  For example:
3987 @example
3988 x = $(y)
3989 y = z
3990 z = Hello
3991 a := $($(x))
3992 @end example
3994 @noindent
3995 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
3996 which becomes @samp{$(z)} which becomes @samp{Hello}.
3998 Nested variable references can also contain modified references and
3999 function invocations (@pxref{Functions, ,Functions for Transforming Text}),
4000 just like any other reference.
4001 For example, using the @code{subst} function 
4002 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
4004 @example
4005 @group
4006 x = variable1
4007 variable2 := Hello
4008 y = $(subst 1,2,$(x))
4009 z = y
4010 a := $($($(z)))
4011 @end group
4012 @end example
4014 @noindent
4015 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
4016 would ever want to write a nested reference as convoluted as this one, but
4017 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
4018 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
4019 @code{x} and changes it by substitution to @samp{variable2}, so that the
4020 entire string becomes @samp{$(variable2)}, a simple variable reference
4021 whose value is @samp{Hello}.@refill
4023 A computed variable name need not consist entirely of a single variable
4024 reference.  It can contain several variable references, as well as some
4025 invariant text.  For example,
4027 @example
4028 @group
4029 a_dirs := dira dirb
4030 1_dirs := dir1 dir2
4031 @end group
4033 @group
4034 a_files := filea fileb
4035 1_files := file1 file2
4036 @end group
4038 @group
4039 ifeq "$(use_a)" "yes"
4040 a1 := a
4041 else
4042 a1 := 1
4043 endif
4044 @end group
4046 @group
4047 ifeq "$(use_dirs)" "yes"
4048 df := dirs
4049 else
4050 df := files
4051 endif
4053 dirs := $($(a1)_$(df))
4054 @end group
4055 @end example
4057 @noindent
4058 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
4059 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
4060 and @code{use_dirs}.@refill
4062 Computed variable names can also be used in substitution references:
4064 @example
4065 @group
4066 a_objects := a.o b.o c.o
4067 1_objects := 1.o 2.o 3.o
4069 sources := $($(a1)_objects:.o=.c)
4070 @end group
4071 @end example
4073 @noindent
4074 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
4075 depending on the value of @code{a1}.
4077 The only restriction on this sort of use of nested variable references
4078 is that they cannot specify part of the name of a function to be called.
4079 This is because the test for a recognized function name is done before
4080 the expansion of nested references.  For example,
4082 @example
4083 @group
4084 ifdef do_sort
4085 func := sort
4086 else
4087 func := strip
4088 endif
4089 @end group
4091 @group
4092 bar := a d b g q c
4093 @end group
4095 @group
4096 foo := $($(func) $(bar))
4097 @end group
4098 @end example
4100 @noindent
4101 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
4102 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
4103 as the argument to either the @code{sort} or the @code{strip} function.
4104 This restriction could be removed in the future if that change is shown
4105 to be a good idea.
4107 You can also use computed variable names in the left-hand side of a
4108 variable assignment, or in a @code{define} directive, as in:
4110 @example
4111 dir = foo
4112 $(dir)_sources := $(wildcard $(dir)/*.c)
4113 define $(dir)_print
4114 lpr $($(dir)_sources)
4115 endef
4116 @end example
4118 @noindent
4119 This example defines the variables @samp{dir}, @samp{foo_sources}, and
4120 @samp{foo_print}.
4122 Note that @dfn{nested variable references} are quite different from
4123 @dfn{recursively expanded variables}
4124 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
4125 used together in complex ways when doing makefile programming.@refill
4127 @node Values, Setting, Advanced, Using Variables
4128 @section How Variables Get Their Values
4129 @cindex variables, how they get their values
4130 @cindex value, how a variable gets it
4132 Variables can get values in several different ways:
4134 @itemize @bullet
4135 @item
4136 You can specify an overriding value when you run @code{make}.
4137 @xref{Overriding, ,Overriding Variables}.
4139 @item
4140 You can specify a value in the makefile, either
4141 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
4142 verbatim definition (@pxref{Defining, ,Defining Variables Verbatim}).@refill
4144 @item
4145 Variables in the environment become @code{make} variables.
4146 @xref{Environment, ,Variables from the Environment}.
4148 @item
4149 Several @dfn{automatic} variables are given new values for each rule.
4150 Each of these has a single conventional use.
4151 @xref{Automatic, ,Automatic Variables}.
4153 @item
4154 Several variables have constant initial values.
4155 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
4156 @end itemize
4158 @node Setting, Appending, Values, Using Variables
4159 @section Setting Variables
4160 @cindex setting variables
4161 @cindex variables, setting
4162 @cindex =
4163 @cindex :=
4165 To set a variable from the makefile, write a line starting with the
4166 variable name followed by @samp{=} or @samp{:=}.  Whatever follows the
4167 @samp{=} or @samp{:=} on the line becomes the value.  For example,
4169 @example
4170 objects = main.o foo.o bar.o utils.o
4171 @end example
4173 @noindent
4174 defines a variable named @code{objects}.  Whitespace around the variable
4175 name and immediately after the @samp{=} is ignored.
4177 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
4178 Variables defined with @samp{:=} are @dfn{simply expanded} variables; these
4179 definitions can contain variable references which will be expanded before
4180 the definition is made.  @xref{Flavors, ,The Two Flavors of Variables}.
4182 The variable name may contain function and variable references, which
4183 are expanded when the line is read to find the actual variable name to use.
4185 There is no limit on the length of the value of a variable except the
4186 amount of swapping space on the computer.  When a variable definition is
4187 long, it is a good idea to break it into several lines by inserting
4188 backslash-newline at convenient places in the definition.  This will not
4189 affect the functioning of @code{make}, but it will make the makefile easier
4190 to read.
4192 Most variable names are considered to have the empty string as a value if
4193 you have never set them.  Several variables have built-in initial values
4194 that are not empty, but you can set them in the usual ways
4195 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).  
4196 Several special variables are set
4197 automatically to a new value for each rule; these are called the
4198 @dfn{automatic} variables (@pxref{Automatic, ,Automatic Variables}).
4200 @node Appending, Override Directive, Setting, Using Variables
4201 @section Appending More Text to Variables
4202 @cindex +=
4203 @cindex appending to variables
4204 @cindex variables, appending to
4206 Often it is useful to add more text to the value of a variable already defined.
4207 You do this with a line containing @samp{+=}, like this:
4209 @example
4210 objects += another.o
4211 @end example
4213 @noindent
4214 This takes the value of the variable @code{objects}, and adds the text
4215 @samp{another.o} to it (preceded by a single space).  Thus:
4217 @example
4218 objects = main.o foo.o bar.o utils.o
4219 objects += another.o
4220 @end example
4222 @noindent
4223 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
4225 Using @samp{+=} is similar to:
4227 @example
4228 objects = main.o foo.o bar.o utils.o
4229 objects := $(objects) another.o
4230 @end example
4232 @noindent
4233 but differs in ways that become important when you use more complex values.
4235 When the variable in question has not been defined before, @samp{+=}
4236 acts just like normal @samp{=}: it defines a recursively-expanded
4237 variable.  However, when there @emph{is} a previous definition, exactly
4238 what @samp{+=} does depends on what flavor of variable you defined
4239 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
4240 explanation of the two flavors of variables.
4242 When you add to a variable's value with @samp{+=}, @code{make} acts
4243 essentially as if you had included the extra text in the initial
4244 definition of the variable.  If you defined it first with @samp{:=},
4245 making it a simply-expanded variable, @samp{+=} adds to that
4246 simply-expanded definition, and expands the new text before appending it
4247 to the old value just as @samp{:=} does
4248 (@pxref{Setting, ,Setting Variables}, for a full explanation of @samp{:=}).
4249 In fact,
4251 @example
4252 variable := value
4253 variable += more
4254 @end example
4256 @noindent
4257 is exactly equivalent to:
4259 @noindent
4260 @example
4261 variable := value
4262 variable := $(variable) more
4263 @end example
4265 On the other hand, when you use @samp{+=} with a variable that you defined
4266 first to be recursively-expanded using plain @samp{=}, @code{make} does
4267 something a bit different.  Recall that when you define a
4268 recursively-expanded variable, @code{make} does not expand the value you set
4269 for variable and function references immediately.  Instead it stores the text
4270 verbatim, and saves these variable and function references to be expanded
4271 later, when you refer to the new variable (@pxref{Flavors, ,The Two Flavors
4272 of Variables}).  When you use @samp{+=} on a recursively-expanded variable,
4273 it is this unexpanded text to which @code{make} appends the new text you
4274 specify.
4276 @example
4277 @group
4278 variable = value
4279 variable += more
4280 @end group
4281 @end example
4283 @noindent
4284 is roughly equivalent to:
4286 @example
4287 @group
4288 temp = value
4289 variable = $(temp) more
4290 @end group
4291 @end example
4293 @noindent
4294 except that of course it never defines a variable called @code{temp}.
4295 The importance of this comes when the variable's old value contains
4296 variable references.  Take this common example:
4298 @example
4299 CFLAGS = $(includes) -O
4300 @dots{}
4301 CFLAGS += -pg # enable profiling
4302 @end example
4304 @noindent
4305 The first line defines the @code{CFLAGS} variable with a reference to another
4306 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
4307 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
4308 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
4309 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
4310 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
4311 need not be defined yet for its value to take effect.  It only has to be
4312 defined before any reference to @code{CFLAGS}.  If we tried to append to the
4313 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
4315 @example
4316 CFLAGS := $(CFLAGS) -pg # enable profiling
4317 @end example
4319 @noindent
4320 This is pretty close, but not quite what we want.  Using @samp{:=}
4321 redefines @code{CFLAGS} as a simply-expanded variable; this means
4322 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
4323 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
4324 -pg}}, and a later definition of @code{includes} will have no effect.
4325 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
4326 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
4327 the reference to @code{includes}, so if that variable gets defined at
4328 any later point, a reference like @samp{$(CFLAGS)} still uses its
4329 value.
4331 @node Override Directive, Defining, Appending, Using Variables
4332 @section The @code{override} Directive
4333 @findex override
4334 @cindex overriding with @code{override}
4335 @cindex variables, overriding
4337 If a variable has been set with a command argument 
4338 (@pxref{Overriding, ,Overriding Variables}),
4339 then ordinary assignments in the makefile are ignored.  If you want to set
4340 the variable in the makefile even though it was set with a command
4341 argument, you can use an @code{override} directive, which is a line that
4342 looks like this:@refill
4344 @example
4345 override @var{variable} = @var{value}
4346 @end example
4348 @noindent
4351 @example
4352 override @var{variable} := @var{value}
4353 @end example
4355 To append more text to a variable defined on the command line, use:
4357 @example
4358 override @var{variable} += @var{more text}
4359 @end example
4361 @noindent
4362 @xref{Appending, ,Appending More Text to Variables}.
4364 The @code{override} directive was not invented for escalation in the war
4365 between makefiles and command arguments.  It was invented so you can alter
4366 and add to values that the user specifies with command arguments.
4368 For example, suppose you always want the @samp{-g} switch when you run the
4369 C compiler, but you would like to allow the user to specify the other
4370 switches with a command argument just as usual.  You could use this
4371 @code{override} directive:
4373 @example
4374 override CFLAGS += -g
4375 @end example
4377 You can also use @code{override} directives with @code{define} directives.
4378 This is done as you might expect:
4380 @example
4381 override define foo
4383 endef
4384 @end example
4386 @noindent
4387 @iftex
4388 See the next section for information about @code{define}.
4389 @end iftex
4390 @ifinfo
4391 @xref{Defining, ,Defining Variables Verbatim}.
4392 @end ifinfo
4394 @node Defining, Environment, Override Directive, Using Variables
4395 @section Defining Variables Verbatim
4396 @findex define
4397 @findex endef
4398 @cindex verbatim variable definition
4399 @cindex defining variables verbatim
4400 @cindex variables, defining verbatim
4402 Another way to set the value of a variable is to use the @code{define}
4403 directive.  This directive has an unusual syntax which allows newline
4404 characters to be included in the value, which is convenient for defining
4405 canned sequences of commands 
4406 (@pxref{Sequences, ,Defining Canned Command Sequences}).
4408 The @code{define} directive is followed on the same line by the name of the
4409 variable and nothing more.  The value to give the variable appears on the
4410 following lines.  The end of the value is marked by a line containing just
4411 the word @code{endef}.  Aside from this difference in syntax, @code{define}
4412 works just like @samp{=}: it creates a recursively-expanded variable
4413 (@pxref{Flavors, ,The Two Flavors of Variables}).
4414 The variable name may contain function and variable references, which
4415 are expanded when the directive is read to find the actual variable name
4416 to use.
4418 @example
4419 define two-lines
4420 echo foo
4421 echo $(bar)
4422 endef
4423 @end example
4425 The value in an ordinary assignment cannot contain a newline; but the
4426 newlines that separate the lines of the value in a @code{define} become
4427 part of the variable's value (except for the final newline which precedes
4428 the @code{endef} and is not considered part of the value).@refill
4430 @need 800
4431 The previous example is functionally equivalent to this:
4433 @example
4434 two-lines = echo foo; echo $(bar)
4435 @end example
4437 @noindent
4438 since two commands separated by semicolon behave much like two separate
4439 shell commands.  However, note that using two separate lines means
4440 @code{make} will invoke the shell twice, running an independent subshell
4441 for each line.  @xref{Execution, ,Command Execution}.
4443 If you want variable definitions made with @code{define} to take
4444 precedence over command-line variable definitions, you can use the
4445 @code{override} directive together with @code{define}:
4447 @example
4448 override define two-lines
4450 $(bar)
4451 endef
4452 @end example
4454 @noindent
4455 @xref{Override Directive, ,The @code{override} Directive}.
4457 @node Environment,  , Defining, Using Variables
4458 @section Variables from the Environment
4460 @cindex variables, environment
4461 @cindex environment
4462 Variables in @code{make} can come from the environment in which
4463 @code{make} is run.  Every environment variable that @code{make} sees when
4464 it starts up is transformed into a @code{make} variable with the same name
4465 and value.  But an explicit assignment in the makefile, or with a command
4466 argument, overrides the environment.  (If the @samp{-e} flag is specified,
4467 then values from the environment override assignments in the makefile.
4468 @xref{Options Summary, ,Summary of Options}.
4469 But this is not recommended practice.)
4471 Thus, by setting the variable @code{CFLAGS} in your environment, you can
4472 cause all C compilations in most makefiles to use the compiler switches you
4473 prefer.  This is safe for variables with standard or conventional meanings
4474 because you know that no makefile will use them for other things.  (But
4475 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
4476 and therefore are not affected by the value in the environment.)
4478 When @code{make} is invoked recursively, variables defined in the
4479 outer invocation can be passed to inner invocations through the
4480 environment (@pxref{Recursion, ,Recursive Use of @code{make}}).  By
4481 default, only variables that came from the environment or the command
4482 line are passed to recursive invocations.  You can use the
4483 @code{export} directive to pass other variables.
4484 @xref{Variables/Recursion, , Communicating Variables to a
4485 Sub-@code{make}}, for full details.
4487 Other use of variables from the environment is not recommended.  It is not
4488 wise for makefiles to depend for their functioning on environment variables
4489 set up outside their control, since this would cause different users to get
4490 different results from the same makefile.  This is against the whole
4491 purpose of most makefiles.
4493 Such problems would be especially likely with the variable @code{SHELL},
4494 which is normally present in the environment to specify the user's choice
4495 of interactive shell.  It would be very undesirable for this choice to
4496 affect @code{make}.  So @code{make} ignores the environment value of
4497 @code{SHELL}.@refill
4499 @node Conditionals, Functions, Using Variables, Top
4500 @chapter Conditional Parts of Makefiles
4502 @cindex conditionals
4503 A @dfn{conditional} causes part of a makefile to be obeyed or ignored
4504 depending on the values of variables.  Conditionals can compare the
4505 value of one variable to another, or the value of a variable to
4506 a constant string.  Conditionals control what @code{make} actually
4507 ``sees'' in the makefile, so they @emph{cannot} be used to control shell
4508 commands at the time of execution.@refill
4510 @menu
4511 * Conditional Example::         Example of a conditional
4512 * Conditional Syntax::          The syntax of conditionals.
4513 * Testing Flags::               Conditionals that test flags.
4514 @end menu
4516 @node Conditional Example, Conditional Syntax,  , Conditionals
4517 @section Example of a Conditional
4519 The following example of a conditional tells @code{make} to use one set
4520 of libraries if the @code{CC} variable is @samp{gcc}, and a different
4521 set of libraries otherwise.  It works by controlling which of two
4522 command lines will be used as the command for a rule.  The result is
4523 that @samp{CC=gcc} as an argument to @code{make} changes not only which
4524 compiler is used but also which libraries are linked.
4526 @example
4527 libs_for_gcc = -lgnu
4528 normal_libs =
4530 foo: $(objects)
4531 ifeq ($(CC),gcc)
4532         $(CC) -o foo $(objects) $(libs_for_gcc)
4533 else
4534         $(CC) -o foo $(objects) $(normal_libs)
4535 endif
4536 @end example
4538 This conditional uses three directives: one @code{ifeq}, one @code{else}
4539 and one @code{endif}.
4541 The @code{ifeq} directive begins the conditional, and specifies the
4542 condition.  It contains two arguments, separated by a comma and surrounded
4543 by parentheses.  Variable substitution is performed on both arguments and
4544 then they are compared.  The lines of the makefile following the
4545 @code{ifeq} are obeyed if the two arguments match; otherwise they are
4546 ignored.
4548 The @code{else} directive causes the following lines to be obeyed if the
4549 previous conditional failed.  In the example above, this means that the
4550 second alternative linking command is used whenever the first alternative
4551 is not used.  It is optional to have an @code{else} in a conditional.
4553 The @code{endif} directive ends the conditional.  Every conditional must
4554 end with an @code{endif}.  Unconditional makefile text follows.
4556 As this example illustrates, conditionals work at the textual level:
4557 the lines of the conditional are treated as part of the makefile, or
4558 ignored, according to the condition.  This is why the larger syntactic
4559 units of the makefile, such as rules, may cross the beginning or the
4560 end of the conditional.
4562 When the variable @code{CC} has the value @samp{gcc}, the above example has
4563 this effect:
4565 @example
4566 foo: $(objects)
4567         $(CC) -o foo $(objects) $(libs_for_gcc)
4568 @end example
4570 @noindent
4571 When the variable @code{CC} has any other value, the effect is this:
4573 @example
4574 foo: $(objects)
4575         $(CC) -o foo $(objects) $(normal_libs)
4576 @end example
4578 Equivalent results can be obtained in another way by conditionalizing a
4579 variable assignment and then using the variable unconditionally:
4581 @example
4582 libs_for_gcc = -lgnu
4583 normal_libs =
4585 ifeq ($(CC),gcc)
4586   libs=$(libs_for_gcc)
4587 else
4588   libs=$(normal_libs)
4589 endif
4591 foo: $(objects)
4592         $(CC) -o foo $(objects) $(libs)
4593 @end example
4595 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
4596 @section Syntax of Conditionals
4597 @findex ifdef
4598 @findex ifeq
4599 @findex ifndef
4600 @findex ifneq
4601 @findex else
4602 @findex endif
4604 The syntax of a simple conditional with no @code{else} is as follows:
4606 @example
4607 @var{conditional-directive}
4608 @var{text-if-true}
4609 endif
4610 @end example
4612 @noindent
4613 The @var{text-if-true} may be any lines of text, to be considered as part
4614 of the makefile if the condition is true.  If the condition is false, no
4615 text is used instead.
4617 The syntax of a complex conditional is as follows:
4619 @example
4620 @var{conditional-directive}
4621 @var{text-if-true}
4622 else
4623 @var{text-if-false}
4624 endif
4625 @end example
4627 @noindent
4628 If the condition is true, @var{text-if-true} is used; otherwise,
4629 @var{text-if-false} is used instead.  The @var{text-if-false} can be any
4630 number of lines of text.
4632 The syntax of the @var{conditional-directive} is the same whether the
4633 conditional is simple or complex.  There are four different directives that
4634 test different conditions.  Here is a table of them:
4636 @table @code
4637 @item 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 @itemx ifeq '@var{arg1}' "@var{arg2}"
4642 Expand all variable references in @var{arg1} and @var{arg2} and
4643 compare them.  If they are identical, the @var{text-if-true} is
4644 effective; otherwise, the @var{text-if-false}, if any, is effective.
4646 Often you want to test if a variable has a non-empty value.  When the
4647 value results from complex expansions of variables and functions,
4648 expansions you would consider empty may actually contain whitespace
4649 characters and thus are not seen as empty.  However, you can use the
4650 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
4651 whitespace as a non-empty value.  For example:
4653 @example
4654 @group
4655 ifeq ($(strip $(foo)),)
4656 @var{text-if-empty}
4657 endif
4658 @end group
4659 @end example
4661 @noindent
4662 will evaluate @var{text-if-empty} even if the expansion of
4663 @code{$(foo)} contains whitespace characters.
4665 @item 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 @itemx ifneq '@var{arg1}' "@var{arg2}"
4670 Expand all variable references in @var{arg1} and @var{arg2} and
4671 compare them.  If they are different, the @var{text-if-true} is
4672 effective; otherwise, the @var{text-if-false}, if any, is effective.
4674 @item ifdef @var{variable-name}
4675 If the variable @var{variable-name} has a non-empty value, the
4676 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
4677 if any, is effective.  Variables that have never been defined have an
4678 empty value.
4680 Note that @code{ifdef} only tests whether a variable has a value.  It
4681 does not expand the variable to see if that value is nonempty.
4682 Consequently, tests using @code{ifdef} return true for all definitions
4683 except those like @code{foo =}.  To test for an empty value, use
4684 @w{@code{ifeq ($(foo),)}}.  For example,
4686 @example
4687 bar =
4688 foo = $(bar)
4689 ifdef foo
4690 frobozz = yes
4691 else
4692 frobozz = no
4693 endif
4694 @end example
4696 @noindent
4697 sets @samp{frobozz} to @samp{yes}, while:
4699 @example
4700 foo =
4701 ifdef foo
4702 frobozz = yes
4703 else
4704 frobozz = no
4705 endif
4706 @end example
4708 @noindent
4709 sets @samp{frobozz} to @samp{no}.
4711 @item ifndef @var{variable-name}
4712 If the variable @var{variable-name} has an empty value, the
4713 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
4714 if any, is effective.
4715 @end table
4717 Extra spaces are allowed and ignored at the beginning of the conditional
4718 directive line, but a tab is not allowed.  (If the line begins with a tab,
4719 it will be considered a command for a rule.)  Aside from this, extra spaces
4720 or tabs may be inserted with no effect anywhere except within the directive
4721 name or within an argument.  A comment starting with @samp{#} may appear at
4722 the end of the line.
4724 The other two directives that play a part in a conditional are @code{else}
4725 and @code{endif}.  Each of these directives is written as one word, with no
4726 arguments.  Extra spaces are allowed and ignored at the beginning of the
4727 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
4728 appear at the end of the line.
4730 Conditionals affect which lines of the makefile @code{make} uses.  If
4731 the condition is true, @code{make} reads the lines of the
4732 @var{text-if-true} as part of the makefile; if the condition is false,
4733 @code{make} ignores those lines completely.  It follows that syntactic
4734 units of the makefile, such as rules, may safely be split across the
4735 beginning or the end of the conditional.@refill
4737 @code{make} evaluates conditionals when it reads a makefile.
4738 Consequently, you cannot use automatic variables in the tests of
4739 conditionals because they are not defined until commands are run
4740 (@pxref{Automatic, , Automatic Variables}).
4742 To prevent intolerable confusion, it is not permitted to start a
4743 conditional in one makefile and end it in another.  However, you may
4744 write an @code{include} directive within a conditional, provided you do
4745 not attempt to terminate the conditional inside the included file.
4747 @node Testing Flags,  , Conditional Syntax, Conditionals
4748 @section Conditionals that Test Flags
4750 You can write a conditional that tests @code{make} command flags such as
4751 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
4752 @code{findstring} function 
4753 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
4754 This is useful when @code{touch} is not enough to make a file appear up
4755 to date.
4757 The @code{findstring} function determines whether one string appears as a
4758 substring of another.  If you want to test for the @samp{-t} flag,
4759 use @samp{t} as the first string and the value of @code{MAKEFLAGS} as
4760 the other.
4762 For example, here is how to arrange to use @samp{ranlib -t} to finish
4763 marking an archive file up to date:
4765 @example
4766 archive.a: @dots{}
4767 ifneq (,$(findstring t,$(MAKEFLAGS)))
4768         +touch archive.a
4769         +ranlib -t archive.a
4770 else
4771         ranlib archive.a
4772 endif
4773 @end example
4775 @noindent
4776 The @samp{+} prefix marks those command lines as ``recursive'' so
4777 that they will be executed despite use of the @samp{-t} flag.
4778 @xref{Recursion, ,Recursive Use of @code{make}}.
4780 @node Functions, Running, Conditionals, Top
4781 @chapter Functions for Transforming Text
4782 @cindex functions
4784 @dfn{Functions} allow you to do text processing in the makefile to compute
4785 the files to operate on or the commands to use.  You use a function in a
4786 @dfn{function call}, where you give the name of the function and some text
4787 (the @dfn{arguments}) for the function to operate on.  The result of the
4788 function's processing is substituted into the makefile at the point of the
4789 call, just as a variable might be substituted.
4791 @menu
4792 * Syntax of Functions::         How to write a function call.
4793 * Text Functions::              General-purpose text manipulation functions.
4794 * Filename Functions::          Functions for manipulating file names.
4795 * Foreach Function::            Repeat some text with controlled variation.
4796 * Origin Function::             Find where a variable got its value.
4797 * Shell Function::              Substitute the output of a shell command.
4798 @end menu
4800 @node Syntax of Functions, Text Functions,  , Functions
4801 @section Function Call Syntax
4802 @cindex @code{$}, in function call
4803 @cindex dollar sign (@code{$}), in function call
4804 @cindex arguments of functions
4805 @cindex functions, syntax of
4807 A function call resembles a variable reference.  It looks like this:
4809 @example
4810 $(@var{function} @var{arguments})
4811 @end example
4813 @noindent
4814 or like this:
4816 @example
4817 $@{@var{function} @var{arguments}@}
4818 @end example
4820 Here @var{function} is a function name; one of a short list of names that
4821 are part of @code{make}.  There is no provision for defining new functions.
4823 The @var{arguments} are the arguments of the function.  They are
4824 separated from the function name by one or more spaces or tabs, and if
4825 there is more than one argument, then they are separated by commas.
4826 Such whitespace and commas are not part of an argument's value.  The
4827 delimiters which you use to surround the function call, whether
4828 parentheses or braces, can appear in an argument only in matching pairs;
4829 the other kind of delimiters may appear singly.  If the arguments
4830 themselves contain other function calls or variable references, it is
4831 wisest to use the same kind of delimiters for all the references; write
4832 @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst a,b,$@{x@})}}.  This
4833 is because it is clearer, and because only one type of delimiter is
4834 matched to find the end of the reference.
4836 The text written for each argument is processed by substitution of
4837 variables and function calls to produce the argument value, which
4838 is the text on which the function acts.  The substitution is done in the
4839 order in which the arguments appear.
4841 Commas and unmatched parentheses or braces cannot appear in the text of an
4842 argument as written; leading spaces cannot appear in the text of the first
4843 argument as written.  These characters can be put into the argument value
4844 by variable substitution.  First define variables @code{comma} and
4845 @code{space} whose values are isolated comma and space characters, then
4846 substitute these variables where such characters are wanted, like this:
4848 @example
4849 @group
4850 comma:= ,
4851 empty:=
4852 space:= $(empty) $(empty)
4853 foo:= a b c
4854 bar:= $(subst $(space),$(comma),$(foo))
4855 # @r{bar is now `a,b,c'.}
4856 @end group
4857 @end example
4859 @noindent
4860 Here the @code{subst} function replaces each space with a comma, through
4861 the value of @code{foo}, and substitutes the result.
4863 @node Text Functions, Filename Functions, Syntax of Functions, Functions
4864 @section Functions for String Substitution and Analysis
4865 @cindex functions, for text
4867 Here are some functions that operate on strings:
4869 @table @code
4870 @item $(subst @var{from},@var{to},@var{text})
4871 @findex subst
4872 Performs a textual replacement on the text @var{text}: each occurrence
4873 of @var{from} is replaced by @var{to}.  The result is substituted for
4874 the function call.  For example,
4876 @example
4877 $(subst ee,EE,feet on the street)
4878 @end example
4880 substitutes the string @samp{fEEt on the strEEt}.
4882 @item $(patsubst @var{pattern},@var{replacement},@var{text})
4883 @findex patsubst
4884 Finds whitespace-separated words in @var{text} that match
4885 @var{pattern} and replaces them with @var{replacement}.  Here
4886 @var{pattern} may contain a @samp{%} which acts as a wildcard,
4887 matching any number of any characters within a word.  If
4888 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
4889 by the text that matched the @samp{%} in @var{pattern}.@refill
4891 @cindex @code{%}, quoting in @code{patsubst}
4892 @cindex @code{%}, quoting with @code{\} (backslash)
4893 @cindex @code{\} (backslash), to quote @code{%}
4894 @cindex backslash (@code{\}), to quote @code{%}
4895 @cindex quoting @code{%}, in @code{patsubst}
4896 @samp{%} characters in @code{patsubst} function invocations can be
4897 quoted with preceding backslashes (@samp{\}).  Backslashes that would
4898 otherwise quote @samp{%} characters can be quoted with more backslashes.
4899 Backslashes that quote @samp{%} characters or other backslashes are
4900 removed from the pattern before it is compared file names or has a stem
4901 substituted into it.  Backslashes that are not in danger of quoting
4902 @samp{%} characters go unmolested.  For example, the pattern
4903 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
4904 operative @samp{%} character, and @samp{pattern\\} following it.  The
4905 final two backslashes are left alone because they cannot affect any
4906 @samp{%} character.@refill
4908 Whitespace between words is folded into single space characters;
4909 leading and trailing whitespace is discarded.
4911 For example,
4913 @example
4914 $(patsubst %.c,%.o,x.c.c bar.c)
4915 @end example
4917 @noindent
4918 produces the value @samp{x.c.o bar.o}.
4920 Substitution references (@pxref{Substitution Refs, ,Substitution
4921 References}) are a simpler way to get the effect of the @code{patsubst}
4922 function:
4924 @example
4925 $(@var{var}:@var{pattern}=@var{replacement})  
4926 @end example
4928 @noindent
4929 is equivalent to 
4931 @example
4932 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
4933 @end example
4935 The second shorthand simplifies one of the most common uses of
4936 @code{patsubst}: replacing the suffix at the end of file names.
4938 @example
4939 $(@var{var}:@var{suffix}=@var{replacement}) 
4940 @end example
4942 @noindent
4943 is equivalent to 
4945 @example
4946 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
4947 @end example
4949 @noindent
4950 For example, you might have a list of object files:
4952 @example
4953 objects = foo.o bar.o baz.o
4954 @end example
4956 @noindent
4957 To get the list of corresponding source files, you could simply write:
4959 @example
4960 $(objects:.o=.c)
4961 @end example
4963 @noindent
4964 instead of using the general form:
4966 @example
4967 $(patsubst %.o,%.c,$(objects))
4968 @end example
4970 @item $(strip @var{string})
4971 @cindex stripping whitespace
4972 @cindex whitespace, stripping
4973 @cindex spaces, stripping
4974 @findex strip
4975 Removes leading and trailing whitespace from @var{string} and replaces
4976 each internal sequence of one or more whitespace characters with a
4977 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
4979 The function @code{strip} can be very useful when used in conjunction
4980 with conditionals.  When comparing something with the empty string
4981 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
4982 just whitespace to match the empty string (@pxref{Conditionals}).
4984 Thus, the following may fail to have the desired results:
4986 @example
4987 .PHONY: all
4988 ifneq   "$(needs_made)" ""
4989 all: $(needs_made)
4990 else
4991 all:;@@echo 'Nothing to make!'
4992 endif
4993 @end example
4995 @noindent
4996 Replacing the variable reference @w{@samp{$(needs_made)}} with the
4997 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
4998 directive would make it more robust.@refill
5000 @item $(findstring @var{find},@var{in})
5001 @findex findstring
5002 @cindex searching for strings
5003 @cindex finding strings
5004 @cindex strings, searching for
5005 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
5006 value is @var{find}; otherwise, the value is empty.  You can use this
5007 function in a conditional to test for the presence of a specific
5008 substring in a given string.  Thus, the two examples,
5010 @example
5011 $(findstring a,a b c)
5012 $(findstring a,b c)
5013 @end example
5015 @noindent
5016 produce the values @samp{a} and @samp{} (the empty string),
5017 respectively.  @xref{Testing Flags}, for a practical application of
5018 @code{findstring}.@refill
5020 @need 750
5021 @findex filter
5022 @cindex filtering words
5023 @cindex words, filtering
5024 @item $(filter @var{pattern}@dots{},@var{text})
5025 Removes all whitespace-separated words in @var{text} that do
5026 @emph{not} match any of the @var{pattern} words, returning only
5027 matching words.  The patterns are written using @samp{%}, just like
5028 the patterns used in the @code{patsubst} function above.@refill
5030 The @code{filter} function can be used to separate out different types
5031 of strings (such as file names) in a variable.  For example:
5033 @example
5034 sources := foo.c bar.c baz.s ugh.h
5035 foo: $(sources)
5036         cc $(filter %.c %.s,$(sources)) -o foo
5037 @end example
5039 @noindent
5040 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
5041 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
5042 @file{baz.s} should be specified in the command to the
5043 compiler.@refill
5045 @item $(filter-out @var{pattern}@dots{},@var{text})
5046 @findex filter-out
5047 @cindex filtering out words
5048 @cindex words, filtering out
5049 Removes all whitespace-separated words in @var{text} that @emph{do}
5050 match the @var{pattern} words, returning only the words that @emph{do
5051 not} match.  This is the exact opposite of the @code{filter}
5052 function.@refill
5054 For example, given:
5056 @example
5057 @group
5058 objects=main1.o foo.o main2.o bar.o
5059 mains=main1.o main2.o
5060 @end group
5061 @end example
5063 @noindent
5064 the following generates a list which contains all the object files not
5065 in @samp{mains}:
5067 @example
5068 $(filter-out $(mains),$(objects))
5069 @end example
5071 @need 1500
5072 @findex sort
5073 @cindex sorting words
5074 @item $(sort @var{list})
5075 Sorts the words of @var{list} in lexical order, removing duplicate
5076 words.  The output is a list of words separated by single spaces.
5077 Thus,
5079 @example
5080 $(sort foo bar lose)
5081 @end example
5083 @noindent
5084 returns the value @samp{bar foo lose}.
5086 @cindex removing duplicate words
5087 @cindex duplicate words, removing
5088 @cindex words, removing duplicates
5089 Incidentally, since @code{sort} removes duplicate words, you can use
5090 it for this purpose even if you don't care about the sort order.
5091 @end table
5093 Here is a realistic example of the use of @code{subst} and
5094 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
5095 to specify a list of directories that @code{make} should search for
5096 dependency files 
5097 (@pxref{General Search, , @code{VPATH} Search Path for All Dependencies}).  
5098 This example shows how to
5099 tell the C compiler to search for header files in the same list of
5100 directories.@refill
5102 The value of @code{VPATH} is a list of directories separated by colons,
5103 such as @samp{src:../headers}.  First, the @code{subst} function is used to
5104 change the colons to spaces:
5106 @example
5107 $(subst :, ,$(VPATH))
5108 @end example
5110 @noindent
5111 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
5112 each directory name into a @samp{-I} flag.  These can be added to the
5113 value of the variable @code{CFLAGS}, which is passed automatically to the C
5114 compiler, like this:
5116 @example
5117 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
5118 @end example
5120 @noindent
5121 The effect is to append the text @samp{-Isrc -I../headers} to the
5122 previously given value of @code{CFLAGS}.  The @code{override} directive is
5123 used so that the new value is assigned even if the previous value of
5124 @code{CFLAGS} was specified with a command argument (@pxref{Override
5125 Directive, , The @code{override} Directive}).
5127 @node Filename Functions, Foreach Function, Text Functions, Functions
5128 @section Functions for File Names
5129 @cindex functions, for file names
5130 @cindex file name functions
5132 Several of the built-in expansion functions relate specifically to
5133 taking apart file names or lists of file names.
5135 Each of the following functions performs a specific transformation on a
5136 file name.  The argument of the function is regarded as a series of file
5137 names, separated by whitespace.  (Leading and trailing whitespace is
5138 ignored.)  Each file name in the series is transformed in the same way and
5139 the results are concatenated with single spaces between them.
5141 @table @code
5142 @item $(dir @var{names}@dots{})
5143 @findex dir
5144 @cindex directory part
5145 @cindex file name, directory part
5146 Extracts the directory-part of each file name in @var{names}.  The
5147 directory-part of the file name is everything up through (and
5148 including) the last slash in it.  If the file name contains no slash,
5149 the directory part is the string @samp{./}.  For example,
5151 @example
5152 $(dir src/foo.c hacks)
5153 @end example
5155 @noindent
5156 produces the result @samp{src/ ./}.
5158 @item $(notdir @var{names}@dots{})
5159 @findex notdir
5160 @cindex file name, nondirectory part
5161 @cindex nondirectory part
5162 Extracts all but the directory-part of each file name in @var{names}.
5163 If the file name contains no slash, it is left unchanged.  Otherwise,
5164 everything through the last slash is removed from it.
5166 A file name that ends with a slash becomes an empty string.  This is
5167 unfortunate, because it means that the result does not always have the
5168 same number of whitespace-separated file names as the argument had;
5169 but we do not see any other valid alternative.
5171 For example,
5173 @example
5174 $(notdir src/foo.c hacks)
5175 @end example
5177 @noindent
5178 produces the result @samp{foo.c hacks}.
5180 @item $(suffix @var{names}@dots{})
5181 @findex suffix
5182 @cindex suffix, function to find
5183 @cindex file name suffix
5184 Extracts the suffix of each file name in @var{names}.  If the file name
5185 contains a period, the suffix is everything starting with the last
5186 period.  Otherwise, the suffix is the empty string.  This frequently
5187 means that the result will be empty when @var{names} is not, and if
5188 @var{names} contains multiple file names, the result may contain fewer
5189 file names.
5191 For example,
5193 @example
5194 $(suffix src/foo.c hacks)
5195 @end example
5197 @noindent
5198 produces the result @samp{.c}.
5200 @item $(basename @var{names}@dots{})
5201 @findex basename
5202 @cindex basename
5203 @cindex file name, basename of
5204 Extracts all but the suffix of each file name in @var{names}.  If the
5205 file name contains a period, the basename is everything starting up to
5206 (and not including) the last period.  Otherwise, the basename is the
5207 entire file name.  For example,
5209 @example
5210 $(basename src/foo.c hacks)
5211 @end example
5213 @noindent
5214 produces the result @samp{src/foo hacks}.
5216 @c plural convention with dots (be consistent)
5217 @item $(addsuffix @var{suffix},@var{names}@dots{})
5218 @findex addsuffix
5219 @cindex suffix, adding
5220 @cindex file name suffix, adding
5221 The argument @var{names} is regarded as a series of names, separated
5222 by whitespace; @var{suffix} is used as a unit.  The value of
5223 @var{suffix} is appended to the end of each individual name and the
5224 resulting larger names are concatenated with single spaces between
5225 them.  For example,
5227 @example
5228 $(addsuffix .c,foo bar)
5229 @end example
5231 @noindent
5232 produces the result @samp{foo.c bar.c}.
5234 @item $(addprefix @var{prefix},@var{names}@dots{})
5235 @findex addprefix
5236 @cindex prefix, adding
5237 @cindex file name prefix, adding
5238 The argument @var{names} is regarded as a series of names, separated
5239 by whitespace; @var{prefix} is used as a unit.  The value of
5240 @var{prefix} is prepended to the front of each individual name and the
5241 resulting larger names are concatenated with single spaces between
5242 them.  For example,
5244 @example
5245 $(addprefix src/,foo bar)
5246 @end example
5248 @noindent
5249 produces the result @samp{src/foo src/bar}.
5251 @item $(join @var{list1},@var{list2})
5252 @findex join
5253 @cindex joining lists of words
5254 @cindex words, joining lists
5255 Concatenates the two arguments word by word: the two first words (one
5256 from each argument) concatenated form the first word of the result, the
5257 two second words form the second word of the result, and so on.  So the
5258 @var{n}th word of the result comes from the @var{n}th word of each
5259 argument.  If one argument has more words that the other, the extra
5260 words are copied unchanged into the result.
5262 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
5264 Whitespace between the words in the lists is not preserved; it is
5265 replaced with a single space.
5267 This function can merge the results of the @code{dir} and
5268 @code{notdir} functions, to produce the original list of files which
5269 was given to those two functions.@refill
5271 @item $(word @var{n},@var{text})
5272 @findex word
5273 @cindex words, selecting
5274 @cindex selecting words
5275 Returns the @var{n}th word of @var{text}.  The legitimate values of
5276 @var{n} start from 1.  If @var{n} is bigger than the number of words
5277 in @var{text}, the value is empty.  For example,
5279 @example
5280 $(word 2, foo bar baz)
5281 @end example
5283 @noindent
5284 returns @samp{bar}.
5286 @c Following item phrased to prevent overfull hbox.  --RJC 17 Jul 92
5287 @item $(words @var{text})
5288 @findex words
5289 @cindex words, finding number
5290 Returns the number of words in @var{text}.  
5291 Thus, the last word of @var{text} is
5292 @w{@code{$(word $(words @var{text}),@var{text})}}.@refill
5294 @item $(firstword @var{names}@dots{})
5295 @findex firstword
5296 @cindex words, extracting first
5297 The argument @var{names} is regarded as a series of names, separated
5298 by whitespace.  The value is the first name in the series.  The rest
5299 of the names are ignored.
5301 For example,
5303 @example
5304 $(firstword foo bar)
5305 @end example
5307 @noindent
5308 produces the result @samp{foo}.  Although @code{$(firstword
5309 @var{text})} is the same as @code{$(word 1,@var{text})}, the
5310 @code{firstword} function is retained for its simplicity.@refill
5312 @item $(wildcard @var{pattern})
5313 @findex wildcard
5314 @cindex wildcard, function
5315 The argument @var{pattern} is a file name pattern, typically containing
5316 wildcard characters (as in shell file name patterns).  The result of
5317 @code{wildcard} is a space-separated list of the names of existing files
5318 that match the pattern.
5319 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
5320 @end table
5322 @node Foreach Function, Origin Function, Filename Functions, Functions
5323 @section The @code{foreach} Function
5324 @findex foreach
5325 @cindex words, iterating over
5327 The @code{foreach} function is very different from other functions.  It
5328 causes one piece of text to be used repeatedly, each time with a different
5329 substitution performed on it.  It resembles the @code{for} command in the
5330 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
5332 The syntax of the @code{foreach} function is:
5334 @example
5335 $(foreach @var{var},@var{list},@var{text})
5336 @end example
5338 @noindent
5339 The first two arguments, @var{var} and @var{list}, are expanded before
5340 anything else is done; note that the last argument, @var{text}, is
5341 @strong{not} expanded at the same time.  Then for each word of the expanded
5342 value of @var{list}, the variable named by the expanded value of @var{var}
5343 is set to that word, and @var{text} is expanded.  Presumably @var{text}
5344 contains references to that variable, so its expansion will be different
5345 each time.
5347 The result is that @var{text} is expanded as many times as there are
5348 whitespace-separated words in @var{list}.  The multiple expansions of
5349 @var{text} are concatenated, with spaces between them, to make the result
5350 of @code{foreach}.
5352 This simple example sets the variable @samp{files} to the list of all files
5353 in the directories in the list @samp{dirs}:
5355 @example
5356 dirs := a b c d
5357 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
5358 @end example
5360 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
5361 finds the value @samp{a} for @code{dir}, so it produces the same result
5362 as @samp{$(wildcard a/*)}; the second repetition produces the result
5363 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
5365 This example has the same result (except for setting @samp{dirs}) as
5366 the following example:
5368 @example
5369 files := $(wildcard a/* b/* c/* d/*)
5370 @end example
5372 When @var{text} is complicated, you can improve readability by giving it
5373 a name, with an additional variable:
5375 @example
5376 find_files = $(wildcard $(dir)/*)
5377 dirs := a b c d
5378 files := $(foreach dir,$(dirs),$(find_files))
5379 @end example
5381 @noindent
5382 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
5383 to define a recursively-expanding variable, so that its value contains an
5384 actual function call to be reexpanded under the control of @code{foreach};
5385 a simply-expanded variable would not do, since @code{wildcard} would be
5386 called only once at the time of defining @code{find_files}.
5388 The @code{foreach} function has no permanent effect on the variable
5389 @var{var}; its value and flavor after the @code{foreach} function call are
5390 the same as they were beforehand.  The other values which are taken from
5391 @var{list} are in effect only temporarily, during the execution of
5392 @code{foreach}.  The variable @var{var} is a simply-expanded variable
5393 during the execution of @code{foreach}.  If @var{var} was undefined
5394 before the @code{foreach} function call, it is undefined after the call.
5395 @xref{Flavors, ,The Two Flavors of Variables}.@refill
5397 You must take care when using complex variable expressions that result in
5398 variable names because many strange things are valid variable names, but
5399 are probably not what you intended.  For example,
5401 @smallexample
5402 files := $(foreach Esta escrito en espanol!,b c ch,$(find_files))
5403 @end smallexample
5405 @noindent
5406 might be useful if the value of @code{find_files} references the variable
5407 whose name is @samp{Esta escrito en espanol!} (es un nombre bastante largo,
5408 no?), but it is more likely to be a mistake.
5410 @node Origin Function, Shell Function, Foreach Function, Functions
5411 @section The @code{origin} Function
5412 @findex origin
5413 @cindex variables, origin of
5414 @cindex origin of variable
5416 The @code{origin} function is unlike most other functions in that it does
5417 not operate on the values of variables; it tells you something @emph{about}
5418 a variable.  Specifically, it tells you where it came from.
5420 The syntax of the @code{origin} function is:
5422 @example
5423 $(origin @var{variable})
5424 @end example
5426 Note that @var{variable} is the @emph{name} of a variable to inquire about;
5427 not a @emph{reference} to that variable.  Therefore you would not normally
5428 use a @samp{$} or parentheses when writing it.  (You can, however, use a
5429 variable reference in the name if you want the name not to be a constant.)
5431 The result of this function is a string telling you how the variable
5432 @var{variable} was defined:
5434 @table @samp
5435 @item undefined
5437 if @var{variable} was never defined.
5439 @item default
5441 if @var{variable} has a default definition, as is usual with @code{CC}
5442 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
5443 Note that if you have redefined a default variable, the @code{origin}
5444 function will return the origin of the later definition.
5446 @item environment
5448 if @var{variable} was defined as an environment variable and the
5449 @samp{-e} option is @emph{not} turned on (@pxref{Options Summary, ,Summary of Options}).
5451 @item environment override
5453 if @var{variable} was defined as an environment variable and the
5454 @w{@samp{-e}} option @emph{is} turned on (@pxref{Options Summary,
5455 ,Summary of Options}).@refill
5457 @item file
5459 if @var{variable} was defined in a makefile.
5461 @item command line
5463 if @var{variable} was defined on the command line.
5465 @item override
5467 if @var{variable} was defined with an @code{override} directive in a
5468 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
5470 @item automatic
5472 if @var{variable} is an automatic variable defined for the
5473 execution of the commands for each rule
5474 (@pxref{Automatic, , Automatic Variables}).
5475 @end table
5477 This information is primarily useful (other than for your curiosity) to
5478 determine if you want to believe the value of a variable.  For example,
5479 suppose you have a makefile @file{foo} that includes another makefile
5480 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
5481 if you run the command @w{@samp{make -f bar}}, even if the environment contains
5482 a definition of @code{bletch}.  However, if @file{foo} defined
5483 @code{bletch} before including @file{bar}, you do not want to override that
5484 definition.  This could be done by using an @code{override} directive in
5485 @file{foo}, giving that definition precedence over the later definition in
5486 @file{bar}; unfortunately, the @code{override} directive would also
5487 override any command line definitions.  So, @file{bar} could
5488 include:@refill
5490 @example
5491 @group
5492 ifdef bletch
5493 ifeq "$(origin bletch)" "environment"
5494 bletch = barf, gag, etc.
5495 endif
5496 endif
5497 @end group
5498 @end example
5500 @noindent
5501 If @code{bletch} has been defined from the environment, this will redefine
5504 If you want to override a previous definition of @code{bletch} if it came
5505 from the environment, even under @samp{-e}, you could instead write:
5507 @example
5508 @group
5509 ifneq "$(findstring environment,$(origin bletch))" ""
5510 bletch = barf, gag, etc.
5511 endif
5512 @end group
5513 @end example
5515 Here the redefinition takes place if @samp{$(origin bletch)} returns either
5516 @samp{environment} or @samp{environment override}.
5517 @xref{Text Functions, , Functions for String Substitution and Analysis}.
5519 @node Shell Function,  , Origin Function, Functions
5520 @section The @code{shell} Function
5521 @findex shell
5522 @cindex commands, expansion
5523 @cindex backquotes
5524 @cindex shell command, function for
5526 The @code{shell} function is unlike any other function except the
5527 @code{wildcard} function 
5528 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
5529 communicates with the world outside of @code{make}.
5531 The @code{shell} function performs the same function that backquotes
5532 (@samp{`}) perform in most shells: it does @dfn{command expansion}.  This
5533 means that it takes an argument that is a shell command and returns the
5534 output of the command.  The only processing @code{make} does on the result,
5535 before substituting it into the surrounding text, is to convert newlines to
5536 spaces.@refill
5538 The commands run by calls to the @code{shell} function are run when the
5539 function calls are expanded.  In most cases, this is when the makefile is
5540 read in.  The exception is that function calls in the commands of the rules
5541 are expanded when the commands are run, and this applies to @code{shell}
5542 function calls like all others.
5544 Here are some examples of the use of the @code{shell} function:
5546 @example
5547 contents := $(shell cat foo)
5548 @end example
5550 @noindent
5551 sets @code{contents} to the contents of the file @file{foo}, with a space
5552 (rather than a newline) separating each line.
5554 @example
5555 files := $(shell echo *.c)
5556 @end example
5558 @noindent
5559 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
5560 using a very strange shell, this has the same result as
5561 @w{@samp{$(wildcard *.c)}}.@refill
5563 @node Running, Implicit Rules, Functions, Top
5564 @chapter How to Run @code{make}
5566 A makefile that says how to recompile a program can be used in more
5567 than one way.  The simplest use is to recompile every file that is out
5568 of date.  Usually, makefiles are written so that if you run
5569 @code{make} with no arguments, it does just that.
5571 But you might want to update only some of the files; you might want to use
5572 a different compiler or different compiler options; you might want just to
5573 find out which files are out of date without changing them.
5575 By giving arguments when you run @code{make}, you can do any of these
5576 things and many others.
5578 The exit status of @code{make} is always one of three values:
5579 @table @code
5580 @item 0
5581 The exit status is zero if @code{make} is successful.
5582 @item 2
5583 The exit status is two if @code{make} encounters any errors.
5584 It will print messages describing the particular errors.
5585 @item 1
5586 The exit status is one if you use the @samp{-q} flag and @code{make}
5587 determines that some target is not already up to date.
5588 @xref{Instead of Execution, ,Instead of Executing the Commands}.
5589 @end table
5591 @menu
5592 * Makefile Arguments::          How to specify which makefile to use.
5593 * Goals::                       How to use goal arguments to specify which 
5594                                   parts of the makefile to use.
5595 * Instead of Execution::        How to use mode flags to specify what
5596                                   kind of thing to do with the commands 
5597                                   in the makefile other than simply 
5598                                   execute them.
5599 * Avoiding Compilation::        How to avoid recompiling certain files.
5600 * Overriding::                  How to override a variable to specify 
5601                                   an alternate compiler and other things.
5602 * Testing::                     How to proceed past some errors, to 
5603                                   test compilation.
5604 * Options Summary::             Summary of Options
5605 @end menu
5607 @node Makefile Arguments, Goals,  , Running
5608 @section Arguments to Specify the Makefile
5609 @cindex @code{--file}
5610 @cindex @code{--makefile}
5611 @cindex @code{-f}
5613 The way to specify the name of the makefile is with the @samp{-f} or
5614 @samp{--file} option (@samp{--makefile} also works).  For example,
5615 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
5617 If you use the @samp{-f} flag several times and follow each @samp{-f}
5618 with an argument, all the specified files are used jointly as
5619 makefiles.
5621 If you do not use the @samp{-f} or @samp{--file} flag, the default is
5622 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
5623 that order, and use the first of these three which exists or can be made
5624 (@pxref{Makefiles, ,Writing Makefiles}).@refill
5626 @node Goals, Instead of Execution, Makefile Arguments, Running
5627 @section Arguments to Specify the Goals
5628 @cindex goal, how to specify
5630 The @dfn{goals} are the targets that @code{make} should strive ultimately
5631 to update.  Other targets are updated as well if they appear as
5632 dependencies of goals, or dependencies of dependencies of goals, etc.
5634 By default, the goal is the first target in the makefile (not counting
5635 targets that start with a period).  Therefore, makefiles are usually
5636 written so that the first target is for compiling the entire program or
5637 programs they describe.  If the first rule in the makefile has several
5638 targets, only the first target in the rule becomes the default goal, not
5639 the whole list.
5641 You can specify a different goal or goals with arguments to @code{make}.
5642 Use the name of the goal as an argument.  If you specify several goals,
5643 @code{make} processes each of them in turn, in the order you name them.
5645 Any target in the makefile may be specified as a goal (unless it
5646 starts with @samp{-} or contains an @samp{=}, in which case it will be
5647 parsed as a switch or variable definition, respectively).  Even
5648 targets not in the makefile may be specified, if @code{make} can find
5649 implicit rules that say how to make them.
5651 One use of specifying a goal is if you want to compile only a part of
5652 the program, or only one of several programs.  Specify as a goal each
5653 file that you wish to remake.  For example, consider a directory containing
5654 several programs, with a makefile that starts like this:
5656 @example
5657 .PHONY: all
5658 all: size nm ld ar as
5659 @end example
5661 If you are working on the program @code{size}, you might want to say
5662 @w{@samp{make size}} so that only the files of that program are recompiled.
5664 Another use of specifying a goal is to make files that are not normally
5665 made.  For example, there may be a file of debugging output, or a
5666 version of the program that is compiled specially for testing, which has
5667 a rule in the makefile but is not a dependency of the default goal.
5669 Another use of specifying a goal is to run the commands associated with
5670 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
5671 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
5672 a phony target named @file{clean} which deletes everything except source
5673 files.  Naturally, this is done only if you request it explicitly with
5674 @w{@samp{make clean}}.  Following is a list of typical phony and empty
5675 target names.  @xref{Standard Targets}, for a detailed list of all the
5676 standard target names which GNU software packages use.
5678 @table @file
5679 @item all
5680 @cindex @code{all} @r{(standard target)}
5681 Make all the top-level targets the makefile knows about.
5683 @item clean
5684 @cindex @code{clean} @r{(standard target)}
5685 Delete all files that are normally created by running @code{make}.
5687 @item mostlyclean
5688 @cindex @code{mostlyclean} @r{(standard target)}
5689 Like @samp{clean}, but may refrain from deleting a few files that people
5690 normally don't want to recompile.  For example, the @samp{mostlyclean}
5691 target for GCC does not delete @file{libgcc.a}, because recompiling it
5692 is rarely necessary and takes a lot of time.
5694 @item distclean
5695 @cindex @code{distclean} @r{(standard target)}
5696 @itemx realclean
5697 @cindex @code{realclean} @r{(standard target)}
5698 @itemx clobber
5699 @cindex @code{clobber} @r{(standard target)}
5700 Any of these targets might be defined to delete @emph{more} files than
5701 @samp{clean} does.  For example, this would delete configuration files
5702 or links that you would normally create as preparation for compilation,
5703 even if the makefile itself cannot create these files.
5705 @item install
5706 @cindex @code{install} @r{(standard target)}
5707 Copy the executable file into a directory that users typically search
5708 for commands; copy any auxiliary files that the executable uses into
5709 the directories where it will look for them.
5711 @item print
5712 @cindex @code{print} @r{(standard target)}
5713 Print listings of the source files that have changed.
5715 @item tar
5716 @cindex @code{tar} @r{(standard target)}
5717 Create a tar file of the source files.
5719 @item shar
5720 @cindex @code{shar} @r{(standard target)}
5721 Create a shell archive (shar file) of the source files.
5723 @item dist
5724 @cindex @code{dist} @r{(standard target)}
5725 Create a distribution file of the source files.  This might
5726 be a tar file, or a shar file, or a compressed version of one of the
5727 above, or even more than one of the above.
5729 @item TAGS
5730 @cindex @code{TAGS} @r{(standard target)}
5731 Update a tags table for this program.
5733 @item check
5734 @cindex @code{check} @r{(standard target)}
5735 @itemx test
5736 @cindex @code{test} @r{(standard target)}
5737 Perform self tests on the program this makefile builds.
5738 @end table
5740 @node Instead of Execution, Avoiding Compilation, Goals, Running
5741 @section Instead of Executing the Commands
5742 @cindex execution, instead of
5743 @cindex commands, instead of executing
5745 The makefile tells @code{make} how to tell whether a target is up to date,
5746 and how to update each target.  But updating the targets is not always
5747 what you want.  Certain options specify other activities for @code{make}.
5749 @comment Extra blank lines make it print better.
5750 @table @samp
5751 @item -n
5752 @itemx --just-print
5753 @itemx --dry-run
5754 @itemx --recon
5755 @cindex @code{--just-print}
5756 @cindex @code{--dry-run}
5757 @cindex @code{--recon}
5758 @cindex @code{-n}
5760 ``No-op''.  The activity is to print what commands would be used to make
5761 the targets up to date, but not actually execute them.
5763 @item -t
5764 @itemx --touch
5765 @cindex @code{--touch}
5766 @cindex touching files
5767 @cindex target, touching
5768 @cindex @code{-t}
5770 ``Touch''.  The activity is to mark the targets as up to date without
5771 actually changing them.  In other words, @code{make} pretends to compile
5772 the targets but does not really change their contents.
5774 @item -q
5775 @itemx --question
5776 @cindex @code{--question}
5777 @cindex @code{-q}
5778 @cindex question mode
5780 ``Question''.  The activity is to find out silently whether the targets
5781 are up to date already; but execute no commands in either case.  In other
5782 words, neither compilation nor output will occur.
5784 @item -W @var{file}
5785 @itemx --what-if=@var{file}
5786 @itemx --assume-new=@var{file}
5787 @itemx --new-file=@var{file}
5788 @cindex @code{--what-if}
5789 @cindex @code{-W}
5790 @cindex @code{--assume-new}
5791 @cindex @code{--new-file}
5792 @cindex what if
5793 @cindex files, assuming new
5795 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
5796 files' modification times are recorded by @code{make} as being the present
5797 time, although the actual modification times remain the same.  
5798 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
5799 to see what would happen if you were to modify specific files.@refill
5800 @end table
5802 With the @samp{-n} flag, @code{make} prints the commands that it would
5803 normally execute but does not execute them.
5805 With the @samp{-t} flag, @code{make} ignores the commands in the rules
5806 and uses (in effect) the command @code{touch} for each target that needs to
5807 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
5808 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
5809 the program @code{touch}.  It does the work directly.
5811 With the @samp{-q} flag, @code{make} prints nothing and executes no
5812 commands, but the exit status code it returns is zero if and only if the
5813 targets to be considered are already up to date.  If the exit status is
5814 one, then some updating needs to be done.  If @code{make} encounters an
5815 error, the exit status is two, so you can distinguish an error from a
5816 target that is not up to date.
5818 It is an error to use more than one of these three flags in the same
5819 invocation of @code{make}.
5821 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect command
5822 lines that begin with @samp{+} characters or contain the strings
5823 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
5824 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
5825 is run regardless of these options.  Other lines in the same rule are
5826 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
5827 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
5829 The @samp{-W} flag provides two features:
5831 @itemize @bullet
5832 @item
5833 If you also use the @samp{-n} or @samp{-q} flag, you can see what
5834 @code{make} would do if you were to modify some files.
5836 @item
5837 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
5838 executing commands, the @samp{-W} flag can direct @code{make} to act
5839 as if some files had been modified, without actually modifying the
5840 files.@refill
5841 @end itemize
5843 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
5844 information about @code{make} or about the makefiles in use
5845 (@pxref{Options Summary, ,Summary of Options}).@refill
5847 @node Avoiding Compilation, Overriding, Instead of Execution, Running
5848 @section Avoiding Recompilation of Some Files
5849 @cindex @code{-o}
5850 @cindex @code{--old-file}
5851 @cindex @code{--assume-old}
5852 @cindex files, assuming old
5853 @cindex files, avoiding recompilation of
5854 @cindex recompilation, avoiding
5856 Sometimes you may have changed a source file but you do not want to
5857 recompile all the files that depend on it.  For example, suppose you add a
5858 macro or a declaration to a header file that many other files depend on.
5859 Being conservative, @code{make} assumes that any change in the header file
5860 requires recompilation of all dependent files, but you know that they do not
5861 need to be recompiled and you would rather not waste the time waiting for
5862 them to compile.
5864 If you anticipate the problem before changing the header file, you can
5865 use the @samp{-t} flag.  This flag tells @code{make} not to run the
5866 commands in the rules, but rather to mark the target up to date by
5867 changing its last-modification date.  You would follow this procedure:
5869 @enumerate
5870 @item
5871 Use the command @samp{make} to recompile the source files that really
5872 need recompilation.
5874 @item
5875 Make the changes in the header files.
5877 @item
5878 Use the command @samp{make -t} to mark all the object files as
5879 up to date.  The next time you run @code{make}, the changes in the
5880 header files will not cause any recompilation.
5881 @end enumerate
5883 If you have already changed the header file at a time when some files
5884 do need recompilation, it is too late to do this.  Instead, you can
5885 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
5886 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
5887 that the file itself will not be remade, and nothing else will be
5888 remade on its account.  Follow this procedure:
5890 @enumerate
5891 @item
5892 Recompile the source files that need compilation for reasons independent
5893 of the particular header file, with @samp{make -o @var{headerfile}}.
5894 If several header files are involved, use a separate @samp{-o} option
5895 for each header file.
5897 @item
5898 Touch all the object files with @samp{make -t}.
5899 @end enumerate
5901 @node Overriding, Testing, Avoiding Compilation, Running
5902 @section Overriding Variables
5903 @cindex overriding variables with arguments
5904 @cindex variables, overriding with arguments
5905 @cindex command line variables
5906 @cindex variables, command line
5908 An argument that contains @samp{=} specifies the value of a variable:
5909 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
5910 If you specify a value in this way, all ordinary assignments of the same
5911 variable in the makefile are ignored; we say they have been
5912 @dfn{overridden} by the command line argument.
5914 The most common way to use this facility is to pass extra flags to
5915 compilers.  For example, in a properly written makefile, the variable
5916 @code{CFLAGS} is included in each command that runs the C compiler, so a
5917 file @file{foo.c} would be compiled something like this:
5919 @example
5920 cc -c $(CFLAGS) foo.c
5921 @end example
5923 Thus, whatever value you set for @code{CFLAGS} affects each compilation
5924 that occurs.  The makefile probably specifies the usual value for
5925 @code{CFLAGS}, like this:
5927 @example
5928 CFLAGS=-g
5929 @end example
5931 Each time you run @code{make}, you can override this value if you
5932 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
5933 compilation will be done with @samp{cc -c -g -O}.  (This illustrates
5934 how you can use quoting in the shell to enclose spaces and other
5935 special characters in the value of a variable when you override it.)
5937 The variable @code{CFLAGS} is only one of many standard variables that
5938 exist just so that you can change them this way.  @xref{Implicit
5939 Variables, , Variables Used by Implicit Rules}, for a complete list.
5941 You can also program the makefile to look at additional variables of your
5942 own, giving the user the ability to control other aspects of how the
5943 makefile works by changing the variables.
5945 When you override a variable with a command argument, you can define either
5946 a recursively-expanded variable or a simply-expanded variable.  The
5947 examples shown above make a recursively-expanded variable; to make a
5948 simply-expanded variable, write @samp{:=} instead of @samp{=}.  But, unless
5949 you want to include a variable reference or function call in the
5950 @emph{value} that you specify, it makes no difference which kind of
5951 variable you create.
5953 There is one way that the makefile can change a variable that you have
5954 overridden.  This is to use the @code{override} directive, which is a line
5955 that looks like this: @samp{override @var{variable} = @var{value}}
5956 (@pxref{Override Directive, ,The @code{override} Directive}).
5958 @node Testing, Options Summary, Overriding, Running
5959 @section Testing the Compilation of a Program
5960 @cindex testing compilation
5961 @cindex compilation, testing
5963 Normally, when an error happens in executing a shell command, @code{make}
5964 gives up immediately, returning a nonzero status.  No further commands are
5965 executed for any target.  The error implies that the goal cannot be
5966 correctly remade, and @code{make} reports this as soon as it knows.
5968 When you are compiling a program that you have just changed, this is not
5969 what you want.  Instead, you would rather that @code{make} try compiling
5970 every file that can be tried, to show you as many compilation errors
5971 as possible.
5973 @cindex @code{-k}
5974 @cindex @code{--keep-going}
5975 On these occasions, you should use the @samp{-k} or
5976 @samp{--keep-going} flag.  This tells @code{make} to continue to
5977 consider the other dependencies of the pending targets, remaking them
5978 if necessary, before it gives up and returns nonzero status.  For
5979 example, after an error in compiling one object file, @samp{make -k}
5980 will continue compiling other object files even though it already
5981 knows that linking them will be impossible.  In addition to continuing
5982 after failed shell commands, @samp{make -k} will continue as much as
5983 possible after discovering that it does not know how to make a target
5984 or dependency file.  This will always cause an error message, but
5985 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
5986 ,Summary of Options}).@refill
5988 The usual behavior of @code{make} assumes that your purpose is to get the
5989 goals up to date; once @code{make} learns that this is impossible, it might
5990 as well report the failure immediately.  The @samp{-k} flag says that the
5991 real purpose is to test as much as possible of the changes made in the
5992 program, perhaps to find several independent problems so that you can
5993 correct them all before the next attempt to compile.  This is why Emacs'
5994 @kbd{M-x compile} command passes the @samp{-k} flag by default.
5996 @node Options Summary,  , Testing, Running
5997 @section Summary of Options
5998 @cindex options
5999 @cindex flags
6000 @cindex switches
6002 Here is a table of all the options @code{make} understands:
6004 @table @samp
6005 @item -b
6006 @cindex @code{-b}
6007 @itemx -m
6008 @cindex @code{-m}
6009 These options are ignored for compatibility with other versions of @code{make}.
6011 @item -C @var{dir}
6012 @cindex @code{-C}
6013 @itemx --directory=@var{dir}
6014 @cindex @code{--directory}
6015 Change to directory @var{dir} before reading the makefiles.  If multiple
6016 @samp{-C} options are specified, each is interpreted relative to the
6017 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
6018 This is typically used with recursive invocations of @code{make}
6019 (@pxref{Recursion, ,Recursive Use of @code{make}}).
6021 @item -d
6022 @cindex @code{-d}
6023 @itemx --debug
6024 @cindex @code{--debug}
6025 @c Extra blank line here makes the table look better.
6027 Print debugging information in addition to normal processing.  The
6028 debugging information says which files are being considered for
6029 remaking, which file-times are being compared and with what results,
6030 which files actually need to be remade, which implicit rules are
6031 considered and which are applied---everything interesting about how
6032 @code{make} decides what to do.
6034 @item -e
6035 @cindex @code{-e}
6036 @itemx --environment-overrides
6037 @cindex @code{--environment-overrides}
6038 Give variables taken from the environment precedence
6039 over variables from makefiles.
6040 @xref{Environment, ,Variables from the Environment}.
6042 @item -f @var{file}
6043 @cindex @code{-f}
6044 @itemx --file=@var{file}
6045 @cindex @code{--file}
6046 @itemx --makefile=@var{file}
6047 @cindex @code{--makefile}
6048 Read the file named @var{file} as a makefile.
6049 @xref{Makefiles, ,Writing Makefiles}.
6051 @item -h
6052 @cindex @code{-h}
6053 @itemx --help
6054 @cindex @code{--help}
6055 @c Extra blank line here makes the table look better.
6057 Remind you of the options that @code{make} understands and then exit.
6059 @item -i
6060 @cindex @code{-i}
6061 @itemx --ignore-errors
6062 @cindex @code{--ignore-errors}
6063 Ignore all errors in commands executed to remake files.
6064 @xref{Errors, ,Errors in Commands}.
6066 @item -I @var{dir}
6067 @cindex @code{-I}
6068 @itemx --include-dir=@var{dir}
6069 @cindex @code{--include-dir}
6070 Specifies a directory @var{dir} to search for included makefiles.
6071 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
6072 options are used to specify several directories, the directories are
6073 searched in the order specified.
6075 @item -j [@var{jobs}]
6076 @cindex @code{-j}
6077 @itemx --jobs=[@var{jobs}]
6078 @cindex @code{--jobs}
6079 Specifies the number of jobs (commands) to run simultaneously.  With no
6080 argument, @code{make} runs as many jobs simultaneously as possible.  If
6081 there is more than one @samp{-j} option, the last one is effective.
6082 @xref{Parallel, ,Parallel Execution},
6083 for more information on how commands are run.
6085 @item -k
6086 @cindex @code{-k}
6087 @itemx --keep-going
6088 @cindex @code{--keep-going}
6089 Continue as much as possible after an error.  While the target that
6090 failed, and those that depend on it, cannot be remade, the other
6091 dependencies of these targets can be processed all the same.
6092 @xref{Testing, ,Testing the Compilation of a Program}.
6094 @item -l [@var{load}]
6095 @cindex @code{-l}
6096 @itemx --load-average[=@var{load}]
6097 @cindex @code{--load-average}
6098 @itemx --max-load[=@var{load}]
6099 @cindex @code{--max-load}
6100 Specifies that no new jobs (commands) should be started if there are
6101 other jobs running and the load average is at least @var{load} (a
6102 floating-point number).  With no argument, removes a previous load
6103 limit.  @xref{Parallel, ,Parallel Execution}.
6105 @item -n
6106 @cindex @code{-n}
6107 @itemx --just-print
6108 @cindex @code{--just-print}
6109 @itemx --dry-run
6110 @cindex @code{--dry-run}
6111 @itemx --recon
6112 @cindex @code{--recon}
6113 @c Extra blank line here makes the table look better.
6115 Print the commands that would be executed, but do not execute them.
6116 @xref{Instead of Execution, ,Instead of Executing the Commands}.
6118 @item -o @var{file}
6119 @cindex @code{-o}
6120 @itemx --old-file=@var{file}
6121 @cindex @code{--old-file}
6122 @itemx --assume-old=@var{file}
6123 @cindex @code{--assume-old}
6124 Do not remake the file @var{file} even if it is older than its
6125 dependencies, and do not remake anything on account of changes in
6126 @var{file}.  Essentially the file is treated as very old and its rules
6127 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
6128 Some Files}.@refill
6130 @item -p
6131 @cindex @code{-p}
6132 @itemx --print-data-base
6133 @cindex @code{--print-data-base}
6134 Print the data base (rules and variable values) that results from
6135 reading the makefiles; then execute as usual or as otherwise
6136 specified.  This also prints the version information given by
6137 the @samp{-v} switch (see below).  To print the data base without
6138 trying to remake any files, use @w{@samp{make -p -f /dev/null}}.
6140 @item -q
6141 @cindex @code{-q}
6142 @itemx --question
6143 @cindex @code{--question}
6144 ``Question mode''.  Do not run any commands, or print anything; just
6145 return an exit status that is zero if the specified targets are already
6146 up to date, one if any remaking is required, or two if an error is
6147 encountered.  @xref{Instead of Execution, ,Instead of Executing the
6148 Commands}.@refill
6150 @item -r
6151 @cindex @code{-r}
6152 @itemx --no-builtin-rules
6153 @cindex @code{--no-builtin-rules}
6154 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
6155 ,Using Implicit Rules}).  You can still define your own by writing
6156 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
6157 Rules}).  The @samp{-r} option also clears out the default list of
6158 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
6159 Rules}).  But you can still define your own suffixes with a rule for
6160 @code{.SUFFIXES}, and then define your own suffix rules.
6162 @item -s
6163 @cindex @code{-s}
6164 @itemx --silent
6165 @cindex @code{--silent}
6166 @itemx --quiet
6167 @cindex @code{--quiet}
6168 @c Extra blank line here makes the table look better.
6170 Silent operation; do not print the commands as they are executed.
6171 @xref{Echoing, ,Command Echoing}.
6173 @item -S
6174 @cindex @code{-S}
6175 @itemx --no-keep-going
6176 @cindex @code{--no-keep-going}
6177 @itemx --stop
6178 @cindex @code{--stop}
6179 @c Extra blank line here makes the table look better.
6181 Cancel the effect of the @samp{-k} option.  This is never necessary
6182 except in a recursive @code{make} where @samp{-k} might be inherited
6183 from the top-level @code{make} via @code{MAKEFLAGS}
6184 (@pxref{Recursion, ,Recursive Use of @code{make}})
6185 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.@refill
6187 @item -t
6188 @cindex @code{-t}
6189 @itemx --touch
6190 @cindex @code{--touch}
6191 @c Extra blank line here makes the table look better.
6193 Touch files (mark them up to date without really changing them)
6194 instead of running their commands.  This is used to pretend that the
6195 commands were done, in order to fool future invocations of
6196 @code{make}.  @xref{Instead of Execution, ,Instead of Executing the Commands}.
6198 @item -v
6199 @cindex @code{-v}
6200 @itemx --version
6201 @cindex @code{--version}
6202 Print the version of the @code{make} program plus a copyright, a list
6203 of authors, and a notice that there is no warranty; then exit.
6205 @item -w
6206 @cindex @code{-w}
6207 @itemx --print-directory
6208 @cindex @code{--print-directory}
6209 Print a message containing the working directory both before and after
6210 executing the makefile.  This may be useful for tracking down errors
6211 from complicated nests of recursive @code{make} commands.
6212 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
6213 rarely need to specify this option since @samp{make} does it for you;
6214 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
6216 @itemx --no-print-directory
6217 @cindex @code{--no-print-directory}
6218 Disable printing of the working directory under @code{-w}.
6219 This option is useful when @code{-w} is turned on automatically,
6220 but you do not want to see the extra messages.
6221 @xref{-w Option, ,The @samp{--print-directory} Option}.
6223 @item -W @var{file}
6224 @cindex @code{-W}
6225 @itemx --what-if=@var{file}
6226 @cindex @code{--what-if}
6227 @itemx --new-file=@var{file}
6228 @cindex @code{--new-file}
6229 @itemx --assume-new=@var{file}
6230 @cindex @code{--assume-new}
6231 Pretend that the target @var{file} has just been modified.  When used
6232 with the @samp{-n} flag, this shows you what would happen if you were
6233 to modify that file.  Without @samp{-n}, it is almost the same as
6234 running a @code{touch} command on the given file before running
6235 @code{make}, except that the modification time is changed only in the
6236 imagination of @code{make}.
6237 @xref{Instead of Execution, ,Instead of Executing the Commands}.
6239 @item --warn-undefined-variables
6240 @cindex @code{--warn-undefined-variables}
6241 @cindex variables, warning for undefined
6242 @cindex undefined variables, warning message
6243 Issue a warning message whenever @code{make} sees a reference to an
6244 undefined variable.  This can be helpful when you are trying to debug
6245 makefiles which use variables in complex ways.
6246 @end table
6248 @node Implicit Rules, Archives, Running, Top
6249 @chapter Using Implicit Rules
6250 @cindex implicit rule
6251 @cindex rule, implicit
6253 Certain standard ways of remaking target files are used very often.  For
6254 example, one customary way to make an object file is from a C source file
6255 using the C compiler, @code{cc}.
6257 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
6258 that you do not have to specify them in detail when you want to use
6259 them.  For example, there is an implicit rule for C compilation.  File
6260 names determine which implicit rules are run.  For example, C
6261 compilation typically takes a @file{.c} file and makes a @file{.o} file.
6262 So @code{make} applies the implicit rule for C compilation when it sees
6263 this combination of file name endings.@refill
6265 A chain of implicit rules can apply in sequence; for example, @code{make}
6266 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
6267 @iftex
6268 @xref{Chained Rules, ,Chains of Implicit Rules}.
6269 @end iftex
6271 The built-in implicit rules use several variables in their commands so
6272 that, by changing the values of the variables, you can change the way the
6273 implicit rule works.  For example, the variable @code{CFLAGS} controls the
6274 flags given to the C compiler by the implicit rule for C compilation.
6275 @iftex
6276 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
6277 @end iftex
6279 You can define your own implicit rules by writing @dfn{pattern rules}.
6280 @iftex
6281 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
6282 @end iftex
6284 @dfn{Suffix rules} are a more limited way to define implicit rules.
6285 Pattern rules are more general and clearer, but suffix rules are
6286 retained for compatibility.
6287 @iftex
6288 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
6289 @end iftex
6291 @menu
6292 * Using Implicit::              How to use an existing implicit rule
6293                                   to get the commands for updating a file.
6294 * Catalogue of Rules::          A list of built-in implicit rules.
6295 * Implicit Variables::          How to change what predefined rules do.
6296 * Chained Rules::               How to use a chain of implicit rules.
6297 * Pattern Rules::               How to define new implicit rules.
6298 * Last Resort::                 How to defining commands for rules 
6299                                   which cannot find any.
6300 * Suffix Rules::                The old-fashioned style of implicit rule.
6301 * Search Algorithm::            The precise algorithm for applying 
6302                                   implicit rules.
6303 @end menu
6305 @node Using Implicit, Catalogue of Rules,  , Implicit Rules
6306 @section Using Implicit Rules
6307 @cindex implicit rule, how to use
6308 @cindex rule, implicit, how to use
6310 To allow @code{make} to find a customary method for updating a target file,
6311 all you have to do is refrain from specifying commands yourself.  Either
6312 write a rule with no command lines, or don't write a rule at all.  Then
6313 @code{make} will figure out which implicit rule to use based on which
6314 kind of source file exists or can be made.
6316 For example, suppose the makefile looks like this:
6318 @example
6319 foo : foo.o bar.o
6320         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
6321 @end example
6323 @noindent
6324 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
6325 will automatically look for an implicit rule that tells how to update it.
6326 This happens whether or not the file @file{foo.o} currently exists.
6328 If an implicit rule is found, it can supply both commands and one or
6329 more dependencies (the source files).  You would want to write a rule
6330 for @file{foo.o} with no command lines if you need to specify additional
6331 dependencies, such as header files, that the implicit rule cannot
6332 supply.
6334 Each implicit rule has a target pattern and dependency patterns.  There may
6335 be many implicit rules with the same target pattern.  For example, numerous
6336 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
6337 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
6338 that actually applies is the one whose dependencies exist or can be made.
6339 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
6340 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
6341 compiler; and so on.
6343 Of course, when you write the makefile, you know which implicit rule you
6344 want @code{make} to use, and you know it will choose that one because you
6345 know which possible dependency files are supposed to exist.
6346 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
6347 for a catalogue of all the predefined implicit rules.
6349 Above, we said an implicit rule applies if the required dependencies ``exist
6350 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
6351 the makefile as a target or a dependency, or if an implicit rule can be
6352 recursively found for how to make it.  When an implicit dependency is the
6353 result of another implicit rule, we say that @dfn{chaining} is occurring.
6354 @xref{Chained Rules, ,Chains of Implicit Rules}.
6356 In general, @code{make} searches for an implicit rule for each target, and
6357 for each double-colon rule, that has no commands.  A file that is mentioned
6358 only as a dependency is considered a target whose rule specifies nothing,
6359 so implicit rule search happens for it.  @xref{Search Algorithm, ,Implicit Rule Search Algorithm}, for the
6360 details of how the search is done.
6362 Note that explicit dependencies do not influence implicit rule search.
6363 For example, consider this explicit rule:
6365 @example
6366 foo.o: foo.p
6367 @end example
6369 @noindent
6370 The dependency on @file{foo.p} does not necessarily mean that
6371 @code{make} will remake @file{foo.o} according to the implicit rule to
6372 make an object file, a @file{.o} file, from a Pascal source file, a
6373 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
6374 rule to make an object file from a C source file is used instead,
6375 because it appears before the Pascal rule in the list of predefined
6376 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
6377 Rules}).
6379 If you do not want an implicit rule to be used for a target that has no
6380 commands, you can give that target empty commands by writing a semicolon
6381 (@pxref{Empty Commands, ,Defining Empty Commands}).
6383 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
6384 @section Catalogue of Implicit Rules
6385 @cindex implicit rule, predefined
6386 @cindex rule, implicit, predefined
6388 Here is a catalogue of predefined implicit rules which are always
6389 available unless the makefile explicitly overrides or cancels them.
6390 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
6391 canceling or overriding an implicit rule.  The @samp{-r} or
6392 @samp{--no-builtin-rules} option cancels all predefined rules.
6394 Not all of these rules will always be defined, even when the @samp{-r}
6395 option is not given.  Many of the predefined implicit rules are
6396 implemented in @code{make} as suffix rules, so which ones will be
6397 defined depends on the @dfn{suffix list} (the list of dependencies of
6398 the special target @code{.SUFFIXES}).  The default suffix list is:
6399 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
6400 @code{.C}, @code{.p}, @code{.f}, @code{.F}, @code{.r}, @code{.y},
6401 @code{.l}, @code{.s}, @code{.S}, @code{.mod}, @code{.sym}, @code{.def},
6402 @code{.h}, @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo},
6403 @code{.texi}, @code{.txinfo}, @code{.w}, @code{.ch} @code{.web},
6404 @code{.sh}, @code{.elc}, @code{.el}.  All of the implicit rules
6405 described below whose dependencies have one of these suffixes are
6406 actually suffix rules.  If you modify the suffix list, the only
6407 predefined suffix rules in effect will be those named by one or two of
6408 the suffixes that are on the list you specify; rules whose suffixes fail
6409 to be on the list are disabled.  @xref{Suffix Rules, ,Old-Fashioned
6410 Suffix Rules}, for full details on suffix rules.
6412 @table @asis
6413 @item Compiling C programs
6414 @cindex C, rule to compile
6415 @pindex cc
6416 @pindex gcc
6417 @pindex .o
6418 @pindex .c
6419 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
6420 a command of the form @samp{$(CC) -c $(CPPFLAGS) $(CFLAGS)}.@refill
6422 @item Compiling C++ programs
6423 @cindex C++, rule to compile
6424 @pindex g++
6425 @pindex .C
6426 @pindex .cc
6427 @file{@var{n}.o} is made automatically from @file{@var{n}.cc} or
6428 @file{@var{n}.C} with a command of the form @samp{$(CXX) -c $(CPPFLAGS)
6429 $(CXXFLAGS)}.  We encourage you to use the suffix @samp{.cc} for C++
6430 source files instead of @samp{.C}.@refill
6432 @item Compiling Pascal programs
6433 @cindex Pascal, rule to compile
6434 @pindex pc
6435 @pindex .p
6436 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
6437 with the command @samp{$(PC) -c $(PFLAGS)}.@refill
6439 @item Compiling Fortran and Ratfor programs
6440 @cindex Fortran, rule to compile
6441 @cindex Ratfor, rule to compile
6442 @pindex f77
6443 @pindex .f
6444 @pindex .r
6445 @pindex .F
6446 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
6447 @file{@var{n}.F} or @file{@var{n}.f} by running the
6448 Fortran compiler.  The precise command used is as follows:@refill
6450 @table @samp
6451 @item .f
6452 @samp{$(FC) -c $(FFLAGS)}.
6453 @item .F
6454 @samp{$(FC) -c $(FFLAGS) $(CPPFLAGS)}.
6455 @item .r
6456 @samp{$(FC) -c $(FFLAGS) $(RFLAGS)}.
6457 @end table
6459 @item Preprocessing Fortran and Ratfor programs
6460 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
6461 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
6462 Ratfor or preprocessable Fortran program into a strict Fortran
6463 program.  The precise command used is as follows:@refill
6465 @table @samp
6466 @item .F
6467 @samp{$(FC) -F $(CPPFLAGS) $(FFLAGS)}.
6468 @item .r
6469 @samp{$(FC) -F $(FFLAGS) $(RFLAGS)}.
6470 @end table
6472 @item Compiling Modula-2 programs
6473 @cindex Modula-2, rule to compile
6474 @pindex m2c
6475 @pindex .sym
6476 @pindex .def
6477 @pindex .mod
6478 @file{@var{n}.sym} is made from @file{@var{n}.def} with a command
6479 of the form @samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}.  @file{@var{n}.o}
6480 is made from @file{@var{n}.mod}; the form is:
6481 @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.@refill
6483 @need 1200
6484 @item Assembling and preprocessing assembler programs
6485 @cindex assembly, rule to compile
6486 @pindex as
6487 @pindex .s
6488 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
6489 running the assembler, @code{as}.  The precise command is
6490 @samp{$(AS) $(ASFLAGS)}.@refill
6492 @pindex .S
6493 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
6494 running the C preprocessor, @code{cpp}.  The precise command is
6495 @w{@samp{$(CPP) $(CPPFLAGS)}}.
6497 @item Linking a single object file
6498 @cindex linking, predefined rule for
6499 @pindex ld
6500 @pindex .o
6501 @file{@var{n}} is made automatically from @file{@var{n}.o} by running
6502 the linker (usually called @code{ld}) via the C compiler.  The precise
6503 command used is @w{@samp{$(CC) $(LDFLAGS) @var{n}.o $(LOADLIBES)}}.
6505 This rule does the right thing for a simple program with only one
6506 source file.  It will also do the right thing if there are multiple
6507 object files (presumably coming from various other source files), one
6508 of which has a name matching that of the executable file.  Thus,
6510 @example
6511 x: y.o z.o
6512 @end example
6514 @noindent
6515 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
6517 @example
6518 @group
6519 cc -c x.c -o x.o
6520 cc -c y.c -o y.o
6521 cc -c z.c -o z.o
6522 cc x.o y.o z.o -o x
6523 rm -f x.o
6524 rm -f y.o
6525 rm -f z.o
6526 @end group
6527 @end example
6529 @noindent
6530 In more complicated cases, such as when there is no object file whose
6531 name derives from the executable file name, you must write an explicit
6532 command for linking.
6534 Each kind of file automatically made into @samp{.o} object files will
6535 be automatically linked by using the compiler (@samp{$(CC)},
6536 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
6537 assemble @samp{.s} files) without the @samp{-c} option.  This could be
6538 done by using the @samp{.o} object files as intermediates, but it is
6539 faster to do the compiling and linking in one step, so that's how it's
6540 done.@refill
6542 @item Yacc for C programs
6543 @pindex yacc
6544 @cindex Yacc, rule to run
6545 @pindex .y
6546 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
6547 running Yacc with the command @samp{$(YACC) $(YFLAGS)}.
6549 @item Lex for C programs
6550 @pindex lex
6551 @cindex Lex, rule to run
6552 @pindex .l
6553 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
6554 by running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
6556 @item Lex for Ratfor programs
6557 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
6558 by running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
6560 The convention of using the same suffix @samp{.l} for all Lex files
6561 regardless of whether they produce C code or Ratfor code makes it
6562 impossible for @code{make} to determine automatically which of the two
6563 languages you are using in any particular case.  If @code{make} is
6564 called upon to remake an object file from a @samp{.l} file, it must
6565 guess which compiler to use.  It will guess the C compiler, because
6566 that is more common.  If you are using Ratfor, make sure @code{make}
6567 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
6568 are using Ratfor exclusively, with no C files, remove @samp{.c} from
6569 the list of implicit rule suffixes with:@refill
6571 @example
6572 @group
6573 .SUFFIXES:
6574 .SUFFIXES: .o .r .f .l @dots{}
6575 @end group
6576 @end example
6578 @item Making Lint Libraries from C, Yacc, or Lex programs
6579 @pindex lint
6580 @cindex @code{lint}, rule to run
6581 @pindex .ln
6582 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
6583 The precise command is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.  
6584 The same command is used on the C code produced from 
6585 @file{@var{n}.y} or @file{@var{n}.l}.@refill
6587 @item @TeX{} and Web
6588 @cindex @TeX{}, rule to run
6589 @cindex Web, rule to run
6590 @pindex tex
6591 @pindex cweave
6592 @pindex weave
6593 @pindex tangle
6594 @pindex ctangle
6595 @pindex .dvi
6596 @pindex .tex
6597 @pindex .web
6598 @pindex .w
6599 @pindex .ch
6600 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the command
6601 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
6602 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
6603 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
6604 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
6605 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
6606 or can be made) with @samp{$(CTANGLE)}.@refill
6608 @item Texinfo and Info
6609 @cindex Texinfo, rule to format
6610 @cindex Info, rule to format
6611 @pindex texi2dvi
6612 @pindex makeinfo
6613 @pindex .texinfo
6614 @pindex .info
6615 @pindex .texi
6616 @pindex .txinfo
6617 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo},
6618 @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with the command
6619 @w{@samp{$(TEXI2DVI) $(TEXI2DVI_FLAGS)}}.  @file{@var{n}.info} is made from
6620 @file{@var{n}.texinfo}, @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with
6621 the command @w{@samp{$(MAKEINFO) $(MAKEINFO_FLAGS)}}.
6623 @item RCS
6624 @cindex RCS, rule to extract from
6625 @pindex co
6626 @pindex ,v @r{(RCS file extension)}
6627 Any file @file{@var{n}} is extracted if necessary from an RCS file
6628 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
6629 command used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
6630 extracted from RCS if it already exists, even if the RCS file is
6631 newer.  The rules for RCS are terminal 
6632 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}), 
6633 so RCS files cannot be generated from another source; they must
6634 actually exist.@refill
6636 @item SCCS
6637 @cindex SCCS, rule to extract from
6638 @pindex get
6639 @pindex s. @r{(SCCS file prefix)}
6640 Any file @file{@var{n}} is extracted if necessary from an SCCS file
6641 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
6642 command used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
6643 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
6644 so SCCS files cannot be generated from another source; they must
6645 actually exist.@refill
6647 @pindex .sh
6648 For the benefit of SCCS, a file @file{@var{n}} is copied from
6649 @file{@var{n}.sh} and made executable (by everyone).  This is for
6650 shell scripts that are checked into SCCS.  Since RCS preserves the
6651 execution permission of a file, you do not need to use this feature
6652 with RCS.@refill
6654 We recommend that you avoid using of SCCS.  RCS is widely held to be
6655 superior, and is also free.  By choosing free software in place of
6656 comparable (or inferior) proprietary software, you support the free
6657 software movement.
6658 @end table
6660 Usually, you want to change only the variables listed in the table
6661 above, which are documented in the following section.
6663 However, the commands in built-in implicit rules actually use
6664 variables such as @code{COMPILE.c}, @code{LINK.p}, and
6665 @code{PREPROCESS.S}, whose values contain the commands listed above.
6667 @code{make} follows the convention that the rule to compile a
6668 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
6669 Similarly, the rule to produce an executable from a @file{.@var{x}}
6670 file uses @code{LINK.@var{x}}; and the rule to preprocess a
6671 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
6673 @vindex OUTPUT_OPTION
6674 Every rule that produces an object file uses the variable
6675 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
6676 contain @samp{-o $@@}, or to be empty, depending on a compile-time
6677 option.  You need the @samp{-o} option to ensure that the output goes
6678 into the right file when the source file is in a different directory,
6679 as when using @code{VPATH} (@pxref{Directory Search}).  However,
6680 compilers on some systems do not accept a @samp{-o} switch for object
6681 files.  If you use such a system, and use @code{VPATH}, some
6682 compilations will put their output in the wrong place.
6683 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
6684 the value @w{@samp{; mv $*.o $@@}}.
6686 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
6687 @section Variables Used by Implicit Rules
6688 @cindex flags for compilers
6690 The commands in built-in implicit rules make liberal use of certain
6691 predefined variables.  You can alter these variables in the makefile,
6692 with arguments to @code{make}, or in the environment to alter how the
6693 implicit rules work without redefining the rules themselves.
6695 For example, the command used to compile a C source file actually says
6696 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
6697 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
6698 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
6699 used for all C compilations performed by the implicit rule.  By redefining
6700 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
6701 each compilation.  @emph{All} implicit rules that do C compilation use
6702 @samp{$(CC)} to get the program name for the compiler and @emph{all}
6703 include @samp{$(CFLAGS)} among the arguments given to the compiler.@refill
6705 The variables used in implicit rules fall into two classes: those that are
6706 names of programs (like @code{CC}) and those that contain arguments for the
6707 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
6708 some command arguments, but it must start with an actual executable program
6709 name.)  If a variable value contains more than one argument, separate them
6710 with spaces.
6712 Here is a table of variables used as names of programs in built-in rules:
6714 @table @code
6715 @item AR
6716 @vindex AR
6717 Archive-maintaining program; default @samp{ar}.
6718 @pindex ar
6720 @item AS
6721 @vindex AS
6722 Program for doing assembly; default @samp{as}.
6723 @pindex as
6725 @item CC
6726 @vindex CC
6727 Program for compiling C programs; default @samp{cc}.
6728 @pindex cc
6730 @item CXX
6731 @vindex CXX
6732 Program for compiling C++ programs; default @samp{g++}.
6733 @pindex g++
6735 @item CO
6736 @vindex CO
6737 Program for extracting a file from RCS; default @samp{co}.
6738 @pindex co
6740 @item CPP
6741 @vindex CPP
6742 Program for running the C preprocessor, with results to standard output;
6743 default @samp{$(CC) -E}.
6745 @item FC
6746 @vindex FC
6747 Program for compiling or preprocessing Fortran and Ratfor programs;
6748 default @samp{f77}.
6749 @pindex f77
6751 @item GET
6752 @vindex GET
6753 Program for extracting a file from SCCS; default @samp{get}.
6754 @pindex get
6756 @item LEX
6757 @vindex LEX
6758 Program to use to turn Lex grammars into C programs or Ratfor programs;
6759 default @samp{lex}.
6760 @pindex lex
6762 @item PC
6763 @vindex PC
6764 Program for compiling Pascal programs; default @samp{pc}.
6765 @pindex pc
6767 @item YACC
6768 @vindex YACC
6769 Program to use to turn Yacc grammars into C programs; default @samp{yacc}.
6770 @pindex yacc
6772 @item YACCR
6773 @vindex YACCR
6774 Program to use to turn Yacc grammars into Ratfor
6775 programs; default @samp{yacc -r}.
6777 @item MAKEINFO
6778 @vindex MAKEINFO
6779 Program to convert a Texinfo source file into an Info file; default
6780 @samp{makeinfo}.
6781 @pindex makeinfo
6783 @item TEX
6784 @vindex TEX
6785 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
6786 default @samp{tex}.
6787 @pindex tex
6789 @item TEXI2DVI
6790 @vindex TEXI2DVI
6791 Program to make @TeX{} @sc{dvi} files from Texinfo source;
6792 default @samp{texi2dvi}.
6793 @pindex texi2dvi
6795 @item WEAVE
6796 @vindex WEAVE
6797 Program to translate Web into @TeX{}; default @samp{weave}.
6798 @pindex weave
6800 @item CWEAVE
6801 @vindex CWEAVE
6802 Program to translate C Web into @TeX{}; default @samp{cweave}.
6803 @pindex cweave
6805 @item TANGLE
6806 @vindex TANGLE
6807 Program to translate Web into Pascal; default @samp{tangle}.
6808 @pindex tangle
6810 @item CTANGLE
6811 @vindex CTANGLE
6812 Program to translate C Web into C; default @samp{ctangle}.
6813 @pindex ctangle
6815 @item RM
6816 @vindex RM
6817 Command to remove a file; default @samp{rm -f}.
6818 @pindex rm
6819 @end table
6821 Here is a table of variables whose values are additional arguments for the
6822 programs above.  The default values for all of these is the empty
6823 string, unless otherwise noted.
6825 @table @code
6826 @item ARFLAGS
6827 @vindex ARFLAGS
6828 Flags to give the archive-maintaining program; default @samp{rv}.
6830 @item ASFLAGS
6831 @vindex ASFLAGS
6832 Extra flags to give to the assembler (when explicitly
6833 invoked on a @samp{.s} or @samp{.S} file).
6835 @item CFLAGS
6836 @vindex CFLAGS
6837 Extra flags to give to the C compiler.
6839 @item CXXFLAGS
6840 @vindex CXXFLAGS
6841 Extra flags to give to the C++ compiler.
6843 @item COFLAGS
6844 @vindex COFLAGS
6845 Extra flags to give to the RCS @code{co} program.
6847 @item CPPFLAGS
6848 @vindex CPPFLAGS
6849 Extra flags to give to the C preprocessor and programs
6850 that use it (the C and Fortran compilers).
6852 @item FFLAGS
6853 @vindex FFLAGS
6854 Extra flags to give to the Fortran compiler.
6856 @item GFLAGS
6857 @vindex GFLAGS
6858 Extra flags to give to the SCCS @code{get} program.
6860 @item LDFLAGS
6861 @vindex LDFLAGS
6862 Extra flags to give to compilers when they are
6863 supposed to invoke the linker, @samp{ld}.
6865 @item LFLAGS
6866 @vindex LFLAGS
6867 Extra flags to give to Lex.
6869 @item PFLAGS
6870 @vindex PFLAGS
6871 Extra flags to give to the Pascal compiler.
6873 @item RFLAGS
6874 @vindex RFLAGS
6875 Extra flags to give to the Fortran compiler for Ratfor programs.
6877 @item YFLAGS
6878 @vindex YFLAGS
6879 Extra flags to give to Yacc.
6880 @end table
6882 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
6883 @section Chains of Implicit Rules
6885 @cindex chains of rules
6886 @cindex rule, implicit, chains of
6887 Sometimes a file can be made by a sequence of implicit rules.  For example,
6888 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
6889 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
6891 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
6892 special searching is required: @code{make} finds that the object file can
6893 be made by C compilation from @file{@var{n}.c}; later on, when considering
6894 how to make @file{@var{n}.c}, the rule for running Yacc is
6895 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
6896 updated.@refill
6898 @cindex intermediate files
6899 @cindex files, intermediate
6900 However, even if @file{@var{n}.c} does not exist and is not mentioned,
6901 @code{make} knows how to envision it as the missing link between
6902 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
6903 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
6904 intermediate file, it is entered in the data base as if it had been
6905 mentioned in the makefile, along with the implicit rule that says how to
6906 create it.@refill
6908 Intermediate files are remade using their rules just like all other
6909 files.  The difference is that the intermediate file is deleted when
6910 @code{make} is finished.  Therefore, the intermediate file which did not
6911 exist before @code{make} also does not exist after @code{make}.  The
6912 deletion is reported to you by printing a @samp{rm -f} command that
6913 shows what @code{make} is doing.  (You can list the target pattern of an
6914 implicit rule (such as @samp{%.o}) as a dependency of the special
6915 target @code{.PRECIOUS} to preserve intermediate files made by implicit
6916 rules whose target patterns match that file's name; 
6917 see @ref{Interrupts}.)@refill
6918 @cindex intermediate files, preserving
6919 @cindex preserving intermediate files
6920 @cindex preserving with @code{.PRECIOUS}
6921 @cindex @code{.PRECIOUS} intermediate files
6923 A chain can involve more than two implicit rules.  For example, it is
6924 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
6925 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
6926 intermediate files that are deleted at the end.@refill
6928 No single implicit rule can appear more than once in a chain.  This means
6929 that @code{make} will not even consider such a ridiculous thing as making
6930 @file{foo} from @file{foo.o.o} by running the linker twice.  This
6931 constraint has the added benefit of preventing any infinite loop in the
6932 search for an implicit rule chain.
6934 There are some special implicit rules to optimize certain cases that would
6935 otherwise be handled by rule chains.  For example, making @file{foo} from
6936 @file{foo.c} could be handled by compiling and linking with separate
6937 chained rules, using @file{foo.o} as an intermediate file.  But what
6938 actually happens is that a special rule for this case does the compilation
6939 and linking with a single @code{cc} command.  The optimized rule is used in
6940 preference to the step-by-step chain because it comes earlier in the
6941 ordering of rules.
6943 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
6944 @section Defining and Redefining Pattern Rules
6946 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
6947 rule looks like an ordinary rule, except that its target contains the
6948 character @samp{%} (exactly one of them).  The target is considered a
6949 pattern for matching file names; the @samp{%} can match any nonempty
6950 substring, while other characters match only themselves.  The dependencies
6951 likewise use @samp{%} to show how their names relate to the target name.
6953 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
6954 @file{@var{stem}.o} from another file @file{@var{stem}.c}.@refill
6956 Note that expansion using @samp{%} in pattern rules occurs
6957 @strong{after} any variable or function expansions, which take place
6958 when the makefile is read.  @xref{Using Variables, , How to Use
6959 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
6961 @menu
6962 * Pattern Intro::               An introduction to pattern rules.
6963 * Pattern Examples::            Examples of pattern rules.
6964 * Automatic::                   How to use automatic variables in the
6965                                   commands of implicit rules.
6966 * Pattern Match::               How patterns match.
6967 * Match-Anything Rules::        Precautions you should take prior to
6968                                   defining rules that can match any
6969                                   target file whatever.
6970 * Canceling Rules::             How to override or cancel built-in rules.
6971 @end menu
6973 @node Pattern Intro, Pattern Examples,  , Pattern Rules
6974 @subsection Introduction to Pattern Rules
6975 @cindex pattern rule
6976 @cindex rule, pattern
6978 A pattern rule contains the character @samp{%} (exactly one of them)
6979 in the target; otherwise, it looks exactly like an ordinary rule.  The
6980 target is a pattern for matching file names; the @samp{%} matches any
6981 nonempty substring, while other characters match only themselves.
6982 @cindex target pattern, implicit
6983 @cindex @code{%}, in pattern rules
6985 For example, @samp{%.c} as a pattern matches any file name that ends in
6986 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
6987 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
6988 (There must be at least one character to match the @samp{%}.)  The substring
6989 that the @samp{%} matches is called the @dfn{stem}.@refill
6991 @samp{%} in a dependency of a pattern rule stands for the same stem
6992 that was matched by the @samp{%} in the target.  In order for
6993 the pattern rule to apply, its target pattern must match the file name
6994 under consideration, and its dependency patterns must name files that
6995 exist or can be made.  These files become dependencies of the target.
6996 @cindex dependency pattern, implicit
6998 Thus, a rule of the form
7000 @example
7001 %.o : %.c ; @var{command}@dots{}
7002 @end example
7004 @noindent
7005 specifies how to make a file @file{@var{n}.o}, with another file
7006 @file{@var{n}.c} as its dependency, provided that @file{@var{n}.c}
7007 exists or can be made.
7009 There may also be dependencies that do not use @samp{%}; such a dependency
7010 attaches to every file made by this pattern rule.  These unvarying
7011 dependencies are useful occasionally.
7013 A pattern rule need not have any dependencies that contain @samp{%}, or
7014 in fact any dependencies at all.  Such a rule is effectively a general
7015 wildcard.  It provides a way to make any file that matches the target
7016 pattern.  @xref{Last Resort}.
7018 @c !!! The end of of this paragraph should be rewritten.  --bob
7019 Pattern rules may have more than one target.  Unlike normal rules, this
7020 does not act as many different rules with the same dependencies and
7021 commands.  If a pattern rule has multiple targets, @code{make} knows that
7022 the rule's commands are responsible for making all of the targets.  The
7023 commands are executed only once to make all the targets.  When searching
7024 for a pattern rule to match a target, the target patterns of a rule other
7025 than the one that matches the target in need of a rule are incidental:
7026 @code{make} worries only about giving commands and dependencies to the file
7027 presently in question.  However, when this file's commands are run, the
7028 other targets are marked as having been updated themselves.
7029 @cindex multiple targets, in pattern rule
7030 @cindex target, multiple in pattern rule
7032 The order in which pattern rules appear in the makefile is important
7033 since this is the order in which they are considered.
7034 Of equally applicable
7035 rules, only the first one found is used.  The rules you write take precedence
7036 over those that are built in.  Note however, that a rule whose
7037 dependencies actually exist or are mentioned always takes priority over a
7038 rule with dependencies that must be made by chaining other implicit rules.
7039 @cindex pattern rules, order of
7040 @cindex order of pattern rules
7042 @node Pattern Examples, Automatic, Pattern Intro, Pattern Rules
7043 @subsection Pattern Rule Examples
7045 Here are some examples of pattern rules actually predefined in
7046 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
7047 files:@refill
7049 @example
7050 %.o : %.c
7051         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
7052 @end example
7054 @noindent
7055 defines a rule that can make any file @file{@var{x}.o} from
7056 @file{@var{x}.c}.  The command uses the automatic variables @samp{$@@} and
7057 @samp{$<} to substitute the names of the target file and the source file
7058 in each case where the rule applies (@pxref{Automatic, ,Automatic Variables}).@refill
7060 Here is a second built-in rule:
7062 @example
7063 % :: RCS/%,v
7064         $(CO) $(COFLAGS) $<
7065 @end example
7067 @noindent
7068 defines a rule that can make any file @file{@var{x}} whatsoever from a
7069 corresponding file @file{@var{x},v} in the subdirectory @file{RCS}.  Since
7070 the target is @samp{%}, this rule will apply to any file whatever, provided
7071 the appropriate dependency file exists.  The double colon makes the rule
7072 @dfn{terminal}, which means that its dependency may not be an intermediate
7073 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).@refill
7075 @need 500
7076 This pattern rule has two targets:
7078 @example
7079 @group
7080 %.tab.c %.tab.h: %.y
7081         bison -d $<
7082 @end group
7083 @end example
7085 @noindent
7086 @c The following paragraph is rewritten to avoid overfull hboxes
7087 This tells @code{make} that the command @samp{bison -d @var{x}.y} will
7088 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
7089 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
7090 and the file @file{scan.o} depends on the file @file{parse.tab.h},
7091 when @file{parse.y} is changed, the command @samp{bison -d parse.y}
7092 will be executed only once, and the dependencies of both
7093 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
7094 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
7095 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
7096 linked from @file{parse.tab.o}, @file{scan.o}, and its other
7097 dependencies, and it will execute happily ever after.)@refill
7099 @node Automatic, Pattern Match, Pattern Examples, Pattern Rules
7100 @subsection Automatic Variables
7101 @cindex automatic variables
7102 @cindex variables, automatic
7103 @cindex variables, and implicit rule
7105 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
7106 @samp{.o} file: how do you write the @samp{cc} command so that it operates
7107 on the right source file name?  You cannot write the name in the command,
7108 because the name is different each time the implicit rule is applied.
7110 What you do is use a special feature of @code{make}, the @dfn{automatic
7111 variables}.  These variables have values computed afresh for each rule that
7112 is executed, based on the target and dependencies of the rule.  In this
7113 example, you would use @samp{$@@} for the object file name and @samp{$<}
7114 for the source file name.
7116 Here is a table of automatic variables:
7118 @table @code
7119 @vindex $@@
7120 @vindex @@ @r{(automatic variable)}
7121 @item $@@
7122 The file name of the target of the rule.  If the target is an archive
7123 member, then @samp{$@@} is the name of the archive file.  In a pattern
7124 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
7125 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
7126 rule's commands to be run.
7128 @vindex $%
7129 @vindex % @r{(automatic variable)}
7130 @item $%
7131 The target member name, when the target is an archive member.
7132 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
7133 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
7134 empty when the target is not an archive member.
7136 @vindex $<
7137 @vindex < @r{(automatic variable)}
7138 @item $<
7139 The name of the first dependency.  If the target got its commands from
7140 an implicit rule, this will be the first dependency added by the
7141 implicit rule (@pxref{Implicit Rules}).
7143 @vindex $?
7144 @vindex ? @r{(automatic variable)}
7145 @item $?
7146 The names of all the dependencies that are newer than the target, with
7147 spaces between them.  For dependencies which are archive members, only
7148 the member named is used (@pxref{Archives}).
7149 @cindex dependencies, list of changed
7150 @cindex list of changed dependencies
7152 @vindex $^
7153 @vindex ^ @r{(automatic variable)}
7154 @item $^
7155 The names of all the dependencies, with spaces between them.  For
7156 dependencies which are archive members, only the member named is used
7157 (@pxref{Archives}).  A target has only one dependency on each other file
7158 it depends on, no matter how many times each file is listed as a
7159 dependency.  So if you list a dependency more than once for a target,
7160 the value of @code{$^} contains just one copy of the name.
7161 @cindex dependencies, list of all
7162 @cindex list of all dependencies
7164 @vindex $+
7165 @vindex + @r{(automatic variable)}
7166 @item $+
7167 This is like @samp{$^}, but dependencies listed more than once are
7168 duplicated in the order they were listed in the makefile.  This is
7169 primarily useful for use in linking commands where it is meaningful to
7170 repeat library file names in a particular order.
7172 @vindex $*
7173 @vindex * @r{(automatic variable)}
7174 @item $*
7175 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
7176 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
7177 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
7178 useful for constructing names of related files.@refill
7179 @cindex stem, variable for
7181 In a static pattern rule, the stem is part of the file name that matched
7182 the @samp{%} in the target pattern.
7184 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
7185 in that way.  Instead, if the target name ends with a recognized suffix
7186 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
7187 the target name minus the suffix.  For example, if the target name is
7188 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
7189 suffix.  GNU @code{make} does this bizarre thing only for compatibility
7190 with other implementations of @code{make}.  You should generally avoid
7191 using @samp{$*} except in implicit rules or static pattern rules.@refill
7193 If the target name in an explicit rule does not end with a recognized
7194 suffix, @samp{$*} is set to the empty string for that rule.
7195 @end table
7197 @samp{$?} is useful even in explicit rules when you wish to operate on only
7198 the dependencies that have changed.  For example, suppose that an archive
7199 named @file{lib} is supposed to contain copies of several object files.
7200 This rule copies just the changed object files into the archive:
7202 @example
7203 @group
7204 lib: foo.o bar.o lose.o win.o
7205         ar r lib $?
7206 @end group
7207 @end example
7209 Of the variables listed above, four have values that are single file
7210 names, and two have values that are lists of file names.  These six have
7211 variants that get just the file's directory name or just the file name
7212 within the directory.  The variant variables' names are formed by
7213 appending @samp{D} or @samp{F}, respectively.  These variants are
7214 semi-obsolete in GNU @code{make} since the functions @code{dir} and
7215 @code{notdir} can be used to get a similar effect (@pxref{Filename
7216 Functions, , Functions for File Names}).  Note, however, that the
7217 @samp{F} variants all omit the trailing slash which always appears in
7218 the output of the @code{dir} function.  Here is a table of the variants:
7220 @table @samp
7221 @vindex $(@@D)
7222 @vindex @@D @r{(automatic variable)}
7223 @item $(@@D)
7224 The directory part of the file name of the target, with the trailing
7225 slash removed.  If the value of @samp{$@@} is @file{dir/foo.o} then
7226 @samp{$(@@D)} is @file{dir}.  This value is @file{.} if @samp{$@@} does
7227 not contain a slash.
7229 @vindex $(@@F)
7230 @vindex @@F @r{(automatic variable)}
7231 @item $(@@F)
7232 The file-within-directory part of the file name of the target.  If the
7233 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
7234 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
7236 @vindex $(*D)
7237 @vindex *D @r{(automatic variable)}
7238 @item $(*D)
7239 @vindex $(*F)
7240 @vindex *F @r{(automatic variable)}
7241 @itemx $(*F)
7242 The directory part and the file-within-directory
7243 part of the stem; @file{dir} and @file{foo} in this example.
7245 @vindex $(%D)
7246 @vindex %D @r{(automatic variable)}
7247 @item $(%D)
7248 @vindex $(%F)
7249 @vindex %F @r{(automatic variable)}
7250 @itemx $(%F)
7251 The directory part and the file-within-directory part of the target
7252 archive member name.  This makes sense only for archive member targets
7253 of the form @file{@var{archive}(@var{member})} and is useful only when
7254 @var{member} may contain a directory name.  (@xref{Archive Members,
7255 ,Archive Members as Targets}.)
7257 @vindex $(<D)
7258 @vindex <D @r{(automatic variable)}
7259 @item $(<D)
7260 @vindex $(<F)
7261 @vindex <F @r{(automatic variable)}
7262 @itemx $(<F)
7263 The directory part and the file-within-directory
7264 part of the first dependency.
7266 @vindex $(^D)
7267 @vindex ^D @r{(automatic variable)}
7268 @item $(^D)
7269 @vindex $(^F)
7270 @vindex ^F @r{(automatic variable)}
7271 @itemx $(^F)
7272 Lists of the directory parts and the file-within-directory
7273 parts of all dependencies.
7275 @vindex $(?D)
7276 @vindex ?D @r{(automatic variable)}
7277 @item $(?D)
7278 @vindex $(?F)
7279 @vindex ?F @r{(automatic variable)}
7280 @itemx $(?F)
7281 Lists of the directory parts and the file-within-directory parts of
7282 all dependencies that are newer than the target.
7283 @end table
7285 Note that we use a special stylistic convention when we talk about these
7286 automatic variables; we write ``the value of @samp{$<}'', rather than
7287 @w{``the variable @code{<}''} as we would write for ordinary variables
7288 such as @code{objects} and @code{CFLAGS}.  We think this convention
7289 looks more natural in this special case.  Please do not assume it has a
7290 deep significance; @samp{$<} refers to the variable named @code{<} just
7291 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
7292 You could just as well use @samp{$(<)} in place of @samp{$<}.
7294 @node Pattern Match, Match-Anything Rules, Automatic, Pattern Rules
7295 @subsection How Patterns Match
7297 @cindex stem
7298 A target pattern is composed of a @samp{%} between a prefix and a suffix,
7299 either or both of which may be empty.  The pattern matches a file name only
7300 if the file name starts with the prefix and ends with the suffix, without
7301 overlap.  The text between the prefix and the suffix is called the
7302 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
7303 @file{test.o}, the stem is @samp{test}.  The pattern rule dependencies are
7304 turned into actual file names by substituting the stem for the character
7305 @samp{%}.  Thus, if in the same example one of the dependencies is written
7306 as @samp{%.c}, it expands to @samp{test.c}.@refill
7308 When the target pattern does not contain a slash (and it usually does
7309 not), directory names in the file names are removed from the file name
7310 before it is compared with the target prefix and suffix.  After the
7311 comparison of the file name to the target pattern, the directory
7312 names, along with the slash that ends them, are added on to the
7313 dependency file names generated from the pattern rule's dependency
7314 patterns and the file name. The directories are ignored only for the
7315 purpose of finding an implicit rule to use, not in the application of
7316 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
7317 with @samp{src/a} as the stem.  When dependencies are turned into file
7318 names, the directories from the stem are added at the front, while the
7319 rest of the stem is substituted for the @samp{%}.  The stem
7320 @samp{src/a} with a dependency pattern @samp{c%r} gives the file name
7321 @file{src/car}.@refill
7323 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
7324 @subsection Match-Anything Pattern Rules
7326 @cindex match-anything rule
7327 @cindex terminal rule
7328 When a pattern rule's target is just @samp{%}, it matches any file name
7329 whatever.  We call these rules @dfn{match-anything} rules.  They are very
7330 useful, but it can take a lot of time for @code{make} to think about them,
7331 because it must consider every such rule for each file name listed either
7332 as a target or as a dependency.
7334 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
7335 would have to consider making it by linking an object file @file{foo.c.o},
7336 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
7337 Pascal compilation-and-linking from @file{foo.c.p}, and many other
7338 possibilities.
7340 We know these possibilities are ridiculous since @file{foo.c} is a C source
7341 file, not an executable.  If @code{make} did consider these possibilities,
7342 it would ultimately reject them, because files such as @file{foo.c.o} and
7343 @file{foo.c.p} would not exist.  But these possibilities are so
7344 numerous that @code{make} would run very slowly if it had to consider
7345 them.@refill
7347 To gain speed, we have put various constraints on the way @code{make}
7348 considers match-anything rules.  There are two different constraints that
7349 can be applied, and each time you define a match-anything rule you must
7350 choose one or the other for that rule.
7352 One choice is to mark the match-anything rule as @dfn{terminal} by defining
7353 it with a double colon.  When a rule is terminal, it does not apply unless
7354 its dependencies actually exist.  Dependencies that could be made with
7355 other implicit rules are not good enough.  In other words, no further
7356 chaining is allowed beyond a terminal rule.
7358 For example, the built-in implicit rules for extracting sources from RCS
7359 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
7360 not exist, @code{make} will not even consider trying to make it as an
7361 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
7362 RCS and SCCS files are generally ultimate source files, which should not be
7363 remade from any other files; therefore, @code{make} can save time by not
7364 looking for ways to remake them.@refill
7366 If you do not mark the match-anything rule as terminal, then it is
7367 nonterminal.  A nonterminal match-anything rule cannot apply to a file name
7368 that indicates a specific type of data.  A file name indicates a specific
7369 type of data if some non-match-anything implicit rule target matches it.
7371 For example, the file name @file{foo.c} matches the target for the pattern
7372 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
7373 rule is actually applicable (which happens only if there is a file
7374 @file{foo.y}), the fact that its target matches is enough to prevent
7375 consideration of any nonterminal match-anything rules for the file
7376 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
7377 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
7378 @file{foo.c.p}, etc.@refill
7380 The motivation for this constraint is that nonterminal match-anything
7381 rules are used for making files containing specific types of data (such as
7382 executable files) and a file name with a recognized suffix indicates some
7383 other specific type of data (such as a C source file).
7385 Special built-in dummy pattern rules are provided solely to recognize
7386 certain file names so that nonterminal match-anything rules will not be
7387 considered.  These dummy rules have no dependencies and no commands, and
7388 they are ignored for all other purposes.  For example, the built-in
7389 implicit rule
7391 @example
7392 %.p :
7393 @end example
7395 @noindent
7396 exists to make sure that Pascal source files such as @file{foo.p} match a
7397 specific target pattern and thereby prevent time from being wasted looking
7398 for @file{foo.p.o} or @file{foo.p.c}.
7400 Dummy pattern rules such as the one for @samp{%.p} are made for every
7401 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
7403 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
7404 @subsection Canceling Implicit Rules
7406 You can override a built-in implicit rule (or one you have defined
7407 yourself) by defining a new pattern rule with the same target and
7408 dependencies, but different commands.  When the new rule is defined, the
7409 built-in one is replaced.  The new rule's position in the sequence of
7410 implicit rules is determined by where you write the new rule.
7412 You can cancel a built-in implicit rule by defining a pattern rule with the
7413 same target and dependencies, but no commands.  For example, the following
7414 would cancel the rule that runs the assembler:
7416 @example
7417 %.o : %.s
7418 @end example
7420 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
7421 @section Defining Last-Resort Default Rules
7422 @cindex last-resort default rules
7423 @cindex default rules, last-resort
7425 You can define a last-resort implicit rule by writing a terminal
7426 match-anything pattern rule with no dependencies (@pxref{Match-Anything
7427 Rules}).  This is just like any other pattern rule; the only thing
7428 special about it is that it will match any target.  So such a rule's
7429 commands are used for all targets and dependencies that have no commands
7430 of their own and for which no other implicit rule applies.
7432 For example, when testing a makefile, you might not care if the source
7433 files contain real data, only that they exist.  Then you might do this:
7435 @example
7437         touch $@@
7438 @end example
7440 @noindent
7441 to cause all the source files needed (as dependencies) to be created
7442 automatically.
7444 @findex .DEFAULT
7445 You can instead define commands to be used for targets for which there
7446 are no rules at all, even ones which don't specify commands.  You do
7447 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
7448 commands are used for all dependencies which do not appear as targets in
7449 any explicit rule, and for which no implicit rule applies.  Naturally,
7450 there is no @code{.DEFAULT} rule unless you write one.
7452 If you use @code{.DEFAULT} with no commands or dependencies:
7454 @example
7455 .DEFAULT:
7456 @end example
7458 @noindent
7459 the commands previously stored for @code{.DEFAULT} are cleared.
7460 Then @code{make} acts as if you had never defined @code{.DEFAULT} at all.
7462 If you do not want a target to get the commands from a match-anything
7463 pattern rule or @code{.DEFAULT}, but you also do not want any commands
7464 to be run for the target, you can give it empty commands (@pxref{Empty
7465 Commands, ,Defining Empty Commands}).@refill
7467 You can use a last-resort rule to override part of another makefile.
7468 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
7470 @node Suffix Rules, Search Algorithm, Last Resort, Implicit Rules
7471 @section Old-Fashioned Suffix Rules
7472 @cindex old-fashioned suffix rules
7473 @cindex suffix rule
7475 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
7476 @code{make}.  Suffix rules are obsolete because pattern rules are more
7477 general and clearer.  They are supported in GNU @code{make} for
7478 compatibility with old makefiles.  They come in two kinds:
7479 @dfn{double-suffix} and @dfn{single-suffix}.@refill
7481 A double-suffix rule is defined by a pair of suffixes: the target suffix
7482 and the source suffix.  It matches any file whose name ends with the
7483 target suffix.  The corresponding implicit dependency is made by
7484 replacing the target suffix with the source suffix in the file name.  A
7485 two-suffix rule whose target and source suffixes are @samp{.o} and
7486 @samp{.c} is equivalent to the pattern rule @samp{%.o : %.c}.
7488 A single-suffix rule is defined by a single suffix, which is the source
7489 suffix.  It matches any file name, and the corresponding implicit
7490 dependency name is made by appending the source suffix.  A single-suffix
7491 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
7492 @samp{% : %.c}.
7494 Suffix rule definitions are recognized by comparing each rule's target
7495 against a defined list of known suffixes.  When @code{make} sees a rule
7496 whose target is a known suffix, this rule is considered a single-suffix
7497 rule.  When @code{make} sees a rule whose target is two known suffixes
7498 concatenated, this rule is taken as a double-suffix rule.
7500 For example, @samp{.c} and @samp{.o} are both on the default list of
7501 known suffixes.  Therefore, if you define a rule whose target is
7502 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
7503 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
7504 way to define the rule for compiling a C source file:@refill
7506 @example
7507 .c.o:
7508         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7509 @end example
7511 Suffix rules cannot have any dependencies of their own.  If they have any,
7512 they are treated as normal files with funny names, not as suffix rules.
7513 Thus, the rule:
7515 @example
7516 .c.o: foo.h
7517         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7518 @end example
7520 @noindent
7521 tells how to make the file @file{.c.o} from the dependency file
7522 @file{foo.h}, and is not at all like the pattern rule:
7524 @example
7525 %.o: %.c foo.h
7526         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
7527 @end example
7529 @noindent
7530 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
7531 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
7533 Suffix rules with no commands are also meaningless.  They do not remove
7534 previous rules as do pattern rules with no commands (@pxref{Canceling
7535 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or pair of suffixes concatenated as
7536 a target in the data base.@refill
7538 @findex .SUFFIXES
7539 The known suffixes are simply the names of the dependencies of the special
7540 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
7541 for @code{.SUFFIXES} that adds more dependencies, as in:
7543 @example
7544 .SUFFIXES: .hack .win
7545 @end example
7547 @noindent
7548 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
7550 If you wish to eliminate the default known suffixes instead of just adding
7551 to them, write a rule for @code{.SUFFIXES} with no dependencies.  By
7552 special dispensation, this eliminates all existing dependencies of
7553 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
7554 want.  For example,
7556 @example
7557 @group
7558 .SUFFIXES:            # @r{Delete the default suffixes}
7559 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
7560 @end group
7561 @end example
7563 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
7564 list of suffixes to be empty.
7566 @vindex SUFFIXES
7567 The variable @code{SUFFIXES} is defined to the default list of suffixes
7568 before @code{make} reads any makefiles.  You can change the list of suffixes
7569 with a rule for the special target @code{.SUFFIXES}, but that does not alter
7570 this variable.
7572 @node Search Algorithm,  , Suffix Rules, Implicit Rules
7573 @section Implicit Rule Search Algorithm
7574 @cindex implicit rule, search algorithm
7575 @cindex search algorithm, implicit rule
7577 Here is the procedure @code{make} uses for searching for an implicit rule
7578 for a target @var{t}.  This procedure is followed for each double-colon
7579 rule with no commands, for each target of ordinary rules none of which have
7580 commands, and for each dependency that is not the target of any rule.  It
7581 is also followed recursively for dependencies that come from implicit
7582 rules, in the search for a chain of rules.
7584 Suffix rules are not mentioned in this algorithm because suffix rules are
7585 converted to equivalent pattern rules once the makefiles have been read in.
7587 For an archive member target of the form
7588 @samp{@var{archive}(@var{member})}, the following algorithm is run
7589 twice, first using the entire target name @var{t}, and second using
7590 @samp{(@var{member})} as the target @var{t} if the first run found no
7591 rule.@refill
7593 @enumerate
7594 @item
7595 Split @var{t} into a directory part, called @var{d}, and the rest,
7596 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
7597 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.@refill
7599 @item
7600 Make a list of all the pattern rules one of whose targets matches
7601 @var{t} or @var{n}.  If the target pattern contains a slash, it is
7602 matched against @var{t}; otherwise, against @var{n}.
7604 @item
7605 If any rule in that list is @emph{not} a match-anything rule, then
7606 remove all nonterminal match-anything rules from the list.
7608 @item
7609 Remove from the list all rules with no commands.
7611 @item
7612 For each pattern rule in the list:
7614 @enumerate a
7615 @item
7616 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
7617 matched by the @samp{%} in the target pattern.@refill
7619 @item
7620 Compute the dependency names by substituting @var{s} for @samp{%}; if
7621 the target pattern does not contain a slash, append @var{d} to
7622 the front of each dependency name.@refill
7624 @item
7625 Test whether all the dependencies exist or ought to exist.  (If a
7626 file name is mentioned in the makefile as a target or as an explicit
7627 dependency, then we say it ought to exist.)
7629 If all dependencies exist or ought to exist, or there are no dependencies,
7630 then this rule applies.
7631 @end enumerate
7633 @item
7634 If no pattern rule has been found so far, try harder.
7635 For each pattern rule in the list:
7637 @enumerate a
7638 @item
7639 If the rule is terminal, ignore it and go on to the next rule.
7641 @item
7642 Compute the dependency names as before.
7644 @item
7645 Test whether all the dependencies exist or ought to exist.
7647 @item
7648 For each dependency that does not exist, follow this algorithm
7649 recursively to see if the dependency can be made by an implicit
7650 rule.
7652 @item
7653 If all dependencies exist, ought to exist, or can be
7654 made by implicit rules, then this rule applies.
7655 @end enumerate
7657 @item
7658 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
7659 applies.  In that case, give @var{t} the same commands that
7660 @code{.DEFAULT} has.  Otherwise, there are no commands for @var{t}.
7661 @end enumerate
7663 Once a rule that applies has been found, for each target pattern of the
7664 rule other than the one that matched @var{t} or @var{n}, the @samp{%} in
7665 the pattern is replaced with @var{s} and the resultant file name is stored
7666 until the commands to remake the target file @var{t} are executed.  After
7667 these commands are executed, each of these stored file names are entered
7668 into the data base and marked as having been updated and having the same
7669 update status as the file @var{t}.
7671 When the commands of a pattern rule are executed for @var{t}, the automatic
7672 variables are set corresponding to the target and dependencies.
7673 @xref{Automatic, ,Automatic Variables}.
7675 @node Archives, Features, Implicit Rules, Top
7676 @chapter Using @code{make} to Update Archive Files
7677 @cindex archive
7679 @dfn{Archive files} are files containing named subfiles called
7680 @dfn{members}; they are maintained with the program @code{ar} and their
7681 main use is as subroutine libraries for linking.
7683 @menu
7684 * Archive Members::             Archive members as targets.
7685 * Archive Update::              The implicit rule for archive member targets.
7686 * Archive Pitfalls::            Dangers to watch out for when using archives.
7687 * Archive Suffix Rules::        You can write a special kind of suffix rule
7688                                   for updating archives.
7689 @end menu
7691 @node Archive Members, Archive Update,  , Archives
7692 @section Archive Members as Targets
7693 @cindex archive member targets
7695 An individual member of an archive file can be used as a target or
7696 dependency in @code{make}.  You specify the member named @var{member} in
7697 archive file @var{archive} as follows:
7699 @example
7700 @var{archive}(@var{member})
7701 @end example
7703 @noindent
7704 This construct is available only in targets and dependencies, not in
7705 commands!  Most programs that you might use in commands do not support this
7706 syntax and cannot act directly on archive members.  Only @code{ar} and
7707 other programs specifically designed to operate on archives can do so.
7708 Therefore, valid commands to update an archive member target probably must
7709 use @code{ar}.  For example, this rule says to create a member
7710 @file{hack.o} in archive @file{foolib} by copying the file @file{hack.o}:
7712 @example
7713 foolib(hack.o) : hack.o
7714         ar cr foolib hack.o
7715 @end example
7717 In fact, nearly all archive member targets are updated in just this way
7718 and there is an implicit rule to do it for you.  @strong{Note:} The
7719 @samp{c} flag to @code{ar} is required if the archive file does not
7720 already exist.
7722 To specify several members in the same archive, you can write all the
7723 member names together between the parentheses.  For example:
7725 @example
7726 foolib(hack.o kludge.o)
7727 @end example
7729 @noindent
7730 is equivalent to:
7732 @example
7733 foolib(hack.o) foolib(kludge.o)
7734 @end example
7736 @cindex wildcard, in archive member
7737 You can also use shell-style wildcards in an archive member reference.
7738 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
7739 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
7740 @file{foolib} archive whose names end in @samp{.o}; perhaps
7741 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
7743 @node Archive Update
7744 @section Implicit Rule for Archive Member Targets
7746 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
7747 member named @var{m} in the archive file @var{a}.
7749 When @code{make} looks for an implicit rule for such a target, as a special
7750 feature it considers implicit rules that match @file{(@var{m})}, as well as
7751 those that match the actual target @file{@var{a}(@var{m})}.
7753 This causes one special rule whose target is @file{(%)} to match.  This
7754 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
7755 into the archive.  For example, it will update the archive member target
7756 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
7757 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
7759 When this rule is chained with others, the result is very powerful.
7760 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
7761 @samp{(} and @samp{)} from being interpreted specially by the shell) in
7762 the presence of a file @file{bar.c} is enough to cause the following
7763 commands to be run, even without a makefile:
7765 @example
7766 cc -c bar.c -o bar.o
7767 ar r foo.a bar.o
7768 rm -f bar.o
7769 @end example
7771 @noindent
7772 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
7773 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
7775 Implicit rules such as this one are written using the automatic variable
7776 @samp{$%}.  @xref{Automatic, ,Automatic Variables}.
7778 An archive member name in an archive cannot contain a directory name, but
7779 it may be useful in a makefile to pretend that it does.  If you write an
7780 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
7781 automatic updating with this command:
7783 @example
7784 ar r foo.a dir/file.o
7785 @end example
7787 @noindent
7788 which has the effect of copying the file @file{dir/file.o} into a member
7789 named @file{file.o}.  In connection with such usage, the automatic variables
7790 @code{%D} and @code{%F} may be useful.
7792 @menu
7793 * Archive Symbols::             How to update archive symbol directories.
7794 @end menu
7796 @node Archive Symbols,  ,  , Archive Update
7797 @subsection Updating Archive Symbol Directories
7798 @cindex @code{__.SYMDEF}
7799 @cindex updating archive symbol directories
7800 @cindex archive symbol directory updating
7801 @cindex symbol directories, updating archive 
7802 @cindex directories, updating archive symbol
7804 An archive file that is used as a library usually contains a special member
7805 named @file{__.SYMDEF} that contains a directory of the external symbol
7806 names defined by all the other members.  After you update any other
7807 members, you need to update @file{__.SYMDEF} so that it will summarize the
7808 other members properly.  This is done by running the @code{ranlib} program:
7810 @example
7811 ranlib @var{archivefile}
7812 @end example
7814 Normally you would put this command in the rule for the archive file,
7815 and make all the members of the archive file dependencies of that rule.
7816 For example,
7818 @example
7819 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
7820         ranlib libfoo.a
7821 @end example
7823 @noindent
7824 The effect of this is to update archive members @file{x.o}, @file{y.o},
7825 etc., and then update the symbol directory member @file{__.SYMDEF} by
7826 running @code{ranlib}.  The rules for updating the members are not shown
7827 here; most likely you can omit them and use the implicit rule which copies
7828 files into the archive, as described in the preceding section.
7830 This is not necessary when using the GNU @code{ar} program, which
7831 updates the @file{__.SYMDEF} member automatically.
7833 @node Archive Pitfalls
7834 @section Dangers When Using Archives
7835 @cindex archive, and parallel execution
7836 @cindex parallel execution, and archive update
7837 @cindex archive, and @code{-j}
7838 @cindex @code{-j}, and archive update
7840 It is important to be careful when using parallel execution (the
7841 @code{-j} switch; @pxref{Parallel, ,Parallel Execution}) and archives.
7842 If multiple @code{ar} commands run at the same time on the same archive
7843 file, they will not know about each other and can corrupt the file.
7845 Possibly a future version of @code{make} will provide a mechanism to
7846 circumvent this problem by serializing all commands that operate on the
7847 same archive file.  But for the time being, you must either write your
7848 makefiles to avoid this problem in some other way, or not use @code{-j}.
7850 @node Archive Suffix Rules, , Archive Pitfalls, Archives
7851 @section Suffix Rules for Archive Files
7852 @cindex suffix rule, for archive
7853 @cindex archive, suffix rule for
7854 @cindex library archive, suffix rule for
7855 @cindex @code{.a} (archives)
7857 You can write a special kind of suffix rule for dealing with archive
7858 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
7859 Archive suffix rules are obsolete in GNU @code{make}, because pattern
7860 rules for archives are a more general mechanism (@pxref{Archive
7861 Update}).  But they are retained for compatibility with other
7862 @code{make}s.
7864 To write a suffix rule for archives, you simply write a suffix rule
7865 using the target suffix @samp{.a} (the usual suffix for archive files).
7866 For example, here is the old-fashioned suffix rule to update a library
7867 archive from C source files:
7869 @example
7870 @group
7871 .c.a:
7872         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
7873         $(AR) r $@@ $*.o
7874         $(RM) $*.o
7875 @end group
7876 @end example
7878 @noindent
7879 This works just as if you had written the pattern rule:
7881 @example
7882 @group
7883 (%.o): %.c
7884         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
7885         $(AR) r $@@ $*.o
7886         $(RM) $*.o
7887 @end group
7888 @end example
7890 In fact, this is just what @code{make} does when it sees a suffix rule
7891 with @samp{.a} as the target suffix.  Any double-suffix rule
7892 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
7893 pattern @samp{(%.o)} and a dependency pattern of @samp{%.@var{x}}.
7895 Since you might want to use @samp{.a} as the suffix for some other kind
7896 of file, @code{make} also converts archive suffix rules to pattern rules
7897 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
7898 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
7899 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
7901 @node Features, Missing, Archives, Top
7902 @chapter Features of GNU @code{make}
7903 @cindex features of GNU @code{make}
7904 @cindex portability
7905 @cindex compatibility
7907 Here is a summary of the features of GNU @code{make}, for comparison
7908 with and credit to other versions of @code{make}.  We consider the
7909 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
7910 concerned with writing portable makefiles, you should use only the
7911 features of @code{make} @emph{not} listed here or in @ref{Missing}.
7913 Many features come from the version of @code{make} in System V.
7915 @itemize @bullet
7916 @item
7917 The @code{VPATH} variable and its special meaning. 
7918 @xref{Directory Search, , Searching Directories for Dependencies}.  
7919 This feature exists in System V @code{make}, but is undocumented.
7920 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
7921 @code{VPATH} feature).@refill
7923 @item
7924 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
7925 Allowing multiple files to be included with a single directive is a GNU
7926 extension.
7928 @item
7929 Variables are read from and communicated via the environment.
7930 @xref{Environment, ,Variables from the Environment}.
7932 @item
7933 Options passed through the variable @code{MAKEFLAGS} to recursive
7934 invocations of @code{make}.
7935 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
7937 @item
7938 The automatic variable @code{$%} is set to the member name
7939 in an archive reference.  @xref{Automatic, ,Automatic Variables}.
7941 @item
7942 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
7943 and @code{$?} have corresponding forms like @code{$(@@F)} and
7944 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
7945 extension.  @xref{Automatic, ,Automatic Variables}.@refill
7947 @item
7948 Substitution variable references.
7949 @xref{Reference, ,Basics of Variable References}.
7951 @item
7952 The command-line options @samp{-b} and @samp{-m}, accepted and
7953 ignored.  In System V @code{make}, these options actually do something.
7955 @item
7956 Execution of recursive commands to run @code{make} via the variable
7957 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
7958 @xref{Recursion, ,Recursive Use of @code{make}}.
7960 @item
7961 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
7962 Rules}.  This feature is obsolete in GNU @code{make}, because the
7963 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
7964 Implicit Rules}) allows one pattern rule for installing members in an
7965 archive (@pxref{Archive Update}) to be sufficient.
7967 @item
7968 The arrangement of lines and backslash-newline combinations in
7969 commands is retained when the commands are printed, so they appear as
7970 they do in the makefile, except for the stripping of initial
7971 whitespace.
7972 @end itemize
7974 The following features were inspired by various other versions of
7975 @code{make}.  In some cases it is unclear exactly which versions inspired
7976 which others.
7978 @itemize @bullet
7979 @item
7980 Pattern rules using @samp{%}.
7981 This has been implemented in several versions of @code{make}.
7982 We're not sure who invented it first, but it's been spread around a bit.
7983 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.@refill
7985 @item
7986 Rule chaining and implicit intermediate files.
7987 This was implemented by Stu Feldman in his version of @code{make}
7988 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
7989 AT&T Bell Labs in his @code{mk} program (where he terms it
7990 ``transitive closure'').  We do not really know if
7991 we got this from either of them or thought it up ourselves at the
7992 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
7994 @item
7995 The automatic variable @code{$^} containing a list of all dependencies
7996 of the current target.  We did not invent this, but we have no idea who
7997 did.  @xref{Automatic, ,Automatic Variables}.  The automatic variable
7998 @code{$+} is a simple extension of @code{$^}.
8000 @item
8001 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
8002 invented by Andrew Hume in @code{mk}.  
8003 @xref{Instead of Execution, ,Instead of Executing the Commands}.
8005 @item
8006 The concept of doing several things at once (parallelism) exists in
8007 many incarnations of @code{make} and similar programs, though not in the
8008 System V or BSD implementations.  @xref{Execution, ,Command Execution}.
8010 @item
8011 Modified variable references using pattern substitution come from
8012 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
8013 This functionality was provided in GNU @code{make} by the
8014 @code{patsubst} function before the alternate syntax was implemented
8015 for compatibility with SunOS 4.  It is not altogether clear who
8016 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
8017 4 was released.@refill
8019 @item
8020 The special significance of @samp{+} characters preceding command lines
8021 (@pxref{Instead of Execution, ,Instead of Executing the Commands}) is
8022 mandated by
8023 @cite{IEEE Standard 1003.2-1992} (POSIX.2).
8025 @item
8026 The @samp{+=} syntax to append to the value of a variable comes from SunOS
8027 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
8029 @item
8030 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
8031 multiple members in a single archive file comes from SunOS 4 @code{make}.
8032 @xref{Archive Members}.
8034 @item
8035 The @code{-include} directive to include makefiles with no error for a
8036 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
8037 @code{make} does not allow multiple makefiles to be specified in one
8038 @code{-include} directive.)
8039 @end itemize
8041 The remaining features are inventions new in GNU @code{make}:
8043 @itemize @bullet
8044 @item
8045 Use the @samp{-v} or @samp{--version} option to print version and
8046 copyright information.
8048 @item 
8049 Use the @samp{-h} or @samp{--help} option to summarize the options to
8050 @code{make}.
8052 @item
8053 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
8055 @item
8056 Pass command-line variable assignments automatically through the
8057 variable @code{MAKE} to recursive @code{make} invocations.
8058 @xref{Recursion, ,Recursive Use of @code{make}}.
8060 @item
8061 Use the @samp{-C} or @samp{--directory} command option to change
8062 directory.  @xref{Options Summary, ,Summary of Options}.
8064 @item
8065 Make verbatim variable definitions with @code{define}.  
8066 @xref{Defining, ,Defining Variables Verbatim}.
8068 @item
8069 Declare phony targets with the special target @code{.PHONY}.
8071 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
8072 different syntax in his @code{mk} program.  This seems to be a case of
8073 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
8075 @item
8076 Manipulate text by calling functions.  
8077 @xref{Functions, ,Functions for Transforming Text}.
8079 @item
8080 Use the @samp{-o} or @samp{--old-file}
8081 option to pretend a file's modification-time is old.
8082 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
8084 @item
8085 Conditional execution.
8087 This feature has been implemented numerous times in various versions
8088 of @code{make}; it seems a natural extension derived from the features
8089 of the C preprocessor and similar macro languages and is not a
8090 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
8092 @item
8093 Specify a search path for included makefiles.
8094 @xref{Include, ,Including Other Makefiles}.
8096 @item
8097 Specify extra makefiles to read with an environment variable.
8098 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
8100 @item
8101 Strip leading sequences of @samp{./} from file names, so that
8102 @file{./@var{file}} and @file{@var{file}} are considered to be the
8103 same file.@refill
8105 @item
8106 Use a special search method for library dependencies written in the
8107 form @samp{-l@var{name}}.  
8108 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
8110 @item
8111 Allow suffixes for suffix rules 
8112 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
8113 characters.  In other versions of @code{make}, they must begin with
8114 @samp{.} and not contain any @samp{/} characters.
8116 @item
8117 Keep track of the current level of @code{make} recursion using the
8118 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
8120 @item
8121 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
8123 @item
8124 Provide selective @code{vpath} search.  
8125 @xref{Directory Search, ,Searching Directories for Dependencies}.
8127 @item
8128 Provide computed variable references.  
8129 @xref{Reference, ,Basics of Variable References}.
8131 @item
8132 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
8133 System V @code{make} has a very, very limited form of this
8134 functionality in that it will check out SCCS files for makefiles.
8136 @item
8137 Various new built-in implicit rules.  
8138 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
8140 @item
8141 The built-in variable @samp{MAKE_VERSION} gives the version number of
8142 @code{make}.
8143 @end itemize
8145 @node Missing, Makefile Conventions, Features, Top
8146 @chapter Incompatibilities and Missing Features
8147 @cindex incompatibilities 
8148 @cindex missing features
8149 @cindex features, missing
8151 The @code{make} programs in various other systems support a few features
8152 that are not implemented in GNU @code{make}.  The POSIX.2 standard
8153 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
8154 require any of these features.@refill
8156 @itemize @bullet
8157 @item
8158 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
8159 of archive file @var{file}.  The member is chosen, not by name, but by
8160 being an object file which defines the linker symbol @var{entry}.@refill
8162 This feature was not put into GNU @code{make} because of the
8163 nonmodularity of putting knowledge into @code{make} of the internal
8164 format of archive file symbol tables.  
8165 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
8167 @item
8168 Suffixes (used in suffix rules) that end with the character @samp{~}
8169 have a special meaning to System V @code{make}; 
8170 they refer to the SCCS file that corresponds
8171 to the file one would get without the @samp{~}.  For example, the
8172 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
8173 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
8174 series of such suffix rules is required.  
8175 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
8177 In GNU @code{make}, this entire series of cases is handled by two
8178 pattern rules for extraction from SCCS, in combination with the
8179 general feature of rule chaining.  
8180 @xref{Chained Rules, ,Chains of Implicit Rules}.
8182 @item
8183 In System V @code{make}, the string @samp{$$@@} has the strange meaning
8184 that, in the dependencies of a rule with multiple targets, it stands
8185 for the particular target that is being processed.
8187 This is not defined in GNU @code{make} because @samp{$$} should always
8188 stand for an ordinary @samp{$}.
8190 It is possible to get this functionality through the use of static pattern
8191 rules (@pxref{Static Pattern, ,Static Pattern Rules}).  
8192 The System V @code{make} rule:
8194 @example
8195 $(targets): $$@@.o lib.a
8196 @end example
8198 @noindent
8199 can be replaced with the GNU @code{make} static pattern rule:
8201 @example
8202 $(targets): %: %.o lib.a
8203 @end example
8205 @item
8206 In System V and 4.3 BSD @code{make}, files found by @code{VPATH} search
8207 (@pxref{Directory Search, ,Searching Directories for Dependencies}) have their names changed inside command
8208 strings.  We feel it is much cleaner to always use automatic variables
8209 and thus make this feature obsolete.@refill
8211 @item
8212 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
8213 the dependencies of a rule has the amazingly strange ``feature'' of
8214 expanding to the full name of the @emph{target of that rule}.  We cannot
8215 imagine what went on in the minds of Unix @code{make} developers to do
8216 this; it is utterly inconsistent with the normal definition of @code{$*}.
8217 @vindex * @r{(automatic variable), unsupported bizarre usage}
8219 @item
8220 In some Unix @code{make}s, implicit rule search
8221 (@pxref{Implicit Rules, ,Using Implicit Rules}) is apparently done for
8222 @emph{all} targets, not just those without commands.  This means you can
8223 do:@refill
8225 @example
8226 @group
8227 foo.o:
8228         cc -c foo.c
8229 @end group
8230 @end example
8232 @noindent
8233 and Unix @code{make} will intuit that @file{foo.o} depends on
8234 @file{foo.c}.@refill
8236 We feel that such usage is broken.  The dependency properties of
8237 @code{make} are well-defined (for GNU @code{make}, at least),
8238 and doing such a thing simply does not fit the model.@refill
8240 @item
8241 GNU @code{make} does not include any built-in implicit rules for
8242 compiling or preprocessing EFL programs.  If we hear of anyone who is
8243 using EFL, we will gladly add them.
8245 @item
8246 It appears that in SVR4 @code{make}, a suffix rule can be specified with
8247 no commands, and it is treated as if it had empty commands
8248 (@pxref{Empty Commands}).  For example:
8250 @example
8251 .c.a:
8252 @end example
8254 @noindent
8255 will override the built-in @file{.c.a} suffix rule.
8257 We feel that it is cleaner for a rule without commands to always simply
8258 add to the dependency list for the target.  The above example can be
8259 easily rewritten to get the desired behavior in GNU @code{make}:
8261 @example
8262 .c.a: ;
8263 @end example
8265 @item
8266 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
8267 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
8268 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
8269 program it runs returns a nonzero status.  We feel it is cleaner to
8270 write each shell command line to stand on its own and not require this
8271 special treatment.
8272 @end itemize
8274 @comment The makefile standards are in a separate file that is also
8275 @comment included by standards.texi.
8276 @include make-stds.texi
8278 @node Quick Reference, Complex Makefile, Makefile Conventions, Top
8279 @appendix Quick Reference
8281 This appendix summarizes the directives, text manipulation functions,
8282 and special variables which GNU @code{make} understands.
8283 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
8284 and @ref{Options Summary, ,Summary of Options},
8285 for other summaries.
8287 Here is a summary of the directives GNU @code{make} recognizes:
8289 @table @code
8290 @item define @var{variable}
8291 @itemx endef
8293 Define a multi-line, recursively-expanded variable.@*
8294 @xref{Sequences}.
8296 @item ifdef @var{variable}
8297 @itemx ifndef @var{variable}
8298 @itemx ifeq (@var{a},@var{b})
8299 @itemx ifeq "@var{a}" "@var{b}"
8300 @itemx ifeq '@var{a}' '@var{b}'
8301 @itemx ifneq (@var{a},@var{b})
8302 @itemx ifneq "@var{a}" "@var{b}"
8303 @itemx ifneq '@var{a}' '@var{b}'
8304 @itemx else
8305 @itemx endif
8307 Conditionally evaluate part of the makefile.@*
8308 @xref{Conditionals}.
8310 @item include @var{file}
8312 Include another makefile.@*
8313 @xref{Include, ,Including Other Makefiles}.
8315 @item override @var{variable} = @var{value}
8316 @itemx override @var{variable} := @var{value}
8317 @itemx override @var{variable} += @var{value}
8318 @itemx override define @var{variable}
8319 @itemx endef
8321 Define a variable, overriding any previous definition, even one from
8322 the command line.@*
8323 @xref{Override Directive, ,The @code{override} Directive}.
8325 @item export
8327 Tell @code{make} to export all variables to child processes by default.@*
8328 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
8330 @item export @var{variable}
8331 @itemx export @var{variable} = @var{value}
8332 @itemx export @var{variable} := @var{value}
8333 @itemx export @var{variable} += @var{value}
8334 @itemx unexport @var{variable}
8335 Tell @code{make} whether or not to export a particular variable to child
8336 processes.@*
8337 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
8339 @item vpath @var{pattern} @var{path}
8340 Specify a search path for files matching a @samp{%} pattern.@*
8341 @xref{Selective Search, , The @code{vpath} Directive}.
8343 @item vpath @var{pattern}
8344 Remove all search paths previously specified for @var{pattern}.
8346 @item vpath
8347 Remove all search paths previously specified in any @code{vpath}
8348 directive.
8349 @end table
8351 Here is a summary of the text manipulation functions (@pxref{Functions}):
8353 @table @code
8354 @item $(subst @var{from},@var{to},@var{text})
8355 Replace @var{from} with @var{to} in @var{text}.@*
8356 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8358 @item $(patsubst @var{pattern},@var{replacement},@var{text})
8359 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
8360 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8362 @item $(strip @var{string})
8363 Remove excess whitespace characters from @var{string}.@*
8364 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8366 @item $(findstring @var{find},@var{text})
8367 Locate @var{find} in @var{text}.@*
8368 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8370 @item $(filter @var{pattern}@dots{},@var{text})
8371 Select words in @var{text} that match one of the @var{pattern} words.@*
8372 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8374 @item $(filter-out @var{pattern}@dots{},@var{text})
8375 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
8376 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8378 @item $(sort @var{list})
8379 Sort the words in @var{list} lexicographically, removing duplicates.@*
8380 @xref{Text Functions, , Functions for String Substitution and Analysis}.
8382 @item $(dir @var{names}@dots{})
8383 Extract the directory part of each file name.@*
8384 @xref{Filename Functions, ,Functions for File Names}.
8386 @item $(notdir @var{names}@dots{})
8387 Extract the non-directory part of each file name.@*
8388 @xref{Filename Functions, ,Functions for File Names}.
8390 @item $(suffix @var{names}@dots{})
8391 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
8392 @xref{Filename Functions, ,Functions for File Names}.
8394 @item $(basename @var{names}@dots{})
8395 Extract the base name (name without suffix) of each file name.@*
8396 @xref{Filename Functions, ,Functions for File Names}.
8398 @item $(addsuffix @var{suffix},@var{names}@dots{})
8399 Append @var{suffix} to each word in @var{names}.@*
8400 @xref{Filename Functions, ,Functions for File Names}.
8402 @item $(addprefix @var{prefix},@var{names}@dots{})
8403 Prepend @var{prefix} to each word in @var{names}.@*
8404 @xref{Filename Functions, ,Functions for File Names}.
8406 @item $(join @var{list1},@var{list2})
8407 Join two parallel lists of words.@*
8408 @xref{Filename Functions, ,Functions for File Names}.
8410 @item $(word @var{n},@var{text})
8411 Extract the @var{n}th word (one-origin) of @var{text}.@*
8412 @xref{Filename Functions, ,Functions for File Names}.
8414 @item $(words @var{text})
8415 Count the number of words in @var{text}.@*
8416 @xref{Filename Functions, ,Functions for File Names}.
8418 @item $(firstword @var{names}@dots{})
8419 Extract the first word of @var{names}.@*
8420 @xref{Filename Functions, ,Functions for File Names}.
8422 @item $(wildcard @var{pattern}@dots{})
8423 Find file names matching a shell file name pattern (@emph{not} a
8424 @samp{%} pattern).@*
8425 @xref{Wildcard Function, ,The Function @code{wildcard}}.
8427 @item $(shell @var{command})
8429 Execute a shell command and return its output.@*
8430 @xref{Shell Function, , The @code{shell} Function}.
8432 @item $(origin @var{variable})
8434 Return a string describing how the @code{make} variable @var{variable} was
8435 defined.@*
8436 @xref{Origin Function, , The @code{origin} Function}.
8438 @item $(foreach @var{var},@var{words},@var{text})
8440 Evaluate @var{text} with @var{var} bound to each word in @var{words},
8441 and concatenate the results.@*
8442 @xref{Foreach Function, ,The @code{foreach} Function}.
8443 @end table
8445 Here is a summary of the automatic variables.
8446 @xref{Automatic, ,Automatic Variables},
8447 for full information.
8449 @table @code
8450 @item $@@
8451 The file name of the target.
8453 @item $%
8454 The target member name, when the target is an archive member.
8456 @item $<
8457 The name of the first dependency.
8459 @item $?
8460 The names of all the dependencies that are
8461 newer than the target, with spaces between them.
8462 For dependencies which are archive members, only
8463 the member named is used (@pxref{Archives}).
8465 @item $^
8466 @itemx $+
8467 The names of all the dependencies, with spaces between them.  For
8468 dependencies which are archive members, only the member named is used
8469 (@pxref{Archives}).  The value of @code{$^} omits duplicate
8470 dependencies, while @code{$+} retains them and preserves their order.
8472 @item $*
8473 The stem with which an implicit rule matches 
8474 (@pxref{Pattern Match, ,How Patterns Match}).
8476 @item $(@@D)
8477 @itemx $(@@F)
8478 The directory part and the file-within-directory part of @code{$@@}.
8480 @item $(*D)
8481 @itemx $(*F)
8482 The directory part and the file-within-directory part of @code{$*}.
8484 @item $(%D)
8485 @itemx $(%F)
8486 The directory part and the file-within-directory part of @code{$%}.
8488 @item $(<D)
8489 @itemx $(<F)
8490 The directory part and the file-within-directory part of @code{$<}.
8492 @item $(^D)
8493 @itemx $(^F)
8494 The directory part and the file-within-directory part of @code{$^}.
8496 @item $(+D)
8497 @itemx $(+F)
8498 The directory part and the file-within-directory part of @code{$+}.
8500 @item $(?D)
8501 @itemx $(?F)
8502 The directory part and the file-within-directory part of @code{$?}.
8503 @end table
8505 These variables are used specially by GNU @code{make}:
8507 @table @code
8508 @item MAKEFILES
8510 Makefiles to be read on every invocation of @code{make}.@*
8511 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
8513 @item VPATH
8515 Directory search path for files not found in the current directory.@*
8516 @xref{General Search, , @code{VPATH} Search Path for All Dependencies}.  
8518 @item SHELL
8520 The name of the system default command interpreter, usually @file{/bin/sh}.
8521 You can set @code{SHELL} in the makefile to change the shell used to run
8522 commands.  @xref{Execution, ,Command Execution}.
8524 @item MAKE
8526 The name with which @code{make} was invoked.
8527 Using this variable in commands has special meaning.
8528 @xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.
8530 @item MAKELEVEL
8532 The number of levels of recursion (sub-@code{make}s).@*
8533 @xref{Variables/Recursion}.
8535 @item MAKEFLAGS
8537 The flags given to @code{make}.  You can set this in the environment or
8538 a makefile to set flags.@*
8539 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
8541 @item SUFFIXES
8543 The default list of suffixes before @code{make} reads any makefiles.
8544 @end table
8546 @node Complex Makefile, Concept Index, Quick Reference, Top
8547 @appendix Complex Makefile Example
8549 Here is the makefile for the GNU @code{tar} program.  This is a
8550 moderately complex makefile.
8552 Because it is the first target, the default goal is @samp{all}.  An
8553 interesting feature of this makefile is that @file{testpad.h} is a
8554 source file automatically created by the @code{testpad} program,
8555 itself compiled from @file{testpad.c}.
8557 If you type @samp{make} or @samp{make all}, then @code{make} creates
8558 the @file{tar} executable, the @file{rmt} daemon that provides
8559 remote tape access, and the @file{tar.info} Info file.
8561 If you type @samp{make install}, then @code{make} not only creates
8562 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
8563 them.
8565 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
8566 files, and the @file{tar}, @file{rmt}, @file{testpad},
8567 @file{testpad.h}, and @file{core} files.
8569 If you type @samp{make distclean}, then @code{make} not only removes
8570 the same files as does @samp{make clean} but also the
8571 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
8572 (Although it is not evident, this makefile (and
8573 @file{config.status}) is generated by the user with the
8574 @code{configure} program, which is provided in the @code{tar}
8575 distribution, but is not shown here.)
8577 If you type @samp{make realclean}, then @code{make} removes the same
8578 files as does @samp{make distclean} and also removes the Info files
8579 generated from @file{tar.texinfo}.
8581 In addition, there are targets @code{shar} and @code{dist} that create
8582 distribution kits.
8584 @example
8585 @group
8586 # Generated automatically from Makefile.in by configure.
8587 # Un*x Makefile for GNU tar program.
8588 # Copyright (C) 1991 Free Software Foundation, Inc.
8589 @end group
8591 @group
8592 # This program is free software; you can redistribute
8593 # it and/or modify it under the terms of the GNU
8594 # General Public License @dots{}
8595 @dots{}
8596 @dots{}
8597 @end group
8599 SHELL = /bin/sh
8601 #### Start of system configuration section. ####
8603 srcdir = .
8605 @group
8606 # If you use gcc, you should either run the
8607 # fixincludes script that comes with it or else use
8608 # gcc with the -traditional option.  Otherwise ioctl
8609 # calls will be compiled incorrectly on some systems.
8610 CC = gcc -O
8611 YACC = bison -y
8612 INSTALL = /usr/local/bin/install -c
8613 INSTALLDATA = /usr/local/bin/install -c -m 644
8614 @end group
8616 # Things you might add to DEFS:
8617 # -DSTDC_HEADERS        If you have ANSI C headers and
8618 #                       libraries.
8619 # -DPOSIX               If you have POSIX.1 headers and 
8620 #                       libraries.
8621 # -DBSD42               If you have sys/dir.h (unless 
8622 #                       you use -DPOSIX), sys/file.h, 
8623 #                       and st_blocks in `struct stat'.
8624 # -DUSG                 If you have System V/ANSI C 
8625 #                       string and memory functions 
8626 #                       and headers, sys/sysmacros.h, 
8627 #                       fcntl.h, getcwd, no valloc, 
8628 #                       and ndir.h (unless 
8629 #                       you use -DDIRENT).
8630 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not 
8631 #                       include memory.h.
8632 # -DDIRENT              If USG and you have dirent.h 
8633 #                       instead of ndir.h.
8634 # -DSIGTYPE=int         If your signal handlers 
8635 #                       return int, not void.
8636 # -DNO_MTIO             If you lack sys/mtio.h 
8637 #                       (magtape ioctls).
8638 # -DNO_REMOTE           If you do not have a remote shell 
8639 #                       or rexec.
8640 # -DUSE_REXEC           To use rexec for remote tape
8641 #                       operations instead of 
8642 #                       forking rsh or remsh.
8643 # -DVPRINTF_MISSING     If you lack vprintf function 
8644 #                       (but have _doprnt).
8645 # -DDOPRNT_MISSING      If you lack _doprnt function.  
8646 #                       Also need to define 
8647 #                       -DVPRINTF_MISSING.
8648 # -DFTIME_MISSING       If you lack ftime system call.
8649 # -DSTRSTR_MISSING      If you lack strstr function.
8650 # -DVALLOC_MISSING      If you lack valloc function.
8651 # -DMKDIR_MISSING       If you lack mkdir and 
8652 #                       rmdir system calls.
8653 # -DRENAME_MISSING      If you lack rename system call.
8654 # -DFTRUNCATE_MISSING   If you lack ftruncate 
8655 #                       system call.
8656 # -DV7                  On Version 7 Unix (not 
8657 #                       tested in a long time).
8658 # -DEMUL_OPEN3          If you lack a 3-argument version 
8659 #                       of open, and want to emulate it 
8660 #                       with system calls you do have.
8661 # -DNO_OPEN3            If you lack the 3-argument open
8662 #                       and want to disable the tar -k 
8663 #                       option instead of emulating open.
8664 # -DXENIX               If you have sys/inode.h 
8665 #                       and need it 94 to be included.
8667 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
8668         -DVPRINTF_MISSING -DBSD42
8669 # Set this to rtapelib.o unless you defined NO_REMOTE, 
8670 # in which case make it empty.
8671 RTAPELIB = rtapelib.o
8672 LIBS = 
8673 DEF_AR_FILE = /dev/rmt8
8674 DEFBLOCKING = 20
8676 @group
8677 CDEBUG = -g
8678 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
8679         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
8680         -DDEFBLOCKING=$(DEFBLOCKING)
8681 LDFLAGS = -g
8682 @end group
8684 @group
8685 prefix = /usr/local
8686 # Prefix for each installed program, 
8687 # normally empty or `g'.
8688 binprefix = 
8690 # The directory to install tar in.
8691 bindir = $(prefix)/bin
8693 # The directory to install the info files in.
8694 infodir = $(prefix)/info
8695 @end group
8697 #### End of system configuration section. ####
8699 SRC1 =  tar.c create.c extract.c buffer.c \
8700         getoldopt.c update.c gnu.c mangle.c
8701 SRC2 =  version.c list.c names.c diffarch.c \
8702         port.c wildmat.c getopt.c
8703 SRC3 =  getopt1.c regex.c getdate.y
8704 SRCS =  $(SRC1) $(SRC2) $(SRC3)
8705 OBJ1 =  tar.o create.o extract.o buffer.o \
8706         getoldopt.o update.o gnu.o mangle.o
8707 OBJ2 =  version.o list.o names.o diffarch.o \
8708         port.o wildmat.o getopt.o
8709 OBJ3 =  getopt1.o regex.o getdate.o $(RTAPELIB)
8710 OBJS =  $(OBJ1) $(OBJ2) $(OBJ3)
8711 @group
8712 AUX =   README COPYING ChangeLog Makefile.in  \
8713         makefile.pc configure configure.in \
8714         tar.texinfo tar.info* texinfo.tex \
8715         tar.h port.h open3.h getopt.h regex.h \
8716         rmt.h rmt.c rtapelib.c alloca.c \
8717         msd_dir.h msd_dir.c tcexparg.c \
8718         level-0 level-1 backup-specs testpad.c
8719 @end group
8721 all:    tar rmt tar.info
8723 @group
8724 tar:    $(OBJS)
8725         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
8726 @end group
8728 @group
8729 rmt:    rmt.c
8730         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
8731 @end group
8733 @group
8734 tar.info: tar.texinfo
8735         makeinfo tar.texinfo
8736 @end group
8738 @group
8739 install: all
8740         $(INSTALL) tar $(bindir)/$(binprefix)tar
8741         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
8742         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
8743 @end group
8745 @group
8746 $(OBJS): tar.h port.h testpad.h
8747 regex.o buffer.o tar.o: regex.h
8748 # getdate.y has 8 shift/reduce conflicts.
8749 @end group
8751 @group
8752 testpad.h: testpad
8753         ./testpad
8754 @end group
8756 @group
8757 testpad: testpad.o
8758         $(CC) -o $@@ testpad.o
8759 @end group
8761 @group
8762 TAGS:   $(SRCS)
8763         etags $(SRCS)
8764 @end group
8766 @group
8767 clean:
8768         rm -f *.o tar rmt testpad testpad.h core
8769 @end group
8771 @group
8772 distclean: clean
8773         rm -f TAGS Makefile config.status
8774 @end group
8776 @group
8777 realclean: distclean
8778         rm -f tar.info*
8779 @end group
8781 @group
8782 shar: $(SRCS) $(AUX)
8783         shar $(SRCS) $(AUX) | compress \
8784           > tar-`sed -e '/version_string/!d' \
8785                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
8786                      -e q 
8787                      version.c`.shar.Z
8788 @end group
8790 @group
8791 dist: $(SRCS) $(AUX)
8792         echo tar-`sed \
8793              -e '/version_string/!d' \
8794              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
8795              -e q 
8796              version.c` > .fname
8797         -rm -rf `cat .fname`
8798         mkdir `cat .fname`
8799         ln $(SRCS) $(AUX) `cat .fname`
8800         -rm -rf `cat .fname` .fname
8801         tar chZf `cat .fname`.tar.Z `cat .fname`
8802 @end group
8804 @group
8805 tar.zoo: $(SRCS) $(AUX)
8806         -rm -rf tmp.dir
8807         -mkdir tmp.dir
8808         -rm tar.zoo
8809         for X in $(SRCS) $(AUX) ; do \
8810             echo $$X ; \
8811             sed 's/$$/^M/' $$X \
8812             > tmp.dir/$$X ; done
8813         cd tmp.dir ; zoo aM ../tar.zoo *
8814         -rm -rf tmp.dir
8815 @end group
8816 @end example
8818 @node Concept Index, Name Index, Complex Makefile, Top
8819 @unnumbered Index of Concepts
8821 @printindex cp
8823 @node Name Index,  , Concept Index, Top
8824 @unnumbered Index of Functions, Variables, & Directives
8826 @printindex fn
8828 @summarycontents
8829 @contents
8830 @bye