1 This is make.info, produced by makeinfo version 4.6 from make.texi.
3 INFO-DIR-SECTION GNU Packages
5 * Make: (make). Remake files automatically.
8 This file documents the GNU Make utility, which determines
9 automatically which pieces of a large program need to be recompiled,
10 and issues the commands to recompile them.
12 This is Edition 0.61, last updated 02 May 2003, of `The GNU Make
13 Manual', for `make', Version 3.81.
15 Copyright 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
16 1998, 1999, 2000, 2002, 2003, 2004 Free Software Foundation, Inc.
18 Permission is granted to copy, distribute and/or modify this document
19 under the terms of the GNU Free Documentation License, Version 1.1 or
20 any later version published by the Free Software Foundation; with no
21 Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
22 Texts. A copy of the license is included in the section entitled "GNU
23 Free Documentation License".
26 File: make.info, Node: Top, Next: Overview, Prev: (dir), Up: (dir)
31 The GNU `make' utility automatically determines which pieces of a large
32 program need to be recompiled, and issues the commands to recompile
35 This edition of the `GNU Make Manual', last updated 02 May 2003,
36 documents GNU `make' Version 3.81.
38 This manual describes `make' and contains the following chapters:
42 * Overview:: Overview of `make'.
43 * Introduction:: An introduction to `make'.
44 * Makefiles:: Makefiles tell `make' what to do.
45 * Rules:: Rules describe when a file must be remade.
46 * Commands:: Commands say how to remake a file.
47 * Using Variables:: You can use variables to avoid repetition.
48 * Conditionals:: Use or ignore parts of the makefile based
49 on the values of variables.
50 * Functions:: Many powerful ways to manipulate text.
51 * Invoking make: Running. How to invoke `make' on the command line.
52 * Implicit Rules:: Use implicit rules to treat many files alike,
53 based on their file names.
54 * Archives:: How `make' can update library archives.
55 * Features:: Features GNU `make' has over other `make's.
56 * Missing:: What GNU `make' lacks from other `make's.
57 * Makefile Conventions:: Conventions for writing makefiles for
59 * Quick Reference:: A quick reference for experienced users.
60 * Error Messages:: A list of common errors generated by `make'.
61 * Complex Makefile:: A real example of a straightforward,
62 but nontrivial, makefile.
64 * GNU Free Documentation License:: License for copying this manual
65 * Concept Index:: Index of Concepts
66 * Name Index:: Index of Functions, Variables, & Directives
68 --- The Detailed Node Listing ---
72 * Preparing:: Preparing and Running Make
73 * Reading:: On Reading this Text
74 * Bugs:: Problems and Bugs
76 An Introduction to Makefiles
78 * Rule Introduction:: What a rule looks like.
79 * Simple Makefile:: A Simple Makefile
80 * How Make Works:: How `make' Processes This Makefile
81 * Variables Simplify:: Variables Make Makefiles Simpler
82 * make Deduces:: Letting `make' Deduce the Commands
83 * Combine By Prerequisite:: Another Style of Makefile
84 * Cleanup:: Rules for Cleaning the Directory
88 * Makefile Contents:: What makefiles contain.
89 * Makefile Names:: How to name your makefile.
90 * Include:: How one makefile can use another makefile.
91 * MAKEFILES Variable:: The environment can specify extra makefiles.
92 * MAKEFILE_LIST Variable:: Discover which makefiles have been read.
93 * Special Variables:: Other special variables.
94 * Remaking Makefiles:: How makefiles get remade.
95 * Overriding Makefiles:: How to override part of one makefile
96 with another makefile.
97 * Reading Makefiles:: How makefiles are parsed.
101 * Rule Example:: An example explained.
102 * Rule Syntax:: General syntax explained.
103 * Prerequisite Types:: There are two types of prerequisites.
104 * Wildcards:: Using wildcard characters such as `*'.
105 * Directory Search:: Searching other directories for source files.
106 * Phony Targets:: Using a target that is not a real file's name.
107 * Force Targets:: You can use a target without commands
108 or prerequisites to mark other
110 * Empty Targets:: When only the date matters and the
112 * Special Targets:: Targets with special built-in meanings.
113 * Multiple Targets:: When to make use of several targets in a rule.
114 * Multiple Rules:: How to use several rules with the same target.
115 * Static Pattern:: Static pattern rules apply to multiple targets
116 and can vary the prerequisites according to
118 * Double-Colon:: How to use a special kind of rule to allow
119 several independent rules for one target.
120 * Automatic Prerequisites:: How to automatically generate rules giving
121 prerequisites from source files themselves.
123 Using Wildcard Characters in File Names
125 * Wildcard Examples:: Several examples
126 * Wildcard Pitfall:: Problems to avoid.
127 * Wildcard Function:: How to cause wildcard expansion where
128 it does not normally take place.
130 Searching Directories for Prerequisites
132 * General Search:: Specifying a search path that applies
133 to every prerequisite.
134 * Selective Search:: Specifying a search path
135 for a specified class of names.
136 * Search Algorithm:: When and how search paths are applied.
137 * Commands/Search:: How to write shell commands that work together
139 * Implicit/Search:: How search paths affect implicit rules.
140 * Libraries/Search:: Directory search for link libraries.
144 * Static Usage:: The syntax of static pattern rules.
145 * Static versus Implicit:: When are they better than implicit rules?
147 Writing the Commands in Rules
149 * Echoing:: How to control when commands are echoed.
150 * Execution:: How commands are executed.
151 * Parallel:: How commands can be executed in parallel.
152 * Errors:: What happens after a command execution error.
153 * Interrupts:: What happens when a command is interrupted.
154 * Recursion:: Invoking `make' from makefiles.
155 * Sequences:: Defining canned sequences of commands.
156 * Empty Commands:: Defining useful, do-nothing commands.
158 Recursive Use of `make'
160 * MAKE Variable:: The special effects of using `$(MAKE)'.
161 * Variables/Recursion:: How to communicate variables to a sub-`make'.
162 * Options/Recursion:: How to communicate options to a sub-`make'.
163 * -w Option:: How the `-w' or `--print-directory' option
164 helps debug use of recursive `make' commands.
168 * Reference:: How to use the value of a variable.
169 * Flavors:: Variables come in two flavors.
170 * Advanced:: Advanced features for referencing a variable.
171 * Values:: All the ways variables get their values.
172 * Setting:: How to set a variable in the makefile.
173 * Appending:: How to append more text to the old value
175 * Override Directive:: How to set a variable in the makefile even if
176 the user has set it with a command argument.
177 * Defining:: An alternate way to set a variable
178 to a verbatim string.
179 * Environment:: Variable values can come from the environment.
180 * Target-specific:: Variable values can be defined on a per-target
182 * Pattern-specific:: Target-specific variable values can be applied
183 to a group of targets that match a pattern.
185 Advanced Features for Reference to Variables
187 * Substitution Refs:: Referencing a variable with
188 substitutions on the value.
189 * Computed Names:: Computing the name of the variable to refer to.
191 Conditional Parts of Makefiles
193 * Conditional Example:: Example of a conditional
194 * Conditional Syntax:: The syntax of conditionals.
195 * Testing Flags:: Conditionals that test flags.
197 Functions for Transforming Text
199 * Syntax of Functions:: How to write a function call.
200 * Text Functions:: General-purpose text manipulation functions.
201 * File Name Functions:: Functions for manipulating file names.
202 * Foreach Function:: Repeat some text with controlled variation.
203 * If Function:: Conditionally expand a value.
204 * Call Function:: Expand a user-defined function.
205 * Value Function:: Return the un-expanded value of a variable.
206 * Eval Function:: Evaluate the arguments as makefile syntax.
207 * Origin Function:: Find where a variable got its value.
208 * Shell Function:: Substitute the output of a shell command.
209 * Make Control Functions:: Functions that control how make runs.
213 * Makefile Arguments:: How to specify which makefile to use.
214 * Goals:: How to use goal arguments to specify which
215 parts of the makefile to use.
216 * Instead of Execution:: How to use mode flags to specify what
217 kind of thing to do with the commands
218 in the makefile other than simply
220 * Avoiding Compilation:: How to avoid recompiling certain files.
221 * Overriding:: How to override a variable to specify
222 an alternate compiler and other things.
223 * Testing:: How to proceed past some errors, to
225 * Options Summary:: Summary of Options
229 * Using Implicit:: How to use an existing implicit rule
230 to get the commands for updating a file.
231 * Catalogue of Rules:: A list of built-in implicit rules.
232 * Implicit Variables:: How to change what predefined rules do.
233 * Chained Rules:: How to use a chain of implicit rules.
234 * Pattern Rules:: How to define new implicit rules.
235 * Last Resort:: How to defining commands for rules
236 which cannot find any.
237 * Suffix Rules:: The old-fashioned style of implicit rule.
238 * Implicit Rule Search:: The precise algorithm for applying
241 Defining and Redefining Pattern Rules
243 * Pattern Intro:: An introduction to pattern rules.
244 * Pattern Examples:: Examples of pattern rules.
245 * Automatic Variables:: How to use automatic variables in the
246 commands of implicit rules.
247 * Pattern Match:: How patterns match.
248 * Match-Anything Rules:: Precautions you should take prior to
249 defining rules that can match any
250 target file whatever.
251 * Canceling Rules:: How to override or cancel built-in rules.
253 Using `make' to Update Archive Files
255 * Archive Members:: Archive members as targets.
256 * Archive Update:: The implicit rule for archive member targets.
257 * Archive Pitfalls:: Dangers to watch out for when using archives.
258 * Archive Suffix Rules:: You can write a special kind of suffix rule
259 for updating archives.
261 Implicit Rule for Archive Member Targets
263 * Archive Symbols:: How to update archive symbol directories.
267 * Makefile Basics:: General Conventions for Makefiles
268 * Utilities in Makefiles:: Utilities in Makefiles
269 * Command Variables:: Variables for Specifying Commands
270 * Directory Variables:: Variables for Installation Directories
271 * Standard Targets:: Standard Targets for Users
272 * Install Command Categories:: Three categories of commands in the `install'
277 File: make.info, Node: Overview, Next: Introduction, Prev: Top, Up: Top
282 The `make' utility automatically determines which pieces of a large
283 program need to be recompiled, and issues commands to recompile them.
284 This manual describes GNU `make', which was implemented by Richard
285 Stallman and Roland McGrath. Development since Version 3.76 has been
286 handled by Paul D. Smith.
288 GNU `make' conforms to section 6.2 of `IEEE Standard 1003.2-1992'
291 Our examples show C programs, since they are most common, but you
292 can use `make' with any programming language whose compiler can be run
293 with a shell command. Indeed, `make' is not limited to programs. You
294 can use it to describe any task where some files must be updated
295 automatically from others whenever the others change.
299 * Preparing:: Preparing and Running Make
300 * Reading:: On Reading this Text
301 * Bugs:: Problems and Bugs
304 File: make.info, Node: Preparing, Next: Reading, Prev: Overview, Up: Overview
306 Preparing and Running Make
307 ==========================
309 To prepare to use `make', you must write a file called the
310 "makefile" that describes the relationships among files in your program
311 and provides commands for updating each file. In a program, typically,
312 the executable file is updated from object files, which are in turn
313 made by compiling source files.
315 Once a suitable makefile exists, each time you change some source
316 files, this simple shell command:
320 suffices to perform all necessary recompilations. The `make' program
321 uses the makefile data base and the last-modification times of the
322 files to decide which of the files need to be updated. For each of
323 those files, it issues the commands recorded in the data base.
325 You can provide command line arguments to `make' to control which
326 files should be recompiled, or how. *Note How to Run `make': Running.
329 File: make.info, Node: Reading, Next: Bugs, Prev: Preparing, Up: Overview
331 How to Read This Manual
332 =======================
334 If you are new to `make', or are looking for a general introduction,
335 read the first few sections of each chapter, skipping the later
336 sections. In each chapter, the first few sections contain introductory
337 or general information and the later sections contain specialized or
338 technical information. The exception is the second chapter, *Note An
339 Introduction to Makefiles: Introduction, all of which is introductory.
341 If you are familiar with other `make' programs, see *Note Features
342 of GNU `make': Features, which lists the enhancements GNU `make' has,
343 and *Note Incompatibilities and Missing Features: Missing, which
344 explains the few things GNU `make' lacks that others have.
346 For a quick summary, see *Note Options Summary::, *Note Quick
347 Reference::, and *Note Special Targets::.
350 File: make.info, Node: Bugs, Prev: Reading, Up: Overview
355 If you have problems with GNU `make' or think you've found a bug,
356 please report it to the developers; we cannot promise to do anything but
357 we might well want to fix it.
359 Before reporting a bug, make sure you've actually found a real bug.
360 Carefully reread the documentation and see if it really says you can do
361 what you're trying to do. If it's not clear whether you should be able
362 to do something or not, report that too; it's a bug in the
365 Before reporting a bug or trying to fix it yourself, try to isolate
366 it to the smallest possible makefile that reproduces the problem. Then
367 send us the makefile and the exact results `make' gave you, including
368 any error or warning messages. Please don't paraphrase these messages:
369 it's best to cut and paste them into your report. When generating this
370 small makefile, be sure to not use any non-free or unusual tools in
371 your commands: you can almost always emulate what such a tool would do
372 with simple shell commands. Finally, be sure to explain what you
373 expected to occur; this will help us decide whether the problem was
374 really in the documentation.
376 Once you have a precise problem you can report it in one of two ways.
377 Either send electronic mail to:
381 or use our Web-based project management tool, at:
383 http://savannah.gnu.org/projects/make/
385 In addition to the information above, please be careful to include the
386 version number of `make' you are using. You can get this information
387 with the command `make --version'. Be sure also to include the type of
388 machine and operating system you are using. One way to obtain this
389 information is by looking at the final lines of output from the command
393 File: make.info, Node: Introduction, Next: Makefiles, Prev: Overview, Up: Top
395 An Introduction to Makefiles
396 ****************************
398 You need a file called a "makefile" to tell `make' what to do. Most
399 often, the makefile tells `make' how to compile and link a program.
401 In this chapter, we will discuss a simple makefile that describes
402 how to compile and link a text editor which consists of eight C source
403 files and three header files. The makefile can also tell `make' how to
404 run miscellaneous commands when explicitly asked (for example, to remove
405 certain files as a clean-up operation). To see a more complex example
406 of a makefile, see *Note Complex Makefile::.
408 When `make' recompiles the editor, each changed C source file must
409 be recompiled. If a header file has changed, each C source file that
410 includes the header file must be recompiled to be safe. Each
411 compilation produces an object file corresponding to the source file.
412 Finally, if any source file has been recompiled, all the object files,
413 whether newly made or saved from previous compilations, must be linked
414 together to produce the new executable editor.
418 * Rule Introduction:: What a rule looks like.
419 * Simple Makefile:: A Simple Makefile
420 * How Make Works:: How `make' Processes This Makefile
421 * Variables Simplify:: Variables Make Makefiles Simpler
422 * make Deduces:: Letting `make' Deduce the Commands
423 * Combine By Prerequisite:: Another Style of Makefile
424 * Cleanup:: Rules for Cleaning the Directory
427 File: make.info, Node: Rule Introduction, Next: Simple Makefile, Prev: Introduction, Up: Introduction
429 What a Rule Looks Like
430 ======================
432 A simple makefile consists of "rules" with the following shape:
434 TARGET ... : PREREQUISITES ...
439 A "target" is usually the name of a file that is generated by a
440 program; examples of targets are executable or object files. A target
441 can also be the name of an action to carry out, such as `clean' (*note
444 A "prerequisite" is a file that is used as input to create the
445 target. A target often depends on several files.
447 A "command" is an action that `make' carries out. A rule may have
448 more than one command, each on its own line. *Please note:* you need
449 to put a tab character at the beginning of every command line! This is
450 an obscurity that catches the unwary.
452 Usually a command is in a rule with prerequisites and serves to
453 create a target file if any of the prerequisites change. However, the
454 rule that specifies commands for the target need not have
455 prerequisites. For example, the rule containing the delete command
456 associated with the target `clean' does not have prerequisites.
458 A "rule", then, explains how and when to remake certain files which
459 are the targets of the particular rule. `make' carries out the
460 commands on the prerequisites to create or update the target. A rule
461 can also explain how and when to carry out an action. *Note Writing
464 A makefile may contain other text besides rules, but a simple
465 makefile need only contain rules. Rules may look somewhat more
466 complicated than shown in this template, but all fit the pattern more
470 File: make.info, Node: Simple Makefile, Next: How Make Works, Prev: Rule Introduction, Up: Introduction
475 Here is a straightforward makefile that describes the way an executable
476 file called `edit' depends on eight object files which, in turn, depend
477 on eight C source and three header files.
479 In this example, all the C files include `defs.h', but only those
480 defining editing commands include `command.h', and only low level files
481 that change the editor buffer include `buffer.h'.
483 edit : main.o kbd.o command.o display.o \
484 insert.o search.o files.o utils.o
485 cc -o edit main.o kbd.o command.o display.o \
486 insert.o search.o files.o utils.o
488 main.o : main.c defs.h
490 kbd.o : kbd.c defs.h command.h
492 command.o : command.c defs.h command.h
494 display.o : display.c defs.h buffer.h
496 insert.o : insert.c defs.h buffer.h
498 search.o : search.c defs.h buffer.h
500 files.o : files.c defs.h buffer.h command.h
502 utils.o : utils.c defs.h
505 rm edit main.o kbd.o command.o display.o \
506 insert.o search.o files.o utils.o
508 We split each long line into two lines using backslash-newline; this is
509 like using one long line, but is easier to read.
511 To use this makefile to create the executable file called `edit',
516 To use this makefile to delete the executable file and all the object
517 files from the directory, type:
521 In the example makefile, the targets include the executable file
522 `edit', and the object files `main.o' and `kbd.o'. The prerequisites
523 are files such as `main.c' and `defs.h'. In fact, each `.o' file is
524 both a target and a prerequisite. Commands include `cc -c main.c' and
527 When a target is a file, it needs to be recompiled or relinked if any
528 of its prerequisites change. In addition, any prerequisites that are
529 themselves automatically generated should be updated first. In this
530 example, `edit' depends on each of the eight object files; the object
531 file `main.o' depends on the source file `main.c' and on the header
534 A shell command follows each line that contains a target and
535 prerequisites. These shell commands say how to update the target file.
536 A tab character must come at the beginning of every command line to
537 distinguish commands lines from other lines in the makefile. (Bear in
538 mind that `make' does not know anything about how the commands work.
539 It is up to you to supply commands that will update the target file
540 properly. All `make' does is execute the commands in the rule you have
541 specified when the target file needs to be updated.)
543 The target `clean' is not a file, but merely the name of an action.
544 Since you normally do not want to carry out the actions in this rule,
545 `clean' is not a prerequisite of any other rule. Consequently, `make'
546 never does anything with it unless you tell it specifically. Note that
547 this rule not only is not a prerequisite, it also does not have any
548 prerequisites, so the only purpose of the rule is to run the specified
549 commands. Targets that do not refer to files but are just actions are
550 called "phony targets". *Note Phony Targets::, for information about
551 this kind of target. *Note Errors in Commands: Errors, to see how to
552 cause `make' to ignore errors from `rm' or any other command.
555 File: make.info, Node: How Make Works, Next: Variables Simplify, Prev: Simple Makefile, Up: Introduction
557 How `make' Processes a Makefile
558 ===============================
560 By default, `make' starts with the first target (not targets whose
561 names start with `.'). This is called the "default goal". ("Goals"
562 are the targets that `make' strives ultimately to update. *Note
563 Arguments to Specify the Goals: Goals.)
565 In the simple example of the previous section, the default goal is to
566 update the executable program `edit'; therefore, we put that rule first.
568 Thus, when you give the command:
572 `make' reads the makefile in the current directory and begins by
573 processing the first rule. In the example, this rule is for relinking
574 `edit'; but before `make' can fully process this rule, it must process
575 the rules for the files that `edit' depends on, which in this case are
576 the object files. Each of these files is processed according to its
577 own rule. These rules say to update each `.o' file by compiling its
578 source file. The recompilation must be done if the source file, or any
579 of the header files named as prerequisites, is more recent than the
580 object file, or if the object file does not exist.
582 The other rules are processed because their targets appear as
583 prerequisites of the goal. If some other rule is not depended on by the
584 goal (or anything it depends on, etc.), that rule is not processed,
585 unless you tell `make' to do so (with a command such as `make clean').
587 Before recompiling an object file, `make' considers updating its
588 prerequisites, the source file and header files. This makefile does not
589 specify anything to be done for them--the `.c' and `.h' files are not
590 the targets of any rules--so `make' does nothing for these files. But
591 `make' would update automatically generated C programs, such as those
592 made by Bison or Yacc, by their own rules at this time.
594 After recompiling whichever object files need it, `make' decides
595 whether to relink `edit'. This must be done if the file `edit' does
596 not exist, or if any of the object files are newer than it. If an
597 object file was just recompiled, it is now newer than `edit', so `edit'
600 Thus, if we change the file `insert.c' and run `make', `make' will
601 compile that file to update `insert.o', and then link `edit'. If we
602 change the file `command.h' and run `make', `make' will recompile the
603 object files `kbd.o', `command.o' and `files.o' and then link the file
607 File: make.info, Node: Variables Simplify, Next: make Deduces, Prev: How Make Works, Up: Introduction
609 Variables Make Makefiles Simpler
610 ================================
612 In our example, we had to list all the object files twice in the rule
613 for `edit' (repeated here):
615 edit : main.o kbd.o command.o display.o \
616 insert.o search.o files.o utils.o
617 cc -o edit main.o kbd.o command.o display.o \
618 insert.o search.o files.o utils.o
620 Such duplication is error-prone; if a new object file is added to the
621 system, we might add it to one list and forget the other. We can
622 eliminate the risk and simplify the makefile by using a variable.
623 "Variables" allow a text string to be defined once and substituted in
624 multiple places later (*note How to Use Variables: Using Variables.).
626 It is standard practice for every makefile to have a variable named
627 `objects', `OBJECTS', `objs', `OBJS', `obj', or `OBJ' which is a list
628 of all object file names. We would define such a variable `objects'
629 with a line like this in the makefile:
631 objects = main.o kbd.o command.o display.o \
632 insert.o search.o files.o utils.o
634 Then, each place we want to put a list of the object file names, we can
635 substitute the variable's value by writing `$(objects)' (*note How to
636 Use Variables: Using Variables.).
638 Here is how the complete simple makefile looks when you use a
639 variable for the object files:
641 objects = main.o kbd.o command.o display.o \
642 insert.o search.o files.o utils.o
645 cc -o edit $(objects)
646 main.o : main.c defs.h
648 kbd.o : kbd.c defs.h command.h
650 command.o : command.c defs.h command.h
652 display.o : display.c defs.h buffer.h
654 insert.o : insert.c defs.h buffer.h
656 search.o : search.c defs.h buffer.h
658 files.o : files.c defs.h buffer.h command.h
660 utils.o : utils.c defs.h
666 File: make.info, Node: make Deduces, Next: Combine By Prerequisite, Prev: Variables Simplify, Up: Introduction
668 Letting `make' Deduce the Commands
669 ==================================
671 It is not necessary to spell out the commands for compiling the
672 individual C source files, because `make' can figure them out: it has an
673 "implicit rule" for updating a `.o' file from a correspondingly named
674 `.c' file using a `cc -c' command. For example, it will use the
675 command `cc -c main.c -o main.o' to compile `main.c' into `main.o'. We
676 can therefore omit the commands from the rules for the object files.
677 *Note Using Implicit Rules: Implicit Rules.
679 When a `.c' file is used automatically in this way, it is also
680 automatically added to the list of prerequisites. We can therefore omit
681 the `.c' files from the prerequisites, provided we omit the commands.
683 Here is the entire example, with both of these changes, and a
684 variable `objects' as suggested above:
686 objects = main.o kbd.o command.o display.o \
687 insert.o search.o files.o utils.o
690 cc -o edit $(objects)
693 kbd.o : defs.h command.h
694 command.o : defs.h command.h
695 display.o : defs.h buffer.h
696 insert.o : defs.h buffer.h
697 search.o : defs.h buffer.h
698 files.o : defs.h buffer.h command.h
705 This is how we would write the makefile in actual practice. (The
706 complications associated with `clean' are described elsewhere. See
707 *Note Phony Targets::, and *Note Errors in Commands: Errors.)
709 Because implicit rules are so convenient, they are important. You
710 will see them used frequently.
713 File: make.info, Node: Combine By Prerequisite, Next: Cleanup, Prev: make Deduces, Up: Introduction
715 Another Style of Makefile
716 =========================
718 When the objects of a makefile are created only by implicit rules, an
719 alternative style of makefile is possible. In this style of makefile,
720 you group entries by their prerequisites instead of by their targets.
721 Here is what one looks like:
723 objects = main.o kbd.o command.o display.o \
724 insert.o search.o files.o utils.o
727 cc -o edit $(objects)
730 kbd.o command.o files.o : command.h
731 display.o insert.o search.o files.o : buffer.h
733 Here `defs.h' is given as a prerequisite of all the object files;
734 `command.h' and `buffer.h' are prerequisites of the specific object
735 files listed for them.
737 Whether this is better is a matter of taste: it is more compact, but
738 some people dislike it because they find it clearer to put all the
739 information about each target in one place.
742 File: make.info, Node: Cleanup, Prev: Combine By Prerequisite, Up: Introduction
744 Rules for Cleaning the Directory
745 ================================
747 Compiling a program is not the only thing you might want to write rules
748 for. Makefiles commonly tell how to do a few other things besides
749 compiling a program: for example, how to delete all the object files
750 and executables so that the directory is `clean'.
752 Here is how we could write a `make' rule for cleaning our example
758 In practice, we might want to write the rule in a somewhat more
759 complicated manner to handle unanticipated situations. We would do
766 This prevents `make' from getting confused by an actual file called
767 `clean' and causes it to continue in spite of errors from `rm'. (See
768 *Note Phony Targets::, and *Note Errors in Commands: Errors.)
770 A rule such as this should not be placed at the beginning of the
771 makefile, because we do not want it to run by default! Thus, in the
772 example makefile, we want the rule for `edit', which recompiles the
773 editor, to remain the default goal.
775 Since `clean' is not a prerequisite of `edit', this rule will not
776 run at all if we give the command `make' with no arguments. In order
777 to make the rule run, we have to type `make clean'. *Note How to Run
781 File: make.info, Node: Makefiles, Next: Rules, Prev: Introduction, Up: Top
786 The information that tells `make' how to recompile a system comes from
787 reading a data base called the "makefile".
791 * Makefile Contents:: What makefiles contain.
792 * Makefile Names:: How to name your makefile.
793 * Include:: How one makefile can use another makefile.
794 * MAKEFILES Variable:: The environment can specify extra makefiles.
795 * MAKEFILE_LIST Variable:: Discover which makefiles have been read.
796 * Special Variables:: Other special variables.
797 * Remaking Makefiles:: How makefiles get remade.
798 * Overriding Makefiles:: How to override part of one makefile
799 with another makefile.
800 * Reading Makefiles:: How makefiles are parsed.
803 File: make.info, Node: Makefile Contents, Next: Makefile Names, Prev: Makefiles, Up: Makefiles
805 What Makefiles Contain
806 ======================
808 Makefiles contain five kinds of things: "explicit rules", "implicit
809 rules", "variable definitions", "directives", and "comments". Rules,
810 variables, and directives are described at length in later chapters.
812 * An "explicit rule" says when and how to remake one or more files,
813 called the rule's "targets". It lists the other files that the
814 targets depend on, called the "prerequisites" of the target, and
815 may also give commands to use to create or update the targets.
816 *Note Writing Rules: Rules.
818 * An "implicit rule" says when and how to remake a class of files
819 based on their names. It describes how a target may depend on a
820 file with a name similar to the target and gives commands to
821 create or update such a target. *Note Using Implicit Rules:
824 * A "variable definition" is a line that specifies a text string
825 value for a variable that can be substituted into the text later.
826 The simple makefile example shows a variable definition for
827 `objects' as a list of all object files (*note Variables Make
828 Makefiles Simpler: Variables Simplify.).
830 * A "directive" is a command for `make' to do something special while
831 reading the makefile. These include:
833 * Reading another makefile (*note Including Other Makefiles:
836 * Deciding (based on the values of variables) whether to use or
837 ignore a part of the makefile (*note Conditional Parts of
838 Makefiles: Conditionals.).
840 * Defining a variable from a verbatim string containing
841 multiple lines (*note Defining Variables Verbatim: Defining.).
843 * `#' in a line of a makefile starts a "comment". It and the rest
844 of the line are ignored, except that a trailing backslash not
845 escaped by another backslash will continue the comment across
846 multiple lines. A line containing just a comment (with perhaps
847 spaces before it) is effectively blank, and is ignored. If you
848 want a literal `#', escape it with a backslash (e.g., `\#').
849 Comments may appear on any line in the makefile, although they are
850 treated specially in certain situations.
852 Within a command script (if the line begins with a TAB character)
853 the entire line is passed to the shell, just as with any other
854 line that begins with a TAB. The shell decides how to interpret
855 the text: whether or not this is a comment is up to the shell.
857 Within a `define' directive, comments are not ignored during the
858 definition of the variable, but rather kept intact in the value of
859 the variable. When the variable is expanded they will either be
860 treated as `make' comments or as command script text, depending on
861 the context in which the variable is evaluated.
864 File: make.info, Node: Makefile Names, Next: Include, Prev: Makefile Contents, Up: Makefiles
866 What Name to Give Your Makefile
867 ===============================
869 By default, when `make' looks for the makefile, it tries the following
870 names, in order: `GNUmakefile', `makefile' and `Makefile'.
872 Normally you should call your makefile either `makefile' or
873 `Makefile'. (We recommend `Makefile' because it appears prominently
874 near the beginning of a directory listing, right near other important
875 files such as `README'.) The first name checked, `GNUmakefile', is not
876 recommended for most makefiles. You should use this name if you have a
877 makefile that is specific to GNU `make', and will not be understood by
878 other versions of `make'. Other `make' programs look for `makefile' and
879 `Makefile', but not `GNUmakefile'.
881 If `make' finds none of these names, it does not use any makefile.
882 Then you must specify a goal with a command argument, and `make' will
883 attempt to figure out how to remake it using only its built-in implicit
884 rules. *Note Using Implicit Rules: Implicit Rules.
886 If you want to use a nonstandard name for your makefile, you can
887 specify the makefile name with the `-f' or `--file' option. The
888 arguments `-f NAME' or `--file=NAME' tell `make' to read the file NAME
889 as the makefile. If you use more than one `-f' or `--file' option, you
890 can specify several makefiles. All the makefiles are effectively
891 concatenated in the order specified. The default makefile names
892 `GNUmakefile', `makefile' and `Makefile' are not checked automatically
893 if you specify `-f' or `--file'.
896 File: make.info, Node: Include, Next: MAKEFILES Variable, Prev: Makefile Names, Up: Makefiles
898 Including Other Makefiles
899 =========================
901 The `include' directive tells `make' to suspend reading the current
902 makefile and read one or more other makefiles before continuing. The
903 directive is a line in the makefile that looks like this:
907 FILENAMES can contain shell file name patterns.
909 Extra spaces are allowed and ignored at the beginning of the line,
910 but a tab is not allowed. (If the line begins with a tab, it will be
911 considered a command line.) Whitespace is required between `include'
912 and the file names, and between file names; extra whitespace is ignored
913 there and at the end of the directive. A comment starting with `#' is
914 allowed at the end of the line. If the file names contain any variable
915 or function references, they are expanded. *Note How to Use Variables:
918 For example, if you have three `.mk' files, `a.mk', `b.mk', and
919 `c.mk', and `$(bar)' expands to `bish bash', then the following
922 include foo *.mk $(bar)
926 include foo a.mk b.mk c.mk bish bash
928 When `make' processes an `include' directive, it suspends reading of
929 the containing makefile and reads from each listed file in turn. When
930 that is finished, `make' resumes reading the makefile in which the
933 One occasion for using `include' directives is when several programs,
934 handled by individual makefiles in various directories, need to use a
935 common set of variable definitions (*note Setting Variables: Setting.)
936 or pattern rules (*note Defining and Redefining Pattern Rules: Pattern
939 Another such occasion is when you want to generate prerequisites from
940 source files automatically; the prerequisites can be put in a file that
941 is included by the main makefile. This practice is generally cleaner
942 than that of somehow appending the prerequisites to the end of the main
943 makefile as has been traditionally done with other versions of `make'.
944 *Note Automatic Prerequisites::.
946 If the specified name does not start with a slash, and the file is
947 not found in the current directory, several other directories are
948 searched. First, any directories you have specified with the `-I' or
949 `--include-dir' option are searched (*note Summary of Options: Options
950 Summary.). Then the following directories (if they exist) are
951 searched, in this order: `PREFIX/include' (normally `/usr/local/include'
952 (1)) `/usr/gnu/include', `/usr/local/include', `/usr/include'.
954 If an included makefile cannot be found in any of these directories,
955 a warning message is generated, but it is not an immediately fatal
956 error; processing of the makefile containing the `include' continues.
957 Once it has finished reading makefiles, `make' will try to remake any
958 that are out of date or don't exist. *Note How Makefiles Are Remade:
959 Remaking Makefiles. Only after it has tried to find a way to remake a
960 makefile and failed, will `make' diagnose the missing makefile as a
963 If you want `make' to simply ignore a makefile which does not exist
964 and cannot be remade, with no error message, use the `-include'
965 directive instead of `include', like this:
967 -include FILENAMES...
969 This acts like `include' in every way except that there is no error
970 (not even a warning) if any of the FILENAMES do not exist. For
971 compatibility with some other `make' implementations, `sinclude' is
972 another name for `-include'.
974 ---------- Footnotes ----------
976 (1) GNU Make compiled for MS-DOS and MS-Windows behaves as if PREFIX
977 has been defined to be the root of the DJGPP tree hierarchy.
980 File: make.info, Node: MAKEFILES Variable, Next: MAKEFILE_LIST Variable, Prev: Include, Up: Makefiles
982 The Variable `MAKEFILES'
983 ========================
985 If the environment variable `MAKEFILES' is defined, `make' considers
986 its value as a list of names (separated by whitespace) of additional
987 makefiles to be read before the others. This works much like the
988 `include' directive: various directories are searched for those files
989 (*note Including Other Makefiles: Include.). In addition, the default
990 goal is never taken from one of these makefiles and it is not an error
991 if the files listed in `MAKEFILES' are not found.
993 The main use of `MAKEFILES' is in communication between recursive
994 invocations of `make' (*note Recursive Use of `make': Recursion.). It
995 usually is not desirable to set the environment variable before a
996 top-level invocation of `make', because it is usually better not to
997 mess with a makefile from outside. However, if you are running `make'
998 without a specific makefile, a makefile in `MAKEFILES' can do useful
999 things to help the built-in implicit rules work better, such as
1000 defining search paths (*note Directory Search::).
1002 Some users are tempted to set `MAKEFILES' in the environment
1003 automatically on login, and program makefiles to expect this to be done.
1004 This is a very bad idea, because such makefiles will fail to work if
1005 run by anyone else. It is much better to write explicit `include'
1006 directives in the makefiles. *Note Including Other Makefiles: Include.
1009 File: make.info, Node: MAKEFILE_LIST Variable, Next: Special Variables, Prev: MAKEFILES Variable, Up: Makefiles
1011 The Variable `MAKEFILE_LIST'
1012 ============================
1014 As `make' reads various makefiles, including any obtained from the
1015 `MAKEFILES' variable, the command line, the default files, or from
1016 `include' directives, their names will be automatically appended to the
1017 `MAKEFILE_LIST' variable. They are added right before `make' begins to
1020 This means that if the first thing a makefile does is examine the
1021 last word in this variable, it will be the name of the current makefile.
1022 Once the current makefile has used `include', however, the last word
1023 will be the just-included makefile.
1025 If a makefile named `Makefile' has this content:
1027 name1 := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
1031 name2 := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
1034 @echo name1 = $(name1)
1035 @echo name2 = $(name2)
1037 then you would expect to see this output:
1042 *Note Text Functions::, for more information on the `word' and
1043 `words' functions used above. *Note The Two Flavors of Variables:
1044 Flavors, for more information on simply-expanded (`:=') variable
1048 File: make.info, Node: Special Variables, Next: Remaking Makefiles, Prev: MAKEFILE_LIST Variable, Up: Makefiles
1050 Other Special Variables
1051 =======================
1053 GNU `make' also supports a special variable. Note that any value you
1054 assign to this variable will be ignored; it will always return its
1057 The first special variable is `.VARIABLES'. When expanded, the
1058 value consists of a list of the _names_ of all global variables defined
1059 in all makefiles read up until that point. This includes variables
1060 which have empty values, as well as built-in variables (*note Variables
1061 Used by Implicit Rules: Implicit Variables.), but does not include any
1062 variables which are only defined in a target-specific context.
1065 File: make.info, Node: Remaking Makefiles, Next: Overriding Makefiles, Prev: Special Variables, Up: Makefiles
1067 How Makefiles Are Remade
1068 ========================
1070 Sometimes makefiles can be remade from other files, such as RCS or SCCS
1071 files. If a makefile can be remade from other files, you probably want
1072 `make' to get an up-to-date version of the makefile to read in.
1074 To this end, after reading in all makefiles, `make' will consider
1075 each as a goal target and attempt to update it. If a makefile has a
1076 rule which says how to update it (found either in that very makefile or
1077 in another one) or if an implicit rule applies to it (*note Using
1078 Implicit Rules: Implicit Rules.), it will be updated if necessary.
1079 After all makefiles have been checked, if any have actually been
1080 changed, `make' starts with a clean slate and reads all the makefiles
1081 over again. (It will also attempt to update each of them over again,
1082 but normally this will not change them again, since they are already up
1085 If you know that one or more of your makefiles cannot be remade and
1086 you want to keep `make' from performing an implicit rule search on
1087 them, perhaps for efficiency reasons, you can use any normal method of
1088 preventing implicit rule lookup to do so. For example, you can write an
1089 explicit rule with the makefile as the target, and an empty command
1090 string (*note Using Empty Commands: Empty Commands.).
1092 If the makefiles specify a double-colon rule to remake a file with
1093 commands but no prerequisites, that file will always be remade (*note
1094 Double-Colon::). In the case of makefiles, a makefile that has a
1095 double-colon rule with commands but no prerequisites will be remade
1096 every time `make' is run, and then again after `make' starts over and
1097 reads the makefiles in again. This would cause an infinite loop:
1098 `make' would constantly remake the makefile, and never do anything
1099 else. So, to avoid this, `make' will *not* attempt to remake makefiles
1100 which are specified as targets of a double-colon rule with commands but
1103 If you do not specify any makefiles to be read with `-f' or `--file'
1104 options, `make' will try the default makefile names; *note What Name to
1105 Give Your Makefile: Makefile Names.. Unlike makefiles explicitly
1106 requested with `-f' or `--file' options, `make' is not certain that
1107 these makefiles should exist. However, if a default makefile does not
1108 exist but can be created by running `make' rules, you probably want the
1109 rules to be run so that the makefile can be used.
1111 Therefore, if none of the default makefiles exists, `make' will try
1112 to make each of them in the same order in which they are searched for
1113 (*note What Name to Give Your Makefile: Makefile Names.) until it
1114 succeeds in making one, or it runs out of names to try. Note that it
1115 is not an error if `make' cannot find or make any makefile; a makefile
1116 is not always necessary.
1118 When you use the `-t' or `--touch' option (*note Instead of
1119 Executing the Commands: Instead of Execution.), you would not want to
1120 use an out-of-date makefile to decide which targets to touch. So the
1121 `-t' option has no effect on updating makefiles; they are really
1122 updated even if `-t' is specified. Likewise, `-q' (or `--question')
1123 and `-n' (or `--just-print') do not prevent updating of makefiles,
1124 because an out-of-date makefile would result in the wrong output for
1125 other targets. Thus, `make -f mfile -n foo' will update `mfile', read
1126 it in, and then print the commands to update `foo' and its prerequisites
1127 without running them. The commands printed for `foo' will be those
1128 specified in the updated contents of `mfile'.
1130 However, on occasion you might actually wish to prevent updating of
1131 even the makefiles. You can do this by specifying the makefiles as
1132 goals in the command line as well as specifying them as makefiles.
1133 When the makefile name is specified explicitly as a goal, the options
1134 `-t' and so on do apply to them.
1136 Thus, `make -f mfile -n mfile foo' would read the makefile `mfile',
1137 print the commands needed to update it without actually running them,
1138 and then print the commands needed to update `foo' without running
1139 them. The commands for `foo' will be those specified by the existing
1140 contents of `mfile'.
1143 File: make.info, Node: Overriding Makefiles, Next: Reading Makefiles, Prev: Remaking Makefiles, Up: Makefiles
1145 Overriding Part of Another Makefile
1146 ===================================
1148 Sometimes it is useful to have a makefile that is mostly just like
1149 another makefile. You can often use the `include' directive to include
1150 one in the other, and add more targets or variable definitions.
1151 However, if the two makefiles give different commands for the same
1152 target, `make' will not let you just do this. But there is another way.
1154 In the containing makefile (the one that wants to include the other),
1155 you can use a match-anything pattern rule to say that to remake any
1156 target that cannot be made from the information in the containing
1157 makefile, `make' should look in another makefile. *Note Pattern
1158 Rules::, for more information on pattern rules.
1160 For example, if you have a makefile called `Makefile' that says how
1161 to make the target `foo' (and other targets), you can write a makefile
1162 called `GNUmakefile' that contains:
1168 @$(MAKE) -f Makefile $@
1171 If you say `make foo', `make' will find `GNUmakefile', read it, and
1172 see that to make `foo', it needs to run the command `frobnicate > foo'.
1173 If you say `make bar', `make' will find no way to make `bar' in
1174 `GNUmakefile', so it will use the commands from the pattern rule: `make
1175 -f Makefile bar'. If `Makefile' provides a rule for updating `bar',
1176 `make' will apply the rule. And likewise for any other target that
1177 `GNUmakefile' does not say how to make.
1179 The way this works is that the pattern rule has a pattern of just
1180 `%', so it matches any target whatever. The rule specifies a
1181 prerequisite `force', to guarantee that the commands will be run even
1182 if the target file already exists. We give `force' target empty
1183 commands to prevent `make' from searching for an implicit rule to build
1184 it--otherwise it would apply the same match-anything rule to `force'
1185 itself and create a prerequisite loop!
1188 File: make.info, Node: Reading Makefiles, Prev: Overriding Makefiles, Up: Makefiles
1190 How `make' Reads a Makefile
1191 ===========================
1193 GNU `make' does its work in two distinct phases. During the first
1194 phase it reads all the makefiles, included makefiles, etc. and
1195 internalizes all the variables and their values, implicit and explicit
1196 rules, and constructs a dependency graph of all the targets and their
1197 prerequisites. During the second phase, `make' uses these internal
1198 structures to determine what targets will need to be rebuilt and to
1199 invoke the rules necessary to do so.
1201 It's important to understand this two-phase approach because it has a
1202 direct impact on how variable and function expansion happens; this is
1203 often a source of some confusion when writing makefiles. Here we will
1204 present a summary of the phases in which expansion happens for different
1205 constructs within the makefile. We say that expansion is "immediate"
1206 if it happens during the first phase: in this case `make' will expand
1207 any variables or functions in that section of a construct as the
1208 makefile is parsed. We say that expansion is "deferred" if expansion
1209 is not performed immediately. Expansion of deferred construct is not
1210 performed until either the construct appears later in an immediate
1211 context, or until the second phase.
1213 You may not be familiar with some of these constructs yet. You can
1214 reference this section as you become familiar with them, in later
1220 Variable definitions are parsed as follows:
1222 IMMEDIATE = DEFERRED
1223 IMMEDIATE ?= DEFERRED
1224 IMMEDIATE := IMMEDIATE
1225 IMMEDIATE += DEFERRED or IMMEDIATE
1231 For the append operator, `+=', the right-hand side is considered
1232 immediate if the variable was previously set as a simple variable
1233 (`:='), and deferred otherwise.
1235 Conditional Statements
1236 ----------------------
1238 All instances of conditional syntax are parsed immediately, in their
1239 entirety; this includes the `ifdef', `ifeq', `ifndef', and `ifneq'
1245 A rule is always expanded the same way, regardless of the form:
1247 IMMEDIATE : IMMEDIATE ; DEFERRED
1250 That is, the target and prerequisite sections are expanded
1251 immediately, and the commands used to construct the target are always
1252 deferred. This general rule is true for explicit rules, pattern rules,
1253 suffix rules, static pattern rules, and simple prerequisite definitions.
1256 File: make.info, Node: Rules, Next: Commands, Prev: Makefiles, Up: Top
1261 A "rule" appears in the makefile and says when and how to remake
1262 certain files, called the rule's "targets" (most often only one per
1263 rule). It lists the other files that are the "prerequisites" of the
1264 target, and "commands" to use to create or update the target.
1266 The order of rules is not significant, except for determining the
1267 "default goal": the target for `make' to consider, if you do not
1268 otherwise specify one. The default goal is the target of the first
1269 rule in the first makefile. If the first rule has multiple targets,
1270 only the first target is taken as the default. There are two
1271 exceptions: a target starting with a period is not a default unless it
1272 contains one or more slashes, `/', as well; and, a target that defines
1273 a pattern rule has no effect on the default goal. (*Note Defining and
1274 Redefining Pattern Rules: Pattern Rules.)
1276 Therefore, we usually write the makefile so that the first rule is
1277 the one for compiling the entire program or all the programs described
1278 by the makefile (often with a target called `all'). *Note Arguments to
1279 Specify the Goals: Goals.
1283 * Rule Example:: An example explained.
1284 * Rule Syntax:: General syntax explained.
1285 * Prerequisite Types:: There are two types of prerequisites.
1286 * Wildcards:: Using wildcard characters such as `*'.
1287 * Directory Search:: Searching other directories for source files.
1288 * Phony Targets:: Using a target that is not a real file's name.
1289 * Force Targets:: You can use a target without commands
1290 or prerequisites to mark other
1292 * Empty Targets:: When only the date matters and the
1294 * Special Targets:: Targets with special built-in meanings.
1295 * Multiple Targets:: When to make use of several targets in a rule.
1296 * Multiple Rules:: How to use several rules with the same target.
1297 * Static Pattern:: Static pattern rules apply to multiple targets
1298 and can vary the prerequisites according to
1300 * Double-Colon:: How to use a special kind of rule to allow
1301 several independent rules for one target.
1302 * Automatic Prerequisites:: How to automatically generate rules giving
1303 prerequisites from source files themselves.
1306 File: make.info, Node: Rule Example, Next: Rule Syntax, Prev: Rules, Up: Rules
1311 Here is an example of a rule:
1313 foo.o : foo.c defs.h # module for twiddling the frobs
1316 Its target is `foo.o' and its prerequisites are `foo.c' and
1317 `defs.h'. It has one command, which is `cc -c -g foo.c'. The command
1318 line starts with a tab to identify it as a command.
1320 This rule says two things:
1322 * How to decide whether `foo.o' is out of date: it is out of date if
1323 it does not exist, or if either `foo.c' or `defs.h' is more recent
1326 * How to update the file `foo.o': by running `cc' as stated. The
1327 command does not explicitly mention `defs.h', but we presume that
1328 `foo.c' includes it, and that that is why `defs.h' was added to
1332 File: make.info, Node: Rule Syntax, Next: Prerequisite Types, Prev: Rule Example, Up: Rules
1337 In general, a rule looks like this:
1339 TARGETS : PREREQUISITES
1345 TARGETS : PREREQUISITES ; COMMAND
1349 The TARGETS are file names, separated by spaces. Wildcard
1350 characters may be used (*note Using Wildcard Characters in File Names:
1351 Wildcards.) and a name of the form `A(M)' represents member M in
1352 archive file A (*note Archive Members as Targets: Archive Members.).
1353 Usually there is only one target per rule, but occasionally there is a
1354 reason to have more (*note Multiple Targets in a Rule: Multiple
1357 The COMMAND lines start with a tab character. The first command may
1358 appear on the line after the prerequisites, with a tab character, or may
1359 appear on the same line, with a semicolon. Either way, the effect is
1360 the same. *Note Writing the Commands in Rules: Commands.
1362 Because dollar signs are used to start variable references, if you
1363 really want a dollar sign in a rule you must write two of them, `$$'
1364 (*note How to Use Variables: Using Variables.). You may split a long
1365 line by inserting a backslash followed by a newline, but this is not
1366 required, as `make' places no limit on the length of a line in a
1369 A rule tells `make' two things: when the targets are out of date,
1370 and how to update them when necessary.
1372 The criterion for being out of date is specified in terms of the
1373 PREREQUISITES, which consist of file names separated by spaces.
1374 (Wildcards and archive members (*note Archives::) are allowed here too.)
1375 A target is out of date if it does not exist or if it is older than any
1376 of the prerequisites (by comparison of last-modification times). The
1377 idea is that the contents of the target file are computed based on
1378 information in the prerequisites, so if any of the prerequisites
1379 changes, the contents of the existing target file are no longer
1382 How to update is specified by COMMANDS. These are lines to be
1383 executed by the shell (normally `sh'), but with some extra features
1384 (*note Writing the Commands in Rules: Commands.).
1387 File: make.info, Node: Prerequisite Types, Next: Wildcards, Prev: Rule Syntax, Up: Rules
1389 Types of Prerequisites
1390 ======================
1392 There are actually two different types of prerequisites understood by
1393 GNU `make': normal prerequisites such as described in the previous
1394 section, and "order-only" prerequisites. A normal prerequisite makes
1395 two statements: first, it imposes an order of execution of build
1396 commands: any commands necessary to build any of a target's
1397 prerequisites will be fully executed before any commands necessary to
1398 build the target. Second, it imposes a dependency relationship: if any
1399 prerequisite is newer than the target, then the target is considered
1400 out-of-date and must be rebuilt.
1402 Normally, this is exactly what you want: if a target's prerequisite
1403 is updated, then the target should also be updated.
1405 Occasionally, however, you have a situation where you want to impose
1406 a specific ordering on the rules to be invoked _without_ forcing the
1407 target to be updated if one of those rules is executed. In that case,
1408 you want to define "order-only" prerequisites. Order-only
1409 prerequisites can be specified by placing a pipe symbol (`|') in the
1410 prerequisites list: any prerequisites to the left of the pipe symbol
1411 are normal; any prerequisites to the right are order-only:
1413 TARGETS : NORMAL-PREREQUISITES | ORDER-ONLY-PREREQUISITES
1415 The normal prerequisites section may of course be empty. Also, you
1416 may still declare multiple lines of prerequisites for the same target:
1417 they are appended appropriately. Note that if you declare the same
1418 file to be both a normal and an order-only prerequisite, the normal
1419 prerequisite takes precedence (since they are a strict superset of the
1420 behavior of an order-only prerequisite).
1423 File: make.info, Node: Wildcards, Next: Directory Search, Prev: Prerequisite Types, Up: Rules
1425 Using Wildcard Characters in File Names
1426 =======================================
1428 A single file name can specify many files using "wildcard characters".
1429 The wildcard characters in `make' are `*', `?' and `[...]', the same as
1430 in the Bourne shell. For example, `*.c' specifies a list of all the
1431 files (in the working directory) whose names end in `.c'.
1433 The character `~' at the beginning of a file name also has special
1434 significance. If alone, or followed by a slash, it represents your home
1435 directory. For example `~/bin' expands to `/home/you/bin'. If the `~'
1436 is followed by a word, the string represents the home directory of the
1437 user named by that word. For example `~john/bin' expands to
1438 `/home/john/bin'. On systems which don't have a home directory for
1439 each user (such as MS-DOS or MS-Windows), this functionality can be
1440 simulated by setting the environment variable HOME.
1442 Wildcard expansion happens automatically in targets, in
1443 prerequisites, and in commands (where the shell does the expansion).
1444 In other contexts, wildcard expansion happens only if you request it
1445 explicitly with the `wildcard' function.
1447 The special significance of a wildcard character can be turned off by
1448 preceding it with a backslash. Thus, `foo\*bar' would refer to a
1449 specific file whose name consists of `foo', an asterisk, and `bar'.
1453 * Wildcard Examples:: Several examples
1454 * Wildcard Pitfall:: Problems to avoid.
1455 * Wildcard Function:: How to cause wildcard expansion where
1456 it does not normally take place.
1459 File: make.info, Node: Wildcard Examples, Next: Wildcard Pitfall, Prev: Wildcards, Up: Wildcards
1464 Wildcards can be used in the commands of a rule, where they are expanded
1465 by the shell. For example, here is a rule to delete all the object
1471 Wildcards are also useful in the prerequisites of a rule. With the
1472 following rule in the makefile, `make print' will print all the `.c'
1473 files that have changed since the last time you printed them:
1479 This rule uses `print' as an empty target file; see *Note Empty Target
1480 Files to Record Events: Empty Targets. (The automatic variable `$?' is
1481 used to print only those files that have changed; see *Note Automatic
1484 Wildcard expansion does not happen when you define a variable.
1485 Thus, if you write this:
1489 then the value of the variable `objects' is the actual string `*.o'.
1490 However, if you use the value of `objects' in a target, prerequisite or
1491 command, wildcard expansion will take place at that time. To set
1492 `objects' to the expansion, instead use:
1494 objects := $(wildcard *.o)
1496 *Note Wildcard Function::.
1499 File: make.info, Node: Wildcard Pitfall, Next: Wildcard Function, Prev: Wildcard Examples, Up: Wildcards
1501 Pitfalls of Using Wildcards
1502 ---------------------------
1504 Now here is an example of a naive way of using wildcard expansion, that
1505 does not do what you would intend. Suppose you would like to say that
1506 the executable file `foo' is made from all the object files in the
1507 directory, and you write this:
1512 cc -o foo $(CFLAGS) $(objects)
1514 The value of `objects' is the actual string `*.o'. Wildcard expansion
1515 happens in the rule for `foo', so that each _existing_ `.o' file
1516 becomes a prerequisite of `foo' and will be recompiled if necessary.
1518 But what if you delete all the `.o' files? When a wildcard matches
1519 no files, it is left as it is, so then `foo' will depend on the
1520 oddly-named file `*.o'. Since no such file is likely to exist, `make'
1521 will give you an error saying it cannot figure out how to make `*.o'.
1522 This is not what you want!
1524 Actually it is possible to obtain the desired result with wildcard
1525 expansion, but you need more sophisticated techniques, including the
1526 `wildcard' function and string substitution. *Note The Function
1527 `wildcard': Wildcard Function.
1529 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes
1530 to separate directories in pathnames, like so:
1534 This is equivalent to the Unix-style `c:/foo/bar/baz.c' (the `c:'
1535 part is the so-called drive letter). When `make' runs on these
1536 systems, it supports backslashes as well as the Unix-style forward
1537 slashes in pathnames. However, this support does _not_ include the
1538 wildcard expansion, where backslash is a quote character. Therefore,
1539 you _must_ use Unix-style slashes in these cases.
1542 File: make.info, Node: Wildcard Function, Prev: Wildcard Pitfall, Up: Wildcards
1544 The Function `wildcard'
1545 -----------------------
1547 Wildcard expansion happens automatically in rules. But wildcard
1548 expansion does not normally take place when a variable is set, or
1549 inside the arguments of a function. If you want to do wildcard
1550 expansion in such places, you need to use the `wildcard' function, like
1553 $(wildcard PATTERN...)
1555 This string, used anywhere in a makefile, is replaced by a
1556 space-separated list of names of existing files that match one of the
1557 given file name patterns. If no existing file name matches a pattern,
1558 then that pattern is omitted from the output of the `wildcard'
1559 function. Note that this is different from how unmatched wildcards
1560 behave in rules, where they are used verbatim rather than ignored
1561 (*note Wildcard Pitfall::).
1563 One use of the `wildcard' function is to get a list of all the C
1564 source files in a directory, like this:
1568 We can change the list of C source files into a list of object files
1569 by replacing the `.c' suffix with `.o' in the result, like this:
1571 $(patsubst %.c,%.o,$(wildcard *.c))
1573 (Here we have used another function, `patsubst'. *Note Functions for
1574 String Substitution and Analysis: Text Functions.)
1576 Thus, a makefile to compile all C source files in the directory and
1577 then link them together could be written as follows:
1579 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1582 cc -o foo $(objects)
1584 (This takes advantage of the implicit rule for compiling C programs, so
1585 there is no need to write explicit rules for compiling the files.
1586 *Note The Two Flavors of Variables: Flavors, for an explanation of
1587 `:=', which is a variant of `='.)
1590 File: make.info, Node: Directory Search, Next: Phony Targets, Prev: Wildcards, Up: Rules
1592 Searching Directories for Prerequisites
1593 =======================================
1595 For large systems, it is often desirable to put sources in a separate
1596 directory from the binaries. The "directory search" features of `make'
1597 facilitate this by searching several directories automatically to find
1598 a prerequisite. When you redistribute the files among directories, you
1599 do not need to change the individual rules, just the search paths.
1603 * General Search:: Specifying a search path that applies
1604 to every prerequisite.
1605 * Selective Search:: Specifying a search path
1606 for a specified class of names.
1607 * Search Algorithm:: When and how search paths are applied.
1608 * Commands/Search:: How to write shell commands that work together
1610 * Implicit/Search:: How search paths affect implicit rules.
1611 * Libraries/Search:: Directory search for link libraries.
1614 File: make.info, Node: General Search, Next: Selective Search, Prev: Directory Search, Up: Directory Search
1616 `VPATH': Search Path for All Prerequisites
1617 ------------------------------------------
1619 The value of the `make' variable `VPATH' specifies a list of
1620 directories that `make' should search. Most often, the directories are
1621 expected to contain prerequisite files that are not in the current
1622 directory; however, `make' uses `VPATH' as a search list for both
1623 prerequisites and targets of rules.
1625 Thus, if a file that is listed as a target or prerequisite does not
1626 exist in the current directory, `make' searches the directories listed
1627 in `VPATH' for a file with that name. If a file is found in one of
1628 them, that file may become the prerequisite (see below). Rules may then
1629 specify the names of files in the prerequisite list as if they all
1630 existed in the current directory. *Note Writing Shell Commands with
1631 Directory Search: Commands/Search.
1633 In the `VPATH' variable, directory names are separated by colons or
1634 blanks. The order in which directories are listed is the order followed
1635 by `make' in its search. (On MS-DOS and MS-Windows, semi-colons are
1636 used as separators of directory names in `VPATH', since the colon can
1637 be used in the pathname itself, after the drive letter.)
1641 VPATH = src:../headers
1643 specifies a path containing two directories, `src' and `../headers',
1644 which `make' searches in that order.
1646 With this value of `VPATH', the following rule,
1650 is interpreted as if it were written like this:
1654 assuming the file `foo.c' does not exist in the current directory but
1655 is found in the directory `src'.
1658 File: make.info, Node: Selective Search, Next: Search Algorithm, Prev: General Search, Up: Directory Search
1660 The `vpath' Directive
1661 ---------------------
1663 Similar to the `VPATH' variable, but more selective, is the `vpath'
1664 directive (note lower case), which allows you to specify a search path
1665 for a particular class of file names: those that match a particular
1666 pattern. Thus you can supply certain search directories for one class
1667 of file names and other directories (or none) for other file names.
1669 There are three forms of the `vpath' directive:
1671 `vpath PATTERN DIRECTORIES'
1672 Specify the search path DIRECTORIES for file names that match
1675 The search path, DIRECTORIES, is a list of directories to be
1676 searched, separated by colons (semi-colons on MS-DOS and
1677 MS-Windows) or blanks, just like the search path used in the
1681 Clear out the search path associated with PATTERN.
1684 Clear all search paths previously specified with `vpath'
1687 A `vpath' pattern is a string containing a `%' character. The
1688 string must match the file name of a prerequisite that is being searched
1689 for, the `%' character matching any sequence of zero or more characters
1690 (as in pattern rules; *note Defining and Redefining Pattern Rules:
1691 Pattern Rules.). For example, `%.h' matches files that end in `.h'.
1692 (If there is no `%', the pattern must match the prerequisite exactly,
1693 which is not useful very often.)
1695 `%' characters in a `vpath' directive's pattern can be quoted with
1696 preceding backslashes (`\'). Backslashes that would otherwise quote
1697 `%' characters can be quoted with more backslashes. Backslashes that
1698 quote `%' characters or other backslashes are removed from the pattern
1699 before it is compared to file names. Backslashes that are not in
1700 danger of quoting `%' characters go unmolested.
1702 When a prerequisite fails to exist in the current directory, if the
1703 PATTERN in a `vpath' directive matches the name of the prerequisite
1704 file, then the DIRECTORIES in that directive are searched just like
1705 (and before) the directories in the `VPATH' variable.
1709 vpath %.h ../headers
1711 tells `make' to look for any prerequisite whose name ends in `.h' in
1712 the directory `../headers' if the file is not found in the current
1715 If several `vpath' patterns match the prerequisite file's name, then
1716 `make' processes each matching `vpath' directive one by one, searching
1717 all the directories mentioned in each directive. `make' handles
1718 multiple `vpath' directives in the order in which they appear in the
1719 makefile; multiple directives with the same pattern are independent of
1728 will look for a file ending in `.c' in `foo', then `blish', then `bar',
1734 will look for a file ending in `.c' in `foo', then `bar', then `blish'.
1737 File: make.info, Node: Search Algorithm, Next: Commands/Search, Prev: Selective Search, Up: Directory Search
1739 How Directory Searches are Performed
1740 ------------------------------------
1742 When a prerequisite is found through directory search, regardless of
1743 type (general or selective), the pathname located may not be the one
1744 that `make' actually provides you in the prerequisite list. Sometimes
1745 the path discovered through directory search is thrown away.
1747 The algorithm `make' uses to decide whether to keep or abandon a
1748 path found via directory search is as follows:
1750 1. If a target file does not exist at the path specified in the
1751 makefile, directory search is performed.
1753 2. If the directory search is successful, that path is kept and this
1754 file is tentatively stored as the target.
1756 3. All prerequisites of this target are examined using this same
1759 4. After processing the prerequisites, the target may or may not need
1762 a. If the target does _not_ need to be rebuilt, the path to the
1763 file found during directory search is used for any
1764 prerequisite lists which contain this target. In short, if
1765 `make' doesn't need to rebuild the target then you use the
1766 path found via directory search.
1768 b. If the target _does_ need to be rebuilt (is out-of-date), the
1769 pathname found during directory search is _thrown away_, and
1770 the target is rebuilt using the file name specified in the
1771 makefile. In short, if `make' must rebuild, then the target
1772 is rebuilt locally, not in the directory found via directory
1775 This algorithm may seem complex, but in practice it is quite often
1776 exactly what you want.
1778 Other versions of `make' use a simpler algorithm: if the file does
1779 not exist, and it is found via directory search, then that pathname is
1780 always used whether or not the target needs to be built. Thus, if the
1781 target is rebuilt it is created at the pathname discovered during
1784 If, in fact, this is the behavior you want for some or all of your
1785 directories, you can use the `GPATH' variable to indicate this to
1788 `GPATH' has the same syntax and format as `VPATH' (that is, a space-
1789 or colon-delimited list of pathnames). If an out-of-date target is
1790 found by directory search in a directory that also appears in `GPATH',
1791 then that pathname is not thrown away. The target is rebuilt using the
1795 File: make.info, Node: Commands/Search, Next: Implicit/Search, Prev: Search Algorithm, Up: Directory Search
1797 Writing Shell Commands with Directory Search
1798 --------------------------------------------
1800 When a prerequisite is found in another directory through directory
1801 search, this cannot change the commands of the rule; they will execute
1802 as written. Therefore, you must write the commands with care so that
1803 they will look for the prerequisite in the directory where `make' finds
1806 This is done with the "automatic variables" such as `$^' (*note
1807 Automatic Variables::). For instance, the value of `$^' is a list of
1808 all the prerequisites of the rule, including the names of the
1809 directories in which they were found, and the value of `$@' is the
1813 cc -c $(CFLAGS) $^ -o $@
1815 (The variable `CFLAGS' exists so you can specify flags for C
1816 compilation by implicit rules; we use it here for consistency so it will
1817 affect all C compilations uniformly; *note Variables Used by Implicit
1818 Rules: Implicit Variables..)
1820 Often the prerequisites include header files as well, which you do
1821 not want to mention in the commands. The automatic variable `$<' is
1822 just the first prerequisite:
1824 VPATH = src:../headers
1825 foo.o : foo.c defs.h hack.h
1826 cc -c $(CFLAGS) $< -o $@
1829 File: make.info, Node: Implicit/Search, Next: Libraries/Search, Prev: Commands/Search, Up: Directory Search
1831 Directory Search and Implicit Rules
1832 -----------------------------------
1834 The search through the directories specified in `VPATH' or with `vpath'
1835 also happens during consideration of implicit rules (*note Using
1836 Implicit Rules: Implicit Rules.).
1838 For example, when a file `foo.o' has no explicit rule, `make'
1839 considers implicit rules, such as the built-in rule to compile `foo.c'
1840 if that file exists. If such a file is lacking in the current
1841 directory, the appropriate directories are searched for it. If `foo.c'
1842 exists (or is mentioned in the makefile) in any of the directories, the
1843 implicit rule for C compilation is applied.
1845 The commands of implicit rules normally use automatic variables as a
1846 matter of necessity; consequently they will use the file names found by
1847 directory search with no extra effort.
1850 File: make.info, Node: Libraries/Search, Prev: Implicit/Search, Up: Directory Search
1852 Directory Search for Link Libraries
1853 -----------------------------------
1855 Directory search applies in a special way to libraries used with the
1856 linker. This special feature comes into play when you write a
1857 prerequisite whose name is of the form `-lNAME'. (You can tell
1858 something strange is going on here because the prerequisite is normally
1859 the name of a file, and the _file name_ of a library generally looks
1860 like `libNAME.a', not like `-lNAME'.)
1862 When a prerequisite's name has the form `-lNAME', `make' handles it
1863 specially by searching for the file `libNAME.so' in the current
1864 directory, in directories specified by matching `vpath' search paths
1865 and the `VPATH' search path, and then in the directories `/lib',
1866 `/usr/lib', and `PREFIX/lib' (normally `/usr/local/lib', but
1867 MS-DOS/MS-Windows versions of `make' behave as if PREFIX is defined to
1868 be the root of the DJGPP installation tree).
1870 If that file is not found, then the file `libNAME.a' is searched
1871 for, in the same directories as above.
1873 For example, if there is a `/usr/lib/libcurses.a' library on your
1874 system (and no `/usr/lib/libcurses.so' file), then
1876 foo : foo.c -lcurses
1879 would cause the command `cc foo.c /usr/lib/libcurses.a -o foo' to be
1880 executed when `foo' is older than `foo.c' or than
1881 `/usr/lib/libcurses.a'.
1883 Although the default set of files to be searched for is `libNAME.so'
1884 and `libNAME.a', this is customizable via the `.LIBPATTERNS' variable.
1885 Each word in the value of this variable is a pattern string. When a
1886 prerequisite like `-lNAME' is seen, `make' will replace the percent in
1887 each pattern in the list with NAME and perform the above directory
1888 searches using that library filename. If no library is found, the next
1889 word in the list will be used.
1891 The default value for `.LIBPATTERNS' is "`lib%.so lib%.a'", which
1892 provides the default behavior described above.
1894 You can turn off link library expansion completely by setting this
1895 variable to an empty value.
1898 File: make.info, Node: Phony Targets, Next: Force Targets, Prev: Directory Search, Up: Rules
1903 A phony target is one that is not really the name of a file. It is
1904 just a name for some commands to be executed when you make an explicit
1905 request. There are two reasons to use a phony target: to avoid a
1906 conflict with a file of the same name, and to improve performance.
1908 If you write a rule whose commands will not create the target file,
1909 the commands will be executed every time the target comes up for
1910 remaking. Here is an example:
1915 Because the `rm' command does not create a file named `clean', probably
1916 no such file will ever exist. Therefore, the `rm' command will be
1917 executed every time you say `make clean'.
1919 The phony target will cease to work if anything ever does create a
1920 file named `clean' in this directory. Since it has no prerequisites,
1921 the file `clean' would inevitably be considered up to date, and its
1922 commands would not be executed. To avoid this problem, you can
1923 explicitly declare the target to be phony, using the special target
1924 `.PHONY' (*note Special Built-in Target Names: Special Targets.) as
1929 Once this is done, `make clean' will run the commands regardless of
1930 whether there is a file named `clean'.
1932 Since it knows that phony targets do not name actual files that
1933 could be remade from other files, `make' skips the implicit rule search
1934 for phony targets (*note Implicit Rules::). This is why declaring a
1935 target phony is good for performance, even if you are not worried about
1936 the actual file existing.
1938 Thus, you first write the line that states that `clean' is a phony
1939 target, then you write the rule, like this:
1945 Another example of the usefulness of phony targets is in conjunction
1946 with recursive invocations of `make' (for more information, see *Note
1947 Recursive Use of `make': Recursion). In this case the makefile will
1948 often contain a variable which lists a number of subdirectories to be
1949 built. One way to handle this is with one rule whose command is a
1950 shell loop over the subdirectories, like this:
1952 SUBDIRS = foo bar baz
1955 for dir in $(SUBDIRS); do \
1959 There are a few problems with this method, however. First, any error
1960 detected in a submake is not noted by this rule, so it will continue to
1961 build the rest of the directories even when one fails. This can be
1962 overcome by adding shell commands to note the error and exit, but then
1963 it will do so even if `make' is invoked with the `-k' option, which is
1964 unfortunate. Second, and perhaps more importantly, you cannot take
1965 advantage of the parallel build capabilities of make using this method,
1966 since there is only one rule.
1968 By declaring the subdirectories as phony targets (you must do this as
1969 the subdirectory obviously always exists; otherwise it won't be built)
1970 you can remove these problems:
1972 SUBDIRS = foo bar baz
1974 .PHONY: subdirs $(SUBDIRS)
1983 Here we've also declared that the `foo' subdirectory cannot be built
1984 until after the `baz' subdirectory is complete; this kind of
1985 relationship declaration is particularly important when attempting
1988 A phony target should not be a prerequisite of a real target file;
1989 if it is, its commands are run every time `make' goes to update that
1990 file. As long as a phony target is never a prerequisite of a real
1991 target, the phony target commands will be executed only when the phony
1992 target is a specified goal (*note Arguments to Specify the Goals:
1995 Phony targets can have prerequisites. When one directory contains
1996 multiple programs, it is most convenient to describe all of the
1997 programs in one makefile `./Makefile'. Since the target remade by
1998 default will be the first one in the makefile, it is common to make
1999 this a phony target named `all' and give it, as prerequisites, all the
2000 individual programs. For example:
2002 all : prog1 prog2 prog3
2005 prog1 : prog1.o utils.o
2006 cc -o prog1 prog1.o utils.o
2011 prog3 : prog3.o sort.o utils.o
2012 cc -o prog3 prog3.o sort.o utils.o
2014 Now you can say just `make' to remake all three programs, or specify as
2015 arguments the ones to remake (as in `make prog1 prog3').
2017 When one phony target is a prerequisite of another, it serves as a
2018 subroutine of the other. For example, here `make cleanall' will delete
2019 the object files, the difference files, and the file `program':
2021 .PHONY: cleanall cleanobj cleandiff
2023 cleanall : cleanobj cleandiff
2033 File: make.info, Node: Force Targets, Next: Empty Targets, Prev: Phony Targets, Up: Rules
2035 Rules without Commands or Prerequisites
2036 =======================================
2038 If a rule has no prerequisites or commands, and the target of the rule
2039 is a nonexistent file, then `make' imagines this target to have been
2040 updated whenever its rule is run. This implies that all targets
2041 depending on this one will always have their commands run.
2043 An example will illustrate this:
2049 Here the target `FORCE' satisfies the special conditions, so the
2050 target `clean' that depends on it is forced to run its commands. There
2051 is nothing special about the name `FORCE', but that is one name
2052 commonly used this way.
2054 As you can see, using `FORCE' this way has the same results as using
2057 Using `.PHONY' is more explicit and more efficient. However, other
2058 versions of `make' do not support `.PHONY'; thus `FORCE' appears in
2059 many makefiles. *Note Phony Targets::.
2062 File: make.info, Node: Empty Targets, Next: Special Targets, Prev: Force Targets, Up: Rules
2064 Empty Target Files to Record Events
2065 ===================================
2067 The "empty target" is a variant of the phony target; it is used to hold
2068 commands for an action that you request explicitly from time to time.
2069 Unlike a phony target, this target file can really exist; but the file's
2070 contents do not matter, and usually are empty.
2072 The purpose of the empty target file is to record, with its
2073 last-modification time, when the rule's commands were last executed. It
2074 does so because one of the commands is a `touch' command to update the
2077 The empty target file should have some prerequisites (otherwise it
2078 doesn't make sense). When you ask to remake the empty target, the
2079 commands are executed if any prerequisite is more recent than the
2080 target; in other words, if a prerequisite has changed since the last
2081 time you remade the target. Here is an example:
2087 With this rule, `make print' will execute the `lpr' command if either
2088 source file has changed since the last `make print'. The automatic
2089 variable `$?' is used to print only those files that have changed
2090 (*note Automatic Variables::).
2093 File: make.info, Node: Special Targets, Next: Multiple Targets, Prev: Empty Targets, Up: Rules
2095 Special Built-in Target Names
2096 =============================
2098 Certain names have special meanings if they appear as targets.
2101 The prerequisites of the special target `.PHONY' are considered to
2102 be phony targets. When it is time to consider such a target,
2103 `make' will run its commands unconditionally, regardless of
2104 whether a file with that name exists or what its last-modification
2105 time is. *Note Phony Targets: Phony Targets.
2108 The prerequisites of the special target `.SUFFIXES' are the list
2109 of suffixes to be used in checking for suffix rules. *Note
2110 Old-Fashioned Suffix Rules: Suffix Rules.
2113 The commands specified for `.DEFAULT' are used for any target for
2114 which no rules are found (either explicit rules or implicit rules).
2115 *Note Last Resort::. If `.DEFAULT' commands are specified, every
2116 file mentioned as a prerequisite, but not as a target in a rule,
2117 will have these commands executed on its behalf. *Note Implicit
2118 Rule Search Algorithm: Implicit Rule Search.
2121 The targets which `.PRECIOUS' depends on are given the following
2122 special treatment: if `make' is killed or interrupted during the
2123 execution of their commands, the target is not deleted. *Note
2124 Interrupting or Killing `make': Interrupts. Also, if the target
2125 is an intermediate file, it will not be deleted after it is no
2126 longer needed, as is normally done. *Note Chains of Implicit
2127 Rules: Chained Rules. In this latter respect it overlaps with the
2128 `.SECONDARY' special target.
2130 You can also list the target pattern of an implicit rule (such as
2131 `%.o') as a prerequisite file of the special target `.PRECIOUS' to
2132 preserve intermediate files created by rules whose target patterns
2133 match that file's name.
2136 The targets which `.INTERMEDIATE' depends on are treated as
2137 intermediate files. *Note Chains of Implicit Rules: Chained Rules.
2138 `.INTERMEDIATE' with no prerequisites has no effect.
2141 The targets which `.SECONDARY' depends on are treated as
2142 intermediate files, except that they are never automatically
2143 deleted. *Note Chains of Implicit Rules: Chained Rules.
2145 `.SECONDARY' with no prerequisites causes all targets to be treated
2146 as secondary (i.e., no target is removed because it is considered
2150 If `.DELETE_ON_ERROR' is mentioned as a target anywhere in the
2151 makefile, then `make' will delete the target of a rule if it has
2152 changed and its commands exit with a nonzero exit status, just as
2153 it does when it receives a signal. *Note Errors in Commands:
2157 If you specify prerequisites for `.IGNORE', then `make' will
2158 ignore errors in execution of the commands run for those particular
2159 files. The commands for `.IGNORE' are not meaningful.
2161 If mentioned as a target with no prerequisites, `.IGNORE' says to
2162 ignore errors in execution of commands for all files. This usage
2163 of `.IGNORE' is supported only for historical compatibility. Since
2164 this affects every command in the makefile, it is not very useful;
2165 we recommend you use the more selective ways to ignore errors in
2166 specific commands. *Note Errors in Commands: Errors.
2168 `.LOW_RESOLUTION_TIME'
2169 If you specify prerequisites for `.LOW_RESOLUTION_TIME', `make'
2170 assumes that these files are created by commands that generate low
2171 resolution time stamps. The commands for `.LOW_RESOLUTION_TIME'
2174 The high resolution file time stamps of many modern hosts lessen
2175 the chance of `make' incorrectly concluding that a file is up to
2176 date. Unfortunately, these hosts provide no way to set a high
2177 resolution file time stamp, so commands like `cp -p' that
2178 explicitly set a file's time stamp must discard its subsecond
2179 part. If a file is created by such a command, you should list it
2180 as a prerequisite of `.LOW_RESOLUTION_TIME' so that `make' does
2181 not mistakenly conclude that the file is out of date. For example:
2183 .LOW_RESOLUTION_TIME: dst
2187 Since `cp -p' discards the subsecond part of `src''s time stamp,
2188 `dst' is typically slightly older than `src' even when it is up to
2189 date. The `.LOW_RESOLUTION_TIME' line causes `make' to consider
2190 `dst' to be up to date if its time stamp is at the start of the
2191 same second that `src''s time stamp is in.
2193 Due to a limitation of the archive format, archive member time
2194 stamps are always low resolution. You need not list archive
2195 members as prerequisites of `.LOW_RESOLUTION_TIME', as `make' does
2199 If you specify prerequisites for `.SILENT', then `make' will not
2200 print the commands to remake those particular files before
2201 executing them. The commands for `.SILENT' are not meaningful.
2203 If mentioned as a target with no prerequisites, `.SILENT' says not
2204 to print any commands before executing them. This usage of
2205 `.SILENT' is supported only for historical compatibility. We
2206 recommend you use the more selective ways to silence specific
2207 commands. *Note Command Echoing: Echoing. If you want to silence
2208 all commands for a particular run of `make', use the `-s' or
2209 `--silent' option (*note Options Summary::).
2211 `.EXPORT_ALL_VARIABLES'
2212 Simply by being mentioned as a target, this tells `make' to export
2213 all variables to child processes by default. *Note Communicating
2214 Variables to a Sub-`make': Variables/Recursion.
2217 If `.NOTPARALLEL' is mentioned as a target, then this invocation of
2218 `make' will be run serially, even if the `-j' option is given.
2219 Any recursively invoked `make' command will still be run in
2220 parallel (unless its makefile contains this target). Any
2221 prerequisites on this target are ignored.
2223 Any defined implicit rule suffix also counts as a special target if
2224 it appears as a target, and so does the concatenation of two suffixes,
2225 such as `.c.o'. These targets are suffix rules, an obsolete way of
2226 defining implicit rules (but a way still widely used). In principle,
2227 any target name could be special in this way if you break it in two and
2228 add both pieces to the suffix list. In practice, suffixes normally
2229 begin with `.', so these special target names also begin with `.'.
2230 *Note Old-Fashioned Suffix Rules: Suffix Rules.
2233 File: make.info, Node: Multiple Targets, Next: Multiple Rules, Prev: Special Targets, Up: Rules
2235 Multiple Targets in a Rule
2236 ==========================
2238 A rule with multiple targets is equivalent to writing many rules, each
2239 with one target, and all identical aside from that. The same commands
2240 apply to all the targets, but their effects may vary because you can
2241 substitute the actual target name into the command using `$@'. The
2242 rule contributes the same prerequisites to all the targets also.
2244 This is useful in two cases.
2246 * You want just prerequisites, no commands. For example:
2248 kbd.o command.o files.o: command.h
2250 gives an additional prerequisite to each of the three object files
2253 * Similar commands work for all the targets. The commands do not
2254 need to be absolutely identical, since the automatic variable `$@'
2255 can be used to substitute the particular target to be remade into
2256 the commands (*note Automatic Variables::). For example:
2258 bigoutput littleoutput : text.g
2259 generate text.g -$(subst output,,$@) > $@
2264 generate text.g -big > bigoutput
2265 littleoutput : text.g
2266 generate text.g -little > littleoutput
2268 Here we assume the hypothetical program `generate' makes two types
2269 of output, one if given `-big' and one if given `-little'. *Note
2270 Functions for String Substitution and Analysis: Text Functions,
2271 for an explanation of the `subst' function.
2273 Suppose you would like to vary the prerequisites according to the
2274 target, much as the variable `$@' allows you to vary the commands. You
2275 cannot do this with multiple targets in an ordinary rule, but you can
2276 do it with a "static pattern rule". *Note Static Pattern Rules: Static
2280 File: make.info, Node: Multiple Rules, Next: Static Pattern, Prev: Multiple Targets, Up: Rules
2282 Multiple Rules for One Target
2283 =============================
2285 One file can be the target of several rules. All the prerequisites
2286 mentioned in all the rules are merged into one list of prerequisites for
2287 the target. If the target is older than any prerequisite from any rule,
2288 the commands are executed.
2290 There can only be one set of commands to be executed for a file. If
2291 more than one rule gives commands for the same file, `make' uses the
2292 last set given and prints an error message. (As a special case, if the
2293 file's name begins with a dot, no error message is printed. This odd
2294 behavior is only for compatibility with other implementations of
2295 `make'... you should avoid using it). Occasionally it is useful to
2296 have the same target invoke multiple commands which are defined in
2297 different parts of your makefile; you can use "double-colon rules"
2298 (*note Double-Colon::) for this.
2300 An extra rule with just prerequisites can be used to give a few extra
2301 prerequisites to many files at once. For example, makefiles often have
2302 a variable, such as `objects', containing a list of all the compiler
2303 output files in the system being made. An easy way to say that all of
2304 them must be recompiled if `config.h' changes is to write the following:
2306 objects = foo.o bar.o
2308 bar.o : defs.h test.h
2309 $(objects) : config.h
2311 This could be inserted or taken out without changing the rules that
2312 really specify how to make the object files, making it a convenient
2313 form to use if you wish to add the additional prerequisite
2316 Another wrinkle is that the additional prerequisites could be
2317 specified with a variable that you set with a command argument to `make'
2318 (*note Overriding Variables: Overriding.). For example,
2321 $(objects) : $(extradeps)
2323 means that the command `make extradeps=foo.h' will consider `foo.h' as
2324 a prerequisite of each object file, but plain `make' will not.
2326 If none of the explicit rules for a target has commands, then `make'
2327 searches for an applicable implicit rule to find some commands *note
2328 Using Implicit Rules: Implicit Rules.).
2331 File: make.info, Node: Static Pattern, Next: Double-Colon, Prev: Multiple Rules, Up: Rules
2333 Static Pattern Rules
2334 ====================
2336 "Static pattern rules" are rules which specify multiple targets and
2337 construct the prerequisite names for each target based on the target
2338 name. They are more general than ordinary rules with multiple targets
2339 because the targets do not have to have identical prerequisites. Their
2340 prerequisites must be _analogous_, but not necessarily _identical_.
2344 * Static Usage:: The syntax of static pattern rules.
2345 * Static versus Implicit:: When are they better than implicit rules?
2348 File: make.info, Node: Static Usage, Next: Static versus Implicit, Prev: Static Pattern, Up: Static Pattern
2350 Syntax of Static Pattern Rules
2351 ------------------------------
2353 Here is the syntax of a static pattern rule:
2355 TARGETS ...: TARGET-PATTERN: PREREQ-PATTERNS ...
2359 The TARGETS list specifies the targets that the rule applies to. The
2360 targets can contain wildcard characters, just like the targets of
2361 ordinary rules (*note Using Wildcard Characters in File Names:
2364 The TARGET-PATTERN and PREREQ-PATTERNS say how to compute the
2365 prerequisites of each target. Each target is matched against the
2366 TARGET-PATTERN to extract a part of the target name, called the "stem".
2367 This stem is substituted into each of the PREREQ-PATTERNS to make the
2368 prerequisite names (one from each PREREQ-PATTERN).
2370 Each pattern normally contains the character `%' just once. When the
2371 TARGET-PATTERN matches a target, the `%' can match any part of the
2372 target name; this part is called the "stem". The rest of the pattern
2373 must match exactly. For example, the target `foo.o' matches the
2374 pattern `%.o', with `foo' as the stem. The targets `foo.c' and
2375 `foo.out' do not match that pattern.
2377 The prerequisite names for each target are made by substituting the
2378 stem for the `%' in each prerequisite pattern. For example, if one
2379 prerequisite pattern is `%.c', then substitution of the stem `foo'
2380 gives the prerequisite name `foo.c'. It is legitimate to write a
2381 prerequisite pattern that does not contain `%'; then this prerequisite
2382 is the same for all targets.
2384 `%' characters in pattern rules can be quoted with preceding
2385 backslashes (`\'). Backslashes that would otherwise quote `%'
2386 characters can be quoted with more backslashes. Backslashes that quote
2387 `%' characters or other backslashes are removed from the pattern before
2388 it is compared to file names or has a stem substituted into it.
2389 Backslashes that are not in danger of quoting `%' characters go
2390 unmolested. For example, the pattern `the\%weird\\%pattern\\' has
2391 `the%weird\' preceding the operative `%' character, and `pattern\\'
2392 following it. The final two backslashes are left alone because they
2393 cannot affect any `%' character.
2395 Here is an example, which compiles each of `foo.o' and `bar.o' from
2396 the corresponding `.c' file:
2398 objects = foo.o bar.o
2402 $(objects): %.o: %.c
2403 $(CC) -c $(CFLAGS) $< -o $@
2405 Here `$<' is the automatic variable that holds the name of the
2406 prerequisite and `$@' is the automatic variable that holds the name of
2407 the target; see *Note Automatic Variables::.
2409 Each target specified must match the target pattern; a warning is
2410 issued for each target that does not. If you have a list of files,
2411 only some of which will match the pattern, you can use the `filter'
2412 function to remove nonmatching file names (*note Functions for String
2413 Substitution and Analysis: Text Functions.):
2415 files = foo.elc bar.o lose.o
2417 $(filter %.o,$(files)): %.o: %.c
2418 $(CC) -c $(CFLAGS) $< -o $@
2419 $(filter %.elc,$(files)): %.elc: %.el
2420 emacs -f batch-byte-compile $<
2422 In this example the result of `$(filter %.o,$(files))' is `bar.o
2423 lose.o', and the first static pattern rule causes each of these object
2424 files to be updated by compiling the corresponding C source file. The
2425 result of `$(filter %.elc,$(files))' is `foo.elc', so that file is made
2428 Another example shows how to use `$*' in static pattern rules:
2430 bigoutput littleoutput : %output : text.g
2431 generate text.g -$* > $@
2433 When the `generate' command is run, `$*' will expand to the stem,
2434 either `big' or `little'.
2437 File: make.info, Node: Static versus Implicit, Prev: Static Usage, Up: Static Pattern
2439 Static Pattern Rules versus Implicit Rules
2440 ------------------------------------------
2442 A static pattern rule has much in common with an implicit rule defined
2443 as a pattern rule (*note Defining and Redefining Pattern Rules: Pattern
2444 Rules.). Both have a pattern for the target and patterns for
2445 constructing the names of prerequisites. The difference is in how
2446 `make' decides _when_ the rule applies.
2448 An implicit rule _can_ apply to any target that matches its pattern,
2449 but it _does_ apply only when the target has no commands otherwise
2450 specified, and only when the prerequisites can be found. If more than
2451 one implicit rule appears applicable, only one applies; the choice
2452 depends on the order of rules.
2454 By contrast, a static pattern rule applies to the precise list of
2455 targets that you specify in the rule. It cannot apply to any other
2456 target and it invariably does apply to each of the targets specified.
2457 If two conflicting rules apply, and both have commands, that's an error.
2459 The static pattern rule can be better than an implicit rule for these
2462 * You may wish to override the usual implicit rule for a few files
2463 whose names cannot be categorized syntactically but can be given
2464 in an explicit list.
2466 * If you cannot be sure of the precise contents of the directories
2467 you are using, you may not be sure which other irrelevant files
2468 might lead `make' to use the wrong implicit rule. The choice
2469 might depend on the order in which the implicit rule search is
2470 done. With static pattern rules, there is no uncertainty: each
2471 rule applies to precisely the targets specified.
2474 File: make.info, Node: Double-Colon, Next: Automatic Prerequisites, Prev: Static Pattern, Up: Rules
2479 "Double-colon" rules are rules written with `::' instead of `:' after
2480 the target names. They are handled differently from ordinary rules
2481 when the same target appears in more than one rule.
2483 When a target appears in multiple rules, all the rules must be the
2484 same type: all ordinary, or all double-colon. If they are
2485 double-colon, each of them is independent of the others. Each
2486 double-colon rule's commands are executed if the target is older than
2487 any prerequisites of that rule. If there are no prerequisites for that
2488 rule, its commands are always executed (even if the target already
2489 exists). This can result in executing none, any, or all of the
2492 Double-colon rules with the same target are in fact completely
2493 separate from one another. Each double-colon rule is processed
2494 individually, just as rules with different targets are processed.
2496 The double-colon rules for a target are executed in the order they
2497 appear in the makefile. However, the cases where double-colon rules
2498 really make sense are those where the order of executing the commands
2501 Double-colon rules are somewhat obscure and not often very useful;
2502 they provide a mechanism for cases in which the method used to update a
2503 target differs depending on which prerequisite files caused the update,
2504 and such cases are rare.
2506 Each double-colon rule should specify commands; if it does not, an
2507 implicit rule will be used if one applies. *Note Using Implicit Rules:
2511 File: make.info, Node: Automatic Prerequisites, Prev: Double-Colon, Up: Rules
2513 Generating Prerequisites Automatically
2514 ======================================
2516 In the makefile for a program, many of the rules you need to write often
2517 say only that some object file depends on some header file. For
2518 example, if `main.c' uses `defs.h' via an `#include', you would write:
2522 You need this rule so that `make' knows that it must remake `main.o'
2523 whenever `defs.h' changes. You can see that for a large program you
2524 would have to write dozens of such rules in your makefile. And, you
2525 must always be very careful to update the makefile every time you add
2526 or remove an `#include'.
2528 To avoid this hassle, most modern C compilers can write these rules
2529 for you, by looking at the `#include' lines in the source files.
2530 Usually this is done with the `-M' option to the compiler. For
2531 example, the command:
2535 generates the output:
2537 main.o : main.c defs.h
2539 Thus you no longer have to write all those rules yourself. The
2540 compiler will do it for you.
2542 Note that such a prerequisite constitutes mentioning `main.o' in a
2543 makefile, so it can never be considered an intermediate file by implicit
2544 rule search. This means that `make' won't ever remove the file after
2545 using it; *note Chains of Implicit Rules: Chained Rules..
2547 With old `make' programs, it was traditional practice to use this
2548 compiler feature to generate prerequisites on demand with a command like
2549 `make depend'. That command would create a file `depend' containing
2550 all the automatically-generated prerequisites; then the makefile could
2551 use `include' to read them in (*note Include::).
2553 In GNU `make', the feature of remaking makefiles makes this practice
2554 obsolete--you need never tell `make' explicitly to regenerate the
2555 prerequisites, because it always regenerates any makefile that is out
2556 of date. *Note Remaking Makefiles::.
2558 The practice we recommend for automatic prerequisite generation is
2559 to have one makefile corresponding to each source file. For each
2560 source file `NAME.c' there is a makefile `NAME.d' which lists what
2561 files the object file `NAME.o' depends on. That way only the source
2562 files that have changed need to be rescanned to produce the new
2565 Here is the pattern rule to generate a file of prerequisites (i.e.,
2566 a makefile) called `NAME.d' from a C source file called `NAME.c':
2570 $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
2571 sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
2574 *Note Pattern Rules::, for information on defining pattern rules. The
2575 `-e' flag to the shell causes it to exit immediately if the `$(CC)'
2576 command (or any other command) fails (exits with a nonzero status).
2578 With the GNU C compiler, you may wish to use the `-MM' flag instead
2579 of `-M'. This omits prerequisites on system header files. *Note
2580 Options Controlling the Preprocessor: (gcc.info)Preprocessor Options,
2583 The purpose of the `sed' command is to translate (for example):
2585 main.o : main.c defs.h
2589 main.o main.d : main.c defs.h
2591 This makes each `.d' file depend on all the source and header files
2592 that the corresponding `.o' file depends on. `make' then knows it must
2593 regenerate the prerequisites whenever any of the source or header files
2596 Once you've defined the rule to remake the `.d' files, you then use
2597 the `include' directive to read them all in. *Note Include::. For
2600 sources = foo.c bar.c
2602 include $(sources:.c=.d)
2604 (This example uses a substitution variable reference to translate the
2605 list of source files `foo.c bar.c' into a list of prerequisite
2606 makefiles, `foo.d bar.d'. *Note Substitution Refs::, for full
2607 information on substitution references.) Since the `.d' files are
2608 makefiles like any others, `make' will remake them as necessary with no
2609 further work from you. *Note Remaking Makefiles::.
2611 Note that the `.d' files contain target definitions; you should be
2612 sure to place the `include' directive _after_ the first, default target
2613 in your makefiles or run the risk of having a random object file become
2614 the default target. *Note How Make Works::.
2617 File: make.info, Node: Commands, Next: Using Variables, Prev: Rules, Up: Top
2619 Writing the Commands in Rules
2620 *****************************
2622 The commands of a rule consist of shell command lines to be executed one
2623 by one. Each command line must start with a tab, except that the first
2624 command line may be attached to the target-and-prerequisites line with a
2625 semicolon in between. Blank lines and lines of just comments may appear
2626 among the command lines; they are ignored. (But beware, an apparently
2627 "blank" line that begins with a tab is _not_ blank! It is an empty
2628 command; *note Empty Commands::.)
2630 Users use many different shell programs, but commands in makefiles
2631 are always interpreted by `/bin/sh' unless the makefile specifies
2632 otherwise. *Note Command Execution: Execution.
2634 The shell that is in use determines whether comments can be written
2635 on command lines, and what syntax they use. When the shell is
2636 `/bin/sh', a `#' starts a comment that extends to the end of the line.
2637 The `#' does not have to be at the beginning of a line. Text on a line
2638 before a `#' is not part of the comment.
2642 * Echoing:: How to control when commands are echoed.
2643 * Execution:: How commands are executed.
2644 * Parallel:: How commands can be executed in parallel.
2645 * Errors:: What happens after a command execution error.
2646 * Interrupts:: What happens when a command is interrupted.
2647 * Recursion:: Invoking `make' from makefiles.
2648 * Sequences:: Defining canned sequences of commands.
2649 * Empty Commands:: Defining useful, do-nothing commands.
2652 File: make.info, Node: Echoing, Next: Execution, Prev: Commands, Up: Commands
2657 Normally `make' prints each command line before it is executed. We
2658 call this "echoing" because it gives the appearance that you are typing
2659 the commands yourself.
2661 When a line starts with `@', the echoing of that line is suppressed.
2662 The `@' is discarded before the command is passed to the shell.
2663 Typically you would use this for a command whose only effect is to print
2664 something, such as an `echo' command to indicate progress through the
2667 @echo About to make distribution files
2669 When `make' is given the flag `-n' or `--just-print' it only echoes
2670 commands, it won't execute them. *Note Summary of Options: Options
2671 Summary. In this case and only this case, even the commands starting
2672 with `@' are printed. This flag is useful for finding out which
2673 commands `make' thinks are necessary without actually doing them.
2675 The `-s' or `--silent' flag to `make' prevents all echoing, as if
2676 all commands started with `@'. A rule in the makefile for the special
2677 target `.SILENT' without prerequisites has the same effect (*note
2678 Special Built-in Target Names: Special Targets.). `.SILENT' is
2679 essentially obsolete since `@' is more flexible.
2682 File: make.info, Node: Execution, Next: Parallel, Prev: Echoing, Up: Commands
2687 When it is time to execute commands to update a target, they are
2688 executed by making a new subshell for each line. (In practice, `make'
2689 may take shortcuts that do not affect the results.)
2691 *Please note:* this implies that shell commands such as `cd' that
2692 set variables local to each process will not affect the following
2693 command lines. (1) If you want to use `cd' to affect the next command,
2694 put the two on a single line with a semicolon between them. Then
2695 `make' will consider them a single command and pass them, together, to
2696 a shell which will execute them in sequence. For example:
2699 cd bar; gobble lose > ../foo
2701 If you would like to split a single shell command into multiple
2702 lines of text, you must use a backslash at the end of all but the last
2703 subline. Such a sequence of lines is combined into a single line, by
2704 deleting the backslash-newline sequences, before passing it to the
2705 shell. Thus, the following is equivalent to the preceding example:
2709 gobble lose > ../foo
2711 The program used as the shell is taken from the variable `SHELL'.
2712 By default, the program `/bin/sh' is used.
2714 On MS-DOS, if `SHELL' is not set, the value of the variable
2715 `COMSPEC' (which is always set) is used instead.
2717 The processing of lines that set the variable `SHELL' in Makefiles
2718 is different on MS-DOS. The stock shell, `command.com', is
2719 ridiculously limited in its functionality and many users of `make' tend
2720 to install a replacement shell. Therefore, on MS-DOS, `make' examines
2721 the value of `SHELL', and changes its behavior based on whether it
2722 points to a Unix-style or DOS-style shell. This allows reasonable
2723 functionality even if `SHELL' points to `command.com'.
2725 If `SHELL' points to a Unix-style shell, `make' on MS-DOS
2726 additionally checks whether that shell can indeed be found; if not, it
2727 ignores the line that sets `SHELL'. In MS-DOS, GNU `make' searches for
2728 the shell in the following places:
2730 1. In the precise place pointed to by the value of `SHELL'. For
2731 example, if the makefile specifies `SHELL = /bin/sh', `make' will
2732 look in the directory `/bin' on the current drive.
2734 2. In the current directory.
2736 3. In each of the directories in the `PATH' variable, in order.
2739 In every directory it examines, `make' will first look for the
2740 specific file (`sh' in the example above). If this is not found, it
2741 will also look in that directory for that file with one of the known
2742 extensions which identify executable files. For example `.exe',
2743 `.com', `.bat', `.btm', `.sh', and some others.
2745 If any of these attempts is successful, the value of `SHELL' will be
2746 set to the full pathname of the shell as found. However, if none of
2747 these is found, the value of `SHELL' will not be changed, and thus the
2748 line that sets it will be effectively ignored. This is so `make' will
2749 only support features specific to a Unix-style shell if such a shell is
2750 actually installed on the system where `make' runs.
2752 Note that this extended search for the shell is limited to the cases
2753 where `SHELL' is set from the Makefile; if it is set in the environment
2754 or command line, you are expected to set it to the full pathname of the
2755 shell, exactly as things are on Unix.
2757 The effect of the above DOS-specific processing is that a Makefile
2758 that says `SHELL = /bin/sh' (as many Unix makefiles do), will work on
2759 MS-DOS unaltered if you have e.g. `sh.exe' installed in some directory
2762 Unlike most variables, the variable `SHELL' is never set from the
2763 environment. This is because the `SHELL' environment variable is used
2764 to specify your personal choice of shell program for interactive use.
2765 It would be very bad for personal choices like this to affect the
2766 functioning of makefiles. *Note Variables from the Environment:
2767 Environment. However, on MS-DOS and MS-Windows the value of `SHELL' in
2768 the environment *is* used, since on those systems most users do not set
2769 this variable, and therefore it is most likely set specifically to be
2770 used by `make'. On MS-DOS, if the setting of `SHELL' is not suitable
2771 for `make', you can set the variable `MAKESHELL' to the shell that
2772 `make' should use; this will override the value of `SHELL'.
2774 ---------- Footnotes ----------
2776 (1) On MS-DOS, the value of current working directory is *global*,
2777 so changing it _will_ affect the following command lines on those
2781 File: make.info, Node: Parallel, Next: Errors, Prev: Execution, Up: Commands
2786 GNU `make' knows how to execute several commands at once. Normally,
2787 `make' will execute only one command at a time, waiting for it to
2788 finish before executing the next. However, the `-j' or `--jobs' option
2789 tells `make' to execute many commands simultaneously.
2791 On MS-DOS, the `-j' option has no effect, since that system doesn't
2792 support multi-processing.
2794 If the `-j' option is followed by an integer, this is the number of
2795 commands to execute at once; this is called the number of "job slots".
2796 If there is nothing looking like an integer after the `-j' option,
2797 there is no limit on the number of job slots. The default number of job
2798 slots is one, which means serial execution (one thing at a time).
2800 One unpleasant consequence of running several commands
2801 simultaneously is that output generated by the commands appears
2802 whenever each command sends it, so messages from different commands may
2805 Another problem is that two processes cannot both take input from the
2806 same device; so to make sure that only one command tries to take input
2807 from the terminal at once, `make' will invalidate the standard input
2808 streams of all but one running command. This means that attempting to
2809 read from standard input will usually be a fatal error (a `Broken pipe'
2810 signal) for most child processes if there are several.
2812 It is unpredictable which command will have a valid standard input
2813 stream (which will come from the terminal, or wherever you redirect the
2814 standard input of `make'). The first command run will always get it
2815 first, and the first command started after that one finishes will get
2818 We will change how this aspect of `make' works if we find a better
2819 alternative. In the mean time, you should not rely on any command using
2820 standard input at all if you are using the parallel execution feature;
2821 but if you are not using this feature, then standard input works
2822 normally in all commands.
2824 Finally, handling recursive `make' invocations raises issues. For
2825 more information on this, see *Note Communicating Options to a
2826 Sub-`make': Options/Recursion.
2828 If a command fails (is killed by a signal or exits with a nonzero
2829 status), and errors are not ignored for that command (*note Errors in
2830 Commands: Errors.), the remaining command lines to remake the same
2831 target will not be run. If a command fails and the `-k' or
2832 `--keep-going' option was not given (*note Summary of Options: Options
2833 Summary.), `make' aborts execution. If make terminates for any reason
2834 (including a signal) with child processes running, it waits for them to
2835 finish before actually exiting.
2837 When the system is heavily loaded, you will probably want to run
2838 fewer jobs than when it is lightly loaded. You can use the `-l' option
2839 to tell `make' to limit the number of jobs to run at once, based on the
2840 load average. The `-l' or `--max-load' option is followed by a
2841 floating-point number. For example,
2845 will not let `make' start more than one job if the load average is
2846 above 2.5. The `-l' option with no following number removes the load
2847 limit, if one was given with a previous `-l' option.
2849 More precisely, when `make' goes to start up a job, and it already
2850 has at least one job running, it checks the current load average; if it
2851 is not lower than the limit given with `-l', `make' waits until the load
2852 average goes below that limit, or until all the other jobs finish.
2854 By default, there is no load limit.
2857 File: make.info, Node: Errors, Next: Interrupts, Prev: Parallel, Up: Commands
2862 After each shell command returns, `make' looks at its exit status. If
2863 the command completed successfully, the next command line is executed
2864 in a new shell; after the last command line is finished, the rule is
2867 If there is an error (the exit status is nonzero), `make' gives up on
2868 the current rule, and perhaps on all rules.
2870 Sometimes the failure of a certain command does not indicate a
2871 problem. For example, you may use the `mkdir' command to ensure that a
2872 directory exists. If the directory already exists, `mkdir' will report
2873 an error, but you probably want `make' to continue regardless.
2875 To ignore errors in a command line, write a `-' at the beginning of
2876 the line's text (after the initial tab). The `-' is discarded before
2877 the command is passed to the shell for execution.
2884 This causes `rm' to continue even if it is unable to remove a file.
2886 When you run `make' with the `-i' or `--ignore-errors' flag, errors
2887 are ignored in all commands of all rules. A rule in the makefile for
2888 the special target `.IGNORE' has the same effect, if there are no
2889 prerequisites. These ways of ignoring errors are obsolete because `-'
2892 When errors are to be ignored, because of either a `-' or the `-i'
2893 flag, `make' treats an error return just like success, except that it
2894 prints out a message that tells you the status code the command exited
2895 with, and says that the error has been ignored.
2897 When an error happens that `make' has not been told to ignore, it
2898 implies that the current target cannot be correctly remade, and neither
2899 can any other that depends on it either directly or indirectly. No
2900 further commands will be executed for these targets, since their
2901 preconditions have not been achieved.
2903 Normally `make' gives up immediately in this circumstance, returning
2904 a nonzero status. However, if the `-k' or `--keep-going' flag is
2905 specified, `make' continues to consider the other prerequisites of the
2906 pending targets, remaking them if necessary, before it gives up and
2907 returns nonzero status. For example, after an error in compiling one
2908 object file, `make -k' will continue compiling other object files even
2909 though it already knows that linking them will be impossible. *Note
2910 Summary of Options: Options Summary.
2912 The usual behavior assumes that your purpose is to get the specified
2913 targets up to date; once `make' learns that this is impossible, it
2914 might as well report the failure immediately. The `-k' option says
2915 that the real purpose is to test as many of the changes made in the
2916 program as possible, perhaps to find several independent problems so
2917 that you can correct them all before the next attempt to compile. This
2918 is why Emacs' `compile' command passes the `-k' flag by default.
2920 Usually when a command fails, if it has changed the target file at
2921 all, the file is corrupted and cannot be used--or at least it is not
2922 completely updated. Yet the file's time stamp says that it is now up to
2923 date, so the next time `make' runs, it will not try to update that
2924 file. The situation is just the same as when the command is killed by a
2925 signal; *note Interrupts::. So generally the right thing to do is to
2926 delete the target file if the command fails after beginning to change
2927 the file. `make' will do this if `.DELETE_ON_ERROR' appears as a
2928 target. This is almost always what you want `make' to do, but it is
2929 not historical practice; so for compatibility, you must explicitly
2933 File: make.info, Node: Interrupts, Next: Recursion, Prev: Errors, Up: Commands
2935 Interrupting or Killing `make'
2936 ==============================
2938 If `make' gets a fatal signal while a command is executing, it may
2939 delete the target file that the command was supposed to update. This is
2940 done if the target file's last-modification time has changed since
2941 `make' first checked it.
2943 The purpose of deleting the target is to make sure that it is remade
2944 from scratch when `make' is next run. Why is this? Suppose you type
2945 `Ctrl-c' while a compiler is running, and it has begun to write an
2946 object file `foo.o'. The `Ctrl-c' kills the compiler, resulting in an
2947 incomplete file whose last-modification time is newer than the source
2948 file `foo.c'. But `make' also receives the `Ctrl-c' signal and deletes
2949 this incomplete file. If `make' did not do this, the next invocation
2950 of `make' would think that `foo.o' did not require updating--resulting
2951 in a strange error message from the linker when it tries to link an
2952 object file half of which is missing.
2954 You can prevent the deletion of a target file in this way by making
2955 the special target `.PRECIOUS' depend on it. Before remaking a target,
2956 `make' checks to see whether it appears on the prerequisites of
2957 `.PRECIOUS', and thereby decides whether the target should be deleted
2958 if a signal happens. Some reasons why you might do this are that the
2959 target is updated in some atomic fashion, or exists only to record a
2960 modification-time (its contents do not matter), or must exist at all
2961 times to prevent other sorts of trouble.
2964 File: make.info, Node: Recursion, Next: Sequences, Prev: Interrupts, Up: Commands
2966 Recursive Use of `make'
2967 =======================
2969 Recursive use of `make' means using `make' as a command in a makefile.
2970 This technique is useful when you want separate makefiles for various
2971 subsystems that compose a larger system. For example, suppose you have
2972 a subdirectory `subdir' which has its own makefile, and you would like
2973 the containing directory's makefile to run `make' on the subdirectory.
2974 You can do it by writing this:
2977 cd subdir && $(MAKE)
2979 or, equivalently, this (*note Summary of Options: Options Summary.):
2984 You can write recursive `make' commands just by copying this example,
2985 but there are many things to know about how they work and why, and about
2986 how the sub-`make' relates to the top-level `make'. You may also find
2987 it useful to declare targets that invoke recursive `make' commands as
2988 `.PHONY' (for more discussion on when this is useful, see *Note Phony
2991 For your convenience, when GNU `make' starts (after it has processed
2992 any `-C' options) it sets the variable `CURDIR' to the pathname of the
2993 current working directory. This value is never touched by `make'
2994 again: in particular note that if you include files from other
2995 directories the value of `CURDIR' does not change. The value has the
2996 same precedence it would have if it were set in the makefile (by
2997 default, an environment variable `CURDIR' will not override this
2998 value). Note that setting this variable has no impact on the operation
2999 of `make' (it does not cause `make' to change its working directory,
3004 * MAKE Variable:: The special effects of using `$(MAKE)'.
3005 * Variables/Recursion:: How to communicate variables to a sub-`make'.
3006 * Options/Recursion:: How to communicate options to a sub-`make'.
3007 * -w Option:: How the `-w' or `--print-directory' option
3008 helps debug use of recursive `make' commands.
3011 File: make.info, Node: MAKE Variable, Next: Variables/Recursion, Prev: Recursion, Up: Recursion
3013 How the `MAKE' Variable Works
3014 -----------------------------
3016 Recursive `make' commands should always use the variable `MAKE', not
3017 the explicit command name `make', as shown here:
3020 cd subdir && $(MAKE)
3022 The value of this variable is the file name with which `make' was
3023 invoked. If this file name was `/bin/make', then the command executed
3024 is `cd subdir && /bin/make'. If you use a special version of `make' to
3025 run the top-level makefile, the same special version will be executed
3026 for recursive invocations.
3028 As a special feature, using the variable `MAKE' in the commands of a
3029 rule alters the effects of the `-t' (`--touch'), `-n' (`--just-print'),
3030 or `-q' (`--question') option. Using the `MAKE' variable has the same
3031 effect as using a `+' character at the beginning of the command line.
3032 *Note Instead of Executing the Commands: Instead of Execution. This
3033 special feature is only enabled if the `MAKE' variable appears directly
3034 in the command script: it does not apply if the `MAKE' variable is
3035 referenced through expansion of another variable. In the latter case
3036 you must use the `+' token to get these special effects.
3038 Consider the command `make -t' in the above example. (The `-t'
3039 option marks targets as up to date without actually running any
3040 commands; see *Note Instead of Execution::.) Following the usual
3041 definition of `-t', a `make -t' command in the example would create a
3042 file named `subsystem' and do nothing else. What you really want it to
3043 do is run `cd subdir && make -t'; but that would require executing the
3044 command, and `-t' says not to execute commands.
3046 The special feature makes this do what you want: whenever a command
3047 line of a rule contains the variable `MAKE', the flags `-t', `-n' and
3048 `-q' do not apply to that line. Command lines containing `MAKE' are
3049 executed normally despite the presence of a flag that causes most
3050 commands not to be run. The usual `MAKEFLAGS' mechanism passes the
3051 flags to the sub-`make' (*note Communicating Options to a Sub-`make':
3052 Options/Recursion.), so your request to touch the files, or print the
3053 commands, is propagated to the subsystem.
3056 File: make.info, Node: Variables/Recursion, Next: Options/Recursion, Prev: MAKE Variable, Up: Recursion
3058 Communicating Variables to a Sub-`make'
3059 ---------------------------------------
3061 Variable values of the top-level `make' can be passed to the sub-`make'
3062 through the environment by explicit request. These variables are
3063 defined in the sub-`make' as defaults, but do not override what is
3064 specified in the makefile used by the sub-`make' makefile unless you
3065 use the `-e' switch (*note Summary of Options: Options Summary.).
3067 To pass down, or "export", a variable, `make' adds the variable and
3068 its value to the environment for running each command. The sub-`make',
3069 in turn, uses the environment to initialize its table of variable
3070 values. *Note Variables from the Environment: Environment.
3072 Except by explicit request, `make' exports a variable only if it is
3073 either defined in the environment initially or set on the command line,
3074 and if its name consists only of letters, numbers, and underscores.
3075 Some shells cannot cope with environment variable names consisting of
3076 characters other than letters, numbers, and underscores.
3078 The special variables `SHELL' and `MAKEFLAGS' are always exported
3079 (unless you unexport them). `MAKEFILES' is exported if you set it to
3082 `make' automatically passes down variable values that were defined
3083 on the command line, by putting them in the `MAKEFLAGS' variable.
3084 *Note Options/Recursion::.
3086 Variables are _not_ normally passed down if they were created by
3087 default by `make' (*note Variables Used by Implicit Rules: Implicit
3088 Variables.). The sub-`make' will define these for itself.
3090 If you want to export specific variables to a sub-`make', use the
3091 `export' directive, like this:
3095 If you want to _prevent_ a variable from being exported, use the
3096 `unexport' directive, like this:
3098 unexport VARIABLE ...
3100 In both of these forms, the arguments to `export' and `unexport' are
3101 expanded, and so could be variables or functions which expand to a
3102 (list of) variable names to be (un)exported.
3104 As a convenience, you can define a variable and export it at the same
3107 export VARIABLE = value
3109 has the same result as:
3116 export VARIABLE := value
3118 has the same result as:
3125 export VARIABLE += value
3132 *Note Appending More Text to Variables: Appending.
3134 You may notice that the `export' and `unexport' directives work in
3135 `make' in the same way they work in the shell, `sh'.
3137 If you want all variables to be exported by default, you can use
3142 This tells `make' that variables which are not explicitly mentioned in
3143 an `export' or `unexport' directive should be exported. Any variable
3144 given in an `unexport' directive will still _not_ be exported. If you
3145 use `export' by itself to export variables by default, variables whose
3146 names contain characters other than alphanumerics and underscores will
3147 not be exported unless specifically mentioned in an `export' directive.
3149 The behavior elicited by an `export' directive by itself was the
3150 default in older versions of GNU `make'. If your makefiles depend on
3151 this behavior and you want to be compatible with old versions of
3152 `make', you can write a rule for the special target
3153 `.EXPORT_ALL_VARIABLES' instead of using the `export' directive. This
3154 will be ignored by old `make's, while the `export' directive will cause
3157 Likewise, you can use `unexport' by itself to tell `make' _not_ to
3158 export variables by default. Since this is the default behavior, you
3159 would only need to do this if `export' had been used by itself earlier
3160 (in an included makefile, perhaps). You *cannot* use `export' and
3161 `unexport' by themselves to have variables exported for some commands
3162 and not for others. The last `export' or `unexport' directive that
3163 appears by itself determines the behavior for the entire run of `make'.
3165 As a special feature, the variable `MAKELEVEL' is changed when it is
3166 passed down from level to level. This variable's value is a string
3167 which is the depth of the level as a decimal number. The value is `0'
3168 for the top-level `make'; `1' for a sub-`make', `2' for a
3169 sub-sub-`make', and so on. The incrementation happens when `make' sets
3170 up the environment for a command.
3172 The main use of `MAKELEVEL' is to test it in a conditional directive
3173 (*note Conditional Parts of Makefiles: Conditionals.); this way you can
3174 write a makefile that behaves one way if run recursively and another
3175 way if run directly by you.
3177 You can use the variable `MAKEFILES' to cause all sub-`make'
3178 commands to use additional makefiles. The value of `MAKEFILES' is a
3179 whitespace-separated list of file names. This variable, if defined in
3180 the outer-level makefile, is passed down through the environment; then
3181 it serves as a list of extra makefiles for the sub-`make' to read
3182 before the usual or specified ones. *Note The Variable `MAKEFILES':
3186 File: make.info, Node: Options/Recursion, Next: -w Option, Prev: Variables/Recursion, Up: Recursion
3188 Communicating Options to a Sub-`make'
3189 -------------------------------------
3191 Flags such as `-s' and `-k' are passed automatically to the sub-`make'
3192 through the variable `MAKEFLAGS'. This variable is set up
3193 automatically by `make' to contain the flag letters that `make'
3194 received. Thus, if you do `make -ks' then `MAKEFLAGS' gets the value
3197 As a consequence, every sub-`make' gets a value for `MAKEFLAGS' in
3198 its environment. In response, it takes the flags from that value and
3199 processes them as if they had been given as arguments. *Note Summary
3200 of Options: Options Summary.
3202 Likewise variables defined on the command line are passed to the
3203 sub-`make' through `MAKEFLAGS'. Words in the value of `MAKEFLAGS' that
3204 contain `=', `make' treats as variable definitions just as if they
3205 appeared on the command line. *Note Overriding Variables: Overriding.
3207 The options `-C', `-f', `-o', and `-W' are not put into `MAKEFLAGS';
3208 these options are not passed down.
3210 The `-j' option is a special case (*note Parallel Execution:
3211 Parallel.). If you set it to some numeric value `N' and your operating
3212 system supports it (most any UNIX system will; others typically won't),
3213 the parent `make' and all the sub-`make's will communicate to ensure
3214 that there are only `N' jobs running at the same time between them all.
3215 Note that any job that is marked recursive (*note Instead of Executing
3216 the Commands: Instead of Execution.) doesn't count against the total
3217 jobs (otherwise we could get `N' sub-`make's running and have no slots
3218 left over for any real work!)
3220 If your operating system doesn't support the above communication,
3221 then `-j 1' is always put into `MAKEFLAGS' instead of the value you
3222 specified. This is because if the `-j' option were passed down to
3223 sub-`make's, you would get many more jobs running in parallel than you
3224 asked for. If you give `-j' with no numeric argument, meaning to run
3225 as many jobs as possible in parallel, this is passed down, since
3226 multiple infinities are no more than one.
3228 If you do not want to pass the other flags down, you must change the
3229 value of `MAKEFLAGS', like this:
3232 cd subdir && $(MAKE) MAKEFLAGS=
3234 The command line variable definitions really appear in the variable
3235 `MAKEOVERRIDES', and `MAKEFLAGS' contains a reference to this variable.
3236 If you do want to pass flags down normally, but don't want to pass
3237 down the command line variable definitions, you can reset
3238 `MAKEOVERRIDES' to empty, like this:
3242 This is not usually useful to do. However, some systems have a small
3243 fixed limit on the size of the environment, and putting so much
3244 information into the value of `MAKEFLAGS' can exceed it. If you see
3245 the error message `Arg list too long', this may be the problem. (For
3246 strict compliance with POSIX.2, changing `MAKEOVERRIDES' does not
3247 affect `MAKEFLAGS' if the special target `.POSIX' appears in the
3248 makefile. You probably do not care about this.)
3250 A similar variable `MFLAGS' exists also, for historical
3251 compatibility. It has the same value as `MAKEFLAGS' except that it
3252 does not contain the command line variable definitions, and it always
3253 begins with a hyphen unless it is empty (`MAKEFLAGS' begins with a
3254 hyphen only when it begins with an option that has no single-letter
3255 version, such as `--warn-undefined-variables'). `MFLAGS' was
3256 traditionally used explicitly in the recursive `make' command, like
3260 cd subdir && $(MAKE) $(MFLAGS)
3262 but now `MAKEFLAGS' makes this usage redundant. If you want your
3263 makefiles to be compatible with old `make' programs, use this
3264 technique; it will work fine with more modern `make' versions too.
3266 The `MAKEFLAGS' variable can also be useful if you want to have
3267 certain options, such as `-k' (*note Summary of Options: Options
3268 Summary.), set each time you run `make'. You simply put a value for
3269 `MAKEFLAGS' in your environment. You can also set `MAKEFLAGS' in a
3270 makefile, to specify additional flags that should also be in effect for
3271 that makefile. (Note that you cannot use `MFLAGS' this way. That
3272 variable is set only for compatibility; `make' does not interpret a
3273 value you set for it in any way.)
3275 When `make' interprets the value of `MAKEFLAGS' (either from the
3276 environment or from a makefile), it first prepends a hyphen if the value
3277 does not already begin with one. Then it chops the value into words
3278 separated by blanks, and parses these words as if they were options
3279 given on the command line (except that `-C', `-f', `-h', `-o', `-W',
3280 and their long-named versions are ignored; and there is no error for an
3283 If you do put `MAKEFLAGS' in your environment, you should be sure not
3284 to include any options that will drastically affect the actions of
3285 `make' and undermine the purpose of makefiles and of `make' itself.
3286 For instance, the `-t', `-n', and `-q' options, if put in one of these
3287 variables, could have disastrous consequences and would certainly have
3288 at least surprising and probably annoying effects.
3291 File: make.info, Node: -w Option, Prev: Options/Recursion, Up: Recursion
3293 The `--print-directory' Option
3294 ------------------------------
3296 If you use several levels of recursive `make' invocations, the `-w' or
3297 `--print-directory' option can make the output a lot easier to
3298 understand by showing each directory as `make' starts processing it and
3299 as `make' finishes processing it. For example, if `make -w' is run in
3300 the directory `/u/gnu/make', `make' will print a line of the form:
3302 make: Entering directory `/u/gnu/make'.
3304 before doing anything else, and a line of the form:
3306 make: Leaving directory `/u/gnu/make'.
3308 when processing is completed.
3310 Normally, you do not need to specify this option because `make' does
3311 it for you: `-w' is turned on automatically when you use the `-C'
3312 option, and in sub-`make's. `make' will not automatically turn on `-w'
3313 if you also use `-s', which says to be silent, or if you use
3314 `--no-print-directory' to explicitly disable it.
3317 File: make.info, Node: Sequences, Next: Empty Commands, Prev: Recursion, Up: Commands
3319 Defining Canned Command Sequences
3320 =================================
3322 When the same sequence of commands is useful in making various targets,
3323 you can define it as a canned sequence with the `define' directive, and
3324 refer to the canned sequence from the rules for those targets. The
3325 canned sequence is actually a variable, so the name must not conflict
3326 with other variable names.
3328 Here is an example of defining a canned sequence of commands:
3331 yacc $(firstword $^)
3335 Here `run-yacc' is the name of the variable being defined; `endef'
3336 marks the end of the definition; the lines in between are the commands.
3337 The `define' directive does not expand variable references and
3338 function calls in the canned sequence; the `$' characters, parentheses,
3339 variable names, and so on, all become part of the value of the variable
3340 you are defining. *Note Defining Variables Verbatim: Defining, for a
3341 complete explanation of `define'.
3343 The first command in this example runs Yacc on the first
3344 prerequisite of whichever rule uses the canned sequence. The output
3345 file from Yacc is always named `y.tab.c'. The second command moves the
3346 output to the rule's target file name.
3348 To use the canned sequence, substitute the variable into the
3349 commands of a rule. You can substitute it like any other variable
3350 (*note Basics of Variable References: Reference.). Because variables
3351 defined by `define' are recursively expanded variables, all the
3352 variable references you wrote inside the `define' are expanded now.
3358 `foo.y' will be substituted for the variable `$^' when it occurs in
3359 `run-yacc''s value, and `foo.c' for `$@'.
3361 This is a realistic example, but this particular one is not needed in
3362 practice because `make' has an implicit rule to figure out these
3363 commands based on the file names involved (*note Using Implicit Rules:
3366 In command execution, each line of a canned sequence is treated just
3367 as if the line appeared on its own in the rule, preceded by a tab. In
3368 particular, `make' invokes a separate subshell for each line. You can
3369 use the special prefix characters that affect command lines (`@', `-',
3370 and `+') on each line of a canned sequence. *Note Writing the Commands
3371 in Rules: Commands. For example, using this canned sequence:
3374 @echo "frobnicating target $@"
3375 frob-step-1 $< -o $@-step-1
3376 frob-step-2 $@-step-1 -o $@
3379 `make' will not echo the first line, the `echo' command. But it _will_
3380 echo the following two command lines.
3382 On the other hand, prefix characters on the command line that refers
3383 to a canned sequence apply to every line in the sequence. So the rule:
3388 does not echo _any_ commands. (*Note Command Echoing: Echoing, for a
3389 full explanation of `@'.)
3392 File: make.info, Node: Empty Commands, Prev: Sequences, Up: Commands
3394 Using Empty Commands
3395 ====================
3397 It is sometimes useful to define commands which do nothing. This is
3398 done simply by giving a command that consists of nothing but
3399 whitespace. For example:
3403 defines an empty command string for `target'. You could also use a
3404 line beginning with a tab character to define an empty command string,
3405 but this would be confusing because such a line looks empty.
3407 You may be wondering why you would want to define a command string
3408 that does nothing. The only reason this is useful is to prevent a
3409 target from getting implicit commands (from implicit rules or the
3410 `.DEFAULT' special target; *note Implicit Rules:: and *note Defining
3411 Last-Resort Default Rules: Last Resort.).
3413 You may be inclined to define empty command strings for targets that
3414 are not actual files, but only exist so that their prerequisites can be
3415 remade. However, this is not the best way to do that, because the
3416 prerequisites may not be remade properly if the target file actually
3417 does exist. *Note Phony Targets: Phony Targets, for a better way to do
3421 File: make.info, Node: Using Variables, Next: Conditionals, Prev: Commands, Up: Top
3423 How to Use Variables
3424 ********************
3426 A "variable" is a name defined in a makefile to represent a string of
3427 text, called the variable's "value". These values are substituted by
3428 explicit request into targets, prerequisites, commands, and other parts
3429 of the makefile. (In some other versions of `make', variables are
3432 Variables and functions in all parts of a makefile are expanded when
3433 read, except for the shell commands in rules, the right-hand sides of
3434 variable definitions using `=', and the bodies of variable definitions
3435 using the `define' directive.
3437 Variables can represent lists of file names, options to pass to
3438 compilers, programs to run, directories to look in for source files,
3439 directories to write output in, or anything else you can imagine.
3441 A variable name may be any sequence of characters not containing `:',
3442 `#', `=', or leading or trailing whitespace. However, variable names
3443 containing characters other than letters, numbers, and underscores
3444 should be avoided, as they may be given special meanings in the future,
3445 and with some shells they cannot be passed through the environment to a
3446 sub-`make' (*note Communicating Variables to a Sub-`make':
3447 Variables/Recursion.).
3449 Variable names are case-sensitive. The names `foo', `FOO', and
3450 `Foo' all refer to different variables.
3452 It is traditional to use upper case letters in variable names, but we
3453 recommend using lower case letters for variable names that serve
3454 internal purposes in the makefile, and reserving upper case for
3455 parameters that control implicit rules or for parameters that the user
3456 should override with command options (*note Overriding Variables:
3459 A few variables have names that are a single punctuation character or
3460 just a few characters. These are the "automatic variables", and they
3461 have particular specialized uses. *Note Automatic Variables::.
3465 * Reference:: How to use the value of a variable.
3466 * Flavors:: Variables come in two flavors.
3467 * Advanced:: Advanced features for referencing a variable.
3468 * Values:: All the ways variables get their values.
3469 * Setting:: How to set a variable in the makefile.
3470 * Appending:: How to append more text to the old value
3472 * Override Directive:: How to set a variable in the makefile even if
3473 the user has set it with a command argument.
3474 * Defining:: An alternate way to set a variable
3475 to a verbatim string.
3476 * Environment:: Variable values can come from the environment.
3477 * Target-specific:: Variable values can be defined on a per-target
3479 * Pattern-specific:: Target-specific variable values can be applied
3480 to a group of targets that match a pattern.
3483 File: make.info, Node: Reference, Next: Flavors, Prev: Using Variables, Up: Using Variables
3485 Basics of Variable References
3486 =============================
3488 To substitute a variable's value, write a dollar sign followed by the
3489 name of the variable in parentheses or braces: either `$(foo)' or
3490 `${foo}' is a valid reference to the variable `foo'. This special
3491 significance of `$' is why you must write `$$' to have the effect of a
3492 single dollar sign in a file name or command.
3494 Variable references can be used in any context: targets,
3495 prerequisites, commands, most directives, and new variable values.
3496 Here is an example of a common case, where a variable holds the names
3497 of all the object files in a program:
3499 objects = program.o foo.o utils.o
3500 program : $(objects)
3501 cc -o program $(objects)
3505 Variable references work by strict textual substitution. Thus, the
3509 prog.o : prog.$(foo)
3510 $(foo)$(foo) -$(foo) prog.$(foo)
3512 could be used to compile a C program `prog.c'. Since spaces before the
3513 variable value are ignored in variable assignments, the value of `foo'
3514 is precisely `c'. (Don't actually write your makefiles this way!)
3516 A dollar sign followed by a character other than a dollar sign,
3517 open-parenthesis or open-brace treats that single character as the
3518 variable name. Thus, you could reference the variable `x' with `$x'.
3519 However, this practice is strongly discouraged, except in the case of
3520 the automatic variables (*note Automatic Variables::).
3523 File: make.info, Node: Flavors, Next: Advanced, Prev: Reference, Up: Using Variables
3525 The Two Flavors of Variables
3526 ============================
3528 There are two ways that a variable in GNU `make' can have a value; we
3529 call them the two "flavors" of variables. The two flavors are
3530 distinguished in how they are defined and in what they do when expanded.
3532 The first flavor of variable is a "recursively expanded" variable.
3533 Variables of this sort are defined by lines using `=' (*note Setting
3534 Variables: Setting.) or by the `define' directive (*note Defining
3535 Variables Verbatim: Defining.). The value you specify is installed
3536 verbatim; if it contains references to other variables, these
3537 references are expanded whenever this variable is substituted (in the
3538 course of expanding some other string). When this happens, it is
3539 called "recursive expansion".
3549 will echo `Huh?': `$(foo)' expands to `$(bar)' which expands to
3550 `$(ugh)' which finally expands to `Huh?'.
3552 This flavor of variable is the only sort supported by other versions
3553 of `make'. It has its advantages and its disadvantages. An advantage
3554 (most would say) is that:
3556 CFLAGS = $(include_dirs) -O
3557 include_dirs = -Ifoo -Ibar
3559 will do what was intended: when `CFLAGS' is expanded in a command, it
3560 will expand to `-Ifoo -Ibar -O'. A major disadvantage is that you
3561 cannot append something on the end of a variable, as in
3563 CFLAGS = $(CFLAGS) -O
3565 because it will cause an infinite loop in the variable expansion.
3566 (Actually `make' detects the infinite loop and reports an error.)
3568 Another disadvantage is that any functions (*note Functions for
3569 Transforming Text: Functions.) referenced in the definition will be
3570 executed every time the variable is expanded. This makes `make' run
3571 slower; worse, it causes the `wildcard' and `shell' functions to give
3572 unpredictable results because you cannot easily control when they are
3573 called, or even how many times.
3575 To avoid all the problems and inconveniences of recursively expanded
3576 variables, there is another flavor: simply expanded variables.
3578 "Simply expanded variables" are defined by lines using `:=' (*note
3579 Setting Variables: Setting.). The value of a simply expanded variable
3580 is scanned once and for all, expanding any references to other
3581 variables and functions, when the variable is defined. The actual
3582 value of the simply expanded variable is the result of expanding the
3583 text that you write. It does not contain any references to other
3584 variables; it contains their values _as of the time this variable was
3585 defined_. Therefore,
3596 When a simply expanded variable is referenced, its value is
3597 substituted verbatim.
3599 Here is a somewhat more complicated example, illustrating the use of
3600 `:=' in conjunction with the `shell' function. (*Note The `shell'
3601 Function: Shell Function.) This example also shows use of the variable
3602 `MAKELEVEL', which is changed when it is passed down from level to
3603 level. (*Note Communicating Variables to a Sub-`make':
3604 Variables/Recursion, for information about `MAKELEVEL'.)
3606 ifeq (0,${MAKELEVEL})
3607 cur-dir := $(shell pwd)
3608 whoami := $(shell whoami)
3609 host-type := $(shell arch)
3610 MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
3613 An advantage of this use of `:=' is that a typical `descend into a
3614 directory' command then looks like this:
3617 ${MAKE} cur-dir=${cur-dir}/$@ -C $@ all
3619 Simply expanded variables generally make complicated makefile
3620 programming more predictable because they work like variables in most
3621 programming languages. They allow you to redefine a variable using its
3622 own value (or its value processed in some way by one of the expansion
3623 functions) and to use the expansion functions much more efficiently
3624 (*note Functions for Transforming Text: Functions.).
3626 You can also use them to introduce controlled leading whitespace into
3627 variable values. Leading whitespace characters are discarded from your
3628 input before substitution of variable references and function calls;
3629 this means you can include leading spaces in a variable value by
3630 protecting them with variable references, like this:
3633 space := $(nullstring) # end of the line
3635 Here the value of the variable `space' is precisely one space. The
3636 comment `# end of the line' is included here just for clarity. Since
3637 trailing space characters are _not_ stripped from variable values, just
3638 a space at the end of the line would have the same effect (but be
3639 rather hard to read). If you put whitespace at the end of a variable
3640 value, it is a good idea to put a comment like that at the end of the
3641 line to make your intent clear. Conversely, if you do _not_ want any
3642 whitespace characters at the end of your variable value, you must
3643 remember not to put a random comment on the end of the line after some
3644 whitespace, such as this:
3646 dir := /foo/bar # directory to put the frobs in
3648 Here the value of the variable `dir' is `/foo/bar ' (with four
3649 trailing spaces), which was probably not the intention. (Imagine
3650 something like `$(dir)/file' with this definition!)
3652 There is another assignment operator for variables, `?='. This is
3653 called a conditional variable assignment operator, because it only has
3654 an effect if the variable is not yet defined. This statement:
3658 is exactly equivalent to this (*note The `origin' Function: Origin
3661 ifeq ($(origin FOO), undefined)
3665 Note that a variable set to an empty value is still defined, so `?='
3666 will not set that variable.
3669 File: make.info, Node: Advanced, Next: Values, Prev: Flavors, Up: Using Variables
3671 Advanced Features for Reference to Variables
3672 ============================================
3674 This section describes some advanced features you can use to reference
3675 variables in more flexible ways.
3679 * Substitution Refs:: Referencing a variable with
3680 substitutions on the value.
3681 * Computed Names:: Computing the name of the variable to refer to.
3684 File: make.info, Node: Substitution Refs, Next: Computed Names, Prev: Advanced, Up: Advanced
3686 Substitution References
3687 -----------------------
3689 A "substitution reference" substitutes the value of a variable with
3690 alterations that you specify. It has the form `$(VAR:A=B)' (or
3691 `${VAR:A=B}') and its meaning is to take the value of the variable VAR,
3692 replace every A at the end of a word with B in that value, and
3693 substitute the resulting string.
3695 When we say "at the end of a word", we mean that A must appear
3696 either followed by whitespace or at the end of the value in order to be
3697 replaced; other occurrences of A in the value are unaltered. For
3703 sets `bar' to `a.c b.c c.c'. *Note Setting Variables: Setting.
3705 A substitution reference is actually an abbreviation for use of the
3706 `patsubst' expansion function (*note Functions for String Substitution
3707 and Analysis: Text Functions.). We provide substitution references as
3708 well as `patsubst' for compatibility with other implementations of
3711 Another type of substitution reference lets you use the full power of
3712 the `patsubst' function. It has the same form `$(VAR:A=B)' described
3713 above, except that now A must contain a single `%' character. This
3714 case is equivalent to `$(patsubst A,B,$(VAR))'. *Note Functions for
3715 String Substitution and Analysis: Text Functions, for a description of
3716 the `patsubst' function.
3721 bar := $(foo:%.o=%.c)
3723 sets `bar' to `a.c b.c c.c'.
3726 File: make.info, Node: Computed Names, Prev: Substitution Refs, Up: Advanced
3728 Computed Variable Names
3729 -----------------------
3731 Computed variable names are a complicated concept needed only for
3732 sophisticated makefile programming. For most purposes you need not
3733 consider them, except to know that making a variable with a dollar sign
3734 in its name might have strange results. However, if you are the type
3735 that wants to understand everything, or you are actually interested in
3736 what they do, read on.
3738 Variables may be referenced inside the name of a variable. This is
3739 called a "computed variable name" or a "nested variable reference".
3746 defines `a' as `z': the `$(x)' inside `$($(x))' expands to `y', so
3747 `$($(x))' expands to `$(y)' which in turn expands to `z'. Here the
3748 name of the variable to reference is not stated explicitly; it is
3749 computed by expansion of `$(x)'. The reference `$(x)' here is nested
3750 within the outer variable reference.
3752 The previous example shows two levels of nesting, but any number of
3753 levels is possible. For example, here are three levels:
3760 Here the innermost `$(x)' expands to `y', so `$($(x))' expands to
3761 `$(y)' which in turn expands to `z'; now we have `$(z)', which becomes
3764 References to recursively-expanded variables within a variable name
3765 are reexpanded in the usual fashion. For example:
3772 defines `a' as `Hello': `$($(x))' becomes `$($(y))' which becomes
3773 `$(z)' which becomes `Hello'.
3775 Nested variable references can also contain modified references and
3776 function invocations (*note Functions for Transforming Text:
3777 Functions.), just like any other reference. For example, using the
3778 `subst' function (*note Functions for String Substitution and Analysis:
3783 y = $(subst 1,2,$(x))
3787 eventually defines `a' as `Hello'. It is doubtful that anyone would
3788 ever want to write a nested reference as convoluted as this one, but it
3789 works: `$($($(z)))' expands to `$($(y))' which becomes `$($(subst
3790 1,2,$(x)))'. This gets the value `variable1' from `x' and changes it
3791 by substitution to `variable2', so that the entire string becomes
3792 `$(variable2)', a simple variable reference whose value is `Hello'.
3794 A computed variable name need not consist entirely of a single
3795 variable reference. It can contain several variable references, as
3796 well as some invariant text. For example,
3801 a_files := filea fileb
3802 1_files := file1 file2
3804 ifeq "$(use_a)" "yes"
3810 ifeq "$(use_dirs)" "yes"
3816 dirs := $($(a1)_$(df))
3818 will give `dirs' the same value as `a_dirs', `1_dirs', `a_files' or
3819 `1_files' depending on the settings of `use_a' and `use_dirs'.
3821 Computed variable names can also be used in substitution references:
3823 a_objects := a.o b.o c.o
3824 1_objects := 1.o 2.o 3.o
3826 sources := $($(a1)_objects:.o=.c)
3828 defines `sources' as either `a.c b.c c.c' or `1.c 2.c 3.c', depending
3829 on the value of `a1'.
3831 The only restriction on this sort of use of nested variable
3832 references is that they cannot specify part of the name of a function
3833 to be called. This is because the test for a recognized function name
3834 is done before the expansion of nested references. For example,
3844 foo := $($(func) $(bar))
3846 attempts to give `foo' the value of the variable `sort a d b g q c' or
3847 `strip a d b g q c', rather than giving `a d b g q c' as the argument
3848 to either the `sort' or the `strip' function. This restriction could
3849 be removed in the future if that change is shown to be a good idea.
3851 You can also use computed variable names in the left-hand side of a
3852 variable assignment, or in a `define' directive, as in:
3855 $(dir)_sources := $(wildcard $(dir)/*.c)
3857 lpr $($(dir)_sources)
3860 This example defines the variables `dir', `foo_sources', and
3863 Note that "nested variable references" are quite different from
3864 "recursively expanded variables" (*note The Two Flavors of Variables:
3865 Flavors.), though both are used together in complex ways when doing
3866 makefile programming.
3869 File: make.info, Node: Values, Next: Setting, Prev: Advanced, Up: Using Variables
3871 How Variables Get Their Values
3872 ==============================
3874 Variables can get values in several different ways:
3876 * You can specify an overriding value when you run `make'. *Note
3877 Overriding Variables: Overriding.
3879 * You can specify a value in the makefile, either with an assignment
3880 (*note Setting Variables: Setting.) or with a verbatim definition
3881 (*note Defining Variables Verbatim: Defining.).
3883 * Variables in the environment become `make' variables. *Note
3884 Variables from the Environment: Environment.
3886 * Several "automatic" variables are given new values for each rule.
3887 Each of these has a single conventional use. *Note Automatic
3890 * Several variables have constant initial values. *Note Variables
3891 Used by Implicit Rules: Implicit Variables.
3894 File: make.info, Node: Setting, Next: Appending, Prev: Values, Up: Using Variables
3899 To set a variable from the makefile, write a line starting with the
3900 variable name followed by `=' or `:='. Whatever follows the `=' or
3901 `:=' on the line becomes the value. For example,
3903 objects = main.o foo.o bar.o utils.o
3905 defines a variable named `objects'. Whitespace around the variable
3906 name and immediately after the `=' is ignored.
3908 Variables defined with `=' are "recursively expanded" variables.
3909 Variables defined with `:=' are "simply expanded" variables; these
3910 definitions can contain variable references which will be expanded
3911 before the definition is made. *Note The Two Flavors of Variables:
3914 The variable name may contain function and variable references, which
3915 are expanded when the line is read to find the actual variable name to
3918 There is no limit on the length of the value of a variable except the
3919 amount of swapping space on the computer. When a variable definition is
3920 long, it is a good idea to break it into several lines by inserting
3921 backslash-newline at convenient places in the definition. This will not
3922 affect the functioning of `make', but it will make the makefile easier
3925 Most variable names are considered to have the empty string as a
3926 value if you have never set them. Several variables have built-in
3927 initial values that are not empty, but you can set them in the usual
3928 ways (*note Variables Used by Implicit Rules: Implicit Variables.).
3929 Several special variables are set automatically to a new value for each
3930 rule; these are called the "automatic" variables (*note Automatic
3933 If you'd like a variable to be set to a value only if it's not
3934 already set, then you can use the shorthand operator `?=' instead of
3935 `='. These two settings of the variable `FOO' are identical (*note The
3936 `origin' Function: Origin Function.):
3942 ifeq ($(origin FOO), undefined)
3947 File: make.info, Node: Appending, Next: Override Directive, Prev: Setting, Up: Using Variables
3949 Appending More Text to Variables
3950 ================================
3952 Often it is useful to add more text to the value of a variable already
3953 defined. You do this with a line containing `+=', like this:
3955 objects += another.o
3957 This takes the value of the variable `objects', and adds the text
3958 `another.o' to it (preceded by a single space). Thus:
3960 objects = main.o foo.o bar.o utils.o
3961 objects += another.o
3963 sets `objects' to `main.o foo.o bar.o utils.o another.o'.
3965 Using `+=' is similar to:
3967 objects = main.o foo.o bar.o utils.o
3968 objects := $(objects) another.o
3970 but differs in ways that become important when you use more complex
3973 When the variable in question has not been defined before, `+=' acts
3974 just like normal `=': it defines a recursively-expanded variable.
3975 However, when there _is_ a previous definition, exactly what `+=' does
3976 depends on what flavor of variable you defined originally. *Note The
3977 Two Flavors of Variables: Flavors, for an explanation of the two
3978 flavors of variables.
3980 When you add to a variable's value with `+=', `make' acts
3981 essentially as if you had included the extra text in the initial
3982 definition of the variable. If you defined it first with `:=', making
3983 it a simply-expanded variable, `+=' adds to that simply-expanded
3984 definition, and expands the new text before appending it to the old
3985 value just as `:=' does (*note Setting Variables: Setting., for a full
3986 explanation of `:='). In fact,
3991 is exactly equivalent to:
3994 variable := $(variable) more
3996 On the other hand, when you use `+=' with a variable that you defined
3997 first to be recursively-expanded using plain `=', `make' does something
3998 a bit different. Recall that when you define a recursively-expanded
3999 variable, `make' does not expand the value you set for variable and
4000 function references immediately. Instead it stores the text verbatim,
4001 and saves these variable and function references to be expanded later,
4002 when you refer to the new variable (*note The Two Flavors of Variables:
4003 Flavors.). When you use `+=' on a recursively-expanded variable, it is
4004 this unexpanded text to which `make' appends the new text you specify.
4009 is roughly equivalent to:
4012 variable = $(temp) more
4014 except that of course it never defines a variable called `temp'. The
4015 importance of this comes when the variable's old value contains
4016 variable references. Take this common example:
4018 CFLAGS = $(includes) -O
4020 CFLAGS += -pg # enable profiling
4022 The first line defines the `CFLAGS' variable with a reference to another
4023 variable, `includes'. (`CFLAGS' is used by the rules for C
4024 compilation; *note Catalogue of Implicit Rules: Catalogue of Rules..)
4025 Using `=' for the definition makes `CFLAGS' a recursively-expanded
4026 variable, meaning `$(includes) -O' is _not_ expanded when `make'
4027 processes the definition of `CFLAGS'. Thus, `includes' need not be
4028 defined yet for its value to take effect. It only has to be defined
4029 before any reference to `CFLAGS'. If we tried to append to the value
4030 of `CFLAGS' without using `+=', we might do it like this:
4032 CFLAGS := $(CFLAGS) -pg # enable profiling
4034 This is pretty close, but not quite what we want. Using `:=' redefines
4035 `CFLAGS' as a simply-expanded variable; this means `make' expands the
4036 text `$(CFLAGS) -pg' before setting the variable. If `includes' is not
4037 yet defined, we get ` -O -pg', and a later definition of `includes'
4038 will have no effect. Conversely, by using `+=' we set `CFLAGS' to the
4039 _unexpanded_ value `$(includes) -O -pg'. Thus we preserve the
4040 reference to `includes', so if that variable gets defined at any later
4041 point, a reference like `$(CFLAGS)' still uses its value.
4044 File: make.info, Node: Override Directive, Next: Defining, Prev: Appending, Up: Using Variables
4046 The `override' Directive
4047 ========================
4049 If a variable has been set with a command argument (*note Overriding
4050 Variables: Overriding.), then ordinary assignments in the makefile are
4051 ignored. If you want to set the variable in the makefile even though
4052 it was set with a command argument, you can use an `override'
4053 directive, which is a line that looks like this:
4055 override VARIABLE = VALUE
4059 override VARIABLE := VALUE
4061 To append more text to a variable defined on the command line, use:
4063 override VARIABLE += MORE TEXT
4065 *Note Appending More Text to Variables: Appending.
4067 The `override' directive was not invented for escalation in the war
4068 between makefiles and command arguments. It was invented so you can
4069 alter and add to values that the user specifies with command arguments.
4071 For example, suppose you always want the `-g' switch when you run the
4072 C compiler, but you would like to allow the user to specify the other
4073 switches with a command argument just as usual. You could use this
4074 `override' directive:
4076 override CFLAGS += -g
4078 You can also use `override' directives with `define' directives.
4079 This is done as you might expect:
4085 *Note Defining Variables Verbatim: Defining.
4088 File: make.info, Node: Defining, Next: Environment, Prev: Override Directive, Up: Using Variables
4090 Defining Variables Verbatim
4091 ===========================
4093 Another way to set the value of a variable is to use the `define'
4094 directive. This directive has an unusual syntax which allows newline
4095 characters to be included in the value, which is convenient for defining
4096 both canned sequences of commands (*note Defining Canned Command
4097 Sequences: Sequences.), and also sections of makefile syntax to use
4098 with `eval' (*note Eval Function::).
4100 The `define' directive is followed on the same line by the name of
4101 the variable and nothing more. The value to give the variable appears
4102 on the following lines. The end of the value is marked by a line
4103 containing just the word `endef'. Aside from this difference in
4104 syntax, `define' works just like `=': it creates a recursively-expanded
4105 variable (*note The Two Flavors of Variables: Flavors.). The variable
4106 name may contain function and variable references, which are expanded
4107 when the directive is read to find the actual variable name to use.
4109 You may nest `define' directives: `make' will keep track of nested
4110 directives and report an error if they are not all properly closed with
4111 `endef'. Note that lines beginning with tab characters are considered
4112 part of a command script, so any `define' or `endef' strings appearing
4113 on such a line will not be considered `make' operators.
4120 The value in an ordinary assignment cannot contain a newline; but the
4121 newlines that separate the lines of the value in a `define' become part
4122 of the variable's value (except for the final newline which precedes
4123 the `endef' and is not considered part of the value).
4125 When used in a command script, the previous example is functionally
4128 two-lines = echo foo; echo $(bar)
4130 since two commands separated by semicolon behave much like two separate
4131 shell commands. However, note that using two separate lines means
4132 `make' will invoke the shell twice, running an independent subshell for
4133 each line. *Note Command Execution: Execution.
4135 If you want variable definitions made with `define' to take
4136 precedence over command-line variable definitions, you can use the
4137 `override' directive together with `define':
4139 override define two-lines
4144 *Note The `override' Directive: Override Directive.
4147 File: make.info, Node: Environment, Next: Target-specific, Prev: Defining, Up: Using Variables
4149 Variables from the Environment
4150 ==============================
4152 Variables in `make' can come from the environment in which `make' is
4153 run. Every environment variable that `make' sees when it starts up is
4154 transformed into a `make' variable with the same name and value. But
4155 an explicit assignment in the makefile, or with a command argument,
4156 overrides the environment. (If the `-e' flag is specified, then values
4157 from the environment override assignments in the makefile. *Note
4158 Summary of Options: Options Summary. But this is not recommended
4161 Thus, by setting the variable `CFLAGS' in your environment, you can
4162 cause all C compilations in most makefiles to use the compiler switches
4163 you prefer. This is safe for variables with standard or conventional
4164 meanings because you know that no makefile will use them for other
4165 things. (But this is not totally reliable; some makefiles set `CFLAGS'
4166 explicitly and therefore are not affected by the value in the
4169 When `make' is invoked recursively, variables defined in the outer
4170 invocation can be passed to inner invocations through the environment
4171 (*note Recursive Use of `make': Recursion.). By default, only
4172 variables that came from the environment or the command line are passed
4173 to recursive invocations. You can use the `export' directive to pass
4174 other variables. *Note Communicating Variables to a Sub-`make':
4175 Variables/Recursion, for full details.
4177 Other use of variables from the environment is not recommended. It
4178 is not wise for makefiles to depend for their functioning on
4179 environment variables set up outside their control, since this would
4180 cause different users to get different results from the same makefile.
4181 This is against the whole purpose of most makefiles.
4183 Such problems would be especially likely with the variable `SHELL',
4184 which is normally present in the environment to specify the user's
4185 choice of interactive shell. It would be very undesirable for this
4186 choice to affect `make'. So `make' ignores the environment value of
4187 `SHELL' (except on MS-DOS and MS-Windows, where `SHELL' is usually not
4188 set. *Note Special handling of SHELL on MS-DOS: Execution.)
4191 File: make.info, Node: Target-specific, Next: Pattern-specific, Prev: Environment, Up: Using Variables
4193 Target-specific Variable Values
4194 ===============================
4196 Variable values in `make' are usually global; that is, they are the
4197 same regardless of where they are evaluated (unless they're reset, of
4198 course). One exception to that is automatic variables (*note Automatic
4201 The other exception is "target-specific variable values". This
4202 feature allows you to define different values for the same variable,
4203 based on the target that `make' is currently building. As with
4204 automatic variables, these values are only available within the context
4205 of a target's command script (and in other target-specific assignments).
4207 Set a target-specific variable value like this:
4209 TARGET ... : VARIABLE-ASSIGNMENT
4213 TARGET ... : override VARIABLE-ASSIGNMENT
4217 TARGET ... : export VARIABLE-ASSIGNMENT
4219 Multiple TARGET values create a target-specific variable value for
4220 each member of the target list individually.
4222 The VARIABLE-ASSIGNMENT can be any valid form of assignment;
4223 recursive (`='), static (`:='), appending (`+='), or conditional
4224 (`?='). All variables that appear within the VARIABLE-ASSIGNMENT are
4225 evaluated within the context of the target: thus, any
4226 previously-defined target-specific variable values will be in effect.
4227 Note that this variable is actually distinct from any "global" value:
4228 the two variables do not have to have the same flavor (recursive vs.
4231 Target-specific variables have the same priority as any other
4232 makefile variable. Variables provided on the command-line (and in the
4233 environment if the `-e' option is in force) will take precedence.
4234 Specifying the `override' directive will allow the target-specific
4235 variable value to be preferred.
4237 There is one more special feature of target-specific variables: when
4238 you define a target-specific variable that variable value is also in
4239 effect for all prerequisites of this target, and all their
4240 prerequisites, etc. (unless those prerequisites override that variable
4241 with their own target-specific variable value). So, for example, a
4242 statement like this:
4245 prog : prog.o foo.o bar.o
4247 will set `CFLAGS' to `-g' in the command script for `prog', but it will
4248 also set `CFLAGS' to `-g' in the command scripts that create `prog.o',
4249 `foo.o', and `bar.o', and any command scripts which create their
4252 Be aware that a given prerequisite will only be built once per
4253 invocation of make, at most. If the same file is a prerequisite of
4254 multiple targets, and each of those targets has a different value for
4255 the same target-specific variable, then the first target to be built
4256 will cause that prerequisite to be built and the prerequisite will
4257 inherit the target-specific value from the first target. It will
4258 ignore the target-specific values from any other targets.
4261 File: make.info, Node: Pattern-specific, Prev: Target-specific, Up: Using Variables
4263 Pattern-specific Variable Values
4264 ================================
4266 In addition to target-specific variable values (*note Target-specific
4267 Variable Values: Target-specific.), GNU `make' supports
4268 pattern-specific variable values. In this form, the variable is
4269 defined for any target that matches the pattern specified. If a target
4270 matches more than one pattern, all the matching pattern-specific
4271 variables are interpreted in the order in which they were defined in
4272 the makefile, and collected together into one set. Variables defined
4273 in this way are searched after any target-specific variables defined
4274 explicitly for that target, and before target-specific variables
4275 defined for the parent target.
4277 Set a pattern-specific variable value like this:
4279 PATTERN ... : VARIABLE-ASSIGNMENT
4283 PATTERN ... : override VARIABLE-ASSIGNMENT
4285 where PATTERN is a %-pattern. As with target-specific variable values,
4286 multiple PATTERN values create a pattern-specific variable value for
4287 each pattern individually. The VARIABLE-ASSIGNMENT can be any valid
4288 form of assignment. Any command-line variable setting will take
4289 precedence, unless `override' is specified.
4295 will assign `CFLAGS' the value of `-O' for all targets matching the
4299 File: make.info, Node: Conditionals, Next: Functions, Prev: Using Variables, Up: Top
4301 Conditional Parts of Makefiles
4302 ******************************
4304 A "conditional" causes part of a makefile to be obeyed or ignored
4305 depending on the values of variables. Conditionals can compare the
4306 value of one variable to another, or the value of a variable to a
4307 constant string. Conditionals control what `make' actually "sees" in
4308 the makefile, so they _cannot_ be used to control shell commands at the
4313 * Conditional Example:: Example of a conditional
4314 * Conditional Syntax:: The syntax of conditionals.
4315 * Testing Flags:: Conditionals that test flags.
4318 File: make.info, Node: Conditional Example, Next: Conditional Syntax, Prev: Conditionals, Up: Conditionals
4320 Example of a Conditional
4321 ========================
4323 The following example of a conditional tells `make' to use one set of
4324 libraries if the `CC' variable is `gcc', and a different set of
4325 libraries otherwise. It works by controlling which of two command
4326 lines will be used as the command for a rule. The result is that
4327 `CC=gcc' as an argument to `make' changes not only which compiler is
4328 used but also which libraries are linked.
4330 libs_for_gcc = -lgnu
4335 $(CC) -o foo $(objects) $(libs_for_gcc)
4337 $(CC) -o foo $(objects) $(normal_libs)
4340 This conditional uses three directives: one `ifeq', one `else' and
4343 The `ifeq' directive begins the conditional, and specifies the
4344 condition. It contains two arguments, separated by a comma and
4345 surrounded by parentheses. Variable substitution is performed on both
4346 arguments and then they are compared. The lines of the makefile
4347 following the `ifeq' are obeyed if the two arguments match; otherwise
4350 The `else' directive causes the following lines to be obeyed if the
4351 previous conditional failed. In the example above, this means that the
4352 second alternative linking command is used whenever the first
4353 alternative is not used. It is optional to have an `else' in a
4356 The `endif' directive ends the conditional. Every conditional must
4357 end with an `endif'. Unconditional makefile text follows.
4359 As this example illustrates, conditionals work at the textual level:
4360 the lines of the conditional are treated as part of the makefile, or
4361 ignored, according to the condition. This is why the larger syntactic
4362 units of the makefile, such as rules, may cross the beginning or the
4363 end of the conditional.
4365 When the variable `CC' has the value `gcc', the above example has
4369 $(CC) -o foo $(objects) $(libs_for_gcc)
4371 When the variable `CC' has any other value, the effect is this:
4374 $(CC) -o foo $(objects) $(normal_libs)
4376 Equivalent results can be obtained in another way by
4377 conditionalizing a variable assignment and then using the variable
4380 libs_for_gcc = -lgnu
4384 libs=$(libs_for_gcc)
4390 $(CC) -o foo $(objects) $(libs)
4393 File: make.info, Node: Conditional Syntax, Next: Testing Flags, Prev: Conditional Example, Up: Conditionals
4395 Syntax of Conditionals
4396 ======================
4398 The syntax of a simple conditional with no `else' is as follows:
4400 CONDITIONAL-DIRECTIVE
4404 The TEXT-IF-TRUE may be any lines of text, to be considered as part of
4405 the makefile if the condition is true. If the condition is false, no
4406 text is used instead.
4408 The syntax of a complex conditional is as follows:
4410 CONDITIONAL-DIRECTIVE
4416 If the condition is true, TEXT-IF-TRUE is used; otherwise,
4417 TEXT-IF-FALSE is used instead. The TEXT-IF-FALSE can be any number of
4420 The syntax of the CONDITIONAL-DIRECTIVE is the same whether the
4421 conditional is simple or complex. There are four different directives
4422 that test different conditions. Here is a table of them:
4425 `ifeq 'ARG1' 'ARG2''
4426 `ifeq "ARG1" "ARG2"'
4427 `ifeq "ARG1" 'ARG2''
4428 `ifeq 'ARG1' "ARG2"'
4429 Expand all variable references in ARG1 and ARG2 and compare them.
4430 If they are identical, the TEXT-IF-TRUE is effective; otherwise,
4431 the TEXT-IF-FALSE, if any, is effective.
4433 Often you want to test if a variable has a non-empty value. When
4434 the value results from complex expansions of variables and
4435 functions, expansions you would consider empty may actually
4436 contain whitespace characters and thus are not seen as empty.
4437 However, you can use the `strip' function (*note Text Functions::)
4438 to avoid interpreting whitespace as a non-empty value. For
4441 ifeq ($(strip $(foo)),)
4445 will evaluate TEXT-IF-EMPTY even if the expansion of `$(foo)'
4446 contains whitespace characters.
4448 `ifneq (ARG1, ARG2)'
4449 `ifneq 'ARG1' 'ARG2''
4450 `ifneq "ARG1" "ARG2"'
4451 `ifneq "ARG1" 'ARG2''
4452 `ifneq 'ARG1' "ARG2"'
4453 Expand all variable references in ARG1 and ARG2 and compare them.
4454 If they are different, the TEXT-IF-TRUE is effective; otherwise,
4455 the TEXT-IF-FALSE, if any, is effective.
4457 `ifdef VARIABLE-NAME'
4458 If the variable VARIABLE-NAME has a non-empty value, the
4459 TEXT-IF-TRUE is effective; otherwise, the TEXT-IF-FALSE, if any,
4460 is effective. Variables that have never been defined have an
4461 empty value. The variable VARIABLE-NAME is itself expanded, so it
4462 could be a variable or function that expands to the name of a
4465 Note that `ifdef' only tests whether a variable has a value. It
4466 does not expand the variable to see if that value is nonempty.
4467 Consequently, tests using `ifdef' return true for all definitions
4468 except those like `foo ='. To test for an empty value, use
4469 `ifeq ($(foo),)'. For example,
4479 sets `frobozz' to `yes', while:
4488 sets `frobozz' to `no'.
4490 `ifndef VARIABLE-NAME'
4491 If the variable VARIABLE-NAME has an empty value, the TEXT-IF-TRUE
4492 is effective; otherwise, the TEXT-IF-FALSE, if any, is effective.
4494 Extra spaces are allowed and ignored at the beginning of the
4495 conditional directive line, but a tab is not allowed. (If the line
4496 begins with a tab, it will be considered a command for a rule.) Aside
4497 from this, extra spaces or tabs may be inserted with no effect anywhere
4498 except within the directive name or within an argument. A comment
4499 starting with `#' may appear at the end of the line.
4501 The other two directives that play a part in a conditional are `else'
4502 and `endif'. Each of these directives is written as one word, with no
4503 arguments. Extra spaces are allowed and ignored at the beginning of the
4504 line, and spaces or tabs at the end. A comment starting with `#' may
4505 appear at the end of the line.
4507 Conditionals affect which lines of the makefile `make' uses. If the
4508 condition is true, `make' reads the lines of the TEXT-IF-TRUE as part
4509 of the makefile; if the condition is false, `make' ignores those lines
4510 completely. It follows that syntactic units of the makefile, such as
4511 rules, may safely be split across the beginning or the end of the
4514 `make' evaluates conditionals when it reads a makefile.
4515 Consequently, you cannot use automatic variables in the tests of
4516 conditionals because they are not defined until commands are run (*note
4517 Automatic Variables::).
4519 To prevent intolerable confusion, it is not permitted to start a
4520 conditional in one makefile and end it in another. However, you may
4521 write an `include' directive within a conditional, provided you do not
4522 attempt to terminate the conditional inside the included file.
4525 File: make.info, Node: Testing Flags, Prev: Conditional Syntax, Up: Conditionals
4527 Conditionals that Test Flags
4528 ============================
4530 You can write a conditional that tests `make' command flags such as
4531 `-t' by using the variable `MAKEFLAGS' together with the `findstring'
4532 function (*note Functions for String Substitution and Analysis: Text
4533 Functions.). This is useful when `touch' is not enough to make a file
4536 The `findstring' function determines whether one string appears as a
4537 substring of another. If you want to test for the `-t' flag, use `t'
4538 as the first string and the value of `MAKEFLAGS' as the other.
4540 For example, here is how to arrange to use `ranlib -t' to finish
4541 marking an archive file up to date:
4544 ifneq (,$(findstring t,$(MAKEFLAGS)))
4546 +ranlib -t archive.a
4551 The `+' prefix marks those command lines as "recursive" so that they
4552 will be executed despite use of the `-t' flag. *Note Recursive Use of
4556 File: make.info, Node: Functions, Next: Running, Prev: Conditionals, Up: Top
4558 Functions for Transforming Text
4559 *******************************
4561 "Functions" allow you to do text processing in the makefile to compute
4562 the files to operate on or the commands to use. You use a function in a
4563 "function call", where you give the name of the function and some text
4564 (the "arguments") for the function to operate on. The result of the
4565 function's processing is substituted into the makefile at the point of
4566 the call, just as a variable might be substituted.
4570 * Syntax of Functions:: How to write a function call.
4571 * Text Functions:: General-purpose text manipulation functions.
4572 * File Name Functions:: Functions for manipulating file names.
4573 * Foreach Function:: Repeat some text with controlled variation.
4574 * If Function:: Conditionally expand a value.
4575 * Call Function:: Expand a user-defined function.
4576 * Value Function:: Return the un-expanded value of a variable.
4577 * Eval Function:: Evaluate the arguments as makefile syntax.
4578 * Origin Function:: Find where a variable got its value.
4579 * Shell Function:: Substitute the output of a shell command.
4580 * Make Control Functions:: Functions that control how make runs.
4583 File: make.info, Node: Syntax of Functions, Next: Text Functions, Prev: Functions, Up: Functions
4585 Function Call Syntax
4586 ====================
4588 A function call resembles a variable reference. It looks like this:
4590 $(FUNCTION ARGUMENTS)
4594 ${FUNCTION ARGUMENTS}
4596 Here FUNCTION is a function name; one of a short list of names that
4597 are part of `make'. You can also essentially create your own functions
4598 by using the `call' builtin function.
4600 The ARGUMENTS are the arguments of the function. They are separated
4601 from the function name by one or more spaces or tabs, and if there is
4602 more than one argument, then they are separated by commas. Such
4603 whitespace and commas are not part of an argument's value. The
4604 delimiters which you use to surround the function call, whether
4605 parentheses or braces, can appear in an argument only in matching pairs;
4606 the other kind of delimiters may appear singly. If the arguments
4607 themselves contain other function calls or variable references, it is
4608 wisest to use the same kind of delimiters for all the references; write
4609 `$(subst a,b,$(x))', not `$(subst a,b,${x})'. This is because it is
4610 clearer, and because only one type of delimiter is matched to find the
4611 end of the reference.
4613 The text written for each argument is processed by substitution of
4614 variables and function calls to produce the argument value, which is
4615 the text on which the function acts. The substitution is done in the
4616 order in which the arguments appear.
4618 Commas and unmatched parentheses or braces cannot appear in the text
4619 of an argument as written; leading spaces cannot appear in the text of
4620 the first argument as written. These characters can be put into the
4621 argument value by variable substitution. First define variables
4622 `comma' and `space' whose values are isolated comma and space
4623 characters, then substitute these variables where such characters are
4628 space:= $(empty) $(empty)
4630 bar:= $(subst $(space),$(comma),$(foo))
4631 # bar is now `a,b,c'.
4633 Here the `subst' function replaces each space with a comma, through the
4634 value of `foo', and substitutes the result.
4637 File: make.info, Node: Text Functions, Next: File Name Functions, Prev: Syntax of Functions, Up: Functions
4639 Functions for String Substitution and Analysis
4640 ==============================================
4642 Here are some functions that operate on strings:
4644 `$(subst FROM,TO,TEXT)'
4645 Performs a textual replacement on the text TEXT: each occurrence
4646 of FROM is replaced by TO. The result is substituted for the
4647 function call. For example,
4649 $(subst ee,EE,feet on the street)
4651 substitutes the string `fEEt on the strEEt'.
4653 `$(patsubst PATTERN,REPLACEMENT,TEXT)'
4654 Finds whitespace-separated words in TEXT that match PATTERN and
4655 replaces them with REPLACEMENT. Here PATTERN may contain a `%'
4656 which acts as a wildcard, matching any number of any characters
4657 within a word. If REPLACEMENT also contains a `%', the `%' is
4658 replaced by the text that matched the `%' in PATTERN. Only the
4659 first `%' in the PATTERN and REPLACEMENT is treated this way; any
4660 subsequent `%' is unchanged.
4662 `%' characters in `patsubst' function invocations can be quoted
4663 with preceding backslashes (`\'). Backslashes that would
4664 otherwise quote `%' characters can be quoted with more backslashes.
4665 Backslashes that quote `%' characters or other backslashes are
4666 removed from the pattern before it is compared file names or has a
4667 stem substituted into it. Backslashes that are not in danger of
4668 quoting `%' characters go unmolested. For example, the pattern
4669 `the\%weird\\%pattern\\' has `the%weird\' preceding the operative
4670 `%' character, and `pattern\\' following it. The final two
4671 backslashes are left alone because they cannot affect any `%'
4674 Whitespace between words is folded into single space characters;
4675 leading and trailing whitespace is discarded.
4679 $(patsubst %.c,%.o,x.c.c bar.c)
4681 produces the value `x.c.o bar.o'.
4683 Substitution references (*note Substitution References:
4684 Substitution Refs.) are a simpler way to get the effect of the
4685 `patsubst' function:
4687 $(VAR:PATTERN=REPLACEMENT)
4691 $(patsubst PATTERN,REPLACEMENT,$(VAR))
4693 The second shorthand simplifies one of the most common uses of
4694 `patsubst': replacing the suffix at the end of file names.
4696 $(VAR:SUFFIX=REPLACEMENT)
4700 $(patsubst %SUFFIX,%REPLACEMENT,$(VAR))
4702 For example, you might have a list of object files:
4704 objects = foo.o bar.o baz.o
4706 To get the list of corresponding source files, you could simply
4711 instead of using the general form:
4713 $(patsubst %.o,%.c,$(objects))
4716 Removes leading and trailing whitespace from STRING and replaces
4717 each internal sequence of one or more whitespace characters with a
4718 single space. Thus, `$(strip a b c )' results in `a b c'.
4720 The function `strip' can be very useful when used in conjunction
4721 with conditionals. When comparing something with the empty string
4722 `' using `ifeq' or `ifneq', you usually want a string of just
4723 whitespace to match the empty string (*note Conditionals::).
4725 Thus, the following may fail to have the desired results:
4728 ifneq "$(needs_made)" ""
4731 all:;@echo 'Nothing to make!'
4734 Replacing the variable reference `$(needs_made)' with the function
4735 call `$(strip $(needs_made))' in the `ifneq' directive would make
4738 `$(findstring FIND,IN)'
4739 Searches IN for an occurrence of FIND. If it occurs, the value is
4740 FIND; otherwise, the value is empty. You can use this function in
4741 a conditional to test for the presence of a specific substring in
4742 a given string. Thus, the two examples,
4744 $(findstring a,a b c)
4747 produce the values `a' and `' (the empty string), respectively.
4748 *Note Testing Flags::, for a practical application of `findstring'.
4750 `$(filter PATTERN...,TEXT)'
4751 Returns all whitespace-separated words in TEXT that _do_ match any
4752 of the PATTERN words, removing any words that _do not_ match. The
4753 patterns are written using `%', just like the patterns used in the
4754 `patsubst' function above.
4756 The `filter' function can be used to separate out different types
4757 of strings (such as file names) in a variable. For example:
4759 sources := foo.c bar.c baz.s ugh.h
4761 cc $(filter %.c %.s,$(sources)) -o foo
4763 says that `foo' depends of `foo.c', `bar.c', `baz.s' and `ugh.h'
4764 but only `foo.c', `bar.c' and `baz.s' should be specified in the
4765 command to the compiler.
4767 `$(filter-out PATTERN...,TEXT)'
4768 Returns all whitespace-separated words in TEXT that _do not_ match
4769 any of the PATTERN words, removing the words that _do_ match one
4770 or more. This is the exact opposite of the `filter' function.
4774 objects=main1.o foo.o main2.o bar.o
4775 mains=main1.o main2.o
4777 the following generates a list which contains all the object files
4780 $(filter-out $(mains),$(objects))
4783 Sorts the words of LIST in lexical order, removing duplicate
4784 words. The output is a list of words separated by single spaces.
4787 $(sort foo bar lose)
4789 returns the value `bar foo lose'.
4791 Incidentally, since `sort' removes duplicate words, you can use it
4792 for this purpose even if you don't care about the sort order.
4795 Returns the Nth word of TEXT. The legitimate values of N start
4796 from 1. If N is bigger than the number of words in TEXT, the
4797 value is empty. For example,
4799 $(word 2, foo bar baz)
4803 `$(wordlist S,E,TEXT)'
4804 Returns the list of words in TEXT starting with word S and ending
4805 with word E (inclusive). The legitimate values of S and E start
4806 from 1. If S is bigger than the number of words in TEXT, the
4807 value is empty. If E is bigger than the number of words in TEXT,
4808 words up to the end of TEXT are returned. If S is greater than E,
4809 nothing is returned. For example,
4811 $(wordlist 2, 3, foo bar baz)
4816 Returns the number of words in TEXT. Thus, the last word of TEXT
4817 is `$(word $(words TEXT),TEXT)'.
4819 `$(firstword NAMES...)'
4820 The argument NAMES is regarded as a series of names, separated by
4821 whitespace. The value is the first name in the series. The rest
4822 of the names are ignored.
4826 $(firstword foo bar)
4828 produces the result `foo'. Although `$(firstword TEXT)' is the
4829 same as `$(word 1,TEXT)', the `firstword' function is retained for
4832 Here is a realistic example of the use of `subst' and `patsubst'.
4833 Suppose that a makefile uses the `VPATH' variable to specify a list of
4834 directories that `make' should search for prerequisite files (*note
4835 `VPATH' Search Path for All Prerequisites: General Search.). This
4836 example shows how to tell the C compiler to search for header files in
4837 the same list of directories.
4839 The value of `VPATH' is a list of directories separated by colons,
4840 such as `src:../headers'. First, the `subst' function is used to
4841 change the colons to spaces:
4843 $(subst :, ,$(VPATH))
4845 This produces `src ../headers'. Then `patsubst' is used to turn each
4846 directory name into a `-I' flag. These can be added to the value of
4847 the variable `CFLAGS', which is passed automatically to the C compiler,
4850 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
4852 The effect is to append the text `-Isrc -I../headers' to the previously
4853 given value of `CFLAGS'. The `override' directive is used so that the
4854 new value is assigned even if the previous value of `CFLAGS' was
4855 specified with a command argument (*note The `override' Directive:
4856 Override Directive.).
4859 File: make.info, Node: File Name Functions, Next: Foreach Function, Prev: Text Functions, Up: Functions
4861 Functions for File Names
4862 ========================
4864 Several of the built-in expansion functions relate specifically to
4865 taking apart file names or lists of file names.
4867 Each of the following functions performs a specific transformation
4868 on a file name. The argument of the function is regarded as a series
4869 of file names, separated by whitespace. (Leading and trailing
4870 whitespace is ignored.) Each file name in the series is transformed in
4871 the same way and the results are concatenated with single spaces
4875 Extracts the directory-part of each file name in NAMES. The
4876 directory-part of the file name is everything up through (and
4877 including) the last slash in it. If the file name contains no
4878 slash, the directory part is the string `./'. For example,
4880 $(dir src/foo.c hacks)
4882 produces the result `src/ ./'.
4884 `$(notdir NAMES...)'
4885 Extracts all but the directory-part of each file name in NAMES.
4886 If the file name contains no slash, it is left unchanged.
4887 Otherwise, everything through the last slash is removed from it.
4889 A file name that ends with a slash becomes an empty string. This
4890 is unfortunate, because it means that the result does not always
4891 have the same number of whitespace-separated file names as the
4892 argument had; but we do not see any other valid alternative.
4896 $(notdir src/foo.c hacks)
4898 produces the result `foo.c hacks'.
4900 `$(suffix NAMES...)'
4901 Extracts the suffix of each file name in NAMES. If the file name
4902 contains a period, the suffix is everything starting with the last
4903 period. Otherwise, the suffix is the empty string. This
4904 frequently means that the result will be empty when NAMES is not,
4905 and if NAMES contains multiple file names, the result may contain
4910 $(suffix src/foo.c src-1.0/bar.c hacks)
4912 produces the result `.c .c'.
4914 `$(basename NAMES...)'
4915 Extracts all but the suffix of each file name in NAMES. If the
4916 file name contains a period, the basename is everything starting
4917 up to (and not including) the last period. Periods in the
4918 directory part are ignored. If there is no period, the basename
4919 is the entire file name. For example,
4921 $(basename src/foo.c src-1.0/bar hacks)
4923 produces the result `src/foo src-1.0/bar hacks'.
4925 `$(addsuffix SUFFIX,NAMES...)'
4926 The argument NAMES is regarded as a series of names, separated by
4927 whitespace; SUFFIX is used as a unit. The value of SUFFIX is
4928 appended to the end of each individual name and the resulting
4929 larger names are concatenated with single spaces between them.
4932 $(addsuffix .c,foo bar)
4934 produces the result `foo.c bar.c'.
4936 `$(addprefix PREFIX,NAMES...)'
4937 The argument NAMES is regarded as a series of names, separated by
4938 whitespace; PREFIX is used as a unit. The value of PREFIX is
4939 prepended to the front of each individual name and the resulting
4940 larger names are concatenated with single spaces between them.
4943 $(addprefix src/,foo bar)
4945 produces the result `src/foo src/bar'.
4947 `$(join LIST1,LIST2)'
4948 Concatenates the two arguments word by word: the two first words
4949 (one from each argument) concatenated form the first word of the
4950 result, the two second words form the second word of the result,
4951 and so on. So the Nth word of the result comes from the Nth word
4952 of each argument. If one argument has more words that the other,
4953 the extra words are copied unchanged into the result.
4955 For example, `$(join a b,.c .o)' produces `a.c b.o'.
4957 Whitespace between the words in the lists is not preserved; it is
4958 replaced with a single space.
4960 This function can merge the results of the `dir' and `notdir'
4961 functions, to produce the original list of files which was given
4962 to those two functions.
4964 `$(wildcard PATTERN)'
4965 The argument PATTERN is a file name pattern, typically containing
4966 wildcard characters (as in shell file name patterns). The result
4967 of `wildcard' is a space-separated list of the names of existing
4968 files that match the pattern. *Note Using Wildcard Characters in
4969 File Names: Wildcards.
4972 File: make.info, Node: Foreach Function, Next: If Function, Prev: File Name Functions, Up: Functions
4974 The `foreach' Function
4975 ======================
4977 The `foreach' function is very different from other functions. It
4978 causes one piece of text to be used repeatedly, each time with a
4979 different substitution performed on it. It resembles the `for' command
4980 in the shell `sh' and the `foreach' command in the C-shell `csh'.
4982 The syntax of the `foreach' function is:
4984 $(foreach VAR,LIST,TEXT)
4986 The first two arguments, VAR and LIST, are expanded before anything
4987 else is done; note that the last argument, TEXT, is *not* expanded at
4988 the same time. Then for each word of the expanded value of LIST, the
4989 variable named by the expanded value of VAR is set to that word, and
4990 TEXT is expanded. Presumably TEXT contains references to that
4991 variable, so its expansion will be different each time.
4993 The result is that TEXT is expanded as many times as there are
4994 whitespace-separated words in LIST. The multiple expansions of TEXT
4995 are concatenated, with spaces between them, to make the result of
4998 This simple example sets the variable `files' to the list of all
4999 files in the directories in the list `dirs':
5002 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
5004 Here TEXT is `$(wildcard $(dir)/*)'. The first repetition finds the
5005 value `a' for `dir', so it produces the same result as `$(wildcard
5006 a/*)'; the second repetition produces the result of `$(wildcard b/*)';
5007 and the third, that of `$(wildcard c/*)'.
5009 This example has the same result (except for setting `dirs') as the
5012 files := $(wildcard a/* b/* c/* d/*)
5014 When TEXT is complicated, you can improve readability by giving it a
5015 name, with an additional variable:
5017 find_files = $(wildcard $(dir)/*)
5019 files := $(foreach dir,$(dirs),$(find_files))
5021 Here we use the variable `find_files' this way. We use plain `=' to
5022 define a recursively-expanding variable, so that its value contains an
5023 actual function call to be reexpanded under the control of `foreach'; a
5024 simply-expanded variable would not do, since `wildcard' would be called
5025 only once at the time of defining `find_files'.
5027 The `foreach' function has no permanent effect on the variable VAR;
5028 its value and flavor after the `foreach' function call are the same as
5029 they were beforehand. The other values which are taken from LIST are
5030 in effect only temporarily, during the execution of `foreach'. The
5031 variable VAR is a simply-expanded variable during the execution of
5032 `foreach'. If VAR was undefined before the `foreach' function call, it
5033 is undefined after the call. *Note The Two Flavors of Variables:
5036 You must take care when using complex variable expressions that
5037 result in variable names because many strange things are valid variable
5038 names, but are probably not what you intended. For example,
5040 files := $(foreach Esta escrito en espanol!,b c ch,$(find_files))
5042 might be useful if the value of `find_files' references the variable
5043 whose name is `Esta escrito en espanol!' (es un nombre bastante largo,
5044 no?), but it is more likely to be a mistake.
5047 File: make.info, Node: If Function, Next: Call Function, Prev: Foreach Function, Up: Functions
5052 The `if' function provides support for conditional expansion in a
5053 functional context (as opposed to the GNU `make' makefile conditionals
5054 such as `ifeq' (*note Syntax of Conditionals: Conditional Syntax.).
5056 An `if' function call can contain either two or three arguments:
5058 $(if CONDITION,THEN-PART[,ELSE-PART])
5060 The first argument, CONDITION, first has all preceding and trailing
5061 whitespace stripped, then is expanded. If it expands to any non-empty
5062 string, then the condition is considered to be true. If it expands to
5063 an empty string, the condition is considered to be false.
5065 If the condition is true then the second argument, THEN-PART, is
5066 evaluated and this is used as the result of the evaluation of the entire
5069 If the condition is false then the third argument, ELSE-PART, is
5070 evaluated and this is the result of the `if' function. If there is no
5071 third argument, the `if' function evaluates to nothing (the empty
5074 Note that only one of the THEN-PART or the ELSE-PART will be
5075 evaluated, never both. Thus, either can contain side-effects (such as
5076 `shell' function calls, etc.)
5079 File: make.info, Node: Call Function, Next: Value Function, Prev: If Function, Up: Functions
5084 The `call' function is unique in that it can be used to create new
5085 parameterized functions. You can write a complex expression as the
5086 value of a variable, then use `call' to expand it with different values.
5088 The syntax of the `call' function is:
5090 $(call VARIABLE,PARAM,PARAM,...)
5092 When `make' expands this function, it assigns each PARAM to
5093 temporary variables `$(1)', `$(2)', etc. The variable `$(0)' will
5094 contain VARIABLE. There is no maximum number of parameter arguments.
5095 There is no minimum, either, but it doesn't make sense to use `call'
5098 Then VARIABLE is expanded as a `make' variable in the context of
5099 these temporary assignments. Thus, any reference to `$(1)' in the
5100 value of VARIABLE will resolve to the first PARAM in the invocation of
5103 Note that VARIABLE is the _name_ of a variable, not a _reference_ to
5104 that variable. Therefore you would not normally use a `$' or
5105 parentheses when writing it. (You can, however, use a variable
5106 reference in the name if you want the name not to be a constant.)
5108 If VARIABLE is the name of a builtin function, the builtin function
5109 is always invoked (even if a `make' variable by that name also exists).
5111 The `call' function expands the PARAM arguments before assigning
5112 them to temporary variables. This means that VARIABLE values
5113 containing references to builtin functions that have special expansion
5114 rules, like `foreach' or `if', may not work as you expect.
5116 Some examples may make this clearer.
5118 This macro simply reverses its arguments:
5122 foo = $(call reverse,a,b)
5124 Here FOO will contain `b a'.
5126 This one is slightly more interesting: it defines a macro to search
5127 for the first instance of a program in `PATH':
5129 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
5131 LS := $(call pathsearch,ls)
5133 Now the variable LS contains `/bin/ls' or similar.
5135 The `call' function can be nested. Each recursive invocation gets
5136 its own local values for `$(1)', etc. that mask the values of
5137 higher-level `call'. For example, here is an implementation of a "map"
5140 map = $(foreach a,$(2),$(call $(1),$(a)))
5142 Now you can MAP a function that normally takes only one argument,
5143 such as `origin', to multiple values in one step:
5145 o = $(call map,origin,o map MAKE)
5147 and end up with O containing something like `file file default'.
5149 A final caution: be careful when adding whitespace to the arguments
5150 to `call'. As with other functions, any whitespace contained in the
5151 second and subsequent arguments is kept; this can cause strange
5152 effects. It's generally safest to remove all extraneous whitespace when
5153 providing parameters to `call'.
5156 File: make.info, Node: Value Function, Next: Eval Function, Prev: Call Function, Up: Functions
5158 The `value' Function
5159 ====================
5161 The `value' function provides a way for you to use the value of a
5162 variable _without_ having it expanded. Please note that this does not
5163 undo expansions which have already occurred; for example if you create
5164 a simply expanded variable its value is expanded during the definition;
5165 in that case the `value' function will return the same result as using
5166 the variable directly.
5168 The syntax of the `value' function is:
5172 Note that VARIABLE is the _name_ of a variable; not a _reference_ to
5173 that variable. Therefore you would not normally use a `$' or
5174 parentheses when writing it. (You can, however, use a variable
5175 reference in the name if you want the name not to be a constant.)
5177 The result of this function is a string containing the value of
5178 VARIABLE, without any expansion occurring. For example, in this
5187 The first output line would be `ATH', since the "$P" would be expanded
5188 as a `make' variable, while the second output line would be the current
5189 value of your `$PATH' environment variable, since the `value' function
5190 avoided the expansion.
5192 The `value' function is most often used in conjunction with the
5193 `eval' function (*note Eval Function::).
5196 File: make.info, Node: Eval Function, Next: Origin Function, Prev: Value Function, Up: Functions
5201 The `eval' function is very special: it allows you to define new
5202 makefile constructs that are not constant; which are the result of
5203 evaluating other variables and functions. The argument to the `eval'
5204 function is expanded, then the results of that expansion are parsed as
5205 makefile syntax. The expanded results can define new `make' variables,
5206 targets, implicit or explicit rules, etc.
5208 The result of the `eval' function is always the empty string; thus,
5209 it can be placed virtually anywhere in a makefile without causing
5212 It's important to realize that the `eval' argument is expanded
5213 _twice_; first by the `eval' function, then the results of that
5214 expansion are expanded again when they are parsed as makefile syntax.
5215 This means you may need to provide extra levels of escaping for "$"
5216 characters when using `eval'. The `value' function (*note Value
5217 Function::) can sometimes be useful in these situations, to circumvent
5218 unwanted expansions.
5220 Here is an example of how `eval' can be used; this example combines
5221 a number of concepts and other functions. Although it might seem
5222 overly complex to use `eval' in this example, rather than just writing
5223 out the rules, consider two things: first, the template definition (in
5224 `PROGRAM_template') could need to be much more complex than it is here;
5225 and second, you might put the complex, "generic" part of this example
5226 into another makefile, then include it in all the individual makefiles.
5227 Now your individual makefiles are quite straightforward.
5229 PROGRAMS = server client
5231 server_OBJS = server.o server_priv.o server_access.o
5232 server_LIBS = priv protocol
5234 client_OBJS = client.o client_api.o client_mem.o
5235 client_LIBS = protocol
5237 # Everything after this is generic
5242 define PROGRAM_template
5243 $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
5244 ALL_OBJS += $$($(1)_OBJS)
5247 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
5250 $(LINK.o) $^ $(LDLIBS) -o $@
5253 rm -f $(ALL_OBJS) $(PROGRAMS)
5256 File: make.info, Node: Origin Function, Next: Shell Function, Prev: Eval Function, Up: Functions
5258 The `origin' Function
5259 =====================
5261 The `origin' function is unlike most other functions in that it does
5262 not operate on the values of variables; it tells you something _about_
5263 a variable. Specifically, it tells you where it came from.
5265 The syntax of the `origin' function is:
5269 Note that VARIABLE is the _name_ of a variable to inquire about; not
5270 a _reference_ to that variable. Therefore you would not normally use a
5271 `$' or parentheses when writing it. (You can, however, use a variable
5272 reference in the name if you want the name not to be a constant.)
5274 The result of this function is a string telling you how the variable
5275 VARIABLE was defined:
5278 if VARIABLE was never defined.
5281 if VARIABLE has a default definition, as is usual with `CC' and so
5282 on. *Note Variables Used by Implicit Rules: Implicit Variables.
5283 Note that if you have redefined a default variable, the `origin'
5284 function will return the origin of the later definition.
5287 if VARIABLE was defined as an environment variable and the `-e'
5288 option is _not_ turned on (*note Summary of Options: Options
5291 `environment override'
5292 if VARIABLE was defined as an environment variable and the `-e'
5293 option _is_ turned on (*note Summary of Options: Options Summary.).
5296 if VARIABLE was defined in a makefile.
5299 if VARIABLE was defined on the command line.
5302 if VARIABLE was defined with an `override' directive in a makefile
5303 (*note The `override' Directive: Override Directive.).
5306 if VARIABLE is an automatic variable defined for the execution of
5307 the commands for each rule (*note Automatic Variables::).
5309 This information is primarily useful (other than for your curiosity)
5310 to determine if you want to believe the value of a variable. For
5311 example, suppose you have a makefile `foo' that includes another
5312 makefile `bar'. You want a variable `bletch' to be defined in `bar' if
5313 you run the command `make -f bar', even if the environment contains a
5314 definition of `bletch'. However, if `foo' defined `bletch' before
5315 including `bar', you do not want to override that definition. This
5316 could be done by using an `override' directive in `foo', giving that
5317 definition precedence over the later definition in `bar';
5318 unfortunately, the `override' directive would also override any command
5319 line definitions. So, `bar' could include:
5322 ifeq "$(origin bletch)" "environment"
5323 bletch = barf, gag, etc.
5327 If `bletch' has been defined from the environment, this will redefine
5330 If you want to override a previous definition of `bletch' if it came
5331 from the environment, even under `-e', you could instead write:
5333 ifneq "$(findstring environment,$(origin bletch))" ""
5334 bletch = barf, gag, etc.
5337 Here the redefinition takes place if `$(origin bletch)' returns
5338 either `environment' or `environment override'. *Note Functions for
5339 String Substitution and Analysis: Text Functions.
5342 File: make.info, Node: Shell Function, Next: Make Control Functions, Prev: Origin Function, Up: Functions
5344 The `shell' Function
5345 ====================
5347 The `shell' function is unlike any other function other than the
5348 `wildcard' function (*note The Function `wildcard': Wildcard Function.)
5349 in that it communicates with the world outside of `make'.
5351 The `shell' function performs the same function that backquotes
5352 (``') perform in most shells: it does "command expansion". This means
5353 that it takes as an argument a shell command and evaluates to the
5354 output of the command. The only processing `make' does on the result
5355 is to convert each newline (or carriage-return / newline pair) to a
5356 single space. If there is a trailing (carriage-return and) newline it
5357 will simply be removed.
5359 The commands run by calls to the `shell' function are run when the
5360 function calls are expanded (*note How `make' Reads a Makefile: Reading
5361 Makefiles.). Because this function involves spawning a new shell, you
5362 should carefully consider the performance implications of using the
5363 `shell' function within recursively expanded variables vs. simply
5364 expanded variables (*note The Two Flavors of Variables: Flavors.).
5366 Here are some examples of the use of the `shell' function:
5368 contents := $(shell cat foo)
5370 sets `contents' to the contents of the file `foo', with a space (rather
5371 than a newline) separating each line.
5373 files := $(shell echo *.c)
5375 sets `files' to the expansion of `*.c'. Unless `make' is using a very
5376 strange shell, this has the same result as `$(wildcard *.c)'.
5379 File: make.info, Node: Make Control Functions, Prev: Shell Function, Up: Functions
5381 Functions That Control Make
5382 ===========================
5384 These functions control the way make runs. Generally, they are used to
5385 provide information to the user of the makefile or to cause make to stop
5386 if some sort of environmental error is detected.
5389 Generates a fatal error where the message is TEXT. Note that the
5390 error is generated whenever this function is evaluated. So, if
5391 you put it inside a command script or on the right side of a
5392 recursive variable assignment, it won't be evaluated until later.
5393 The TEXT will be expanded before the error is generated.
5398 $(error error is $(ERROR1))
5401 will generate a fatal error during the read of the makefile if the
5402 `make' variable `ERROR1' is defined. Or,
5404 ERR = $(error found an error!)
5409 will generate a fatal error while `make' is running, if the `err'
5412 `$(warning TEXT...)'
5413 This function works similarly to the `error' function, above,
5414 except that `make' doesn't exit. Instead, TEXT is expanded and
5415 the resulting message is displayed, but processing of the makefile
5418 The result of the expansion of this function is the empty string.
5421 File: make.info, Node: Running, Next: Implicit Rules, Prev: Functions, Up: Top
5426 A makefile that says how to recompile a program can be used in more
5427 than one way. The simplest use is to recompile every file that is out
5428 of date. Usually, makefiles are written so that if you run `make' with
5429 no arguments, it does just that.
5431 But you might want to update only some of the files; you might want
5432 to use a different compiler or different compiler options; you might
5433 want just to find out which files are out of date without changing them.
5435 By giving arguments when you run `make', you can do any of these
5436 things and many others.
5438 The exit status of `make' is always one of three values:
5440 The exit status is zero if `make' is successful.
5443 The exit status is two if `make' encounters any errors. It will
5444 print messages describing the particular errors.
5447 The exit status is one if you use the `-q' flag and `make'
5448 determines that some target is not already up to date. *Note
5449 Instead of Executing the Commands: Instead of Execution.
5453 * Makefile Arguments:: How to specify which makefile to use.
5454 * Goals:: How to use goal arguments to specify which
5455 parts of the makefile to use.
5456 * Instead of Execution:: How to use mode flags to specify what
5457 kind of thing to do with the commands
5458 in the makefile other than simply
5460 * Avoiding Compilation:: How to avoid recompiling certain files.
5461 * Overriding:: How to override a variable to specify
5462 an alternate compiler and other things.
5463 * Testing:: How to proceed past some errors, to
5465 * Options Summary:: Summary of Options
5468 File: make.info, Node: Makefile Arguments, Next: Goals, Prev: Running, Up: Running
5470 Arguments to Specify the Makefile
5471 =================================
5473 The way to specify the name of the makefile is with the `-f' or
5474 `--file' option (`--makefile' also works). For example, `-f altmake'
5475 says to use the file `altmake' as the makefile.
5477 If you use the `-f' flag several times and follow each `-f' with an
5478 argument, all the specified files are used jointly as makefiles.
5480 If you do not use the `-f' or `--file' flag, the default is to try
5481 `GNUmakefile', `makefile', and `Makefile', in that order, and use the
5482 first of these three which exists or can be made (*note Writing
5483 Makefiles: Makefiles.).
5486 File: make.info, Node: Goals, Next: Instead of Execution, Prev: Makefile Arguments, Up: Running
5488 Arguments to Specify the Goals
5489 ==============================
5491 The "goals" are the targets that `make' should strive ultimately to
5492 update. Other targets are updated as well if they appear as
5493 prerequisites of goals, or prerequisites of prerequisites of goals, etc.
5495 By default, the goal is the first target in the makefile (not
5496 counting targets that start with a period). Therefore, makefiles are
5497 usually written so that the first target is for compiling the entire
5498 program or programs they describe. If the first rule in the makefile
5499 has several targets, only the first target in the rule becomes the
5500 default goal, not the whole list.
5502 You can specify a different goal or goals with arguments to `make'.
5503 Use the name of the goal as an argument. If you specify several goals,
5504 `make' processes each of them in turn, in the order you name them.
5506 Any target in the makefile may be specified as a goal (unless it
5507 starts with `-' or contains an `=', in which case it will be parsed as
5508 a switch or variable definition, respectively). Even targets not in
5509 the makefile may be specified, if `make' can find implicit rules that
5510 say how to make them.
5512 `Make' will set the special variable `MAKECMDGOALS' to the list of
5513 goals you specified on the command line. If no goals were given on the
5514 command line, this variable is empty. Note that this variable should
5515 be used only in special circumstances.
5517 An example of appropriate use is to avoid including `.d' files
5518 during `clean' rules (*note Automatic Prerequisites::), so `make' won't
5519 create them only to immediately remove them again:
5521 sources = foo.c bar.c
5523 ifneq ($(MAKECMDGOALS),clean)
5524 include $(sources:.c=.d)
5527 One use of specifying a goal is if you want to compile only a part of
5528 the program, or only one of several programs. Specify as a goal each
5529 file that you wish to remake. For example, consider a directory
5530 containing several programs, with a makefile that starts like this:
5533 all: size nm ld ar as
5535 If you are working on the program `size', you might want to say
5536 `make size' so that only the files of that program are recompiled.
5538 Another use of specifying a goal is to make files that are not
5539 normally made. For example, there may be a file of debugging output,
5540 or a version of the program that is compiled specially for testing,
5541 which has a rule in the makefile but is not a prerequisite of the
5544 Another use of specifying a goal is to run the commands associated
5545 with a phony target (*note Phony Targets::) or empty target (*note
5546 Empty Target Files to Record Events: Empty Targets.). Many makefiles
5547 contain a phony target named `clean' which deletes everything except
5548 source files. Naturally, this is done only if you request it
5549 explicitly with `make clean'. Following is a list of typical phony and
5550 empty target names. *Note Standard Targets::, for a detailed list of
5551 all the standard target names which GNU software packages use.
5554 Make all the top-level targets the makefile knows about.
5557 Delete all files that are normally created by running `make'.
5560 Like `clean', but may refrain from deleting a few files that people
5561 normally don't want to recompile. For example, the `mostlyclean'
5562 target for GCC does not delete `libgcc.a', because recompiling it
5563 is rarely necessary and takes a lot of time.
5568 Any of these targets might be defined to delete _more_ files than
5569 `clean' does. For example, this would delete configuration files
5570 or links that you would normally create as preparation for
5571 compilation, even if the makefile itself cannot create these files.
5574 Copy the executable file into a directory that users typically
5575 search for commands; copy any auxiliary files that the executable
5576 uses into the directories where it will look for them.
5579 Print listings of the source files that have changed.
5582 Create a tar file of the source files.
5585 Create a shell archive (shar file) of the source files.
5588 Create a distribution file of the source files. This might be a
5589 tar file, or a shar file, or a compressed version of one of the
5590 above, or even more than one of the above.
5593 Update a tags table for this program.
5597 Perform self tests on the program this makefile builds.
5600 File: make.info, Node: Instead of Execution, Next: Avoiding Compilation, Prev: Goals, Up: Running
5602 Instead of Executing the Commands
5603 =================================
5605 The makefile tells `make' how to tell whether a target is up to date,
5606 and how to update each target. But updating the targets is not always
5607 what you want. Certain options specify other activities for `make'.
5613 "No-op". The activity is to print what commands would be used to
5614 make the targets up to date, but not actually execute them.
5618 "Touch". The activity is to mark the targets as up to date without
5619 actually changing them. In other words, `make' pretends to compile
5620 the targets but does not really change their contents.
5624 "Question". The activity is to find out silently whether the
5625 targets are up to date already; but execute no commands in either
5626 case. In other words, neither compilation nor output will occur.
5632 "What if". Each `-W' flag is followed by a file name. The given
5633 files' modification times are recorded by `make' as being the
5634 present time, although the actual modification times remain the
5635 same. You can use the `-W' flag in conjunction with the `-n' flag
5636 to see what would happen if you were to modify specific files.
5638 With the `-n' flag, `make' prints the commands that it would
5639 normally execute but does not execute them.
5641 With the `-t' flag, `make' ignores the commands in the rules and
5642 uses (in effect) the command `touch' for each target that needs to be
5643 remade. The `touch' command is also printed, unless `-s' or `.SILENT'
5644 is used. For speed, `make' does not actually invoke the program
5645 `touch'. It does the work directly.
5647 With the `-q' flag, `make' prints nothing and executes no commands,
5648 but the exit status code it returns is zero if and only if the targets
5649 to be considered are already up to date. If the exit status is one,
5650 then some updating needs to be done. If `make' encounters an error,
5651 the exit status is two, so you can distinguish an error from a target
5652 that is not up to date.
5654 It is an error to use more than one of these three flags in the same
5655 invocation of `make'.
5657 The `-n', `-t', and `-q' options do not affect command lines that
5658 begin with `+' characters or contain the strings `$(MAKE)' or
5659 `${MAKE}'. Note that only the line containing the `+' character or the
5660 strings `$(MAKE)' or `${MAKE}' is run regardless of these options.
5661 Other lines in the same rule are not run unless they too begin with `+'
5662 or contain `$(MAKE)' or `${MAKE}' (*Note How the `MAKE' Variable Works:
5665 The `-W' flag provides two features:
5667 * If you also use the `-n' or `-q' flag, you can see what `make'
5668 would do if you were to modify some files.
5670 * Without the `-n' or `-q' flag, when `make' is actually executing
5671 commands, the `-W' flag can direct `make' to act as if some files
5672 had been modified, without actually modifying the files.
5674 Note that the options `-p' and `-v' allow you to obtain other
5675 information about `make' or about the makefiles in use (*note Summary
5676 of Options: Options Summary.).
5679 File: make.info, Node: Avoiding Compilation, Next: Overriding, Prev: Instead of Execution, Up: Running
5681 Avoiding Recompilation of Some Files
5682 ====================================
5684 Sometimes you may have changed a source file but you do not want to
5685 recompile all the files that depend on it. For example, suppose you add
5686 a macro or a declaration to a header file that many other files depend
5687 on. Being conservative, `make' assumes that any change in the header
5688 file requires recompilation of all dependent files, but you know that
5689 they do not need to be recompiled and you would rather not waste the
5690 time waiting for them to compile.
5692 If you anticipate the problem before changing the header file, you
5693 can use the `-t' flag. This flag tells `make' not to run the commands
5694 in the rules, but rather to mark the target up to date by changing its
5695 last-modification date. You would follow this procedure:
5697 1. Use the command `make' to recompile the source files that really
5698 need recompilation, ensuring that the object files are up-to-date
5701 2. Make the changes in the header files.
5703 3. Use the command `make -t' to mark all the object files as up to
5704 date. The next time you run `make', the changes in the header
5705 files will not cause any recompilation.
5707 If you have already changed the header file at a time when some files
5708 do need recompilation, it is too late to do this. Instead, you can use
5709 the `-o FILE' flag, which marks a specified file as "old" (*note
5710 Summary of Options: Options Summary.). This means that the file itself
5711 will not be remade, and nothing else will be remade on its account.
5712 Follow this procedure:
5714 1. Recompile the source files that need compilation for reasons
5715 independent of the particular header file, with `make -o
5716 HEADERFILE'. If several header files are involved, use a separate
5717 `-o' option for each header file.
5719 2. Touch all the object files with `make -t'.
5722 File: make.info, Node: Overriding, Next: Testing, Prev: Avoiding Compilation, Up: Running
5724 Overriding Variables
5725 ====================
5727 An argument that contains `=' specifies the value of a variable: `V=X'
5728 sets the value of the variable V to X. If you specify a value in this
5729 way, all ordinary assignments of the same variable in the makefile are
5730 ignored; we say they have been "overridden" by the command line
5733 The most common way to use this facility is to pass extra flags to
5734 compilers. For example, in a properly written makefile, the variable
5735 `CFLAGS' is included in each command that runs the C compiler, so a
5736 file `foo.c' would be compiled something like this:
5738 cc -c $(CFLAGS) foo.c
5740 Thus, whatever value you set for `CFLAGS' affects each compilation
5741 that occurs. The makefile probably specifies the usual value for
5742 `CFLAGS', like this:
5746 Each time you run `make', you can override this value if you wish.
5747 For example, if you say `make CFLAGS='-g -O'', each C compilation will
5748 be done with `cc -c -g -O'. (This also illustrates how you can use
5749 quoting in the shell to enclose spaces and other special characters in
5750 the value of a variable when you override it.)
5752 The variable `CFLAGS' is only one of many standard variables that
5753 exist just so that you can change them this way. *Note Variables Used
5754 by Implicit Rules: Implicit Variables, for a complete list.
5756 You can also program the makefile to look at additional variables of
5757 your own, giving the user the ability to control other aspects of how
5758 the makefile works by changing the variables.
5760 When you override a variable with a command argument, you can define
5761 either a recursively-expanded variable or a simply-expanded variable.
5762 The examples shown above make a recursively-expanded variable; to make a
5763 simply-expanded variable, write `:=' instead of `='. But, unless you
5764 want to include a variable reference or function call in the _value_
5765 that you specify, it makes no difference which kind of variable you
5768 There is one way that the makefile can change a variable that you
5769 have overridden. This is to use the `override' directive, which is a
5770 line that looks like this: `override VARIABLE = VALUE' (*note The
5771 `override' Directive: Override Directive.).
5774 File: make.info, Node: Testing, Next: Options Summary, Prev: Overriding, Up: Running
5776 Testing the Compilation of a Program
5777 ====================================
5779 Normally, when an error happens in executing a shell command, `make'
5780 gives up immediately, returning a nonzero status. No further commands
5781 are executed for any target. The error implies that the goal cannot be
5782 correctly remade, and `make' reports this as soon as it knows.
5784 When you are compiling a program that you have just changed, this is
5785 not what you want. Instead, you would rather that `make' try compiling
5786 every file that can be tried, to show you as many compilation errors as
5789 On these occasions, you should use the `-k' or `--keep-going' flag.
5790 This tells `make' to continue to consider the other prerequisites of
5791 the pending targets, remaking them if necessary, before it gives up and
5792 returns nonzero status. For example, after an error in compiling one
5793 object file, `make -k' will continue compiling other object files even
5794 though it already knows that linking them will be impossible. In
5795 addition to continuing after failed shell commands, `make -k' will
5796 continue as much as possible after discovering that it does not know
5797 how to make a target or prerequisite file. This will always cause an
5798 error message, but without `-k', it is a fatal error (*note Summary of
5799 Options: Options Summary.).
5801 The usual behavior of `make' assumes that your purpose is to get the
5802 goals up to date; once `make' learns that this is impossible, it might
5803 as well report the failure immediately. The `-k' flag says that the
5804 real purpose is to test as much as possible of the changes made in the
5805 program, perhaps to find several independent problems so that you can
5806 correct them all before the next attempt to compile. This is why Emacs'
5807 `M-x compile' command passes the `-k' flag by default.
5810 File: make.info, Node: Options Summary, Prev: Testing, Up: Running
5815 Here is a table of all the options `make' understands:
5819 These options are ignored for compatibility with other versions of
5824 Consider all targets out-of-date. GNU `make' proceeds to consider
5825 targets and their prerequisites using the normal algorithms;
5826 however, all these targets are remade, regardless of the status of
5827 their prerequisites.
5831 Change to directory DIR before reading the makefiles. If multiple
5832 `-C' options are specified, each is interpreted relative to the
5833 previous one: `-C / -C etc' is equivalent to `-C /etc'. This is
5834 typically used with recursive invocations of `make' (*note
5835 Recursive Use of `make': Recursion.).
5838 Print debugging information in addition to normal processing. The
5839 debugging information says which files are being considered for
5840 remaking, which file-times are being compared and with what
5841 results, which files actually need to be remade, which implicit
5842 rules are considered and which are applied--everything interesting
5843 about how `make' decides what to do. The `-d' option is
5844 equivalent to `--debug=a' (see below).
5847 Print debugging information in addition to normal processing.
5848 Various levels and types of output can be chosen. With no
5849 arguments, print the "basic" level of debugging. Possible
5850 arguments are below; only the first character is considered, and
5851 values must be comma- or space-separated.
5854 All types of debugging output are enabled. This is
5855 equivalent to using `-d'.
5858 Basic debugging prints each target that was found to be
5859 out-of-date, and whether the build was successful or not.
5862 A level above `basic'; includes messages about which
5863 makefiles were parsed, prerequisites that did not need to be
5864 rebuilt, etc. This option also enables `basic' messages.
5867 Prints messages describing the implicit rule searches for
5868 each target. This option also enables `basic' messages.
5871 Prints messages giving details on the invocation of specific
5875 By default, the above messages are not enabled while trying
5876 to remake the makefiles. This option enables messages while
5877 rebuilding makefiles, too. Note that the `all' option does
5878 enable this option. This option also enables `basic'
5882 `--environment-overrides'
5883 Give variables taken from the environment precedence over
5884 variables from makefiles. *Note Variables from the Environment:
5890 Read the file named FILE as a makefile. *Note Writing Makefiles:
5895 Remind you of the options that `make' understands and then exit.
5899 Ignore all errors in commands executed to remake files. *Note
5900 Errors in Commands: Errors.
5904 Specifies a directory DIR to search for included makefiles. *Note
5905 Including Other Makefiles: Include. If several `-I' options are
5906 used to specify several directories, the directories are searched
5907 in the order specified.
5911 Specifies the number of jobs (commands) to run simultaneously.
5912 With no argument, `make' runs as many jobs simultaneously as
5913 possible. If there is more than one `-j' option, the last one is
5914 effective. *Note Parallel Execution: Parallel, for more
5915 information on how commands are run. Note that this option is
5920 Continue as much as possible after an error. While the target that
5921 failed, and those that depend on it, cannot be remade, the other
5922 prerequisites of these targets can be processed all the same.
5923 *Note Testing the Compilation of a Program: Testing.
5926 `--load-average[=LOAD]'
5928 Specifies that no new jobs (commands) should be started if there
5929 are other jobs running and the load average is at least LOAD (a
5930 floating-point number). With no argument, removes a previous load
5931 limit. *Note Parallel Execution: Parallel.
5937 Print the commands that would be executed, but do not execute them.
5938 *Note Instead of Executing the Commands: Instead of Execution.
5943 Do not remake the file FILE even if it is older than its
5944 prerequisites, and do not remake anything on account of changes in
5945 FILE. Essentially the file is treated as very old and its rules
5946 are ignored. *Note Avoiding Recompilation of Some Files: Avoiding
5951 Print the data base (rules and variable values) that results from
5952 reading the makefiles; then execute as usual or as otherwise
5953 specified. This also prints the version information given by the
5954 `-v' switch (see below). To print the data base without trying to
5955 remake any files, use `make -qp'. To print the data base of
5956 predefined rules and variables, use `make -p -f /dev/null'. The
5957 data base output contains filename and linenumber information for
5958 command and variable definitions, so it can be a useful debugging
5959 tool in complex environments.
5963 "Question mode". Do not run any commands, or print anything; just
5964 return an exit status that is zero if the specified targets are
5965 already up to date, one if any remaking is required, or two if an
5966 error is encountered. *Note Instead of Executing the Commands:
5967 Instead of Execution.
5970 `--no-builtin-rules'
5971 Eliminate use of the built-in implicit rules (*note Using Implicit
5972 Rules: Implicit Rules.). You can still define your own by writing
5973 pattern rules (*note Defining and Redefining Pattern Rules:
5974 Pattern Rules.). The `-r' option also clears out the default list
5975 of suffixes for suffix rules (*note Old-Fashioned Suffix Rules:
5976 Suffix Rules.). But you can still define your own suffixes with a
5977 rule for `.SUFFIXES', and then define your own suffix rules. Note
5978 that only _rules_ are affected by the `-r' option; default
5979 variables remain in effect (*note Variables Used by Implicit
5980 Rules: Implicit Variables.); see the `-R' option below.
5983 `--no-builtin-variables'
5984 Eliminate use of the built-in rule-specific variables (*note
5985 Variables Used by Implicit Rules: Implicit Variables.). You can
5986 still define your own, of course. The `-R' option also
5987 automatically enables the `-r' option (see above), since it
5988 doesn't make sense to have implicit rules without any definitions
5989 for the variables that they use.
5994 Silent operation; do not print the commands as they are executed.
5995 *Note Command Echoing: Echoing.
6000 Cancel the effect of the `-k' option. This is never necessary
6001 except in a recursive `make' where `-k' might be inherited from
6002 the top-level `make' via `MAKEFLAGS' (*note Recursive Use of
6003 `make': Recursion.) or if you set `-k' in `MAKEFLAGS' in your
6008 Touch files (mark them up to date without really changing them)
6009 instead of running their commands. This is used to pretend that
6010 the commands were done, in order to fool future invocations of
6011 `make'. *Note Instead of Executing the Commands: Instead of
6016 Print the version of the `make' program plus a copyright, a list
6017 of authors, and a notice that there is no warranty; then exit.
6021 Print a message containing the working directory both before and
6022 after executing the makefile. This may be useful for tracking
6023 down errors from complicated nests of recursive `make' commands.
6024 *Note Recursive Use of `make': Recursion. (In practice, you
6025 rarely need to specify this option since `make' does it for you;
6026 see *Note The `--print-directory' Option: -w Option.)
6028 `--no-print-directory'
6029 Disable printing of the working directory under `-w'. This option
6030 is useful when `-w' is turned on automatically, but you do not
6031 want to see the extra messages. *Note The `--print-directory'
6038 Pretend that the target FILE has just been modified. When used
6039 with the `-n' flag, this shows you what would happen if you were
6040 to modify that file. Without `-n', it is almost the same as
6041 running a `touch' command on the given file before running `make',
6042 except that the modification time is changed only in the
6043 imagination of `make'. *Note Instead of Executing the Commands:
6044 Instead of Execution.
6046 `--warn-undefined-variables'
6047 Issue a warning message whenever `make' sees a reference to an
6048 undefined variable. This can be helpful when you are trying to
6049 debug makefiles which use variables in complex ways.
6052 File: make.info, Node: Implicit Rules, Next: Archives, Prev: Running, Up: Top
6054 Using Implicit Rules
6055 ********************
6057 Certain standard ways of remaking target files are used very often. For
6058 example, one customary way to make an object file is from a C source
6059 file using the C compiler, `cc'.
6061 "Implicit rules" tell `make' how to use customary techniques so that
6062 you do not have to specify them in detail when you want to use them.
6063 For example, there is an implicit rule for C compilation. File names
6064 determine which implicit rules are run. For example, C compilation
6065 typically takes a `.c' file and makes a `.o' file. So `make' applies
6066 the implicit rule for C compilation when it sees this combination of
6069 A chain of implicit rules can apply in sequence; for example, `make'
6070 will remake a `.o' file from a `.y' file by way of a `.c' file.
6072 The built-in implicit rules use several variables in their commands
6073 so that, by changing the values of the variables, you can change the
6074 way the implicit rule works. For example, the variable `CFLAGS'
6075 controls the flags given to the C compiler by the implicit rule for C
6078 You can define your own implicit rules by writing "pattern rules".
6080 "Suffix rules" are a more limited way to define implicit rules.
6081 Pattern rules are more general and clearer, but suffix rules are
6082 retained for compatibility.
6086 * Using Implicit:: How to use an existing implicit rule
6087 to get the commands for updating a file.
6088 * Catalogue of Rules:: A list of built-in implicit rules.
6089 * Implicit Variables:: How to change what predefined rules do.
6090 * Chained Rules:: How to use a chain of implicit rules.
6091 * Pattern Rules:: How to define new implicit rules.
6092 * Last Resort:: How to defining commands for rules
6093 which cannot find any.
6094 * Suffix Rules:: The old-fashioned style of implicit rule.
6095 * Implicit Rule Search:: The precise algorithm for applying
6099 File: make.info, Node: Using Implicit, Next: Catalogue of Rules, Prev: Implicit Rules, Up: Implicit Rules
6101 Using Implicit Rules
6102 ====================
6104 To allow `make' to find a customary method for updating a target file,
6105 all you have to do is refrain from specifying commands yourself. Either
6106 write a rule with no command lines, or don't write a rule at all. Then
6107 `make' will figure out which implicit rule to use based on which kind
6108 of source file exists or can be made.
6110 For example, suppose the makefile looks like this:
6113 cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
6115 Because you mention `foo.o' but do not give a rule for it, `make' will
6116 automatically look for an implicit rule that tells how to update it.
6117 This happens whether or not the file `foo.o' currently exists.
6119 If an implicit rule is found, it can supply both commands and one or
6120 more prerequisites (the source files). You would want to write a rule
6121 for `foo.o' with no command lines if you need to specify additional
6122 prerequisites, such as header files, that the implicit rule cannot
6125 Each implicit rule has a target pattern and prerequisite patterns.
6126 There may be many implicit rules with the same target pattern. For
6127 example, numerous rules make `.o' files: one, from a `.c' file with the
6128 C compiler; another, from a `.p' file with the Pascal compiler; and so
6129 on. The rule that actually applies is the one whose prerequisites
6130 exist or can be made. So, if you have a file `foo.c', `make' will run
6131 the C compiler; otherwise, if you have a file `foo.p', `make' will run
6132 the Pascal compiler; and so on.
6134 Of course, when you write the makefile, you know which implicit rule
6135 you want `make' to use, and you know it will choose that one because you
6136 know which possible prerequisite files are supposed to exist. *Note
6137 Catalogue of Implicit Rules: Catalogue of Rules, for a catalogue of all
6138 the predefined implicit rules.
6140 Above, we said an implicit rule applies if the required
6141 prerequisites "exist or can be made". A file "can be made" if it is
6142 mentioned explicitly in the makefile as a target or a prerequisite, or
6143 if an implicit rule can be recursively found for how to make it. When
6144 an implicit prerequisite is the result of another implicit rule, we say
6145 that "chaining" is occurring. *Note Chains of Implicit Rules: Chained
6148 In general, `make' searches for an implicit rule for each target, and
6149 for each double-colon rule, that has no commands. A file that is
6150 mentioned only as a prerequisite is considered a target whose rule
6151 specifies nothing, so implicit rule search happens for it. *Note
6152 Implicit Rule Search Algorithm: Implicit Rule Search, for the details
6153 of how the search is done.
6155 Note that explicit prerequisites do not influence implicit rule
6156 search. For example, consider this explicit rule:
6160 The prerequisite on `foo.p' does not necessarily mean that `make' will
6161 remake `foo.o' according to the implicit rule to make an object file, a
6162 `.o' file, from a Pascal source file, a `.p' file. For example, if
6163 `foo.c' also exists, the implicit rule to make an object file from a C
6164 source file is used instead, because it appears before the Pascal rule
6165 in the list of predefined implicit rules (*note Catalogue of Implicit
6166 Rules: Catalogue of Rules.).
6168 If you do not want an implicit rule to be used for a target that has
6169 no commands, you can give that target empty commands by writing a
6170 semicolon (*note Defining Empty Commands: Empty Commands.).
6173 File: make.info, Node: Catalogue of Rules, Next: Implicit Variables, Prev: Using Implicit, Up: Implicit Rules
6175 Catalogue of Implicit Rules
6176 ===========================
6178 Here is a catalogue of predefined implicit rules which are always
6179 available unless the makefile explicitly overrides or cancels them.
6180 *Note Canceling Implicit Rules: Canceling Rules, for information on
6181 canceling or overriding an implicit rule. The `-r' or
6182 `--no-builtin-rules' option cancels all predefined rules.
6184 Not all of these rules will always be defined, even when the `-r'
6185 option is not given. Many of the predefined implicit rules are
6186 implemented in `make' as suffix rules, so which ones will be defined
6187 depends on the "suffix list" (the list of prerequisites of the special
6188 target `.SUFFIXES'). The default suffix list is: `.out', `.a', `.ln',
6189 `.o', `.c', `.cc', `.C', `.p', `.f', `.F', `.r', `.y', `.l', `.s',
6190 `.S', `.mod', `.sym', `.def', `.h', `.info', `.dvi', `.tex', `.texinfo',
6191 `.texi', `.txinfo', `.w', `.ch' `.web', `.sh', `.elc', `.el'. All of
6192 the implicit rules described below whose prerequisites have one of
6193 these suffixes are actually suffix rules. If you modify the suffix
6194 list, the only predefined suffix rules in effect will be those named by
6195 one or two of the suffixes that are on the list you specify; rules
6196 whose suffixes fail to be on the list are disabled. *Note
6197 Old-Fashioned Suffix Rules: Suffix Rules, for full details on suffix
6200 Compiling C programs
6201 `N.o' is made automatically from `N.c' with a command of the form
6202 `$(CC) -c $(CPPFLAGS) $(CFLAGS)'.
6204 Compiling C++ programs
6205 `N.o' is made automatically from `N.cc' or `N.C' with a command of
6206 the form `$(CXX) -c $(CPPFLAGS) $(CXXFLAGS)'. We encourage you to
6207 use the suffix `.cc' for C++ source files instead of `.C'.
6209 Compiling Pascal programs
6210 `N.o' is made automatically from `N.p' with the command `$(PC) -c
6213 Compiling Fortran and Ratfor programs
6214 `N.o' is made automatically from `N.r', `N.F' or `N.f' by running
6215 the Fortran compiler. The precise command used is as follows:
6218 `$(FC) -c $(FFLAGS)'.
6221 `$(FC) -c $(FFLAGS) $(CPPFLAGS)'.
6224 `$(FC) -c $(FFLAGS) $(RFLAGS)'.
6226 Preprocessing Fortran and Ratfor programs
6227 `N.f' is made automatically from `N.r' or `N.F'. This rule runs
6228 just the preprocessor to convert a Ratfor or preprocessable
6229 Fortran program into a strict Fortran program. The precise
6230 command used is as follows:
6233 `$(FC) -F $(CPPFLAGS) $(FFLAGS)'.
6236 `$(FC) -F $(FFLAGS) $(RFLAGS)'.
6238 Compiling Modula-2 programs
6239 `N.sym' is made from `N.def' with a command of the form `$(M2C)
6240 $(M2FLAGS) $(DEFFLAGS)'. `N.o' is made from `N.mod'; the form is:
6241 `$(M2C) $(M2FLAGS) $(MODFLAGS)'.
6243 Assembling and preprocessing assembler programs
6244 `N.o' is made automatically from `N.s' by running the assembler,
6245 `as'. The precise command is `$(AS) $(ASFLAGS)'.
6247 `N.s' is made automatically from `N.S' by running the C
6248 preprocessor, `cpp'. The precise command is `$(CPP) $(CPPFLAGS)'.
6250 Linking a single object file
6251 `N' is made automatically from `N.o' by running the linker
6252 (usually called `ld') via the C compiler. The precise command
6253 used is `$(CC) $(LDFLAGS) N.o $(LOADLIBES) $(LDLIBS)'.
6255 This rule does the right thing for a simple program with only one
6256 source file. It will also do the right thing if there are multiple
6257 object files (presumably coming from various other source files),
6258 one of which has a name matching that of the executable file.
6263 when `x.c', `y.c' and `z.c' all exist will execute:
6273 In more complicated cases, such as when there is no object file
6274 whose name derives from the executable file name, you must write
6275 an explicit command for linking.
6277 Each kind of file automatically made into `.o' object files will
6278 be automatically linked by using the compiler (`$(CC)', `$(FC)' or
6279 `$(PC)'; the C compiler `$(CC)' is used to assemble `.s' files)
6280 without the `-c' option. This could be done by using the `.o'
6281 object files as intermediates, but it is faster to do the
6282 compiling and linking in one step, so that's how it's done.
6285 `N.c' is made automatically from `N.y' by running Yacc with the
6286 command `$(YACC) $(YFLAGS)'.
6289 `N.c' is made automatically from `N.l' by running Lex. The actual
6290 command is `$(LEX) $(LFLAGS)'.
6292 Lex for Ratfor programs
6293 `N.r' is made automatically from `N.l' by running Lex. The actual
6294 command is `$(LEX) $(LFLAGS)'.
6296 The convention of using the same suffix `.l' for all Lex files
6297 regardless of whether they produce C code or Ratfor code makes it
6298 impossible for `make' to determine automatically which of the two
6299 languages you are using in any particular case. If `make' is
6300 called upon to remake an object file from a `.l' file, it must
6301 guess which compiler to use. It will guess the C compiler, because
6302 that is more common. If you are using Ratfor, make sure `make'
6303 knows this by mentioning `N.r' in the makefile. Or, if you are
6304 using Ratfor exclusively, with no C files, remove `.c' from the
6305 list of implicit rule suffixes with:
6308 .SUFFIXES: .o .r .f .l ...
6310 Making Lint Libraries from C, Yacc, or Lex programs
6311 `N.ln' is made from `N.c' by running `lint'. The precise command
6312 is `$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i'. The same command is
6313 used on the C code produced from `N.y' or `N.l'.
6316 `N.dvi' is made from `N.tex' with the command `$(TEX)'. `N.tex'
6317 is made from `N.web' with `$(WEAVE)', or from `N.w' (and from
6318 `N.ch' if it exists or can be made) with `$(CWEAVE)'. `N.p' is
6319 made from `N.web' with `$(TANGLE)' and `N.c' is made from `N.w'
6320 (and from `N.ch' if it exists or can be made) with `$(CTANGLE)'.
6323 `N.dvi' is made from `N.texinfo', `N.texi', or `N.txinfo', with
6324 the command `$(TEXI2DVI) $(TEXI2DVI_FLAGS)'. `N.info' is made from
6325 `N.texinfo', `N.texi', or `N.txinfo', with the command
6326 `$(MAKEINFO) $(MAKEINFO_FLAGS)'.
6329 Any file `N' is extracted if necessary from an RCS file named
6330 either `N,v' or `RCS/N,v'. The precise command used is
6331 `$(CO) $(COFLAGS)'. `N' will not be extracted from RCS if it
6332 already exists, even if the RCS file is newer. The rules for RCS
6333 are terminal (*note Match-Anything Pattern Rules: Match-Anything
6334 Rules.), so RCS files cannot be generated from another source;
6335 they must actually exist.
6338 Any file `N' is extracted if necessary from an SCCS file named
6339 either `s.N' or `SCCS/s.N'. The precise command used is
6340 `$(GET) $(GFLAGS)'. The rules for SCCS are terminal (*note
6341 Match-Anything Pattern Rules: Match-Anything Rules.), so SCCS
6342 files cannot be generated from another source; they must actually
6345 For the benefit of SCCS, a file `N' is copied from `N.sh' and made
6346 executable (by everyone). This is for shell scripts that are
6347 checked into SCCS. Since RCS preserves the execution permission
6348 of a file, you do not need to use this feature with RCS.
6350 We recommend that you avoid using of SCCS. RCS is widely held to
6351 be superior, and is also free. By choosing free software in place
6352 of comparable (or inferior) proprietary software, you support the
6353 free software movement.
6355 Usually, you want to change only the variables listed in the table
6356 above, which are documented in the following section.
6358 However, the commands in built-in implicit rules actually use
6359 variables such as `COMPILE.c', `LINK.p', and `PREPROCESS.S', whose
6360 values contain the commands listed above.
6362 `make' follows the convention that the rule to compile a `.X' source
6363 file uses the variable `COMPILE.X'. Similarly, the rule to produce an
6364 executable from a `.X' file uses `LINK.X'; and the rule to preprocess a
6365 `.X' file uses `PREPROCESS.X'.
6367 Every rule that produces an object file uses the variable
6368 `OUTPUT_OPTION'. `make' defines this variable either to contain `-o
6369 $@', or to be empty, depending on a compile-time option. You need the
6370 `-o' option to ensure that the output goes into the right file when the
6371 source file is in a different directory, as when using `VPATH' (*note
6372 Directory Search::). However, compilers on some systems do not accept
6373 a `-o' switch for object files. If you use such a system, and use
6374 `VPATH', some compilations will put their output in the wrong place. A
6375 possible workaround for this problem is to give `OUTPUT_OPTION' the
6376 value `; mv $*.o $@'.
6379 File: make.info, Node: Implicit Variables, Next: Chained Rules, Prev: Catalogue of Rules, Up: Implicit Rules
6381 Variables Used by Implicit Rules
6382 ================================
6384 The commands in built-in implicit rules make liberal use of certain
6385 predefined variables. You can alter these variables in the makefile,
6386 with arguments to `make', or in the environment to alter how the
6387 implicit rules work without redefining the rules themselves. You can
6388 cancel all variables used by implicit rules with the `-R' or
6389 `--no-builtin-variables' option.
6391 For example, the command used to compile a C source file actually
6392 says `$(CC) -c $(CFLAGS) $(CPPFLAGS)'. The default values of the
6393 variables used are `cc' and nothing, resulting in the command `cc -c'.
6394 By redefining `CC' to `ncc', you could cause `ncc' to be used for all C
6395 compilations performed by the implicit rule. By redefining `CFLAGS' to
6396 be `-g', you could pass the `-g' option to each compilation. _All_
6397 implicit rules that do C compilation use `$(CC)' to get the program
6398 name for the compiler and _all_ include `$(CFLAGS)' among the arguments
6399 given to the compiler.
6401 The variables used in implicit rules fall into two classes: those
6402 that are names of programs (like `CC') and those that contain arguments
6403 for the programs (like `CFLAGS'). (The "name of a program" may also
6404 contain some command arguments, but it must start with an actual
6405 executable program name.) If a variable value contains more than one
6406 argument, separate them with spaces.
6408 Here is a table of variables used as names of programs in built-in
6412 Archive-maintaining program; default `ar'.
6415 Program for doing assembly; default `as'.
6418 Program for compiling C programs; default `cc'.
6421 Program for compiling C++ programs; default `g++'.
6424 Program for extracting a file from RCS; default `co'.
6427 Program for running the C preprocessor, with results to standard
6428 output; default `$(CC) -E'.
6431 Program for compiling or preprocessing Fortran and Ratfor programs;
6435 Program for extracting a file from SCCS; default `get'.
6438 Program to use to turn Lex grammars into C programs or Ratfor
6439 programs; default `lex'.
6442 Program for compiling Pascal programs; default `pc'.
6445 Program to use to turn Yacc grammars into C programs; default
6449 Program to use to turn Yacc grammars into Ratfor programs; default
6453 Program to convert a Texinfo source file into an Info file; default
6457 Program to make TeX DVI files from TeX source; default `tex'.
6460 Program to make TeX DVI files from Texinfo source; default
6464 Program to translate Web into TeX; default `weave'.
6467 Program to translate C Web into TeX; default `cweave'.
6470 Program to translate Web into Pascal; default `tangle'.
6473 Program to translate C Web into C; default `ctangle'.
6476 Command to remove a file; default `rm -f'.
6478 Here is a table of variables whose values are additional arguments
6479 for the programs above. The default values for all of these is the
6480 empty string, unless otherwise noted.
6483 Flags to give the archive-maintaining program; default `rv'.
6486 Extra flags to give to the assembler (when explicitly invoked on a
6490 Extra flags to give to the C compiler.
6493 Extra flags to give to the C++ compiler.
6496 Extra flags to give to the RCS `co' program.
6499 Extra flags to give to the C preprocessor and programs that use it
6500 (the C and Fortran compilers).
6503 Extra flags to give to the Fortran compiler.
6506 Extra flags to give to the SCCS `get' program.
6509 Extra flags to give to compilers when they are supposed to invoke
6513 Extra flags to give to Lex.
6516 Extra flags to give to the Pascal compiler.
6519 Extra flags to give to the Fortran compiler for Ratfor programs.
6522 Extra flags to give to Yacc.
6525 File: make.info, Node: Chained Rules, Next: Pattern Rules, Prev: Implicit Variables, Up: Implicit Rules
6527 Chains of Implicit Rules
6528 ========================
6530 Sometimes a file can be made by a sequence of implicit rules. For
6531 example, a file `N.o' could be made from `N.y' by running first Yacc
6532 and then `cc'. Such a sequence is called a "chain".
6534 If the file `N.c' exists, or is mentioned in the makefile, no
6535 special searching is required: `make' finds that the object file can be
6536 made by C compilation from `N.c'; later on, when considering how to
6537 make `N.c', the rule for running Yacc is used. Ultimately both `N.c'
6538 and `N.o' are updated.
6540 However, even if `N.c' does not exist and is not mentioned, `make'
6541 knows how to envision it as the missing link between `N.o' and `N.y'!
6542 In this case, `N.c' is called an "intermediate file". Once `make' has
6543 decided to use the intermediate file, it is entered in the data base as
6544 if it had been mentioned in the makefile, along with the implicit rule
6545 that says how to create it.
6547 Intermediate files are remade using their rules just like all other
6548 files. But intermediate files are treated differently in two ways.
6550 The first difference is what happens if the intermediate file does
6551 not exist. If an ordinary file B does not exist, and `make' considers
6552 a target that depends on B, it invariably creates B and then updates
6553 the target from B. But if B is an intermediate file, then `make' can
6554 leave well enough alone. It won't bother updating B, or the ultimate
6555 target, unless some prerequisite of B is newer than that target or
6556 there is some other reason to update that target.
6558 The second difference is that if `make' _does_ create B in order to
6559 update something else, it deletes B later on after it is no longer
6560 needed. Therefore, an intermediate file which did not exist before
6561 `make' also does not exist after `make'. `make' reports the deletion
6562 to you by printing a `rm -f' command showing which file it is deleting.
6564 Ordinarily, a file cannot be intermediate if it is mentioned in the
6565 makefile as a target or prerequisite. However, you can explicitly mark
6566 a file as intermediate by listing it as a prerequisite of the special
6567 target `.INTERMEDIATE'. This takes effect even if the file is mentioned
6568 explicitly in some other way.
6570 You can prevent automatic deletion of an intermediate file by
6571 marking it as a "secondary" file. To do this, list it as a
6572 prerequisite of the special target `.SECONDARY'. When a file is
6573 secondary, `make' will not create the file merely because it does not
6574 already exist, but `make' does not automatically delete the file.
6575 Marking a file as secondary also marks it as intermediate.
6577 You can list the target pattern of an implicit rule (such as `%.o')
6578 as a prerequisite of the special target `.PRECIOUS' to preserve
6579 intermediate files made by implicit rules whose target patterns match
6580 that file's name; see *Note Interrupts::.
6582 A chain can involve more than two implicit rules. For example, it is
6583 possible to make a file `foo' from `RCS/foo.y,v' by running RCS, Yacc
6584 and `cc'. Then both `foo.y' and `foo.c' are intermediate files that
6585 are deleted at the end.
6587 No single implicit rule can appear more than once in a chain. This
6588 means that `make' will not even consider such a ridiculous thing as
6589 making `foo' from `foo.o.o' by running the linker twice. This
6590 constraint has the added benefit of preventing any infinite loop in the
6591 search for an implicit rule chain.
6593 There are some special implicit rules to optimize certain cases that
6594 would otherwise be handled by rule chains. For example, making `foo'
6595 from `foo.c' could be handled by compiling and linking with separate
6596 chained rules, using `foo.o' as an intermediate file. But what
6597 actually happens is that a special rule for this case does the
6598 compilation and linking with a single `cc' command. The optimized rule
6599 is used in preference to the step-by-step chain because it comes
6600 earlier in the ordering of rules.
6603 File: make.info, Node: Pattern Rules, Next: Last Resort, Prev: Chained Rules, Up: Implicit Rules
6605 Defining and Redefining Pattern Rules
6606 =====================================
6608 You define an implicit rule by writing a "pattern rule". A pattern
6609 rule looks like an ordinary rule, except that its target contains the
6610 character `%' (exactly one of them). The target is considered a
6611 pattern for matching file names; the `%' can match any nonempty
6612 substring, while other characters match only themselves. The
6613 prerequisites likewise use `%' to show how their names relate to the
6616 Thus, a pattern rule `%.o : %.c' says how to make any file `STEM.o'
6617 from another file `STEM.c'.
6619 Note that expansion using `%' in pattern rules occurs *after* any
6620 variable or function expansions, which take place when the makefile is
6621 read. *Note How to Use Variables: Using Variables, and *Note Functions
6622 for Transforming Text: Functions.
6626 * Pattern Intro:: An introduction to pattern rules.
6627 * Pattern Examples:: Examples of pattern rules.
6628 * Automatic Variables:: How to use automatic variables in the
6629 commands of implicit rules.
6630 * Pattern Match:: How patterns match.
6631 * Match-Anything Rules:: Precautions you should take prior to
6632 defining rules that can match any
6633 target file whatever.
6634 * Canceling Rules:: How to override or cancel built-in rules.
6637 File: make.info, Node: Pattern Intro, Next: Pattern Examples, Prev: Pattern Rules, Up: Pattern Rules
6639 Introduction to Pattern Rules
6640 -----------------------------
6642 A pattern rule contains the character `%' (exactly one of them) in the
6643 target; otherwise, it looks exactly like an ordinary rule. The target
6644 is a pattern for matching file names; the `%' matches any nonempty
6645 substring, while other characters match only themselves.
6647 For example, `%.c' as a pattern matches any file name that ends in
6648 `.c'. `s.%.c' as a pattern matches any file name that starts with
6649 `s.', ends in `.c' and is at least five characters long. (There must
6650 be at least one character to match the `%'.) The substring that the
6651 `%' matches is called the "stem".
6653 `%' in a prerequisite of a pattern rule stands for the same stem
6654 that was matched by the `%' in the target. In order for the pattern
6655 rule to apply, its target pattern must match the file name under
6656 consideration, and its prerequisite patterns must name files that exist
6657 or can be made. These files become prerequisites of the target.
6659 Thus, a rule of the form
6661 %.o : %.c ; COMMAND...
6663 specifies how to make a file `N.o', with another file `N.c' as its
6664 prerequisite, provided that `N.c' exists or can be made.
6666 There may also be prerequisites that do not use `%'; such a
6667 prerequisite attaches to every file made by this pattern rule. These
6668 unvarying prerequisites are useful occasionally.
6670 A pattern rule need not have any prerequisites that contain `%', or
6671 in fact any prerequisites at all. Such a rule is effectively a general
6672 wildcard. It provides a way to make any file that matches the target
6673 pattern. *Note Last Resort::.
6675 Pattern rules may have more than one target. Unlike normal rules,
6676 this does not act as many different rules with the same prerequisites
6677 and commands. If a pattern rule has multiple targets, `make' knows that
6678 the rule's commands are responsible for making all of the targets. The
6679 commands are executed only once to make all the targets. When searching
6680 for a pattern rule to match a target, the target patterns of a rule
6681 other than the one that matches the target in need of a rule are
6682 incidental: `make' worries only about giving commands and prerequisites
6683 to the file presently in question. However, when this file's commands
6684 are run, the other targets are marked as having been updated themselves.
6686 The order in which pattern rules appear in the makefile is important
6687 since this is the order in which they are considered. Of equally
6688 applicable rules, only the first one found is used. The rules you
6689 write take precedence over those that are built in. Note however, that
6690 a rule whose prerequisites actually exist or are mentioned always takes
6691 priority over a rule with prerequisites that must be made by chaining
6692 other implicit rules.
6695 File: make.info, Node: Pattern Examples, Next: Automatic Variables, Prev: Pattern Intro, Up: Pattern Rules
6697 Pattern Rule Examples
6698 ---------------------
6700 Here are some examples of pattern rules actually predefined in `make'.
6701 First, the rule that compiles `.c' files into `.o' files:
6704 $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
6706 defines a rule that can make any file `X.o' from `X.c'. The command
6707 uses the automatic variables `$@' and `$<' to substitute the names of
6708 the target file and the source file in each case where the rule applies
6709 (*note Automatic Variables::).
6711 Here is a second built-in rule:
6716 defines a rule that can make any file `X' whatsoever from a
6717 corresponding file `X,v' in the subdirectory `RCS'. Since the target
6718 is `%', this rule will apply to any file whatever, provided the
6719 appropriate prerequisite file exists. The double colon makes the rule
6720 "terminal", which means that its prerequisite may not be an intermediate
6721 file (*note Match-Anything Pattern Rules: Match-Anything Rules.).
6723 This pattern rule has two targets:
6725 %.tab.c %.tab.h: %.y
6728 This tells `make' that the command `bison -d X.y' will make both
6729 `X.tab.c' and `X.tab.h'. If the file `foo' depends on the files
6730 `parse.tab.o' and `scan.o' and the file `scan.o' depends on the file
6731 `parse.tab.h', when `parse.y' is changed, the command `bison -d parse.y'
6732 will be executed only once, and the prerequisites of both `parse.tab.o'
6733 and `scan.o' will be satisfied. (Presumably the file `parse.tab.o'
6734 will be recompiled from `parse.tab.c' and the file `scan.o' from
6735 `scan.c', while `foo' is linked from `parse.tab.o', `scan.o', and its
6736 other prerequisites, and it will execute happily ever after.)
6739 File: make.info, Node: Automatic Variables, Next: Pattern Match, Prev: Pattern Examples, Up: Pattern Rules
6744 Suppose you are writing a pattern rule to compile a `.c' file into a
6745 `.o' file: how do you write the `cc' command so that it operates on the
6746 right source file name? You cannot write the name in the command,
6747 because the name is different each time the implicit rule is applied.
6749 What you do is use a special feature of `make', the "automatic
6750 variables". These variables have values computed afresh for each rule
6751 that is executed, based on the target and prerequisites of the rule.
6752 In this example, you would use `$@' for the object file name and `$<'
6753 for the source file name.
6755 It's very important that you recognize the limited scope in which
6756 automatic variable values are available: they only have values within
6757 the command script. In particular, you cannot use them anywhere within
6758 the target or prerequisite lists of a rule; they have no value there
6759 and will expand to the empty string. A common mistake is attempting to
6760 use `$@' within the prerequisites list in a rule; this will not work.
6761 However, see below for information on the SysV-style `$$@' variables.
6763 Here is a table of automatic variables:
6766 The file name of the target of the rule. If the target is an
6767 archive member, then `$@' is the name of the archive file. In a
6768 pattern rule that has multiple targets (*note Introduction to
6769 Pattern Rules: Pattern Intro.), `$@' is the name of whichever
6770 target caused the rule's commands to be run.
6773 The target member name, when the target is an archive member.
6774 *Note Archives::. For example, if the target is `foo.a(bar.o)'
6775 then `$%' is `bar.o' and `$@' is `foo.a'. `$%' is empty when the
6776 target is not an archive member.
6779 The name of the first prerequisite. If the target got its
6780 commands from an implicit rule, this will be the first
6781 prerequisite added by the implicit rule (*note Implicit Rules::).
6784 The names of all the prerequisites that are newer than the target,
6785 with spaces between them. For prerequisites which are archive
6786 members, only the member named is used (*note Archives::).
6789 The names of all the prerequisites, with spaces between them. For
6790 prerequisites which are archive members, only the member named is
6791 used (*note Archives::). A target has only one prerequisite on
6792 each other file it depends on, no matter how many times each file
6793 is listed as a prerequisite. So if you list a prerequisite more
6794 than once for a target, the value of `$^' contains just one copy
6798 This is like `$^', but prerequisites listed more than once are
6799 duplicated in the order they were listed in the makefile. This is
6800 primarily useful for use in linking commands where it is
6801 meaningful to repeat library file names in a particular order.
6804 The stem with which an implicit rule matches (*note How Patterns
6805 Match: Pattern Match.). If the target is `dir/a.foo.b' and the
6806 target pattern is `a.%.b' then the stem is `dir/foo'. The stem is
6807 useful for constructing names of related files.
6809 In a static pattern rule, the stem is part of the file name that
6810 matched the `%' in the target pattern.
6812 In an explicit rule, there is no stem; so `$*' cannot be determined
6813 in that way. Instead, if the target name ends with a recognized
6814 suffix (*note Old-Fashioned Suffix Rules: Suffix Rules.), `$*' is
6815 set to the target name minus the suffix. For example, if the
6816 target name is `foo.c', then `$*' is set to `foo', since `.c' is a
6817 suffix. GNU `make' does this bizarre thing only for compatibility
6818 with other implementations of `make'. You should generally avoid
6819 using `$*' except in implicit rules or static pattern rules.
6821 If the target name in an explicit rule does not end with a
6822 recognized suffix, `$*' is set to the empty string for that rule.
6824 `$?' is useful even in explicit rules when you wish to operate on
6825 only the prerequisites that have changed. For example, suppose that an
6826 archive named `lib' is supposed to contain copies of several object
6827 files. This rule copies just the changed object files into the archive:
6829 lib: foo.o bar.o lose.o win.o
6832 Of the variables listed above, four have values that are single file
6833 names, and three have values that are lists of file names. These seven
6834 have variants that get just the file's directory name or just the file
6835 name within the directory. The variant variables' names are formed by
6836 appending `D' or `F', respectively. These variants are semi-obsolete
6837 in GNU `make' since the functions `dir' and `notdir' can be used to get
6838 a similar effect (*note Functions for File Names: File Name
6839 Functions.). Note, however, that the `D' variants all omit the
6840 trailing slash which always appears in the output of the `dir'
6841 function. Here is a table of the variants:
6844 The directory part of the file name of the target, with the
6845 trailing slash removed. If the value of `$@' is `dir/foo.o' then
6846 `$(@D)' is `dir'. This value is `.' if `$@' does not contain a
6850 The file-within-directory part of the file name of the target. If
6851 the value of `$@' is `dir/foo.o' then `$(@F)' is `foo.o'. `$(@F)'
6852 is equivalent to `$(notdir $@)'.
6856 The directory part and the file-within-directory part of the stem;
6857 `dir' and `foo' in this example.
6861 The directory part and the file-within-directory part of the target
6862 archive member name. This makes sense only for archive member
6863 targets of the form `ARCHIVE(MEMBER)' and is useful only when
6864 MEMBER may contain a directory name. (*Note Archive Members as
6865 Targets: Archive Members.)
6869 The directory part and the file-within-directory part of the first
6874 Lists of the directory parts and the file-within-directory parts
6875 of all prerequisites.
6879 Lists of the directory parts and the file-within-directory parts
6880 of all prerequisites, including multiple instances of duplicated
6885 Lists of the directory parts and the file-within-directory parts of
6886 all prerequisites that are newer than the target.
6888 Note that we use a special stylistic convention when we talk about
6889 these automatic variables; we write "the value of `$<'", rather than
6890 "the variable `<'" as we would write for ordinary variables such as
6891 `objects' and `CFLAGS'. We think this convention looks more natural in
6892 this special case. Please do not assume it has a deep significance;
6893 `$<' refers to the variable named `<' just as `$(CFLAGS)' refers to the
6894 variable named `CFLAGS'. You could just as well use `$(<)' in place of
6897 GNU `make' provides support for the SysV `make' feature that allows
6898 special variable references `$$@', `$$(@D)', and `$$(@F)' (note the
6899 required double-"$"!) to appear with the _prerequisites list_ (normal
6900 automatic variables are available only within a command script). When
6901 appearing in a prerequisites list, these variables are expanded to the
6902 name of the target, the directory component of the target, and the file
6903 component of the target, respectively.
6905 Note that these variables are available only within explicit and
6906 static pattern (*note Static Pattern Rules: Static Pattern.) rules;
6907 they have no special significance within implicit (suffix or pattern)
6908 rules. Also note that while SysV `make' actually expands its entire
6909 prerequisite list _twice_, GNU `make' does not behave this way: instead
6910 it simply expands these special variables without re-expanding any
6911 other part of the prerequisites list.
6913 This somewhat bizarre feature is included only to provide some
6914 compatibility with SysV makefiles. In a native GNU `make' file there
6915 are other ways to accomplish the same results. This feature is
6916 disabled if the special pseudo target `.POSIX' is defined.
6919 File: make.info, Node: Pattern Match, Next: Match-Anything Rules, Prev: Automatic Variables, Up: Pattern Rules
6924 A target pattern is composed of a `%' between a prefix and a suffix,
6925 either or both of which may be empty. The pattern matches a file name
6926 only if the file name starts with the prefix and ends with the suffix,
6927 without overlap. The text between the prefix and the suffix is called
6928 the "stem". Thus, when the pattern `%.o' matches the file name
6929 `test.o', the stem is `test'. The pattern rule prerequisites are
6930 turned into actual file names by substituting the stem for the character
6931 `%'. Thus, if in the same example one of the prerequisites is written
6932 as `%.c', it expands to `test.c'.
6934 When the target pattern does not contain a slash (and it usually does
6935 not), directory names in the file names are removed from the file name
6936 before it is compared with the target prefix and suffix. After the
6937 comparison of the file name to the target pattern, the directory names,
6938 along with the slash that ends them, are added on to the prerequisite
6939 file names generated from the pattern rule's prerequisite patterns and
6940 the file name. The directories are ignored only for the purpose of
6941 finding an implicit rule to use, not in the application of that rule.
6942 Thus, `e%t' matches the file name `src/eat', with `src/a' as the stem.
6943 When prerequisites are turned into file names, the directories from the
6944 stem are added at the front, while the rest of the stem is substituted
6945 for the `%'. The stem `src/a' with a prerequisite pattern `c%r' gives
6946 the file name `src/car'.
6949 File: make.info, Node: Match-Anything Rules, Next: Canceling Rules, Prev: Pattern Match, Up: Pattern Rules
6951 Match-Anything Pattern Rules
6952 ----------------------------
6954 When a pattern rule's target is just `%', it matches any file name
6955 whatever. We call these rules "match-anything" rules. They are very
6956 useful, but it can take a lot of time for `make' to think about them,
6957 because it must consider every such rule for each file name listed
6958 either as a target or as a prerequisite.
6960 Suppose the makefile mentions `foo.c'. For this target, `make'
6961 would have to consider making it by linking an object file `foo.c.o',
6962 or by C compilation-and-linking in one step from `foo.c.c', or by
6963 Pascal compilation-and-linking from `foo.c.p', and many other
6966 We know these possibilities are ridiculous since `foo.c' is a C
6967 source file, not an executable. If `make' did consider these
6968 possibilities, it would ultimately reject them, because files such as
6969 `foo.c.o' and `foo.c.p' would not exist. But these possibilities are so
6970 numerous that `make' would run very slowly if it had to consider them.
6972 To gain speed, we have put various constraints on the way `make'
6973 considers match-anything rules. There are two different constraints
6974 that can be applied, and each time you define a match-anything rule you
6975 must choose one or the other for that rule.
6977 One choice is to mark the match-anything rule as "terminal" by
6978 defining it with a double colon. When a rule is terminal, it does not
6979 apply unless its prerequisites actually exist. Prerequisites that
6980 could be made with other implicit rules are not good enough. In other
6981 words, no further chaining is allowed beyond a terminal rule.
6983 For example, the built-in implicit rules for extracting sources from
6984 RCS and SCCS files are terminal; as a result, if the file `foo.c,v' does
6985 not exist, `make' will not even consider trying to make it as an
6986 intermediate file from `foo.c,v.o' or from `RCS/SCCS/s.foo.c,v'. RCS
6987 and SCCS files are generally ultimate source files, which should not be
6988 remade from any other files; therefore, `make' can save time by not
6989 looking for ways to remake them.
6991 If you do not mark the match-anything rule as terminal, then it is
6992 nonterminal. A nonterminal match-anything rule cannot apply to a file
6993 name that indicates a specific type of data. A file name indicates a
6994 specific type of data if some non-match-anything implicit rule target
6997 For example, the file name `foo.c' matches the target for the pattern
6998 rule `%.c : %.y' (the rule to run Yacc). Regardless of whether this
6999 rule is actually applicable (which happens only if there is a file
7000 `foo.y'), the fact that its target matches is enough to prevent
7001 consideration of any nonterminal match-anything rules for the file
7002 `foo.c'. Thus, `make' will not even consider trying to make `foo.c' as
7003 an executable file from `foo.c.o', `foo.c.c', `foo.c.p', etc.
7005 The motivation for this constraint is that nonterminal match-anything
7006 rules are used for making files containing specific types of data (such
7007 as executable files) and a file name with a recognized suffix indicates
7008 some other specific type of data (such as a C source file).
7010 Special built-in dummy pattern rules are provided solely to recognize
7011 certain file names so that nonterminal match-anything rules will not be
7012 considered. These dummy rules have no prerequisites and no commands,
7013 and they are ignored for all other purposes. For example, the built-in
7018 exists to make sure that Pascal source files such as `foo.p' match a
7019 specific target pattern and thereby prevent time from being wasted
7020 looking for `foo.p.o' or `foo.p.c'.
7022 Dummy pattern rules such as the one for `%.p' are made for every
7023 suffix listed as valid for use in suffix rules (*note Old-Fashioned
7024 Suffix Rules: Suffix Rules.).
7027 File: make.info, Node: Canceling Rules, Prev: Match-Anything Rules, Up: Pattern Rules
7029 Canceling Implicit Rules
7030 ------------------------
7032 You can override a built-in implicit rule (or one you have defined
7033 yourself) by defining a new pattern rule with the same target and
7034 prerequisites, but different commands. When the new rule is defined,
7035 the built-in one is replaced. The new rule's position in the sequence
7036 of implicit rules is determined by where you write the new rule.
7038 You can cancel a built-in implicit rule by defining a pattern rule
7039 with the same target and prerequisites, but no commands. For example,
7040 the following would cancel the rule that runs the assembler:
7045 File: make.info, Node: Last Resort, Next: Suffix Rules, Prev: Pattern Rules, Up: Implicit Rules
7047 Defining Last-Resort Default Rules
7048 ==================================
7050 You can define a last-resort implicit rule by writing a terminal
7051 match-anything pattern rule with no prerequisites (*note Match-Anything
7052 Rules::). This is just like any other pattern rule; the only thing
7053 special about it is that it will match any target. So such a rule's
7054 commands are used for all targets and prerequisites that have no
7055 commands of their own and for which no other implicit rule applies.
7057 For example, when testing a makefile, you might not care if the
7058 source files contain real data, only that they exist. Then you might
7064 to cause all the source files needed (as prerequisites) to be created
7067 You can instead define commands to be used for targets for which
7068 there are no rules at all, even ones which don't specify commands. You
7069 do this by writing a rule for the target `.DEFAULT'. Such a rule's
7070 commands are used for all prerequisites which do not appear as targets
7071 in any explicit rule, and for which no implicit rule applies.
7072 Naturally, there is no `.DEFAULT' rule unless you write one.
7074 If you use `.DEFAULT' with no commands or prerequisites:
7078 the commands previously stored for `.DEFAULT' are cleared. Then `make'
7079 acts as if you had never defined `.DEFAULT' at all.
7081 If you do not want a target to get the commands from a match-anything
7082 pattern rule or `.DEFAULT', but you also do not want any commands to be
7083 run for the target, you can give it empty commands (*note Defining
7084 Empty Commands: Empty Commands.).
7086 You can use a last-resort rule to override part of another makefile.
7087 *Note Overriding Part of Another Makefile: Overriding Makefiles.
7090 File: make.info, Node: Suffix Rules, Next: Implicit Rule Search, Prev: Last Resort, Up: Implicit Rules
7092 Old-Fashioned Suffix Rules
7093 ==========================
7095 "Suffix rules" are the old-fashioned way of defining implicit rules for
7096 `make'. Suffix rules are obsolete because pattern rules are more
7097 general and clearer. They are supported in GNU `make' for
7098 compatibility with old makefiles. They come in two kinds:
7099 "double-suffix" and "single-suffix".
7101 A double-suffix rule is defined by a pair of suffixes: the target
7102 suffix and the source suffix. It matches any file whose name ends with
7103 the target suffix. The corresponding implicit prerequisite is made by
7104 replacing the target suffix with the source suffix in the file name. A
7105 two-suffix rule whose target and source suffixes are `.o' and `.c' is
7106 equivalent to the pattern rule `%.o : %.c'.
7108 A single-suffix rule is defined by a single suffix, which is the
7109 source suffix. It matches any file name, and the corresponding implicit
7110 prerequisite name is made by appending the source suffix. A
7111 single-suffix rule whose source suffix is `.c' is equivalent to the
7112 pattern rule `% : %.c'.
7114 Suffix rule definitions are recognized by comparing each rule's
7115 target against a defined list of known suffixes. When `make' sees a
7116 rule whose target is a known suffix, this rule is considered a
7117 single-suffix rule. When `make' sees a rule whose target is two known
7118 suffixes concatenated, this rule is taken as a double-suffix rule.
7120 For example, `.c' and `.o' are both on the default list of known
7121 suffixes. Therefore, if you define a rule whose target is `.c.o',
7122 `make' takes it to be a double-suffix rule with source suffix `.c' and
7123 target suffix `.o'. Here is the old-fashioned way to define the rule
7124 for compiling a C source file:
7127 $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $<
7129 Suffix rules cannot have any prerequisites of their own. If they
7130 have any, they are treated as normal files with funny names, not as
7131 suffix rules. Thus, the rule:
7134 $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $<
7136 tells how to make the file `.c.o' from the prerequisite file `foo.h',
7137 and is not at all like the pattern rule:
7140 $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $<
7142 which tells how to make `.o' files from `.c' files, and makes all `.o'
7143 files using this pattern rule also depend on `foo.h'.
7145 Suffix rules with no commands are also meaningless. They do not
7146 remove previous rules as do pattern rules with no commands (*note
7147 Canceling Implicit Rules: Canceling Rules.). They simply enter the
7148 suffix or pair of suffixes concatenated as a target in the data base.
7150 The known suffixes are simply the names of the prerequisites of the
7151 special target `.SUFFIXES'. You can add your own suffixes by writing a
7152 rule for `.SUFFIXES' that adds more prerequisites, as in:
7154 .SUFFIXES: .hack .win
7156 which adds `.hack' and `.win' to the end of the list of suffixes.
7158 If you wish to eliminate the default known suffixes instead of just
7159 adding to them, write a rule for `.SUFFIXES' with no prerequisites. By
7160 special dispensation, this eliminates all existing prerequisites of
7161 `.SUFFIXES'. You can then write another rule to add the suffixes you
7164 .SUFFIXES: # Delete the default suffixes
7165 .SUFFIXES: .c .o .h # Define our suffix list
7167 The `-r' or `--no-builtin-rules' flag causes the default list of
7168 suffixes to be empty.
7170 The variable `SUFFIXES' is defined to the default list of suffixes
7171 before `make' reads any makefiles. You can change the list of suffixes
7172 with a rule for the special target `.SUFFIXES', but that does not alter