* Update to GPLv3
[make.git] / doc / make.texi
blobc3706214c0c905a9d2f8864be5c9c30b923747c6
1 \input texinfo                @c -*- Texinfo -*-
2 @c %**start of header
3 @setfilename make.info
5 @include version.texi
6 @set EDITION 0.70
7 @set RCSID $Id: make.texi,v 1.49 2007/07/04 19:35:21 psmith Exp $
9 @settitle GNU @code{make}
10 @setchapternewpage odd
11 @c Combine the variable and function indices:
12 @syncodeindex vr fn
13 @c Combine the program and concept indices:
14 @syncodeindex pg cp
15 @c FSF publishers: format makebook.texi instead of using this file directly.
16 @c ISBN provided by Lisa M. Opus Goldstein <opus@gnu.org>, 5 May 2004
17 @set ISBN 1-882114-83-5
18 @c %**end of header
20 @copying
21 This file documents the GNU @code{make} utility, which determines
22 automatically which pieces of a large program need to be recompiled,
23 and issues the commands to recompile them.
25 This is Edition @value{EDITION}, last updated @value{UPDATED},
26 of @cite{The GNU Make Manual}, for GNU @code{make} version @value{VERSION}.
28 Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
29 1996, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007
30 Free Software Foundation, Inc.
32 @quotation
33 Permission is granted to copy, distribute and/or modify this document
34 under the terms of the GNU Free Documentation License, Version 1.2 or
35 any later version published by the Free Software Foundation; with no
36 Invariant Sections, with the Front-Cover Texts being ``A GNU Manual,''
37 and with the Back-Cover Texts as in (a) below.  A copy of the
38 license is included in the section entitled ``GNU Free Documentation
39 License.''
41 (a) The FSF's Back-Cover Text is: ``You are free to copy and modify
42 this GNU Manual. Buying copies from GNU Press supports the FSF in
43 developing GNU and promoting software freedom.''
44 @end quotation
45 @end copying
47 @c finalout
49 @c ISPELL CHECK: done, 10 June 1993 --roland
50 @c ISPELL CHECK: done, 2000-06-25 --Martin Buchholz
53 @dircategory Software development
54 @direntry
55 * Make: (make).            Remake files automatically.
56 @end direntry
58 @iftex
59 @shorttitlepage GNU Make
60 @end iftex
61 @titlepage
62 @title GNU Make
63 @subtitle A Program for Directing Recompilation
64 @subtitle GNU @code{make} Version @value{VERSION}
65 @subtitle @value{UPDATED-MONTH}
66 @author Richard M. Stallman, Roland McGrath, Paul D. Smith
67 @page
68 @vskip 0pt plus 1filll
69 @insertcopying
70 @sp 2
71 Published by the Free Software Foundation @*
72 51 Franklin St. -- Fifth Floor @*
73 Boston, MA 02110-1301 USA @*
74 ISBN @value{ISBN} @*
75 @sp 2
76 Cover art by Etienne Suvasa.
77 @end titlepage
79 @summarycontents
80 @contents
82 @ifnottex
83 @node Top, Overview, (dir), (dir)
84 @top GNU @code{make}
86 @insertcopying
87 @end ifnottex
89 @menu
90 * Overview::                    Overview of @code{make}.
91 * Introduction::                An introduction to @code{make}.
92 * Makefiles::                   Makefiles tell @code{make} what to do.
93 * Rules::                       Rules describe when a file must be remade.
94 * Commands::                    Commands say how to remake a file.
95 * Using Variables::             You can use variables to avoid repetition.
96 * Conditionals::                Use or ignore parts of the makefile based
97                                   on the values of variables.
98 * Functions::                   Many powerful ways to manipulate text.
99 * Invoking make: Running.       How to invoke @code{make} on the command line.
100 * Implicit Rules::              Use implicit rules to treat many files alike,
101                                   based on their file names.
102 * Archives::                    How @code{make} can update library archives.
103 * Features::                    Features GNU @code{make} has over other @code{make}s.
104 * Missing::                     What GNU @code{make} lacks from other @code{make}s.
105 * Makefile Conventions::        Conventions for writing makefiles for
106                                   GNU programs.
107 * Quick Reference::             A quick reference for experienced users.
108 * Error Messages::              A list of common errors generated by @code{make}.
109 * Complex Makefile::            A real example of a straightforward,
110                                   but nontrivial, makefile.
112 * GNU Free Documentation License::  License for copying this manual
113 * Concept Index::               Index of Concepts
114 * Name Index::                  Index of Functions, Variables, & Directives
116 @detailmenu
117  --- The Detailed Node Listing ---
119 Overview of @code{make}
121 * Preparing::                   Preparing and Running Make
122 * Reading::                     On Reading this Text
123 * Bugs::                        Problems and Bugs
125 An Introduction to Makefiles
127 * Rule Introduction::           What a rule looks like.
128 * Simple Makefile::             A Simple Makefile
129 * How Make Works::              How @code{make} Processes This Makefile
130 * Variables Simplify::          Variables Make Makefiles Simpler
131 * make Deduces::                Letting @code{make} Deduce the Commands
132 * Combine By Prerequisite::     Another Style of Makefile
133 * Cleanup::                     Rules for Cleaning the Directory
135 Writing Makefiles
137 * Makefile Contents::           What makefiles contain.
138 * Makefile Names::              How to name your makefile.
139 * Include::                     How one makefile can use another makefile.
140 * MAKEFILES Variable::          The environment can specify extra makefiles.
141 * MAKEFILE_LIST Variable::      Discover which makefiles have been read.
142 * Special Variables::           Other special variables.
143 * Remaking Makefiles::          How makefiles get remade.
144 * Overriding Makefiles::        How to override part of one makefile
145                                   with another makefile.
146 * Reading Makefiles::           How makefiles are parsed.
147 * Secondary Expansion::         How and when secondary expansion is performed.
149 Writing Rules
151 * Rule Example::                An example explained.
152 * Rule Syntax::                 General syntax explained.
153 * Prerequisite Types::          There are two types of prerequisites.
154 * Wildcards::                   Using wildcard characters such as `*'.
155 * Directory Search::            Searching other directories for source files.
156 * Phony Targets::               Using a target that is not a real file's name.
157 * Force Targets::               You can use a target without commands
158                                   or prerequisites to mark other targets
159                                   as phony.
160 * Empty Targets::               When only the date matters and the
161                                   files are empty.
162 * Special Targets::             Targets with special built-in meanings.
163 * Multiple Targets::            When to make use of several targets in a rule.
164 * Multiple Rules::              How to use several rules with the same target.
165 * Static Pattern::              Static pattern rules apply to multiple targets
166                                   and can vary the prerequisites according to
167                                   the target name.
168 * Double-Colon::                How to use a special kind of rule to allow
169                                   several independent rules for one target.
170 * Automatic Prerequisites::     How to automatically generate rules giving
171                                   prerequisites from source files themselves.
173 Using Wildcard Characters in File Names
175 * Wildcard Examples::           Several examples
176 * Wildcard Pitfall::            Problems to avoid.
177 * Wildcard Function::           How to cause wildcard expansion where
178                                   it does not normally take place.
180 Searching Directories for Prerequisites
182 * General Search::              Specifying a search path that applies
183                                   to every prerequisite.
184 * Selective Search::            Specifying a search path
185                                   for a specified class of names.
186 * Search Algorithm::            When and how search paths are applied.
187 * Commands/Search::             How to write shell commands that work together
188                                   with search paths.
189 * Implicit/Search::             How search paths affect implicit rules.
190 * Libraries/Search::            Directory search for link libraries.
192 Static Pattern Rules
194 * Static Usage::                The syntax of static pattern rules.
195 * Static versus Implicit::      When are they better than implicit rules?
197 Writing the Commands in Rules
199 * Command Syntax::              Command syntax features and pitfalls.
200 * Echoing::                     How to control when commands are echoed.
201 * Execution::                   How commands are executed.
202 * Parallel::                    How commands can be executed in parallel.
203 * Errors::                      What happens after a command execution error.
204 * Interrupts::                  What happens when a command is interrupted.
205 * Recursion::                   Invoking @code{make} from makefiles.
206 * Sequences::                   Defining canned sequences of commands.
207 * Empty Commands::              Defining useful, do-nothing commands.
209 Command Syntax
211 * Splitting Lines::             Breaking long command lines for readability.
212 * Variables in Commands::       Using @code{make} variables in commands.
214 Command Execution
216 * Choosing the Shell::          How @code{make} chooses the shell used
217                                   to run commands.
219 Recursive Use of @code{make}
221 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
222 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
223 * Options/Recursion::           How to communicate options to a sub-@code{make}.
224 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
225                                   helps debug use of recursive @code{make} commands.
227 How to Use Variables
229 * Reference::                   How to use the value of a variable.
230 * Flavors::                     Variables come in two flavors.
231 * Advanced::                    Advanced features for referencing a variable.
232 * Values::                      All the ways variables get their values.
233 * Setting::                     How to set a variable in the makefile.
234 * Appending::                   How to append more text to the old value
235                                   of a variable.
236 * Override Directive::          How to set a variable in the makefile even if
237                                   the user has set it with a command argument.
238 * Defining::                    An alternate way to set a variable
239                                   to a verbatim string.
240 * Environment::                 Variable values can come from the environment.
241 * Target-specific::             Variable values can be defined on a per-target
242                                   basis.
243 * Pattern-specific::            Target-specific variable values can be applied
244                                   to a group of targets that match a pattern.
246 Advanced Features for Reference to Variables
248 * Substitution Refs::           Referencing a variable with
249                                   substitutions on the value.
250 * Computed Names::              Computing the name of the variable to refer to.
252 Conditional Parts of Makefiles
254 * Conditional Example::         Example of a conditional
255 * Conditional Syntax::          The syntax of conditionals.
256 * Testing Flags::               Conditionals that test flags.
258 Functions for Transforming Text
260 * Syntax of Functions::         How to write a function call.
261 * Text Functions::              General-purpose text manipulation functions.
262 * File Name Functions::         Functions for manipulating file names.
263 * Conditional Functions::       Functions that implement conditions.
264 * Foreach Function::            Repeat some text with controlled variation.
265 * Call Function::               Expand a user-defined function.
266 * Value Function::              Return the un-expanded value of a variable.
267 * Eval Function::               Evaluate the arguments as makefile syntax.
268 * Origin Function::             Find where a variable got its value.
269 * Flavor Function::             Find out the flavor of a variable.
270 * Shell Function::              Substitute the output of a shell command.
271 * Make Control Functions::      Functions that control how make runs.
273 How to Run @code{make}
275 * Makefile Arguments::          How to specify which makefile to use.
276 * Goals::                       How to use goal arguments to specify which
277                                   parts of the makefile to use.
278 * Instead of Execution::        How to use mode flags to specify what
279                                   kind of thing to do with the commands
280                                   in the makefile other than simply
281                                   execute them.
282 * Avoiding Compilation::        How to avoid recompiling certain files.
283 * Overriding::                  How to override a variable to specify
284                                   an alternate compiler and other things.
285 * Testing::                     How to proceed past some errors, to
286                                   test compilation.
287 * Options Summary::             Summary of Options
289 Using Implicit Rules
291 * Using Implicit::              How to use an existing implicit rule
292                                   to get the commands for updating a file.
293 * Catalogue of Rules::          A list of built-in implicit rules.
294 * Implicit Variables::          How to change what predefined rules do.
295 * Chained Rules::               How to use a chain of implicit rules.
296 * Pattern Rules::               How to define new implicit rules.
297 * Last Resort::                 How to define commands for rules which
298                                   cannot find any.
299 * Suffix Rules::                The old-fashioned style of implicit rule.
300 * Implicit Rule Search::        The precise algorithm for applying
301                                   implicit rules.
303 Defining and Redefining Pattern Rules
305 * Pattern Intro::               An introduction to pattern rules.
306 * Pattern Examples::            Examples of pattern rules.
307 * Automatic Variables::         How to use automatic variables in the
308                                   commands of implicit rules.
309 * Pattern Match::               How patterns match.
310 * Match-Anything Rules::        Precautions you should take prior to
311                                   defining rules that can match any
312                                   target file whatever.
313 * Canceling Rules::             How to override or cancel built-in rules.
315 Using @code{make} to Update Archive Files
317 * Archive Members::             Archive members as targets.
318 * Archive Update::              The implicit rule for archive member targets.
319 * Archive Pitfalls::            Dangers to watch out for when using archives.
320 * Archive Suffix Rules::        You can write a special kind of suffix rule
321                                   for updating archives.
323 Implicit Rule for Archive Member Targets
325 * Archive Symbols::             How to update archive symbol directories.
327 @end detailmenu
328 @end menu
330 @node Overview, Introduction, Top, Top
331 @comment  node-name,  next,  previous,  up
332 @chapter Overview of @code{make}
334 The @code{make} utility automatically determines which pieces of a large
335 program need to be recompiled, and issues commands to recompile them.
336 This manual describes GNU @code{make}, which was implemented by Richard
337 Stallman and Roland McGrath.  Development since Version 3.76 has been
338 handled by Paul D. Smith.
340 GNU @code{make} conforms to section 6.2 of @cite{IEEE Standard
341 1003.2-1992} (POSIX.2).
342 @cindex POSIX
343 @cindex IEEE Standard 1003.2
344 @cindex standards conformance
346 Our examples show C programs, since they are most common, but you can use
347 @code{make} with any programming language whose compiler can be run with a
348 shell command.  Indeed, @code{make} is not limited to programs.  You can
349 use it to describe any task where some files must be updated automatically
350 from others whenever the others change.
352 @menu
353 * Preparing::                   Preparing and Running Make
354 * Reading::                     On Reading this Text
355 * Bugs::                        Problems and Bugs
356 @end menu
358 @node Preparing, Reading, Overview, Overview
359 @ifnottex
360 @heading Preparing and Running Make
361 @end ifnottex
363 To prepare to use @code{make}, you must write a file called
364 the @dfn{makefile} that describes the relationships among files
365 in your program and provides commands for updating each file.
366 In a program, typically, the executable file is updated from object
367 files, which are in turn made by compiling source files.@refill
369 Once a suitable makefile exists, each time you change some source files,
370 this simple shell command:
372 @example
373 make
374 @end example
376 @noindent
377 suffices to perform all necessary recompilations.  The @code{make} program
378 uses the makefile data base and the last-modification times of the files to
379 decide which of the files need to be updated.  For each of those files, it
380 issues the commands recorded in the data base.
382 You can provide command line arguments to @code{make} to control which
383 files should be recompiled, or how.  @xref{Running, ,How to Run
384 @code{make}}.
386 @node Reading, Bugs, Preparing, Overview
387 @section How to Read This Manual
389 If you are new to @code{make}, or are looking for a general
390 introduction, read the first few sections of each chapter, skipping the
391 later sections.  In each chapter, the first few sections contain
392 introductory or general information and the later sections contain
393 specialized or technical information.
394 @ifnottex
395 The exception is the second chapter, @ref{Introduction, ,An
396 Introduction to Makefiles}, all of which is introductory.
397 @end ifnottex
398 @iftex
399 The exception is @ref{Introduction, ,An Introduction to Makefiles},
400 all of which is introductory.
401 @end iftex
403 If you are familiar with other @code{make} programs, see @ref{Features,
404 ,Features of GNU @code{make}}, which lists the enhancements GNU
405 @code{make} has, and @ref{Missing, ,Incompatibilities and Missing
406 Features}, which explains the few things GNU @code{make} lacks that
407 others have.
409 For a quick summary, see @ref{Options Summary}, @ref{Quick Reference},
410 and @ref{Special Targets}.
412 @node Bugs,  , Reading, Overview
413 @section Problems and Bugs
414 @cindex reporting bugs
415 @cindex bugs, reporting
416 @cindex problems and bugs, reporting
418 If you have problems with GNU @code{make} or think you've found a bug,
419 please report it to the developers; we cannot promise to do anything but
420 we might well want to fix it.
422 Before reporting a bug, make sure you've actually found a real bug.
423 Carefully reread the documentation and see if it really says you can do
424 what you're trying to do.  If it's not clear whether you should be able
425 to do something or not, report that too; it's a bug in the
426 documentation!
428 Before reporting a bug or trying to fix it yourself, try to isolate it
429 to the smallest possible makefile that reproduces the problem.  Then
430 send us the makefile and the exact results @code{make} gave you,
431 including any error or warning messages.  Please don't paraphrase
432 these messages: it's best to cut and paste them into your report.
433 When generating this small makefile, be sure to not use any non-free
434 or unusual tools in your commands: you can almost always emulate what
435 such a tool would do with simple shell commands.  Finally, be sure to
436 explain what you expected to occur; this will help us decide whether
437 the problem was really in the documentation.
439 Once you have a precise problem you can report it in one of two ways.
440 Either send electronic mail to:
442 @example
443     bug-make@@gnu.org
444 @end example
446 @noindent
447 or use our Web-based project management tool, at:
449 @example
450     http://savannah.gnu.org/projects/make/
451 @end example
453 @noindent
454 In addition to the information above, please be careful to include the
455 version number of @code{make} you are using.  You can get this
456 information with the command @samp{make --version}.  Be sure also to
457 include the type of machine and operating system you are using.  One
458 way to obtain this information is by looking at the final lines of
459 output from the command @samp{make --help}.
461 @node Introduction, Makefiles, Overview, Top
462 @comment  node-name,  next,  previous,  up
463 @chapter An Introduction to Makefiles
465 You need a file called a @dfn{makefile} to tell @code{make} what to do.
466 Most often, the makefile tells @code{make} how to compile and link a
467 program.
468 @cindex makefile
470 In this chapter, we will discuss a simple makefile that describes how to
471 compile and link a text editor which consists of eight C source files
472 and three header files.  The makefile can also tell @code{make} how to
473 run miscellaneous commands when explicitly asked (for example, to remove
474 certain files as a clean-up operation).  To see a more complex example
475 of a makefile, see @ref{Complex Makefile}.
477 When @code{make} recompiles the editor, each changed C source file
478 must be recompiled.  If a header file has changed, each C source file
479 that includes the header file must be recompiled to be safe.  Each
480 compilation produces an object file corresponding to the source file.
481 Finally, if any source file has been recompiled, all the object files,
482 whether newly made or saved from previous compilations, must be linked
483 together to produce the new executable editor.
484 @cindex recompilation
485 @cindex editor
487 @menu
488 * Rule Introduction::           What a rule looks like.
489 * Simple Makefile::             A Simple Makefile
490 * How Make Works::              How @code{make} Processes This Makefile
491 * Variables Simplify::          Variables Make Makefiles Simpler
492 * make Deduces::                Letting @code{make} Deduce the Commands
493 * Combine By Prerequisite::     Another Style of Makefile
494 * Cleanup::                     Rules for Cleaning the Directory
495 @end menu
497 @node Rule Introduction, Simple Makefile, Introduction, Introduction
498 @comment  node-name,  next,  previous,  up
499 @section What a Rule Looks Like
500 @cindex rule, introduction to
501 @cindex makefile rule parts
502 @cindex parts of makefile rule
504 A simple makefile consists of ``rules'' with the following shape:
506 @cindex targets, introduction to
507 @cindex prerequisites, introduction to
508 @cindex commands, introduction to
509 @example
510 @group
511 @var{target} @dots{} : @var{prerequisites} @dots{}
512         @var{command}
513         @dots{}
514         @dots{}
515 @end group
516 @end example
518 A @dfn{target} is usually the name of a file that is generated by a
519 program; examples of targets are executable or object files.  A target
520 can also be the name of an action to carry out, such as @samp{clean}
521 (@pxref{Phony Targets}).
523 A @dfn{prerequisite} is a file that is used as input to create the
524 target.  A target often depends on several files.
526 @cindex tabs in rules
527 A @dfn{command} is an action that @code{make} carries out.
528 A rule may have more than one command, each on its own line.
529 @strong{Please note:} you need to put a tab character at the beginning of
530 every command line!  This is an obscurity that catches the unwary.
532 Usually a command is in a rule with prerequisites and serves to create a
533 target file if any of the prerequisites change.  However, the rule that
534 specifies commands for the target need not have prerequisites.  For
535 example, the rule containing the delete command associated with the
536 target @samp{clean} does not have prerequisites.
538 A @dfn{rule}, then, explains how and when to remake certain files
539 which are the targets of the particular rule.  @code{make} carries out
540 the commands on the prerequisites to create or update the target.  A
541 rule can also explain how and when to carry out an action.
542 @xref{Rules, , Writing Rules}.
544 A makefile may contain other text besides rules, but a simple makefile
545 need only contain rules.  Rules may look somewhat more complicated
546 than shown in this template, but all fit the pattern more or less.
548 @node Simple Makefile, How Make Works, Rule Introduction, Introduction
549 @section A Simple Makefile
550 @cindex simple makefile
551 @cindex makefile, simple
553 Here is a straightforward makefile that describes the way an
554 executable file called @code{edit} depends on eight object files
555 which, in turn, depend on eight C source and three header files.
557 In this example, all the C files include @file{defs.h}, but only those
558 defining editing commands include @file{command.h}, and only low
559 level files that change the editor buffer include @file{buffer.h}.
561 @example
562 @group
563 edit : main.o kbd.o command.o display.o \
564        insert.o search.o files.o utils.o
565         cc -o edit main.o kbd.o command.o display.o \
566                    insert.o search.o files.o utils.o
568 main.o : main.c defs.h
569         cc -c main.c
570 kbd.o : kbd.c defs.h command.h
571         cc -c kbd.c
572 command.o : command.c defs.h command.h
573         cc -c command.c
574 display.o : display.c defs.h buffer.h
575         cc -c display.c
576 insert.o : insert.c defs.h buffer.h
577         cc -c insert.c
578 search.o : search.c defs.h buffer.h
579         cc -c search.c
580 files.o : files.c defs.h buffer.h command.h
581         cc -c files.c
582 utils.o : utils.c defs.h
583         cc -c utils.c
584 clean :
585         rm edit main.o kbd.o command.o display.o \
586            insert.o search.o files.o utils.o
587 @end group
588 @end example
590 @noindent
591 We split each long line into two lines using backslash-newline; this is
592 like using one long line, but is easier to read.
593 @cindex continuation lines
594 @cindex @code{\} (backslash), for continuation lines
595 @cindex backslash (@code{\}), for continuation lines
596 @cindex quoting newline, in makefile
597 @cindex newline, quoting, in makefile
599 To use this makefile to create the executable file called @file{edit},
600 type:
602 @example
603 make
604 @end example
606 To use this makefile to delete the executable file and all the object
607 files from the directory, type:
609 @example
610 make clean
611 @end example
613 In the example makefile, the targets include the executable file
614 @samp{edit}, and the object files @samp{main.o} and @samp{kbd.o}.  The
615 prerequisites are files such as @samp{main.c} and @samp{defs.h}.
616 In fact, each @samp{.o} file is both a target and a prerequisite.
617 Commands include @w{@samp{cc -c main.c}} and @w{@samp{cc -c kbd.c}}.
619 When a target is a file, it needs to be recompiled or relinked if any
620 of its prerequisites change.  In addition, any prerequisites that are
621 themselves automatically generated should be updated first.  In this
622 example, @file{edit} depends on each of the eight object files; the
623 object file @file{main.o} depends on the source file @file{main.c} and
624 on the header file @file{defs.h}.
626 A shell command follows each line that contains a target and
627 prerequisites.  These shell commands say how to update the target file.
628 A tab character must come at the beginning of every command line to
629 distinguish command lines from other lines in the makefile.  (Bear in
630 mind that @code{make} does not know anything about how the commands
631 work.  It is up to you to supply commands that will update the target
632 file properly.  All @code{make} does is execute the commands in the rule
633 you have specified when the target file needs to be updated.)
634 @cindex shell command
636 The target @samp{clean} is not a file, but merely the name of an
637 action.  Since you
638 normally
639 do not want to carry out the actions in this rule, @samp{clean} is not a prerequisite of any other rule.
640 Consequently, @code{make} never does anything with it unless you tell
641 it specifically.  Note that this rule not only is not a prerequisite, it
642 also does not have any prerequisites, so the only purpose of the rule
643 is to run the specified commands.  Targets that do not refer to files
644 but are just actions are called @dfn{phony targets}.  @xref{Phony
645 Targets}, for information about this kind of target.  @xref{Errors, ,
646 Errors in Commands}, to see how to cause @code{make} to ignore errors
647 from @code{rm} or any other command.
648 @cindex @code{clean} target
649 @cindex @code{rm} (shell command)
651 @node How Make Works, Variables Simplify, Simple Makefile, Introduction
652 @comment  node-name,  next,  previous,  up
653 @section How @code{make} Processes a Makefile
654 @cindex processing a makefile
655 @cindex makefile, how @code{make} processes
657 By default, @code{make} starts with the first target (not targets whose
658 names start with @samp{.}).  This is called the @dfn{default goal}.
659 (@dfn{Goals} are the targets that @code{make} strives ultimately to
660 update.    You can override this behavior using the command line
661 (@pxref{Goals, , Arguments to Specify the Goals}) or with the
662 @code{.DEFAULT_GOAL} special variable (@pxref{Special Variables, ,
663 Other Special Variables}).
664 @cindex default goal
665 @cindex goal, default
666 @cindex goal
668 In the simple example of the previous section, the default goal is to
669 update the executable program @file{edit}; therefore, we put that rule
670 first.
672 Thus, when you give the command:
674 @example
675 make
676 @end example
678 @noindent
679 @code{make} reads the makefile in the current directory and begins by
680 processing the first rule.  In the example, this rule is for relinking
681 @file{edit}; but before @code{make} can fully process this rule, it
682 must process the rules for the files that @file{edit} depends on,
683 which in this case are the object files.  Each of these files is
684 processed according to its own rule.  These rules say to update each
685 @samp{.o} file by compiling its source file.  The recompilation must
686 be done if the source file, or any of the header files named as
687 prerequisites, is more recent than the object file, or if the object
688 file does not exist.
690 The other rules are processed because their targets appear as
691 prerequisites of the goal.  If some other rule is not depended on by the
692 goal (or anything it depends on, etc.), that rule is not processed,
693 unless you tell @code{make} to do so (with a command such as
694 @w{@code{make clean}}).
696 Before recompiling an object file, @code{make} considers updating its
697 prerequisites, the source file and header files.  This makefile does not
698 specify anything to be done for them---the @samp{.c} and @samp{.h} files
699 are not the targets of any rules---so @code{make} does nothing for these
700 files.  But @code{make} would update automatically generated C programs,
701 such as those made by Bison or Yacc, by their own rules at this time.
703 After recompiling whichever object files need it, @code{make} decides
704 whether to relink @file{edit}.  This must be done if the file
705 @file{edit} does not exist, or if any of the object files are newer than
706 it.  If an object file was just recompiled, it is now newer than
707 @file{edit}, so @file{edit} is relinked.
708 @cindex relinking
710 Thus, if we change the file @file{insert.c} and run @code{make},
711 @code{make} will compile that file to update @file{insert.o}, and then
712 link @file{edit}.  If we change the file @file{command.h} and run
713 @code{make}, @code{make} will recompile the object files @file{kbd.o},
714 @file{command.o} and @file{files.o} and then link the file @file{edit}.
716 @node Variables Simplify, make Deduces, How Make Works, Introduction
717 @section Variables Make Makefiles Simpler
718 @cindex variables
719 @cindex simplifying with variables
721 In our example, we had to list all the object files twice in the rule for
722 @file{edit} (repeated here):
724 @example
725 @group
726 edit : main.o kbd.o command.o display.o \
727               insert.o search.o files.o utils.o
728         cc -o edit main.o kbd.o command.o display.o \
729                    insert.o search.o files.o utils.o
730 @end group
731 @end example
733 @cindex @code{objects}
734 Such duplication is error-prone; if a new object file is added to the
735 system, we might add it to one list and forget the other.  We can eliminate
736 the risk and simplify the makefile by using a variable.  @dfn{Variables}
737 allow a text string to be defined once and substituted in multiple places
738 later (@pxref{Using Variables, ,How to Use Variables}).
740 @cindex @code{OBJECTS}
741 @cindex @code{objs}
742 @cindex @code{OBJS}
743 @cindex @code{obj}
744 @cindex @code{OBJ}
745 It is standard practice for every makefile to have a variable named
746 @code{objects}, @code{OBJECTS}, @code{objs}, @code{OBJS}, @code{obj},
747 or @code{OBJ} which is a list of all object file names.  We would
748 define such a variable @code{objects} with a line like this in the
749 makefile:@refill
751 @example
752 @group
753 objects = main.o kbd.o command.o display.o \
754           insert.o search.o files.o utils.o
755 @end group
756 @end example
758 @noindent
759 Then, each place we want to put a list of the object file names, we can
760 substitute the variable's value by writing @samp{$(objects)}
761 (@pxref{Using Variables, ,How to Use Variables}).
763 Here is how the complete simple makefile looks when you use a variable
764 for the object files:
766 @example
767 @group
768 objects = main.o kbd.o command.o display.o \
769           insert.o search.o files.o utils.o
771 edit : $(objects)
772         cc -o edit $(objects)
773 main.o : main.c defs.h
774         cc -c main.c
775 kbd.o : kbd.c defs.h command.h
776         cc -c kbd.c
777 command.o : command.c defs.h command.h
778         cc -c command.c
779 display.o : display.c defs.h buffer.h
780         cc -c display.c
781 insert.o : insert.c defs.h buffer.h
782         cc -c insert.c
783 search.o : search.c defs.h buffer.h
784         cc -c search.c
785 files.o : files.c defs.h buffer.h command.h
786         cc -c files.c
787 utils.o : utils.c defs.h
788         cc -c utils.c
789 clean :
790         rm edit $(objects)
791 @end group
792 @end example
794 @node make Deduces, Combine By Prerequisite, Variables Simplify, Introduction
795 @section Letting @code{make} Deduce the Commands
796 @cindex deducing commands (implicit rules)
797 @cindex implicit rule, introduction to
798 @cindex rule, implicit, introduction to
800 It is not necessary to spell out the commands for compiling the individual
801 C source files, because @code{make} can figure them out: it has an
802 @dfn{implicit rule} for updating a @samp{.o} file from a correspondingly
803 named @samp{.c} file using a @samp{cc -c} command.  For example, it will
804 use the command @samp{cc -c main.c -o main.o} to compile @file{main.c} into
805 @file{main.o}.  We can therefore omit the commands from the rules for the
806 object files.  @xref{Implicit Rules, ,Using Implicit Rules}.@refill
808 When a @samp{.c} file is used automatically in this way, it is also
809 automatically added to the list of prerequisites.  We can therefore omit
810 the @samp{.c} files from the prerequisites, provided we omit the commands.
812 Here is the entire example, with both of these changes, and a variable
813 @code{objects} as suggested above:
815 @example
816 @group
817 objects = main.o kbd.o command.o display.o \
818           insert.o search.o files.o utils.o
820 edit : $(objects)
821         cc -o edit $(objects)
823 main.o : defs.h
824 kbd.o : defs.h command.h
825 command.o : defs.h command.h
826 display.o : defs.h buffer.h
827 insert.o : defs.h buffer.h
828 search.o : defs.h buffer.h
829 files.o : defs.h buffer.h command.h
830 utils.o : defs.h
832 .PHONY : clean
833 clean :
834         rm edit $(objects)
835 @end group
836 @end example
838 @noindent
839 This is how we would write the makefile in actual practice.  (The
840 complications associated with @samp{clean} are described elsewhere.
841 See @ref{Phony Targets}, and @ref{Errors, ,Errors in Commands}.)
843 Because implicit rules are so convenient, they are important.  You
844 will see them used frequently.@refill
846 @node Combine By Prerequisite, Cleanup, make Deduces, Introduction
847 @section Another Style of Makefile
848 @cindex combining rules by prerequisite
850 When the objects of a makefile are created only by implicit rules, an
851 alternative style of makefile is possible.  In this style of makefile,
852 you group entries by their prerequisites instead of by their targets.
853 Here is what one looks like:
855 @example
856 @group
857 objects = main.o kbd.o command.o display.o \
858           insert.o search.o files.o utils.o
860 edit : $(objects)
861         cc -o edit $(objects)
863 $(objects) : defs.h
864 kbd.o command.o files.o : command.h
865 display.o insert.o search.o files.o : buffer.h
866 @end group
867 @end example
869 @noindent
870 Here @file{defs.h} is given as a prerequisite of all the object files;
871 @file{command.h} and @file{buffer.h} are prerequisites of the specific
872 object files listed for them.
874 Whether this is better is a matter of taste: it is more compact, but some
875 people dislike it because they find it clearer to put all the information
876 about each target in one place.
878 @node Cleanup,  , Combine By Prerequisite, Introduction
879 @section Rules for Cleaning the Directory
880 @cindex cleaning up
881 @cindex removing, to clean up
883 Compiling a program is not the only thing you might want to write rules
884 for.  Makefiles commonly tell how to do a few other things besides
885 compiling a program: for example, how to delete all the object files
886 and executables so that the directory is @samp{clean}.
888 @cindex @code{clean} target
889 Here is how we
890 could write a @code{make} rule for cleaning our example editor:
892 @example
893 @group
894 clean:
895         rm edit $(objects)
896 @end group
897 @end example
899 In practice, we might want to write the rule in a somewhat more
900 complicated manner to handle unanticipated situations.  We would do this:
902 @example
903 @group
904 .PHONY : clean
905 clean :
906         -rm edit $(objects)
907 @end group
908 @end example
910 @noindent
911 This prevents @code{make} from getting confused by an actual file
912 called @file{clean} and causes it to continue in spite of errors from
913 @code{rm}.  (See @ref{Phony Targets}, and @ref{Errors, ,Errors in
914 Commands}.)
916 @noindent
917 A rule such as this should not be placed at the beginning of the
918 makefile, because we do not want it to run by default!  Thus, in the
919 example makefile, we want the rule for @code{edit}, which recompiles
920 the editor, to remain the default goal.
922 Since @code{clean} is not a prerequisite of @code{edit}, this rule will not
923 run at all if we give the command @samp{make} with no arguments.  In
924 order to make the rule run, we have to type @samp{make clean}.
925 @xref{Running, ,How to Run @code{make}}.
927 @node Makefiles, Rules, Introduction, Top
928 @chapter Writing Makefiles
930 @cindex makefile, how to write
931 The information that tells @code{make} how to recompile a system comes from
932 reading a data base called the @dfn{makefile}.
934 @menu
935 * Makefile Contents::           What makefiles contain.
936 * Makefile Names::              How to name your makefile.
937 * Include::                     How one makefile can use another makefile.
938 * MAKEFILES Variable::          The environment can specify extra makefiles.
939 * MAKEFILE_LIST Variable::      Discover which makefiles have been read.
940 * Special Variables::           Other special variables.
941 * Remaking Makefiles::          How makefiles get remade.
942 * Overriding Makefiles::        How to override part of one makefile
943                                   with another makefile.
944 * Reading Makefiles::           How makefiles are parsed.
945 * Secondary Expansion::         How and when secondary expansion is performed.
946 @end menu
948 @node Makefile Contents, Makefile Names, Makefiles, Makefiles
949 @section What Makefiles Contain
951 Makefiles contain five kinds of things: @dfn{explicit rules},
952 @dfn{implicit rules}, @dfn{variable definitions}, @dfn{directives},
953 and @dfn{comments}.  Rules, variables, and directives are described at
954 length in later chapters.@refill
956 @itemize @bullet
957 @cindex rule, explicit, definition of
958 @cindex explicit rule, definition of
959 @item
960 An @dfn{explicit rule} says when and how to remake one or more files,
961 called the rule's @dfn{targets}.  It lists the other files that the
962 targets depend on, called the @dfn{prerequisites} of the target, and
963 may also give commands to use to create or update the targets.
964 @xref{Rules, ,Writing Rules}.
966 @cindex rule, implicit, definition of
967 @cindex implicit rule, definition of
968 @item
969 An @dfn{implicit rule} says when and how to remake a class of files
970 based on their names.  It describes how a target may depend on a file
971 with a name similar to the target and gives commands to create or
972 update such a target.  @xref{Implicit Rules, ,Using Implicit Rules}.
974 @cindex variable definition
975 @item
976 A @dfn{variable definition} is a line that specifies a text string
977 value for a variable that can be substituted into the text later.  The
978 simple makefile example shows a variable definition for @code{objects}
979 as a list of all object files (@pxref{Variables Simplify, , Variables
980 Make Makefiles Simpler}).
982 @cindex directive
983 @item
984 A @dfn{directive} is a command for @code{make} to do something special while
985 reading the makefile.  These include:
987 @itemize @bullet
988 @item
989 Reading another makefile (@pxref{Include, ,Including Other Makefiles}).
991 @item
992 Deciding (based on the values of variables) whether to use or
993 ignore a part of the makefile (@pxref{Conditionals, ,Conditional Parts of Makefiles}).
995 @item
996 Defining a variable from a verbatim string containing multiple lines
997 (@pxref{Defining, ,Defining Variables Verbatim}).
998 @end itemize
1000 @cindex comments, in makefile
1001 @cindex @code{#} (comments), in makefile
1002 @item
1003 @samp{#} in a line of a makefile starts a @dfn{comment}.  It and the
1004 rest of the line are ignored, except that a trailing backslash not
1005 escaped by another backslash will continue the comment across multiple
1006 lines.  A line containing just a comment (with perhaps spaces before
1007 it) is effectively blank, and is ignored.  If you want a literal
1008 @code{#}, escape it with a backslash (e.g., @code{\#}).  Comments may
1009 appear on any line in the makefile, although they are treated
1010 specially in certain situations.
1012 You cannot use comments within variable references or function calls:
1013 any instance of @code{#} will be treated literally (rather than as the
1014 start of a comment) inside a variable reference or function call.
1016 Within a command script (if the line begins with a TAB character) the
1017 entire line is passed to the shell, just as with any other line that
1018 begins with a TAB.  The shell decides how to interpret the text:
1019 whether or not this is a comment is up to the shell.
1021 Within a @code{define} directive, comments are not ignored during the
1022 definition of the variable, but rather kept intact in the value of the
1023 variable.  When the variable is expanded they will either be treated
1024 as @code{make} comments or as command script text, depending on the
1025 context in which the variable is evaluated.
1026 @end itemize
1028 @node Makefile Names, Include, Makefile Contents, Makefiles
1029 @section What Name to Give Your Makefile
1030 @cindex makefile name
1031 @cindex name of makefile
1032 @cindex default makefile name
1033 @cindex file name of makefile
1035 @c following paragraph rewritten to avoid overfull hbox
1036 By default, when @code{make} looks for the makefile, it tries the
1037 following names, in order: @file{GNUmakefile}, @file{makefile}
1038 and @file{Makefile}.@refill
1039 @findex Makefile
1040 @findex GNUmakefile
1041 @findex makefile
1043 @cindex @code{README}
1044 Normally you should call your makefile either @file{makefile} or
1045 @file{Makefile}.  (We recommend @file{Makefile} because it appears
1046 prominently near the beginning of a directory listing, right near other
1047 important files such as @file{README}.)  The first name checked,
1048 @file{GNUmakefile}, is not recommended for most makefiles.  You should
1049 use this name if you have a makefile that is specific to GNU
1050 @code{make}, and will not be understood by other versions of
1051 @code{make}.  Other @code{make} programs look for @file{makefile} and
1052 @file{Makefile}, but not @file{GNUmakefile}.
1054 If @code{make} finds none of these names, it does not use any makefile.
1055 Then you must specify a goal with a command argument, and @code{make}
1056 will attempt to figure out how to remake it using only its built-in
1057 implicit rules.  @xref{Implicit Rules, ,Using Implicit Rules}.
1059 @cindex @code{-f}
1060 @cindex @code{--file}
1061 @cindex @code{--makefile}
1062 If you want to use a nonstandard name for your makefile, you can specify
1063 the makefile name with the @samp{-f} or @samp{--file} option.  The
1064 arguments @w{@samp{-f @var{name}}} or @w{@samp{--file=@var{name}}} tell
1065 @code{make} to read the file @var{name} as the makefile.  If you use
1066 more than one @samp{-f} or @samp{--file} option, you can specify several
1067 makefiles.  All the makefiles are effectively concatenated in the order
1068 specified.  The default makefile names @file{GNUmakefile},
1069 @file{makefile} and @file{Makefile} are not checked automatically if you
1070 specify @samp{-f} or @samp{--file}.@refill
1071 @cindex specifying makefile name
1072 @cindex makefile name, how to specify
1073 @cindex name of makefile, how to specify
1074 @cindex file name of makefile, how to specify
1076 @node Include, MAKEFILES Variable, Makefile Names, Makefiles
1077 @section Including Other Makefiles
1078 @cindex including other makefiles
1079 @cindex makefile, including
1081 @findex include
1082 The @code{include} directive tells @code{make} to suspend reading the
1083 current makefile and read one or more other makefiles before continuing.
1084 The directive is a line in the makefile that looks like this:
1086 @example
1087 include @var{filenames}@dots{}
1088 @end example
1090 @noindent
1091 @var{filenames} can contain shell file name patterns.  If
1092 @var{filenames} is empty, nothing is included and no error is printed.
1093 @cindex shell file name pattern (in @code{include})
1094 @cindex shell wildcards (in @code{include})
1095 @cindex wildcard, in @code{include}
1097 Extra spaces are allowed and ignored at the beginning of the line, but
1098 a tab is not allowed.  (If the line begins with a tab, it will be
1099 considered a command line.)  Whitespace is required between
1100 @code{include} and the file names, and between file names; extra
1101 whitespace is ignored there and at the end of the directive.  A
1102 comment starting with @samp{#} is allowed at the end of the line.  If
1103 the file names contain any variable or function references, they are
1104 expanded.  @xref{Using Variables, ,How to Use Variables}.
1106 For example, if you have three @file{.mk} files, @file{a.mk},
1107 @file{b.mk}, and @file{c.mk}, and @code{$(bar)} expands to
1108 @code{bish bash}, then the following expression
1110 @example
1111 include foo *.mk $(bar)
1112 @end example
1114 is equivalent to
1116 @example
1117 include foo a.mk b.mk c.mk bish bash
1118 @end example
1120 When @code{make} processes an @code{include} directive, it suspends
1121 reading of the containing makefile and reads from each listed file in
1122 turn.  When that is finished, @code{make} resumes reading the
1123 makefile in which the directive appears.
1125 One occasion for using @code{include} directives is when several programs,
1126 handled by individual makefiles in various directories, need to use a
1127 common set of variable definitions
1128 (@pxref{Setting, ,Setting Variables}) or pattern rules
1129 (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
1131 Another such occasion is when you want to generate prerequisites from
1132 source files automatically; the prerequisites can be put in a file that
1133 is included by the main makefile.  This practice is generally cleaner
1134 than that of somehow appending the prerequisites to the end of the main
1135 makefile as has been traditionally done with other versions of
1136 @code{make}.  @xref{Automatic Prerequisites}.
1137 @cindex prerequisites, automatic generation
1138 @cindex automatic generation of prerequisites
1139 @cindex generating prerequisites automatically
1141 @cindex @code{-I}
1142 @cindex @code{--include-dir}
1143 @cindex included makefiles, default directories
1144 @cindex default directories for included makefiles
1145 @findex /usr/gnu/include
1146 @findex /usr/local/include
1147 @findex /usr/include
1148 If the specified name does not start with a slash, and the file is not
1149 found in the current directory, several other directories are searched.
1150 First, any directories you have specified with the @samp{-I} or
1151 @samp{--include-dir} option are searched
1152 (@pxref{Options Summary, ,Summary of Options}).
1153 Then the following directories (if they exist)
1154 are searched, in this order:
1155 @file{@var{prefix}/include} (normally @file{/usr/local/include}
1156 @footnote{GNU Make compiled for MS-DOS and MS-Windows behaves as if
1157 @var{prefix} has been defined to be the root of the DJGPP tree
1158 hierarchy.})
1159 @file{/usr/gnu/include},
1160 @file{/usr/local/include}, @file{/usr/include}.
1162 If an included makefile cannot be found in any of these directories, a
1163 warning message is generated, but it is not an immediately fatal error;
1164 processing of the makefile containing the @code{include} continues.
1165 Once it has finished reading makefiles, @code{make} will try to remake
1166 any that are out of date or don't exist.
1167 @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
1168 Only after it has tried to find a way to remake a makefile and failed,
1169 will @code{make} diagnose the missing makefile as a fatal error.
1171 If you want @code{make} to simply ignore a makefile which does not exist
1172 and cannot be remade, with no error message, use the @w{@code{-include}}
1173 directive instead of @code{include}, like this:
1175 @example
1176 -include @var{filenames}@dots{}
1177 @end example
1179 This acts like @code{include} in every way except that there is no
1180 error (not even a warning) if any of the @var{filenames} do not exist.
1181 For compatibility with some other @code{make} implementations,
1182 @code{sinclude} is another name for @w{@code{-include}}.
1184 @node MAKEFILES Variable, MAKEFILE_LIST Variable, Include, Makefiles
1185 @section The Variable @code{MAKEFILES}
1186 @cindex makefile, and @code{MAKEFILES} variable
1187 @cindex including (@code{MAKEFILES} variable)
1189 @vindex MAKEFILES
1190 If the environment variable @code{MAKEFILES} is defined, @code{make}
1191 considers its value as a list of names (separated by whitespace) of
1192 additional makefiles to be read before the others.  This works much like
1193 the @code{include} directive: various directories are searched for those
1194 files (@pxref{Include, ,Including Other Makefiles}).  In addition, the
1195 default goal is never taken from one of these makefiles and it is not an
1196 error if the files listed in @code{MAKEFILES} are not found.@refill
1198 @cindex recursion, and @code{MAKEFILES} variable
1199 The main use of @code{MAKEFILES} is in communication between recursive
1200 invocations of @code{make} (@pxref{Recursion, ,Recursive Use of
1201 @code{make}}).  It usually is not desirable to set the environment
1202 variable before a top-level invocation of @code{make}, because it is
1203 usually better not to mess with a makefile from outside.  However, if
1204 you are running @code{make} without a specific makefile, a makefile in
1205 @code{MAKEFILES} can do useful things to help the built-in implicit
1206 rules work better, such as defining search paths (@pxref{Directory Search}).
1208 Some users are tempted to set @code{MAKEFILES} in the environment
1209 automatically on login, and program makefiles to expect this to be done.
1210 This is a very bad idea, because such makefiles will fail to work if run by
1211 anyone else.  It is much better to write explicit @code{include} directives
1212 in the makefiles.  @xref{Include, , Including Other Makefiles}.
1214 @node MAKEFILE_LIST Variable, Special Variables, MAKEFILES Variable, Makefiles
1215 @comment  node-name,  next,  previous,  up
1216 @section The Variable @code{MAKEFILE_LIST}
1217 @cindex makefiles, and @code{MAKEFILE_LIST} variable
1218 @cindex including (@code{MAKEFILE_LIST} variable)
1219 @vindex MAKEFILE_LIST
1221 As @code{make} reads various makefiles, including any obtained from the
1222 @code{MAKEFILES} variable, the command line, the default files, or
1223 from @code{include} directives, their names will be automatically
1224 appended to the @code{MAKEFILE_LIST} variable.  They are added right
1225 before @code{make} begins to parse them.
1227 This means that if the first thing a makefile does is examine the last
1228 word in this variable, it will be the name of the current makefile.
1229 Once the current makefile has used @code{include}, however, the last
1230 word will be the just-included makefile.
1232 If a makefile named @code{Makefile} has this content:
1234 @example
1235 @group
1236 name1 := $(lastword $(MAKEFILE_LIST))
1238 include inc.mk
1240 name2 := $(lastword $(MAKEFILE_LIST))
1242 all:
1243         @@echo name1 = $(name1)
1244         @@echo name2 = $(name2)
1245 @end group
1246 @end example
1248 @noindent
1249 then you would expect to see this output:
1251 @example
1252 @group
1253 name1 = Makefile
1254 name2 = inc.mk
1255 @end group
1256 @end example
1258 @xref{Text Functions}, for more information on the @code{lastword}
1259 function used above.  @xref{Flavors, The Two Flavors of Variables},
1260 for more information on simply-expanded (@code{:=}) variable
1261 definitions.
1263 @node Special Variables, Remaking Makefiles, MAKEFILE_LIST Variable, Makefiles
1264 @comment  node-name,  next,  previous,  up
1265 @section Other Special Variables
1266 @cindex makefiles, and special variables
1267 @cindex special variables
1269 GNU @code{make} also supports other special variables.  Unless
1270 otherwise documented here, these values lose their special properties
1271 if they are set by a makefile or on the command line.
1273 @table @code
1275 @vindex .DEFAULT_GOAL @r{(define default goal)}
1276 @item .DEFAULT_GOAL
1277 Sets the default goal to be used if no targets were specified on the
1278 command line (@pxref{Goals, , Arguments to Specify the Goals}).  The
1279 @code{.DEFAULT_GOAL} variable allows you to discover the current
1280 default goal, restart the default goal selection algorithm by clearing
1281 its value, or to explicitly set the default goal.  The following
1282 example illustrates these cases:
1284 @example
1285 @group
1286 # Query the default goal.
1287 ifeq ($(.DEFAULT_GOAL),)
1288   $(warning no default goal is set)
1289 endif
1291 .PHONY: foo
1292 foo: ; @@echo $@@
1294 $(warning default goal is $(.DEFAULT_GOAL))
1296 # Reset the default goal.
1297 .DEFAULT_GOAL :=
1299 .PHONY: bar
1300 bar: ; @@echo $@@
1302 $(warning default goal is $(.DEFAULT_GOAL))
1304 # Set our own.
1305 .DEFAULT_GOAL := foo
1306 @end group
1307 @end example
1309 This makefile prints:
1311 @example
1312 @group
1313 no default goal is set
1314 default goal is foo
1315 default goal is bar
1317 @end group
1318 @end example
1320 Note that assigning more than one target name to @code{.DEFAULT_GOAL} is
1321 illegal and will result in an error.
1323 @vindex MAKE_RESTARTS @r{(number of times @code{make} has restarted)}
1324 @item MAKE_RESTARTS
1325 This variable is set only if this instance of @code{make} has
1326 restarted (@pxref{Remaking Makefiles, , How Makefiles Are Remade}): it
1327 will contain the number of times this instance has restarted.  Note
1328 this is not the same as recursion (counted by the @code{MAKELEVEL}
1329 variable).  You should not set, modify, or export this variable.
1331 @vindex .VARIABLES @r{(list of variables)}
1332 @item .VARIABLES
1333 Expands to a list of the @emph{names} of all global variables defined
1334 so far.  This includes variables which have empty values, as well as
1335 built-in variables (@pxref{Implicit Variables, , Variables Used by
1336 Implicit Rules}), but does not include any variables which are only
1337 defined in a target-specific context.  Note that any value you assign
1338 to this variable will be ignored; it will always return its special
1339 value.
1341 @c @vindex .TARGETS @r{(list of targets)}
1342 @c @item .TARGETS
1343 @c The second special variable is @code{.TARGETS}.  When expanded, the
1344 @c value consists of a list of all targets defined in all makefiles read
1345 @c up until that point.  Note it's not enough for a file to be simply
1346 @c mentioned in the makefile to be listed in this variable, even if it
1347 @c would match an implicit rule and become an ``implicit target''.  The
1348 @c file must appear as a target, on the left-hand side of a ``:'', to be
1349 @c considered a target for the purposes of this variable.
1351 @vindex .FEATURES @r{(list of supported features)}
1352 @item .FEATURES
1353 Expands to a list of special features supported by this version of
1354 @code{make}.  Possible values include:
1356 @table @samp
1358 @item archives
1359 Supports @code{ar} (archive) files using special filename syntax.
1360 @xref{Archives, ,Using @code{make} to Update Archive Files}.
1362 @item check-symlink
1363 Supports the @code{-L} (@code{--check-symlink-times}) flag.
1364 @xref{Options Summary, ,Summary of Options}.
1366 @item else-if
1367 Supports ``else if'' non-nested conditionals.  @xref{Conditional
1368 Syntax, ,Syntax of Conditionals}.
1370 @item jobserver
1371 Supports ``job server'' enhanced parallel builds.  @xref{Parallel,
1372 ,Parallel Execution}.
1374 @item second-expansion
1375 Supports secondary expansion of prerequisite lists.
1377 @item order-only
1378 Supports order-only prerequisites.  @xref{Prerequisite Types, ,Types
1379 of Prerequisites}.
1381 @item target-specific
1382 Supports target-specific and pattern-specific variable assignments.
1383 @xref{Target-specific, ,Target-specific Variable Values}.
1385 @end table
1387 @vindex .INCLUDE_DIRS @r{(list of include directories)}
1388 @item .INCLUDE_DIRS
1389 Expands to a list of directories that @code{make} searches for
1390 included makefiles (@pxref{Include, , Including Other Makefiles}).
1392 @end table
1394 @node Remaking Makefiles, Overriding Makefiles, Special Variables, Makefiles
1395 @section How Makefiles Are Remade
1397 @cindex updating makefiles
1398 @cindex remaking makefiles
1399 @cindex makefile, remaking of
1400 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1401 files.  If a makefile can be remade from other files, you probably want
1402 @code{make} to get an up-to-date version of the makefile to read in.
1404 To this end, after reading in all makefiles, @code{make} will consider
1405 each as a goal target and attempt to update it.  If a makefile has a
1406 rule which says how to update it (found either in that very makefile or
1407 in another one) or if an implicit rule applies to it (@pxref{Implicit
1408 Rules, ,Using Implicit Rules}), it will be updated if necessary.  After
1409 all makefiles have been checked, if any have actually been changed,
1410 @code{make} starts with a clean slate and reads all the makefiles over
1411 again.  (It will also attempt to update each of them over again, but
1412 normally this will not change them again, since they are already up to
1413 date.)@refill
1415 If you know that one or more of your makefiles cannot be remade and you
1416 want to keep @code{make} from performing an implicit rule search on
1417 them, perhaps for efficiency reasons, you can use any normal method of
1418 preventing implicit rule lookup to do so.  For example, you can write an
1419 explicit rule with the makefile as the target, and an empty command
1420 string (@pxref{Empty Commands, ,Using Empty Commands}).
1422 If the makefiles specify a double-colon rule to remake a file with
1423 commands but no prerequisites, that file will always be remade
1424 (@pxref{Double-Colon}).  In the case of makefiles, a makefile that has a
1425 double-colon rule with commands but no prerequisites will be remade every
1426 time @code{make} is run, and then again after @code{make} starts over
1427 and reads the makefiles in again.  This would cause an infinite loop:
1428 @code{make} would constantly remake the makefile, and never do anything
1429 else.  So, to avoid this, @code{make} will @strong{not} attempt to
1430 remake makefiles which are specified as targets of a double-colon rule
1431 with commands but no prerequisites.@refill
1433 If you do not specify any makefiles to be read with @samp{-f} or
1434 @samp{--file} options, @code{make} will try the default makefile names;
1435 @pxref{Makefile Names, ,What Name to Give Your Makefile}.  Unlike
1436 makefiles explicitly requested with @samp{-f} or @samp{--file} options,
1437 @code{make} is not certain that these makefiles should exist.  However,
1438 if a default makefile does not exist but can be created by running
1439 @code{make} rules, you probably want the rules to be run so that the
1440 makefile can be used.
1442 Therefore, if none of the default makefiles exists, @code{make} will try
1443 to make each of them in the same order in which they are searched for
1444 (@pxref{Makefile Names, ,What Name to Give Your Makefile})
1445 until it succeeds in making one, or it runs out of names to try.  Note
1446 that it is not an error if @code{make} cannot find or make any makefile;
1447 a makefile is not always necessary.@refill
1449 When you use the @samp{-t} or @samp{--touch} option
1450 (@pxref{Instead of Execution, ,Instead of Executing the Commands}),
1451 you would not want to use an out-of-date makefile to decide which
1452 targets to touch.  So the @samp{-t} option has no effect on updating
1453 makefiles; they are really updated even if @samp{-t} is specified.
1454 Likewise, @samp{-q} (or @samp{--question}) and @samp{-n} (or
1455 @samp{--just-print}) do not prevent updating of makefiles, because an
1456 out-of-date makefile would result in the wrong output for other targets.
1457 Thus, @samp{make -f mfile -n foo} will update @file{mfile}, read it in,
1458 and then print the commands to update @file{foo} and its prerequisites
1459 without running them.  The commands printed for @file{foo} will be those
1460 specified in the updated contents of @file{mfile}.
1462 However, on occasion you might actually wish to prevent updating of even
1463 the makefiles.  You can do this by specifying the makefiles as goals in
1464 the command line as well as specifying them as makefiles.  When the
1465 makefile name is specified explicitly as a goal, the options @samp{-t}
1466 and so on do apply to them.
1468 Thus, @samp{make -f mfile -n mfile foo} would read the makefile
1469 @file{mfile}, print the commands needed to update it without actually
1470 running them, and then print the commands needed to update @file{foo}
1471 without running them.  The commands for @file{foo} will be those
1472 specified by the existing contents of @file{mfile}.
1474 @node Overriding Makefiles, Reading Makefiles, Remaking Makefiles, Makefiles
1475 @section Overriding Part of Another Makefile
1477 @cindex overriding makefiles
1478 @cindex makefile, overriding
1479 Sometimes it is useful to have a makefile that is mostly just like
1480 another makefile.  You can often use the @samp{include} directive to
1481 include one in the other, and add more targets or variable definitions.
1482 However, if the two makefiles give different commands for the same
1483 target, @code{make} will not let you just do this.  But there is another way.
1485 @cindex match-anything rule, used to override
1486 In the containing makefile (the one that wants to include the other),
1487 you can use a match-anything pattern rule to say that to remake any
1488 target that cannot be made from the information in the containing
1489 makefile, @code{make} should look in another makefile.
1490 @xref{Pattern Rules}, for more information on pattern rules.
1492 For example, if you have a makefile called @file{Makefile} that says how
1493 to make the target @samp{foo} (and other targets), you can write a
1494 makefile called @file{GNUmakefile} that contains:
1496 @example
1497 foo:
1498         frobnicate > foo
1500 %: force
1501         @@$(MAKE) -f Makefile $@@
1502 force: ;
1503 @end example
1505 If you say @samp{make foo}, @code{make} will find @file{GNUmakefile},
1506 read it, and see that to make @file{foo}, it needs to run the command
1507 @samp{frobnicate > foo}.  If you say @samp{make bar}, @code{make} will
1508 find no way to make @file{bar} in @file{GNUmakefile}, so it will use the
1509 commands from the pattern rule: @samp{make -f Makefile bar}.  If
1510 @file{Makefile} provides a rule for updating @file{bar}, @code{make}
1511 will apply the rule.  And likewise for any other target that
1512 @file{GNUmakefile} does not say how to make.
1514 The way this works is that the pattern rule has a pattern of just
1515 @samp{%}, so it matches any target whatever.  The rule specifies a
1516 prerequisite @file{force}, to guarantee that the commands will be run even
1517 if the target file already exists.  We give @file{force} target empty
1518 commands to prevent @code{make} from searching for an implicit rule to
1519 build it---otherwise it would apply the same match-anything rule to
1520 @file{force} itself and create a prerequisite loop!
1522 @node Reading Makefiles,  Secondary Expansion, Overriding Makefiles, Makefiles
1523 @section How @code{make} Reads a Makefile
1524 @cindex reading makefiles
1525 @cindex makefile, parsing
1527 GNU @code{make} does its work in two distinct phases.  During the first
1528 phase it reads all the makefiles, included makefiles, etc. and
1529 internalizes all the variables and their values, implicit and explicit
1530 rules, and constructs a dependency graph of all the targets and their
1531 prerequisites.  During the second phase, @code{make} uses these internal
1532 structures to determine what targets will need to be rebuilt and to
1533 invoke the rules necessary to do so.
1535 It's important to understand this two-phase approach because it has a
1536 direct impact on how variable and function expansion happens; this is
1537 often a source of some confusion when writing makefiles.  Here we will
1538 present a summary of the phases in which expansion happens for different
1539 constructs within the makefile.  We say that expansion is
1540 @dfn{immediate} if it happens during the first phase: in this case
1541 @code{make} will expand any variables or functions in that section of a
1542 construct as the makefile is parsed.  We say that expansion is
1543 @dfn{deferred} if expansion is not performed immediately.  Expansion of
1544 a deferred construct is not performed until either the construct appears
1545 later in an immediate context, or until the second phase.
1547 You may not be familiar with some of these constructs yet.  You can
1548 reference this section as you become familiar with them, in later
1549 chapters.
1551 @subheading Variable Assignment
1552 @cindex +=, expansion
1553 @cindex =, expansion
1554 @cindex ?=, expansion
1555 @cindex +=, expansion
1556 @cindex define, expansion
1558 Variable definitions are parsed as follows:
1560 @example
1561 @var{immediate} = @var{deferred}
1562 @var{immediate} ?= @var{deferred}
1563 @var{immediate} := @var{immediate}
1564 @var{immediate} += @var{deferred} or @var{immediate}
1566 define @var{immediate}
1567   @var{deferred}
1568 endef
1569 @end example
1571 For the append operator, @samp{+=}, the right-hand side is considered
1572 immediate if the variable was previously set as a simple variable
1573 (@samp{:=}), and deferred otherwise.
1575 @subheading Conditional Statements
1576 @cindex ifdef, expansion
1577 @cindex ifeq, expansion
1578 @cindex ifndef, expansion
1579 @cindex ifneq, expansion
1581 All instances of conditional syntax are parsed immediately, in their
1582 entirety; this includes the @code{ifdef}, @code{ifeq}, @code{ifndef},
1583 and @code{ifneq} forms.  Of course this means that automatic variables
1584 cannot be used in conditional statements, as automatic variables are
1585 not set until the command script for that rule is invoked.  If you
1586 need to use automatic variables in a conditional you @emph{must} use
1587 shell conditional syntax, in your command script proper, for these
1588 tests, not @code{make} conditionals.
1590 @subheading Rule Definition
1591 @cindex target, expansion
1592 @cindex prerequisite, expansion
1593 @cindex implicit rule, expansion
1594 @cindex pattern rule, expansion
1595 @cindex explicit rule, expansion
1597 A rule is always expanded the same way, regardless of the form:
1599 @example
1600 @var{immediate} : @var{immediate} ; @var{deferred}
1601         @var{deferred}
1602 @end example
1604 That is, the target and prerequisite sections are expanded immediately,
1605 and the commands used to construct the target are always deferred.  This
1606 general rule is true for explicit rules, pattern rules, suffix rules,
1607 static pattern rules, and simple prerequisite definitions.
1609 @node Secondary Expansion, , Reading Makefiles, Makefiles
1610 @section Secondary Expansion
1611 @cindex secondary expansion
1612 @cindex expansion, secondary
1614 @findex .SECONDEXPANSION
1615 In the previous section we learned that GNU @code{make} works in two
1616 distinct phases: a read-in phase and a target-update phase
1617 (@pxref{Reading Makefiles, , How @code{make} Reads a Makefile}).  GNU
1618 make also has the ability to enable a @emph{second expansion} of the
1619 prerequisites (only) for some or all targets defined in the makefile.
1620 In order for this second expansion to occur, the special target
1621 @code{.SECONDEXPANSION} must be defined before the first prerequisite
1622 list that makes use of this feature.
1624 If that special target is defined then in between the two phases
1625 mentioned above, right at the end of the read-in phase, all the
1626 prerequisites of the targets defined after the special target are
1627 expanded a @emph{second time}.  In most circumstances this secondary
1628 expansion will have no effect, since all variable and function
1629 references will have been expanded during the initial parsing of the
1630 makefiles.  In order to take advantage of the secondary expansion
1631 phase of the parser, then, it's necessary to @emph{escape} the
1632 variable or function reference in the makefile.  In this case the
1633 first expansion merely un-escapes the reference but doesn't expand it,
1634 and expansion is left to the secondary expansion phase.  For example,
1635 consider this makefile:
1637 @example
1638 .SECONDEXPANSION:
1639 ONEVAR = onefile
1640 TWOVAR = twofile
1641 myfile: $(ONEVAR) $$(TWOVAR)
1642 @end example
1644 After the first expansion phase the prerequisites list of the
1645 @file{myfile} target will be @code{onefile} and @code{$(TWOVAR)}; the
1646 first (unescaped) variable reference to @var{ONEVAR} is expanded,
1647 while the second (escaped) variable reference is simply unescaped,
1648 without being recognized as a variable reference.  Now during the
1649 secondary expansion the first word is expanded again but since it
1650 contains no variable or function references it remains the static
1651 value @file{onefile}, while the second word is now a normal reference
1652 to the variable @var{TWOVAR}, which is expanded to the value
1653 @file{twofile}.  The final result is that there are two prerequisites,
1654 @file{onefile} and @file{twofile}.
1656 Obviously, this is not a very interesting case since the same result
1657 could more easily have been achieved simply by having both variables
1658 appear, unescaped, in the prerequisites list.  One difference becomes
1659 apparent if the variables are reset; consider this example:
1661 @example
1662 .SECONDEXPANSION:
1663 AVAR = top
1664 onefile: $(AVAR)
1665 twofile: $$(AVAR)
1666 AVAR = bottom
1667 @end example
1669 Here the prerequisite of @file{onefile} will be expanded immediately,
1670 and resolve to the value @file{top}, while the prerequisite of
1671 @file{twofile} will not be full expanded until the secondary expansion
1672 and yield a value of @file{bottom}.
1674 This is marginally more exciting, but the true power of this feature
1675 only becomes apparent when you discover that secondary expansions
1676 always take place within the scope of the automatic variables for that
1677 target.  This means that you can use variables such as @code{$@@},
1678 @code{$*}, etc. during the second expansion and they will have their
1679 expected values, just as in the command script.  All you have to do is
1680 defer the expansion by escaping the @code{$}.  Also, secondary
1681 expansion occurs for both explicit and implicit (pattern) rules.
1682 Knowing this, the possible uses for this feature increase
1683 dramatically.  For example:
1685 @example
1686 .SECONDEXPANSION:
1687 main_OBJS := main.o try.o test.o
1688 lib_OBJS := lib.o api.o
1690 main lib: $$($$@@_OBJS)
1691 @end example
1693 Here, after the initial expansion the prerequisites of both the
1694 @file{main} and @file{lib} targets will be @code{$($@@_OBJS)}.  During
1695 the secondary expansion, the @code{$@@} variable is set to the name of
1696 the target and so the expansion for the @file{main} target will yield
1697 @code{$(main_OBJS)}, or @code{main.o try.o test.o}, while the
1698 secondary expansion for the @file{lib} target will yield
1699 @code{$(lib_OBJS)}, or @code{lib.o api.o}.
1701 You can also mix functions here, as long as they are properly escaped:
1703 @example
1704 main_SRCS := main.c try.c test.c
1705 lib_SRCS := lib.c api.c
1707 .SECONDEXPANSION:
1708 main lib: $$(patsubst %.c,%.o,$$($$@@_SRCS))
1709 @end example
1711 This version allows users to specify source files rather than object
1712 files, but gives the same resulting prerequisites list as the previous
1713 example.
1715 Evaluation of automatic variables during the secondary expansion
1716 phase, especially of the target name variable @code{$$@@}, behaves
1717 similarly to evaluation within command scripts.  However, there are
1718 some subtle differences and ``corner cases'' which come into play for
1719 the different types of rule definitions that @code{make} understands.
1720 The subtleties of using the different automatic variables are
1721 described below.
1723 @subheading Secondary Expansion of Explicit Rules
1724 @cindex secondary expansion and explicit rules
1725 @cindex explicit rules, secondary expansion of
1727 During the secondary expansion of explicit rules, @code{$$@@} and
1728 @code{$$%} evaluate, respectively, to the file name of the target and,
1729 when the target is an archive member, the target member name.  The
1730 @code{$$<} variable evaluates to the first prerequisite in the first
1731 rule for this target.  @code{$$^} and @code{$$+} evaluate to the list
1732 of all prerequisites of rules @emph{that have already appeared} for
1733 the same target (@code{$$+} with repetitions and @code{$$^}
1734 without).  The following example will help illustrate these behaviors:
1736 @example
1737 .SECONDEXPANSION:
1739 foo: foo.1 bar.1 $$< $$^ $$+    # line #1
1741 foo: foo.2 bar.2 $$< $$^ $$+    # line #2
1743 foo: foo.3 bar.3 $$< $$^ $$+    # line #3
1744 @end example
1746 In the first prerequisite list, all three variables (@code{$$<},
1747 @code{$$^}, and @code{$$+}) expand to the empty string.  In the
1748 second, they will have values @code{foo.1}, @code{foo.1 bar.1}, and
1749 @code{foo.1 bar.1} respectively.  In the third they will have values
1750 @code{foo.1}, @code{foo.1 bar.1 foo.2 bar.2}, and @code{foo.1 bar.1
1751 foo.2 bar.2 foo.1 foo.1 bar.1 foo.1 bar.1} respectively.
1753 Rules undergo secondary expansion in makefile order, except that
1754 the rule with the command script is always evaluated last.
1756 The variables @code{$$?} and @code{$$*} are not available and expand
1757 to the empty string.
1759 @subheading Secondary Expansion of Static Pattern Rules
1760 @cindex secondary expansion and static pattern rules
1761 @cindex static pattern rules, secondary expansion of
1763 Rules for secondary expansion of static pattern rules are identical to
1764 those for explicit rules, above, with one exception: for static
1765 pattern rules the @code{$$*} variable is set to the pattern stem.  As
1766 with explicit rules, @code{$$?} is not available and expands to the
1767 empty string.
1769 @subheading Secondary Expansion of Implicit Rules
1770 @cindex secondary expansion and implicit rules
1771 @cindex implicit rules, secondary expansion of
1773 As @code{make} searches for an implicit rule, it substitutes the stem
1774 and then performs secondary expansion for every rule with a matching
1775 target pattern.  The value of the automatic variables is derived in
1776 the same fashion as for static pattern rules.  As an example:
1778 @example
1779 .SECONDEXPANSION:
1781 foo: bar
1783 foo foz: fo%: bo%
1785 %oo: $$< $$^ $$+ $$*
1786 @end example
1788 When the implicit rule is tried for target @file{foo}, @code{$$<}
1789 expands to @file{bar}, @code{$$^} expands to @file{bar boo},
1790 @code{$$+} also expands to @file{bar boo}, and @code{$$*} expands to
1791 @file{f}.
1793 Note that the directory prefix (D), as described in @ref{Implicit Rule
1794 Search, ,Implicit Rule Search Algorithm}, is appended (after
1795 expansion) to all the patterns in the prerequisites list.  As an
1796 example:
1798 @example
1799 .SECONDEXPANSION:
1801 /tmp/foo.o:
1803 %.o: $$(addsuffix /%.c,foo bar) foo.h
1804 @end example
1806 The prerequisite list after the secondary expansion and directory
1807 prefix reconstruction will be @file{/tmp/foo/foo.c /tmp/var/bar/foo.c
1808 foo.h}.  If you are not interested in this reconstruction, you can use
1809 @code{$$*} instead of @code{%} in the prerequisites list.
1811 @node Rules, Commands, Makefiles, Top
1812 @chapter Writing Rules
1813 @cindex writing rules
1814 @cindex rule, how to write
1815 @cindex target
1816 @cindex prerequisite
1818 A @dfn{rule} appears in the makefile and says when and how to remake
1819 certain files, called the rule's @dfn{targets} (most often only one per rule).
1820 It lists the other files that are the @dfn{prerequisites} of the target, and
1821 @dfn{commands} to use to create or update the target.
1823 @cindex default goal
1824 @cindex goal, default
1825 The order of rules is not significant, except for determining the
1826 @dfn{default goal}: the target for @code{make} to consider, if you do
1827 not otherwise specify one.  The default goal is the target of the first
1828 rule in the first makefile.  If the first rule has multiple targets,
1829 only the first target is taken as the default.  There are two
1830 exceptions: a target starting with a period is not a default unless it
1831 contains one or more slashes, @samp{/}, as well; and, a target that
1832 defines a pattern rule has no effect on the default goal.
1833 (@xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.)
1835 Therefore, we usually write the makefile so that the first rule is the
1836 one for compiling the entire program or all the programs described by
1837 the makefile (often with a target called @samp{all}).
1838 @xref{Goals, ,Arguments to Specify the Goals}.
1840 @menu
1841 * Rule Example::                An example explained.
1842 * Rule Syntax::                 General syntax explained.
1843 * Prerequisite Types::          There are two types of prerequisites.
1844 * Wildcards::                   Using wildcard characters such as `*'.
1845 * Directory Search::            Searching other directories for source files.
1846 * Phony Targets::               Using a target that is not a real file's name.
1847 * Force Targets::               You can use a target without commands
1848                                   or prerequisites to mark other targets
1849                                   as phony.
1850 * Empty Targets::               When only the date matters and the
1851                                   files are empty.
1852 * Special Targets::             Targets with special built-in meanings.
1853 * Multiple Targets::            When to make use of several targets in a rule.
1854 * Multiple Rules::              How to use several rules with the same target.
1855 * Static Pattern::              Static pattern rules apply to multiple targets
1856                                   and can vary the prerequisites according to
1857                                   the target name.
1858 * Double-Colon::                How to use a special kind of rule to allow
1859                                   several independent rules for one target.
1860 * Automatic Prerequisites::     How to automatically generate rules giving
1861                                   prerequisites from source files themselves.
1862 @end menu
1864 @ifnottex
1865 @node Rule Example, Rule Syntax, Rules, Rules
1866 @section Rule Example
1868 Here is an example of a rule:
1870 @example
1871 foo.o : foo.c defs.h       # module for twiddling the frobs
1872         cc -c -g foo.c
1873 @end example
1875 Its target is @file{foo.o} and its prerequisites are @file{foo.c} and
1876 @file{defs.h}.  It has one command, which is @samp{cc -c -g foo.c}.
1877 The command line starts with a tab to identify it as a command.
1879 This rule says two things:
1881 @itemize @bullet
1882 @item
1883 How to decide whether @file{foo.o} is out of date: it is out of date
1884 if it does not exist, or if either @file{foo.c} or @file{defs.h} is
1885 more recent than it.
1887 @item
1888 How to update the file @file{foo.o}: by running @code{cc} as stated.
1889 The command does not explicitly mention @file{defs.h}, but we presume
1890 that @file{foo.c} includes it, and that that is why @file{defs.h} was
1891 added to the prerequisites.
1892 @end itemize
1893 @end ifnottex
1895 @node Rule Syntax, Prerequisite Types, Rule Example, Rules
1896 @section Rule Syntax
1898 @cindex rule syntax
1899 @cindex syntax of rules
1900 In general, a rule looks like this:
1902 @example
1903 @var{targets} : @var{prerequisites}
1904         @var{command}
1905         @dots{}
1906 @end example
1908 @noindent
1909 or like this:
1911 @example
1912 @var{targets} : @var{prerequisites} ; @var{command}
1913         @var{command}
1914         @dots{}
1915 @end example
1917 @cindex targets
1918 @cindex rule targets
1919 The @var{targets} are file names, separated by spaces.  Wildcard
1920 characters may be used (@pxref{Wildcards, ,Using Wildcard Characters
1921 in File Names}) and a name of the form @file{@var{a}(@var{m})}
1922 represents member @var{m} in archive file @var{a}
1923 (@pxref{Archive Members, ,Archive Members as Targets}).
1924 Usually there is only one
1925 target per rule, but occasionally there is a reason to have more
1926 (@pxref{Multiple Targets, , Multiple Targets in a Rule}).@refill
1928 @cindex commands
1929 @cindex tab character (in commands)
1930 The @var{command} lines start with a tab character.  The first command may
1931 appear on the line after the prerequisites, with a tab character, or may
1932 appear on the same line, with a semicolon.  Either way, the effect is the
1933 same.  There are other differences in the syntax of command lines.
1934 @xref{Commands, ,Writing the Commands in Rules}.
1936 @cindex dollar sign (@code{$}), in rules
1937 @cindex @code{$}, in rules
1938 @cindex rules, and @code{$}
1939 Because dollar signs are used to start @code{make} variable
1940 references, if you really want a dollar sign in a target or
1941 prerequisite you must write two of them, @samp{$$} (@pxref{Using
1942 Variables, ,How to Use Variables}).  If you have enabled secondary
1943 expansion (@pxref{Secondary Expansion}) and you want a literal dollar
1944 sign in the prerequisites list, you must actually write @emph{four}
1945 dollar signs (@samp{$$$$}).
1947 You may split a long line by inserting a backslash followed by a
1948 newline, but this is not required, as @code{make} places no limit on
1949 the length of a line in a makefile.
1951 A rule tells @code{make} two things: when the targets are out of date,
1952 and how to update them when necessary.
1954 @cindex prerequisites
1955 @cindex rule prerequisites
1956 The criterion for being out of date is specified in terms of the
1957 @var{prerequisites}, which consist of file names separated by spaces.
1958 (Wildcards and archive members (@pxref{Archives}) are allowed here too.)
1959 A target is out of date if it does not exist or if it is older than any
1960 of the prerequisites (by comparison of last-modification times).  The
1961 idea is that the contents of the target file are computed based on
1962 information in the prerequisites, so if any of the prerequisites changes,
1963 the contents of the existing target file are no longer necessarily
1964 valid.
1966 How to update is specified by @var{commands}.  These are lines to be
1967 executed by the shell (normally @samp{sh}), but with some extra features
1968 (@pxref{Commands, ,Writing the Commands in Rules}).
1970 @node Prerequisite Types, Wildcards, Rule Syntax, Rules
1971 @comment  node-name,  next,  previous,  up
1972 @section Types of Prerequisites
1973 @cindex prerequisite types
1974 @cindex types of prerequisites
1976 @cindex prerequisites, normal
1977 @cindex normal prerequisites
1978 @cindex prerequisites, order-only
1979 @cindex order-only prerequisites
1980 There are actually two different types of prerequisites understood by
1981 GNU @code{make}: normal prerequisites such as described in the
1982 previous section, and @dfn{order-only} prerequisites.  A normal
1983 prerequisite makes two statements: first, it imposes an order of
1984 execution of build commands: any commands necessary to build any of a
1985 target's prerequisites will be fully executed before any commands
1986 necessary to build the target.  Second, it imposes a dependency
1987 relationship: if any prerequisite is newer than the target, then the
1988 target is considered out-of-date and must be rebuilt.
1990 Normally, this is exactly what you want: if a target's prerequisite is
1991 updated, then the target should also be updated.
1993 Occasionally, however, you have a situation where you want to impose a
1994 specific ordering on the rules to be invoked @emph{without} forcing
1995 the target to be updated if one of those rules is executed.  In that
1996 case, you want to define @dfn{order-only} prerequisites.  Order-only
1997 prerequisites can be specified by placing a pipe symbol (@code{|})
1998 in the prerequisites list: any prerequisites to the left of the pipe
1999 symbol are normal; any prerequisites to the right are order-only:
2001 @example
2002 @var{targets} : @var{normal-prerequisites} | @var{order-only-prerequisites}
2003 @end example
2005 The normal prerequisites section may of course be empty.  Also, you
2006 may still declare multiple lines of prerequisites for the same target:
2007 they are appended appropriately (normal prerequisites are appended to
2008 the list of normal prerequisites; order-only prerequisites are
2009 appended to the list of order-only prerequisites).  Note that if you
2010 declare the same file to be both a normal and an order-only
2011 prerequisite, the normal prerequisite takes precedence (since they
2012 have a strict superset of the behavior of an order-only prerequisite).
2014 Consider an example where your targets are to be placed in a separate
2015 directory, and that directory might not exist before @code{make} is
2016 run.  In this situation, you want the directory to be created before
2017 any targets are placed into it but, because the timestamps on
2018 directories change whenever a file is added, removed, or renamed, we
2019 certainly don't want to rebuild all the targets whenever the
2020 directory's timestamp changes.  One way to manage this is with
2021 order-only prerequisites: make the directory an order-only
2022 prerequisite on all the targets:
2024 @example
2025 OBJDIR := objdir
2026 OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
2028 $(OBJDIR)/%.o : %.c
2029         $(COMPILE.c) $(OUTPUT_OPTION) $<
2031 all: $(OBJS)
2033 $(OBJS): | $(OBJDIR)
2035 $(OBJDIR):
2036         mkdir $(OBJDIR)
2037 @end example
2039 Now the rule to create the @file{objdir} directory will be run, if
2040 needed, before any @samp{.o} is built, but no @samp{.o} will be built
2041 because the @file{objdir} directory timestamp changed.
2043 @node Wildcards, Directory Search, Prerequisite Types, Rules
2044 @section Using Wildcard Characters in File Names
2045 @cindex wildcard
2046 @cindex file name with wildcards
2047 @cindex globbing (wildcards)
2049 @cindex @code{*} (wildcard character)
2050 @cindex @code{?} (wildcard character)
2051 @cindex @code{[@dots{}]} (wildcard characters)
2052 A single file name can specify many files using @dfn{wildcard characters}.
2053 The wildcard characters in @code{make} are @samp{*}, @samp{?} and
2054 @samp{[@dots{}]}, the same as in the Bourne shell.  For example, @file{*.c}
2055 specifies a list of all the files (in the working directory) whose names
2056 end in @samp{.c}.@refill
2058 @cindex @code{~} (tilde)
2059 @cindex tilde (@code{~})
2060 @cindex home directory
2061 The character @samp{~} at the beginning of a file name also has special
2062 significance.  If alone, or followed by a slash, it represents your home
2063 directory.  For example @file{~/bin} expands to @file{/home/you/bin}.
2064 If the @samp{~} is followed by a word, the string represents the home
2065 directory of the user named by that word.  For example @file{~john/bin}
2066 expands to @file{/home/john/bin}.  On systems which don't have a home
2067 directory for each user (such as MS-DOS or MS-Windows), this
2068 functionality can be simulated by setting the environment variable
2069 @var{HOME}.@refill
2071 Wildcard expansion is performed by @code{make} automatically in
2072 targets and in prerequisites.  In commands the shell is responsible
2073 for wildcard expansion.  In other contexts, wildcard expansion happens
2074 only if you request it explicitly with the @code{wildcard} function.
2076 The special significance of a wildcard character can be turned off by
2077 preceding it with a backslash.  Thus, @file{foo\*bar} would refer to a
2078 specific file whose name consists of @samp{foo}, an asterisk, and
2079 @samp{bar}.@refill
2081 @menu
2082 * Wildcard Examples::           Several examples
2083 * Wildcard Pitfall::            Problems to avoid.
2084 * Wildcard Function::           How to cause wildcard expansion where
2085                                   it does not normally take place.
2086 @end menu
2088 @node Wildcard Examples, Wildcard Pitfall, Wildcards, Wildcards
2089 @subsection Wildcard Examples
2091 Wildcards can be used in the commands of a rule, where they are expanded
2092 by the shell.  For example, here is a rule to delete all the object files:
2094 @example
2095 @group
2096 clean:
2097         rm -f *.o
2098 @end group
2099 @end example
2100 @cindex @code{rm} (shell command)
2102 Wildcards are also useful in the prerequisites of a rule.  With the
2103 following rule in the makefile, @samp{make print} will print all the
2104 @samp{.c} files that have changed since the last time you printed them:
2106 @example
2107 print: *.c
2108         lpr -p $?
2109         touch print
2110 @end example
2112 @cindex @code{print} target
2113 @cindex @code{lpr} (shell command)
2114 @cindex @code{touch} (shell command)
2115 @noindent
2116 This rule uses @file{print} as an empty target file; see @ref{Empty
2117 Targets, ,Empty Target Files to Record Events}.  (The automatic variable
2118 @samp{$?} is used to print only those files that have changed; see
2119 @ref{Automatic Variables}.)@refill
2121 Wildcard expansion does not happen when you define a variable.  Thus, if
2122 you write this:
2124 @example
2125 objects = *.o
2126 @end example
2128 @noindent
2129 then the value of the variable @code{objects} is the actual string
2130 @samp{*.o}.  However, if you use the value of @code{objects} in a target,
2131 prerequisite or command, wildcard expansion will take place at that time.
2132 To set @code{objects} to the expansion, instead use:
2134 @example
2135 objects := $(wildcard *.o)
2136 @end example
2138 @noindent
2139 @xref{Wildcard Function}.
2141 @node Wildcard Pitfall, Wildcard Function, Wildcard Examples, Wildcards
2142 @subsection Pitfalls of Using Wildcards
2143 @cindex wildcard pitfalls
2144 @cindex pitfalls of wildcards
2145 @cindex mistakes with wildcards
2146 @cindex errors with wildcards
2147 @cindex problems with wildcards
2149 Now here is an example of a naive way of using wildcard expansion, that
2150 does not do what you would intend.  Suppose you would like to say that the
2151 executable file @file{foo} is made from all the object files in the
2152 directory, and you write this:
2154 @example
2155 objects = *.o
2157 foo : $(objects)
2158         cc -o foo $(CFLAGS) $(objects)
2159 @end example
2161 @noindent
2162 The value of @code{objects} is the actual string @samp{*.o}.  Wildcard
2163 expansion happens in the rule for @file{foo}, so that each @emph{existing}
2164 @samp{.o} file becomes a prerequisite of @file{foo} and will be recompiled if
2165 necessary.
2167 But what if you delete all the @samp{.o} files?  When a wildcard matches
2168 no files, it is left as it is, so then @file{foo} will depend on the
2169 oddly-named file @file{*.o}.  Since no such file is likely to exist,
2170 @code{make} will give you an error saying it cannot figure out how to
2171 make @file{*.o}.  This is not what you want!
2173 Actually it is possible to obtain the desired result with wildcard
2174 expansion, but you need more sophisticated techniques, including the
2175 @code{wildcard} function and string substitution.
2176 @ifnottex
2177 @xref{Wildcard Function, ,The Function @code{wildcard}}.
2178 @end ifnottex
2179 @iftex
2180 These are described in the following section.
2181 @end iftex
2183 @cindex wildcards and MS-DOS/MS-Windows backslashes
2184 @cindex backslashes in pathnames and wildcard expansion
2186 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes to
2187 separate directories in pathnames, like so:
2189 @example
2190   c:\foo\bar\baz.c
2191 @end example
2193 This is equivalent to the Unix-style @file{c:/foo/bar/baz.c} (the
2194 @file{c:} part is the so-called drive letter).  When @code{make} runs on
2195 these systems, it supports backslashes as well as the Unix-style forward
2196 slashes in pathnames.  However, this support does @emph{not} include the
2197 wildcard expansion, where backslash is a quote character.  Therefore,
2198 you @emph{must} use Unix-style slashes in these cases.
2201 @node Wildcard Function,  , Wildcard Pitfall, Wildcards
2202 @subsection The Function @code{wildcard}
2203 @findex wildcard
2205 Wildcard expansion happens automatically in rules.  But wildcard expansion
2206 does not normally take place when a variable is set, or inside the
2207 arguments of a function.  If you want to do wildcard expansion in such
2208 places, you need to use the @code{wildcard} function, like this:
2210 @example
2211 $(wildcard @var{pattern}@dots{})
2212 @end example
2214 @noindent
2215 This string, used anywhere in a makefile, is replaced by a
2216 space-separated list of names of existing files that match one of the
2217 given file name patterns.  If no existing file name matches a pattern,
2218 then that pattern is omitted from the output of the @code{wildcard}
2219 function.  Note that this is different from how unmatched wildcards
2220 behave in rules, where they are used verbatim rather than ignored
2221 (@pxref{Wildcard Pitfall}).
2223 One use of the @code{wildcard} function is to get a list of all the C source
2224 files in a directory, like this:
2226 @example
2227 $(wildcard *.c)
2228 @end example
2230 We can change the list of C source files into a list of object files by
2231 replacing the @samp{.c} suffix with @samp{.o} in the result, like this:
2233 @example
2234 $(patsubst %.c,%.o,$(wildcard *.c))
2235 @end example
2237 @noindent
2238 (Here we have used another function, @code{patsubst}.
2239 @xref{Text Functions, ,Functions for String Substitution and Analysis}.)@refill
2241 Thus, a makefile to compile all C source files in the directory and then
2242 link them together could be written as follows:
2244 @example
2245 objects := $(patsubst %.c,%.o,$(wildcard *.c))
2247 foo : $(objects)
2248         cc -o foo $(objects)
2249 @end example
2251 @noindent
2252 (This takes advantage of the implicit rule for compiling C programs, so
2253 there is no need to write explicit rules for compiling the files.
2254 @xref{Flavors, ,The Two Flavors of Variables}, for an explanation of
2255 @samp{:=}, which is a variant of @samp{=}.)
2257 @node Directory Search, Phony Targets, Wildcards, Rules
2258 @section Searching Directories for Prerequisites
2259 @vindex VPATH
2260 @findex vpath
2261 @cindex vpath
2262 @cindex search path for prerequisites (@code{VPATH})
2263 @cindex directory search (@code{VPATH})
2265 For large systems, it is often desirable to put sources in a separate
2266 directory from the binaries.  The @dfn{directory search} features of
2267 @code{make} facilitate this by searching several directories
2268 automatically to find a prerequisite.  When you redistribute the files
2269 among directories, you do not need to change the individual rules,
2270 just the search paths.
2272 @menu
2273 * General Search::              Specifying a search path that applies
2274                                   to every prerequisite.
2275 * Selective Search::            Specifying a search path
2276                                   for a specified class of names.
2277 * Search Algorithm::            When and how search paths are applied.
2278 * Commands/Search::             How to write shell commands that work together
2279                                   with search paths.
2280 * Implicit/Search::             How search paths affect implicit rules.
2281 * Libraries/Search::            Directory search for link libraries.
2282 @end menu
2284 @node General Search, Selective Search, Directory Search, Directory Search
2285 @subsection @code{VPATH}: Search Path for All Prerequisites
2286 @vindex VPATH
2288 The value of the @code{make} variable @code{VPATH} specifies a list of
2289 directories that @code{make} should search.  Most often, the
2290 directories are expected to contain prerequisite files that are not in the
2291 current directory; however, @code{make} uses @code{VPATH} as a search
2292 list for both prerequisites and targets of rules.
2294 Thus, if a file that is listed as a target or prerequisite does not exist
2295 in the current directory, @code{make} searches the directories listed in
2296 @code{VPATH} for a file with that name.  If a file is found in one of
2297 them, that file may become the prerequisite (see below).  Rules may then
2298 specify the names of files in the prerequisite list as if they all
2299 existed in the current directory.  @xref{Commands/Search, ,Writing Shell
2300 Commands with Directory Search}.
2302 In the @code{VPATH} variable, directory names are separated by colons or
2303 blanks.  The order in which directories are listed is the order followed
2304 by @code{make} in its search.  (On MS-DOS and MS-Windows, semi-colons
2305 are used as separators of directory names in @code{VPATH}, since the
2306 colon can be used in the pathname itself, after the drive letter.)
2308 For example,
2310 @example
2311 VPATH = src:../headers
2312 @end example
2314 @noindent
2315 specifies a path containing two directories, @file{src} and
2316 @file{../headers}, which @code{make} searches in that order.
2318 With this value of @code{VPATH}, the following rule,
2320 @example
2321 foo.o : foo.c
2322 @end example
2324 @noindent
2325 is interpreted as if it were written like this:
2327 @example
2328 foo.o : src/foo.c
2329 @end example
2331 @noindent
2332 assuming the file @file{foo.c} does not exist in the current directory but
2333 is found in the directory @file{src}.
2335 @node Selective Search, Search Algorithm, General Search, Directory Search
2336 @subsection The @code{vpath} Directive
2337 @findex vpath
2339 Similar to the @code{VPATH} variable, but more selective, is the
2340 @code{vpath} directive (note lower case), which allows you to specify a
2341 search path for a particular class of file names: those that match a
2342 particular pattern.  Thus you can supply certain search directories for
2343 one class of file names and other directories (or none) for other file
2344 names.
2346 There are three forms of the @code{vpath} directive:
2348 @table @code
2349 @item vpath @var{pattern} @var{directories}
2350 Specify the search path @var{directories} for file names that match
2351 @var{pattern}.
2353 The search path, @var{directories}, is a list of directories to be
2354 searched, separated by colons (semi-colons on MS-DOS and MS-Windows) or
2355 blanks, just like the search path used in the @code{VPATH} variable.
2357 @item vpath @var{pattern}
2358 Clear out the search path associated with @var{pattern}.
2360 @c Extra blank line makes sure this gets two lines.
2361 @item vpath
2363 Clear all search paths previously specified with @code{vpath} directives.
2364 @end table
2366 A @code{vpath} pattern is a string containing a @samp{%} character.  The
2367 string must match the file name of a prerequisite that is being searched
2368 for, the @samp{%} character matching any sequence of zero or more
2369 characters (as in pattern rules; @pxref{Pattern Rules, ,Defining and
2370 Redefining Pattern Rules}).  For example, @code{%.h} matches files that
2371 end in @code{.h}.  (If there is no @samp{%}, the pattern must match the
2372 prerequisite exactly, which is not useful very often.)
2374 @cindex @code{%}, quoting in @code{vpath}
2375 @cindex @code{%}, quoting with @code{\} (backslash)
2376 @cindex @code{\} (backslash), to quote @code{%}
2377 @cindex backslash (@code{\}), to quote @code{%}
2378 @cindex quoting @code{%}, in @code{vpath}
2379 @samp{%} characters in a @code{vpath} directive's pattern can be quoted
2380 with preceding backslashes (@samp{\}).  Backslashes that would otherwise
2381 quote @samp{%} characters can be quoted with more backslashes.
2382 Backslashes that quote @samp{%} characters or other backslashes are
2383 removed from the pattern before it is compared to file names.  Backslashes
2384 that are not in danger of quoting @samp{%} characters go unmolested.@refill
2386 When a prerequisite fails to exist in the current directory, if the
2387 @var{pattern} in a @code{vpath} directive matches the name of the
2388 prerequisite file, then the @var{directories} in that directive are searched
2389 just like (and before) the directories in the @code{VPATH} variable.
2391 For example,
2393 @example
2394 vpath %.h ../headers
2395 @end example
2397 @noindent
2398 tells @code{make} to look for any prerequisite whose name ends in @file{.h}
2399 in the directory @file{../headers} if the file is not found in the current
2400 directory.
2402 If several @code{vpath} patterns match the prerequisite file's name, then
2403 @code{make} processes each matching @code{vpath} directive one by one,
2404 searching all the directories mentioned in each directive.  @code{make}
2405 handles multiple @code{vpath} directives in the order in which they
2406 appear in the makefile; multiple directives with the same pattern are
2407 independent of each other.
2409 @need 750
2410 Thus,
2412 @example
2413 @group
2414 vpath %.c foo
2415 vpath %   blish
2416 vpath %.c bar
2417 @end group
2418 @end example
2420 @noindent
2421 will look for a file ending in @samp{.c} in @file{foo}, then
2422 @file{blish}, then @file{bar}, while
2424 @example
2425 @group
2426 vpath %.c foo:bar
2427 vpath %   blish
2428 @end group
2429 @end example
2431 @noindent
2432 will look for a file ending in @samp{.c} in @file{foo}, then
2433 @file{bar}, then @file{blish}.
2435 @node Search Algorithm, Commands/Search, Selective Search, Directory Search
2436 @subsection How Directory Searches are Performed
2437 @cindex algorithm for directory search
2438 @cindex directory search algorithm
2440 When a prerequisite is found through directory search, regardless of type
2441 (general or selective), the pathname located may not be the one that
2442 @code{make} actually provides you in the prerequisite list.  Sometimes
2443 the path discovered through directory search is thrown away.
2445 The algorithm @code{make} uses to decide whether to keep or abandon a
2446 path found via directory search is as follows:
2448 @enumerate
2449 @item
2450 If a target file does not exist at the path specified in the makefile,
2451 directory search is performed.
2453 @item
2454 If the directory search is successful, that path is kept and this file
2455 is tentatively stored as the target.
2457 @item
2458 All prerequisites of this target are examined using this same method.
2460 @item
2461 After processing the prerequisites, the target may or may not need to be
2462 rebuilt:
2464 @enumerate a
2465 @item
2466 If the target does @emph{not} need to be rebuilt, the path to the file
2467 found during directory search is used for any prerequisite lists which
2468 contain this target.  In short, if @code{make} doesn't need to rebuild
2469 the target then you use the path found via directory search.
2471 @item
2472 If the target @emph{does} need to be rebuilt (is out-of-date), the
2473 pathname found during directory search is @emph{thrown away}, and the
2474 target is rebuilt using the file name specified in the makefile.  In
2475 short, if @code{make} must rebuild, then the target is rebuilt locally,
2476 not in the directory found via directory search.
2477 @end enumerate
2478 @end enumerate
2480 This algorithm may seem complex, but in practice it is quite often
2481 exactly what you want.
2483 @cindex traditional directory search (GPATH)
2484 @cindex directory search, traditional (GPATH)
2485 Other versions of @code{make} use a simpler algorithm: if the file does
2486 not exist, and it is found via directory search, then that pathname is
2487 always used whether or not the target needs to be built.  Thus, if the
2488 target is rebuilt it is created at the pathname discovered during
2489 directory search.
2491 @vindex GPATH
2492 If, in fact, this is the behavior you want for some or all of your
2493 directories, you can use the @code{GPATH} variable to indicate this to
2494 @code{make}.
2496 @code{GPATH} has the same syntax and format as @code{VPATH} (that is, a
2497 space- or colon-delimited list of pathnames).  If an out-of-date target
2498 is found by directory search in a directory that also appears in
2499 @code{GPATH}, then that pathname is not thrown away.  The target is
2500 rebuilt using the expanded path.
2502 @node Commands/Search, Implicit/Search, Search Algorithm, Directory Search
2503 @subsection Writing Shell Commands with Directory Search
2504 @cindex shell command, and directory search
2505 @cindex directory search (@code{VPATH}), and shell commands
2507 When a prerequisite is found in another directory through directory search,
2508 this cannot change the commands of the rule; they will execute as written.
2509 Therefore, you must write the commands with care so that they will look for
2510 the prerequisite in the directory where @code{make} finds it.
2512 This is done with the @dfn{automatic variables} such as @samp{$^}
2513 (@pxref{Automatic Variables}).
2514 For instance, the value of @samp{$^} is a
2515 list of all the prerequisites of the rule, including the names of
2516 the directories in which they were found, and the value of
2517 @samp{$@@} is the target.  Thus:@refill
2519 @example
2520 foo.o : foo.c
2521         cc -c $(CFLAGS) $^ -o $@@
2522 @end example
2524 @noindent
2525 (The variable @code{CFLAGS} exists so you can specify flags for C
2526 compilation by implicit rules; we use it here for consistency so it will
2527 affect all C compilations uniformly;
2528 @pxref{Implicit Variables, ,Variables Used by Implicit Rules}.)
2530 Often the prerequisites include header files as well, which you do not
2531 want to mention in the commands.  The automatic variable @samp{$<} is
2532 just the first prerequisite:
2534 @example
2535 VPATH = src:../headers
2536 foo.o : foo.c defs.h hack.h
2537         cc -c $(CFLAGS) $< -o $@@
2538 @end example
2540 @node Implicit/Search, Libraries/Search, Commands/Search, Directory Search
2541 @subsection Directory Search and Implicit Rules
2542 @cindex @code{VPATH}, and implicit rules
2543 @cindex directory search (@code{VPATH}), and implicit rules
2544 @cindex search path for prerequisites (@code{VPATH}), and implicit rules
2545 @cindex implicit rule, and directory search
2546 @cindex implicit rule, and @code{VPATH}
2547 @cindex rule, implicit, and directory search
2548 @cindex rule, implicit, and @code{VPATH}
2550 The search through the directories specified in @code{VPATH} or with
2551 @code{vpath} also happens during consideration of implicit rules
2552 (@pxref{Implicit Rules, ,Using Implicit Rules}).
2554 For example, when a file @file{foo.o} has no explicit rule, @code{make}
2555 considers implicit rules, such as the built-in rule to compile
2556 @file{foo.c} if that file exists.  If such a file is lacking in the
2557 current directory, the appropriate directories are searched for it.  If
2558 @file{foo.c} exists (or is mentioned in the makefile) in any of the
2559 directories, the implicit rule for C compilation is applied.
2561 The commands of implicit rules normally use automatic variables as a
2562 matter of necessity; consequently they will use the file names found by
2563 directory search with no extra effort.
2565 @node Libraries/Search,  , Implicit/Search, Directory Search
2566 @subsection Directory Search for Link Libraries
2567 @cindex link libraries, and directory search
2568 @cindex libraries for linking, directory search
2569 @cindex directory search (@code{VPATH}), and link libraries
2570 @cindex @code{VPATH}, and link libraries
2571 @cindex search path for prerequisites (@code{VPATH}), and link libraries
2572 @cindex @code{-l} (library search)
2573 @cindex link libraries, patterns matching
2574 @cindex @code{.LIBPATTERNS}, and link libraries
2575 @vindex .LIBPATTERNS
2577 Directory search applies in a special way to libraries used with the
2578 linker.  This special feature comes into play when you write a prerequisite
2579 whose name is of the form @samp{-l@var{name}}.  (You can tell something
2580 strange is going on here because the prerequisite is normally the name of a
2581 file, and the @emph{file name} of a library generally looks like
2582 @file{lib@var{name}.a}, not like @samp{-l@var{name}}.)@refill
2584 When a prerequisite's name has the form @samp{-l@var{name}}, @code{make}
2585 handles it specially by searching for the file @file{lib@var{name}.so} in
2586 the current directory, in directories specified by matching @code{vpath}
2587 search paths and the @code{VPATH} search path, and then in the
2588 directories @file{/lib}, @file{/usr/lib}, and @file{@var{prefix}/lib}
2589 (normally @file{/usr/local/lib}, but MS-DOS/MS-Windows versions of
2590 @code{make} behave as if @var{prefix} is defined to be the root of the
2591 DJGPP installation tree).
2593 If that file is not found, then the file @file{lib@var{name}.a} is
2594 searched for, in the same directories as above.
2596 For example, if there is a @file{/usr/lib/libcurses.a} library on your
2597 system (and no @file{/usr/lib/libcurses.so} file), then
2599 @example
2600 @group
2601 foo : foo.c -lcurses
2602         cc $^ -o $@@
2603 @end group
2604 @end example
2606 @noindent
2607 would cause the command @samp{cc foo.c /usr/lib/libcurses.a -o foo} to
2608 be executed when @file{foo} is older than @file{foo.c} or than
2609 @file{/usr/lib/libcurses.a}.@refill
2611 Although the default set of files to be searched for is
2612 @file{lib@var{name}.so} and @file{lib@var{name}.a}, this is customizable
2613 via the @code{.LIBPATTERNS} variable.  Each word in the value of this
2614 variable is a pattern string.  When a prerequisite like
2615 @samp{-l@var{name}} is seen, @code{make} will replace the percent in
2616 each pattern in the list with @var{name} and perform the above directory
2617 searches using that library filename.  If no library is found, the next
2618 word in the list will be used.
2620 The default value for @code{.LIBPATTERNS} is @samp{lib%.so lib%.a},
2621 which provides the default behavior described above.
2623 You can turn off link library expansion completely by setting this
2624 variable to an empty value.
2626 @node Phony Targets, Force Targets, Directory Search, Rules
2627 @section Phony Targets
2628 @cindex phony targets
2629 @cindex targets, phony
2630 @cindex targets without a file
2632 A phony target is one that is not really the name of a file.  It is just a
2633 name for some commands to be executed when you make an explicit request.
2634 There are two reasons to use a phony target: to avoid a conflict with
2635 a file of the same name, and to improve performance.
2637 If you write a rule whose commands will not create the target file, the
2638 commands will be executed every time the target comes up for remaking.
2639 Here is an example:
2641 @example
2642 @group
2643 clean:
2644         rm *.o temp
2645 @end group
2646 @end example
2648 @noindent
2649 Because the @code{rm} command does not create a file named @file{clean},
2650 probably no such file will ever exist.  Therefore, the @code{rm} command
2651 will be executed every time you say @samp{make clean}.
2652 @cindex @code{rm} (shell command)
2654 @findex .PHONY
2655 The phony target will cease to work if anything ever does create a file
2656 named @file{clean} in this directory.  Since it has no prerequisites, the
2657 file @file{clean} would inevitably be considered up to date, and its
2658 commands would not be executed.  To avoid this problem, you can explicitly
2659 declare the target to be phony, using the special target @code{.PHONY}
2660 (@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
2662 @example
2663 .PHONY : clean
2664 @end example
2666 @noindent
2667 Once this is done, @samp{make clean} will run the commands regardless of
2668 whether there is a file named @file{clean}.
2670 Since it knows that phony targets do not name actual files that could be
2671 remade from other files, @code{make} skips the implicit rule search for
2672 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
2673 phony is good for performance, even if you are not worried about the
2674 actual file existing.
2676 Thus, you first write the line that states that @code{clean} is a
2677 phony target, then you write the rule, like this:
2679 @example
2680 @group
2681 .PHONY: clean
2682 clean:
2683         rm *.o temp
2684 @end group
2685 @end example
2687 Another example of the usefulness of phony targets is in conjunction
2688 with recursive invocations of @code{make} (for more information, see
2689 @ref{Recursion, ,Recursive Use of @code{make}}).  In this case the
2690 makefile will often contain a variable which lists a number of
2691 subdirectories to be built.  One way to handle this is with one rule
2692 whose command is a shell loop over the subdirectories, like this:
2694 @example
2695 @group
2696 SUBDIRS = foo bar baz
2698 subdirs:
2699         for dir in $(SUBDIRS); do \
2700           $(MAKE) -C $$dir; \
2701         done
2702 @end group
2703 @end example
2705 There are a few problems with this method, however.  First, any error
2706 detected in a submake is not noted by this rule, so it will continue to
2707 build the rest of the directories even when one fails.  This can be
2708 overcome by adding shell commands to note the error and exit, but then
2709 it will do so even if @code{make} is invoked with the @code{-k} option,
2710 which is unfortunate.  Second, and perhaps more importantly, you cannot
2711 take advantage of @code{make}'s ability to build targets in parallel
2712 (@pxref{Parallel, ,Parallel Execution}), since there is only one rule.
2714 By declaring the subdirectories as phony targets (you must do this as
2715 the subdirectory obviously always exists; otherwise it won't be built)
2716 you can remove these problems:
2718 @example
2719 @group
2720 SUBDIRS = foo bar baz
2722 .PHONY: subdirs $(SUBDIRS)
2724 subdirs: $(SUBDIRS)
2726 $(SUBDIRS):
2727         $(MAKE) -C $@@
2729 foo: baz
2730 @end group
2731 @end example
2733 Here we've also declared that the @file{foo} subdirectory cannot be
2734 built until after the @file{baz} subdirectory is complete; this kind of
2735 relationship declaration is particularly important when attempting
2736 parallel builds.
2738 A phony target should not be a prerequisite of a real target file; if it
2739 is, its commands are run every time @code{make} goes to update that
2740 file.  As long as a phony target is never a prerequisite of a real
2741 target, the phony target commands will be executed only when the phony
2742 target is a specified goal (@pxref{Goals, ,Arguments to Specify the
2743 Goals}).
2745 Phony targets can have prerequisites.  When one directory contains multiple
2746 programs, it is most convenient to describe all of the programs in one
2747 makefile @file{./Makefile}.  Since the target remade by default will be the
2748 first one in the makefile, it is common to make this a phony target named
2749 @samp{all} and give it, as prerequisites, all the individual programs.  For
2750 example:
2752 @example
2753 all : prog1 prog2 prog3
2754 .PHONY : all
2756 prog1 : prog1.o utils.o
2757         cc -o prog1 prog1.o utils.o
2759 prog2 : prog2.o
2760         cc -o prog2 prog2.o
2762 prog3 : prog3.o sort.o utils.o
2763         cc -o prog3 prog3.o sort.o utils.o
2764 @end example
2766 @noindent
2767 Now you can say just @samp{make} to remake all three programs, or
2768 specify as arguments the ones to remake (as in @samp{make prog1
2769 prog3}).  Phoniness is not inherited: the prerequisites of a phony
2770 target are not themselves phony, unless explicitly declared to be so.
2772 When one phony target is a prerequisite of another, it serves as a subroutine
2773 of the other.  For example, here @samp{make cleanall} will delete the
2774 object files, the difference files, and the file @file{program}:
2776 @example
2777 .PHONY: cleanall cleanobj cleandiff
2779 cleanall : cleanobj cleandiff
2780         rm program
2782 cleanobj :
2783         rm *.o
2785 cleandiff :
2786         rm *.diff
2787 @end example
2789 @node Force Targets, Empty Targets, Phony Targets, Rules
2790 @section Rules without Commands or Prerequisites
2791 @cindex force targets
2792 @cindex targets, force
2793 @cindex @code{FORCE}
2794 @cindex rule, no commands or prerequisites
2796 If a rule has no prerequisites or commands, and the target of the rule
2797 is a nonexistent file, then @code{make} imagines this target to have
2798 been updated whenever its rule is run.  This implies that all targets
2799 depending on this one will always have their commands run.
2801 An example will illustrate this:
2803 @example
2804 @group
2805 clean: FORCE
2806         rm $(objects)
2807 FORCE:
2808 @end group
2809 @end example
2811 Here the target @samp{FORCE} satisfies the special conditions, so the
2812 target @file{clean} that depends on it is forced to run its commands.
2813 There is nothing special about the name @samp{FORCE}, but that is one name
2814 commonly used this way.
2816 As you can see, using @samp{FORCE} this way has the same results as using
2817 @samp{.PHONY: clean}.
2819 Using @samp{.PHONY} is more explicit and more efficient.  However,
2820 other versions of @code{make} do not support @samp{.PHONY}; thus
2821 @samp{FORCE} appears in many makefiles.  @xref{Phony Targets}.
2823 @node Empty Targets, Special Targets, Force Targets, Rules
2824 @section Empty Target Files to Record Events
2825 @cindex empty targets
2826 @cindex targets, empty
2827 @cindex recording events with empty targets
2829 The @dfn{empty target} is a variant of the phony target; it is used to hold
2830 commands for an action that you request explicitly from time to time.
2831 Unlike a phony target, this target file can really exist; but the file's
2832 contents do not matter, and usually are empty.
2834 The purpose of the empty target file is to record, with its
2835 last-modification time, when the rule's commands were last executed.  It
2836 does so because one of the commands is a @code{touch} command to update the
2837 target file.
2839 The empty target file should have some prerequisites (otherwise it
2840 doesn't make sense).  When you ask to remake the empty target, the
2841 commands are executed if any prerequisite is more recent than the target;
2842 in other words, if a prerequisite has changed since the last time you
2843 remade the target.  Here is an example:
2845 @example
2846 print: foo.c bar.c
2847         lpr -p $?
2848         touch print
2849 @end example
2850 @cindex @code{print} target
2851 @cindex @code{lpr} (shell command)
2852 @cindex @code{touch} (shell command)
2854 @noindent
2855 With this rule, @samp{make print} will execute the @code{lpr} command if
2856 either source file has changed since the last @samp{make print}.  The
2857 automatic variable @samp{$?} is used to print only those files that have
2858 changed (@pxref{Automatic Variables}).
2860 @node Special Targets, Multiple Targets, Empty Targets, Rules
2861 @section Special Built-in Target Names
2862 @cindex special targets
2863 @cindex built-in special targets
2864 @cindex targets, built-in special
2866 Certain names have special meanings if they appear as targets.
2868 @table @code
2869 @findex .PHONY
2870 @item .PHONY
2872 The prerequisites of the special target @code{.PHONY} are considered to
2873 be phony targets.  When it is time to consider such a target,
2874 @code{make} will run its commands unconditionally, regardless of
2875 whether a file with that name exists or what its last-modification
2876 time is.  @xref{Phony Targets, ,Phony Targets}.
2878 @findex .SUFFIXES
2879 @item .SUFFIXES
2881 The prerequisites of the special target @code{.SUFFIXES} are the list
2882 of suffixes to be used in checking for suffix rules.
2883 @xref{Suffix Rules, , Old-Fashioned Suffix Rules}.
2885 @findex .DEFAULT
2886 @item .DEFAULT
2888 The commands specified for @code{.DEFAULT} are used for any target for
2889 which no rules are found (either explicit rules or implicit rules).
2890 @xref{Last Resort}.  If @code{.DEFAULT} commands are specified, every
2891 file mentioned as a prerequisite, but not as a target in a rule, will have
2892 these commands executed on its behalf.  @xref{Implicit Rule Search,
2893 ,Implicit Rule Search Algorithm}.
2895 @findex .PRECIOUS
2896 @item .PRECIOUS
2897 @cindex precious targets
2898 @cindex preserving with @code{.PRECIOUS}
2900 The targets which @code{.PRECIOUS} depends on are given the following
2901 special treatment: if @code{make} is killed or interrupted during the
2902 execution of their commands, the target is not deleted.
2903 @xref{Interrupts, ,Interrupting or Killing @code{make}}.  Also, if the
2904 target is an intermediate file, it will not be deleted after it is no
2905 longer needed, as is normally done.  @xref{Chained Rules, ,Chains of
2906 Implicit Rules}.  In this latter respect it overlaps with the
2907 @code{.SECONDARY} special target.
2909 You can also list the target pattern of an implicit rule (such as
2910 @samp{%.o}) as a prerequisite file of the special target @code{.PRECIOUS}
2911 to preserve intermediate files created by rules whose target patterns
2912 match that file's name.
2914 @findex .INTERMEDIATE
2915 @item .INTERMEDIATE
2916 @cindex intermediate targets, explicit
2918 The targets which @code{.INTERMEDIATE} depends on are treated as
2919 intermediate files.  @xref{Chained Rules, ,Chains of Implicit Rules}.
2920 @code{.INTERMEDIATE} with no prerequisites has no effect.
2922 @findex .SECONDARY
2923 @item .SECONDARY
2924 @cindex secondary targets
2925 @cindex preserving with @code{.SECONDARY}
2927 The targets which @code{.SECONDARY} depends on are treated as
2928 intermediate files, except that they are never automatically deleted.
2929 @xref{Chained Rules, ,Chains of Implicit Rules}.
2931 @code{.SECONDARY} with no prerequisites causes all targets to be treated
2932 as secondary (i.e., no target is removed because it is considered
2933 intermediate).
2935 @findex .SECONDEXPANSION
2936 @item .SECONDEXPANSION
2938 If @code{.SECONDEXPANSION} is mentioned as a target anywhere in the
2939 makefile, then all prerequisite lists defined @emph{after} it appears
2940 will be expanded a second time after all makefiles have been read in.
2941 @xref{Secondary Expansion, ,Secondary Expansion}.
2943 @findex .DELETE_ON_ERROR
2944 @item .DELETE_ON_ERROR
2945 @cindex removing targets on failure
2947 If @code{.DELETE_ON_ERROR} is mentioned as a target anywhere in the
2948 makefile, then @code{make} will delete the target of a rule if it has
2949 changed and its commands exit with a nonzero exit status, just as it
2950 does when it receives a signal.  @xref{Errors, ,Errors in Commands}.
2952 @findex .IGNORE
2953 @item .IGNORE
2955 If you specify prerequisites for @code{.IGNORE}, then @code{make} will
2956 ignore errors in execution of the commands run for those particular
2957 files.  The commands for @code{.IGNORE} are not meaningful.
2959 If mentioned as a target with no prerequisites, @code{.IGNORE} says to
2960 ignore errors in execution of commands for all files.  This usage of
2961 @samp{.IGNORE} is supported only for historical compatibility.  Since
2962 this affects every command in the makefile, it is not very useful; we
2963 recommend you use the more selective ways to ignore errors in specific
2964 commands.  @xref{Errors, ,Errors in Commands}.
2966 @findex .LOW_RESOLUTION_TIME
2967 @item .LOW_RESOLUTION_TIME
2969 If you specify prerequisites for @code{.LOW_RESOLUTION_TIME},
2970 @command{make} assumes that these files are created by commands that
2971 generate low resolution time stamps.  The commands for
2972 @code{.LOW_RESOLUTION_TIME} are not meaningful.
2974 The high resolution file time stamps of many modern hosts lessen the
2975 chance of @command{make} incorrectly concluding that a file is up to
2976 date.  Unfortunately, these hosts provide no way to set a high
2977 resolution file time stamp, so commands like @samp{cp -p} that
2978 explicitly set a file's time stamp must discard its subsecond part.  If
2979 a file is created by such a command, you should list it as a
2980 prerequisite of @code{.LOW_RESOLUTION_TIME} so that @command{make} does
2981 not mistakenly conclude that the file is out of date.  For example:
2983 @example
2984 @group
2985 .LOW_RESOLUTION_TIME: dst
2986 dst: src
2987         cp -p src dst
2988 @end group
2989 @end example
2991 Since @samp{cp -p} discards the subsecond part of @file{src}'s time
2992 stamp, @file{dst} is typically slightly older than @file{src} even when
2993 it is up to date.  The @code{.LOW_RESOLUTION_TIME} line causes
2994 @command{make} to consider @file{dst} to be up to date if its time stamp
2995 is at the start of the same second that @file{src}'s time stamp is in.
2997 Due to a limitation of the archive format, archive member time stamps
2998 are always low resolution.  You need not list archive members as
2999 prerequisites of @code{.LOW_RESOLUTION_TIME}, as @command{make} does this
3000 automatically.
3002 @findex .SILENT
3003 @item .SILENT
3005 If you specify prerequisites for @code{.SILENT}, then @code{make} will
3006 not print the commands to remake those particular files before executing
3007 them.  The commands for @code{.SILENT} are not meaningful.
3009 If mentioned as a target with no prerequisites, @code{.SILENT} says not
3010 to print any commands before executing them.  This usage of
3011 @samp{.SILENT} is supported only for historical compatibility.  We
3012 recommend you use the more selective ways to silence specific commands.
3013 @xref{Echoing, ,Command Echoing}.  If you want to silence all commands
3014 for a particular run of @code{make}, use the @samp{-s} or
3015 @w{@samp{--silent}} option (@pxref{Options Summary}).
3017 @findex .EXPORT_ALL_VARIABLES
3018 @item .EXPORT_ALL_VARIABLES
3020 Simply by being mentioned as a target, this tells @code{make} to
3021 export all variables to child processes by default.
3022 @xref{Variables/Recursion, ,Communicating Variables to a
3023 Sub-@code{make}}.
3025 @findex .NOTPARALLEL
3026 @item .NOTPARALLEL
3027 @cindex parallel execution, overriding
3029 If @code{.NOTPARALLEL} is mentioned as a target, then this invocation
3030 of @code{make} will be run serially, even if the @samp{-j} option is
3031 given.  Any recursively invoked @code{make} command will still run
3032 commands in parallel (unless its makefile also contains this target).
3033 Any prerequisites on this target are ignored.
3034 @end table
3036 Any defined implicit rule suffix also counts as a special target if it
3037 appears as a target, and so does the concatenation of two suffixes, such
3038 as @samp{.c.o}.  These targets are suffix rules, an obsolete way of
3039 defining implicit rules (but a way still widely used).  In principle, any
3040 target name could be special in this way if you break it in two and add
3041 both pieces to the suffix list.  In practice, suffixes normally begin with
3042 @samp{.}, so these special target names also begin with @samp{.}.
3043 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
3045 @node Multiple Targets, Multiple Rules, Special Targets, Rules
3046 @section Multiple Targets in a Rule
3047 @cindex multiple targets
3048 @cindex several targets in a rule
3049 @cindex targets, multiple
3050 @cindex rule, with multiple targets
3052 A rule with multiple targets is equivalent to writing many rules, each with
3053 one target, and all identical aside from that.  The same commands apply to
3054 all the targets, but their effects may vary because you can substitute the
3055 actual target name into the command using @samp{$@@}.  The rule contributes
3056 the same prerequisites to all the targets also.
3058 This is useful in two cases.
3060 @itemize @bullet
3061 @item
3062 You want just prerequisites, no commands.  For example:
3064 @example
3065 kbd.o command.o files.o: command.h
3066 @end example
3068 @noindent
3069 gives an additional prerequisite to each of the three object files
3070 mentioned.
3072 @item
3073 Similar commands work for all the targets.  The commands do not need
3074 to be absolutely identical, since the automatic variable @samp{$@@}
3075 can be used to substitute the particular target to be remade into the
3076 commands (@pxref{Automatic Variables}).  For example:
3078 @example
3079 @group
3080 bigoutput littleoutput : text.g
3081         generate text.g -$(subst output,,$@@) > $@@
3082 @end group
3083 @end example
3084 @findex subst
3086 @noindent
3087 is equivalent to
3089 @example
3090 bigoutput : text.g
3091         generate text.g -big > bigoutput
3092 littleoutput : text.g
3093         generate text.g -little > littleoutput
3094 @end example
3096 @noindent
3097 Here we assume the hypothetical program @code{generate} makes two
3098 types of output, one if given @samp{-big} and one if given
3099 @samp{-little}.
3100 @xref{Text Functions, ,Functions for String Substitution and Analysis},
3101 for an explanation of the @code{subst} function.
3102 @end itemize
3104 Suppose you would like to vary the prerequisites according to the target,
3105 much as the variable @samp{$@@} allows you to vary the commands.
3106 You cannot do this with multiple targets in an ordinary rule, but you can
3107 do it with a @dfn{static pattern rule}.
3108 @xref{Static Pattern, ,Static Pattern Rules}.
3110 @node Multiple Rules, Static Pattern, Multiple Targets, Rules
3111 @section Multiple Rules for One Target
3112 @cindex multiple rules for one target
3113 @cindex several rules for one target
3114 @cindex rule, multiple for one target
3115 @cindex target, multiple rules for one
3117 One file can be the target of several rules.  All the prerequisites
3118 mentioned in all the rules are merged into one list of prerequisites for
3119 the target.  If the target is older than any prerequisite from any rule,
3120 the commands are executed.
3122 There can only be one set of commands to be executed for a file.  If
3123 more than one rule gives commands for the same file, @code{make} uses
3124 the last set given and prints an error message.  (As a special case,
3125 if the file's name begins with a dot, no error message is printed.
3126 This odd behavior is only for compatibility with other implementations
3127 of @code{make}@dots{} you should avoid using it).  Occasionally it is
3128 useful to have the same target invoke multiple commands which are
3129 defined in different parts of your makefile; you can use
3130 @dfn{double-colon rules} (@pxref{Double-Colon}) for this.
3132 An extra rule with just prerequisites can be used to give a few extra
3133 prerequisites to many files at once.  For example, makefiles often
3134 have a variable, such as @code{objects}, containing a list of all the
3135 compiler output files in the system being made.  An easy way to say
3136 that all of them must be recompiled if @file{config.h} changes is to
3137 write the following:
3139 @example
3140 objects = foo.o bar.o
3141 foo.o : defs.h
3142 bar.o : defs.h test.h
3143 $(objects) : config.h
3144 @end example
3146 This could be inserted or taken out without changing the rules that really
3147 specify how to make the object files, making it a convenient form to use if
3148 you wish to add the additional prerequisite intermittently.
3150 Another wrinkle is that the additional prerequisites could be specified with
3151 a variable that you set with a command argument to @code{make}
3152 (@pxref{Overriding, ,Overriding Variables}).  For example,
3154 @example
3155 @group
3156 extradeps=
3157 $(objects) : $(extradeps)
3158 @end group
3159 @end example
3161 @noindent
3162 means that the command @samp{make extradeps=foo.h} will consider
3163 @file{foo.h} as a prerequisite of each object file, but plain @samp{make}
3164 will not.
3166 If none of the explicit rules for a target has commands, then @code{make}
3167 searches for an applicable implicit rule to find some commands
3168 @pxref{Implicit Rules, ,Using Implicit Rules}).
3170 @node Static Pattern, Double-Colon, Multiple Rules, Rules
3171 @section Static Pattern Rules
3172 @cindex static pattern rule
3173 @cindex rule, static pattern
3174 @cindex pattern rules, static (not implicit)
3175 @cindex varying prerequisites
3176 @cindex prerequisites, varying (static pattern)
3178 @dfn{Static pattern rules} are rules which specify multiple targets and
3179 construct the prerequisite names for each target based on the target name.
3180 They are more general than ordinary rules with multiple targets because the
3181 targets do not have to have identical prerequisites.  Their prerequisites must
3182 be @emph{analogous}, but not necessarily @emph{identical}.
3184 @menu
3185 * Static Usage::                The syntax of static pattern rules.
3186 * Static versus Implicit::      When are they better than implicit rules?
3187 @end menu
3189 @node Static Usage, Static versus Implicit, Static Pattern, Static Pattern
3190 @subsection Syntax of Static Pattern Rules
3191 @cindex static pattern rule, syntax of
3192 @cindex pattern rules, static, syntax of
3194 Here is the syntax of a static pattern rule:
3196 @example
3197 @var{targets} @dots{}: @var{target-pattern}: @var{prereq-patterns} @dots{}
3198         @var{commands}
3199         @dots{}
3200 @end example
3202 @noindent
3203 The @var{targets} list specifies the targets that the rule applies to.
3204 The targets can contain wildcard characters, just like the targets of
3205 ordinary rules (@pxref{Wildcards, ,Using Wildcard Characters in File
3206 Names}).
3208 @cindex target pattern, static (not implicit)
3209 @cindex stem
3210 The @var{target-pattern} and @var{prereq-patterns} say how to compute the
3211 prerequisites of each target.  Each target is matched against the
3212 @var{target-pattern} to extract a part of the target name, called the
3213 @dfn{stem}.  This stem is substituted into each of the @var{prereq-patterns}
3214 to make the prerequisite names (one from each @var{prereq-pattern}).
3216 Each pattern normally contains the character @samp{%} just once.  When the
3217 @var{target-pattern} matches a target, the @samp{%} can match any part of
3218 the target name; this part is called the @dfn{stem}.  The rest of the
3219 pattern must match exactly.  For example, the target @file{foo.o} matches
3220 the pattern @samp{%.o}, with @samp{foo} as the stem.  The targets
3221 @file{foo.c} and @file{foo.out} do not match that pattern.@refill
3223 @cindex prerequisite pattern, static (not implicit)
3224 The prerequisite names for each target are made by substituting the stem
3225 for the @samp{%} in each prerequisite pattern.  For example, if one
3226 prerequisite pattern is @file{%.c}, then substitution of the stem
3227 @samp{foo} gives the prerequisite name @file{foo.c}.  It is legitimate
3228 to write a prerequisite pattern that does not contain @samp{%}; then this
3229 prerequisite is the same for all targets.
3231 @cindex @code{%}, quoting in static pattern
3232 @cindex @code{%}, quoting with @code{\} (backslash)
3233 @cindex @code{\} (backslash), to quote @code{%}
3234 @cindex backslash (@code{\}), to quote @code{%}
3235 @cindex quoting @code{%}, in static pattern
3236 @samp{%} characters in pattern rules can be quoted with preceding
3237 backslashes (@samp{\}).  Backslashes that would otherwise quote @samp{%}
3238 characters can be quoted with more backslashes.  Backslashes that quote
3239 @samp{%} characters or other backslashes are removed from the pattern
3240 before it is compared to file names or has a stem substituted into it.
3241 Backslashes that are not in danger of quoting @samp{%} characters go
3242 unmolested.  For example, the pattern @file{the\%weird\\%pattern\\} has
3243 @samp{the%weird\} preceding the operative @samp{%} character, and
3244 @samp{pattern\\} following it.  The final two backslashes are left alone
3245 because they cannot affect any @samp{%} character.@refill
3247 Here is an example, which compiles each of @file{foo.o} and @file{bar.o}
3248 from the corresponding @file{.c} file:
3250 @example
3251 @group
3252 objects = foo.o bar.o
3254 all: $(objects)
3256 $(objects): %.o: %.c
3257         $(CC) -c $(CFLAGS) $< -o $@@
3258 @end group
3259 @end example
3261 @noindent
3262 Here @samp{$<} is the automatic variable that holds the name of the
3263 prerequisite and @samp{$@@} is the automatic variable that holds the name
3264 of the target; see @ref{Automatic Variables}.
3266 Each target specified must match the target pattern; a warning is issued
3267 for each target that does not.  If you have a list of files, only some of
3268 which will match the pattern, you can use the @code{filter} function to
3269 remove nonmatching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
3271 @example
3272 files = foo.elc bar.o lose.o
3274 $(filter %.o,$(files)): %.o: %.c
3275         $(CC) -c $(CFLAGS) $< -o $@@
3276 $(filter %.elc,$(files)): %.elc: %.el
3277         emacs -f batch-byte-compile $<
3278 @end example
3280 @noindent
3281 In this example the result of @samp{$(filter %.o,$(files))} is
3282 @file{bar.o lose.o}, and the first static pattern rule causes each of
3283 these object files to be updated by compiling the corresponding C source
3284 file.  The result of @w{@samp{$(filter %.elc,$(files))}} is
3285 @file{foo.elc}, so that file is made from @file{foo.el}.@refill
3287 Another example shows how to use @code{$*} in static pattern rules:
3288 @vindex $*@r{, and static pattern}
3290 @example
3291 @group
3292 bigoutput littleoutput : %output : text.g
3293         generate text.g -$* > $@@
3294 @end group
3295 @end example
3297 @noindent
3298 When the @code{generate} command is run, @code{$*} will expand to the
3299 stem, either @samp{big} or @samp{little}.
3301 @node Static versus Implicit,  , Static Usage, Static Pattern
3302 @subsection Static Pattern Rules versus Implicit Rules
3303 @cindex rule, static pattern versus implicit
3304 @cindex static pattern rule, versus implicit
3306 A static pattern rule has much in common with an implicit rule defined as a
3307 pattern rule (@pxref{Pattern Rules, ,Defining and Redefining Pattern Rules}).
3308 Both have a pattern for the target and patterns for constructing the
3309 names of prerequisites.  The difference is in how @code{make} decides
3310 @emph{when} the rule applies.
3312 An implicit rule @emph{can} apply to any target that matches its pattern,
3313 but it @emph{does} apply only when the target has no commands otherwise
3314 specified, and only when the prerequisites can be found.  If more than one
3315 implicit rule appears applicable, only one applies; the choice depends on
3316 the order of rules.
3318 By contrast, a static pattern rule applies to the precise list of targets
3319 that you specify in the rule.  It cannot apply to any other target and it
3320 invariably does apply to each of the targets specified.  If two conflicting
3321 rules apply, and both have commands, that's an error.
3323 The static pattern rule can be better than an implicit rule for these
3324 reasons:
3326 @itemize @bullet
3327 @item
3328 You may wish to override the usual implicit rule for a few
3329 files whose names cannot be categorized syntactically but
3330 can be given in an explicit list.
3332 @item
3333 If you cannot be sure of the precise contents of the directories
3334 you are using, you may not be sure which other irrelevant files
3335 might lead @code{make} to use the wrong implicit rule.  The choice
3336 might depend on the order in which the implicit rule search is done.
3337 With static pattern rules, there is no uncertainty: each rule applies
3338 to precisely the targets specified.
3339 @end itemize
3341 @node Double-Colon, Automatic Prerequisites, Static Pattern, Rules
3342 @section Double-Colon Rules
3343 @cindex double-colon rules
3344 @cindex rule, double-colon (@code{::})
3345 @cindex multiple rules for one target (@code{::})
3346 @cindex @code{::} rules (double-colon)
3348 @dfn{Double-colon} rules are rules written with @samp{::} instead of
3349 @samp{:} after the target names.  They are handled differently from
3350 ordinary rules when the same target appears in more than one rule.
3352 When a target appears in multiple rules, all the rules must be the same
3353 type: all ordinary, or all double-colon.  If they are double-colon, each
3354 of them is independent of the others.  Each double-colon rule's commands
3355 are executed if the target is older than any prerequisites of that rule.
3356 If there are no prerequisites for that rule, its commands are always
3357 executed (even if the target already exists).  This can result in
3358 executing none, any, or all of the double-colon rules.
3360 Double-colon rules with the same target are in fact completely separate
3361 from one another.  Each double-colon rule is processed individually, just
3362 as rules with different targets are processed.
3364 The double-colon rules for a target are executed in the order they appear
3365 in the makefile.  However, the cases where double-colon rules really make
3366 sense are those where the order of executing the commands would not matter.
3368 Double-colon rules are somewhat obscure and not often very useful; they
3369 provide a mechanism for cases in which the method used to update a target
3370 differs depending on which prerequisite files caused the update, and such
3371 cases are rare.
3373 Each double-colon rule should specify commands; if it does not, an
3374 implicit rule will be used if one applies.
3375 @xref{Implicit Rules, ,Using Implicit Rules}.
3377 @node Automatic Prerequisites,  , Double-Colon, Rules
3378 @section Generating Prerequisites Automatically
3379 @cindex prerequisites, automatic generation
3380 @cindex automatic generation of prerequisites
3381 @cindex generating prerequisites automatically
3383 In the makefile for a program, many of the rules you need to write often
3384 say only that some object file depends on some header
3385 file.  For example, if @file{main.c} uses @file{defs.h} via an
3386 @code{#include}, you would write:
3388 @example
3389 main.o: defs.h
3390 @end example
3392 @noindent
3393 You need this rule so that @code{make} knows that it must remake
3394 @file{main.o} whenever @file{defs.h} changes.  You can see that for a
3395 large program you would have to write dozens of such rules in your
3396 makefile.  And, you must always be very careful to update the makefile
3397 every time you add or remove an @code{#include}.
3398 @cindex @code{#include}
3400 @cindex @code{-M} (to compiler)
3401 To avoid this hassle, most modern C compilers can write these rules for
3402 you, by looking at the @code{#include} lines in the source files.
3403 Usually this is done with the @samp{-M} option to the compiler.
3404 For example, the command:
3406 @example
3407 cc -M main.c
3408 @end example
3410 @noindent
3411 generates the output:
3413 @example
3414 main.o : main.c defs.h
3415 @end example
3417 @noindent
3418 Thus you no longer have to write all those rules yourself.
3419 The compiler will do it for you.
3421 Note that such a prerequisite constitutes mentioning @file{main.o} in a
3422 makefile, so it can never be considered an intermediate file by implicit
3423 rule search.  This means that @code{make} won't ever remove the file
3424 after using it; @pxref{Chained Rules, ,Chains of Implicit Rules}.
3426 @cindex @code{make depend}
3427 With old @code{make} programs, it was traditional practice to use this
3428 compiler feature to generate prerequisites on demand with a command like
3429 @samp{make depend}.  That command would create a file @file{depend}
3430 containing all the automatically-generated prerequisites; then the
3431 makefile could use @code{include} to read them in (@pxref{Include}).
3433 In GNU @code{make}, the feature of remaking makefiles makes this
3434 practice obsolete---you need never tell @code{make} explicitly to
3435 regenerate the prerequisites, because it always regenerates any makefile
3436 that is out of date.  @xref{Remaking Makefiles}.
3438 The practice we recommend for automatic prerequisite generation is to have
3439 one makefile corresponding to each source file.  For each source file
3440 @file{@var{name}.c} there is a makefile @file{@var{name}.d} which lists
3441 what files the object file @file{@var{name}.o} depends on.  That way
3442 only the source files that have changed need to be rescanned to produce
3443 the new prerequisites.
3445 Here is the pattern rule to generate a file of prerequisites (i.e., a makefile)
3446 called @file{@var{name}.d} from a C source file called @file{@var{name}.c}:
3448 @smallexample
3449 @group
3450 %.d: %.c
3451         @@set -e; rm -f $@@; \
3452          $(CC) -M $(CPPFLAGS) $< > $@@.$$$$; \
3453          sed 's,\($*\)\.o[ :]*,\1.o $@@ : ,g' < $@@.$$$$ > $@@; \
3454          rm -f $@@.$$$$
3455 @end group
3456 @end smallexample
3458 @noindent
3459 @xref{Pattern Rules}, for information on defining pattern rules.  The
3460 @samp{-e} flag to the shell causes it to exit immediately if the
3461 @code{$(CC)} command (or any other command) fails (exits with a
3462 nonzero status).
3463 @cindex @code{-e} (shell flag)
3465 @cindex @code{-MM} (to GNU compiler)
3466 With the GNU C compiler, you may wish to use the @samp{-MM} flag instead
3467 of @samp{-M}.  This omits prerequisites on system header files.
3468 @xref{Preprocessor Options, , Options Controlling the Preprocessor,
3469 gcc.info, Using GNU CC}, for details.
3471 @cindex @code{sed} (shell command)
3472 The purpose of the @code{sed} command is to translate (for example):
3474 @example
3475 main.o : main.c defs.h
3476 @end example
3478 @noindent
3479 into:
3481 @example
3482 main.o main.d : main.c defs.h
3483 @end example
3485 @noindent
3486 @cindex @code{.d}
3487 This makes each @samp{.d} file depend on all the source and header files
3488 that the corresponding @samp{.o} file depends on.  @code{make} then
3489 knows it must regenerate the prerequisites whenever any of the source or
3490 header files changes.
3492 Once you've defined the rule to remake the @samp{.d} files,
3493 you then use the @code{include} directive to read them all in.
3494 @xref{Include}.  For example:
3496 @example
3497 @group
3498 sources = foo.c bar.c
3500 include $(sources:.c=.d)
3501 @end group
3502 @end example
3504 @noindent
3505 (This example uses a substitution variable reference to translate the
3506 list of source files @samp{foo.c bar.c} into a list of prerequisite
3507 makefiles, @samp{foo.d bar.d}.  @xref{Substitution Refs}, for full
3508 information on substitution references.)  Since the @samp{.d} files are
3509 makefiles like any others, @code{make} will remake them as necessary
3510 with no further work from you.  @xref{Remaking Makefiles}.
3512 Note that the @samp{.d} files contain target definitions; you should
3513 be sure to place the @code{include} directive @emph{after} the first,
3514 default goal in your makefiles or run the risk of having a random
3515 object file become the default goal.
3516 @xref{How Make Works}.
3518 @node Commands, Using Variables, Rules, Top
3519 @chapter Writing the Commands in Rules
3520 @cindex commands, how to write
3521 @cindex rule commands
3522 @cindex writing rule commands
3524 The commands of a rule consist of one or more shell command lines to
3525 be executed, one at a time, in the order they appear.  Typically, the
3526 result of executing these commands is that the target of the rule is
3527 brought up to date.
3529 Users use many different shell programs, but commands in makefiles are
3530 always interpreted by @file{/bin/sh} unless the makefile specifies
3531 otherwise.  @xref{Execution, ,Command Execution}.
3533 @menu
3534 * Command Syntax::              Command syntax features and pitfalls.
3535 * Echoing::                     How to control when commands are echoed.
3536 * Execution::                   How commands are executed.
3537 * Parallel::                    How commands can be executed in parallel.
3538 * Errors::                      What happens after a command execution error.
3539 * Interrupts::                  What happens when a command is interrupted.
3540 * Recursion::                   Invoking @code{make} from makefiles.
3541 * Sequences::                   Defining canned sequences of commands.
3542 * Empty Commands::              Defining useful, do-nothing commands.
3543 @end menu
3545 @node Command Syntax, Echoing, Commands, Commands
3546 @section Command Syntax
3547 @cindex command syntax
3548 @cindex syntax of commands
3550 Makefiles have the unusual property that there are really two distinct
3551 syntaxes in one file.  Most of the makefile uses @code{make} syntax
3552 (@pxref{Makefiles, ,Writing Makefiles}).  However, commands are meant to be
3553 interpreted by the shell and so they are written using shell syntax.
3554 The @code{make} program does not try to understand shell syntax: it
3555 performs only a very few specific translations on the content of the
3556 command before handing it to the shell.
3558 Each command line must start with a tab, except that the first command
3559 line may be attached to the target-and-prerequisites line with a
3560 semicolon in between.  @emph{Any} line in the makefile that begins
3561 with a tab and appears in a ``rule context'' (that is, after a rule
3562 has been started until another rule or variable definition) will be
3563 considered a command line for that rule.  Blank lines and lines of
3564 just comments may appear among the command lines; they are ignored.
3566 Some consequences of these rules include:
3568 @itemize @bullet
3569 @item
3570 A blank line that begins with a tab is not blank: it's an empty
3571 command (@pxref{Empty Commands}).
3573 @cindex comments, in commands
3574 @cindex commands, comments in
3575 @cindex @code{#} (comments), in commands
3576 @item
3577 A comment in a command line is not a @code{make} comment; it will be
3578 passed to the shell as-is.  Whether the shell treats it as a comment
3579 or not depends on your shell.
3581 @item
3582 A variable definition in a ``rule context'' which is indented by a tab
3583 as the first character on the line, will be considered a command line,
3584 not a @code{make} variable definition, and passed to the shell.
3586 @item
3587 A conditional expression (@code{ifdef}, @code{ifeq},
3588 etc. @pxref{Conditional Syntax, ,Syntax of Conditionals}) in a ``rule
3589 context'' which is indented by a tab as the first character on the
3590 line, will be considered a command line and be passed to the shell.
3592 @end itemize
3594 @menu
3595 * Splitting Lines::             Breaking long command lines for readability.
3596 * Variables in Commands::       Using @code{make} variables in commands.
3597 @end menu
3599 @node Splitting Lines, Variables in Commands, Command Syntax, Command Syntax
3600 @subsection Splitting Command Lines
3601 @cindex commands, splitting
3602 @cindex splitting commands
3603 @cindex commands, backslash (@code{\}) in
3604 @cindex commands, quoting newlines in
3605 @cindex backslash (@code{\}), in commands
3606 @cindex @code{\} (backslash), in commands
3607 @cindex quoting newline, in commands
3608 @cindex newline, quoting, in commands
3610 One of the few ways in which @code{make} does interpret command lines
3611 is checking for a backslash just before the newline.  As in normal
3612 makefile syntax, a single command can be split into multiple lines in
3613 the makefile by placing a backslash before each newline.  A sequence
3614 of lines like this is considered a single command, and one instance of
3615 the shell will be invoked to run it.
3617 However, in contrast to how they are treated in other places in a
3618 makefile, backslash-newline pairs are @emph{not} removed from the
3619 command.  Both the backslash and the newline characters are preserved
3620 and passed to the shell.  How the backslash-newline is interpreted
3621 depends on your shell.  If the first character of the next line
3622 after the backslash-newline is a tab, then that tab (and only that
3623 tab) is removed.  Whitespace is never added to the command.
3625 For example, this makefile:
3627 @example
3628 @group
3629 all :
3630         @@echo no\
3631 space
3632         @@echo no\
3633         space
3634         @@echo one \
3635         space
3636         @@echo one\
3637          space
3638 @end group
3639 @end example
3641 @noindent
3642 consists of four separate shell commands where the output is:
3644 @example
3645 @group
3646 nospace
3647 nospace
3648 one space
3649 one space
3650 @end group
3651 @end example
3653 As a more complex example, this makefile:
3655 @example
3656 @group
3657 all : ; @@echo 'hello \
3658         world' ; echo "hello \
3659     world"
3660 @end group
3661 @end example
3663 @noindent
3664 will run one shell with a command script of:
3666 @example
3667 @group
3668 echo 'hello \
3669 world' ; echo "hello \
3670     world"
3671 @end group
3672 @end example
3674 @noindent
3675 which, according to shell quoting rules, will yield the following output:
3677 @example
3678 @group
3679 hello \
3680 world
3681 hello     world
3682 @end group
3683 @end example
3685 @noindent
3686 Notice how the backslash/newline pair was removed inside the string
3687 quoted with double quotes (@code{"@dots{}"}), but not from the string
3688 quoted with single quotes (@code{'@dots{}'}).  This is the way the
3689 default shell (@file{/bin/sh}) handles backslash/newline pairs.  If
3690 you specify a different shell in your makefiles it may treat them
3691 differently.
3693 Sometimes you want to split a long line inside of single quotes, but
3694 you don't want the backslash-newline to appear in the quoted content.
3695 This is often the case when passing scripts to languages such as Perl,
3696 where extraneous backslashes inside the script can change its meaning
3697 or even be a syntax error.  One simple way of handling this is to
3698 place the quoted string, or even the entire command, into a
3699 @code{make} variable then use the variable in the command.  In this
3700 situation the newline quoting rules for makefiles will be used, and
3701 the backslash-newline will be removed.  If we rewrite our example
3702 above using this method:
3704 @example
3705 @group
3706 HELLO = 'hello \
3707 world'
3709 all : ; @@echo $(HELLO)
3710 @end group
3711 @end example
3713 @noindent
3714 we will get output like this:
3716 @example
3717 @group
3718 hello world
3719 @end group
3720 @end example
3722 If you like, you can also use target-specific variables
3723 (@pxref{Target-specific, ,Target-specific Variable Values}) to obtain
3724 a tighter correspondence between the variable and the command that
3725 uses it.
3727 @node Variables in Commands,  , Splitting Lines, Command Syntax
3728 @subsection Using Variables in Commands
3729 @cindex variable references in commands
3730 @cindex commands, using variables in
3732 The other way in which @code{make} processes commands is by expanding
3733 any variable references in them (@pxref{Reference,Basics of Variable
3734 References}).  This occurs after make has finished reading all the
3735 makefiles and the target is determined to be out of date; so, the
3736 commands for targets which are not rebuilt are never expanded.
3738 Variable and function references in commands have identical syntax and
3739 semantics to references elsewhere in the makefile.  They also have the
3740 same quoting rules: if you want a dollar sign to appear in your
3741 command, you must double it (@samp{$$}).  For shells like the default
3742 shell, that use dollar signs to introduce variables, it's important to
3743 keep clear in your mind whether the variable you want to reference is
3744 a @code{make} variable (use a single dollar sign) or a shell variable
3745 (use two dollar signs).  For example:
3747 @example
3748 @group
3749 LIST = one two three
3750 all:
3751         for i in $(LIST); do \
3752             echo $$i; \
3753         done
3754 @end group
3755 @end example
3757 @noindent
3758 results in the following command being passed to the shell:
3760 @example
3761 @group
3762 for i in one two three; do \
3763     echo $i; \
3764 done
3765 @end group
3766 @end example
3768 @noindent
3769 which generates the expected result:
3771 @example
3772 @group
3775 three
3776 @end group
3777 @end example
3779 @node Echoing, Execution, Command Syntax, Commands
3780 @section Command Echoing
3781 @cindex echoing of commands
3782 @cindex silent operation
3783 @cindex @code{@@} (in commands)
3784 @cindex commands, echoing
3785 @cindex printing of commands
3787 Normally @code{make} prints each command line before it is executed.
3788 We call this @dfn{echoing} because it gives the appearance that you
3789 are typing the commands yourself.
3791 When a line starts with @samp{@@}, the echoing of that line is suppressed.
3792 The @samp{@@} is discarded before the command is passed to the shell.
3793 Typically you would use this for a command whose only effect is to print
3794 something, such as an @code{echo} command to indicate progress through
3795 the makefile:
3797 @example
3798 @@echo About to make distribution files
3799 @end example
3801 @cindex @code{-n}
3802 @cindex @code{--just-print}
3803 @cindex @code{--dry-run}
3804 @cindex @code{--recon}
3805 When @code{make} is given the flag @samp{-n} or @samp{--just-print}
3806 it only echoes commands, it won't execute them.  @xref{Options Summary,
3807 ,Summary of Options}.  In this case and only this case, even the
3808 commands starting with @samp{@@} are printed.  This flag is useful for
3809 finding out which commands @code{make} thinks are necessary without
3810 actually doing them.
3812 @cindex @code{-s}
3813 @cindex @code{--silent}
3814 @cindex @code{--quiet}
3815 @findex .SILENT
3816 The @samp{-s} or @samp{--silent}
3817 flag to @code{make} prevents all echoing, as if all commands
3818 started with @samp{@@}.  A rule in the makefile for the special target
3819 @code{.SILENT} without prerequisites has the same effect
3820 (@pxref{Special Targets, ,Special Built-in Target Names}).
3821 @code{.SILENT} is essentially obsolete since @samp{@@} is more flexible.@refill
3823 @node Execution, Parallel, Echoing, Commands
3824 @section Command Execution
3825 @cindex commands, execution
3826 @cindex execution, of commands
3827 @cindex shell command, execution
3828 @vindex @code{SHELL} @r{(command execution)}
3830 When it is time to execute commands to update a target, they are
3831 executed by invoking a new subshell for each command line.  (In
3832 practice, @code{make} may take shortcuts that do not affect the
3833 results.)
3835 @cindex @code{cd} (shell command)
3836 @cindex shell variables, setting in commands
3837 @cindex commands setting shell variables
3838 @strong{Please note:} this implies that setting shell variables and
3839 invoking shell commands such as @code{cd} that set a context local to
3840 each process will not affect the following command lines.@footnote{On
3841 MS-DOS, the value of current working directory is @strong{global}, so
3842 changing it @emph{will} affect the following command lines on those
3843 systems.}  If you want to use @code{cd} to affect the next statement,
3844 put both statements in a single command line.  Then @code{make} will
3845 invoke one shell to run the entire line, and the shell will execute
3846 the statements in sequence.  For example:
3848 @example
3849 foo : bar/lose
3850         cd $(@@D) && gobble $(@@F) > ../$@@
3851 @end example
3853 @noindent
3854 Here we use the shell AND operator (@code{&&}) so that if the
3855 @code{cd} command fails, the script will fail without trying to invoke
3856 the @code{gobble} command in the wrong directory, which could cause
3857 problems (in this case it would certainly cause @file{../foo} to be
3858 truncated, at least).
3860 @menu
3861 * Choosing the Shell::          How @code{make} chooses the shell used
3862                                   to run commands.
3863 @end menu
3865 @node Choosing the Shell,  , Execution, Execution
3866 @subsection Choosing the Shell
3867 @cindex shell, choosing the
3868 @cindex @code{SHELL}, value of
3870 @vindex SHELL
3871 The program used as the shell is taken from the variable @code{SHELL}.
3872 If this variable is not set in your makefile, the program
3873 @file{/bin/sh} is used as the shell.
3875 @cindex environment, @code{SHELL} in
3876 Unlike most variables, the variable @code{SHELL} is never set from the
3877 environment.  This is because the @code{SHELL} environment variable is
3878 used to specify your personal choice of shell program for interactive
3879 use.  It would be very bad for personal choices like this to affect the
3880 functioning of makefiles.  @xref{Environment, ,Variables from the
3881 Environment}.
3883 Furthermore, when you do set @code{SHELL} in your makefile that value
3884 is @emph{not} exported in the environment to commands that @code{make}
3885 invokes.  Instead, the value inherited from the user's environment, if
3886 any, is exported.  You can override this behavior by explicitly
3887 exporting @code{SHELL} (@pxref{Variables/Recursion, ,Communicating
3888 Variables to a Sub-@code{make}}), forcing it to be passed in the
3889 environment to commands.
3891 @vindex @code{MAKESHELL} @r{(MS-DOS alternative to @code{SHELL})}
3892 However, on MS-DOS and MS-Windows the value of @code{SHELL} in the
3893 environment @strong{is} used, since on those systems most users do not
3894 set this variable, and therefore it is most likely set specifically to
3895 be used by @code{make}.  On MS-DOS, if the setting of @code{SHELL} is
3896 not suitable for @code{make}, you can set the variable
3897 @code{MAKESHELL} to the shell that @code{make} should use; if set it
3898 will be used as the shell instead of the value of @code{SHELL}.
3900 @subsubheading Choosing a Shell in DOS and Windows
3901 @cindex shell, in DOS and Windows
3902 @cindex DOS, choosing a shell in
3903 @cindex Windows, choosing a shell in
3905 Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3906 other systems.
3908 @vindex COMSPEC
3909 On MS-DOS, if @code{SHELL} is not set, the value of the variable
3910 @code{COMSPEC} (which is always set) is used instead.
3912 @cindex @code{SHELL}, MS-DOS specifics
3913 The processing of lines that set the variable @code{SHELL} in Makefiles
3914 is different on MS-DOS.  The stock shell, @file{command.com}, is
3915 ridiculously limited in its functionality and many users of @code{make}
3916 tend to install a replacement shell.  Therefore, on MS-DOS, @code{make}
3917 examines the value of @code{SHELL}, and changes its behavior based on
3918 whether it points to a Unix-style or DOS-style shell.  This allows
3919 reasonable functionality even if @code{SHELL} points to
3920 @file{command.com}.
3922 If @code{SHELL} points to a Unix-style shell, @code{make} on MS-DOS
3923 additionally checks whether that shell can indeed be found; if not, it
3924 ignores the line that sets @code{SHELL}.  In MS-DOS, GNU @code{make}
3925 searches for the shell in the following places:
3927 @enumerate
3928 @item
3929 In the precise place pointed to by the value of @code{SHELL}.  For
3930 example, if the makefile specifies @samp{SHELL = /bin/sh}, @code{make}
3931 will look in the directory @file{/bin} on the current drive.
3933 @item
3934 In the current directory.
3936 @item
3937 In each of the directories in the @code{PATH} variable, in order.
3939 @end enumerate
3941 In every directory it examines, @code{make} will first look for the
3942 specific file (@file{sh} in the example above).  If this is not found,
3943 it will also look in that directory for that file with one of the known
3944 extensions which identify executable files.  For example @file{.exe},
3945 @file{.com}, @file{.bat}, @file{.btm}, @file{.sh}, and some others.
3947 If any of these attempts is successful, the value of @code{SHELL} will
3948 be set to the full pathname of the shell as found.  However, if none of
3949 these is found, the value of @code{SHELL} will not be changed, and thus
3950 the line that sets it will be effectively ignored.  This is so
3951 @code{make} will only support features specific to a Unix-style shell if
3952 such a shell is actually installed on the system where @code{make} runs.
3954 Note that this extended search for the shell is limited to the cases
3955 where @code{SHELL} is set from the Makefile; if it is set in the
3956 environment or command line, you are expected to set it to the full
3957 pathname of the shell, exactly as things are on Unix.
3959 The effect of the above DOS-specific processing is that a Makefile that
3960 contains @samp{SHELL = /bin/sh} (as many Unix makefiles do), will work
3961 on MS-DOS unaltered if you have e.g.@: @file{sh.exe} installed in some
3962 directory along your @code{PATH}.
3964 @node Parallel, Errors, Execution, Commands
3965 @section Parallel Execution
3966 @cindex commands, execution in parallel
3967 @cindex parallel execution
3968 @cindex execution, in parallel
3969 @cindex job slots
3970 @cindex @code{-j}
3971 @cindex @code{--jobs}
3973 GNU @code{make} knows how to execute several commands at once.
3974 Normally, @code{make} will execute only one command at a time, waiting
3975 for it to finish before executing the next.  However, the @samp{-j} or
3976 @samp{--jobs} option tells @code{make} to execute many commands
3977 simultaneously.  You can inhibit parallelism in a particular makefile
3978 with the @code{.NOTPARALLEL} pseudo-target (@pxref{Special
3979 Targets,Special Built-in Target Names}).@refill
3981 On MS-DOS, the @samp{-j} option has no effect, since that system doesn't
3982 support multi-processing.
3984 If the @samp{-j} option is followed by an integer, this is the number of
3985 commands to execute at once; this is called the number of @dfn{job slots}.
3986 If there is nothing looking like an integer after the @samp{-j} option,
3987 there is no limit on the number of job slots.  The default number of job
3988 slots is one, which means serial execution (one thing at a time).
3990 One unpleasant consequence of running several commands simultaneously is
3991 that output generated by the commands appears whenever each command
3992 sends it, so messages from different commands may be interspersed.
3994 Another problem is that two processes cannot both take input from the
3995 same device; so to make sure that only one command tries to take input
3996 from the terminal at once, @code{make} will invalidate the standard
3997 input streams of all but one running command.  This means that
3998 attempting to read from standard input will usually be a fatal error (a
3999 @samp{Broken pipe} signal) for most child processes if there are
4000 several.
4001 @cindex broken pipe
4002 @cindex standard input
4004 It is unpredictable which command will have a valid standard input stream
4005 (which will come from the terminal, or wherever you redirect the standard
4006 input of @code{make}).  The first command run will always get it first, and
4007 the first command started after that one finishes will get it next, and so
4010 We will change how this aspect of @code{make} works if we find a better
4011 alternative.  In the mean time, you should not rely on any command using
4012 standard input at all if you are using the parallel execution feature; but
4013 if you are not using this feature, then standard input works normally in
4014 all commands.
4016 Finally, handling recursive @code{make} invocations raises issues.  For
4017 more information on this, see
4018 @ref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
4020 If a command fails (is killed by a signal or exits with a nonzero
4021 status), and errors are not ignored for that command
4022 (@pxref{Errors, ,Errors in Commands}),
4023 the remaining command lines to remake the same target will not be run.
4024 If a command fails and the @samp{-k} or @samp{--keep-going}
4025 option was not given
4026 (@pxref{Options Summary, ,Summary of Options}),
4027 @code{make} aborts execution.  If make
4028 terminates for any reason (including a signal) with child processes
4029 running, it waits for them to finish before actually exiting.@refill
4031 @cindex load average
4032 @cindex limiting jobs based on load
4033 @cindex jobs, limiting based on load
4034 @cindex @code{-l} (load average)
4035 @cindex @code{--max-load}
4036 @cindex @code{--load-average}
4037 When the system is heavily loaded, you will probably want to run fewer jobs
4038 than when it is lightly loaded.  You can use the @samp{-l} option to tell
4039 @code{make} to limit the number of jobs to run at once, based on the load
4040 average.  The @samp{-l} or @samp{--max-load}
4041 option is followed by a floating-point number.  For
4042 example,
4044 @example
4045 -l 2.5
4046 @end example
4048 @noindent
4049 will not let @code{make} start more than one job if the load average is
4050 above 2.5.  The @samp{-l} option with no following number removes the
4051 load limit, if one was given with a previous @samp{-l} option.@refill
4053 More precisely, when @code{make} goes to start up a job, and it already has
4054 at least one job running, it checks the current load average; if it is not
4055 lower than the limit given with @samp{-l}, @code{make} waits until the load
4056 average goes below that limit, or until all the other jobs finish.
4058 By default, there is no load limit.
4060 @node Errors, Interrupts, Parallel, Commands
4061 @section Errors in Commands
4062 @cindex errors (in commands)
4063 @cindex commands, errors in
4064 @cindex exit status (errors)
4066 After each shell command returns, @code{make} looks at its exit status.
4067 If the command completed successfully, the next command line is executed
4068 in a new shell; after the last command line is finished, the rule is
4069 finished.
4071 If there is an error (the exit status is nonzero), @code{make} gives up on
4072 the current rule, and perhaps on all rules.
4074 Sometimes the failure of a certain command does not indicate a problem.
4075 For example, you may use the @code{mkdir} command to ensure that a
4076 directory exists.  If the directory already exists, @code{mkdir} will
4077 report an error, but you probably want @code{make} to continue regardless.
4079 @cindex @code{-} (in commands)
4080 To ignore errors in a command line, write a @samp{-} at the beginning of
4081 the line's text (after the initial tab).  The @samp{-} is discarded before
4082 the command is passed to the shell for execution.
4084 For example,
4086 @example
4087 @group
4088 clean:
4089         -rm -f *.o
4090 @end group
4091 @end example
4092 @cindex @code{rm} (shell command)
4094 @noindent
4095 This causes @code{rm} to continue even if it is unable to remove a file.
4097 @cindex @code{-i}
4098 @cindex @code{--ignore-errors}
4099 @findex .IGNORE
4100 When you run @code{make} with the @samp{-i} or @samp{--ignore-errors}
4101 flag, errors are ignored in all commands of all rules.  A rule in the
4102 makefile for the special target @code{.IGNORE} has the same effect, if
4103 there are no prerequisites.  These ways of ignoring errors are obsolete
4104 because @samp{-} is more flexible.
4106 When errors are to be ignored, because of either a @samp{-} or the
4107 @samp{-i} flag, @code{make} treats an error return just like success,
4108 except that it prints out a message that tells you the status code
4109 the command exited with, and says that the error has been ignored.
4111 When an error happens that @code{make} has not been told to ignore,
4112 it implies that the current target cannot be correctly remade, and neither
4113 can any other that depends on it either directly or indirectly.  No further
4114 commands will be executed for these targets, since their preconditions
4115 have not been achieved.
4118 @cindex @code{-k}
4119 @cindex @code{--keep-going}
4120 Normally @code{make} gives up immediately in this circumstance, returning a
4121 nonzero status.  However, if the @samp{-k} or @samp{--keep-going}
4122 flag is specified, @code{make}
4123 continues to consider the other prerequisites of the pending targets,
4124 remaking them if necessary, before it gives up and returns nonzero status.
4125 For example, after an error in compiling one object file, @samp{make -k}
4126 will continue compiling other object files even though it already knows
4127 that linking them will be impossible.  @xref{Options Summary, ,Summary of Options}.
4129 The usual behavior assumes that your purpose is to get the specified
4130 targets up to date; once @code{make} learns that this is impossible, it
4131 might as well report the failure immediately.  The @samp{-k} option says
4132 that the real purpose is to test as many of the changes made in the
4133 program as possible, perhaps to find several independent problems so
4134 that you can correct them all before the next attempt to compile.  This
4135 is why Emacs' @code{compile} command passes the @samp{-k} flag by
4136 default.
4137 @cindex Emacs (@code{M-x compile})
4139 @findex .DELETE_ON_ERROR
4140 @cindex deletion of target files
4141 @cindex removal of target files
4142 @cindex target, deleting on error
4143 Usually when a command fails, if it has changed the target file at all,
4144 the file is corrupted and cannot be used---or at least it is not
4145 completely updated.  Yet the file's time stamp says that it is now up to
4146 date, so the next time @code{make} runs, it will not try to update that
4147 file.  The situation is just the same as when the command is killed by a
4148 signal; @pxref{Interrupts}.  So generally the right thing to do is to
4149 delete the target file if the command fails after beginning to change
4150 the file.  @code{make} will do this if @code{.DELETE_ON_ERROR} appears
4151 as a target.  This is almost always what you want @code{make} to do, but
4152 it is not historical practice; so for compatibility, you must explicitly
4153 request it.
4155 @node Interrupts, Recursion, Errors, Commands
4156 @section Interrupting or Killing @code{make}
4157 @cindex interrupt
4158 @cindex signal
4159 @cindex deletion of target files
4160 @cindex removal of target files
4161 @cindex target, deleting on interrupt
4162 @cindex killing (interruption)
4164 If @code{make} gets a fatal signal while a command is executing, it may
4165 delete the target file that the command was supposed to update.  This is
4166 done if the target file's last-modification time has changed since
4167 @code{make} first checked it.
4169 The purpose of deleting the target is to make sure that it is remade from
4170 scratch when @code{make} is next run.  Why is this?  Suppose you type
4171 @kbd{Ctrl-c} while a compiler is running, and it has begun to write an
4172 object file @file{foo.o}.  The @kbd{Ctrl-c} kills the compiler, resulting
4173 in an incomplete file whose last-modification time is newer than the source
4174 file @file{foo.c}.  But @code{make} also receives the @kbd{Ctrl-c} signal
4175 and deletes this incomplete file.  If @code{make} did not do this, the next
4176 invocation of @code{make} would think that @file{foo.o} did not require
4177 updating---resulting in a strange error message from the linker when it
4178 tries to link an object file half of which is missing.
4180 @findex .PRECIOUS
4181 You can prevent the deletion of a target file in this way by making the
4182 special target @code{.PRECIOUS} depend on it.  Before remaking a target,
4183 @code{make} checks to see whether it appears on the prerequisites of
4184 @code{.PRECIOUS}, and thereby decides whether the target should be deleted
4185 if a signal happens.  Some reasons why you might do this are that the
4186 target is updated in some atomic fashion, or exists only to record a
4187 modification-time (its contents do not matter), or must exist at all
4188 times to prevent other sorts of trouble.
4190 @node Recursion, Sequences, Interrupts, Commands
4191 @section Recursive Use of @code{make}
4192 @cindex recursion
4193 @cindex subdirectories, recursion for
4195 Recursive use of @code{make} means using @code{make} as a command in a
4196 makefile.  This technique is useful when you want separate makefiles for
4197 various subsystems that compose a larger system.  For example, suppose you
4198 have a subdirectory @file{subdir} which has its own makefile, and you would
4199 like the containing directory's makefile to run @code{make} on the
4200 subdirectory.  You can do it by writing this:
4202 @example
4203 subsystem:
4204         cd subdir && $(MAKE)
4205 @end example
4207 @noindent
4208 or, equivalently, this (@pxref{Options Summary, ,Summary of Options}):
4210 @example
4211 subsystem:
4212         $(MAKE) -C subdir
4213 @end example
4214 @cindex @code{-C}
4215 @cindex @code{--directory}
4217 You can write recursive @code{make} commands just by copying this example,
4218 but there are many things to know about how they work and why, and about
4219 how the sub-@code{make} relates to the top-level @code{make}.  You may
4220 also find it useful to declare targets that invoke recursive
4221 @code{make} commands as @samp{.PHONY} (for more discussion on when
4222 this is useful, see @ref{Phony Targets}).
4224 @vindex @code{CURDIR}
4225 For your convenience, when GNU @code{make} starts (after it has
4226 processed any @code{-C} options) it sets the variable @code{CURDIR} to
4227 the pathname of the current working directory.  This value is never
4228 touched by @code{make} again: in particular note that if you include
4229 files from other directories the value of @code{CURDIR} does not
4230 change.  The value has the same precedence it would have if it were
4231 set in the makefile (by default, an environment variable @code{CURDIR}
4232 will not override this value).  Note that setting this variable has no
4233 impact on the operation of @code{make} (it does not cause @code{make}
4234 to change its working directory, for example).
4236 @menu
4237 * MAKE Variable::               The special effects of using @samp{$(MAKE)}.
4238 * Variables/Recursion::         How to communicate variables to a sub-@code{make}.
4239 * Options/Recursion::           How to communicate options to a sub-@code{make}.
4240 * -w Option::                   How the @samp{-w} or @samp{--print-directory} option
4241                                   helps debug use of recursive @code{make} commands.
4242 @end menu
4244 @node MAKE Variable, Variables/Recursion, Recursion, Recursion
4245 @subsection How the @code{MAKE} Variable Works
4246 @vindex MAKE
4247 @cindex recursion, and @code{MAKE} variable
4249 Recursive @code{make} commands should always use the variable @code{MAKE},
4250 not the explicit command name @samp{make}, as shown here:
4252 @example
4253 @group
4254 subsystem:
4255         cd subdir && $(MAKE)
4256 @end group
4257 @end example
4259 The value of this variable is the file name with which @code{make} was
4260 invoked.  If this file name was @file{/bin/make}, then the command executed
4261 is @samp{cd subdir && /bin/make}.  If you use a special version of
4262 @code{make} to run the top-level makefile, the same special version will be
4263 executed for recursive invocations.
4264 @cindex @code{cd} (shell command)
4266 @cindex +, and commands
4267 As a special feature, using the variable @code{MAKE} in the commands of
4268 a rule alters the effects of the @samp{-t} (@samp{--touch}), @samp{-n}
4269 (@samp{--just-print}), or @samp{-q} (@w{@samp{--question}}) option.
4270 Using the @code{MAKE} variable has the same effect as using a @samp{+}
4271 character at the beginning of the command line.  @xref{Instead of
4272 Execution, ,Instead of Executing the Commands}.  This special feature
4273 is only enabled if the @code{MAKE} variable appears directly in the
4274 command script: it does not apply if the @code{MAKE} variable is
4275 referenced through expansion of another variable.  In the latter case
4276 you must use the @samp{+} token to get these special effects.@refill
4278 Consider the command @samp{make -t} in the above example.  (The
4279 @samp{-t} option marks targets as up to date without actually running
4280 any commands; see @ref{Instead of Execution}.)  Following the usual
4281 definition of @samp{-t}, a @samp{make -t} command in the example would
4282 create a file named @file{subsystem} and do nothing else.  What you
4283 really want it to do is run @samp{@w{cd subdir &&} @w{make -t}}; but that would
4284 require executing the command, and @samp{-t} says not to execute
4285 commands.@refill
4286 @cindex @code{-t}, and recursion
4287 @cindex recursion, and @code{-t}
4288 @cindex @code{--touch}, and recursion
4290 The special feature makes this do what you want: whenever a command
4291 line of a rule contains the variable @code{MAKE}, the flags @samp{-t},
4292 @samp{-n} and @samp{-q} do not apply to that line.  Command lines
4293 containing @code{MAKE} are executed normally despite the presence of a
4294 flag that causes most commands not to be run.  The usual
4295 @code{MAKEFLAGS} mechanism passes the flags to the sub-@code{make}
4296 (@pxref{Options/Recursion, ,Communicating Options to a
4297 Sub-@code{make}}), so your request to touch the files, or print the
4298 commands, is propagated to the subsystem.@refill
4300 @node Variables/Recursion, Options/Recursion, MAKE Variable, Recursion
4301 @subsection Communicating Variables to a Sub-@code{make}
4302 @cindex sub-@code{make}
4303 @cindex environment, and recursion
4304 @cindex exporting variables
4305 @cindex variables, environment
4306 @cindex variables, exporting
4307 @cindex recursion, and environment
4308 @cindex recursion, and variables
4310 Variable values of the top-level @code{make} can be passed to the
4311 sub-@code{make} through the environment by explicit request.  These
4312 variables are defined in the sub-@code{make} as defaults, but do not
4313 override what is specified in the makefile used by the sub-@code{make}
4314 makefile unless you use the @samp{-e} switch (@pxref{Options Summary,
4315 ,Summary of Options}).@refill
4317 To pass down, or @dfn{export}, a variable, @code{make} adds the variable
4318 and its value to the environment for running each command.  The
4319 sub-@code{make}, in turn, uses the environment to initialize its table
4320 of variable values.  @xref{Environment, ,Variables from the
4321 Environment}.
4323 Except by explicit request, @code{make} exports a variable only if it
4324 is either defined in the environment initially or set on the command
4325 line, and if its name consists only of letters, numbers, and underscores.
4326 Some shells cannot cope with environment variable names consisting of
4327 characters other than letters, numbers, and underscores.
4329 @cindex SHELL, exported value
4330 The value of the @code{make} variable @code{SHELL} is not exported.
4331 Instead, the value of the @code{SHELL} variable from the invoking
4332 environment is passed to the sub-@code{make}.  You can force
4333 @code{make} to export its value for @code{SHELL} by using the
4334 @code{export} directive, described below.  @xref{Choosing the Shell}.
4336 The special variable @code{MAKEFLAGS} is always exported (unless you
4337 unexport it).  @code{MAKEFILES} is exported if you set it to anything.
4339 @code{make} automatically passes down variable values that were defined
4340 on the command line, by putting them in the @code{MAKEFLAGS} variable.
4341 @iftex
4342 See the next section.
4343 @end iftex
4344 @ifnottex
4345 @xref{Options/Recursion}.
4346 @end ifnottex
4348 Variables are @emph{not} normally passed down if they were created by
4349 default by @code{make} (@pxref{Implicit Variables, ,Variables Used by
4350 Implicit Rules}).  The sub-@code{make} will define these for
4351 itself.@refill
4353 @findex export
4354 If you want to export specific variables to a sub-@code{make}, use the
4355 @code{export} directive, like this:
4357 @example
4358 export @var{variable} @dots{}
4359 @end example
4361 @noindent
4362 @findex unexport
4363 If you want to @emph{prevent} a variable from being exported, use the
4364 @code{unexport} directive, like this:
4366 @example
4367 unexport @var{variable} @dots{}
4368 @end example
4370 @noindent
4371 In both of these forms, the arguments to @code{export} and
4372 @code{unexport} are expanded, and so could be variables or functions
4373 which expand to a (list of) variable names to be (un)exported.
4375 As a convenience, you can define a variable and export it at the same
4376 time by doing:
4378 @example
4379 export @var{variable} = value
4380 @end example
4382 @noindent
4383 has the same result as:
4385 @example
4386 @var{variable} = value
4387 export @var{variable}
4388 @end example
4390 @noindent
4393 @example
4394 export @var{variable} := value
4395 @end example
4397 @noindent
4398 has the same result as:
4400 @example
4401 @var{variable} := value
4402 export @var{variable}
4403 @end example
4405 Likewise,
4407 @example
4408 export @var{variable} += value
4409 @end example
4411 @noindent
4412 is just like:
4414 @example
4415 @var{variable} += value
4416 export @var{variable}
4417 @end example
4419 @noindent
4420 @xref{Appending, ,Appending More Text to Variables}.
4422 You may notice that the @code{export} and @code{unexport} directives
4423 work in @code{make} in the same way they work in the shell, @code{sh}.
4425 If you want all variables to be exported by default, you can use
4426 @code{export} by itself:
4428 @example
4429 export
4430 @end example
4432 @noindent
4433 This tells @code{make} that variables which are not explicitly mentioned
4434 in an @code{export} or @code{unexport} directive should be exported.
4435 Any variable given in an @code{unexport} directive will still @emph{not}
4436 be exported.  If you use @code{export} by itself to export variables by
4437 default, variables whose names contain characters other than
4438 alphanumerics and underscores will not be exported unless specifically
4439 mentioned in an @code{export} directive.@refill
4441 @findex .EXPORT_ALL_VARIABLES
4442 The behavior elicited by an @code{export} directive by itself was the
4443 default in older versions of GNU @code{make}.  If your makefiles depend
4444 on this behavior and you want to be compatible with old versions of
4445 @code{make}, you can write a rule for the special target
4446 @code{.EXPORT_ALL_VARIABLES} instead of using the @code{export} directive.
4447 This will be ignored by old @code{make}s, while the @code{export}
4448 directive will cause a syntax error.@refill
4449 @cindex compatibility in exporting
4451 Likewise, you can use @code{unexport} by itself to tell @code{make}
4452 @emph{not} to export variables by default.  Since this is the default
4453 behavior, you would only need to do this if @code{export} had been used
4454 by itself earlier (in an included makefile, perhaps).  You
4455 @strong{cannot} use @code{export} and @code{unexport} by themselves to
4456 have variables exported for some commands and not for others.  The last
4457 @code{export} or @code{unexport} directive that appears by itself
4458 determines the behavior for the entire run of @code{make}.@refill
4460 @vindex MAKELEVEL
4461 @cindex recursion, level of
4462 As a special feature, the variable @code{MAKELEVEL} is changed when it
4463 is passed down from level to level.  This variable's value is a string
4464 which is the depth of the level as a decimal number.  The value is
4465 @samp{0} for the top-level @code{make}; @samp{1} for a sub-@code{make},
4466 @samp{2} for a sub-sub-@code{make}, and so on.  The incrementation
4467 happens when @code{make} sets up the environment for a command.@refill
4469 The main use of @code{MAKELEVEL} is to test it in a conditional
4470 directive (@pxref{Conditionals, ,Conditional Parts of Makefiles}); this
4471 way you can write a makefile that behaves one way if run recursively and
4472 another way if run directly by you.@refill
4474 @vindex MAKEFILES
4475 You can use the variable @code{MAKEFILES} to cause all sub-@code{make}
4476 commands to use additional makefiles.  The value of @code{MAKEFILES} is
4477 a whitespace-separated list of file names.  This variable, if defined in
4478 the outer-level makefile, is passed down through the environment; then
4479 it serves as a list of extra makefiles for the sub-@code{make} to read
4480 before the usual or specified ones.  @xref{MAKEFILES Variable, ,The
4481 Variable @code{MAKEFILES}}.@refill
4483 @node Options/Recursion, -w Option, Variables/Recursion, Recursion
4484 @subsection Communicating Options to a Sub-@code{make}
4485 @cindex options, and recursion
4486 @cindex recursion, and options
4488 @vindex MAKEFLAGS
4489 Flags such as @samp{-s} and @samp{-k} are passed automatically to the
4490 sub-@code{make} through the variable @code{MAKEFLAGS}.  This variable is
4491 set up automatically by @code{make} to contain the flag letters that
4492 @code{make} received.  Thus, if you do @w{@samp{make -ks}} then
4493 @code{MAKEFLAGS} gets the value @samp{ks}.@refill
4495 As a consequence, every sub-@code{make} gets a value for @code{MAKEFLAGS}
4496 in its environment.  In response, it takes the flags from that value and
4497 processes them as if they had been given as arguments.
4498 @xref{Options Summary, ,Summary of Options}.
4500 @cindex command line variable definitions, and recursion
4501 @cindex variables, command line, and recursion
4502 @cindex recursion, and command line variable definitions
4503 Likewise variables defined on the command line are passed to the
4504 sub-@code{make} through @code{MAKEFLAGS}.  Words in the value of
4505 @code{MAKEFLAGS} that contain @samp{=}, @code{make} treats as variable
4506 definitions just as if they appeared on the command line.
4507 @xref{Overriding, ,Overriding Variables}.
4509 @cindex @code{-C}, and recursion
4510 @cindex @code{-f}, and recursion
4511 @cindex @code{-o}, and recursion
4512 @cindex @code{-W}, and recursion
4513 @cindex @code{--directory}, and recursion
4514 @cindex @code{--file}, and recursion
4515 @cindex @code{--old-file}, and recursion
4516 @cindex @code{--assume-old}, and recursion
4517 @cindex @code{--assume-new}, and recursion
4518 @cindex @code{--new-file}, and recursion
4519 @cindex recursion, and @code{-C}
4520 @cindex recursion, and @code{-f}
4521 @cindex recursion, and @code{-o}
4522 @cindex recursion, and @code{-W}
4523 The options @samp{-C}, @samp{-f}, @samp{-o}, and @samp{-W} are not put
4524 into @code{MAKEFLAGS}; these options are not passed down.@refill
4526 @cindex @code{-j}, and recursion
4527 @cindex @code{--jobs}, and recursion
4528 @cindex recursion, and @code{-j}
4529 @cindex job slots, and recursion
4530 The @samp{-j} option is a special case (@pxref{Parallel, ,Parallel Execution}).
4531 If you set it to some numeric value @samp{N} and your operating system
4532 supports it (most any UNIX system will; others typically won't), the
4533 parent @code{make} and all the sub-@code{make}s will communicate to
4534 ensure that there are only @samp{N} jobs running at the same time
4535 between them all.  Note that any job that is marked recursive
4536 (@pxref{Instead of Execution, ,Instead of Executing the Commands})
4537 doesn't count against the total jobs (otherwise we could get @samp{N}
4538 sub-@code{make}s running and have no slots left over for any real work!)
4540 If your operating system doesn't support the above communication, then
4541 @samp{-j 1} is always put into @code{MAKEFLAGS} instead of the value you
4542 specified.  This is because if the @w{@samp{-j}} option were passed down
4543 to sub-@code{make}s, you would get many more jobs running in parallel
4544 than you asked for.  If you give @samp{-j} with no numeric argument,
4545 meaning to run as many jobs as possible in parallel, this is passed
4546 down, since multiple infinities are no more than one.@refill
4548 If you do not want to pass the other flags down, you must change the
4549 value of @code{MAKEFLAGS}, like this:
4551 @example
4552 subsystem:
4553         cd subdir && $(MAKE) MAKEFLAGS=
4554 @end example
4556 @vindex MAKEOVERRIDES
4557 The command line variable definitions really appear in the variable
4558 @code{MAKEOVERRIDES}, and @code{MAKEFLAGS} contains a reference to this
4559 variable.  If you do want to pass flags down normally, but don't want to
4560 pass down the command line variable definitions, you can reset
4561 @code{MAKEOVERRIDES} to empty, like this:
4563 @example
4564 MAKEOVERRIDES =
4565 @end example
4567 @noindent
4568 @cindex Arg list too long
4569 @cindex E2BIG
4570 This is not usually useful to do.  However, some systems have a small
4571 fixed limit on the size of the environment, and putting so much
4572 information into the value of @code{MAKEFLAGS} can exceed it.  If you
4573 see the error message @samp{Arg list too long}, this may be the problem.
4574 @findex .POSIX
4575 @cindex POSIX.2
4576 (For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
4577 not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
4578 in the makefile.  You probably do not care about this.)
4580 @vindex MFLAGS
4581 A similar variable @code{MFLAGS} exists also, for historical
4582 compatibility.  It has the same value as @code{MAKEFLAGS} except that it
4583 does not contain the command line variable definitions, and it always
4584 begins with a hyphen unless it is empty (@code{MAKEFLAGS} begins with a
4585 hyphen only when it begins with an option that has no single-letter
4586 version, such as @samp{--warn-undefined-variables}).  @code{MFLAGS} was
4587 traditionally used explicitly in the recursive @code{make} command, like
4588 this:
4590 @example
4591 subsystem:
4592         cd subdir && $(MAKE) $(MFLAGS)
4593 @end example
4595 @noindent
4596 but now @code{MAKEFLAGS} makes this usage redundant.  If you want your
4597 makefiles to be compatible with old @code{make} programs, use this
4598 technique; it will work fine with more modern @code{make} versions too.
4600 @cindex setting options from environment
4601 @cindex options, setting from environment
4602 @cindex setting options in makefiles
4603 @cindex options, setting in makefiles
4604 The @code{MAKEFLAGS} variable can also be useful if you want to have
4605 certain options, such as @samp{-k} (@pxref{Options Summary, ,Summary of
4606 Options}), set each time you run @code{make}.  You simply put a value for
4607 @code{MAKEFLAGS} in your environment.  You can also set @code{MAKEFLAGS} in
4608 a makefile, to specify additional flags that should also be in effect for
4609 that makefile.  (Note that you cannot use @code{MFLAGS} this way.  That
4610 variable is set only for compatibility; @code{make} does not interpret a
4611 value you set for it in any way.)
4613 When @code{make} interprets the value of @code{MAKEFLAGS} (either from the
4614 environment or from a makefile), it first prepends a hyphen if the value
4615 does not already begin with one.  Then it chops the value into words
4616 separated by blanks, and parses these words as if they were options given
4617 on the command line (except that @samp{-C}, @samp{-f}, @samp{-h},
4618 @samp{-o}, @samp{-W}, and their long-named versions are ignored; and there
4619 is no error for an invalid option).
4621 If you do put @code{MAKEFLAGS} in your environment, you should be sure not
4622 to include any options that will drastically affect the actions of
4623 @code{make} and undermine the purpose of makefiles and of @code{make}
4624 itself.  For instance, the @samp{-t}, @samp{-n}, and @samp{-q} options, if
4625 put in one of these variables, could have disastrous consequences and would
4626 certainly have at least surprising and probably annoying effects.@refill
4628 @node -w Option,  , Options/Recursion, Recursion
4629 @subsection The @samp{--print-directory} Option
4630 @cindex directories, printing them
4631 @cindex printing directories
4632 @cindex recursion, and printing directories
4634 If you use several levels of recursive @code{make} invocations, the
4635 @samp{-w} or @w{@samp{--print-directory}} option can make the output a
4636 lot easier to understand by showing each directory as @code{make}
4637 starts processing it and as @code{make} finishes processing it.  For
4638 example, if @samp{make -w} is run in the directory @file{/u/gnu/make},
4639 @code{make} will print a line of the form:@refill
4641 @example
4642 make: Entering directory `/u/gnu/make'.
4643 @end example
4645 @noindent
4646 before doing anything else, and a line of the form:
4648 @example
4649 make: Leaving directory `/u/gnu/make'.
4650 @end example
4652 @noindent
4653 when processing is completed.
4655 @cindex @code{-C}, and @code{-w}
4656 @cindex @code{--directory}, and @code{--print-directory}
4657 @cindex recursion, and @code{-w}
4658 @cindex @code{-w}, and @code{-C}
4659 @cindex @code{-w}, and recursion
4660 @cindex @code{--print-directory}, and @code{--directory}
4661 @cindex @code{--print-directory}, and recursion
4662 @cindex @code{--no-print-directory}
4663 @cindex @code{--print-directory}, disabling
4664 @cindex @code{-w}, disabling
4665 Normally, you do not need to specify this option because @samp{make}
4666 does it for you: @samp{-w} is turned on automatically when you use the
4667 @samp{-C} option, and in sub-@code{make}s.  @code{make} will not
4668 automatically turn on @samp{-w} if you also use @samp{-s}, which says to
4669 be silent, or if you use @samp{--no-print-directory} to explicitly
4670 disable it.
4672 @node Sequences, Empty Commands, Recursion, Commands
4673 @section Defining Canned Command Sequences
4674 @cindex sequences of commands
4675 @cindex commands, sequences of
4677 When the same sequence of commands is useful in making various targets, you
4678 can define it as a canned sequence with the @code{define} directive, and
4679 refer to the canned sequence from the rules for those targets.  The canned
4680 sequence is actually a variable, so the name must not conflict with other
4681 variable names.
4683 Here is an example of defining a canned sequence of commands:
4685 @example
4686 define run-yacc
4687 yacc $(firstword $^)
4688 mv y.tab.c $@@
4689 endef
4690 @end example
4691 @cindex @code{yacc}
4693 @noindent
4694 Here @code{run-yacc} is the name of the variable being defined;
4695 @code{endef} marks the end of the definition; the lines in between are the
4696 commands.  The @code{define} directive does not expand variable references
4697 and function calls in the canned sequence; the @samp{$} characters,
4698 parentheses, variable names, and so on, all become part of the value of the
4699 variable you are defining.
4700 @xref{Defining, ,Defining Variables Verbatim},
4701 for a complete explanation of @code{define}.
4703 The first command in this example runs Yacc on the first prerequisite of
4704 whichever rule uses the canned sequence.  The output file from Yacc is
4705 always named @file{y.tab.c}.  The second command moves the output to the
4706 rule's target file name.
4708 To use the canned sequence, substitute the variable into the commands of a
4709 rule.  You can substitute it like any other variable
4710 (@pxref{Reference, ,Basics of Variable References}).
4711 Because variables defined by @code{define} are recursively expanded
4712 variables, all the variable references you wrote inside the @code{define}
4713 are expanded now.  For example:
4715 @example
4716 foo.c : foo.y
4717         $(run-yacc)
4718 @end example
4720 @noindent
4721 @samp{foo.y} will be substituted for the variable @samp{$^} when it occurs in
4722 @code{run-yacc}'s value, and @samp{foo.c} for @samp{$@@}.@refill
4724 This is a realistic example, but this particular one is not needed in
4725 practice because @code{make} has an implicit rule to figure out these
4726 commands based on the file names involved
4727 (@pxref{Implicit Rules, ,Using Implicit Rules}).
4729 @cindex @@, and @code{define}
4730 @cindex -, and @code{define}
4731 @cindex +, and @code{define}
4732 In command execution, each line of a canned sequence is treated just as
4733 if the line appeared on its own in the rule, preceded by a tab.  In
4734 particular, @code{make} invokes a separate subshell for each line.  You
4735 can use the special prefix characters that affect command lines
4736 (@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
4737 @xref{Commands, ,Writing the Commands in Rules}.
4738 For example, using this canned sequence:
4740 @example
4741 define frobnicate
4742 @@echo "frobnicating target $@@"
4743 frob-step-1 $< -o $@@-step-1
4744 frob-step-2 $@@-step-1 -o $@@
4745 endef
4746 @end example
4748 @noindent
4749 @code{make} will not echo the first line, the @code{echo} command.
4750 But it @emph{will} echo the following two command lines.
4752 On the other hand, prefix characters on the command line that refers to
4753 a canned sequence apply to every line in the sequence.  So the rule:
4755 @example
4756 frob.out: frob.in
4757         @@$(frobnicate)
4758 @end example
4760 @noindent
4761 does not echo @emph{any} commands.
4762 (@xref{Echoing, ,Command Echoing}, for a full explanation of @samp{@@}.)
4764 @node Empty Commands,  , Sequences, Commands
4765 @section Using Empty Commands
4766 @cindex empty commands
4767 @cindex commands, empty
4769 It is sometimes useful to define commands which do nothing.  This is done
4770 simply by giving a command that consists of nothing but whitespace.  For
4771 example:
4773 @example
4774 target: ;
4775 @end example
4777 @noindent
4778 defines an empty command string for @file{target}.  You could also use a
4779 line beginning with a tab character to define an empty command string,
4780 but this would be confusing because such a line looks empty.
4782 @findex .DEFAULT@r{, and empty commands}
4783 You may be wondering why you would want to define a command string that
4784 does nothing.  The only reason this is useful is to prevent a target
4785 from getting implicit commands (from implicit rules or the
4786 @code{.DEFAULT} special target; @pxref{Implicit Rules} and
4787 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
4789 @c !!! another reason is for canonical stamp files:
4790 @ignore
4791 @example
4792 foo: stamp-foo ;
4793 stamp-foo: foo.in
4794         create foo frm foo.in
4795         touch $@
4796 @end example
4797 @end ignore
4799 You may be inclined to define empty command strings for targets that are
4800 not actual files, but only exist so that their prerequisites can be
4801 remade.  However, this is not the best way to do that, because the
4802 prerequisites may not be remade properly if the target file actually does exist.
4803 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
4805 @node Using Variables, Conditionals, Commands, Top
4806 @chapter How to Use Variables
4807 @cindex variable
4808 @cindex value
4809 @cindex recursive variable expansion
4810 @cindex simple variable expansion
4812 A @dfn{variable} is a name defined in a makefile to represent a string
4813 of text, called the variable's @dfn{value}.  These values are
4814 substituted by explicit request into targets, prerequisites, commands,
4815 and other parts of the makefile.  (In some other versions of @code{make},
4816 variables are called @dfn{macros}.)
4817 @cindex macro
4819 Variables and functions in all parts of a makefile are expanded when
4820 read, except for the shell commands in rules, the right-hand sides of
4821 variable definitions using @samp{=}, and the bodies of variable
4822 definitions using the @code{define} directive.@refill
4824 Variables can represent lists of file names, options to pass to compilers,
4825 programs to run, directories to look in for source files, directories to
4826 write output in, or anything else you can imagine.
4828 A variable name may be any sequence of characters not containing @samp{:},
4829 @samp{#}, @samp{=}, or leading or trailing whitespace.  However,
4830 variable names containing characters other than letters, numbers, and
4831 underscores should be avoided, as they may be given special meanings in the
4832 future, and with some shells they cannot be passed through the environment to a
4833 sub-@code{make}
4834 (@pxref{Variables/Recursion, ,Communicating Variables to a Sub-@code{make}}).
4836 Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
4837 and @samp{Foo} all refer to different variables.
4839 It is traditional to use upper case letters in variable names, but we
4840 recommend using lower case letters for variable names that serve internal
4841 purposes in the makefile, and reserving upper case for parameters that
4842 control implicit rules or for parameters that the user should override with
4843 command options (@pxref{Overriding, ,Overriding Variables}).
4845 A few variables have names that are a single punctuation character or
4846 just a few characters.  These are the @dfn{automatic variables}, and
4847 they have particular specialized uses.  @xref{Automatic Variables}.
4849 @menu
4850 * Reference::                   How to use the value of a variable.
4851 * Flavors::                     Variables come in two flavors.
4852 * Advanced::                    Advanced features for referencing a variable.
4853 * Values::                      All the ways variables get their values.
4854 * Setting::                     How to set a variable in the makefile.
4855 * Appending::                   How to append more text to the old value
4856                                   of a variable.
4857 * Override Directive::          How to set a variable in the makefile even if
4858                                   the user has set it with a command argument.
4859 * Defining::                    An alternate way to set a variable
4860                                   to a verbatim string.
4861 * Environment::                 Variable values can come from the environment.
4862 * Target-specific::             Variable values can be defined on a per-target
4863                                   basis.
4864 * Pattern-specific::            Target-specific variable values can be applied
4865                                   to a group of targets that match a pattern.
4866 @end menu
4868 @node Reference, Flavors, Using Variables, Using Variables
4869 @section Basics of Variable References
4870 @cindex variables, how to reference
4871 @cindex reference to variables
4872 @cindex @code{$}, in variable reference
4873 @cindex dollar sign (@code{$}), in variable reference
4875 To substitute a variable's value, write a dollar sign followed by the name
4876 of the variable in parentheses or braces: either @samp{$(foo)} or
4877 @samp{$@{foo@}} is a valid reference to the variable @code{foo}.  This
4878 special significance of @samp{$} is why you must write @samp{$$} to have
4879 the effect of a single dollar sign in a file name or command.
4881 Variable references can be used in any context: targets, prerequisites,
4882 commands, most directives, and new variable values.  Here is an
4883 example of a common case, where a variable holds the names of all the
4884 object files in a program:
4886 @example
4887 @group
4888 objects = program.o foo.o utils.o
4889 program : $(objects)
4890         cc -o program $(objects)
4892 $(objects) : defs.h
4893 @end group
4894 @end example
4896 Variable references work by strict textual substitution.  Thus, the rule
4898 @example
4899 @group
4900 foo = c
4901 prog.o : prog.$(foo)
4902         $(foo)$(foo) -$(foo) prog.$(foo)
4903 @end group
4904 @end example
4906 @noindent
4907 could be used to compile a C program @file{prog.c}.  Since spaces before
4908 the variable value are ignored in variable assignments, the value of
4909 @code{foo} is precisely @samp{c}.  (Don't actually write your makefiles
4910 this way!)
4912 A dollar sign followed by a character other than a dollar sign,
4913 open-parenthesis or open-brace treats that single character as the
4914 variable name.  Thus, you could reference the variable @code{x} with
4915 @samp{$x}.  However, this practice is strongly discouraged, except in
4916 the case of the automatic variables (@pxref{Automatic Variables}).
4918 @node Flavors, Advanced, Reference, Using Variables
4919 @section The Two Flavors of Variables
4920 @cindex flavors of variables
4921 @cindex recursive variable expansion
4922 @cindex variables, flavors
4923 @cindex recursively expanded variables
4924 @cindex variables, recursively expanded
4926 There are two ways that a variable in GNU @code{make} can have a value;
4927 we call them the two @dfn{flavors} of variables.  The two flavors are
4928 distinguished in how they are defined and in what they do when expanded.
4930 @cindex =
4931 The first flavor of variable is a @dfn{recursively expanded} variable.
4932 Variables of this sort are defined by lines using @samp{=}
4933 (@pxref{Setting, ,Setting Variables}) or by the @code{define} directive
4934 (@pxref{Defining, ,Defining Variables Verbatim}).  The value you specify
4935 is installed verbatim; if it contains references to other variables,
4936 these references are expanded whenever this variable is substituted (in
4937 the course of expanding some other string).  When this happens, it is
4938 called @dfn{recursive expansion}.@refill
4940 For example,
4942 @example
4943 foo = $(bar)
4944 bar = $(ugh)
4945 ugh = Huh?
4947 all:;echo $(foo)
4948 @end example
4950 @noindent
4951 will echo @samp{Huh?}: @samp{$(foo)} expands to @samp{$(bar)} which
4952 expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
4954 This flavor of variable is the only sort supported by other versions of
4955 @code{make}.  It has its advantages and its disadvantages.  An advantage
4956 (most would say) is that:
4958 @example
4959 CFLAGS = $(include_dirs) -O
4960 include_dirs = -Ifoo -Ibar
4961 @end example
4963 @noindent
4964 will do what was intended: when @samp{CFLAGS} is expanded in a command,
4965 it will expand to @samp{-Ifoo -Ibar -O}.  A major disadvantage is that you
4966 cannot append something on the end of a variable, as in
4968 @example
4969 CFLAGS = $(CFLAGS) -O
4970 @end example
4972 @noindent
4973 because it will cause an infinite loop in the variable expansion.
4974 (Actually @code{make} detects the infinite loop and reports an error.)
4975 @cindex loops in variable expansion
4976 @cindex variables, loops in expansion
4978 Another disadvantage is that any functions
4979 (@pxref{Functions, ,Functions for Transforming Text})
4980 referenced in the definition will be executed every time the variable is
4981 expanded.  This makes @code{make} run slower; worse, it causes the
4982 @code{wildcard} and @code{shell} functions to give unpredictable results
4983 because you cannot easily control when they are called, or even how many
4984 times.
4986 To avoid all the problems and inconveniences of recursively expanded
4987 variables, there is another flavor: simply expanded variables.
4989 @cindex simply expanded variables
4990 @cindex variables, simply expanded
4991 @cindex :=
4992 @dfn{Simply expanded variables} are defined by lines using @samp{:=}
4993 (@pxref{Setting, ,Setting Variables}).
4994 The value of a simply expanded variable is scanned
4995 once and for all, expanding any references to other variables and
4996 functions, when the variable is defined.  The actual value of the simply
4997 expanded variable is the result of expanding the text that you write.
4998 It does not contain any references to other variables; it contains their
4999 values @emph{as of the time this variable was defined}.  Therefore,
5001 @example
5002 x := foo
5003 y := $(x) bar
5004 x := later
5005 @end example
5007 @noindent
5008 is equivalent to
5010 @example
5011 y := foo bar
5012 x := later
5013 @end example
5015 When a simply expanded variable is referenced, its value is substituted
5016 verbatim.
5018 Here is a somewhat more complicated example, illustrating the use of
5019 @samp{:=} in conjunction with the @code{shell} function.
5020 (@xref{Shell Function, , The @code{shell} Function}.)  This example
5021 also shows use of the variable @code{MAKELEVEL}, which is changed
5022 when it is passed down from level to level.
5023 (@xref{Variables/Recursion, , Communicating Variables to a
5024 Sub-@code{make}}, for information about @code{MAKELEVEL}.)
5026 @vindex MAKELEVEL
5027 @vindex MAKE
5028 @example
5029 @group
5030 ifeq (0,$@{MAKELEVEL@})
5031 whoami    := $(shell whoami)
5032 host-type := $(shell arch)
5033 MAKE := $@{MAKE@} host-type=$@{host-type@} whoami=$@{whoami@}
5034 endif
5035 @end group
5036 @end example
5038 @noindent
5039 An advantage of this use of @samp{:=} is that a typical
5040 `descend into a directory' command then looks like this:
5042 @example
5043 @group
5044 $@{subdirs@}:
5045         $@{MAKE@} -C $@@ all
5046 @end group
5047 @end example
5049 Simply expanded variables generally make complicated makefile programming
5050 more predictable because they work like variables in most programming
5051 languages.  They allow you to redefine a variable using its own value (or
5052 its value processed in some way by one of the expansion functions) and to
5053 use the expansion functions much more efficiently
5054 (@pxref{Functions, ,Functions for Transforming Text}).
5056 @cindex spaces, in variable values
5057 @cindex whitespace, in variable values
5058 @cindex variables, spaces in values
5059 You can also use them to introduce controlled leading whitespace into
5060 variable values.  Leading whitespace characters are discarded from your
5061 input before substitution of variable references and function calls;
5062 this means you can include leading spaces in a variable value by
5063 protecting them with variable references, like this:
5065 @example
5066 nullstring :=
5067 space := $(nullstring) # end of the line
5068 @end example
5070 @noindent
5071 Here the value of the variable @code{space} is precisely one space.  The
5072 comment @w{@samp{# end of the line}} is included here just for clarity.
5073 Since trailing space characters are @emph{not} stripped from variable
5074 values, just a space at the end of the line would have the same effect
5075 (but be rather hard to read).  If you put whitespace at the end of a
5076 variable value, it is a good idea to put a comment like that at the end
5077 of the line to make your intent clear.  Conversely, if you do @emph{not}
5078 want any whitespace characters at the end of your variable value, you
5079 must remember not to put a random comment on the end of the line after
5080 some whitespace, such as this:
5082 @example
5083 dir := /foo/bar    # directory to put the frobs in
5084 @end example
5086 @noindent
5087 Here the value of the variable @code{dir} is @w{@samp{/foo/bar    }}
5088 (with four trailing spaces), which was probably not the intention.
5089 (Imagine something like @w{@samp{$(dir)/file}} with this definition!)
5091 @cindex conditional variable assignment
5092 @cindex variables, conditional assignment
5093 @cindex ?=
5094 There is another assignment operator for variables, @samp{?=}.  This
5095 is called a conditional variable assignment operator, because it only
5096 has an effect if the variable is not yet defined.  This statement:
5098 @example
5099 FOO ?= bar
5100 @end example
5102 @noindent
5103 is exactly equivalent to this
5104 (@pxref{Origin Function, ,The @code{origin} Function}):
5106 @example
5107 ifeq ($(origin FOO), undefined)
5108   FOO = bar
5109 endif
5110 @end example
5112 Note that a variable set to an empty value is still defined, so
5113 @samp{?=} will not set that variable.
5115 @node Advanced, Values, Flavors, Using Variables
5116 @section Advanced Features for Reference to Variables
5117 @cindex reference to variables
5119 This section describes some advanced features you can use to reference
5120 variables in more flexible ways.
5122 @menu
5123 * Substitution Refs::           Referencing a variable with
5124                                   substitutions on the value.
5125 * Computed Names::              Computing the name of the variable to refer to.
5126 @end menu
5128 @node Substitution Refs, Computed Names, Advanced, Advanced
5129 @subsection Substitution References
5130 @cindex modified variable reference
5131 @cindex substitution variable reference
5132 @cindex variables, modified reference
5133 @cindex variables, substitution reference
5135 @cindex variables, substituting suffix in
5136 @cindex suffix, substituting in variables
5137 A @dfn{substitution reference} substitutes the value of a variable with
5138 alterations that you specify.  It has the form
5139 @samp{$(@var{var}:@var{a}=@var{b})} (or
5140 @samp{$@{@var{var}:@var{a}=@var{b}@}}) and its meaning is to take the value
5141 of the variable @var{var}, replace every @var{a} at the end of a word with
5142 @var{b} in that value, and substitute the resulting string.
5144 When we say ``at the end of a word'', we mean that @var{a} must appear
5145 either followed by whitespace or at the end of the value in order to be
5146 replaced; other occurrences of @var{a} in the value are unaltered.  For
5147 example:@refill
5149 @example
5150 foo := a.o b.o c.o
5151 bar := $(foo:.o=.c)
5152 @end example
5154 @noindent
5155 sets @samp{bar} to @samp{a.c b.c c.c}.  @xref{Setting, ,Setting Variables}.
5157 A substitution reference is actually an abbreviation for use of the
5158 @code{patsubst} expansion function (@pxref{Text Functions, ,Functions for String Substitution and Analysis}).  We provide
5159 substitution references as well as @code{patsubst} for compatibility with
5160 other implementations of @code{make}.
5162 @findex patsubst
5163 Another type of substitution reference lets you use the full power of
5164 the @code{patsubst} function.  It has the same form
5165 @samp{$(@var{var}:@var{a}=@var{b})} described above, except that now
5166 @var{a} must contain a single @samp{%} character.  This case is
5167 equivalent to @samp{$(patsubst @var{a},@var{b},$(@var{var}))}.
5168 @xref{Text Functions, ,Functions for String Substitution and Analysis},
5169 for a description of the @code{patsubst} function.@refill
5171 @example
5172 @group
5173 @exdent For example:
5175 foo := a.o b.o c.o
5176 bar := $(foo:%.o=%.c)
5177 @end group
5178 @end example
5180 @noindent
5181 sets @samp{bar} to @samp{a.c b.c c.c}.
5183 @node Computed Names,  , Substitution Refs, Advanced
5184 @subsection Computed Variable Names
5185 @cindex nested variable reference
5186 @cindex computed variable name
5187 @cindex variables, computed names
5188 @cindex variables, nested references
5189 @cindex variables, @samp{$} in name
5190 @cindex @code{$}, in variable name
5191 @cindex dollar sign (@code{$}), in variable name
5193 Computed variable names are a complicated concept needed only for
5194 sophisticated makefile programming.  For most purposes you need not
5195 consider them, except to know that making a variable with a dollar sign
5196 in its name might have strange results.  However, if you are the type
5197 that wants to understand everything, or you are actually interested in
5198 what they do, read on.
5200 Variables may be referenced inside the name of a variable.  This is
5201 called a @dfn{computed variable name} or a @dfn{nested variable
5202 reference}.  For example,
5204 @example
5205 x = y
5206 y = z
5207 a := $($(x))
5208 @end example
5210 @noindent
5211 defines @code{a} as @samp{z}: the @samp{$(x)} inside @samp{$($(x))} expands
5212 to @samp{y}, so @samp{$($(x))} expands to @samp{$(y)} which in turn expands
5213 to @samp{z}.  Here the name of the variable to reference is not stated
5214 explicitly; it is computed by expansion of @samp{$(x)}.  The reference
5215 @samp{$(x)} here is nested within the outer variable reference.
5217 The previous example shows two levels of nesting, but any number of levels
5218 is possible.  For example, here are three levels:
5220 @example
5221 x = y
5222 y = z
5223 z = u
5224 a := $($($(x)))
5225 @end example
5227 @noindent
5228 Here the innermost @samp{$(x)} expands to @samp{y}, so @samp{$($(x))}
5229 expands to @samp{$(y)} which in turn expands to @samp{z}; now we have
5230 @samp{$(z)}, which becomes @samp{u}.
5232 References to recursively-expanded variables within a variable name are
5233 reexpanded in the usual fashion.  For example:
5235 @example
5236 x = $(y)
5237 y = z
5238 z = Hello
5239 a := $($(x))
5240 @end example
5242 @noindent
5243 defines @code{a} as @samp{Hello}: @samp{$($(x))} becomes @samp{$($(y))}
5244 which becomes @samp{$(z)} which becomes @samp{Hello}.
5246 Nested variable references can also contain modified references and
5247 function invocations (@pxref{Functions, ,Functions for Transforming Text}),
5248 just like any other reference.
5249 For example, using the @code{subst} function
5250 (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
5252 @example
5253 @group
5254 x = variable1
5255 variable2 := Hello
5256 y = $(subst 1,2,$(x))
5257 z = y
5258 a := $($($(z)))
5259 @end group
5260 @end example
5262 @noindent
5263 eventually defines @code{a} as @samp{Hello}.  It is doubtful that anyone
5264 would ever want to write a nested reference as convoluted as this one, but
5265 it works: @samp{$($($(z)))} expands to @samp{$($(y))} which becomes
5266 @samp{$($(subst 1,2,$(x)))}.  This gets the value @samp{variable1} from
5267 @code{x} and changes it by substitution to @samp{variable2}, so that the
5268 entire string becomes @samp{$(variable2)}, a simple variable reference
5269 whose value is @samp{Hello}.@refill
5271 A computed variable name need not consist entirely of a single variable
5272 reference.  It can contain several variable references, as well as some
5273 invariant text.  For example,
5275 @example
5276 @group
5277 a_dirs := dira dirb
5278 1_dirs := dir1 dir2
5279 @end group
5281 @group
5282 a_files := filea fileb
5283 1_files := file1 file2
5284 @end group
5286 @group
5287 ifeq "$(use_a)" "yes"
5288 a1 := a
5289 else
5290 a1 := 1
5291 endif
5292 @end group
5294 @group
5295 ifeq "$(use_dirs)" "yes"
5296 df := dirs
5297 else
5298 df := files
5299 endif
5301 dirs := $($(a1)_$(df))
5302 @end group
5303 @end example
5305 @noindent
5306 will give @code{dirs} the same value as @code{a_dirs}, @code{1_dirs},
5307 @code{a_files} or @code{1_files} depending on the settings of @code{use_a}
5308 and @code{use_dirs}.@refill
5310 Computed variable names can also be used in substitution references:
5312 @example
5313 @group
5314 a_objects := a.o b.o c.o
5315 1_objects := 1.o 2.o 3.o
5317 sources := $($(a1)_objects:.o=.c)
5318 @end group
5319 @end example
5321 @noindent
5322 defines @code{sources} as either @samp{a.c b.c c.c} or @samp{1.c 2.c 3.c},
5323 depending on the value of @code{a1}.
5325 The only restriction on this sort of use of nested variable references
5326 is that they cannot specify part of the name of a function to be called.
5327 This is because the test for a recognized function name is done before
5328 the expansion of nested references.  For example,
5330 @example
5331 @group
5332 ifdef do_sort
5333 func := sort
5334 else
5335 func := strip
5336 endif
5337 @end group
5339 @group
5340 bar := a d b g q c
5341 @end group
5343 @group
5344 foo := $($(func) $(bar))
5345 @end group
5346 @end example
5348 @noindent
5349 attempts to give @samp{foo} the value of the variable @samp{sort a d b g
5350 q c} or @samp{strip a d b g q c}, rather than giving @samp{a d b g q c}
5351 as the argument to either the @code{sort} or the @code{strip} function.
5352 This restriction could be removed in the future if that change is shown
5353 to be a good idea.
5355 You can also use computed variable names in the left-hand side of a
5356 variable assignment, or in a @code{define} directive, as in:
5358 @example
5359 dir = foo
5360 $(dir)_sources := $(wildcard $(dir)/*.c)
5361 define $(dir)_print
5362 lpr $($(dir)_sources)
5363 endef
5364 @end example
5366 @noindent
5367 This example defines the variables @samp{dir}, @samp{foo_sources}, and
5368 @samp{foo_print}.
5370 Note that @dfn{nested variable references} are quite different from
5371 @dfn{recursively expanded variables}
5372 (@pxref{Flavors, ,The Two Flavors of Variables}), though both are
5373 used together in complex ways when doing makefile programming.@refill
5375 @node Values, Setting, Advanced, Using Variables
5376 @section How Variables Get Their Values
5377 @cindex variables, how they get their values
5378 @cindex value, how a variable gets it
5380 Variables can get values in several different ways:
5382 @itemize @bullet
5383 @item
5384 You can specify an overriding value when you run @code{make}.
5385 @xref{Overriding, ,Overriding Variables}.
5387 @item
5388 You can specify a value in the makefile, either
5389 with an assignment (@pxref{Setting, ,Setting Variables}) or with a
5390 verbatim definition (@pxref{Defining, ,Defining Variables Verbatim}).@refill
5392 @item
5393 Variables in the environment become @code{make} variables.
5394 @xref{Environment, ,Variables from the Environment}.
5396 @item
5397 Several @dfn{automatic} variables are given new values for each rule.
5398 Each of these has a single conventional use.
5399 @xref{Automatic Variables}.
5401 @item
5402 Several variables have constant initial values.
5403 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
5404 @end itemize
5406 @node Setting, Appending, Values, Using Variables
5407 @section Setting Variables
5408 @cindex setting variables
5409 @cindex variables, setting
5410 @cindex =
5411 @cindex :=
5412 @cindex ?=
5414 To set a variable from the makefile, write a line starting with the
5415 variable name followed by @samp{=} or @samp{:=}.  Whatever follows the
5416 @samp{=} or @samp{:=} on the line becomes the value.  For example,
5418 @example
5419 objects = main.o foo.o bar.o utils.o
5420 @end example
5422 @noindent
5423 defines a variable named @code{objects}.  Whitespace around the variable
5424 name and immediately after the @samp{=} is ignored.
5426 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
5427 Variables defined with @samp{:=} are @dfn{simply expanded} variables; these
5428 definitions can contain variable references which will be expanded before
5429 the definition is made.  @xref{Flavors, ,The Two Flavors of Variables}.
5431 The variable name may contain function and variable references, which
5432 are expanded when the line is read to find the actual variable name to use.
5434 There is no limit on the length of the value of a variable except the
5435 amount of swapping space on the computer.  When a variable definition is
5436 long, it is a good idea to break it into several lines by inserting
5437 backslash-newline at convenient places in the definition.  This will not
5438 affect the functioning of @code{make}, but it will make the makefile easier
5439 to read.
5441 Most variable names are considered to have the empty string as a value if
5442 you have never set them.  Several variables have built-in initial values
5443 that are not empty, but you can set them in the usual ways
5444 (@pxref{Implicit Variables, ,Variables Used by Implicit Rules}).
5445 Several special variables are set
5446 automatically to a new value for each rule; these are called the
5447 @dfn{automatic} variables (@pxref{Automatic Variables}).
5449 If you'd like a variable to be set to a value only if it's not already
5450 set, then you can use the shorthand operator @samp{?=} instead of
5451 @samp{=}.  These two settings of the variable @samp{FOO} are identical
5452 (@pxref{Origin Function, ,The @code{origin} Function}):
5454 @example
5455 FOO ?= bar
5456 @end example
5458 @noindent
5461 @example
5462 ifeq ($(origin FOO), undefined)
5463 FOO = bar
5464 endif
5465 @end example
5467 @node Appending, Override Directive, Setting, Using Variables
5468 @section Appending More Text to Variables
5469 @cindex +=
5470 @cindex appending to variables
5471 @cindex variables, appending to
5473 Often it is useful to add more text to the value of a variable already defined.
5474 You do this with a line containing @samp{+=}, like this:
5476 @example
5477 objects += another.o
5478 @end example
5480 @noindent
5481 This takes the value of the variable @code{objects}, and adds the text
5482 @samp{another.o} to it (preceded by a single space).  Thus:
5484 @example
5485 objects = main.o foo.o bar.o utils.o
5486 objects += another.o
5487 @end example
5489 @noindent
5490 sets @code{objects} to @samp{main.o foo.o bar.o utils.o another.o}.
5492 Using @samp{+=} is similar to:
5494 @example
5495 objects = main.o foo.o bar.o utils.o
5496 objects := $(objects) another.o
5497 @end example
5499 @noindent
5500 but differs in ways that become important when you use more complex values.
5502 When the variable in question has not been defined before, @samp{+=}
5503 acts just like normal @samp{=}: it defines a recursively-expanded
5504 variable.  However, when there @emph{is} a previous definition, exactly
5505 what @samp{+=} does depends on what flavor of variable you defined
5506 originally.  @xref{Flavors, ,The Two Flavors of Variables}, for an
5507 explanation of the two flavors of variables.
5509 When you add to a variable's value with @samp{+=}, @code{make} acts
5510 essentially as if you had included the extra text in the initial
5511 definition of the variable.  If you defined it first with @samp{:=},
5512 making it a simply-expanded variable, @samp{+=} adds to that
5513 simply-expanded definition, and expands the new text before appending it
5514 to the old value just as @samp{:=} does
5515 (see @ref{Setting, ,Setting Variables}, for a full explanation of @samp{:=}).
5516 In fact,
5518 @example
5519 variable := value
5520 variable += more
5521 @end example
5523 @noindent
5524 is exactly equivalent to:
5526 @noindent
5527 @example
5528 variable := value
5529 variable := $(variable) more
5530 @end example
5532 On the other hand, when you use @samp{+=} with a variable that you defined
5533 first to be recursively-expanded using plain @samp{=}, @code{make} does
5534 something a bit different.  Recall that when you define a
5535 recursively-expanded variable, @code{make} does not expand the value you set
5536 for variable and function references immediately.  Instead it stores the text
5537 verbatim, and saves these variable and function references to be expanded
5538 later, when you refer to the new variable (@pxref{Flavors, ,The Two Flavors
5539 of Variables}).  When you use @samp{+=} on a recursively-expanded variable,
5540 it is this unexpanded text to which @code{make} appends the new text you
5541 specify.
5543 @example
5544 @group
5545 variable = value
5546 variable += more
5547 @end group
5548 @end example
5550 @noindent
5551 is roughly equivalent to:
5553 @example
5554 @group
5555 temp = value
5556 variable = $(temp) more
5557 @end group
5558 @end example
5560 @noindent
5561 except that of course it never defines a variable called @code{temp}.
5562 The importance of this comes when the variable's old value contains
5563 variable references.  Take this common example:
5565 @example
5566 CFLAGS = $(includes) -O
5567 @dots{}
5568 CFLAGS += -pg # enable profiling
5569 @end example
5571 @noindent
5572 The first line defines the @code{CFLAGS} variable with a reference to another
5573 variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
5574 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
5575 Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
5576 variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
5577 @code{make} processes the definition of @code{CFLAGS}.  Thus, @code{includes}
5578 need not be defined yet for its value to take effect.  It only has to be
5579 defined before any reference to @code{CFLAGS}.  If we tried to append to the
5580 value of @code{CFLAGS} without using @samp{+=}, we might do it like this:
5582 @example
5583 CFLAGS := $(CFLAGS) -pg # enable profiling
5584 @end example
5586 @noindent
5587 This is pretty close, but not quite what we want.  Using @samp{:=}
5588 redefines @code{CFLAGS} as a simply-expanded variable; this means
5589 @code{make} expands the text @w{@samp{$(CFLAGS) -pg}} before setting the
5590 variable.  If @code{includes} is not yet defined, we get @w{@samp{ -O
5591 -pg}}, and a later definition of @code{includes} will have no effect.
5592 Conversely, by using @samp{+=} we set @code{CFLAGS} to the
5593 @emph{unexpanded} value @w{@samp{$(includes) -O -pg}}.  Thus we preserve
5594 the reference to @code{includes}, so if that variable gets defined at
5595 any later point, a reference like @samp{$(CFLAGS)} still uses its
5596 value.
5598 @node Override Directive, Defining, Appending, Using Variables
5599 @section The @code{override} Directive
5600 @findex override
5601 @cindex overriding with @code{override}
5602 @cindex variables, overriding
5604 If a variable has been set with a command argument
5605 (@pxref{Overriding, ,Overriding Variables}),
5606 then ordinary assignments in the makefile are ignored.  If you want to set
5607 the variable in the makefile even though it was set with a command
5608 argument, you can use an @code{override} directive, which is a line that
5609 looks like this:@refill
5611 @example
5612 override @var{variable} = @var{value}
5613 @end example
5615 @noindent
5618 @example
5619 override @var{variable} := @var{value}
5620 @end example
5622 To append more text to a variable defined on the command line, use:
5624 @example
5625 override @var{variable} += @var{more text}
5626 @end example
5628 @noindent
5629 @xref{Appending, ,Appending More Text to Variables}.
5631 The @code{override} directive was not invented for escalation in the war
5632 between makefiles and command arguments.  It was invented so you can alter
5633 and add to values that the user specifies with command arguments.
5635 For example, suppose you always want the @samp{-g} switch when you run the
5636 C compiler, but you would like to allow the user to specify the other
5637 switches with a command argument just as usual.  You could use this
5638 @code{override} directive:
5640 @example
5641 override CFLAGS += -g
5642 @end example
5644 You can also use @code{override} directives with @code{define} directives.
5645 This is done as you might expect:
5647 @example
5648 override define foo
5650 endef
5651 @end example
5653 @noindent
5654 @iftex
5655 See the next section for information about @code{define}.
5656 @end iftex
5657 @ifnottex
5658 @xref{Defining, ,Defining Variables Verbatim}.
5659 @end ifnottex
5661 @node Defining, Environment, Override Directive, Using Variables
5662 @section Defining Variables Verbatim
5663 @findex define
5664 @findex endef
5665 @cindex verbatim variable definition
5666 @cindex defining variables verbatim
5667 @cindex variables, defining verbatim
5669 Another way to set the value of a variable is to use the @code{define}
5670 directive.  This directive has an unusual syntax which allows newline
5671 characters to be included in the value, which is convenient for defining
5672 both canned sequences of commands
5673 (@pxref{Sequences, ,Defining Canned Command Sequences}), and also
5674 sections of makefile syntax to use with @code{eval} (@pxref{Eval Function}).
5676 The @code{define} directive is followed on the same line by the name of the
5677 variable and nothing more.  The value to give the variable appears on the
5678 following lines.  The end of the value is marked by a line containing just
5679 the word @code{endef}.  Aside from this difference in syntax, @code{define}
5680 works just like @samp{=}: it creates a recursively-expanded variable
5681 (@pxref{Flavors, ,The Two Flavors of Variables}).
5682 The variable name may contain function and variable references, which
5683 are expanded when the directive is read to find the actual variable name
5684 to use.
5686 You may nest @code{define} directives: @code{make} will keep track of
5687 nested directives and report an error if they are not all properly
5688 closed with @code{endef}.  Note that lines beginning with tab
5689 characters are considered part of a command script, so any
5690 @code{define} or @code{endef} strings appearing on such a line will
5691 not be considered @code{make} operators.
5693 @example
5694 define two-lines
5695 echo foo
5696 echo $(bar)
5697 endef
5698 @end example
5700 The value in an ordinary assignment cannot contain a newline; but the
5701 newlines that separate the lines of the value in a @code{define} become
5702 part of the variable's value (except for the final newline which precedes
5703 the @code{endef} and is not considered part of the value).@refill
5705 @need 800
5706 When used in a command script, the previous example is functionally
5707 equivalent to this:
5709 @example
5710 two-lines = echo foo; echo $(bar)
5711 @end example
5713 @noindent
5714 since two commands separated by semicolon behave much like two separate
5715 shell commands.  However, note that using two separate lines means
5716 @code{make} will invoke the shell twice, running an independent subshell
5717 for each line.  @xref{Execution, ,Command Execution}.
5719 If you want variable definitions made with @code{define} to take
5720 precedence over command-line variable definitions, you can use the
5721 @code{override} directive together with @code{define}:
5723 @example
5724 override define two-lines
5726 $(bar)
5727 endef
5728 @end example
5730 @noindent
5731 @xref{Override Directive, ,The @code{override} Directive}.
5733 @node Environment, Target-specific, Defining, Using Variables
5734 @section Variables from the Environment
5736 @cindex variables, environment
5737 @cindex environment
5738 Variables in @code{make} can come from the environment in which
5739 @code{make} is run.  Every environment variable that @code{make} sees
5740 when it starts up is transformed into a @code{make} variable with the
5741 same name and value.  However, an explicit assignment in the makefile,
5742 or with a command argument, overrides the environment.  (If the
5743 @samp{-e} flag is specified, then values from the environment override
5744 assignments in the makefile.  @xref{Options Summary, ,Summary of
5745 Options}.  But this is not recommended practice.)
5747 Thus, by setting the variable @code{CFLAGS} in your environment, you can
5748 cause all C compilations in most makefiles to use the compiler switches you
5749 prefer.  This is safe for variables with standard or conventional meanings
5750 because you know that no makefile will use them for other things.  (Note
5751 this is not totally reliable; some makefiles set @code{CFLAGS} explicitly
5752 and therefore are not affected by the value in the environment.)
5754 When @code{make} runs a command script, variables defined in the
5755 makefile are placed into the environment of that command.  This allows
5756 you to pass values to sub-@code{make} invocations (@pxref{Recursion,
5757 ,Recursive Use of @code{make}}).  By default, only variables that came
5758 from the environment or the command line are passed to recursive
5759 invocations.  You can use the @code{export} directive to pass other
5760 variables.  @xref{Variables/Recursion, , Communicating Variables to a
5761 Sub-@code{make}}, for full details.
5763 Other use of variables from the environment is not recommended.  It is not
5764 wise for makefiles to depend for their functioning on environment variables
5765 set up outside their control, since this would cause different users to get
5766 different results from the same makefile.  This is against the whole
5767 purpose of most makefiles.
5769 @cindex SHELL, import from environment
5770 Such problems would be especially likely with the variable
5771 @code{SHELL}, which is normally present in the environment to specify
5772 the user's choice of interactive shell.  It would be very undesirable
5773 for this choice to affect @code{make}; so, @code{make} handles the
5774 @code{SHELL} environment variable in a special way; see @ref{Choosing
5775 the Shell}.@refill
5777 @node Target-specific, Pattern-specific, Environment, Using Variables
5778 @section Target-specific Variable Values
5779 @cindex target-specific variables
5780 @cindex variables, target-specific
5782 Variable values in @code{make} are usually global; that is, they are the
5783 same regardless of where they are evaluated (unless they're reset, of
5784 course).  One exception to that is automatic variables
5785 (@pxref{Automatic Variables}).
5787 The other exception is @dfn{target-specific variable values}.  This
5788 feature allows you to define different values for the same variable,
5789 based on the target that @code{make} is currently building.  As with
5790 automatic variables, these values are only available within the context
5791 of a target's command script (and in other target-specific assignments).
5793 Set a target-specific variable value like this:
5795 @example
5796 @var{target} @dots{} : @var{variable-assignment}
5797 @end example
5799 @noindent
5800 or like this:
5802 @example
5803 @var{target} @dots{} : override @var{variable-assignment}
5804 @end example
5806 @noindent
5807 or like this:
5809 @example
5810 @var{target} @dots{} : export @var{variable-assignment}
5811 @end example
5813 Multiple @var{target} values create a target-specific variable value for
5814 each member of the target list individually.
5816 The @var{variable-assignment} can be any valid form of assignment;
5817 recursive (@samp{=}), static (@samp{:=}), appending (@samp{+=}), or
5818 conditional (@samp{?=}).  All variables that appear within the
5819 @var{variable-assignment} are evaluated within the context of the
5820 target: thus, any previously-defined target-specific variable values
5821 will be in effect.  Note that this variable is actually distinct from
5822 any ``global'' value: the two variables do not have to have the same
5823 flavor (recursive vs.@: static).
5825 Target-specific variables have the same priority as any other makefile
5826 variable.  Variables provided on the command-line (and in the
5827 environment if the @samp{-e} option is in force) will take precedence.
5828 Specifying the @code{override} directive will allow the target-specific
5829 variable value to be preferred.
5831 There is one more special feature of target-specific variables: when
5832 you define a target-specific variable that variable value is also in
5833 effect for all prerequisites of this target, and all their
5834 prerequisites, etc.@: (unless those prerequisites override that variable
5835 with their own target-specific variable value).  So, for example, a
5836 statement like this:
5838 @example
5839 prog : CFLAGS = -g
5840 prog : prog.o foo.o bar.o
5841 @end example
5843 @noindent
5844 will set @code{CFLAGS} to @samp{-g} in the command script for
5845 @file{prog}, but it will also set @code{CFLAGS} to @samp{-g} in the
5846 command scripts that create @file{prog.o}, @file{foo.o}, and
5847 @file{bar.o}, and any command scripts which create their
5848 prerequisites.
5850 Be aware that a given prerequisite will only be built once per
5851 invocation of make, at most.  If the same file is a prerequisite of
5852 multiple targets, and each of those targets has a different value for
5853 the same target-specific variable, then the first target to be built
5854 will cause that prerequisite to be built and the prerequisite will
5855 inherit the target-specific value from the first target.  It will
5856 ignore the target-specific values from any other targets.
5858 @node Pattern-specific,  , Target-specific, Using Variables
5859 @section Pattern-specific Variable Values
5860 @cindex pattern-specific variables
5861 @cindex variables, pattern-specific
5863 In addition to target-specific variable values
5864 (@pxref{Target-specific, ,Target-specific Variable Values}), GNU
5865 @code{make} supports pattern-specific variable values.  In this form,
5866 the variable is defined for any target that matches the pattern
5867 specified.  If a target matches more than one pattern, all the
5868 matching pattern-specific variables are interpreted in the order in
5869 which they were defined in the makefile, and collected together into
5870 one set.  Variables defined in this way are searched after any
5871 target-specific variables defined explicitly for that target, and
5872 before target-specific variables defined for the parent target.
5874 Set a pattern-specific variable value like this:
5876 @example
5877 @var{pattern} @dots{} : @var{variable-assignment}
5878 @end example
5880 @noindent
5881 or like this:
5883 @example
5884 @var{pattern} @dots{} : override @var{variable-assignment}
5885 @end example
5887 @noindent
5888 where @var{pattern} is a %-pattern.  As with target-specific variable
5889 values, multiple @var{pattern} values create a pattern-specific variable
5890 value for each pattern individually.  The @var{variable-assignment} can
5891 be any valid form of assignment.  Any command-line variable setting will
5892 take precedence, unless @code{override} is specified.
5894 For example:
5896 @example
5897 %.o : CFLAGS = -O
5898 @end example
5900 @noindent
5901 will assign @code{CFLAGS} the value of @samp{-O} for all targets
5902 matching the pattern @code{%.o}.
5904 @node Conditionals, Functions, Using Variables, Top
5905 @chapter Conditional Parts of Makefiles
5907 @cindex conditionals
5908 A @dfn{conditional} causes part of a makefile to be obeyed or ignored
5909 depending on the values of variables.  Conditionals can compare the
5910 value of one variable to another, or the value of a variable to
5911 a constant string.  Conditionals control what @code{make} actually
5912 ``sees'' in the makefile, so they @emph{cannot} be used to control shell
5913 commands at the time of execution.@refill
5915 @menu
5916 * Conditional Example::         Example of a conditional
5917 * Conditional Syntax::          The syntax of conditionals.
5918 * Testing Flags::               Conditionals that test flags.
5919 @end menu
5921 @node Conditional Example, Conditional Syntax, Conditionals, Conditionals
5922 @section Example of a Conditional
5924 The following example of a conditional tells @code{make} to use one set
5925 of libraries if the @code{CC} variable is @samp{gcc}, and a different
5926 set of libraries otherwise.  It works by controlling which of two
5927 command lines will be used as the command for a rule.  The result is
5928 that @samp{CC=gcc} as an argument to @code{make} changes not only which
5929 compiler is used but also which libraries are linked.
5931 @example
5932 libs_for_gcc = -lgnu
5933 normal_libs =
5935 foo: $(objects)
5936 ifeq ($(CC),gcc)
5937         $(CC) -o foo $(objects) $(libs_for_gcc)
5938 else
5939         $(CC) -o foo $(objects) $(normal_libs)
5940 endif
5941 @end example
5943 This conditional uses three directives: one @code{ifeq}, one @code{else}
5944 and one @code{endif}.
5946 The @code{ifeq} directive begins the conditional, and specifies the
5947 condition.  It contains two arguments, separated by a comma and surrounded
5948 by parentheses.  Variable substitution is performed on both arguments and
5949 then they are compared.  The lines of the makefile following the
5950 @code{ifeq} are obeyed if the two arguments match; otherwise they are
5951 ignored.
5953 The @code{else} directive causes the following lines to be obeyed if the
5954 previous conditional failed.  In the example above, this means that the
5955 second alternative linking command is used whenever the first alternative
5956 is not used.  It is optional to have an @code{else} in a conditional.
5958 The @code{endif} directive ends the conditional.  Every conditional must
5959 end with an @code{endif}.  Unconditional makefile text follows.
5961 As this example illustrates, conditionals work at the textual level:
5962 the lines of the conditional are treated as part of the makefile, or
5963 ignored, according to the condition.  This is why the larger syntactic
5964 units of the makefile, such as rules, may cross the beginning or the
5965 end of the conditional.
5967 When the variable @code{CC} has the value @samp{gcc}, the above example has
5968 this effect:
5970 @example
5971 foo: $(objects)
5972         $(CC) -o foo $(objects) $(libs_for_gcc)
5973 @end example
5975 @noindent
5976 When the variable @code{CC} has any other value, the effect is this:
5978 @example
5979 foo: $(objects)
5980         $(CC) -o foo $(objects) $(normal_libs)
5981 @end example
5983 Equivalent results can be obtained in another way by conditionalizing a
5984 variable assignment and then using the variable unconditionally:
5986 @example
5987 libs_for_gcc = -lgnu
5988 normal_libs =
5990 ifeq ($(CC),gcc)
5991   libs=$(libs_for_gcc)
5992 else
5993   libs=$(normal_libs)
5994 endif
5996 foo: $(objects)
5997         $(CC) -o foo $(objects) $(libs)
5998 @end example
6000 @node Conditional Syntax, Testing Flags, Conditional Example, Conditionals
6001 @section Syntax of Conditionals
6002 @findex ifdef
6003 @findex ifeq
6004 @findex ifndef
6005 @findex ifneq
6006 @findex else
6007 @findex endif
6009 The syntax of a simple conditional with no @code{else} is as follows:
6011 @example
6012 @var{conditional-directive}
6013 @var{text-if-true}
6014 endif
6015 @end example
6017 @noindent
6018 The @var{text-if-true} may be any lines of text, to be considered as part
6019 of the makefile if the condition is true.  If the condition is false, no
6020 text is used instead.
6022 The syntax of a complex conditional is as follows:
6024 @example
6025 @var{conditional-directive}
6026 @var{text-if-true}
6027 else
6028 @var{text-if-false}
6029 endif
6030 @end example
6034 @example
6035 @var{conditional-directive}
6036 @var{text-if-one-is-true}
6037 else @var{conditional-directive}
6038 @var{text-if-true}
6039 else
6040 @var{text-if-false}
6041 endif
6042 @end example
6044 @noindent
6045 There can be as many ``@code{else} @var{conditional-directive}''
6046 clauses as necessary.  Once a given condition is true,
6047 @var{text-if-true} is used and no other clause is used; if no
6048 condition is true then @var{text-if-false} is used.  The
6049 @var{text-if-true} and @var{text-if-false} can be any number of lines
6050 of text.
6052 The syntax of the @var{conditional-directive} is the same whether the
6053 conditional is simple or complex; after an @code{else} or not.  There
6054 are four different directives that test different conditions.  Here is
6055 a table of them:
6057 @table @code
6058 @item ifeq (@var{arg1}, @var{arg2})
6059 @itemx ifeq '@var{arg1}' '@var{arg2}'
6060 @itemx ifeq "@var{arg1}" "@var{arg2}"
6061 @itemx ifeq "@var{arg1}" '@var{arg2}'
6062 @itemx ifeq '@var{arg1}' "@var{arg2}"
6063 Expand all variable references in @var{arg1} and @var{arg2} and
6064 compare them.  If they are identical, the @var{text-if-true} is
6065 effective; otherwise, the @var{text-if-false}, if any, is effective.
6067 Often you want to test if a variable has a non-empty value.  When the
6068 value results from complex expansions of variables and functions,
6069 expansions you would consider empty may actually contain whitespace
6070 characters and thus are not seen as empty.  However, you can use the
6071 @code{strip} function (@pxref{Text Functions}) to avoid interpreting
6072 whitespace as a non-empty value.  For example:
6074 @example
6075 @group
6076 ifeq ($(strip $(foo)),)
6077 @var{text-if-empty}
6078 endif
6079 @end group
6080 @end example
6082 @noindent
6083 will evaluate @var{text-if-empty} even if the expansion of
6084 @code{$(foo)} contains whitespace characters.
6086 @item ifneq (@var{arg1}, @var{arg2})
6087 @itemx ifneq '@var{arg1}' '@var{arg2}'
6088 @itemx ifneq "@var{arg1}" "@var{arg2}"
6089 @itemx ifneq "@var{arg1}" '@var{arg2}'
6090 @itemx ifneq '@var{arg1}' "@var{arg2}"
6091 Expand all variable references in @var{arg1} and @var{arg2} and
6092 compare them.  If they are different, the @var{text-if-true} is
6093 effective; otherwise, the @var{text-if-false}, if any, is effective.
6095 @item ifdef @var{variable-name}
6096 The @code{ifdef} form takes the @emph{name} of a variable as its
6097 argument, not a reference to a variable.  The value of that variable
6098 has a non-empty value, the @var{text-if-true} is effective; otherwise,
6099 the @var{text-if-false}, if any, is effective.  Variables that have
6100 never been defined have an empty value.  The text @var{variable-name}
6101 is expanded, so it could be a variable or function that expands
6102 to the name of a variable.  For example:
6104 @example
6105 bar = true
6106 foo = bar
6107 ifdef $(foo)
6108 frobozz = yes
6109 endif
6110 @end example
6112 The variable reference @code{$(foo)} is expanded, yielding @code{bar},
6113 which is considered to be the name of a variable.  The variable
6114 @code{bar} is not expanded, but its value is examined to determine if
6115 it is non-empty.
6117 Note that @code{ifdef} only tests whether a variable has a value.  It
6118 does not expand the variable to see if that value is nonempty.
6119 Consequently, tests using @code{ifdef} return true for all definitions
6120 except those like @code{foo =}.  To test for an empty value, use
6121 @w{@code{ifeq ($(foo),)}}.  For example,
6123 @example
6124 bar =
6125 foo = $(bar)
6126 ifdef foo
6127 frobozz = yes
6128 else
6129 frobozz = no
6130 endif
6131 @end example
6133 @noindent
6134 sets @samp{frobozz} to @samp{yes}, while:
6136 @example
6137 foo =
6138 ifdef foo
6139 frobozz = yes
6140 else
6141 frobozz = no
6142 endif
6143 @end example
6145 @noindent
6146 sets @samp{frobozz} to @samp{no}.
6148 @item ifndef @var{variable-name}
6149 If the variable @var{variable-name} has an empty value, the
6150 @var{text-if-true} is effective; otherwise, the @var{text-if-false},
6151 if any, is effective.  The rules for expansion and testing of
6152 @var{variable-name} are identical to the @code{ifdef} directive.
6153 @end table
6155 Extra spaces are allowed and ignored at the beginning of the conditional
6156 directive line, but a tab is not allowed.  (If the line begins with a tab,
6157 it will be considered a command for a rule.)  Aside from this, extra spaces
6158 or tabs may be inserted with no effect anywhere except within the directive
6159 name or within an argument.  A comment starting with @samp{#} may appear at
6160 the end of the line.
6162 The other two directives that play a part in a conditional are @code{else}
6163 and @code{endif}.  Each of these directives is written as one word, with no
6164 arguments.  Extra spaces are allowed and ignored at the beginning of the
6165 line, and spaces or tabs at the end.  A comment starting with @samp{#} may
6166 appear at the end of the line.
6168 Conditionals affect which lines of the makefile @code{make} uses.  If
6169 the condition is true, @code{make} reads the lines of the
6170 @var{text-if-true} as part of the makefile; if the condition is false,
6171 @code{make} ignores those lines completely.  It follows that syntactic
6172 units of the makefile, such as rules, may safely be split across the
6173 beginning or the end of the conditional.@refill
6175 @code{make} evaluates conditionals when it reads a makefile.
6176 Consequently, you cannot use automatic variables in the tests of
6177 conditionals because they are not defined until commands are run
6178 (@pxref{Automatic Variables}).
6180 To prevent intolerable confusion, it is not permitted to start a
6181 conditional in one makefile and end it in another.  However, you may
6182 write an @code{include} directive within a conditional, provided you do
6183 not attempt to terminate the conditional inside the included file.
6185 @node Testing Flags,  , Conditional Syntax, Conditionals
6186 @section Conditionals that Test Flags
6188 You can write a conditional that tests @code{make} command flags such as
6189 @samp{-t} by using the variable @code{MAKEFLAGS} together with the
6190 @code{findstring} function
6191 (@pxref{Text Functions, , Functions for String Substitution and Analysis}).
6192 This is useful when @code{touch} is not enough to make a file appear up
6193 to date.
6195 The @code{findstring} function determines whether one string appears as a
6196 substring of another.  If you want to test for the @samp{-t} flag,
6197 use @samp{t} as the first string and the value of @code{MAKEFLAGS} as
6198 the other.
6200 For example, here is how to arrange to use @samp{ranlib -t} to finish
6201 marking an archive file up to date:
6203 @example
6204 archive.a: @dots{}
6205 ifneq (,$(findstring t,$(MAKEFLAGS)))
6206         +touch archive.a
6207         +ranlib -t archive.a
6208 else
6209         ranlib archive.a
6210 endif
6211 @end example
6213 @noindent
6214 The @samp{+} prefix marks those command lines as ``recursive'' so
6215 that they will be executed despite use of the @samp{-t} flag.
6216 @xref{Recursion, ,Recursive Use of @code{make}}.
6218 @node Functions, Running, Conditionals, Top
6219 @chapter Functions for Transforming Text
6220 @cindex functions
6222 @dfn{Functions} allow you to do text processing in the makefile to compute
6223 the files to operate on or the commands to use.  You use a function in a
6224 @dfn{function call}, where you give the name of the function and some text
6225 (the @dfn{arguments}) for the function to operate on.  The result of the
6226 function's processing is substituted into the makefile at the point of the
6227 call, just as a variable might be substituted.
6229 @menu
6230 * Syntax of Functions::         How to write a function call.
6231 * Text Functions::              General-purpose text manipulation functions.
6232 * File Name Functions::         Functions for manipulating file names.
6233 * Conditional Functions::       Functions that implement conditions.
6234 * Foreach Function::            Repeat some text with controlled variation.
6235 * Call Function::               Expand a user-defined function.
6236 * Value Function::              Return the un-expanded value of a variable.
6237 * Eval Function::               Evaluate the arguments as makefile syntax.
6238 * Origin Function::             Find where a variable got its value.
6239 * Flavor Function::             Find out the flavor of a variable.
6240 * Shell Function::              Substitute the output of a shell command.
6241 * Make Control Functions::      Functions that control how make runs.
6242 @end menu
6244 @node Syntax of Functions, Text Functions, Functions, Functions
6245 @section Function Call Syntax
6246 @cindex @code{$}, in function call
6247 @cindex dollar sign (@code{$}), in function call
6248 @cindex arguments of functions
6249 @cindex functions, syntax of
6251 A function call resembles a variable reference.  It looks like this:
6253 @example
6254 $(@var{function} @var{arguments})
6255 @end example
6257 @noindent
6258 or like this:
6260 @example
6261 $@{@var{function} @var{arguments}@}
6262 @end example
6264 Here @var{function} is a function name; one of a short list of names
6265 that are part of @code{make}.  You can also essentially create your own
6266 functions by using the @code{call} builtin function.
6268 The @var{arguments} are the arguments of the function.  They are
6269 separated from the function name by one or more spaces or tabs, and if
6270 there is more than one argument, then they are separated by commas.
6271 Such whitespace and commas are not part of an argument's value.  The
6272 delimiters which you use to surround the function call, whether
6273 parentheses or braces, can appear in an argument only in matching pairs;
6274 the other kind of delimiters may appear singly.  If the arguments
6275 themselves contain other function calls or variable references, it is
6276 wisest to use the same kind of delimiters for all the references; write
6277 @w{@samp{$(subst a,b,$(x))}}, not @w{@samp{$(subst a,b,$@{x@})}}.  This
6278 is because it is clearer, and because only one type of delimiter is
6279 matched to find the end of the reference.
6281 The text written for each argument is processed by substitution of
6282 variables and function calls to produce the argument value, which
6283 is the text on which the function acts.  The substitution is done in the
6284 order in which the arguments appear.
6286 Commas and unmatched parentheses or braces cannot appear in the text of an
6287 argument as written; leading spaces cannot appear in the text of the first
6288 argument as written.  These characters can be put into the argument value
6289 by variable substitution.  First define variables @code{comma} and
6290 @code{space} whose values are isolated comma and space characters, then
6291 substitute these variables where such characters are wanted, like this:
6293 @example
6294 @group
6295 comma:= ,
6296 empty:=
6297 space:= $(empty) $(empty)
6298 foo:= a b c
6299 bar:= $(subst $(space),$(comma),$(foo))
6300 # @r{bar is now `a,b,c'.}
6301 @end group
6302 @end example
6304 @noindent
6305 Here the @code{subst} function replaces each space with a comma, through
6306 the value of @code{foo}, and substitutes the result.
6308 @node Text Functions, File Name Functions, Syntax of Functions, Functions
6309 @section Functions for String Substitution and Analysis
6310 @cindex functions, for text
6312 Here are some functions that operate on strings:
6314 @table @code
6315 @item $(subst @var{from},@var{to},@var{text})
6316 @findex subst
6317 Performs a textual replacement on the text @var{text}: each occurrence
6318 of @var{from} is replaced by @var{to}.  The result is substituted for
6319 the function call.  For example,
6321 @example
6322 $(subst ee,EE,feet on the street)
6323 @end example
6325 substitutes the string @samp{fEEt on the strEEt}.
6327 @item $(patsubst @var{pattern},@var{replacement},@var{text})
6328 @findex patsubst
6329 Finds whitespace-separated words in @var{text} that match
6330 @var{pattern} and replaces them with @var{replacement}.  Here
6331 @var{pattern} may contain a @samp{%} which acts as a wildcard,
6332 matching any number of any characters within a word.  If
6333 @var{replacement} also contains a @samp{%}, the @samp{%} is replaced
6334 by the text that matched the @samp{%} in @var{pattern}.  Only the first
6335 @samp{%} in the @var{pattern} and @var{replacement} is treated this
6336 way; any subsequent @samp{%} is unchanged.@refill
6338 @cindex @code{%}, quoting in @code{patsubst}
6339 @cindex @code{%}, quoting with @code{\} (backslash)
6340 @cindex @code{\} (backslash), to quote @code{%}
6341 @cindex backslash (@code{\}), to quote @code{%}
6342 @cindex quoting @code{%}, in @code{patsubst}
6343 @samp{%} characters in @code{patsubst} function invocations can be
6344 quoted with preceding backslashes (@samp{\}).  Backslashes that would
6345 otherwise quote @samp{%} characters can be quoted with more backslashes.
6346 Backslashes that quote @samp{%} characters or other backslashes are
6347 removed from the pattern before it is compared file names or has a stem
6348 substituted into it.  Backslashes that are not in danger of quoting
6349 @samp{%} characters go unmolested.  For example, the pattern
6350 @file{the\%weird\\%pattern\\} has @samp{the%weird\} preceding the
6351 operative @samp{%} character, and @samp{pattern\\} following it.  The
6352 final two backslashes are left alone because they cannot affect any
6353 @samp{%} character.@refill
6355 Whitespace between words is folded into single space characters;
6356 leading and trailing whitespace is discarded.
6358 For example,
6360 @example
6361 $(patsubst %.c,%.o,x.c.c bar.c)
6362 @end example
6364 @noindent
6365 produces the value @samp{x.c.o bar.o}.
6367 Substitution references (@pxref{Substitution Refs, ,Substitution
6368 References}) are a simpler way to get the effect of the @code{patsubst}
6369 function:
6371 @example
6372 $(@var{var}:@var{pattern}=@var{replacement})
6373 @end example
6375 @noindent
6376 is equivalent to
6378 @example
6379 $(patsubst @var{pattern},@var{replacement},$(@var{var}))
6380 @end example
6382 The second shorthand simplifies one of the most common uses of
6383 @code{patsubst}: replacing the suffix at the end of file names.
6385 @example
6386 $(@var{var}:@var{suffix}=@var{replacement})
6387 @end example
6389 @noindent
6390 is equivalent to
6392 @example
6393 $(patsubst %@var{suffix},%@var{replacement},$(@var{var}))
6394 @end example
6396 @noindent
6397 For example, you might have a list of object files:
6399 @example
6400 objects = foo.o bar.o baz.o
6401 @end example
6403 @noindent
6404 To get the list of corresponding source files, you could simply write:
6406 @example
6407 $(objects:.o=.c)
6408 @end example
6410 @noindent
6411 instead of using the general form:
6413 @example
6414 $(patsubst %.o,%.c,$(objects))
6415 @end example
6417 @item $(strip @var{string})
6418 @cindex stripping whitespace
6419 @cindex whitespace, stripping
6420 @cindex spaces, stripping
6421 @findex strip
6422 Removes leading and trailing whitespace from @var{string} and replaces
6423 each internal sequence of one or more whitespace characters with a
6424 single space.  Thus, @samp{$(strip a b  c )} results in @w{@samp{a b c}}.
6426 The function @code{strip} can be very useful when used in conjunction
6427 with conditionals.  When comparing something with the empty string
6428 @samp{} using @code{ifeq} or @code{ifneq}, you usually want a string of
6429 just whitespace to match the empty string (@pxref{Conditionals}).
6431 Thus, the following may fail to have the desired results:
6433 @example
6434 .PHONY: all
6435 ifneq   "$(needs_made)" ""
6436 all: $(needs_made)
6437 else
6438 all:;@@echo 'Nothing to make!'
6439 endif
6440 @end example
6442 @noindent
6443 Replacing the variable reference @w{@samp{$(needs_made)}} with the
6444 function call @w{@samp{$(strip $(needs_made))}} in the @code{ifneq}
6445 directive would make it more robust.@refill
6447 @item $(findstring @var{find},@var{in})
6448 @findex findstring
6449 @cindex searching for strings
6450 @cindex finding strings
6451 @cindex strings, searching for
6452 Searches @var{in} for an occurrence of @var{find}.  If it occurs, the
6453 value is @var{find}; otherwise, the value is empty.  You can use this
6454 function in a conditional to test for the presence of a specific
6455 substring in a given string.  Thus, the two examples,
6457 @example
6458 $(findstring a,a b c)
6459 $(findstring a,b c)
6460 @end example
6462 @noindent
6463 produce the values @samp{a} and @samp{} (the empty string),
6464 respectively.  @xref{Testing Flags}, for a practical application of
6465 @code{findstring}.@refill
6467 @need 750
6468 @findex filter
6469 @cindex filtering words
6470 @cindex words, filtering
6471 @item $(filter @var{pattern}@dots{},@var{text})
6472 Returns all whitespace-separated words in @var{text} that @emph{do} match
6473 any of the @var{pattern} words, removing any words that @emph{do not}
6474 match.  The patterns are written using @samp{%}, just like the patterns
6475 used in the @code{patsubst} function above.@refill
6477 The @code{filter} function can be used to separate out different types
6478 of strings (such as file names) in a variable.  For example:
6480 @example
6481 sources := foo.c bar.c baz.s ugh.h
6482 foo: $(sources)
6483         cc $(filter %.c %.s,$(sources)) -o foo
6484 @end example
6486 @noindent
6487 says that @file{foo} depends of @file{foo.c}, @file{bar.c},
6488 @file{baz.s} and @file{ugh.h} but only @file{foo.c}, @file{bar.c} and
6489 @file{baz.s} should be specified in the command to the
6490 compiler.@refill
6492 @item $(filter-out @var{pattern}@dots{},@var{text})
6493 @findex filter-out
6494 @cindex filtering out words
6495 @cindex words, filtering out
6496 Returns all whitespace-separated words in @var{text} that @emph{do not}
6497 match any of the @var{pattern} words, removing the words that @emph{do}
6498 match one or more.  This is the exact opposite of the @code{filter}
6499 function.@refill
6501 For example, given:
6503 @example
6504 @group
6505 objects=main1.o foo.o main2.o bar.o
6506 mains=main1.o main2.o
6507 @end group
6508 @end example
6510 @noindent
6511 the following generates a list which contains all the object files not
6512 in @samp{mains}:
6514 @example
6515 $(filter-out $(mains),$(objects))
6516 @end example
6518 @need 1500
6519 @findex sort
6520 @cindex sorting words
6521 @item $(sort @var{list})
6522 Sorts the words of @var{list} in lexical order, removing duplicate
6523 words.  The output is a list of words separated by single spaces.
6524 Thus,
6526 @example
6527 $(sort foo bar lose)
6528 @end example
6530 @noindent
6531 returns the value @samp{bar foo lose}.
6533 @cindex removing duplicate words
6534 @cindex duplicate words, removing
6535 @cindex words, removing duplicates
6536 Incidentally, since @code{sort} removes duplicate words, you can use
6537 it for this purpose even if you don't care about the sort order.
6539 @item $(word @var{n},@var{text})
6540 @findex word
6541 @cindex word, selecting a
6542 @cindex selecting a word
6543 Returns the @var{n}th word of @var{text}.  The legitimate values of
6544 @var{n} start from 1.  If @var{n} is bigger than the number of words
6545 in @var{text}, the value is empty.  For example,
6547 @example
6548 $(word 2, foo bar baz)
6549 @end example
6551 @noindent
6552 returns @samp{bar}.
6554 @item $(wordlist @var{s},@var{e},@var{text})
6555 @findex wordlist
6556 @cindex words, selecting lists of
6557 @cindex selecting word lists
6558 Returns the list of words in @var{text} starting with word @var{s} and
6559 ending with word @var{e} (inclusive).  The legitimate values of @var{s}
6560 start from 1; @var{e} may start from 0.  If @var{s} is bigger than the
6561 number of words in @var{text}, the value is empty.  If @var{e} is
6562 bigger than the number of words in @var{text}, words up to the end of
6563 @var{text} are returned.  If @var{s} is greater than @var{e}, nothing
6564 is returned.  For example,
6566 @example
6567 $(wordlist 2, 3, foo bar baz)
6568 @end example
6570 @noindent
6571 returns @samp{bar baz}.
6573 @c Following item phrased to prevent overfull hbox.  --RJC 17 Jul 92
6574 @item $(words @var{text})
6575 @findex words
6576 @cindex words, finding number
6577 Returns the number of words in @var{text}.
6578 Thus, the last word of @var{text} is
6579 @w{@code{$(word $(words @var{text}),@var{text})}}.@refill
6581 @item $(firstword @var{names}@dots{})
6582 @findex firstword
6583 @cindex words, extracting first
6584 The argument @var{names} is regarded as a series of names, separated
6585 by whitespace.  The value is the first name in the series.  The rest
6586 of the names are ignored.
6588 For example,
6590 @example
6591 $(firstword foo bar)
6592 @end example
6594 @noindent
6595 produces the result @samp{foo}.  Although @code{$(firstword
6596 @var{text})} is the same as @code{$(word 1,@var{text})}, the
6597 @code{firstword} function is retained for its simplicity.@refill
6600 @item $(lastword @var{names}@dots{})
6601 @findex lastword
6602 @cindex words, extracting last
6603 The argument @var{names} is regarded as a series of names, separated
6604 by whitespace.  The value is the last name in the series.
6606 For example,
6608 @example
6609 $(lastword foo bar)
6610 @end example
6612 @noindent
6613 produces the result @samp{bar}.  Although @code{$(lastword
6614 @var{text})} is the same as @code{$(word $(words @var{text}),@var{text})},
6615 the @code{lastword} function was added for its simplicity and better
6616 performance.@refill
6617 @end table
6620 Here is a realistic example of the use of @code{subst} and
6621 @code{patsubst}.  Suppose that a makefile uses the @code{VPATH} variable
6622 to specify a list of directories that @code{make} should search for
6623 prerequisite files
6624 (@pxref{General Search, , @code{VPATH} Search Path for All Prerequisites}).
6625 This example shows how to
6626 tell the C compiler to search for header files in the same list of
6627 directories.@refill
6629 The value of @code{VPATH} is a list of directories separated by colons,
6630 such as @samp{src:../headers}.  First, the @code{subst} function is used to
6631 change the colons to spaces:
6633 @example
6634 $(subst :, ,$(VPATH))
6635 @end example
6637 @noindent
6638 This produces @samp{src ../headers}.  Then @code{patsubst} is used to turn
6639 each directory name into a @samp{-I} flag.  These can be added to the
6640 value of the variable @code{CFLAGS}, which is passed automatically to the C
6641 compiler, like this:
6643 @example
6644 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
6645 @end example
6647 @noindent
6648 The effect is to append the text @samp{-Isrc -I../headers} to the
6649 previously given value of @code{CFLAGS}.  The @code{override} directive is
6650 used so that the new value is assigned even if the previous value of
6651 @code{CFLAGS} was specified with a command argument (@pxref{Override
6652 Directive, , The @code{override} Directive}).
6654 @node File Name Functions, Conditional Functions, Text Functions, Functions
6655 @section Functions for File Names
6656 @cindex functions, for file names
6657 @cindex file name functions
6659 Several of the built-in expansion functions relate specifically to
6660 taking apart file names or lists of file names.
6662 Each of the following functions performs a specific transformation on a
6663 file name.  The argument of the function is regarded as a series of file
6664 names, separated by whitespace.  (Leading and trailing whitespace is
6665 ignored.)  Each file name in the series is transformed in the same way and
6666 the results are concatenated with single spaces between them.
6668 @table @code
6669 @item $(dir @var{names}@dots{})
6670 @findex dir
6671 @cindex directory part
6672 @cindex file name, directory part
6673 Extracts the directory-part of each file name in @var{names}.  The
6674 directory-part of the file name is everything up through (and
6675 including) the last slash in it.  If the file name contains no slash,
6676 the directory part is the string @samp{./}.  For example,
6678 @example
6679 $(dir src/foo.c hacks)
6680 @end example
6682 @noindent
6683 produces the result @samp{src/ ./}.
6685 @item $(notdir @var{names}@dots{})
6686 @findex notdir
6687 @cindex file name, nondirectory part
6688 @cindex nondirectory part
6689 Extracts all but the directory-part of each file name in @var{names}.
6690 If the file name contains no slash, it is left unchanged.  Otherwise,
6691 everything through the last slash is removed from it.
6693 A file name that ends with a slash becomes an empty string.  This is
6694 unfortunate, because it means that the result does not always have the
6695 same number of whitespace-separated file names as the argument had;
6696 but we do not see any other valid alternative.
6698 For example,
6700 @example
6701 $(notdir src/foo.c hacks)
6702 @end example
6704 @noindent
6705 produces the result @samp{foo.c hacks}.
6707 @item $(suffix @var{names}@dots{})
6708 @findex suffix
6709 @cindex suffix, function to find
6710 @cindex file name suffix
6711 Extracts the suffix of each file name in @var{names}.  If the file name
6712 contains a period, the suffix is everything starting with the last
6713 period.  Otherwise, the suffix is the empty string.  This frequently
6714 means that the result will be empty when @var{names} is not, and if
6715 @var{names} contains multiple file names, the result may contain fewer
6716 file names.
6718 For example,
6720 @example
6721 $(suffix src/foo.c src-1.0/bar.c hacks)
6722 @end example
6724 @noindent
6725 produces the result @samp{.c .c}.
6727 @item $(basename @var{names}@dots{})
6728 @findex basename
6729 @cindex basename
6730 @cindex file name, basename of
6731 Extracts all but the suffix of each file name in @var{names}.  If the
6732 file name contains a period, the basename is everything starting up to
6733 (and not including) the last period.  Periods in the directory part are
6734 ignored.  If there is no period, the basename is the entire file name.
6735 For example,
6737 @example
6738 $(basename src/foo.c src-1.0/bar hacks)
6739 @end example
6741 @noindent
6742 produces the result @samp{src/foo src-1.0/bar hacks}.
6744 @c plural convention with dots (be consistent)
6745 @item $(addsuffix @var{suffix},@var{names}@dots{})
6746 @findex addsuffix
6747 @cindex suffix, adding
6748 @cindex file name suffix, adding
6749 The argument @var{names} is regarded as a series of names, separated
6750 by whitespace; @var{suffix} is used as a unit.  The value of
6751 @var{suffix} is appended to the end of each individual name and the
6752 resulting larger names are concatenated with single spaces between
6753 them.  For example,
6755 @example
6756 $(addsuffix .c,foo bar)
6757 @end example
6759 @noindent
6760 produces the result @samp{foo.c bar.c}.
6762 @item $(addprefix @var{prefix},@var{names}@dots{})
6763 @findex addprefix
6764 @cindex prefix, adding
6765 @cindex file name prefix, adding
6766 The argument @var{names} is regarded as a series of names, separated
6767 by whitespace; @var{prefix} is used as a unit.  The value of
6768 @var{prefix} is prepended to the front of each individual name and the
6769 resulting larger names are concatenated with single spaces between
6770 them.  For example,
6772 @example
6773 $(addprefix src/,foo bar)
6774 @end example
6776 @noindent
6777 produces the result @samp{src/foo src/bar}.
6779 @item $(join @var{list1},@var{list2})
6780 @findex join
6781 @cindex joining lists of words
6782 @cindex words, joining lists
6783 Concatenates the two arguments word by word: the two first words (one
6784 from each argument) concatenated form the first word of the result, the
6785 two second words form the second word of the result, and so on.  So the
6786 @var{n}th word of the result comes from the @var{n}th word of each
6787 argument.  If one argument has more words that the other, the extra
6788 words are copied unchanged into the result.
6790 For example, @samp{$(join a b,.c .o)} produces @samp{a.c b.o}.
6792 Whitespace between the words in the lists is not preserved; it is
6793 replaced with a single space.
6795 This function can merge the results of the @code{dir} and
6796 @code{notdir} functions, to produce the original list of files which
6797 was given to those two functions.@refill
6799 @item $(wildcard @var{pattern})
6800 @findex wildcard
6801 @cindex wildcard, function
6802 The argument @var{pattern} is a file name pattern, typically containing
6803 wildcard characters (as in shell file name patterns).  The result of
6804 @code{wildcard} is a space-separated list of the names of existing files
6805 that match the pattern.
6806 @xref{Wildcards, ,Using Wildcard Characters in File Names}.
6808 @item $(realpath @var{names}@dots{})
6809 @findex realpath
6810 @cindex realpath
6811 @cindex file name, realpath of
6812 For each file name in @var{names} return the canonical absolute name.
6813 A canonical name does not contain any @code{.} or @code{..} components,
6814 nor any repeated path separators (@code{/}) or symlinks.  In case of a
6815 failure the empty string is returned.  Consult the @code{realpath(3)}
6816 documentation for a list of possible failure causes.
6818 @item $(abspath @var{names}@dots{})
6819 @findex abspath
6820 @cindex abspath
6821 @cindex file name, abspath of
6822 For each file name in @var{names} return an absolute name that does
6823 not contain any @code{.} or @code{..} components, nor any repeated path
6824 separators (@code{/}).  Note that, in contrast to @code{realpath}
6825 function, @code{abspath} does not resolve symlinks and does not require
6826 the file names to refer to an existing file or directory.  Use the
6827 @code{wildcard} function to test for existence.
6828 @end table
6830 @node Conditional Functions, Foreach Function, File Name Functions, Functions
6831 @section Functions for Conditionals
6832 @findex if
6833 @cindex conditional expansion
6834 There are three functions that provide conditional expansion.  A key
6835 aspect of these functions is that not all of the arguments are
6836 expanded initially.  Only those arguments which need to be expanded,
6837 will be expanded.
6839 @table @code
6840 @item $(if @var{condition},@var{then-part}[,@var{else-part}])
6841 @findex if
6842 The @code{if} function provides support for conditional expansion in a
6843 functional context (as opposed to the GNU @code{make} makefile
6844 conditionals such as @code{ifeq} (@pxref{Conditional Syntax, ,Syntax of
6845 Conditionals}).
6847 The first argument, @var{condition}, first has all preceding and
6848 trailing whitespace stripped, then is expanded.  If it expands to any
6849 non-empty string, then the condition is considered to be true.  If it
6850 expands to an empty string, the condition is considered to be false.
6852 If the condition is true then the second argument, @var{then-part}, is
6853 evaluated and this is used as the result of the evaluation of the entire
6854 @code{if} function.
6856 If the condition is false then the third argument, @var{else-part}, is
6857 evaluated and this is the result of the @code{if} function.  If there is
6858 no third argument, the @code{if} function evaluates to nothing (the
6859 empty string).
6861 Note that only one of the @var{then-part} or the @var{else-part} will be
6862 evaluated, never both.  Thus, either can contain side-effects (such as
6863 @code{shell} function calls, etc.)
6865 @item $(or @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
6866 @findex or
6867 The @code{or} function provides a ``short-circuiting'' OR operation.
6868 Each argument is expanded, in order.  If an argument expands to a
6869 non-empty string the processing stops and the result of the expansion
6870 is that string.  If, after all arguments are expanded, all of them are
6871 false (empty), then the result of the expansion is the empty string.
6873 @item $(and @var{condition1}[,@var{condition2}[,@var{condition3}@dots{}]])
6874 @findex and
6875 The @code{and} function provides a ``short-circuiting'' AND operation.
6876 Each argument is expanded, in order.  If an argument expands to an
6877 empty string the processing stops and the result of the expansion is
6878 the empty string.  If all arguments expand to a non-empty string then
6879 the result of the expansion is the expansion of the last argument.
6881 @end table
6883 @node Foreach Function, Call Function, Conditional Functions, Functions
6884 @section The @code{foreach} Function
6885 @findex foreach
6886 @cindex words, iterating over
6888 The @code{foreach} function is very different from other functions.  It
6889 causes one piece of text to be used repeatedly, each time with a different
6890 substitution performed on it.  It resembles the @code{for} command in the
6891 shell @code{sh} and the @code{foreach} command in the C-shell @code{csh}.
6893 The syntax of the @code{foreach} function is:
6895 @example
6896 $(foreach @var{var},@var{list},@var{text})
6897 @end example
6899 @noindent
6900 The first two arguments, @var{var} and @var{list}, are expanded before
6901 anything else is done; note that the last argument, @var{text}, is
6902 @strong{not} expanded at the same time.  Then for each word of the expanded
6903 value of @var{list}, the variable named by the expanded value of @var{var}
6904 is set to that word, and @var{text} is expanded.  Presumably @var{text}
6905 contains references to that variable, so its expansion will be different
6906 each time.
6908 The result is that @var{text} is expanded as many times as there are
6909 whitespace-separated words in @var{list}.  The multiple expansions of
6910 @var{text} are concatenated, with spaces between them, to make the result
6911 of @code{foreach}.
6913 This simple example sets the variable @samp{files} to the list of all files
6914 in the directories in the list @samp{dirs}:
6916 @example
6917 dirs := a b c d
6918 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
6919 @end example
6921 Here @var{text} is @samp{$(wildcard $(dir)/*)}.  The first repetition
6922 finds the value @samp{a} for @code{dir}, so it produces the same result
6923 as @samp{$(wildcard a/*)}; the second repetition produces the result
6924 of @samp{$(wildcard b/*)}; and the third, that of @samp{$(wildcard c/*)}.
6926 This example has the same result (except for setting @samp{dirs}) as
6927 the following example:
6929 @example
6930 files := $(wildcard a/* b/* c/* d/*)
6931 @end example
6933 When @var{text} is complicated, you can improve readability by giving it
6934 a name, with an additional variable:
6936 @example
6937 find_files = $(wildcard $(dir)/*)
6938 dirs := a b c d
6939 files := $(foreach dir,$(dirs),$(find_files))
6940 @end example
6942 @noindent
6943 Here we use the variable @code{find_files} this way.  We use plain @samp{=}
6944 to define a recursively-expanding variable, so that its value contains an
6945 actual function call to be reexpanded under the control of @code{foreach};
6946 a simply-expanded variable would not do, since @code{wildcard} would be
6947 called only once at the time of defining @code{find_files}.
6949 The @code{foreach} function has no permanent effect on the variable
6950 @var{var}; its value and flavor after the @code{foreach} function call are
6951 the same as they were beforehand.  The other values which are taken from
6952 @var{list} are in effect only temporarily, during the execution of
6953 @code{foreach}.  The variable @var{var} is a simply-expanded variable
6954 during the execution of @code{foreach}.  If @var{var} was undefined
6955 before the @code{foreach} function call, it is undefined after the call.
6956 @xref{Flavors, ,The Two Flavors of Variables}.@refill
6958 You must take care when using complex variable expressions that result in
6959 variable names because many strange things are valid variable names, but
6960 are probably not what you intended.  For example,
6962 @smallexample
6963 files := $(foreach Esta escrito en espanol!,b c ch,$(find_files))
6964 @end smallexample
6966 @noindent
6967 might be useful if the value of @code{find_files} references the variable
6968 whose name is @samp{Esta escrito en espanol!} (es un nombre bastante largo,
6969 no?), but it is more likely to be a mistake.
6971 @node Call Function, Value Function, Foreach Function, Functions
6972 @section The @code{call} Function
6973 @findex call
6974 @cindex functions, user defined
6975 @cindex user defined functions
6977 The @code{call} function is unique in that it can be used to create new
6978 parameterized functions.  You can write a complex expression as the
6979 value of a variable, then use @code{call} to expand it with different
6980 values.
6982 The syntax of the @code{call} function is:
6984 @example
6985 $(call @var{variable},@var{param},@var{param},@dots{})
6986 @end example
6988 When @code{make} expands this function, it assigns each @var{param} to
6989 temporary variables @code{$(1)}, @code{$(2)}, etc.  The variable
6990 @code{$(0)} will contain @var{variable}.  There is no maximum number of
6991 parameter arguments.  There is no minimum, either, but it doesn't make
6992 sense to use @code{call} with no parameters.
6994 Then @var{variable} is expanded as a @code{make} variable in the context
6995 of these temporary assignments.  Thus, any reference to @code{$(1)} in
6996 the value of @var{variable} will resolve to the first @var{param} in the
6997 invocation of @code{call}.
6999 Note that @var{variable} is the @emph{name} of a variable, not a
7000 @emph{reference} to that variable.  Therefore you would not normally use
7001 a @samp{$} or parentheses when writing it.  (You can, however, use a
7002 variable reference in the name if you want the name not to be a
7003 constant.)
7005 If @var{variable} is the name of a builtin function, the builtin function
7006 is always invoked (even if a @code{make} variable by that name also
7007 exists).
7009 The @code{call} function expands the @var{param} arguments before
7010 assigning them to temporary variables.  This means that @var{variable}
7011 values containing references to builtin functions that have special
7012 expansion rules, like @code{foreach} or @code{if}, may not work as you
7013 expect.
7015 Some examples may make this clearer.
7017 This macro simply reverses its arguments:
7019 @smallexample
7020 reverse = $(2) $(1)
7022 foo = $(call reverse,a,b)
7023 @end smallexample
7025 @noindent
7026 Here @var{foo} will contain @samp{b a}.
7028 This one is slightly more interesting: it defines a macro to search for
7029 the first instance of a program in @code{PATH}:
7031 @smallexample
7032 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
7034 LS := $(call pathsearch,ls)
7035 @end smallexample
7037 @noindent
7038 Now the variable LS contains @code{/bin/ls} or similar.
7040 The @code{call} function can be nested.  Each recursive invocation gets
7041 its own local values for @code{$(1)}, etc.@: that mask the values of
7042 higher-level @code{call}.  For example, here is an implementation of a
7043 @dfn{map} function:
7045 @smallexample
7046 map = $(foreach a,$(2),$(call $(1),$(a)))
7047 @end smallexample
7049 Now you can @var{map} a function that normally takes only one argument,
7050 such as @code{origin}, to multiple values in one step:
7052 @smallexample
7053 o = $(call map,origin,o map MAKE)
7054 @end smallexample
7056 and end up with @var{o} containing something like @samp{file file default}.
7058 A final caution: be careful when adding whitespace to the arguments to
7059 @code{call}.  As with other functions, any whitespace contained in the
7060 second and subsequent arguments is kept; this can cause strange
7061 effects.  It's generally safest to remove all extraneous whitespace when
7062 providing parameters to @code{call}.
7064 @node Value Function, Eval Function, Call Function, Functions
7065 @comment  node-name,  next,  previous,  up
7066 @section The @code{value} Function
7067 @findex value
7068 @cindex variables, unexpanded value
7070 The @code{value} function provides a way for you to use the value of a
7071 variable @emph{without} having it expanded.  Please note that this
7072 does not undo expansions which have already occurred; for example if
7073 you create a simply expanded variable its value is expanded during the
7074 definition; in that case the @code{value} function will return the
7075 same result as using the variable directly.
7077 The syntax of the @code{value} function is:
7079 @example
7080 $(value @var{variable})
7081 @end example
7083 Note that @var{variable} is the @emph{name} of a variable; not a
7084 @emph{reference} to that variable.  Therefore you would not normally
7085 use a @samp{$} or parentheses when writing it.  (You can, however, use
7086 a variable reference in the name if you want the name not to be a
7087 constant.)
7089 The result of this function is a string containing the value of
7090 @var{variable}, without any expansion occurring.  For example, in this
7091 makefile:
7093 @example
7094 @group
7095 FOO = $PATH
7097 all:
7098         @@echo $(FOO)
7099         @@echo $(value FOO)
7100 @end group
7101 @end example
7103 @noindent
7104 The first output line would be @code{ATH}, since the ``$P'' would be
7105 expanded as a @code{make} variable, while the second output line would
7106 be the current value of your @code{$PATH} environment variable, since
7107 the @code{value} function avoided the expansion.
7109 The @code{value} function is most often used in conjunction with the
7110 @code{eval} function (@pxref{Eval Function}).
7112 @node Eval Function, Origin Function, Value Function, Functions
7113 @comment  node-name,  next,  previous,  up
7114 @section The @code{eval} Function
7115 @findex eval
7116 @cindex evaluating makefile syntax
7117 @cindex makefile syntax, evaluating
7119 The @code{eval} function is very special: it allows you to define new
7120 makefile constructs that are not constant; which are the result of
7121 evaluating other variables and functions.  The argument to the
7122 @code{eval} function is expanded, then the results of that expansion
7123 are parsed as makefile syntax.  The expanded results can define new
7124 @code{make} variables, targets, implicit or explicit rules, etc.
7126 The result of the @code{eval} function is always the empty string;
7127 thus, it can be placed virtually anywhere in a makefile without
7128 causing syntax errors.
7130 It's important to realize that the @code{eval} argument is expanded
7131 @emph{twice}; first by the @code{eval} function, then the results of
7132 that expansion are expanded again when they are parsed as makefile
7133 syntax.  This means you may need to provide extra levels of escaping
7134 for ``$'' characters when using @code{eval}.  The @code{value}
7135 function (@pxref{Value Function}) can sometimes be useful in these
7136 situations, to circumvent unwanted expansions.
7138 Here is an example of how @code{eval} can be used; this example
7139 combines a number of concepts and other functions.  Although it might
7140 seem overly complex to use @code{eval} in this example, rather than
7141 just writing out the rules, consider two things: first, the template
7142 definition (in @code{PROGRAM_template}) could need to be much more
7143 complex than it is here; and second, you might put the complex,
7144 ``generic'' part of this example into another makefile, then include
7145 it in all the individual makefiles.  Now your individual makefiles are
7146 quite straightforward.
7148 @example
7149 @group
7150 PROGRAMS    = server client
7152 server_OBJS = server.o server_priv.o server_access.o
7153 server_LIBS = priv protocol
7155 client_OBJS = client.o client_api.o client_mem.o
7156 client_LIBS = protocol
7158 # Everything after this is generic
7160 .PHONY: all
7161 all: $(PROGRAMS)
7163 define PROGRAM_template
7164  $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
7165  ALL_OBJS   += $$($(1)_OBJS)
7166 endef
7168 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
7170 $(PROGRAMS):
7171         $(LINK.o) $^ $(LDLIBS) -o $@@
7173 clean:
7174         rm -f $(ALL_OBJS) $(PROGRAMS)
7175 @end group
7176 @end example
7178 @node Origin Function, Flavor Function, Eval Function, Functions
7179 @section The @code{origin} Function
7180 @findex origin
7181 @cindex variables, origin of
7182 @cindex origin of variable
7184 The @code{origin} function is unlike most other functions in that it does
7185 not operate on the values of variables; it tells you something @emph{about}
7186 a variable.  Specifically, it tells you where it came from.
7188 The syntax of the @code{origin} function is:
7190 @example
7191 $(origin @var{variable})
7192 @end example
7194 Note that @var{variable} is the @emph{name} of a variable to inquire about;
7195 not a @emph{reference} to that variable.  Therefore you would not normally
7196 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7197 variable reference in the name if you want the name not to be a constant.)
7199 The result of this function is a string telling you how the variable
7200 @var{variable} was defined:
7202 @table @samp
7203 @item undefined
7205 if @var{variable} was never defined.
7207 @item default
7209 if @var{variable} has a default definition, as is usual with @code{CC}
7210 and so on.  @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
7211 Note that if you have redefined a default variable, the @code{origin}
7212 function will return the origin of the later definition.
7214 @item environment
7216 if @var{variable} was defined as an environment variable and the
7217 @samp{-e} option is @emph{not} turned on (@pxref{Options Summary, ,Summary of Options}).
7219 @item environment override
7221 if @var{variable} was defined as an environment variable and the
7222 @w{@samp{-e}} option @emph{is} turned on (@pxref{Options Summary,
7223 ,Summary of Options}).@refill
7225 @item file
7227 if @var{variable} was defined in a makefile.
7229 @item command line
7231 if @var{variable} was defined on the command line.
7233 @item override
7235 if @var{variable} was defined with an @code{override} directive in a
7236 makefile (@pxref{Override Directive, ,The @code{override} Directive}).
7238 @item automatic
7240 if @var{variable} is an automatic variable defined for the
7241 execution of the commands for each rule
7242 (@pxref{Automatic Variables}).
7243 @end table
7245 This information is primarily useful (other than for your curiosity) to
7246 determine if you want to believe the value of a variable.  For example,
7247 suppose you have a makefile @file{foo} that includes another makefile
7248 @file{bar}.  You want a variable @code{bletch} to be defined in @file{bar}
7249 if you run the command @w{@samp{make -f bar}}, even if the environment contains
7250 a definition of @code{bletch}.  However, if @file{foo} defined
7251 @code{bletch} before including @file{bar}, you do not want to override that
7252 definition.  This could be done by using an @code{override} directive in
7253 @file{foo}, giving that definition precedence over the later definition in
7254 @file{bar}; unfortunately, the @code{override} directive would also
7255 override any command line definitions.  So, @file{bar} could
7256 include:@refill
7258 @example
7259 @group
7260 ifdef bletch
7261 ifeq "$(origin bletch)" "environment"
7262 bletch = barf, gag, etc.
7263 endif
7264 endif
7265 @end group
7266 @end example
7268 @noindent
7269 If @code{bletch} has been defined from the environment, this will redefine
7272 If you want to override a previous definition of @code{bletch} if it came
7273 from the environment, even under @samp{-e}, you could instead write:
7275 @example
7276 @group
7277 ifneq "$(findstring environment,$(origin bletch))" ""
7278 bletch = barf, gag, etc.
7279 endif
7280 @end group
7281 @end example
7283 Here the redefinition takes place if @samp{$(origin bletch)} returns either
7284 @samp{environment} or @samp{environment override}.
7285 @xref{Text Functions, , Functions for String Substitution and Analysis}.
7287 @node Flavor Function, Shell Function, Origin Function, Functions
7288 @section The @code{flavor} Function
7289 @findex flavor
7290 @cindex variables, flavor of
7291 @cindex flavor of variable
7293 The @code{flavor} function is unlike most other functions (and like
7294 @code{origin} function) in that it does not operate on the values of
7295 variables; it tells you something @emph{about} a variable.
7296 Specifically, it tells you the flavor of a variable (@pxref{Flavors,
7297 ,The Two Flavors of Variables}).
7299 The syntax of the @code{flavor} function is:
7301 @example
7302 $(flavor @var{variable})
7303 @end example
7305 Note that @var{variable} is the @emph{name} of a variable to inquire about;
7306 not a @emph{reference} to that variable.  Therefore you would not normally
7307 use a @samp{$} or parentheses when writing it.  (You can, however, use a
7308 variable reference in the name if you want the name not to be a constant.)
7310 The result of this function is a string that identifies the flavor of the
7311 variable @var{variable}:
7313 @table @samp
7314 @item undefined
7316 if @var{variable} was never defined.
7318 @item recursive
7320 if @var{variable} is a recursively expanded variable.
7322 @item simple
7324 if @var{variable} is a simply expanded variable.
7326 @end table
7329 @node Shell Function, Make Control Functions, Flavor Function, Functions
7330 @section The @code{shell} Function
7331 @findex shell
7332 @cindex commands, expansion
7333 @cindex backquotes
7334 @cindex shell command, function for
7336 The @code{shell} function is unlike any other function other than the
7337 @code{wildcard} function
7338 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
7339 communicates with the world outside of @code{make}.
7341 The @code{shell} function performs the same function that backquotes
7342 (@samp{`}) perform in most shells: it does @dfn{command expansion}.
7343 This means that it takes as an argument a shell command and evaluates
7344 to the output of the command.  The only processing @code{make} does on
7345 the result is to convert each newline (or carriage-return / newline
7346 pair) to a single space.  If there is a trailing (carriage-return
7347 and) newline it will simply be removed.@refill
7349 The commands run by calls to the @code{shell} function are run when the
7350 function calls are expanded (@pxref{Reading Makefiles, , How
7351 @code{make} Reads a Makefile}).  Because this function involves
7352 spawning a new shell, you should carefully consider the performance
7353 implications of using the @code{shell} function within recursively
7354 expanded variables vs.@: simply expanded variables (@pxref{Flavors, ,The
7355 Two Flavors of Variables}).
7357 Here are some examples of the use of the @code{shell} function:
7359 @example
7360 contents := $(shell cat foo)
7361 @end example
7363 @noindent
7364 sets @code{contents} to the contents of the file @file{foo}, with a space
7365 (rather than a newline) separating each line.
7367 @example
7368 files := $(shell echo *.c)
7369 @end example
7371 @noindent
7372 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
7373 using a very strange shell, this has the same result as
7374 @w{@samp{$(wildcard *.c)}} (as long as at least one @samp{.c} file
7375 exists).@refill
7377 @node Make Control Functions,  , Shell Function, Functions
7378 @section Functions That Control Make
7379 @cindex functions, for controlling make
7380 @cindex controlling make
7382 These functions control the way make runs.  Generally, they are used to
7383 provide information to the user of the makefile or to cause make to stop
7384 if some sort of environmental error is detected.
7386 @table @code
7387 @item $(error @var{text}@dots{})
7388 @findex error
7389 @cindex error, stopping on
7390 @cindex stopping make
7391 Generates a fatal error where the message is @var{text}.  Note that the
7392 error is generated whenever this function is evaluated.  So, if you put
7393 it inside a command script or on the right side of a recursive variable
7394 assignment, it won't be evaluated until later.  The @var{text} will be
7395 expanded before the error is generated.
7397 For example,
7399 @example
7400 ifdef ERROR1
7401 $(error error is $(ERROR1))
7402 endif
7403 @end example
7405 @noindent
7406 will generate a fatal error during the read of the makefile if the
7407 @code{make} variable @code{ERROR1} is defined.  Or,
7409 @example
7410 ERR = $(error found an error!)
7412 .PHONY: err
7413 err: ; $(ERR)
7414 @end example
7416 @noindent
7417 will generate a fatal error while @code{make} is running, if the
7418 @code{err} target is invoked.
7420 @item $(warning @var{text}@dots{})
7421 @findex warning
7422 @cindex warnings, printing
7423 @cindex printing user warnings
7424 This function works similarly to the @code{error} function, above,
7425 except that @code{make} doesn't exit.  Instead, @var{text} is expanded
7426 and the resulting message is displayed, but processing of the makefile
7427 continues.
7429 The result of the expansion of this function is the empty string.
7431 @item $(info @var{text}@dots{})
7432 @findex info
7433 @cindex printing messages
7434 This function does nothing more than print its (expanded) argument(s)
7435 to standard output.  No makefile name or line number is added.  The
7436 result of the expansion of this function is the empty string.
7437 @end table
7439 @node Running, Implicit Rules, Functions, Top
7440 @chapter How to Run @code{make}
7442 A makefile that says how to recompile a program can be used in more
7443 than one way.  The simplest use is to recompile every file that is out
7444 of date.  Usually, makefiles are written so that if you run
7445 @code{make} with no arguments, it does just that.
7447 But you might want to update only some of the files; you might want to use
7448 a different compiler or different compiler options; you might want just to
7449 find out which files are out of date without changing them.
7451 By giving arguments when you run @code{make}, you can do any of these
7452 things and many others.
7454 @cindex exit status of make
7455 The exit status of @code{make} is always one of three values:
7456 @table @code
7457 @item 0
7458 The exit status is zero if @code{make} is successful.
7459 @item 2
7460 The exit status is two if @code{make} encounters any errors.
7461 It will print messages describing the particular errors.
7462 @item 1
7463 The exit status is one if you use the @samp{-q} flag and @code{make}
7464 determines that some target is not already up to date.
7465 @xref{Instead of Execution, ,Instead of Executing the Commands}.
7466 @end table
7468 @menu
7469 * Makefile Arguments::          How to specify which makefile to use.
7470 * Goals::                       How to use goal arguments to specify which
7471                                   parts of the makefile to use.
7472 * Instead of Execution::        How to use mode flags to specify what
7473                                   kind of thing to do with the commands
7474                                   in the makefile other than simply
7475                                   execute them.
7476 * Avoiding Compilation::        How to avoid recompiling certain files.
7477 * Overriding::                  How to override a variable to specify
7478                                   an alternate compiler and other things.
7479 * Testing::                     How to proceed past some errors, to
7480                                   test compilation.
7481 * Options Summary::             Summary of Options
7482 @end menu
7484 @node Makefile Arguments, Goals, Running, Running
7485 @section Arguments to Specify the Makefile
7486 @cindex @code{--file}
7487 @cindex @code{--makefile}
7488 @cindex @code{-f}
7490 The way to specify the name of the makefile is with the @samp{-f} or
7491 @samp{--file} option (@samp{--makefile} also works).  For example,
7492 @samp{-f altmake} says to use the file @file{altmake} as the makefile.
7494 If you use the @samp{-f} flag several times and follow each @samp{-f}
7495 with an argument, all the specified files are used jointly as
7496 makefiles.
7498 If you do not use the @samp{-f} or @samp{--file} flag, the default is
7499 to try @file{GNUmakefile}, @file{makefile}, and @file{Makefile}, in
7500 that order, and use the first of these three which exists or can be made
7501 (@pxref{Makefiles, ,Writing Makefiles}).@refill
7503 @node Goals, Instead of Execution, Makefile Arguments, Running
7504 @section Arguments to Specify the Goals
7505 @cindex goal, how to specify
7507 The @dfn{goals} are the targets that @code{make} should strive ultimately
7508 to update.  Other targets are updated as well if they appear as
7509 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
7511 By default, the goal is the first target in the makefile (not counting
7512 targets that start with a period).  Therefore, makefiles are usually
7513 written so that the first target is for compiling the entire program or
7514 programs they describe.  If the first rule in the makefile has several
7515 targets, only the first target in the rule becomes the default goal, not
7516 the whole list.  You can manage the selection of the default goal from
7517 within your makefile using the @code{.DEFAULT_GOAL} variable
7518 (@pxref{Special Variables, , Other Special Variables}).
7520 You can also specify a different goal or goals with command-line
7521 arguments to @code{make}.  Use the name of the goal as an argument.
7522 If you specify several goals, @code{make} processes each of them in
7523 turn, in the order you name them.
7525 Any target in the makefile may be specified as a goal (unless it
7526 starts with @samp{-} or contains an @samp{=}, in which case it will be
7527 parsed as a switch or variable definition, respectively).  Even
7528 targets not in the makefile may be specified, if @code{make} can find
7529 implicit rules that say how to make them.
7531 @vindex MAKECMDGOALS
7532 @code{Make} will set the special variable @code{MAKECMDGOALS} to the
7533 list of goals you specified on the command line.  If no goals were given
7534 on the command line, this variable is empty.  Note that this variable
7535 should be used only in special circumstances.
7537 An example of appropriate use is to avoid including @file{.d} files
7538 during @code{clean} rules (@pxref{Automatic Prerequisites}), so
7539 @code{make} won't create them only to immediately remove them
7540 again:@refill
7542 @example
7543 @group
7544 sources = foo.c bar.c
7546 ifneq ($(MAKECMDGOALS),clean)
7547 include $(sources:.c=.d)
7548 endif
7549 @end group
7550 @end example
7552 One use of specifying a goal is if you want to compile only a part of
7553 the program, or only one of several programs.  Specify as a goal each
7554 file that you wish to remake.  For example, consider a directory containing
7555 several programs, with a makefile that starts like this:
7557 @example
7558 .PHONY: all
7559 all: size nm ld ar as
7560 @end example
7562 If you are working on the program @code{size}, you might want to say
7563 @w{@samp{make size}} so that only the files of that program are recompiled.
7565 Another use of specifying a goal is to make files that are not normally
7566 made.  For example, there may be a file of debugging output, or a
7567 version of the program that is compiled specially for testing, which has
7568 a rule in the makefile but is not a prerequisite of the default goal.
7570 Another use of specifying a goal is to run the commands associated with
7571 a phony target (@pxref{Phony Targets}) or empty target (@pxref{Empty
7572 Targets, ,Empty Target Files to Record Events}).  Many makefiles contain
7573 a phony target named @file{clean} which deletes everything except source
7574 files.  Naturally, this is done only if you request it explicitly with
7575 @w{@samp{make clean}}.  Following is a list of typical phony and empty
7576 target names.  @xref{Standard Targets}, for a detailed list of all the
7577 standard target names which GNU software packages use.
7579 @table @file
7580 @item all
7581 @cindex @code{all} @r{(standard target)}
7582 Make all the top-level targets the makefile knows about.
7584 @item clean
7585 @cindex @code{clean} @r{(standard target)}
7586 Delete all files that are normally created by running @code{make}.
7588 @item mostlyclean
7589 @cindex @code{mostlyclean} @r{(standard target)}
7590 Like @samp{clean}, but may refrain from deleting a few files that people
7591 normally don't want to recompile.  For example, the @samp{mostlyclean}
7592 target for GCC does not delete @file{libgcc.a}, because recompiling it
7593 is rarely necessary and takes a lot of time.
7595 @item distclean
7596 @cindex @code{distclean} @r{(standard target)}
7597 @itemx realclean
7598 @cindex @code{realclean} @r{(standard target)}
7599 @itemx clobber
7600 @cindex @code{clobber} @r{(standard target)}
7601 Any of these targets might be defined to delete @emph{more} files than
7602 @samp{clean} does.  For example, this would delete configuration files
7603 or links that you would normally create as preparation for compilation,
7604 even if the makefile itself cannot create these files.
7606 @item install
7607 @cindex @code{install} @r{(standard target)}
7608 Copy the executable file into a directory that users typically search
7609 for commands; copy any auxiliary files that the executable uses into
7610 the directories where it will look for them.
7612 @item print
7613 @cindex @code{print} @r{(standard target)}
7614 Print listings of the source files that have changed.
7616 @item tar
7617 @cindex @code{tar} @r{(standard target)}
7618 Create a tar file of the source files.
7620 @item shar
7621 @cindex @code{shar} @r{(standard target)}
7622 Create a shell archive (shar file) of the source files.
7624 @item dist
7625 @cindex @code{dist} @r{(standard target)}
7626 Create a distribution file of the source files.  This might
7627 be a tar file, or a shar file, or a compressed version of one of the
7628 above, or even more than one of the above.
7630 @item TAGS
7631 @cindex @code{TAGS} @r{(standard target)}
7632 Update a tags table for this program.
7634 @item check
7635 @cindex @code{check} @r{(standard target)}
7636 @itemx test
7637 @cindex @code{test} @r{(standard target)}
7638 Perform self tests on the program this makefile builds.
7639 @end table
7641 @node Instead of Execution, Avoiding Compilation, Goals, Running
7642 @section Instead of Executing the Commands
7643 @cindex execution, instead of
7644 @cindex commands, instead of executing
7646 The makefile tells @code{make} how to tell whether a target is up to date,
7647 and how to update each target.  But updating the targets is not always
7648 what you want.  Certain options specify other activities for @code{make}.
7650 @comment Extra blank lines make it print better.
7651 @table @samp
7652 @item -n
7653 @itemx --just-print
7654 @itemx --dry-run
7655 @itemx --recon
7656 @cindex @code{--just-print}
7657 @cindex @code{--dry-run}
7658 @cindex @code{--recon}
7659 @cindex @code{-n}
7661 ``No-op''.  The activity is to print what commands would be used to make
7662 the targets up to date, but not actually execute them.
7664 @item -t
7665 @itemx --touch
7666 @cindex @code{--touch}
7667 @cindex touching files
7668 @cindex target, touching
7669 @cindex @code{-t}
7671 ``Touch''.  The activity is to mark the targets as up to date without
7672 actually changing them.  In other words, @code{make} pretends to compile
7673 the targets but does not really change their contents.
7675 @item -q
7676 @itemx --question
7677 @cindex @code{--question}
7678 @cindex @code{-q}
7679 @cindex question mode
7681 ``Question''.  The activity is to find out silently whether the targets
7682 are up to date already; but execute no commands in either case.  In other
7683 words, neither compilation nor output will occur.
7685 @item -W @var{file}
7686 @itemx --what-if=@var{file}
7687 @itemx --assume-new=@var{file}
7688 @itemx --new-file=@var{file}
7689 @cindex @code{--what-if}
7690 @cindex @code{-W}
7691 @cindex @code{--assume-new}
7692 @cindex @code{--new-file}
7693 @cindex what if
7694 @cindex files, assuming new
7696 ``What if''.  Each @samp{-W} flag is followed by a file name.  The given
7697 files' modification times are recorded by @code{make} as being the present
7698 time, although the actual modification times remain the same.
7699 You can use the @samp{-W} flag in conjunction with the @samp{-n} flag
7700 to see what would happen if you were to modify specific files.@refill
7701 @end table
7703 With the @samp{-n} flag, @code{make} prints the commands that it would
7704 normally execute but does not execute them.
7706 With the @samp{-t} flag, @code{make} ignores the commands in the rules
7707 and uses (in effect) the command @code{touch} for each target that needs to
7708 be remade.  The @code{touch} command is also printed, unless @samp{-s} or
7709 @code{.SILENT} is used.  For speed, @code{make} does not actually invoke
7710 the program @code{touch}.  It does the work directly.
7712 With the @samp{-q} flag, @code{make} prints nothing and executes no
7713 commands, but the exit status code it returns is zero if and only if the
7714 targets to be considered are already up to date.  If the exit status is
7715 one, then some updating needs to be done.  If @code{make} encounters an
7716 error, the exit status is two, so you can distinguish an error from a
7717 target that is not up to date.
7719 It is an error to use more than one of these three flags in the same
7720 invocation of @code{make}.
7722 @cindex +, and command execution
7723 The @samp{-n}, @samp{-t}, and @samp{-q} options do not affect command
7724 lines that begin with @samp{+} characters or contain the strings
7725 @samp{$(MAKE)} or @samp{$@{MAKE@}}.  Note that only the line containing
7726 the @samp{+} character or the strings @samp{$(MAKE)} or @samp{$@{MAKE@}}
7727 is run regardless of these options.  Other lines in the same rule are
7728 not run unless they too begin with @samp{+} or contain @samp{$(MAKE)} or
7729 @samp{$@{MAKE@}} (@xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.)
7731 The @samp{-W} flag provides two features:
7733 @itemize @bullet
7734 @item
7735 If you also use the @samp{-n} or @samp{-q} flag, you can see what
7736 @code{make} would do if you were to modify some files.
7738 @item
7739 Without the @samp{-n} or @samp{-q} flag, when @code{make} is actually
7740 executing commands, the @samp{-W} flag can direct @code{make} to act
7741 as if some files had been modified, without actually modifying the
7742 files.@refill
7743 @end itemize
7745 Note that the options @samp{-p} and @samp{-v} allow you to obtain other
7746 information about @code{make} or about the makefiles in use
7747 (@pxref{Options Summary, ,Summary of Options}).@refill
7749 @node Avoiding Compilation, Overriding, Instead of Execution, Running
7750 @section Avoiding Recompilation of Some Files
7751 @cindex @code{-o}
7752 @cindex @code{--old-file}
7753 @cindex @code{--assume-old}
7754 @cindex files, assuming old
7755 @cindex files, avoiding recompilation of
7756 @cindex recompilation, avoiding
7758 Sometimes you may have changed a source file but you do not want to
7759 recompile all the files that depend on it.  For example, suppose you add
7760 a macro or a declaration to a header file that many other files depend
7761 on.  Being conservative, @code{make} assumes that any change in the
7762 header file requires recompilation of all dependent files, but you know
7763 that they do not need to be recompiled and you would rather not waste
7764 the time waiting for them to compile.
7766 If you anticipate the problem before changing the header file, you can
7767 use the @samp{-t} flag.  This flag tells @code{make} not to run the
7768 commands in the rules, but rather to mark the target up to date by
7769 changing its last-modification date.  You would follow this procedure:
7771 @enumerate
7772 @item
7773 Use the command @samp{make} to recompile the source files that really
7774 need recompilation, ensuring that the object files are up-to-date
7775 before you begin.
7777 @item
7778 Make the changes in the header files.
7780 @item
7781 Use the command @samp{make -t} to mark all the object files as
7782 up to date.  The next time you run @code{make}, the changes in the
7783 header files will not cause any recompilation.
7784 @end enumerate
7786 If you have already changed the header file at a time when some files
7787 do need recompilation, it is too late to do this.  Instead, you can
7788 use the @w{@samp{-o @var{file}}} flag, which marks a specified file as
7789 ``old'' (@pxref{Options Summary, ,Summary of Options}).  This means
7790 that the file itself will not be remade, and nothing else will be
7791 remade on its account.  Follow this procedure:
7793 @enumerate
7794 @item
7795 Recompile the source files that need compilation for reasons independent
7796 of the particular header file, with @samp{make -o @var{headerfile}}.
7797 If several header files are involved, use a separate @samp{-o} option
7798 for each header file.
7800 @item
7801 Touch all the object files with @samp{make -t}.
7802 @end enumerate
7804 @node Overriding, Testing, Avoiding Compilation, Running
7805 @section Overriding Variables
7806 @cindex overriding variables with arguments
7807 @cindex variables, overriding with arguments
7808 @cindex command line variables
7809 @cindex variables, command line
7811 An argument that contains @samp{=} specifies the value of a variable:
7812 @samp{@var{v}=@var{x}} sets the value of the variable @var{v} to @var{x}.
7813 If you specify a value in this way, all ordinary assignments of the same
7814 variable in the makefile are ignored; we say they have been
7815 @dfn{overridden} by the command line argument.
7817 The most common way to use this facility is to pass extra flags to
7818 compilers.  For example, in a properly written makefile, the variable
7819 @code{CFLAGS} is included in each command that runs the C compiler, so a
7820 file @file{foo.c} would be compiled something like this:
7822 @example
7823 cc -c $(CFLAGS) foo.c
7824 @end example
7826 Thus, whatever value you set for @code{CFLAGS} affects each compilation
7827 that occurs.  The makefile probably specifies the usual value for
7828 @code{CFLAGS}, like this:
7830 @example
7831 CFLAGS=-g
7832 @end example
7834 Each time you run @code{make}, you can override this value if you
7835 wish.  For example, if you say @samp{make CFLAGS='-g -O'}, each C
7836 compilation will be done with @samp{cc -c -g -O}.  (This also
7837 illustrates how you can use quoting in the shell to enclose spaces and
7838 other special characters in the value of a variable when you override
7839 it.)
7841 The variable @code{CFLAGS} is only one of many standard variables that
7842 exist just so that you can change them this way.  @xref{Implicit
7843 Variables, , Variables Used by Implicit Rules}, for a complete list.
7845 You can also program the makefile to look at additional variables of your
7846 own, giving the user the ability to control other aspects of how the
7847 makefile works by changing the variables.
7849 When you override a variable with a command argument, you can define either
7850 a recursively-expanded variable or a simply-expanded variable.  The
7851 examples shown above make a recursively-expanded variable; to make a
7852 simply-expanded variable, write @samp{:=} instead of @samp{=}.  But, unless
7853 you want to include a variable reference or function call in the
7854 @emph{value} that you specify, it makes no difference which kind of
7855 variable you create.
7857 There is one way that the makefile can change a variable that you have
7858 overridden.  This is to use the @code{override} directive, which is a line
7859 that looks like this: @samp{override @var{variable} = @var{value}}
7860 (@pxref{Override Directive, ,The @code{override} Directive}).
7862 @node Testing, Options Summary, Overriding, Running
7863 @section Testing the Compilation of a Program
7864 @cindex testing compilation
7865 @cindex compilation, testing
7867 Normally, when an error happens in executing a shell command, @code{make}
7868 gives up immediately, returning a nonzero status.  No further commands are
7869 executed for any target.  The error implies that the goal cannot be
7870 correctly remade, and @code{make} reports this as soon as it knows.
7872 When you are compiling a program that you have just changed, this is not
7873 what you want.  Instead, you would rather that @code{make} try compiling
7874 every file that can be tried, to show you as many compilation errors
7875 as possible.
7877 @cindex @code{-k}
7878 @cindex @code{--keep-going}
7879 On these occasions, you should use the @samp{-k} or
7880 @samp{--keep-going} flag.  This tells @code{make} to continue to
7881 consider the other prerequisites of the pending targets, remaking them
7882 if necessary, before it gives up and returns nonzero status.  For
7883 example, after an error in compiling one object file, @samp{make -k}
7884 will continue compiling other object files even though it already
7885 knows that linking them will be impossible.  In addition to continuing
7886 after failed shell commands, @samp{make -k} will continue as much as
7887 possible after discovering that it does not know how to make a target
7888 or prerequisite file.  This will always cause an error message, but
7889 without @samp{-k}, it is a fatal error (@pxref{Options Summary,
7890 ,Summary of Options}).@refill
7892 The usual behavior of @code{make} assumes that your purpose is to get the
7893 goals up to date; once @code{make} learns that this is impossible, it might
7894 as well report the failure immediately.  The @samp{-k} flag says that the
7895 real purpose is to test as much as possible of the changes made in the
7896 program, perhaps to find several independent problems so that you can
7897 correct them all before the next attempt to compile.  This is why Emacs'
7898 @kbd{M-x compile} command passes the @samp{-k} flag by default.
7900 @node Options Summary,  , Testing, Running
7901 @section Summary of Options
7902 @cindex options
7903 @cindex flags
7904 @cindex switches
7906 Here is a table of all the options @code{make} understands:
7908 @table @samp
7909 @item -b
7910 @cindex @code{-b}
7911 @itemx -m
7912 @cindex @code{-m}
7913 These options are ignored for compatibility with other versions of @code{make}.
7915 @item -B
7916 @cindex @code{-B}
7917 @itemx --always-make
7918 @cindex @code{--always-make}
7919 Consider all targets out-of-date.  GNU @code{make} proceeds to
7920 consider targets and their prerequisites using the normal algorithms;
7921 however, all targets so considered are always remade regardless of the
7922 status of their prerequisites.  To avoid infinite recursion, if
7923 @code{MAKE_RESTARTS} (@pxref{Special Variables, , Other Special
7924 Variables}) is set to a number greater than 0 this option is disabled
7925 when considering whether to remake makefiles (@pxref{Remaking
7926 Makefiles, , How Makefiles Are Remade}).
7928 @item -C @var{dir}
7929 @cindex @code{-C}
7930 @itemx --directory=@var{dir}
7931 @cindex @code{--directory}
7932 Change to directory @var{dir} before reading the makefiles.  If multiple
7933 @samp{-C} options are specified, each is interpreted relative to the
7934 previous one: @samp{-C / -C etc} is equivalent to @samp{-C /etc}.
7935 This is typically used with recursive invocations of @code{make}
7936 (@pxref{Recursion, ,Recursive Use of @code{make}}).
7938 @item -d
7939 @cindex @code{-d}
7940 @c Extra blank line here makes the table look better.
7942 Print debugging information in addition to normal processing.  The
7943 debugging information says which files are being considered for
7944 remaking, which file-times are being compared and with what results,
7945 which files actually need to be remade, which implicit rules are
7946 considered and which are applied---everything interesting about how
7947 @code{make} decides what to do.  The @code{-d} option is equivalent to
7948 @samp{--debug=a} (see below).
7950 @item --debug[=@var{options}]
7951 @cindex @code{--debug}
7952 @c Extra blank line here makes the table look better.
7954 Print debugging information in addition to normal processing.  Various
7955 levels and types of output can be chosen.  With no arguments, print the
7956 ``basic'' level of debugging.  Possible arguments are below; only the
7957 first character is considered, and values must be comma- or
7958 space-separated.
7960 @table @code
7961 @item a (@i{all})
7962 All types of debugging output are enabled.  This is equivalent to using
7963 @samp{-d}.
7965 @item b (@i{basic})
7966 Basic debugging prints each target that was found to be out-of-date, and
7967 whether the build was successful or not.
7969 @item v (@i{verbose})
7970 A level above @samp{basic}; includes messages about which makefiles were
7971 parsed, prerequisites that did not need to be rebuilt, etc.  This option
7972 also enables @samp{basic} messages.
7974 @item i (@i{implicit})
7975 Prints messages describing the implicit rule searches for each target.
7976 This option also enables @samp{basic} messages.
7978 @item j (@i{jobs})
7979 Prints messages giving details on the invocation of specific subcommands.
7981 @item m (@i{makefile})
7982 By default, the above messages are not enabled while trying to remake
7983 the makefiles.  This option enables messages while rebuilding makefiles,
7984 too.  Note that the @samp{all} option does enable this option.  This
7985 option also enables @samp{basic} messages.
7986 @end table
7988 @item -e
7989 @cindex @code{-e}
7990 @itemx --environment-overrides
7991 @cindex @code{--environment-overrides}
7992 Give variables taken from the environment precedence
7993 over variables from makefiles.
7994 @xref{Environment, ,Variables from the Environment}.
7996 @item -f @var{file}
7997 @cindex @code{-f}
7998 @itemx --file=@var{file}
7999 @cindex @code{--file}
8000 @itemx --makefile=@var{file}
8001 @cindex @code{--makefile}
8002 Read the file named @var{file} as a makefile.
8003 @xref{Makefiles, ,Writing Makefiles}.
8005 @item -h
8006 @cindex @code{-h}
8007 @itemx --help
8008 @cindex @code{--help}
8009 @c Extra blank line here makes the table look better.
8011 Remind you of the options that @code{make} understands and then exit.
8013 @item -i
8014 @cindex @code{-i}
8015 @itemx --ignore-errors
8016 @cindex @code{--ignore-errors}
8017 Ignore all errors in commands executed to remake files.
8018 @xref{Errors, ,Errors in Commands}.
8020 @item -I @var{dir}
8021 @cindex @code{-I}
8022 @itemx --include-dir=@var{dir}
8023 @cindex @code{--include-dir}
8024 Specifies a directory @var{dir} to search for included makefiles.
8025 @xref{Include, ,Including Other Makefiles}.  If several @samp{-I}
8026 options are used to specify several directories, the directories are
8027 searched in the order specified.
8029 @item -j [@var{jobs}]
8030 @cindex @code{-j}
8031 @itemx --jobs[=@var{jobs}]
8032 @cindex @code{--jobs}
8033 Specifies the number of jobs (commands) to run simultaneously.  With no
8034 argument, @code{make} runs as many jobs simultaneously as possible.  If
8035 there is more than one @samp{-j} option, the last one is effective.
8036 @xref{Parallel, ,Parallel Execution},
8037 for more information on how commands are run.
8038 Note that this option is ignored on MS-DOS.
8040 @item -k
8041 @cindex @code{-k}
8042 @itemx --keep-going
8043 @cindex @code{--keep-going}
8044 Continue as much as possible after an error.  While the target that
8045 failed, and those that depend on it, cannot be remade, the other
8046 prerequisites of these targets can be processed all the same.
8047 @xref{Testing, ,Testing the Compilation of a Program}.
8049 @item -l [@var{load}]
8050 @cindex @code{-l}
8051 @itemx --load-average[=@var{load}]
8052 @cindex @code{--load-average}
8053 @itemx --max-load[=@var{load}]
8054 @cindex @code{--max-load}
8055 Specifies that no new jobs (commands) should be started if there are
8056 other jobs running and the load average is at least @var{load} (a
8057 floating-point number).  With no argument, removes a previous load
8058 limit.  @xref{Parallel, ,Parallel Execution}.
8060 @item -L
8061 @cindex @code{-L}
8062 @itemx --check-symlink-times
8063 @cindex @code{--check-symlink-times}
8064 On systems that support symbolic links, this option causes @code{make}
8065 to consider the timestamps on any symbolic links in addition to the
8066 timestamp on the file referenced by those links.  When this option is
8067 provided, the most recent timestamp among the file and the symbolic
8068 links is taken as the modification time for this target file.
8070 @item -n
8071 @cindex @code{-n}
8072 @itemx --just-print
8073 @cindex @code{--just-print}
8074 @itemx --dry-run
8075 @cindex @code{--dry-run}
8076 @itemx --recon
8077 @cindex @code{--recon}
8078 @c Extra blank line here makes the table look better.
8080 Print the commands that would be executed, but do not execute them.
8081 @xref{Instead of Execution, ,Instead of Executing the Commands}.
8083 @item -o @var{file}
8084 @cindex @code{-o}
8085 @itemx --old-file=@var{file}
8086 @cindex @code{--old-file}
8087 @itemx --assume-old=@var{file}
8088 @cindex @code{--assume-old}
8089 Do not remake the file @var{file} even if it is older than its
8090 prerequisites, and do not remake anything on account of changes in
8091 @var{file}.  Essentially the file is treated as very old and its rules
8092 are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
8093 Some Files}.@refill
8095 @item -p
8096 @cindex @code{-p}
8097 @itemx --print-data-base
8098 @cindex @code{--print-data-base}
8099 @cindex data base of @code{make} rules
8100 @cindex predefined rules and variables, printing
8101 Print the data base (rules and variable values) that results from
8102 reading the makefiles; then execute as usual or as otherwise specified.
8103 This also prints the version information given by the @samp{-v} switch
8104 (see below).  To print the data base without trying to remake any files,
8105 use @w{@samp{make -qp}}.  To print the data base of predefined rules and
8106 variables, use @w{@samp{make -p -f /dev/null}}.  The data base output
8107 contains filename and linenumber information for command and variable
8108 definitions, so it can be a useful debugging tool in complex environments.
8110 @item -q
8111 @cindex @code{-q}
8112 @itemx --question
8113 @cindex @code{--question}
8114 ``Question mode''.  Do not run any commands, or print anything; just
8115 return an exit status that is zero if the specified targets are already
8116 up to date, one if any remaking is required, or two if an error is
8117 encountered.  @xref{Instead of Execution, ,Instead of Executing the
8118 Commands}.@refill
8120 @item -r
8121 @cindex @code{-r}
8122 @itemx --no-builtin-rules
8123 @cindex @code{--no-builtin-rules}
8124 Eliminate use of the built-in implicit rules (@pxref{Implicit Rules,
8125 ,Using Implicit Rules}).  You can still define your own by writing
8126 pattern rules (@pxref{Pattern Rules, ,Defining and Redefining Pattern
8127 Rules}).  The @samp{-r} option also clears out the default list of
8128 suffixes for suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix
8129 Rules}).  But you can still define your own suffixes with a rule for
8130 @code{.SUFFIXES}, and then define your own suffix rules.  Note that only
8131 @emph{rules} are affected by the @code{-r} option; default variables
8132 remain in effect (@pxref{Implicit Variables, ,Variables Used by Implicit
8133 Rules}); see the @samp{-R} option below.
8135 @item -R
8136 @cindex @code{-R}
8137 @itemx --no-builtin-variables
8138 @cindex @code{--no-builtin-variables}
8139 Eliminate use of the built-in rule-specific variables (@pxref{Implicit
8140 Variables, ,Variables Used by Implicit Rules}).  You can still define
8141 your own, of course.  The @samp{-R} option also automatically enables
8142 the @samp{-r} option (see above), since it doesn't make sense to have
8143 implicit rules without any definitions for the variables that they use.
8145 @item -s
8146 @cindex @code{-s}
8147 @itemx --silent
8148 @cindex @code{--silent}
8149 @itemx --quiet
8150 @cindex @code{--quiet}
8151 @c Extra blank line here makes the table look better.
8153 Silent operation; do not print the commands as they are executed.
8154 @xref{Echoing, ,Command Echoing}.
8156 @item -S
8157 @cindex @code{-S}
8158 @itemx --no-keep-going
8159 @cindex @code{--no-keep-going}
8160 @itemx --stop
8161 @cindex @code{--stop}
8162 @c Extra blank line here makes the table look better.
8164 Cancel the effect of the @samp{-k} option.  This is never necessary
8165 except in a recursive @code{make} where @samp{-k} might be inherited
8166 from the top-level @code{make} via @code{MAKEFLAGS}
8167 (@pxref{Recursion, ,Recursive Use of @code{make}})
8168 or if you set @samp{-k} in @code{MAKEFLAGS} in your environment.@refill
8170 @item -t
8171 @cindex @code{-t}
8172 @itemx --touch
8173 @cindex @code{--touch}
8174 @c Extra blank line here makes the table look better.
8176 Touch files (mark them up to date without really changing them)
8177 instead of running their commands.  This is used to pretend that the
8178 commands were done, in order to fool future invocations of
8179 @code{make}.  @xref{Instead of Execution, ,Instead of Executing the Commands}.
8181 @item -v
8182 @cindex @code{-v}
8183 @itemx --version
8184 @cindex @code{--version}
8185 Print the version of the @code{make} program plus a copyright, a list
8186 of authors, and a notice that there is no warranty; then exit.
8188 @item -w
8189 @cindex @code{-w}
8190 @itemx --print-directory
8191 @cindex @code{--print-directory}
8192 Print a message containing the working directory both before and after
8193 executing the makefile.  This may be useful for tracking down errors
8194 from complicated nests of recursive @code{make} commands.
8195 @xref{Recursion, ,Recursive Use of @code{make}}.  (In practice, you
8196 rarely need to specify this option since @samp{make} does it for you;
8197 see @ref{-w Option, ,The @samp{--print-directory} Option}.)
8199 @itemx --no-print-directory
8200 @cindex @code{--no-print-directory}
8201 Disable printing of the working directory under @code{-w}.
8202 This option is useful when @code{-w} is turned on automatically,
8203 but you do not want to see the extra messages.
8204 @xref{-w Option, ,The @samp{--print-directory} Option}.
8206 @item -W @var{file}
8207 @cindex @code{-W}
8208 @itemx --what-if=@var{file}
8209 @cindex @code{--what-if}
8210 @itemx --new-file=@var{file}
8211 @cindex @code{--new-file}
8212 @itemx --assume-new=@var{file}
8213 @cindex @code{--assume-new}
8214 Pretend that the target @var{file} has just been modified.  When used
8215 with the @samp{-n} flag, this shows you what would happen if you were
8216 to modify that file.  Without @samp{-n}, it is almost the same as
8217 running a @code{touch} command on the given file before running
8218 @code{make}, except that the modification time is changed only in the
8219 imagination of @code{make}.
8220 @xref{Instead of Execution, ,Instead of Executing the Commands}.
8222 @item --warn-undefined-variables
8223 @cindex @code{--warn-undefined-variables}
8224 @cindex variables, warning for undefined
8225 @cindex undefined variables, warning message
8226 Issue a warning message whenever @code{make} sees a reference to an
8227 undefined variable.  This can be helpful when you are trying to debug
8228 makefiles which use variables in complex ways.
8229 @end table
8231 @node Implicit Rules, Archives, Running, Top
8232 @chapter Using Implicit Rules
8233 @cindex implicit rule
8234 @cindex rule, implicit
8236 Certain standard ways of remaking target files are used very often.  For
8237 example, one customary way to make an object file is from a C source file
8238 using the C compiler, @code{cc}.
8240 @dfn{Implicit rules} tell @code{make} how to use customary techniques so
8241 that you do not have to specify them in detail when you want to use
8242 them.  For example, there is an implicit rule for C compilation.  File
8243 names determine which implicit rules are run.  For example, C
8244 compilation typically takes a @file{.c} file and makes a @file{.o} file.
8245 So @code{make} applies the implicit rule for C compilation when it sees
8246 this combination of file name endings.@refill
8248 A chain of implicit rules can apply in sequence; for example, @code{make}
8249 will remake a @file{.o} file from a @file{.y} file by way of a @file{.c} file.
8250 @iftex
8251 @xref{Chained Rules, ,Chains of Implicit Rules}.
8252 @end iftex
8254 The built-in implicit rules use several variables in their commands so
8255 that, by changing the values of the variables, you can change the way the
8256 implicit rule works.  For example, the variable @code{CFLAGS} controls the
8257 flags given to the C compiler by the implicit rule for C compilation.
8258 @iftex
8259 @xref{Implicit Variables, ,Variables Used by Implicit Rules}.
8260 @end iftex
8262 You can define your own implicit rules by writing @dfn{pattern rules}.
8263 @iftex
8264 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.
8265 @end iftex
8267 @dfn{Suffix rules} are a more limited way to define implicit rules.
8268 Pattern rules are more general and clearer, but suffix rules are
8269 retained for compatibility.
8270 @iftex
8271 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
8272 @end iftex
8274 @menu
8275 * Using Implicit::              How to use an existing implicit rule
8276                                   to get the commands for updating a file.
8277 * Catalogue of Rules::          A list of built-in implicit rules.
8278 * Implicit Variables::          How to change what predefined rules do.
8279 * Chained Rules::               How to use a chain of implicit rules.
8280 * Pattern Rules::               How to define new implicit rules.
8281 * Last Resort::                 How to define commands for rules which
8282                                   cannot find any.
8283 * Suffix Rules::                The old-fashioned style of implicit rule.
8284 * Implicit Rule Search::        The precise algorithm for applying
8285                                   implicit rules.
8286 @end menu
8288 @node Using Implicit, Catalogue of Rules, Implicit Rules, Implicit Rules
8289 @section Using Implicit Rules
8290 @cindex implicit rule, how to use
8291 @cindex rule, implicit, how to use
8293 To allow @code{make} to find a customary method for updating a target file,
8294 all you have to do is refrain from specifying commands yourself.  Either
8295 write a rule with no command lines, or don't write a rule at all.  Then
8296 @code{make} will figure out which implicit rule to use based on which
8297 kind of source file exists or can be made.
8299 For example, suppose the makefile looks like this:
8301 @example
8302 foo : foo.o bar.o
8303         cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
8304 @end example
8306 @noindent
8307 Because you mention @file{foo.o} but do not give a rule for it, @code{make}
8308 will automatically look for an implicit rule that tells how to update it.
8309 This happens whether or not the file @file{foo.o} currently exists.
8311 If an implicit rule is found, it can supply both commands and one or
8312 more prerequisites (the source files).  You would want to write a rule
8313 for @file{foo.o} with no command lines if you need to specify additional
8314 prerequisites, such as header files, that the implicit rule cannot
8315 supply.
8317 Each implicit rule has a target pattern and prerequisite patterns.  There may
8318 be many implicit rules with the same target pattern.  For example, numerous
8319 rules make @samp{.o} files: one, from a @samp{.c} file with the C compiler;
8320 another, from a @samp{.p} file with the Pascal compiler; and so on.  The rule
8321 that actually applies is the one whose prerequisites exist or can be made.
8322 So, if you have a file @file{foo.c}, @code{make} will run the C compiler;
8323 otherwise, if you have a file @file{foo.p}, @code{make} will run the Pascal
8324 compiler; and so on.
8326 Of course, when you write the makefile, you know which implicit rule you
8327 want @code{make} to use, and you know it will choose that one because you
8328 know which possible prerequisite files are supposed to exist.
8329 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
8330 for a catalogue of all the predefined implicit rules.
8332 Above, we said an implicit rule applies if the required prerequisites ``exist
8333 or can be made''.  A file ``can be made'' if it is mentioned explicitly in
8334 the makefile as a target or a prerequisite, or if an implicit rule can be
8335 recursively found for how to make it.  When an implicit prerequisite is the
8336 result of another implicit rule, we say that @dfn{chaining} is occurring.
8337 @xref{Chained Rules, ,Chains of Implicit Rules}.
8339 In general, @code{make} searches for an implicit rule for each target, and
8340 for each double-colon rule, that has no commands.  A file that is mentioned
8341 only as a prerequisite is considered a target whose rule specifies nothing,
8342 so implicit rule search happens for it.  @xref{Implicit Rule Search, ,Implicit Rule Search Algorithm}, for the
8343 details of how the search is done.
8345 Note that explicit prerequisites do not influence implicit rule search.
8346 For example, consider this explicit rule:
8348 @example
8349 foo.o: foo.p
8350 @end example
8352 @noindent
8353 The prerequisite on @file{foo.p} does not necessarily mean that
8354 @code{make} will remake @file{foo.o} according to the implicit rule to
8355 make an object file, a @file{.o} file, from a Pascal source file, a
8356 @file{.p} file.  For example, if @file{foo.c} also exists, the implicit
8357 rule to make an object file from a C source file is used instead,
8358 because it appears before the Pascal rule in the list of predefined
8359 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
8360 Rules}).
8362 If you do not want an implicit rule to be used for a target that has no
8363 commands, you can give that target empty commands by writing a semicolon
8364 (@pxref{Empty Commands, ,Defining Empty Commands}).
8366 @node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
8367 @section Catalogue of Implicit Rules
8368 @cindex implicit rule, predefined
8369 @cindex rule, implicit, predefined
8371 Here is a catalogue of predefined implicit rules which are always
8372 available unless the makefile explicitly overrides or cancels them.
8373 @xref{Canceling Rules, ,Canceling Implicit Rules}, for information on
8374 canceling or overriding an implicit rule.  The @samp{-r} or
8375 @samp{--no-builtin-rules} option cancels all predefined rules.
8377 This manual only documents the default rules available on POSIX-based
8378 operating systems.  Other operating systems, such as VMS, Windows,
8379 OS/2, etc. may have different sets of default rules.  To see the full
8380 list of default rules and variables available in your version of GNU
8381 @code{make}, run @samp{make -p} in a directory with no makefile.
8383 Not all of these rules will always be defined, even when the @samp{-r}
8384 option is not given.  Many of the predefined implicit rules are
8385 implemented in @code{make} as suffix rules, so which ones will be
8386 defined depends on the @dfn{suffix list} (the list of prerequisites of
8387 the special target @code{.SUFFIXES}).  The default suffix list is:
8388 @code{.out}, @code{.a}, @code{.ln}, @code{.o}, @code{.c}, @code{.cc},
8389 @code{.C}, @code{.cpp}, @code{.p}, @code{.f}, @code{.F}, @code{.m},
8390 @code{.r}, @code{.y}, @code{.l}, @code{.ym}, @code{.lm}, @code{.s},
8391 @code{.S}, @code{.mod}, @code{.sym}, @code{.def}, @code{.h},
8392 @code{.info}, @code{.dvi}, @code{.tex}, @code{.texinfo}, @code{.texi},
8393 @code{.txinfo}, @code{.w}, @code{.ch} @code{.web}, @code{.sh},
8394 @code{.elc}, @code{.el}.  All of the implicit rules described below
8395 whose prerequisites have one of these suffixes are actually suffix
8396 rules.  If you modify the suffix list, the only predefined suffix
8397 rules in effect will be those named by one or two of the suffixes that
8398 are on the list you specify; rules whose suffixes fail to be on the
8399 list are disabled.  @xref{Suffix Rules, ,Old-Fashioned Suffix Rules},
8400 for full details on suffix rules.
8402 @table @asis
8403 @item Compiling C programs
8404 @cindex C, rule to compile
8405 @pindex cc
8406 @pindex gcc
8407 @pindex .o
8408 @pindex .c
8409 @file{@var{n}.o} is made automatically from @file{@var{n}.c} with
8410 a command of the form @samp{$(CC) -c $(CPPFLAGS) $(CFLAGS)}.@refill
8412 @item Compiling C++ programs
8413 @cindex C++, rule to compile
8414 @pindex g++
8415 @pindex .cc
8416 @pindex .cpp
8417 @pindex .C
8418 @file{@var{n}.o} is made automatically from @file{@var{n}.cc},
8419 @file{@var{n}.cpp}, or @file{@var{n}.C} with a command of the form
8420 @samp{$(CXX) -c $(CPPFLAGS) $(CXXFLAGS)}.  We encourage you to use the
8421 suffix @samp{.cc} for C++ source files instead of @samp{.C}.@refill
8423 @item Compiling Pascal programs
8424 @cindex Pascal, rule to compile
8425 @pindex pc
8426 @pindex .p
8427 @file{@var{n}.o} is made automatically from @file{@var{n}.p}
8428 with the command @samp{$(PC) -c $(PFLAGS)}.@refill
8430 @item Compiling Fortran and Ratfor programs
8431 @cindex Fortran, rule to compile
8432 @cindex Ratfor, rule to compile
8433 @pindex f77
8434 @pindex .f
8435 @pindex .r
8436 @pindex .F
8437 @file{@var{n}.o} is made automatically from @file{@var{n}.r},
8438 @file{@var{n}.F} or @file{@var{n}.f} by running the
8439 Fortran compiler.  The precise command used is as follows:@refill
8441 @table @samp
8442 @item .f
8443 @samp{$(FC) -c $(FFLAGS)}.
8444 @item .F
8445 @samp{$(FC) -c $(FFLAGS) $(CPPFLAGS)}.
8446 @item .r
8447 @samp{$(FC) -c $(FFLAGS) $(RFLAGS)}.
8448 @end table
8450 @item Preprocessing Fortran and Ratfor programs
8451 @file{@var{n}.f} is made automatically from @file{@var{n}.r} or
8452 @file{@var{n}.F}.  This rule runs just the preprocessor to convert a
8453 Ratfor or preprocessable Fortran program into a strict Fortran
8454 program.  The precise command used is as follows:@refill
8456 @table @samp
8457 @item .F
8458 @samp{$(FC) -F $(CPPFLAGS) $(FFLAGS)}.
8459 @item .r
8460 @samp{$(FC) -F $(FFLAGS) $(RFLAGS)}.
8461 @end table
8463 @item Compiling Modula-2 programs
8464 @cindex Modula-2, rule to compile
8465 @pindex m2c
8466 @pindex .sym
8467 @pindex .def
8468 @pindex .mod
8469 @file{@var{n}.sym} is made from @file{@var{n}.def} with a command
8470 of the form @samp{$(M2C) $(M2FLAGS) $(DEFFLAGS)}.  @file{@var{n}.o}
8471 is made from @file{@var{n}.mod}; the form is:
8472 @w{@samp{$(M2C) $(M2FLAGS) $(MODFLAGS)}}.@refill
8474 @need 1200
8475 @item Assembling and preprocessing assembler programs
8476 @cindex assembly, rule to compile
8477 @pindex as
8478 @pindex .s
8479 @file{@var{n}.o} is made automatically from @file{@var{n}.s} by
8480 running the assembler, @code{as}.  The precise command is
8481 @samp{$(AS) $(ASFLAGS)}.@refill
8483 @pindex .S
8484 @file{@var{n}.s} is made automatically from @file{@var{n}.S} by
8485 running the C preprocessor, @code{cpp}.  The precise command is
8486 @w{@samp{$(CPP) $(CPPFLAGS)}}.
8488 @item Linking a single object file
8489 @cindex linking, predefined rule for
8490 @pindex ld
8491 @pindex .o
8492 @file{@var{n}} is made automatically from @file{@var{n}.o} by running
8493 the linker (usually called @code{ld}) via the C compiler.  The precise
8494 command used is @w{@samp{$(CC) $(LDFLAGS) @var{n}.o $(LOADLIBES) $(LDLIBS)}}.
8496 This rule does the right thing for a simple program with only one
8497 source file.  It will also do the right thing if there are multiple
8498 object files (presumably coming from various other source files), one
8499 of which has a name matching that of the executable file.  Thus,
8501 @example
8502 x: y.o z.o
8503 @end example
8505 @noindent
8506 when @file{x.c}, @file{y.c} and @file{z.c} all exist will execute:
8508 @example
8509 @group
8510 cc -c x.c -o x.o
8511 cc -c y.c -o y.o
8512 cc -c z.c -o z.o
8513 cc x.o y.o z.o -o x
8514 rm -f x.o
8515 rm -f y.o
8516 rm -f z.o
8517 @end group
8518 @end example
8520 @noindent
8521 In more complicated cases, such as when there is no object file whose
8522 name derives from the executable file name, you must write an explicit
8523 command for linking.
8525 Each kind of file automatically made into @samp{.o} object files will
8526 be automatically linked by using the compiler (@samp{$(CC)},
8527 @samp{$(FC)} or @samp{$(PC)}; the C compiler @samp{$(CC)} is used to
8528 assemble @samp{.s} files) without the @samp{-c} option.  This could be
8529 done by using the @samp{.o} object files as intermediates, but it is
8530 faster to do the compiling and linking in one step, so that's how it's
8531 done.@refill
8533 @item Yacc for C programs
8534 @pindex yacc
8535 @cindex Yacc, rule to run
8536 @pindex .y
8537 @file{@var{n}.c} is made automatically from @file{@var{n}.y} by
8538 running Yacc with the command @samp{$(YACC) $(YFLAGS)}.
8540 @item Lex for C programs
8541 @pindex lex
8542 @cindex Lex, rule to run
8543 @pindex .l
8544 @file{@var{n}.c} is made automatically from @file{@var{n}.l} by
8545 running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
8547 @item Lex for Ratfor programs
8548 @file{@var{n}.r} is made automatically from @file{@var{n}.l} by
8549 running Lex.  The actual command is @samp{$(LEX) $(LFLAGS)}.
8551 The convention of using the same suffix @samp{.l} for all Lex files
8552 regardless of whether they produce C code or Ratfor code makes it
8553 impossible for @code{make} to determine automatically which of the two
8554 languages you are using in any particular case.  If @code{make} is
8555 called upon to remake an object file from a @samp{.l} file, it must
8556 guess which compiler to use.  It will guess the C compiler, because
8557 that is more common.  If you are using Ratfor, make sure @code{make}
8558 knows this by mentioning @file{@var{n}.r} in the makefile.  Or, if you
8559 are using Ratfor exclusively, with no C files, remove @samp{.c} from
8560 the list of implicit rule suffixes with:@refill
8562 @example
8563 @group
8564 .SUFFIXES:
8565 .SUFFIXES: .o .r .f .l @dots{}
8566 @end group
8567 @end example
8569 @item Making Lint Libraries from C, Yacc, or Lex programs
8570 @pindex lint
8571 @cindex @code{lint}, rule to run
8572 @pindex .ln
8573 @file{@var{n}.ln} is made from @file{@var{n}.c} by running @code{lint}.
8574 The precise command is @w{@samp{$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i}}.
8575 The same command is used on the C code produced from
8576 @file{@var{n}.y} or @file{@var{n}.l}.@refill
8578 @item @TeX{} and Web
8579 @cindex @TeX{}, rule to run
8580 @cindex Web, rule to run
8581 @pindex tex
8582 @pindex cweave
8583 @pindex weave
8584 @pindex tangle
8585 @pindex ctangle
8586 @pindex .dvi
8587 @pindex .tex
8588 @pindex .web
8589 @pindex .w
8590 @pindex .ch
8591 @file{@var{n}.dvi} is made from @file{@var{n}.tex} with the command
8592 @samp{$(TEX)}.  @file{@var{n}.tex} is made from @file{@var{n}.web} with
8593 @samp{$(WEAVE)}, or from @file{@var{n}.w} (and from @file{@var{n}.ch} if
8594 it exists or can be made) with @samp{$(CWEAVE)}.  @file{@var{n}.p} is
8595 made from @file{@var{n}.web} with @samp{$(TANGLE)} and @file{@var{n}.c}
8596 is made from @file{@var{n}.w} (and from @file{@var{n}.ch} if it exists
8597 or can be made) with @samp{$(CTANGLE)}.@refill
8599 @item Texinfo and Info
8600 @cindex Texinfo, rule to format
8601 @cindex Info, rule to format
8602 @pindex texi2dvi
8603 @pindex makeinfo
8604 @pindex .texinfo
8605 @pindex .info
8606 @pindex .texi
8607 @pindex .txinfo
8608 @file{@var{n}.dvi} is made from @file{@var{n}.texinfo},
8609 @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with the command
8610 @w{@samp{$(TEXI2DVI) $(TEXI2DVI_FLAGS)}}.  @file{@var{n}.info} is made from
8611 @file{@var{n}.texinfo}, @file{@var{n}.texi}, or @file{@var{n}.txinfo}, with
8612 the command @w{@samp{$(MAKEINFO) $(MAKEINFO_FLAGS)}}.
8614 @item RCS
8615 @cindex RCS, rule to extract from
8616 @pindex co
8617 @pindex ,v @r{(RCS file extension)}
8618 Any file @file{@var{n}} is extracted if necessary from an RCS file
8619 named either @file{@var{n},v} or @file{RCS/@var{n},v}.  The precise
8620 command used is @w{@samp{$(CO) $(COFLAGS)}}.  @file{@var{n}} will not be
8621 extracted from RCS if it already exists, even if the RCS file is
8622 newer.  The rules for RCS are terminal
8623 (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
8624 so RCS files cannot be generated from another source; they must
8625 actually exist.@refill
8627 @item SCCS
8628 @cindex SCCS, rule to extract from
8629 @pindex get
8630 @pindex s. @r{(SCCS file prefix)}
8631 Any file @file{@var{n}} is extracted if necessary from an SCCS file
8632 named either @file{s.@var{n}} or @file{SCCS/s.@var{n}}.  The precise
8633 command used is @w{@samp{$(GET) $(GFLAGS)}}.  The rules for SCCS are
8634 terminal (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}),
8635 so SCCS files cannot be generated from another source; they must
8636 actually exist.@refill
8638 @pindex .sh
8639 For the benefit of SCCS, a file @file{@var{n}} is copied from
8640 @file{@var{n}.sh} and made executable (by everyone).  This is for
8641 shell scripts that are checked into SCCS.  Since RCS preserves the
8642 execution permission of a file, you do not need to use this feature
8643 with RCS.@refill
8645 We recommend that you avoid using of SCCS.  RCS is widely held to be
8646 superior, and is also free.  By choosing free software in place of
8647 comparable (or inferior) proprietary software, you support the free
8648 software movement.
8649 @end table
8651 Usually, you want to change only the variables listed in the table
8652 above, which are documented in the following section.
8654 However, the commands in built-in implicit rules actually use
8655 variables such as @code{COMPILE.c}, @code{LINK.p}, and
8656 @code{PREPROCESS.S}, whose values contain the commands listed above.
8658 @code{make} follows the convention that the rule to compile a
8659 @file{.@var{x}} source file uses the variable @code{COMPILE.@var{x}}.
8660 Similarly, the rule to produce an executable from a @file{.@var{x}}
8661 file uses @code{LINK.@var{x}}; and the rule to preprocess a
8662 @file{.@var{x}} file uses @code{PREPROCESS.@var{x}}.
8664 @vindex OUTPUT_OPTION
8665 Every rule that produces an object file uses the variable
8666 @code{OUTPUT_OPTION}.  @code{make} defines this variable either to
8667 contain @samp{-o $@@}, or to be empty, depending on a compile-time
8668 option.  You need the @samp{-o} option to ensure that the output goes
8669 into the right file when the source file is in a different directory,
8670 as when using @code{VPATH} (@pxref{Directory Search}).  However,
8671 compilers on some systems do not accept a @samp{-o} switch for object
8672 files.  If you use such a system, and use @code{VPATH}, some
8673 compilations will put their output in the wrong place.
8674 A possible workaround for this problem is to give @code{OUTPUT_OPTION}
8675 the value @w{@samp{; mv $*.o $@@}}.
8677 @node Implicit Variables, Chained Rules, Catalogue of Rules, Implicit Rules
8678 @section Variables Used by Implicit Rules
8679 @cindex flags for compilers
8681 The commands in built-in implicit rules make liberal use of certain
8682 predefined variables.  You can alter the values of these variables in
8683 the makefile, with arguments to @code{make}, or in the environment to
8684 alter how the implicit rules work without redefining the rules
8685 themselves.  You can cancel all variables used by implicit rules with
8686 the @samp{-R} or @samp{--no-builtin-variables} option.
8688 For example, the command used to compile a C source file actually says
8689 @samp{$(CC) -c $(CFLAGS) $(CPPFLAGS)}.  The default values of the variables
8690 used are @samp{cc} and nothing, resulting in the command @samp{cc -c}.  By
8691 redefining @samp{CC} to @samp{ncc}, you could cause @samp{ncc} to be
8692 used for all C compilations performed by the implicit rule.  By redefining
8693 @samp{CFLAGS} to be @samp{-g}, you could pass the @samp{-g} option to
8694 each compilation.  @emph{All} implicit rules that do C compilation use
8695 @samp{$(CC)} to get the program name for the compiler and @emph{all}
8696 include @samp{$(CFLAGS)} among the arguments given to the compiler.@refill
8698 The variables used in implicit rules fall into two classes: those that are
8699 names of programs (like @code{CC}) and those that contain arguments for the
8700 programs (like @code{CFLAGS}).  (The ``name of a program'' may also contain
8701 some command arguments, but it must start with an actual executable program
8702 name.)  If a variable value contains more than one argument, separate them
8703 with spaces.
8705 The following tables describe of some of the more commonly-used predefined
8706 variables.  This list is not exhaustive, and the default values shown here may
8707 not be what are selected by @code{make} for your environment.  To see the
8708 complete list of predefined variables for your instance of GNU @code{make} you
8709 can run @samp{make -p} in a directory with no makefiles.
8711 Here is a table of some of the more common variables used as names of
8712 programs in built-in rules:
8713 makefiles.
8715 @table @code
8716 @item AR
8717 @vindex AR
8718 Archive-maintaining program; default @samp{ar}.
8719 @pindex ar
8721 @item AS
8722 @vindex AS
8723 Program for compiling assembly files; default @samp{as}.
8724 @pindex as
8726 @item CC
8727 @vindex CC
8728 Program for compiling C programs; default @samp{cc}.
8729 @pindex cc
8731 @item CXX
8732 @vindex CXX
8733 Program for compiling C++ programs; default @samp{g++}.
8734 @pindex g++
8736 @item CPP
8737 @vindex CPP
8738 Program for running the C preprocessor, with results to standard output;
8739 default @samp{$(CC) -E}.
8741 @item FC
8742 @vindex FC
8743 Program for compiling or preprocessing Fortran and Ratfor programs;
8744 default @samp{f77}.
8745 @pindex f77
8747 @item M2C
8748 @vindex M2C
8749 Program to use to compile Modula-2 source code; default @samp{m2c}.
8750 @pindex m2c
8752 @item PC
8753 @vindex PC
8754 Program for compiling Pascal programs; default @samp{pc}.
8755 @pindex pc
8757 @item CO
8758 @vindex CO
8759 Program for extracting a file from RCS; default @samp{co}.
8760 @pindex co
8762 @item GET
8763 @vindex GET
8764 Program for extracting a file from SCCS; default @samp{get}.
8765 @pindex get
8767 @item LEX
8768 @vindex LEX
8769 Program to use to turn Lex grammars into source code; default @samp{lex}.
8770 @pindex lex
8772 @item YACC
8773 @vindex YACC
8774 Program to use to turn Yacc grammars into source code; default @samp{yacc}.
8775 @pindex yacc
8777 @item LINT
8778 @vindex LINT
8779 Program to use to run lint on source code; default @samp{lint}.
8780 @pindex lint
8782 @item MAKEINFO
8783 @vindex MAKEINFO
8784 Program to convert a Texinfo source file into an Info file; default
8785 @samp{makeinfo}.
8786 @pindex makeinfo
8788 @item TEX
8789 @vindex TEX
8790 Program to make @TeX{} @sc{dvi} files from @TeX{} source;
8791 default @samp{tex}.
8792 @pindex tex
8794 @item TEXI2DVI
8795 @vindex TEXI2DVI
8796 Program to make @TeX{} @sc{dvi} files from Texinfo source;
8797 default @samp{texi2dvi}.
8798 @pindex texi2dvi
8800 @item WEAVE
8801 @vindex WEAVE
8802 Program to translate Web into @TeX{}; default @samp{weave}.
8803 @pindex weave
8805 @item CWEAVE
8806 @vindex CWEAVE
8807 Program to translate C Web into @TeX{}; default @samp{cweave}.
8808 @pindex cweave
8810 @item TANGLE
8811 @vindex TANGLE
8812 Program to translate Web into Pascal; default @samp{tangle}.
8813 @pindex tangle
8815 @item CTANGLE
8816 @vindex CTANGLE
8817 Program to translate C Web into C; default @samp{ctangle}.
8818 @pindex ctangle
8820 @item RM
8821 @vindex RM
8822 Command to remove a file; default @samp{rm -f}.
8823 @pindex rm
8824 @end table
8826 Here is a table of variables whose values are additional arguments for the
8827 programs above.  The default values for all of these is the empty
8828 string, unless otherwise noted.
8830 @table @code
8831 @item ARFLAGS
8832 @vindex ARFLAGS
8833 Flags to give the archive-maintaining program; default @samp{rv}.
8835 @item ASFLAGS
8836 @vindex ASFLAGS
8837 Extra flags to give to the assembler (when explicitly
8838 invoked on a @samp{.s} or @samp{.S} file).
8840 @item CFLAGS
8841 @vindex CFLAGS
8842 Extra flags to give to the C compiler.
8844 @item CXXFLAGS
8845 @vindex CXXFLAGS
8846 Extra flags to give to the C++ compiler.
8848 @item COFLAGS
8849 @vindex COFLAGS
8850 Extra flags to give to the RCS @code{co} program.
8852 @item CPPFLAGS
8853 @vindex CPPFLAGS
8854 Extra flags to give to the C preprocessor and programs
8855 that use it (the C and Fortran compilers).
8857 @item FFLAGS
8858 @vindex FFLAGS
8859 Extra flags to give to the Fortran compiler.
8861 @item GFLAGS
8862 @vindex GFLAGS
8863 Extra flags to give to the SCCS @code{get} program.
8865 @item LDFLAGS
8866 @vindex LDFLAGS
8867 Extra flags to give to compilers when they are supposed to invoke the linker,
8868 @samp{ld}.
8870 @item LFLAGS
8871 @vindex LFLAGS
8872 Extra flags to give to Lex.
8874 @item YFLAGS
8875 @vindex YFLAGS
8876 Extra flags to give to Yacc.
8878 @item PFLAGS
8879 @vindex PFLAGS
8880 Extra flags to give to the Pascal compiler.
8882 @item RFLAGS
8883 @vindex RFLAGS
8884 Extra flags to give to the Fortran compiler for Ratfor programs.
8886 @item LINTFLAGS
8887 @vindex LINTFLAGS
8888 Extra flags to give to lint.
8889 @end table
8891 @node Chained Rules, Pattern Rules, Implicit Variables, Implicit Rules
8892 @section Chains of Implicit Rules
8894 @cindex chains of rules
8895 @cindex rule, implicit, chains of
8896 Sometimes a file can be made by a sequence of implicit rules.  For example,
8897 a file @file{@var{n}.o} could be made from @file{@var{n}.y} by running
8898 first Yacc and then @code{cc}.  Such a sequence is called a @dfn{chain}.
8900 If the file @file{@var{n}.c} exists, or is mentioned in the makefile, no
8901 special searching is required: @code{make} finds that the object file can
8902 be made by C compilation from @file{@var{n}.c}; later on, when considering
8903 how to make @file{@var{n}.c}, the rule for running Yacc is
8904 used.  Ultimately both @file{@var{n}.c} and @file{@var{n}.o} are
8905 updated.@refill
8907 @cindex intermediate files
8908 @cindex files, intermediate
8909 However, even if @file{@var{n}.c} does not exist and is not mentioned,
8910 @code{make} knows how to envision it as the missing link between
8911 @file{@var{n}.o} and @file{@var{n}.y}!  In this case, @file{@var{n}.c} is
8912 called an @dfn{intermediate file}.  Once @code{make} has decided to use the
8913 intermediate file, it is entered in the data base as if it had been
8914 mentioned in the makefile, along with the implicit rule that says how to
8915 create it.@refill
8917 Intermediate files are remade using their rules just like all other
8918 files.  But intermediate files are treated differently in two ways.
8920 The first difference is what happens if the intermediate file does not
8921 exist.  If an ordinary file @var{b} does not exist, and @code{make}
8922 considers a target that depends on @var{b}, it invariably creates
8923 @var{b} and then updates the target from @var{b}.  But if @var{b} is an
8924 intermediate file, then @code{make} can leave well enough alone.  It
8925 won't bother updating @var{b}, or the ultimate target, unless some
8926 prerequisite of @var{b} is newer than that target or there is some other
8927 reason to update that target.
8929 The second difference is that if @code{make} @emph{does} create @var{b}
8930 in order to update something else, it deletes @var{b} later on after it
8931 is no longer needed.  Therefore, an intermediate file which did not
8932 exist before @code{make} also does not exist after @code{make}.
8933 @code{make} reports the deletion to you by printing a @samp{rm -f}
8934 command showing which file it is deleting.
8936 Ordinarily, a file cannot be intermediate if it is mentioned in the
8937 makefile as a target or prerequisite.  However, you can explicitly mark a
8938 file as intermediate by listing it as a prerequisite of the special target
8939 @code{.INTERMEDIATE}.  This takes effect even if the file is mentioned
8940 explicitly in some other way.
8942 @cindex intermediate files, preserving
8943 @cindex preserving intermediate files
8944 @cindex secondary files
8945 You can prevent automatic deletion of an intermediate file by marking it
8946 as a @dfn{secondary} file.  To do this, list it as a prerequisite of the
8947 special target @code{.SECONDARY}.  When a file is secondary, @code{make}
8948 will not create the file merely because it does not already exist, but
8949 @code{make} does not automatically delete the file.  Marking a file as
8950 secondary also marks it as intermediate.
8952 You can list the target pattern of an implicit rule (such as @samp{%.o})
8953 as a prerequisite of the special target @code{.PRECIOUS} to preserve
8954 intermediate files made by implicit rules whose target patterns match
8955 that file's name; see @ref{Interrupts}.@refill
8956 @cindex preserving with @code{.PRECIOUS}
8957 @cindex @code{.PRECIOUS} intermediate files
8959 A chain can involve more than two implicit rules.  For example, it is
8960 possible to make a file @file{foo} from @file{RCS/foo.y,v} by running RCS,
8961 Yacc and @code{cc}.  Then both @file{foo.y} and @file{foo.c} are
8962 intermediate files that are deleted at the end.@refill
8964 No single implicit rule can appear more than once in a chain.  This means
8965 that @code{make} will not even consider such a ridiculous thing as making
8966 @file{foo} from @file{foo.o.o} by running the linker twice.  This
8967 constraint has the added benefit of preventing any infinite loop in the
8968 search for an implicit rule chain.
8970 There are some special implicit rules to optimize certain cases that would
8971 otherwise be handled by rule chains.  For example, making @file{foo} from
8972 @file{foo.c} could be handled by compiling and linking with separate
8973 chained rules, using @file{foo.o} as an intermediate file.  But what
8974 actually happens is that a special rule for this case does the compilation
8975 and linking with a single @code{cc} command.  The optimized rule is used in
8976 preference to the step-by-step chain because it comes earlier in the
8977 ordering of rules.
8979 @node Pattern Rules, Last Resort, Chained Rules, Implicit Rules
8980 @section Defining and Redefining Pattern Rules
8982 You define an implicit rule by writing a @dfn{pattern rule}.  A pattern
8983 rule looks like an ordinary rule, except that its target contains the
8984 character @samp{%} (exactly one of them).  The target is considered a
8985 pattern for matching file names; the @samp{%} can match any nonempty
8986 substring, while other characters match only themselves.  The prerequisites
8987 likewise use @samp{%} to show how their names relate to the target name.
8989 Thus, a pattern rule @samp{%.o : %.c} says how to make any file
8990 @file{@var{stem}.o} from another file @file{@var{stem}.c}.@refill
8992 Note that expansion using @samp{%} in pattern rules occurs
8993 @strong{after} any variable or function expansions, which take place
8994 when the makefile is read.  @xref{Using Variables, , How to Use
8995 Variables}, and @ref{Functions, ,Functions for Transforming Text}.
8997 @menu
8998 * Pattern Intro::               An introduction to pattern rules.
8999 * Pattern Examples::            Examples of pattern rules.
9000 * Automatic Variables::         How to use automatic variables in the
9001                                   commands of implicit rules.
9002 * Pattern Match::               How patterns match.
9003 * Match-Anything Rules::        Precautions you should take prior to
9004                                   defining rules that can match any
9005                                   target file whatever.
9006 * Canceling Rules::             How to override or cancel built-in rules.
9007 @end menu
9009 @node Pattern Intro, Pattern Examples, Pattern Rules, Pattern Rules
9010 @subsection Introduction to Pattern Rules
9011 @cindex pattern rule
9012 @cindex rule, pattern
9014 A pattern rule contains the character @samp{%} (exactly one of them)
9015 in the target; otherwise, it looks exactly like an ordinary rule.  The
9016 target is a pattern for matching file names; the @samp{%} matches any
9017 nonempty substring, while other characters match only themselves.
9018 @cindex target pattern, implicit
9019 @cindex @code{%}, in pattern rules
9021 For example, @samp{%.c} as a pattern matches any file name that ends in
9022 @samp{.c}.  @samp{s.%.c} as a pattern matches any file name that starts
9023 with @samp{s.}, ends in @samp{.c} and is at least five characters long.
9024 (There must be at least one character to match the @samp{%}.)  The substring
9025 that the @samp{%} matches is called the @dfn{stem}.@refill
9027 @samp{%} in a prerequisite of a pattern rule stands for the same stem
9028 that was matched by the @samp{%} in the target.  In order for the
9029 pattern rule to apply, its target pattern must match the file name
9030 under consideration and all of its prerequisites (after pattern
9031 substitution) must name files that exist or can be made.  These files
9032 become prerequisites of the target.
9033 @cindex prerequisite pattern, implicit
9035 Thus, a rule of the form
9037 @example
9038 %.o : %.c ; @var{command}@dots{}
9039 @end example
9041 @noindent
9042 specifies how to make a file @file{@var{n}.o}, with another file
9043 @file{@var{n}.c} as its prerequisite, provided that @file{@var{n}.c}
9044 exists or can be made.
9046 There may also be prerequisites that do not use @samp{%}; such a prerequisite
9047 attaches to every file made by this pattern rule.  These unvarying
9048 prerequisites are useful occasionally.
9050 A pattern rule need not have any prerequisites that contain @samp{%}, or
9051 in fact any prerequisites at all.  Such a rule is effectively a general
9052 wildcard.  It provides a way to make any file that matches the target
9053 pattern.  @xref{Last Resort}.
9055 @c !!! The end of of this paragraph should be rewritten.  --bob
9056 Pattern rules may have more than one target.  Unlike normal rules, this
9057 does not act as many different rules with the same prerequisites and
9058 commands.  If a pattern rule has multiple targets, @code{make} knows that
9059 the rule's commands are responsible for making all of the targets.  The
9060 commands are executed only once to make all the targets.  When searching
9061 for a pattern rule to match a target, the target patterns of a rule other
9062 than the one that matches the target in need of a rule are incidental:
9063 @code{make} worries only about giving commands and prerequisites to the file
9064 presently in question.  However, when this file's commands are run, the
9065 other targets are marked as having been updated themselves.
9066 @cindex multiple targets, in pattern rule
9067 @cindex target, multiple in pattern rule
9069 The order in which pattern rules appear in the makefile is important
9070 since this is the order in which they are considered.
9071 Of equally applicable
9072 rules, only the first one found is used.  The rules you write take precedence
9073 over those that are built in.  Note however, that a rule whose
9074 prerequisites actually exist or are mentioned always takes priority over a
9075 rule with prerequisites that must be made by chaining other implicit rules.
9076 @cindex pattern rules, order of
9077 @cindex order of pattern rules
9079 @node Pattern Examples, Automatic Variables, Pattern Intro, Pattern Rules
9080 @subsection Pattern Rule Examples
9082 Here are some examples of pattern rules actually predefined in
9083 @code{make}.  First, the rule that compiles @samp{.c} files into @samp{.o}
9084 files:@refill
9086 @example
9087 %.o : %.c
9088         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@@
9089 @end example
9091 @noindent
9092 defines a rule that can make any file @file{@var{x}.o} from
9093 @file{@var{x}.c}.  The command uses the automatic variables @samp{$@@} and
9094 @samp{$<} to substitute the names of the target file and the source file
9095 in each case where the rule applies (@pxref{Automatic Variables}).@refill
9097 Here is a second built-in rule:
9099 @example
9100 % :: RCS/%,v
9101         $(CO) $(COFLAGS) $<
9102 @end example
9104 @noindent
9105 defines a rule that can make any file @file{@var{x}} whatsoever from a
9106 corresponding file @file{@var{x},v} in the subdirectory @file{RCS}.  Since
9107 the target is @samp{%}, this rule will apply to any file whatever, provided
9108 the appropriate prerequisite file exists.  The double colon makes the rule
9109 @dfn{terminal}, which means that its prerequisite may not be an intermediate
9110 file (@pxref{Match-Anything Rules, ,Match-Anything Pattern Rules}).@refill
9112 @need 500
9113 This pattern rule has two targets:
9115 @example
9116 @group
9117 %.tab.c %.tab.h: %.y
9118         bison -d $<
9119 @end group
9120 @end example
9122 @noindent
9123 @c The following paragraph is rewritten to avoid overfull hboxes
9124 This tells @code{make} that the command @samp{bison -d @var{x}.y} will
9125 make both @file{@var{x}.tab.c} and @file{@var{x}.tab.h}.  If the file
9126 @file{foo} depends on the files @file{parse.tab.o} and @file{scan.o}
9127 and the file @file{scan.o} depends on the file @file{parse.tab.h},
9128 when @file{parse.y} is changed, the command @samp{bison -d parse.y}
9129 will be executed only once, and the prerequisites of both
9130 @file{parse.tab.o} and @file{scan.o} will be satisfied.  (Presumably
9131 the file @file{parse.tab.o} will be recompiled from @file{parse.tab.c}
9132 and the file @file{scan.o} from @file{scan.c}, while @file{foo} is
9133 linked from @file{parse.tab.o}, @file{scan.o}, and its other
9134 prerequisites, and it will execute happily ever after.)@refill
9136 @node Automatic Variables, Pattern Match, Pattern Examples, Pattern Rules
9137 @subsection Automatic Variables
9138 @cindex automatic variables
9139 @cindex variables, automatic
9140 @cindex variables, and implicit rule
9142 Suppose you are writing a pattern rule to compile a @samp{.c} file into a
9143 @samp{.o} file: how do you write the @samp{cc} command so that it operates
9144 on the right source file name?  You cannot write the name in the command,
9145 because the name is different each time the implicit rule is applied.
9147 What you do is use a special feature of @code{make}, the @dfn{automatic
9148 variables}.  These variables have values computed afresh for each rule that
9149 is executed, based on the target and prerequisites of the rule.  In this
9150 example, you would use @samp{$@@} for the object file name and @samp{$<}
9151 for the source file name.
9153 @cindex automatic variables in prerequisites
9154 @cindex prerequisites, and automatic variables
9155 It's very important that you recognize the limited scope in which
9156 automatic variable values are available: they only have values within
9157 the command script.  In particular, you cannot use them anywhere
9158 within the target list of a rule; they have no value there and will
9159 expand to the empty string.  Also, they cannot be accessed directly
9160 within the prerequisite list of a rule.  A common mistake is
9161 attempting to use @code{$@@} within the prerequisites list; this will
9162 not work.  However, there is a special feature of GNU @code{make},
9163 secondary expansion (@pxref{Secondary Expansion}), which will allow
9164 automatic variable values to be used in prerequisite lists.
9166 Here is a table of automatic variables:
9168 @table @code
9169 @vindex $@@
9170 @vindex @@ @r{(automatic variable)}
9171 @item $@@
9172 The file name of the target of the rule.  If the target is an archive
9173 member, then @samp{$@@} is the name of the archive file.  In a pattern
9174 rule that has multiple targets (@pxref{Pattern Intro, ,Introduction to
9175 Pattern Rules}), @samp{$@@} is the name of whichever target caused the
9176 rule's commands to be run.
9178 @vindex $%
9179 @vindex % @r{(automatic variable)}
9180 @item $%
9181 The target member name, when the target is an archive member.
9182 @xref{Archives}.  For example, if the target is @file{foo.a(bar.o)} then
9183 @samp{$%} is @file{bar.o} and @samp{$@@} is @file{foo.a}.  @samp{$%} is
9184 empty when the target is not an archive member.
9186 @vindex $<
9187 @vindex < @r{(automatic variable)}
9188 @item $<
9189 The name of the first prerequisite.  If the target got its commands from
9190 an implicit rule, this will be the first prerequisite added by the
9191 implicit rule (@pxref{Implicit Rules}).
9193 @vindex $?
9194 @vindex ? @r{(automatic variable)}
9195 @item $?
9196 The names of all the prerequisites that are newer than the target, with
9197 spaces between them.  For prerequisites which are archive members, only
9198 the member named is used (@pxref{Archives}).
9199 @cindex prerequisites, list of changed
9200 @cindex list of changed prerequisites
9202 @vindex $^
9203 @vindex ^ @r{(automatic variable)}
9204 @item $^
9205 The names of all the prerequisites, with spaces between them.  For
9206 prerequisites which are archive members, only the member named is used
9207 (@pxref{Archives}).  A target has only one prerequisite on each other file
9208 it depends on, no matter how many times each file is listed as a
9209 prerequisite.  So if you list a prerequisite more than once for a target,
9210 the value of @code{$^} contains just one copy of the name.  This list
9211 does @strong{not} contain any of the order-only prerequisites; for those
9212 see the @samp{$|} variable, below.
9213 @cindex prerequisites, list of all
9214 @cindex list of all prerequisites
9216 @vindex $+
9217 @vindex + @r{(automatic variable)}
9218 @item $+
9219 This is like @samp{$^}, but prerequisites listed more than once are
9220 duplicated in the order they were listed in the makefile.  This is
9221 primarily useful for use in linking commands where it is meaningful to
9222 repeat library file names in a particular order.
9224 @vindex $|
9225 @vindex | @r{(automatic variable)}
9226 @item $|
9227 The names of all the order-only prerequisites, with spaces between
9228 them.
9230 @vindex $*
9231 @vindex * @r{(automatic variable)}
9232 @item $*
9233 The stem with which an implicit rule matches (@pxref{Pattern Match, ,How
9234 Patterns Match}).  If the target is @file{dir/a.foo.b} and the target
9235 pattern is @file{a.%.b} then the stem is @file{dir/foo}.  The stem is
9236 useful for constructing names of related files.@refill
9237 @cindex stem, variable for
9239 In a static pattern rule, the stem is part of the file name that matched
9240 the @samp{%} in the target pattern.
9242 In an explicit rule, there is no stem; so @samp{$*} cannot be determined
9243 in that way.  Instead, if the target name ends with a recognized suffix
9244 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}), @samp{$*} is set to
9245 the target name minus the suffix.  For example, if the target name is
9246 @samp{foo.c}, then @samp{$*} is set to @samp{foo}, since @samp{.c} is a
9247 suffix.  GNU @code{make} does this bizarre thing only for compatibility
9248 with other implementations of @code{make}.  You should generally avoid
9249 using @samp{$*} except in implicit rules or static pattern rules.@refill
9251 If the target name in an explicit rule does not end with a recognized
9252 suffix, @samp{$*} is set to the empty string for that rule.
9253 @end table
9255 @samp{$?} is useful even in explicit rules when you wish to operate on only
9256 the prerequisites that have changed.  For example, suppose that an archive
9257 named @file{lib} is supposed to contain copies of several object files.
9258 This rule copies just the changed object files into the archive:
9260 @example
9261 @group
9262 lib: foo.o bar.o lose.o win.o
9263         ar r lib $?
9264 @end group
9265 @end example
9267 Of the variables listed above, four have values that are single file
9268 names, and three have values that are lists of file names.  These seven
9269 have variants that get just the file's directory name or just the file
9270 name within the directory.  The variant variables' names are formed by
9271 appending @samp{D} or @samp{F}, respectively.  These variants are
9272 semi-obsolete in GNU @code{make} since the functions @code{dir} and
9273 @code{notdir} can be used to get a similar effect (@pxref{File Name
9274 Functions, , Functions for File Names}).  Note, however, that the
9275 @samp{D} variants all omit the trailing slash which always appears in
9276 the output of the @code{dir} function.  Here is a table of the variants:
9278 @table @samp
9279 @vindex $(@@D)
9280 @vindex @@D @r{(automatic variable)}
9281 @item $(@@D)
9282 The directory part of the file name of the target, with the trailing
9283 slash removed.  If the value of @samp{$@@} is @file{dir/foo.o} then
9284 @samp{$(@@D)} is @file{dir}.  This value is @file{.} if @samp{$@@} does
9285 not contain a slash.
9287 @vindex $(@@F)
9288 @vindex @@F @r{(automatic variable)}
9289 @item $(@@F)
9290 The file-within-directory part of the file name of the target.  If the
9291 value of @samp{$@@} is @file{dir/foo.o} then @samp{$(@@F)} is
9292 @file{foo.o}.  @samp{$(@@F)} is equivalent to @samp{$(notdir $@@)}.
9294 @vindex $(*D)
9295 @vindex *D @r{(automatic variable)}
9296 @item $(*D)
9297 @vindex $(*F)
9298 @vindex *F @r{(automatic variable)}
9299 @itemx $(*F)
9300 The directory part and the file-within-directory
9301 part of the stem; @file{dir} and @file{foo} in this example.
9303 @vindex $(%D)
9304 @vindex %D @r{(automatic variable)}
9305 @item $(%D)
9306 @vindex $(%F)
9307 @vindex %F @r{(automatic variable)}
9308 @itemx $(%F)
9309 The directory part and the file-within-directory part of the target
9310 archive member name.  This makes sense only for archive member targets
9311 of the form @file{@var{archive}(@var{member})} and is useful only when
9312 @var{member} may contain a directory name.  (@xref{Archive Members,
9313 ,Archive Members as Targets}.)
9315 @vindex $(<D)
9316 @vindex <D @r{(automatic variable)}
9317 @item $(<D)
9318 @vindex $(<F)
9319 @vindex <F @r{(automatic variable)}
9320 @itemx $(<F)
9321 The directory part and the file-within-directory
9322 part of the first prerequisite.
9324 @vindex $(^D)
9325 @vindex ^D @r{(automatic variable)}
9326 @item $(^D)
9327 @vindex $(^F)
9328 @vindex ^F @r{(automatic variable)}
9329 @itemx $(^F)
9330 Lists of the directory parts and the file-within-directory
9331 parts of all prerequisites.
9333 @vindex $(+D)
9334 @vindex +D @r{(automatic variable)}
9335 @item $(+D)
9336 @vindex $(+F)
9337 @vindex +F @r{(automatic variable)}
9338 @itemx $(+F)
9339 Lists of the directory parts and the file-within-directory
9340 parts of all prerequisites, including multiple instances of duplicated
9341 prerequisites.
9343 @vindex $(?D)
9344 @vindex ?D @r{(automatic variable)}
9345 @item $(?D)
9346 @vindex $(?F)
9347 @vindex ?F @r{(automatic variable)}
9348 @itemx $(?F)
9349 Lists of the directory parts and the file-within-directory parts of
9350 all prerequisites that are newer than the target.
9351 @end table
9353 Note that we use a special stylistic convention when we talk about these
9354 automatic variables; we write ``the value of @samp{$<}'', rather than
9355 @w{``the variable @code{<}''} as we would write for ordinary variables
9356 such as @code{objects} and @code{CFLAGS}.  We think this convention
9357 looks more natural in this special case.  Please do not assume it has a
9358 deep significance; @samp{$<} refers to the variable named @code{<} just
9359 as @samp{$(CFLAGS)} refers to the variable named @code{CFLAGS}.
9360 You could just as well use @samp{$(<)} in place of @samp{$<}.
9362 @node Pattern Match, Match-Anything Rules, Automatic Variables, Pattern Rules
9363 @subsection How Patterns Match
9365 @cindex stem
9366 A target pattern is composed of a @samp{%} between a prefix and a suffix,
9367 either or both of which may be empty.  The pattern matches a file name only
9368 if the file name starts with the prefix and ends with the suffix, without
9369 overlap.  The text between the prefix and the suffix is called the
9370 @dfn{stem}.  Thus, when the pattern @samp{%.o} matches the file name
9371 @file{test.o}, the stem is @samp{test}.  The pattern rule prerequisites are
9372 turned into actual file names by substituting the stem for the character
9373 @samp{%}.  Thus, if in the same example one of the prerequisites is written
9374 as @samp{%.c}, it expands to @samp{test.c}.@refill
9376 When the target pattern does not contain a slash (and it usually does
9377 not), directory names in the file names are removed from the file name
9378 before it is compared with the target prefix and suffix.  After the
9379 comparison of the file name to the target pattern, the directory
9380 names, along with the slash that ends them, are added on to the
9381 prerequisite file names generated from the pattern rule's prerequisite
9382 patterns and the file name.  The directories are ignored only for the
9383 purpose of finding an implicit rule to use, not in the application of
9384 that rule.  Thus, @samp{e%t} matches the file name @file{src/eat},
9385 with @samp{src/a} as the stem.  When prerequisites are turned into file
9386 names, the directories from the stem are added at the front, while the
9387 rest of the stem is substituted for the @samp{%}.  The stem
9388 @samp{src/a} with a prerequisite pattern @samp{c%r} gives the file name
9389 @file{src/car}.@refill
9391 @node Match-Anything Rules, Canceling Rules, Pattern Match, Pattern Rules
9392 @subsection Match-Anything Pattern Rules
9394 @cindex match-anything rule
9395 @cindex terminal rule
9396 When a pattern rule's target is just @samp{%}, it matches any file name
9397 whatever.  We call these rules @dfn{match-anything} rules.  They are very
9398 useful, but it can take a lot of time for @code{make} to think about them,
9399 because it must consider every such rule for each file name listed either
9400 as a target or as a prerequisite.
9402 Suppose the makefile mentions @file{foo.c}.  For this target, @code{make}
9403 would have to consider making it by linking an object file @file{foo.c.o},
9404 or by C compilation-and-linking in one step from @file{foo.c.c}, or by
9405 Pascal compilation-and-linking from @file{foo.c.p}, and many other
9406 possibilities.
9408 We know these possibilities are ridiculous since @file{foo.c} is a C source
9409 file, not an executable.  If @code{make} did consider these possibilities,
9410 it would ultimately reject them, because files such as @file{foo.c.o} and
9411 @file{foo.c.p} would not exist.  But these possibilities are so
9412 numerous that @code{make} would run very slowly if it had to consider
9413 them.@refill
9415 To gain speed, we have put various constraints on the way @code{make}
9416 considers match-anything rules.  There are two different constraints that
9417 can be applied, and each time you define a match-anything rule you must
9418 choose one or the other for that rule.
9420 One choice is to mark the match-anything rule as @dfn{terminal} by defining
9421 it with a double colon.  When a rule is terminal, it does not apply unless
9422 its prerequisites actually exist.  Prerequisites that could be made with
9423 other implicit rules are not good enough.  In other words, no further
9424 chaining is allowed beyond a terminal rule.
9426 For example, the built-in implicit rules for extracting sources from RCS
9427 and SCCS files are terminal; as a result, if the file @file{foo.c,v} does
9428 not exist, @code{make} will not even consider trying to make it as an
9429 intermediate file from @file{foo.c,v.o} or from @file{RCS/SCCS/s.foo.c,v}.
9430 RCS and SCCS files are generally ultimate source files, which should not be
9431 remade from any other files; therefore, @code{make} can save time by not
9432 looking for ways to remake them.@refill
9434 If you do not mark the match-anything rule as terminal, then it is
9435 nonterminal.  A nonterminal match-anything rule cannot apply to a file name
9436 that indicates a specific type of data.  A file name indicates a specific
9437 type of data if some non-match-anything implicit rule target matches it.
9439 For example, the file name @file{foo.c} matches the target for the pattern
9440 rule @samp{%.c : %.y} (the rule to run Yacc).  Regardless of whether this
9441 rule is actually applicable (which happens only if there is a file
9442 @file{foo.y}), the fact that its target matches is enough to prevent
9443 consideration of any nonterminal match-anything rules for the file
9444 @file{foo.c}.  Thus, @code{make} will not even consider trying to make
9445 @file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
9446 @file{foo.c.p}, etc.@refill
9448 The motivation for this constraint is that nonterminal match-anything
9449 rules are used for making files containing specific types of data (such as
9450 executable files) and a file name with a recognized suffix indicates some
9451 other specific type of data (such as a C source file).
9453 Special built-in dummy pattern rules are provided solely to recognize
9454 certain file names so that nonterminal match-anything rules will not be
9455 considered.  These dummy rules have no prerequisites and no commands, and
9456 they are ignored for all other purposes.  For example, the built-in
9457 implicit rule
9459 @example
9460 %.p :
9461 @end example
9463 @noindent
9464 exists to make sure that Pascal source files such as @file{foo.p} match a
9465 specific target pattern and thereby prevent time from being wasted looking
9466 for @file{foo.p.o} or @file{foo.p.c}.
9468 Dummy pattern rules such as the one for @samp{%.p} are made for every
9469 suffix listed as valid for use in suffix rules (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}).
9471 @node Canceling Rules,  , Match-Anything Rules, Pattern Rules
9472 @subsection Canceling Implicit Rules
9474 You can override a built-in implicit rule (or one you have defined
9475 yourself) by defining a new pattern rule with the same target and
9476 prerequisites, but different commands.  When the new rule is defined, the
9477 built-in one is replaced.  The new rule's position in the sequence of
9478 implicit rules is determined by where you write the new rule.
9480 You can cancel a built-in implicit rule by defining a pattern rule with the
9481 same target and prerequisites, but no commands.  For example, the following
9482 would cancel the rule that runs the assembler:
9484 @example
9485 %.o : %.s
9486 @end example
9488 @node Last Resort, Suffix Rules, Pattern Rules, Implicit Rules
9489 @section Defining Last-Resort Default Rules
9490 @cindex last-resort default rules
9491 @cindex default rules, last-resort
9493 You can define a last-resort implicit rule by writing a terminal
9494 match-anything pattern rule with no prerequisites (@pxref{Match-Anything
9495 Rules}).  This is just like any other pattern rule; the only thing
9496 special about it is that it will match any target.  So such a rule's
9497 commands are used for all targets and prerequisites that have no commands
9498 of their own and for which no other implicit rule applies.
9500 For example, when testing a makefile, you might not care if the source
9501 files contain real data, only that they exist.  Then you might do this:
9503 @example
9505         touch $@@
9506 @end example
9508 @noindent
9509 to cause all the source files needed (as prerequisites) to be created
9510 automatically.
9512 @findex .DEFAULT
9513 You can instead define commands to be used for targets for which there
9514 are no rules at all, even ones which don't specify commands.  You do
9515 this by writing a rule for the target @code{.DEFAULT}.  Such a rule's
9516 commands are used for all prerequisites which do not appear as targets in
9517 any explicit rule, and for which no implicit rule applies.  Naturally,
9518 there is no @code{.DEFAULT} rule unless you write one.
9520 If you use @code{.DEFAULT} with no commands or prerequisites:
9522 @example
9523 .DEFAULT:
9524 @end example
9526 @noindent
9527 the commands previously stored for @code{.DEFAULT} are cleared.
9528 Then @code{make} acts as if you had never defined @code{.DEFAULT} at all.
9530 If you do not want a target to get the commands from a match-anything
9531 pattern rule or @code{.DEFAULT}, but you also do not want any commands
9532 to be run for the target, you can give it empty commands (@pxref{Empty
9533 Commands, ,Defining Empty Commands}).@refill
9535 You can use a last-resort rule to override part of another makefile.
9536 @xref{Overriding Makefiles, , Overriding Part of Another Makefile}.
9538 @node Suffix Rules, Implicit Rule Search, Last Resort, Implicit Rules
9539 @section Old-Fashioned Suffix Rules
9540 @cindex old-fashioned suffix rules
9541 @cindex suffix rule
9543 @dfn{Suffix rules} are the old-fashioned way of defining implicit rules for
9544 @code{make}.  Suffix rules are obsolete because pattern rules are more
9545 general and clearer.  They are supported in GNU @code{make} for
9546 compatibility with old makefiles.  They come in two kinds:
9547 @dfn{double-suffix} and @dfn{single-suffix}.@refill
9549 A double-suffix rule is defined by a pair of suffixes: the target suffix
9550 and the source suffix.  It matches any file whose name ends with the
9551 target suffix.  The corresponding implicit prerequisite is made by
9552 replacing the target suffix with the source suffix in the file name.  A
9553 two-suffix rule whose target and source suffixes are @samp{.o} and
9554 @samp{.c} is equivalent to the pattern rule @samp{%.o : %.c}.
9556 A single-suffix rule is defined by a single suffix, which is the source
9557 suffix.  It matches any file name, and the corresponding implicit
9558 prerequisite name is made by appending the source suffix.  A single-suffix
9559 rule whose source suffix is @samp{.c} is equivalent to the pattern rule
9560 @samp{% : %.c}.
9562 Suffix rule definitions are recognized by comparing each rule's target
9563 against a defined list of known suffixes.  When @code{make} sees a rule
9564 whose target is a known suffix, this rule is considered a single-suffix
9565 rule.  When @code{make} sees a rule whose target is two known suffixes
9566 concatenated, this rule is taken as a double-suffix rule.
9568 For example, @samp{.c} and @samp{.o} are both on the default list of
9569 known suffixes.  Therefore, if you define a rule whose target is
9570 @samp{.c.o}, @code{make} takes it to be a double-suffix rule with source
9571 suffix @samp{.c} and target suffix @samp{.o}.  Here is the old-fashioned
9572 way to define the rule for compiling a C source file:@refill
9574 @example
9575 .c.o:
9576         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
9577 @end example
9579 Suffix rules cannot have any prerequisites of their own.  If they have any,
9580 they are treated as normal files with funny names, not as suffix rules.
9581 Thus, the rule:
9583 @example
9584 .c.o: foo.h
9585         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
9586 @end example
9588 @noindent
9589 tells how to make the file @file{.c.o} from the prerequisite file
9590 @file{foo.h}, and is not at all like the pattern rule:
9592 @example
9593 %.o: %.c foo.h
9594         $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@@ $<
9595 @end example
9597 @noindent
9598 which tells how to make @samp{.o} files from @samp{.c} files, and makes all
9599 @samp{.o} files using this pattern rule also depend on @file{foo.h}.
9601 Suffix rules with no commands are also meaningless.  They do not remove
9602 previous rules as do pattern rules with no commands (@pxref{Canceling
9603 Rules, , Canceling Implicit Rules}).  They simply enter the suffix or pair of suffixes concatenated as
9604 a target in the data base.@refill
9606 @findex .SUFFIXES
9607 The known suffixes are simply the names of the prerequisites of the special
9608 target @code{.SUFFIXES}.  You can add your own suffixes by writing a rule
9609 for @code{.SUFFIXES} that adds more prerequisites, as in:
9611 @example
9612 .SUFFIXES: .hack .win
9613 @end example
9615 @noindent
9616 which adds @samp{.hack} and @samp{.win} to the end of the list of suffixes.
9618 If you wish to eliminate the default known suffixes instead of just adding
9619 to them, write a rule for @code{.SUFFIXES} with no prerequisites.  By
9620 special dispensation, this eliminates all existing prerequisites of
9621 @code{.SUFFIXES}.  You can then write another rule to add the suffixes you
9622 want.  For example,
9624 @example
9625 @group
9626 .SUFFIXES:            # @r{Delete the default suffixes}
9627 .SUFFIXES: .c .o .h   # @r{Define our suffix list}
9628 @end group
9629 @end example
9631 The @samp{-r} or @samp{--no-builtin-rules} flag causes the default
9632 list of suffixes to be empty.
9634 @vindex SUFFIXES
9635 The variable @code{SUFFIXES} is defined to the default list of suffixes
9636 before @code{make} reads any makefiles.  You can change the list of suffixes
9637 with a rule for the special target @code{.SUFFIXES}, but that does not alter
9638 this variable.
9640 @node Implicit Rule Search,  , Suffix Rules, Implicit Rules
9641 @section Implicit Rule Search Algorithm
9642 @cindex implicit rule, search algorithm
9643 @cindex search algorithm, implicit rule
9645 Here is the procedure @code{make} uses for searching for an implicit rule
9646 for a target @var{t}.  This procedure is followed for each double-colon
9647 rule with no commands, for each target of ordinary rules none of which have
9648 commands, and for each prerequisite that is not the target of any rule.  It
9649 is also followed recursively for prerequisites that come from implicit
9650 rules, in the search for a chain of rules.
9652 Suffix rules are not mentioned in this algorithm because suffix rules are
9653 converted to equivalent pattern rules once the makefiles have been read in.
9655 For an archive member target of the form
9656 @samp{@var{archive}(@var{member})}, the following algorithm is run
9657 twice, first using the entire target name @var{t}, and second using
9658 @samp{(@var{member})} as the target @var{t} if the first run found no
9659 rule.@refill
9661 @enumerate
9662 @item
9663 Split @var{t} into a directory part, called @var{d}, and the rest,
9664 called @var{n}.  For example, if @var{t} is @samp{src/foo.o}, then
9665 @var{d} is @samp{src/} and @var{n} is @samp{foo.o}.@refill
9667 @item
9668 Make a list of all the pattern rules one of whose targets matches
9669 @var{t} or @var{n}.  If the target pattern contains a slash, it is
9670 matched against @var{t}; otherwise, against @var{n}.
9672 @item
9673 If any rule in that list is @emph{not} a match-anything rule, then
9674 remove all nonterminal match-anything rules from the list.
9676 @item
9677 Remove from the list all rules with no commands.
9679 @item
9680 For each pattern rule in the list:
9682 @enumerate a
9683 @item
9684 Find the stem @var{s}, which is the nonempty part of @var{t} or @var{n}
9685 matched by the @samp{%} in the target pattern.@refill
9687 @item
9688 Compute the prerequisite names by substituting @var{s} for @samp{%}; if
9689 the target pattern does not contain a slash, append @var{d} to
9690 the front of each prerequisite name.@refill
9692 @item
9693 Test whether all the prerequisites exist or ought to exist.  (If a
9694 file name is mentioned in the makefile as a target or as an explicit
9695 prerequisite, then we say it ought to exist.)
9697 If all prerequisites exist or ought to exist, or there are no prerequisites,
9698 then this rule applies.
9699 @end enumerate
9701 @item
9702 If no pattern rule has been found so far, try harder.
9703 For each pattern rule in the list:
9705 @enumerate a
9706 @item
9707 If the rule is terminal, ignore it and go on to the next rule.
9709 @item
9710 Compute the prerequisite names as before.
9712 @item
9713 Test whether all the prerequisites exist or ought to exist.
9715 @item
9716 For each prerequisite that does not exist, follow this algorithm
9717 recursively to see if the prerequisite can be made by an implicit
9718 rule.
9720 @item
9721 If all prerequisites exist, ought to exist, or can be
9722 made by implicit rules, then this rule applies.
9723 @end enumerate
9725 @item
9726 If no implicit rule applies, the rule for @code{.DEFAULT}, if any,
9727 applies.  In that case, give @var{t} the same commands that
9728 @code{.DEFAULT} has.  Otherwise, there are no commands for @var{t}.
9729 @end enumerate
9731 Once a rule that applies has been found, for each target pattern of the
9732 rule other than the one that matched @var{t} or @var{n}, the @samp{%} in
9733 the pattern is replaced with @var{s} and the resultant file name is stored
9734 until the commands to remake the target file @var{t} are executed.  After
9735 these commands are executed, each of these stored file names are entered
9736 into the data base and marked as having been updated and having the same
9737 update status as the file @var{t}.
9739 When the commands of a pattern rule are executed for @var{t}, the automatic
9740 variables are set corresponding to the target and prerequisites.
9741 @xref{Automatic Variables}.
9743 @node Archives, Features, Implicit Rules, Top
9744 @chapter Using @code{make} to Update Archive Files
9745 @cindex archive
9747 @dfn{Archive files} are files containing named subfiles called
9748 @dfn{members}; they are maintained with the program @code{ar} and their
9749 main use is as subroutine libraries for linking.
9751 @menu
9752 * Archive Members::             Archive members as targets.
9753 * Archive Update::              The implicit rule for archive member targets.
9754 * Archive Pitfalls::            Dangers to watch out for when using archives.
9755 * Archive Suffix Rules::        You can write a special kind of suffix rule
9756                                   for updating archives.
9757 @end menu
9759 @node Archive Members, Archive Update, Archives, Archives
9760 @section Archive Members as Targets
9761 @cindex archive member targets
9763 An individual member of an archive file can be used as a target or
9764 prerequisite in @code{make}.  You specify the member named @var{member} in
9765 archive file @var{archive} as follows:
9767 @example
9768 @var{archive}(@var{member})
9769 @end example
9771 @noindent
9772 This construct is available only in targets and prerequisites, not in
9773 commands!  Most programs that you might use in commands do not support this
9774 syntax and cannot act directly on archive members.  Only @code{ar} and
9775 other programs specifically designed to operate on archives can do so.
9776 Therefore, valid commands to update an archive member target probably must
9777 use @code{ar}.  For example, this rule says to create a member
9778 @file{hack.o} in archive @file{foolib} by copying the file @file{hack.o}:
9780 @example
9781 foolib(hack.o) : hack.o
9782         ar cr foolib hack.o
9783 @end example
9785 In fact, nearly all archive member targets are updated in just this way
9786 and there is an implicit rule to do it for you.  @strong{Please note:} The
9787 @samp{c} flag to @code{ar} is required if the archive file does not
9788 already exist.
9790 To specify several members in the same archive, you can write all the
9791 member names together between the parentheses.  For example:
9793 @example
9794 foolib(hack.o kludge.o)
9795 @end example
9797 @noindent
9798 is equivalent to:
9800 @example
9801 foolib(hack.o) foolib(kludge.o)
9802 @end example
9804 @cindex wildcard, in archive member
9805 You can also use shell-style wildcards in an archive member reference.
9806 @xref{Wildcards, ,Using Wildcard Characters in File Names}.  For
9807 example, @w{@samp{foolib(*.o)}} expands to all existing members of the
9808 @file{foolib} archive whose names end in @samp{.o}; perhaps
9809 @samp{@w{foolib(hack.o)} @w{foolib(kludge.o)}}.
9811 @node Archive Update, Archive Pitfalls, Archive Members, Archives
9812 @section Implicit Rule for Archive Member Targets
9814 Recall that a target that looks like @file{@var{a}(@var{m})} stands for the
9815 member named @var{m} in the archive file @var{a}.
9817 When @code{make} looks for an implicit rule for such a target, as a special
9818 feature it considers implicit rules that match @file{(@var{m})}, as well as
9819 those that match the actual target @file{@var{a}(@var{m})}.
9821 This causes one special rule whose target is @file{(%)} to match.  This
9822 rule updates the target @file{@var{a}(@var{m})} by copying the file @var{m}
9823 into the archive.  For example, it will update the archive member target
9824 @file{foo.a(bar.o)} by copying the @emph{file} @file{bar.o} into the
9825 archive @file{foo.a} as a @emph{member} named @file{bar.o}.
9827 When this rule is chained with others, the result is very powerful.
9828 Thus, @samp{make "foo.a(bar.o)"} (the quotes are needed to protect the
9829 @samp{(} and @samp{)} from being interpreted specially by the shell) in
9830 the presence of a file @file{bar.c} is enough to cause the following
9831 commands to be run, even without a makefile:
9833 @example
9834 cc -c bar.c -o bar.o
9835 ar r foo.a bar.o
9836 rm -f bar.o
9837 @end example
9839 @noindent
9840 Here @code{make} has envisioned the file @file{bar.o} as an intermediate
9841 file.  @xref{Chained Rules, ,Chains of Implicit Rules}.
9843 Implicit rules such as this one are written using the automatic variable
9844 @samp{$%}.  @xref{Automatic Variables}.
9846 An archive member name in an archive cannot contain a directory name, but
9847 it may be useful in a makefile to pretend that it does.  If you write an
9848 archive member target @file{foo.a(dir/file.o)}, @code{make} will perform
9849 automatic updating with this command:
9851 @example
9852 ar r foo.a dir/file.o
9853 @end example
9855 @noindent
9856 which has the effect of copying the file @file{dir/file.o} into a member
9857 named @file{file.o}.  In connection with such usage, the automatic variables
9858 @code{%D} and @code{%F} may be useful.
9860 @menu
9861 * Archive Symbols::             How to update archive symbol directories.
9862 @end menu
9864 @node Archive Symbols,  , Archive Update, Archive Update
9865 @subsection Updating Archive Symbol Directories
9866 @cindex @code{__.SYMDEF}
9867 @cindex updating archive symbol directories
9868 @cindex archive symbol directory updating
9869 @cindex symbol directories, updating archive
9870 @cindex directories, updating archive symbol
9872 An archive file that is used as a library usually contains a special member
9873 named @file{__.SYMDEF} that contains a directory of the external symbol
9874 names defined by all the other members.  After you update any other
9875 members, you need to update @file{__.SYMDEF} so that it will summarize the
9876 other members properly.  This is done by running the @code{ranlib} program:
9878 @example
9879 ranlib @var{archivefile}
9880 @end example
9882 Normally you would put this command in the rule for the archive file,
9883 and make all the members of the archive file prerequisites of that rule.
9884 For example,
9886 @example
9887 libfoo.a: libfoo.a(x.o) libfoo.a(y.o) @dots{}
9888         ranlib libfoo.a
9889 @end example
9891 @noindent
9892 The effect of this is to update archive members @file{x.o}, @file{y.o},
9893 etc., and then update the symbol directory member @file{__.SYMDEF} by
9894 running @code{ranlib}.  The rules for updating the members are not shown
9895 here; most likely you can omit them and use the implicit rule which copies
9896 files into the archive, as described in the preceding section.
9898 This is not necessary when using the GNU @code{ar} program, which
9899 updates the @file{__.SYMDEF} member automatically.
9901 @node Archive Pitfalls, Archive Suffix Rules, Archive Update, Archives
9902 @section Dangers When Using Archives
9903 @cindex archive, and parallel execution
9904 @cindex parallel execution, and archive update
9905 @cindex archive, and @code{-j}
9906 @cindex @code{-j}, and archive update
9908 It is important to be careful when using parallel execution (the
9909 @code{-j} switch; @pxref{Parallel, ,Parallel Execution}) and archives.
9910 If multiple @code{ar} commands run at the same time on the same archive
9911 file, they will not know about each other and can corrupt the file.
9913 Possibly a future version of @code{make} will provide a mechanism to
9914 circumvent this problem by serializing all commands that operate on the
9915 same archive file.  But for the time being, you must either write your
9916 makefiles to avoid this problem in some other way, or not use @code{-j}.
9918 @node Archive Suffix Rules,  , Archive Pitfalls, Archives
9919 @section Suffix Rules for Archive Files
9920 @cindex suffix rule, for archive
9921 @cindex archive, suffix rule for
9922 @cindex library archive, suffix rule for
9923 @cindex @code{.a} (archives)
9925 You can write a special kind of suffix rule for dealing with archive
9926 files.  @xref{Suffix Rules}, for a full explanation of suffix rules.
9927 Archive suffix rules are obsolete in GNU @code{make}, because pattern
9928 rules for archives are a more general mechanism (@pxref{Archive
9929 Update}).  But they are retained for compatibility with other
9930 @code{make}s.
9932 To write a suffix rule for archives, you simply write a suffix rule
9933 using the target suffix @samp{.a} (the usual suffix for archive files).
9934 For example, here is the old-fashioned suffix rule to update a library
9935 archive from C source files:
9937 @example
9938 @group
9939 .c.a:
9940         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
9941         $(AR) r $@@ $*.o
9942         $(RM) $*.o
9943 @end group
9944 @end example
9946 @noindent
9947 This works just as if you had written the pattern rule:
9949 @example
9950 @group
9951 (%.o): %.c
9952         $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $*.o
9953         $(AR) r $@@ $*.o
9954         $(RM) $*.o
9955 @end group
9956 @end example
9958 In fact, this is just what @code{make} does when it sees a suffix rule
9959 with @samp{.a} as the target suffix.  Any double-suffix rule
9960 @w{@samp{.@var{x}.a}} is converted to a pattern rule with the target
9961 pattern @samp{(%.o)} and a prerequisite pattern of @samp{%.@var{x}}.
9963 Since you might want to use @samp{.a} as the suffix for some other kind
9964 of file, @code{make} also converts archive suffix rules to pattern rules
9965 in the normal way (@pxref{Suffix Rules}).  Thus a double-suffix rule
9966 @w{@samp{.@var{x}.a}} produces two pattern rules: @samp{@w{(%.o):}
9967 @w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
9969 @node Features, Missing, Archives, Top
9970 @chapter Features of GNU @code{make}
9971 @cindex features of GNU @code{make}
9972 @cindex portability
9973 @cindex compatibility
9975 Here is a summary of the features of GNU @code{make}, for comparison
9976 with and credit to other versions of @code{make}.  We consider the
9977 features of @code{make} in 4.2 BSD systems as a baseline.  If you are
9978 concerned with writing portable makefiles, you should not use the
9979 features of @code{make} listed here, nor the ones in @ref{Missing}.
9981 Many features come from the version of @code{make} in System V.
9983 @itemize @bullet
9984 @item
9985 The @code{VPATH} variable and its special meaning.
9986 @xref{Directory Search, , Searching Directories for Prerequisites}.
9987 This feature exists in System V @code{make}, but is undocumented.
9988 It is documented in 4.3 BSD @code{make} (which says it mimics System V's
9989 @code{VPATH} feature).@refill
9991 @item
9992 Included makefiles.  @xref{Include, ,Including Other Makefiles}.
9993 Allowing multiple files to be included with a single directive is a GNU
9994 extension.
9996 @item
9997 Variables are read from and communicated via the environment.
9998 @xref{Environment, ,Variables from the Environment}.
10000 @item
10001 Options passed through the variable @code{MAKEFLAGS} to recursive
10002 invocations of @code{make}.
10003 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
10005 @item
10006 The automatic variable @code{$%} is set to the member name
10007 in an archive reference.  @xref{Automatic Variables}.
10009 @item
10010 The automatic variables @code{$@@}, @code{$*}, @code{$<}, @code{$%},
10011 and @code{$?} have corresponding forms like @code{$(@@F)} and
10012 @code{$(@@D)}.  We have generalized this to @code{$^} as an obvious
10013 extension.  @xref{Automatic Variables}.@refill
10015 @item
10016 Substitution variable references.
10017 @xref{Reference, ,Basics of Variable References}.
10019 @item
10020 The command-line options @samp{-b} and @samp{-m}, accepted and
10021 ignored.  In System V @code{make}, these options actually do something.
10023 @item
10024 Execution of recursive commands to run @code{make} via the variable
10025 @code{MAKE} even if @samp{-n}, @samp{-q} or @samp{-t} is specified.
10026 @xref{Recursion, ,Recursive Use of @code{make}}.
10028 @item
10029 Support for suffix @samp{.a} in suffix rules.  @xref{Archive Suffix
10030 Rules}.  This feature is obsolete in GNU @code{make}, because the
10031 general feature of rule chaining (@pxref{Chained Rules, ,Chains of
10032 Implicit Rules}) allows one pattern rule for installing members in an
10033 archive (@pxref{Archive Update}) to be sufficient.
10035 @item
10036 The arrangement of lines and backslash-newline combinations in
10037 commands is retained when the commands are printed, so they appear as
10038 they do in the makefile, except for the stripping of initial
10039 whitespace.
10040 @end itemize
10042 The following features were inspired by various other versions of
10043 @code{make}.  In some cases it is unclear exactly which versions inspired
10044 which others.
10046 @itemize @bullet
10047 @item
10048 Pattern rules using @samp{%}.
10049 This has been implemented in several versions of @code{make}.
10050 We're not sure who invented it first, but it's been spread around a bit.
10051 @xref{Pattern Rules, ,Defining and Redefining Pattern Rules}.@refill
10053 @item
10054 Rule chaining and implicit intermediate files.
10055 This was implemented by Stu Feldman in his version of @code{make}
10056 for AT&T Eighth Edition Research Unix, and later by Andrew Hume of
10057 AT&T Bell Labs in his @code{mk} program (where he terms it
10058 ``transitive closure'').  We do not really know if
10059 we got this from either of them or thought it up ourselves at the
10060 same time.  @xref{Chained Rules, ,Chains of Implicit Rules}.
10062 @item
10063 The automatic variable @code{$^} containing a list of all prerequisites
10064 of the current target.  We did not invent this, but we have no idea who
10065 did.  @xref{Automatic Variables}.  The automatic variable
10066 @code{$+} is a simple extension of @code{$^}.
10068 @item
10069 The ``what if'' flag (@samp{-W} in GNU @code{make}) was (as far as we know)
10070 invented by Andrew Hume in @code{mk}.
10071 @xref{Instead of Execution, ,Instead of Executing the Commands}.
10073 @item
10074 The concept of doing several things at once (parallelism) exists in
10075 many incarnations of @code{make} and similar programs, though not in the
10076 System V or BSD implementations.  @xref{Execution, ,Command Execution}.
10078 @item
10079 Modified variable references using pattern substitution come from
10080 SunOS 4.  @xref{Reference, ,Basics of Variable References}.
10081 This functionality was provided in GNU @code{make} by the
10082 @code{patsubst} function before the alternate syntax was implemented
10083 for compatibility with SunOS 4.  It is not altogether clear who
10084 inspired whom, since GNU @code{make} had @code{patsubst} before SunOS
10085 4 was released.@refill
10087 @item
10088 The special significance of @samp{+} characters preceding command lines
10089 (@pxref{Instead of Execution, ,Instead of Executing the Commands}) is
10090 mandated by
10091 @cite{IEEE Standard 1003.2-1992} (POSIX.2).
10093 @item
10094 The @samp{+=} syntax to append to the value of a variable comes from SunOS
10095 4 @code{make}.  @xref{Appending, , Appending More Text to Variables}.
10097 @item
10098 The syntax @w{@samp{@var{archive}(@var{mem1} @var{mem2}@dots{})}} to list
10099 multiple members in a single archive file comes from SunOS 4 @code{make}.
10100 @xref{Archive Members}.
10102 @item
10103 The @code{-include} directive to include makefiles with no error for a
10104 nonexistent file comes from SunOS 4 @code{make}.  (But note that SunOS 4
10105 @code{make} does not allow multiple makefiles to be specified in one
10106 @code{-include} directive.)  The same feature appears with the name
10107 @code{sinclude} in SGI @code{make} and perhaps others.
10108 @end itemize
10110 The remaining features are inventions new in GNU @code{make}:
10112 @itemize @bullet
10113 @item
10114 Use the @samp{-v} or @samp{--version} option to print version and
10115 copyright information.
10117 @item
10118 Use the @samp{-h} or @samp{--help} option to summarize the options to
10119 @code{make}.
10121 @item
10122 Simply-expanded variables.  @xref{Flavors, ,The Two Flavors of Variables}.
10124 @item
10125 Pass command-line variable assignments automatically through the
10126 variable @code{MAKE} to recursive @code{make} invocations.
10127 @xref{Recursion, ,Recursive Use of @code{make}}.
10129 @item
10130 Use the @samp{-C} or @samp{--directory} command option to change
10131 directory.  @xref{Options Summary, ,Summary of Options}.
10133 @item
10134 Make verbatim variable definitions with @code{define}.
10135 @xref{Defining, ,Defining Variables Verbatim}.
10137 @item
10138 Declare phony targets with the special target @code{.PHONY}.
10140 Andrew Hume of AT&T Bell Labs implemented a similar feature with a
10141 different syntax in his @code{mk} program.  This seems to be a case of
10142 parallel discovery.  @xref{Phony Targets, ,Phony Targets}.
10144 @item
10145 Manipulate text by calling functions.
10146 @xref{Functions, ,Functions for Transforming Text}.
10148 @item
10149 Use the @samp{-o} or @samp{--old-file}
10150 option to pretend a file's modification-time is old.
10151 @xref{Avoiding Compilation, ,Avoiding Recompilation of Some Files}.
10153 @item
10154 Conditional execution.
10156 This feature has been implemented numerous times in various versions
10157 of @code{make}; it seems a natural extension derived from the features
10158 of the C preprocessor and similar macro languages and is not a
10159 revolutionary concept.  @xref{Conditionals, ,Conditional Parts of Makefiles}.
10161 @item
10162 Specify a search path for included makefiles.
10163 @xref{Include, ,Including Other Makefiles}.
10165 @item
10166 Specify extra makefiles to read with an environment variable.
10167 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
10169 @item
10170 Strip leading sequences of @samp{./} from file names, so that
10171 @file{./@var{file}} and @file{@var{file}} are considered to be the
10172 same file.@refill
10174 @item
10175 Use a special search method for library prerequisites written in the
10176 form @samp{-l@var{name}}.
10177 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
10179 @item
10180 Allow suffixes for suffix rules
10181 (@pxref{Suffix Rules, ,Old-Fashioned Suffix Rules}) to contain any
10182 characters.  In other versions of @code{make}, they must begin with
10183 @samp{.} and not contain any @samp{/} characters.
10185 @item
10186 Keep track of the current level of @code{make} recursion using the
10187 variable @code{MAKELEVEL}.  @xref{Recursion, ,Recursive Use of @code{make}}.
10189 @item
10190 Provide any goals given on the command line in the variable
10191 @code{MAKECMDGOALS}.  @xref{Goals, ,Arguments to Specify the Goals}.
10193 @item
10194 Specify static pattern rules.  @xref{Static Pattern, ,Static Pattern Rules}.
10196 @item
10197 Provide selective @code{vpath} search.
10198 @xref{Directory Search, ,Searching Directories for Prerequisites}.
10200 @item
10201 Provide computed variable references.
10202 @xref{Reference, ,Basics of Variable References}.
10204 @item
10205 Update makefiles.  @xref{Remaking Makefiles, ,How Makefiles Are Remade}.
10206 System V @code{make} has a very, very limited form of this
10207 functionality in that it will check out SCCS files for makefiles.
10209 @item
10210 Various new built-in implicit rules.
10211 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
10213 @item
10214 The built-in variable @samp{MAKE_VERSION} gives the version number of
10215 @code{make}.
10216 @vindex MAKE_VERSION
10217 @end itemize
10219 @node Missing, Makefile Conventions, Features, Top
10220 @chapter Incompatibilities and Missing Features
10221 @cindex incompatibilities
10222 @cindex missing features
10223 @cindex features, missing
10225 The @code{make} programs in various other systems support a few features
10226 that are not implemented in GNU @code{make}.  The POSIX.2 standard
10227 (@cite{IEEE Standard 1003.2-1992}) which specifies @code{make} does not
10228 require any of these features.@refill
10230 @itemize @bullet
10231 @item
10232 A target of the form @samp{@var{file}((@var{entry}))} stands for a member
10233 of archive file @var{file}.  The member is chosen, not by name, but by
10234 being an object file which defines the linker symbol @var{entry}.@refill
10236 This feature was not put into GNU @code{make} because of the
10237 nonmodularity of putting knowledge into @code{make} of the internal
10238 format of archive file symbol tables.
10239 @xref{Archive Symbols, ,Updating Archive Symbol Directories}.
10241 @item
10242 Suffixes (used in suffix rules) that end with the character @samp{~}
10243 have a special meaning to System V @code{make};
10244 they refer to the SCCS file that corresponds
10245 to the file one would get without the @samp{~}.  For example, the
10246 suffix rule @samp{.c~.o} would make the file @file{@var{n}.o} from
10247 the SCCS file @file{s.@var{n}.c}.  For complete coverage, a whole
10248 series of such suffix rules is required.
10249 @xref{Suffix Rules, ,Old-Fashioned Suffix Rules}.
10251 In GNU @code{make}, this entire series of cases is handled by two
10252 pattern rules for extraction from SCCS, in combination with the
10253 general feature of rule chaining.
10254 @xref{Chained Rules, ,Chains of Implicit Rules}.
10256 @item
10257 In System V and 4.3 BSD @code{make}, files found by @code{VPATH} search
10258 (@pxref{Directory Search, ,Searching Directories for Prerequisites}) have their names changed inside command
10259 strings.  We feel it is much cleaner to always use automatic variables
10260 and thus make this feature obsolete.@refill
10262 @item
10263 In some Unix @code{make}s, the automatic variable @code{$*} appearing in
10264 the prerequisites of a rule has the amazingly strange ``feature'' of
10265 expanding to the full name of the @emph{target of that rule}.  We cannot
10266 imagine what went on in the minds of Unix @code{make} developers to do
10267 this; it is utterly inconsistent with the normal definition of @code{$*}.
10268 @vindex * @r{(automatic variable), unsupported bizarre usage}
10270 @item
10271 In some Unix @code{make}s, implicit rule search
10272 (@pxref{Implicit Rules, ,Using Implicit Rules}) is apparently done for
10273 @emph{all} targets, not just those without commands.  This means you can
10274 do:@refill
10276 @example
10277 @group
10278 foo.o:
10279         cc -c foo.c
10280 @end group
10281 @end example
10283 @noindent
10284 and Unix @code{make} will intuit that @file{foo.o} depends on
10285 @file{foo.c}.@refill
10287 We feel that such usage is broken.  The prerequisite properties of
10288 @code{make} are well-defined (for GNU @code{make}, at least),
10289 and doing such a thing simply does not fit the model.@refill
10291 @item
10292 GNU @code{make} does not include any built-in implicit rules for
10293 compiling or preprocessing EFL programs.  If we hear of anyone who is
10294 using EFL, we will gladly add them.
10296 @item
10297 It appears that in SVR4 @code{make}, a suffix rule can be specified with
10298 no commands, and it is treated as if it had empty commands
10299 (@pxref{Empty Commands}).  For example:
10301 @example
10302 .c.a:
10303 @end example
10305 @noindent
10306 will override the built-in @file{.c.a} suffix rule.
10308 We feel that it is cleaner for a rule without commands to always simply
10309 add to the prerequisite list for the target.  The above example can be
10310 easily rewritten to get the desired behavior in GNU @code{make}:
10312 @example
10313 .c.a: ;
10314 @end example
10316 @item
10317 Some versions of @code{make} invoke the shell with the @samp{-e} flag,
10318 except under @samp{-k} (@pxref{Testing, ,Testing the Compilation of a
10319 Program}).  The @samp{-e} flag tells the shell to exit as soon as any
10320 program it runs returns a nonzero status.  We feel it is cleaner to
10321 write each shell command line to stand on its own and not require this
10322 special treatment.
10323 @end itemize
10325 @comment The makefile standards are in a separate file that is also
10326 @comment included by standards.texi.
10327 @include make-stds.texi
10329 @node Quick Reference, Error Messages, Makefile Conventions, Top
10330 @appendix Quick Reference
10332 This appendix summarizes the directives, text manipulation functions,
10333 and special variables which GNU @code{make} understands.
10334 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
10335 and @ref{Options Summary, ,Summary of Options},
10336 for other summaries.
10338 Here is a summary of the directives GNU @code{make} recognizes:
10340 @table @code
10341 @item define @var{variable}
10342 @itemx endef
10344 Define a multi-line, recursively-expanded variable.@*
10345 @xref{Sequences}.
10347 @item ifdef @var{variable}
10348 @itemx ifndef @var{variable}
10349 @itemx ifeq (@var{a},@var{b})
10350 @itemx ifeq "@var{a}" "@var{b}"
10351 @itemx ifeq '@var{a}' '@var{b}'
10352 @itemx ifneq (@var{a},@var{b})
10353 @itemx ifneq "@var{a}" "@var{b}"
10354 @itemx ifneq '@var{a}' '@var{b}'
10355 @itemx else
10356 @itemx endif
10358 Conditionally evaluate part of the makefile.@*
10359 @xref{Conditionals}.
10361 @item include @var{file}
10362 @itemx -include @var{file}
10363 @itemx sinclude @var{file}
10365 Include another makefile.@*
10366 @xref{Include, ,Including Other Makefiles}.
10368 @item override @var{variable} = @var{value}
10369 @itemx override @var{variable} := @var{value}
10370 @itemx override @var{variable} += @var{value}
10371 @itemx override @var{variable} ?= @var{value}
10372 @itemx override define @var{variable}
10373 @itemx endef
10375 Define a variable, overriding any previous definition, even one from
10376 the command line.@*
10377 @xref{Override Directive, ,The @code{override} Directive}.
10379 @item export
10381 Tell @code{make} to export all variables to child processes by default.@*
10382 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
10384 @item export @var{variable}
10385 @itemx export @var{variable} = @var{value}
10386 @itemx export @var{variable} := @var{value}
10387 @itemx export @var{variable} += @var{value}
10388 @itemx export @var{variable} ?= @var{value}
10389 @itemx unexport @var{variable}
10390 Tell @code{make} whether or not to export a particular variable to child
10391 processes.@*
10392 @xref{Variables/Recursion, , Communicating Variables to a Sub-@code{make}}.
10394 @item vpath @var{pattern} @var{path}
10395 Specify a search path for files matching a @samp{%} pattern.@*
10396 @xref{Selective Search, , The @code{vpath} Directive}.
10398 @item vpath @var{pattern}
10399 Remove all search paths previously specified for @var{pattern}.
10401 @item vpath
10402 Remove all search paths previously specified in any @code{vpath}
10403 directive.
10404 @end table
10406 Here is a summary of the built-in functions (@pxref{Functions}):
10408 @table @code
10409 @item $(subst @var{from},@var{to},@var{text})
10410 Replace @var{from} with @var{to} in @var{text}.@*
10411 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10413 @item $(patsubst @var{pattern},@var{replacement},@var{text})
10414 Replace words matching @var{pattern} with @var{replacement} in @var{text}.@*
10415 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10417 @item $(strip @var{string})
10418 Remove excess whitespace characters from @var{string}.@*
10419 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10421 @item $(findstring @var{find},@var{text})
10422 Locate @var{find} in @var{text}.@*
10423 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10425 @item $(filter @var{pattern}@dots{},@var{text})
10426 Select words in @var{text} that match one of the @var{pattern} words.@*
10427 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10429 @item $(filter-out @var{pattern}@dots{},@var{text})
10430 Select words in @var{text} that @emph{do not} match any of the @var{pattern} words.@*
10431 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10433 @item $(sort @var{list})
10434 Sort the words in @var{list} lexicographically, removing duplicates.@*
10435 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10437 @item $(word @var{n},@var{text})
10438 Extract the @var{n}th word (one-origin) of @var{text}.@*
10439 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10441 @item $(words @var{text})
10442 Count the number of words in @var{text}.@*
10443 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10445 @item $(wordlist @var{s},@var{e},@var{text})
10446 Returns the list of words in @var{text} from @var{s} to @var{e}.@*
10447 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10449 @item $(firstword @var{names}@dots{})
10450 Extract the first word of @var{names}.@*
10451 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10453 @item $(lastword @var{names}@dots{})
10454 Extract the last word of @var{names}.@*
10455 @xref{Text Functions, , Functions for String Substitution and Analysis}.
10457 @item $(dir @var{names}@dots{})
10458 Extract the directory part of each file name.@*
10459 @xref{File Name Functions, ,Functions for File Names}.
10461 @item $(notdir @var{names}@dots{})
10462 Extract the non-directory part of each file name.@*
10463 @xref{File Name Functions, ,Functions for File Names}.
10465 @item $(suffix @var{names}@dots{})
10466 Extract the suffix (the last @samp{.} and following characters) of each file name.@*
10467 @xref{File Name Functions, ,Functions for File Names}.
10469 @item $(basename @var{names}@dots{})
10470 Extract the base name (name without suffix) of each file name.@*
10471 @xref{File Name Functions, ,Functions for File Names}.
10473 @item $(addsuffix @var{suffix},@var{names}@dots{})
10474 Append @var{suffix} to each word in @var{names}.@*
10475 @xref{File Name Functions, ,Functions for File Names}.
10477 @item $(addprefix @var{prefix},@var{names}@dots{})
10478 Prepend @var{prefix} to each word in @var{names}.@*
10479 @xref{File Name Functions, ,Functions for File Names}.
10481 @item $(join @var{list1},@var{list2})
10482 Join two parallel lists of words.@*
10483 @xref{File Name Functions, ,Functions for File Names}.
10485 @item $(wildcard @var{pattern}@dots{})
10486 Find file names matching a shell file name pattern (@emph{not} a
10487 @samp{%} pattern).@*
10488 @xref{Wildcard Function, ,The Function @code{wildcard}}.
10490 @item $(realpath @var{names}@dots{})
10491 For each file name in @var{names}, expand to an absolute name that
10492 does not contain any @code{.}, @code{..}, nor symlinks.@*
10493 @xref{File Name Functions, ,Functions for File Names}.
10495 @item $(abspath @var{names}@dots{})
10496 For each file name in @var{names}, expand to an absolute name that
10497 does not contain any @code{.} or @code{..} components, but preserves
10498 symlinks.@*
10499 @xref{File Name Functions, ,Functions for File Names}.
10501 @item $(error @var{text}@dots{})
10503 When this function is evaluated, @code{make} generates a fatal error
10504 with the message @var{text}.@*
10505 @xref{Make Control Functions, ,Functions That Control Make}.
10507 @item $(warning @var{text}@dots{})
10509 When this function is evaluated, @code{make} generates a warning with
10510 the message @var{text}.@*
10511 @xref{Make Control Functions, ,Functions That Control Make}.
10513 @item $(shell @var{command})
10515 Execute a shell command and return its output.@*
10516 @xref{Shell Function, , The @code{shell} Function}.
10518 @item $(origin @var{variable})
10520 Return a string describing how the @code{make} variable @var{variable} was
10521 defined.@*
10522 @xref{Origin Function, , The @code{origin} Function}.
10524 @item $(flavor @var{variable})
10526 Return a string describing the flavor of the @code{make} variable
10527 @var{variable}.@*
10528 @xref{Flavor Function, , The @code{flavor} Function}.
10530 @item $(foreach @var{var},@var{words},@var{text})
10532 Evaluate @var{text} with @var{var} bound to each word in @var{words},
10533 and concatenate the results.@*
10534 @xref{Foreach Function, ,The @code{foreach} Function}.
10536 @item $(call @var{var},@var{param},@dots{})
10538 Evaluate the variable @var{var} replacing any references to @code{$(1)},
10539 @code{$(2)} with the first, second, etc.@: @var{param} values.@*
10540 @xref{Call Function, ,The @code{call} Function}.
10542 @item $(eval @var{text})
10544 Evaluate @var{text} then read the results as makefile commands.
10545 Expands to the empty string.@*
10546 @xref{Eval Function, ,The @code{eval} Function}.
10548 @item $(value @var{var})
10550 Evaluates to the contents of the variable @var{var}, with no expansion
10551 performed on it.@*
10552 @xref{Value Function, ,The @code{value} Function}.
10553 @end table
10555 Here is a summary of the automatic variables.
10556 @xref{Automatic Variables},
10557 for full information.
10559 @table @code
10560 @item $@@
10561 The file name of the target.
10563 @item $%
10564 The target member name, when the target is an archive member.
10566 @item $<
10567 The name of the first prerequisite.
10569 @item $?
10570 The names of all the prerequisites that are
10571 newer than the target, with spaces between them.
10572 For prerequisites which are archive members, only
10573 the member named is used (@pxref{Archives}).
10575 @item $^
10576 @itemx $+
10577 The names of all the prerequisites, with spaces between them.  For
10578 prerequisites which are archive members, only the member named is used
10579 (@pxref{Archives}).  The value of @code{$^} omits duplicate
10580 prerequisites, while @code{$+} retains them and preserves their order.
10582 @item $*
10583 The stem with which an implicit rule matches
10584 (@pxref{Pattern Match, ,How Patterns Match}).
10586 @item $(@@D)
10587 @itemx $(@@F)
10588 The directory part and the file-within-directory part of @code{$@@}.
10590 @item $(*D)
10591 @itemx $(*F)
10592 The directory part and the file-within-directory part of @code{$*}.
10594 @item $(%D)
10595 @itemx $(%F)
10596 The directory part and the file-within-directory part of @code{$%}.
10598 @item $(<D)
10599 @itemx $(<F)
10600 The directory part and the file-within-directory part of @code{$<}.
10602 @item $(^D)
10603 @itemx $(^F)
10604 The directory part and the file-within-directory part of @code{$^}.
10606 @item $(+D)
10607 @itemx $(+F)
10608 The directory part and the file-within-directory part of @code{$+}.
10610 @item $(?D)
10611 @itemx $(?F)
10612 The directory part and the file-within-directory part of @code{$?}.
10613 @end table
10615 These variables are used specially by GNU @code{make}:
10617 @table @code
10618 @item MAKEFILES
10620 Makefiles to be read on every invocation of @code{make}.@*
10621 @xref{MAKEFILES Variable, ,The Variable @code{MAKEFILES}}.
10623 @item VPATH
10625 Directory search path for files not found in the current directory.@*
10626 @xref{General Search, , @code{VPATH} Search Path for All Prerequisites}.
10628 @item SHELL
10630 The name of the system default command interpreter, usually @file{/bin/sh}.
10631 You can set @code{SHELL} in the makefile to change the shell used to run
10632 commands.  @xref{Execution, ,Command Execution}.  The @code{SHELL}
10633 variable is handled specially when importing from and exporting to the
10634 environment.  @xref{Choosing the Shell}.
10636 @item MAKESHELL
10638 On MS-DOS only, the name of the command interpreter that is to be used
10639 by @code{make}.  This value takes precedence over the value of
10640 @code{SHELL}.  @xref{Execution, ,MAKESHELL variable}.
10642 @item MAKE
10644 The name with which @code{make} was invoked.
10645 Using this variable in commands has special meaning.
10646 @xref{MAKE Variable, ,How the @code{MAKE} Variable Works}.
10648 @item MAKELEVEL
10650 The number of levels of recursion (sub-@code{make}s).@*
10651 @xref{Variables/Recursion}.
10653 @item MAKEFLAGS
10655 The flags given to @code{make}.  You can set this in the environment or
10656 a makefile to set flags.@*
10657 @xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
10659 It is @emph{never} appropriate to use @code{MAKEFLAGS} directly on a
10660 command line: its contents may not be quoted correctly for use in the
10661 shell.  Always allow recursive @code{make}'s to obtain these values
10662 through the environment from its parent.
10664 @item MAKECMDGOALS
10666 The targets given to @code{make} on the command line.  Setting this
10667 variable has no effect on the operation of @code{make}.@*
10668 @xref{Goals, ,Arguments to Specify the Goals}.
10670 @item CURDIR
10672 Set to the pathname of the current working directory (after all
10673 @code{-C} options are processed, if any).  Setting this variable has no
10674 effect on the operation of @code{make}.@*
10675 @xref{Recursion, ,Recursive Use of @code{make}}.
10677 @item SUFFIXES
10679 The default list of suffixes before @code{make} reads any makefiles.
10681 @item .LIBPATTERNS
10682 Defines the naming of the libraries @code{make} searches for, and their
10683 order.@*
10684 @xref{Libraries/Search, ,Directory Search for Link Libraries}.
10685 @end table
10687 @node Error Messages, Complex Makefile, Quick Reference, Top
10688 @comment  node-name,  next,  previous,  up
10689 @appendix Errors Generated by Make
10691 Here is a list of the more common errors you might see generated by
10692 @code{make}, and some information about what they mean and how to fix
10693 them.
10695 Sometimes @code{make} errors are not fatal, especially in the presence
10696 of a @code{-} prefix on a command script line, or the @code{-k} command
10697 line option.  Errors that are fatal are prefixed with the string
10698 @code{***}.
10700 Error messages are all either prefixed with the name of the program
10701 (usually @samp{make}), or, if the error is found in a makefile, the name
10702 of the file and linenumber containing the problem.
10704 In the table below, these common prefixes are left off.
10706 @table @samp
10708 @item [@var{foo}] Error @var{NN}
10709 @itemx [@var{foo}] @var{signal description}
10710 These errors are not really @code{make} errors at all.  They mean that a
10711 program that @code{make} invoked as part of a command script returned a
10712 non-0 error code (@samp{Error @var{NN}}), which @code{make} interprets
10713 as failure, or it exited in some other abnormal fashion (with a
10714 signal of some type).  @xref{Errors, ,Errors in Commands}.
10716 If no @code{***} is attached to the message, then the subprocess failed
10717 but the rule in the makefile was prefixed with the @code{-} special
10718 character, so @code{make} ignored the error.
10720 @item missing separator.  Stop.
10721 @itemx missing separator (did you mean TAB instead of 8 spaces?).  Stop.
10722 This means that @code{make} could not understand much of anything about
10723 the command line it just read.  GNU @code{make} looks for various kinds
10724 of separators (@code{:}, @code{=}, TAB characters, etc.) to help it
10725 decide what kind of commandline it's seeing.  This means it couldn't
10726 find a valid one.
10728 One of the most common reasons for this message is that you (or perhaps
10729 your oh-so-helpful editor, as is the case with many MS-Windows editors)
10730 have attempted to indent your command scripts with spaces instead of a
10731 TAB character.  In this case, @code{make} will use the second form of
10732 the error above.  Remember that every line in the command script must
10733 begin with a TAB character.  Eight spaces do not count.  @xref{Rule
10734 Syntax}.
10736 @item commands commence before first target.  Stop.
10737 @itemx missing rule before commands.  Stop.
10738 This means the first thing in the makefile seems to be part of a command
10739 script: it begins with a TAB character and doesn't appear to be a legal
10740 @code{make} command (such as a variable assignment).  Command scripts
10741 must always be associated with a target.
10743 The second form is generated if the line has a semicolon as the first
10744 non-whitespace character; @code{make} interprets this to mean you left
10745 out the "target: prerequisite" section of a rule.  @xref{Rule Syntax}.
10747 @item No rule to make target `@var{xxx}'.
10748 @itemx No rule to make target `@var{xxx}', needed by `@var{yyy}'.
10749 This means that @code{make} decided it needed to build a target, but
10750 then couldn't find any instructions in the makefile on how to do that,
10751 either explicit or implicit (including in the default rules database).
10753 If you want that file to be built, you will need to add a rule to your
10754 makefile describing how that target can be built.  Other possible
10755 sources of this problem are typos in the makefile (if that filename is
10756 wrong) or a corrupted source tree (if that file is not supposed to be
10757 built, but rather only a prerequisite).
10759 @item No targets specified and no makefile found.  Stop.
10760 @itemx No targets.  Stop.
10761 The former means that you didn't provide any targets to be built on the
10762 command line, and @code{make} couldn't find any makefiles to read in.
10763 The latter means that some makefile was found, but it didn't contain any
10764 default goal and none was given on the command line.  GNU @code{make}
10765 has nothing to do in these situations.
10766 @xref{Makefile Arguments, ,Arguments to Specify the Makefile}.@refill
10768 @item Makefile `@var{xxx}' was not found.
10769 @itemx Included makefile `@var{xxx}' was not found.
10770 A makefile specified on the command line (first form) or included
10771 (second form) was not found.
10773 @item warning: overriding commands for target `@var{xxx}'
10774 @itemx warning: ignoring old commands for target `@var{xxx}'
10775 GNU @code{make} allows commands to be specified only once per target
10776 (except for double-colon rules).  If you give commands for a target
10777 which already has been defined to have commands, this warning is issued
10778 and the second set of commands will overwrite the first set.
10779 @xref{Multiple Rules, ,Multiple Rules for One Target}.
10781 @item Circular @var{xxx} <- @var{yyy} dependency dropped.
10782 This means that @code{make} detected a loop in the dependency graph:
10783 after tracing the prerequisite @var{yyy} of target @var{xxx}, and its
10784 prerequisites, etc., one of them depended on @var{xxx} again.
10786 @item Recursive variable `@var{xxx}' references itself (eventually).  Stop.
10787 This means you've defined a normal (recursive) @code{make} variable
10788 @var{xxx} that, when it's expanded, will refer to itself (@var{xxx}).
10789 This is not allowed; either use simply-expanded variables (@code{:=}) or
10790 use the append operator (@code{+=}).  @xref{Using Variables, ,How to Use
10791 Variables}.
10793 @item Unterminated variable reference.  Stop.
10794 This means you forgot to provide the proper closing parenthesis
10795 or brace in your variable or function reference.
10797 @item insufficient arguments to function `@var{xxx}'.  Stop.
10798 This means you haven't provided the requisite number of arguments for
10799 this function.  See the documentation of the function for a description
10800 of its arguments.  @xref{Functions, ,Functions for Transforming Text}.
10802 @item missing target pattern.  Stop.
10803 @itemx multiple target patterns.  Stop.
10804 @itemx target pattern contains no `%'.  Stop.
10805 @itemx mixed implicit and static pattern rules.  Stop.
10806 These are generated for malformed static pattern rules.  The first means
10807 there's no pattern in the target section of the rule; the second means
10808 there are multiple patterns in the target section; the third means
10809 the target doesn't contain a pattern character (@code{%}); and the
10810 fourth means that all three parts of the static pattern rule contain
10811 pattern characters (@code{%})--only the first two parts should.
10812 @xref{Static Usage, ,Syntax of Static Pattern Rules}.
10814 @item warning: -jN forced in submake: disabling jobserver mode.
10815 This warning and the next are generated if @code{make} detects error
10816 conditions related to parallel processing on systems where
10817 sub-@code{make}s can communicate (@pxref{Options/Recursion,
10818 ,Communicating Options to a Sub-@code{make}}).  This warning is
10819 generated if a recursive invocation of a @code{make} process is forced
10820 to have @samp{-j@var{N}} in its argument list (where @var{N} is greater
10821 than one).  This could happen, for example, if you set the @code{MAKE}
10822 environment variable to @samp{make -j2}.  In this case, the
10823 sub-@code{make} doesn't communicate with other @code{make} processes and
10824 will simply pretend it has two jobs of its own.
10826 @item warning: jobserver unavailable: using -j1.  Add `+' to parent make rule.
10827 In order for @code{make} processes to communicate, the parent will pass
10828 information to the child.  Since this could result in problems if the
10829 child process isn't actually a @code{make}, the parent will only do this
10830 if it thinks the child is a @code{make}.  The parent uses the normal
10831 algorithms to determine this (@pxref{MAKE Variable, ,How the @code{MAKE}
10832 Variable Works}).  If the makefile is constructed such that the parent
10833 doesn't know the child is a @code{make} process, then the child will
10834 receive only part of the information necessary.  In this case, the child
10835 will generate this warning message and proceed with its build in a
10836 sequential manner.
10838 @end table
10840 @node Complex Makefile, GNU Free Documentation License, Error Messages, Top
10841 @appendix Complex Makefile Example
10843 Here is the makefile for the GNU @code{tar} program.  This is a
10844 moderately complex makefile.
10846 Because it is the first target, the default goal is @samp{all}.  An
10847 interesting feature of this makefile is that @file{testpad.h} is a
10848 source file automatically created by the @code{testpad} program,
10849 itself compiled from @file{testpad.c}.
10851 If you type @samp{make} or @samp{make all}, then @code{make} creates
10852 the @file{tar} executable, the @file{rmt} daemon that provides
10853 remote tape access, and the @file{tar.info} Info file.
10855 If you type @samp{make install}, then @code{make} not only creates
10856 @file{tar}, @file{rmt}, and @file{tar.info}, but also installs
10857 them.
10859 If you type @samp{make clean}, then @code{make} removes the @samp{.o}
10860 files, and the @file{tar}, @file{rmt}, @file{testpad},
10861 @file{testpad.h}, and @file{core} files.
10863 If you type @samp{make distclean}, then @code{make} not only removes
10864 the same files as does @samp{make clean} but also the
10865 @file{TAGS}, @file{Makefile}, and @file{config.status} files.
10866 (Although it is not evident, this makefile (and
10867 @file{config.status}) is generated by the user with the
10868 @code{configure} program, which is provided in the @code{tar}
10869 distribution, but is not shown here.)
10871 If you type @samp{make realclean}, then @code{make} removes the same
10872 files as does @samp{make distclean} and also removes the Info files
10873 generated from @file{tar.texinfo}.
10875 In addition, there are targets @code{shar} and @code{dist} that create
10876 distribution kits.
10878 @example
10879 @group
10880 # Generated automatically from Makefile.in by configure.
10881 # Un*x Makefile for GNU tar program.
10882 # Copyright (C) 1991 Free Software Foundation, Inc.
10883 @end group
10885 @group
10886 # This program is free software; you can redistribute
10887 # it and/or modify it under the terms of the GNU
10888 # General Public License @dots{}
10889 @dots{}
10890 @dots{}
10891 @end group
10893 SHELL = /bin/sh
10895 #### Start of system configuration section. ####
10897 srcdir = .
10899 @group
10900 # If you use gcc, you should either run the
10901 # fixincludes script that comes with it or else use
10902 # gcc with the -traditional option.  Otherwise ioctl
10903 # calls will be compiled incorrectly on some systems.
10904 CC = gcc -O
10905 YACC = bison -y
10906 INSTALL = /usr/local/bin/install -c
10907 INSTALLDATA = /usr/local/bin/install -c -m 644
10908 @end group
10910 # Things you might add to DEFS:
10911 # -DSTDC_HEADERS        If you have ANSI C headers and
10912 #                       libraries.
10913 # -DPOSIX               If you have POSIX.1 headers and
10914 #                       libraries.
10915 # -DBSD42               If you have sys/dir.h (unless
10916 #                       you use -DPOSIX), sys/file.h,
10917 #                       and st_blocks in `struct stat'.
10918 # -DUSG                 If you have System V/ANSI C
10919 #                       string and memory functions
10920 #                       and headers, sys/sysmacros.h,
10921 #                       fcntl.h, getcwd, no valloc,
10922 #                       and ndir.h (unless
10923 #                       you use -DDIRENT).
10924 # -DNO_MEMORY_H         If USG or STDC_HEADERS but do not
10925 #                       include memory.h.
10926 # -DDIRENT              If USG and you have dirent.h
10927 #                       instead of ndir.h.
10928 # -DSIGTYPE=int         If your signal handlers
10929 #                       return int, not void.
10930 # -DNO_MTIO             If you lack sys/mtio.h
10931 #                       (magtape ioctls).
10932 # -DNO_REMOTE           If you do not have a remote shell
10933 #                       or rexec.
10934 # -DUSE_REXEC           To use rexec for remote tape
10935 #                       operations instead of
10936 #                       forking rsh or remsh.
10937 # -DVPRINTF_MISSING     If you lack vprintf function
10938 #                       (but have _doprnt).
10939 # -DDOPRNT_MISSING      If you lack _doprnt function.
10940 #                       Also need to define
10941 #                       -DVPRINTF_MISSING.
10942 # -DFTIME_MISSING       If you lack ftime system call.
10943 # -DSTRSTR_MISSING      If you lack strstr function.
10944 # -DVALLOC_MISSING      If you lack valloc function.
10945 # -DMKDIR_MISSING       If you lack mkdir and
10946 #                       rmdir system calls.
10947 # -DRENAME_MISSING      If you lack rename system call.
10948 # -DFTRUNCATE_MISSING   If you lack ftruncate
10949 #                       system call.
10950 # -DV7                  On Version 7 Unix (not
10951 #                       tested in a long time).
10952 # -DEMUL_OPEN3          If you lack a 3-argument version
10953 #                       of open, and want to emulate it
10954 #                       with system calls you do have.
10955 # -DNO_OPEN3            If you lack the 3-argument open
10956 #                       and want to disable the tar -k
10957 #                       option instead of emulating open.
10958 # -DXENIX               If you have sys/inode.h
10959 #                       and need it 94 to be included.
10961 DEFS =  -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
10962         -DVPRINTF_MISSING -DBSD42
10963 # Set this to rtapelib.o unless you defined NO_REMOTE,
10964 # in which case make it empty.
10965 RTAPELIB = rtapelib.o
10966 LIBS =
10967 DEF_AR_FILE = /dev/rmt8
10968 DEFBLOCKING = 20
10970 @group
10971 CDEBUG = -g
10972 CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
10973         -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
10974         -DDEFBLOCKING=$(DEFBLOCKING)
10975 LDFLAGS = -g
10976 @end group
10978 @group
10979 prefix = /usr/local
10980 # Prefix for each installed program,
10981 # normally empty or `g'.
10982 binprefix =
10984 # The directory to install tar in.
10985 bindir = $(prefix)/bin
10987 # The directory to install the info files in.
10988 infodir = $(prefix)/info
10989 @end group
10991 #### End of system configuration section. ####
10993 SRC1 =  tar.c create.c extract.c buffer.c \
10994         getoldopt.c update.c gnu.c mangle.c
10995 SRC2 =  version.c list.c names.c diffarch.c \
10996         port.c wildmat.c getopt.c
10997 SRC3 =  getopt1.c regex.c getdate.y
10998 SRCS =  $(SRC1) $(SRC2) $(SRC3)
10999 OBJ1 =  tar.o create.o extract.o buffer.o \
11000         getoldopt.o update.o gnu.o mangle.o
11001 OBJ2 =  version.o list.o names.o diffarch.o \
11002         port.o wildmat.o getopt.o
11003 OBJ3 =  getopt1.o regex.o getdate.o $(RTAPELIB)
11004 OBJS =  $(OBJ1) $(OBJ2) $(OBJ3)
11005 @group
11006 AUX =   README COPYING ChangeLog Makefile.in  \
11007         makefile.pc configure configure.in \
11008         tar.texinfo tar.info* texinfo.tex \
11009         tar.h port.h open3.h getopt.h regex.h \
11010         rmt.h rmt.c rtapelib.c alloca.c \
11011         msd_dir.h msd_dir.c tcexparg.c \
11012         level-0 level-1 backup-specs testpad.c
11013 @end group
11015 .PHONY: all
11016 all:    tar rmt tar.info
11018 @group
11019 .PHONY: tar
11020 tar:    $(OBJS)
11021         $(CC) $(LDFLAGS) -o $@@ $(OBJS) $(LIBS)
11022 @end group
11024 @group
11025 rmt:    rmt.c
11026         $(CC) $(CFLAGS) $(LDFLAGS) -o $@@ rmt.c
11027 @end group
11029 @group
11030 tar.info: tar.texinfo
11031         makeinfo tar.texinfo
11032 @end group
11034 @group
11035 .PHONY: install
11036 install: all
11037         $(INSTALL) tar $(bindir)/$(binprefix)tar
11038         -test ! -f rmt || $(INSTALL) rmt /etc/rmt
11039         $(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
11040 @end group
11042 @group
11043 $(OBJS): tar.h port.h testpad.h
11044 regex.o buffer.o tar.o: regex.h
11045 # getdate.y has 8 shift/reduce conflicts.
11046 @end group
11048 @group
11049 testpad.h: testpad
11050         ./testpad
11051 @end group
11053 @group
11054 testpad: testpad.o
11055         $(CC) -o $@@ testpad.o
11056 @end group
11058 @group
11059 TAGS:   $(SRCS)
11060         etags $(SRCS)
11061 @end group
11063 @group
11064 .PHONY: clean
11065 clean:
11066         rm -f *.o tar rmt testpad testpad.h core
11067 @end group
11069 @group
11070 .PHONY: distclean
11071 distclean: clean
11072         rm -f TAGS Makefile config.status
11073 @end group
11075 @group
11076 .PHONY: realclean
11077 realclean: distclean
11078         rm -f tar.info*
11079 @end group
11081 @group
11082 .PHONY: shar
11083 shar: $(SRCS) $(AUX)
11084         shar $(SRCS) $(AUX) | compress \
11085           > tar-`sed -e '/version_string/!d' \
11086                      -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11087                      -e q
11088                      version.c`.shar.Z
11089 @end group
11091 @group
11092 .PHONY: dist
11093 dist: $(SRCS) $(AUX)
11094         echo tar-`sed \
11095              -e '/version_string/!d' \
11096              -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
11097              -e q
11098              version.c` > .fname
11099         -rm -rf `cat .fname`
11100         mkdir `cat .fname`
11101         ln $(SRCS) $(AUX) `cat .fname`
11102         tar chZf `cat .fname`.tar.Z `cat .fname`
11103         -rm -rf `cat .fname` .fname
11104 @end group
11106 @group
11107 tar.zoo: $(SRCS) $(AUX)
11108         -rm -rf tmp.dir
11109         -mkdir tmp.dir
11110         -rm tar.zoo
11111         for X in $(SRCS) $(AUX) ; do \
11112             echo $$X ; \
11113             sed 's/$$/^M/' $$X \
11114             > tmp.dir/$$X ; done
11115         cd tmp.dir ; zoo aM ../tar.zoo *
11116         -rm -rf tmp.dir
11117 @end group
11118 @end example
11120 @raisesections
11121 @include fdl.texi
11122 @lowersections
11124 @node Concept Index, Name Index, GNU Free Documentation License, Top
11125 @unnumbered Index of Concepts
11127 @printindex cp
11129 @node Name Index,  , Concept Index, Top
11130 @unnumbered Index of Functions, Variables, & Directives
11132 @printindex fn
11134 @bye