VirtualBox

source: kBuild/vendor/gnumake/3.81/doc/make.info-1@ 1158

Last change on this file since 1158 was 501, checked in by bird, 18 years ago

Load make-3.81/ into vendor/gnumake/current.

  • Property svn:eol-style set to native
File size: 294.2 KB
Line 
1This is make.info, produced by makeinfo version 4.8 from make.texi.
2
3 This file documents the GNU `make' utility, which determines
4automatically which pieces of a large program need to be recompiled,
5and issues the commands to recompile them.
6
7 This is Edition 0.70, last updated 1 April 2006, of `The GNU Make
8Manual', for GNU `make' version 3.81.
9
10 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
111997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free Software
12Foundation, Inc.
13
14 Permission is granted to copy, distribute and/or modify this
15 document under the terms of the GNU Free Documentation License,
16 Version 1.2 or any later version published by the Free Software
17 Foundation; with no Invariant Sections, with the Front-Cover Texts
18 being "A GNU Manual," and with the Back-Cover Texts as in (a)
19 below. A copy of the license is included in the section entitled
20 "GNU Free Documentation License."
21
22 (a) The FSF's Back-Cover Text is: "You have freedom to copy and
23 modify this GNU Manual, like GNU software. Copies published by
24 the Free Software Foundation raise funds for GNU development."
25
26INFO-DIR-SECTION GNU Packages
27START-INFO-DIR-ENTRY
28* Make: (make). Remake files automatically.
29END-INFO-DIR-ENTRY
30
31
32File: make.info, Node: Top, Next: Overview, Prev: (dir), Up: (dir)
33
34GNU `make'
35**********
36
37This file documents the GNU `make' utility, which determines
38automatically which pieces of a large program need to be recompiled,
39and issues the commands to recompile them.
40
41 This is Edition 0.70, last updated 1 April 2006, of `The GNU Make
42Manual', for GNU `make' version 3.81.
43
44 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
451997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free Software
46Foundation, Inc.
47
48 Permission is granted to copy, distribute and/or modify this
49 document under the terms of the GNU Free Documentation License,
50 Version 1.2 or any later version published by the Free Software
51 Foundation; with no Invariant Sections, with the Front-Cover Texts
52 being "A GNU Manual," and with the Back-Cover Texts as in (a)
53 below. A copy of the license is included in the section entitled
54 "GNU Free Documentation License."
55
56 (a) The FSF's Back-Cover Text is: "You have freedom to copy and
57 modify this GNU Manual, like GNU software. Copies published by
58 the Free Software Foundation raise funds for GNU development."
59
60* Menu:
61
62* Overview:: Overview of `make'.
63* Introduction:: An introduction to `make'.
64* Makefiles:: Makefiles tell `make' what to do.
65* Rules:: Rules describe when a file must be remade.
66* Commands:: Commands say how to remake a file.
67* Using Variables:: You can use variables to avoid repetition.
68* Conditionals:: Use or ignore parts of the makefile based
69 on the values of variables.
70* Functions:: Many powerful ways to manipulate text.
71* Invoking make: Running. How to invoke `make' on the command line.
72* Implicit Rules:: Use implicit rules to treat many files alike,
73 based on their file names.
74* Archives:: How `make' can update library archives.
75* Features:: Features GNU `make' has over other `make's.
76* Missing:: What GNU `make' lacks from other `make's.
77* Makefile Conventions:: Conventions for writing makefiles for
78 GNU programs.
79* Quick Reference:: A quick reference for experienced users.
80* Error Messages:: A list of common errors generated by `make'.
81* Complex Makefile:: A real example of a straightforward,
82 but nontrivial, makefile.
83
84* GNU Free Documentation License:: License for copying this manual
85* Concept Index:: Index of Concepts
86* Name Index:: Index of Functions, Variables, & Directives
87
88 --- The Detailed Node Listing ---
89
90Overview of `make'
91
92* Preparing:: Preparing and Running Make
93* Reading:: On Reading this Text
94* Bugs:: Problems and Bugs
95
96An Introduction to Makefiles
97
98* Rule Introduction:: What a rule looks like.
99* Simple Makefile:: A Simple Makefile
100* How Make Works:: How `make' Processes This Makefile
101* Variables Simplify:: Variables Make Makefiles Simpler
102* make Deduces:: Letting `make' Deduce the Commands
103* Combine By Prerequisite:: Another Style of Makefile
104* Cleanup:: Rules for Cleaning the Directory
105
106Writing Makefiles
107
108* Makefile Contents:: What makefiles contain.
109* Makefile Names:: How to name your makefile.
110* Include:: How one makefile can use another makefile.
111* MAKEFILES Variable:: The environment can specify extra makefiles.
112* MAKEFILE_LIST Variable:: Discover which makefiles have been read.
113* Special Variables:: Other special variables.
114* Remaking Makefiles:: How makefiles get remade.
115* Overriding Makefiles:: How to override part of one makefile
116 with another makefile.
117* Reading Makefiles:: How makefiles are parsed.
118* Secondary Expansion:: How and when secondary expansion is performed.
119
120Writing Rules
121
122* Rule Example:: An example explained.
123* Rule Syntax:: General syntax explained.
124* Prerequisite Types:: There are two types of prerequisites.
125* Wildcards:: Using wildcard characters such as `*'.
126* Directory Search:: Searching other directories for source files.
127* Phony Targets:: Using a target that is not a real file's name.
128* Force Targets:: You can use a target without commands
129 or prerequisites to mark other targets
130 as phony.
131* Empty Targets:: When only the date matters and the
132 files are empty.
133* Special Targets:: Targets with special built-in meanings.
134* Multiple Targets:: When to make use of several targets in a rule.
135* Multiple Rules:: How to use several rules with the same target.
136* Static Pattern:: Static pattern rules apply to multiple targets
137 and can vary the prerequisites according to
138 the target name.
139* Double-Colon:: How to use a special kind of rule to allow
140 several independent rules for one target.
141* Automatic Prerequisites:: How to automatically generate rules giving
142 prerequisites from source files themselves.
143
144Using Wildcard Characters in File Names
145
146* Wildcard Examples:: Several examples
147* Wildcard Pitfall:: Problems to avoid.
148* Wildcard Function:: How to cause wildcard expansion where
149 it does not normally take place.
150
151Searching Directories for Prerequisites
152
153* General Search:: Specifying a search path that applies
154 to every prerequisite.
155* Selective Search:: Specifying a search path
156 for a specified class of names.
157* Search Algorithm:: When and how search paths are applied.
158* Commands/Search:: How to write shell commands that work together
159 with search paths.
160* Implicit/Search:: How search paths affect implicit rules.
161* Libraries/Search:: Directory search for link libraries.
162
163Static Pattern Rules
164
165* Static Usage:: The syntax of static pattern rules.
166* Static versus Implicit:: When are they better than implicit rules?
167
168Writing the Commands in Rules
169
170* Command Syntax:: Command syntax features and pitfalls.
171* Echoing:: How to control when commands are echoed.
172* Execution:: How commands are executed.
173* Parallel:: How commands can be executed in parallel.
174* Errors:: What happens after a command execution error.
175* Interrupts:: What happens when a command is interrupted.
176* Recursion:: Invoking `make' from makefiles.
177* Sequences:: Defining canned sequences of commands.
178* Empty Commands:: Defining useful, do-nothing commands.
179
180Command Syntax
181
182* Splitting Lines:: Breaking long command lines for readability.
183* Variables in Commands:: Using `make' variables in commands.
184
185Command Execution
186
187* Choosing the Shell:: How `make' chooses the shell used
188 to run commands.
189
190Recursive Use of `make'
191
192* MAKE Variable:: The special effects of using `$(MAKE)'.
193* Variables/Recursion:: How to communicate variables to a sub-`make'.
194* Options/Recursion:: How to communicate options to a sub-`make'.
195* -w Option:: How the `-w' or `--print-directory' option
196 helps debug use of recursive `make' commands.
197
198How to Use Variables
199
200* Reference:: How to use the value of a variable.
201* Flavors:: Variables come in two flavors.
202* Advanced:: Advanced features for referencing a variable.
203* Values:: All the ways variables get their values.
204* Setting:: How to set a variable in the makefile.
205* Appending:: How to append more text to the old value
206 of a variable.
207* Override Directive:: How to set a variable in the makefile even if
208 the user has set it with a command argument.
209* Defining:: An alternate way to set a variable
210 to a verbatim string.
211* Environment:: Variable values can come from the environment.
212* Target-specific:: Variable values can be defined on a per-target
213 basis.
214* Pattern-specific:: Target-specific variable values can be applied
215 to a group of targets that match a pattern.
216
217Advanced Features for Reference to Variables
218
219* Substitution Refs:: Referencing a variable with
220 substitutions on the value.
221* Computed Names:: Computing the name of the variable to refer to.
222
223Conditional Parts of Makefiles
224
225* Conditional Example:: Example of a conditional
226* Conditional Syntax:: The syntax of conditionals.
227* Testing Flags:: Conditionals that test flags.
228
229Functions for Transforming Text
230
231* Syntax of Functions:: How to write a function call.
232* Text Functions:: General-purpose text manipulation functions.
233* File Name Functions:: Functions for manipulating file names.
234* Conditional Functions:: Functions that implement conditions.
235* Foreach Function:: Repeat some text with controlled variation.
236* Call Function:: Expand a user-defined function.
237* Value Function:: Return the un-expanded value of a variable.
238* Eval Function:: Evaluate the arguments as makefile syntax.
239* Origin Function:: Find where a variable got its value.
240* Flavor Function:: Find out the flavor of a variable.
241* Shell Function:: Substitute the output of a shell command.
242* Make Control Functions:: Functions that control how make runs.
243
244How to Run `make'
245
246* Makefile Arguments:: How to specify which makefile to use.
247* Goals:: How to use goal arguments to specify which
248 parts of the makefile to use.
249* Instead of Execution:: How to use mode flags to specify what
250 kind of thing to do with the commands
251 in the makefile other than simply
252 execute them.
253* Avoiding Compilation:: How to avoid recompiling certain files.
254* Overriding:: How to override a variable to specify
255 an alternate compiler and other things.
256* Testing:: How to proceed past some errors, to
257 test compilation.
258* Options Summary:: Summary of Options
259
260Using Implicit Rules
261
262* Using Implicit:: How to use an existing implicit rule
263 to get the commands for updating a file.
264* Catalogue of Rules:: A list of built-in implicit rules.
265* Implicit Variables:: How to change what predefined rules do.
266* Chained Rules:: How to use a chain of implicit rules.
267* Pattern Rules:: How to define new implicit rules.
268* Last Resort:: How to define commands for rules which
269 cannot find any.
270* Suffix Rules:: The old-fashioned style of implicit rule.
271* Implicit Rule Search:: The precise algorithm for applying
272 implicit rules.
273
274Defining and Redefining Pattern Rules
275
276* Pattern Intro:: An introduction to pattern rules.
277* Pattern Examples:: Examples of pattern rules.
278* Automatic Variables:: How to use automatic variables in the
279 commands of implicit rules.
280* Pattern Match:: How patterns match.
281* Match-Anything Rules:: Precautions you should take prior to
282 defining rules that can match any
283 target file whatever.
284* Canceling Rules:: How to override or cancel built-in rules.
285
286Using `make' to Update Archive Files
287
288* Archive Members:: Archive members as targets.
289* Archive Update:: The implicit rule for archive member targets.
290* Archive Pitfalls:: Dangers to watch out for when using archives.
291* Archive Suffix Rules:: You can write a special kind of suffix rule
292 for updating archives.
293
294Implicit Rule for Archive Member Targets
295
296* Archive Symbols:: How to update archive symbol directories.
297
298
299File: make.info, Node: Overview, Next: Introduction, Prev: Top, Up: Top
300
3011 Overview of `make'
302********************
303
304The `make' utility automatically determines which pieces of a large
305program need to be recompiled, and issues commands to recompile them.
306This manual describes GNU `make', which was implemented by Richard
307Stallman and Roland McGrath. Development since Version 3.76 has been
308handled by Paul D. Smith.
309
310 GNU `make' conforms to section 6.2 of `IEEE Standard 1003.2-1992'
311(POSIX.2).
312
313 Our examples show C programs, since they are most common, but you
314can use `make' with any programming language whose compiler can be run
315with a shell command. Indeed, `make' is not limited to programs. You
316can use it to describe any task where some files must be updated
317automatically from others whenever the others change.
318
319* Menu:
320
321* Preparing:: Preparing and Running Make
322* Reading:: On Reading this Text
323* Bugs:: Problems and Bugs
324
325
326File: make.info, Node: Preparing, Next: Reading, Prev: Overview, Up: Overview
327
328Preparing and Running Make
329==========================
330
331 To prepare to use `make', you must write a file called the
332"makefile" that describes the relationships among files in your program
333and provides commands for updating each file. In a program, typically,
334the executable file is updated from object files, which are in turn
335made by compiling source files.
336
337 Once a suitable makefile exists, each time you change some source
338files, this simple shell command:
339
340 make
341
342suffices to perform all necessary recompilations. The `make' program
343uses the makefile data base and the last-modification times of the
344files to decide which of the files need to be updated. For each of
345those files, it issues the commands recorded in the data base.
346
347 You can provide command line arguments to `make' to control which
348files should be recompiled, or how. *Note How to Run `make': Running.
349
350
351File: make.info, Node: Reading, Next: Bugs, Prev: Preparing, Up: Overview
352
3531.1 How to Read This Manual
354===========================
355
356If you are new to `make', or are looking for a general introduction,
357read the first few sections of each chapter, skipping the later
358sections. In each chapter, the first few sections contain introductory
359or general information and the later sections contain specialized or
360technical information. The exception is the second chapter, *Note An
361Introduction to Makefiles: Introduction, all of which is introductory.
362
363 If you are familiar with other `make' programs, see *Note Features
364of GNU `make': Features, which lists the enhancements GNU `make' has,
365and *Note Incompatibilities and Missing Features: Missing, which
366explains the few things GNU `make' lacks that others have.
367
368 For a quick summary, see *Note Options Summary::, *Note Quick
369Reference::, and *Note Special Targets::.
370
371
372File: make.info, Node: Bugs, Prev: Reading, Up: Overview
373
3741.2 Problems and Bugs
375=====================
376
377If you have problems with GNU `make' or think you've found a bug,
378please report it to the developers; we cannot promise to do anything but
379we might well want to fix it.
380
381 Before reporting a bug, make sure you've actually found a real bug.
382Carefully reread the documentation and see if it really says you can do
383what you're trying to do. If it's not clear whether you should be able
384to do something or not, report that too; it's a bug in the
385documentation!
386
387 Before reporting a bug or trying to fix it yourself, try to isolate
388it to the smallest possible makefile that reproduces the problem. Then
389send us the makefile and the exact results `make' gave you, including
390any error or warning messages. Please don't paraphrase these messages:
391it's best to cut and paste them into your report. When generating this
392small makefile, be sure to not use any non-free or unusual tools in
393your commands: you can almost always emulate what such a tool would do
394with simple shell commands. Finally, be sure to explain what you
395expected to occur; this will help us decide whether the problem was
396really in the documentation.
397
398 Once you have a precise problem you can report it in one of two ways.
399Either send electronic mail to:
400
401 [email protected]
402
403or use our Web-based project management tool, at:
404
405 http://savannah.gnu.org/projects/make/
406
407In addition to the information above, please be careful to include the
408version number of `make' you are using. You can get this information
409with the command `make --version'. Be sure also to include the type of
410machine and operating system you are using. One way to obtain this
411information is by looking at the final lines of output from the command
412`make --help'.
413
414
415File: make.info, Node: Introduction, Next: Makefiles, Prev: Overview, Up: Top
416
4172 An Introduction to Makefiles
418******************************
419
420You need a file called a "makefile" to tell `make' what to do. Most
421often, the makefile tells `make' how to compile and link a program.
422
423 In this chapter, we will discuss a simple makefile that describes
424how to compile and link a text editor which consists of eight C source
425files and three header files. The makefile can also tell `make' how to
426run miscellaneous commands when explicitly asked (for example, to remove
427certain files as a clean-up operation). To see a more complex example
428of a makefile, see *Note Complex Makefile::.
429
430 When `make' recompiles the editor, each changed C source file must
431be recompiled. If a header file has changed, each C source file that
432includes the header file must be recompiled to be safe. Each
433compilation produces an object file corresponding to the source file.
434Finally, if any source file has been recompiled, all the object files,
435whether newly made or saved from previous compilations, must be linked
436together to produce the new executable editor.
437
438* Menu:
439
440* Rule Introduction:: What a rule looks like.
441* Simple Makefile:: A Simple Makefile
442* How Make Works:: How `make' Processes This Makefile
443* Variables Simplify:: Variables Make Makefiles Simpler
444* make Deduces:: Letting `make' Deduce the Commands
445* Combine By Prerequisite:: Another Style of Makefile
446* Cleanup:: Rules for Cleaning the Directory
447
448
449File: make.info, Node: Rule Introduction, Next: Simple Makefile, Prev: Introduction, Up: Introduction
450
4512.1 What a Rule Looks Like
452==========================
453
454A simple makefile consists of "rules" with the following shape:
455
456 TARGET ... : PREREQUISITES ...
457 COMMAND
458 ...
459 ...
460
461 A "target" is usually the name of a file that is generated by a
462program; examples of targets are executable or object files. A target
463can also be the name of an action to carry out, such as `clean' (*note
464Phony Targets::).
465
466 A "prerequisite" is a file that is used as input to create the
467target. A target often depends on several files.
468
469 A "command" is an action that `make' carries out. A rule may have
470more than one command, each on its own line. *Please note:* you need
471to put a tab character at the beginning of every command line! This is
472an obscurity that catches the unwary.
473
474 Usually a command is in a rule with prerequisites and serves to
475create a target file if any of the prerequisites change. However, the
476rule that specifies commands for the target need not have
477prerequisites. For example, the rule containing the delete command
478associated with the target `clean' does not have prerequisites.
479
480 A "rule", then, explains how and when to remake certain files which
481are the targets of the particular rule. `make' carries out the
482commands on the prerequisites to create or update the target. A rule
483can also explain how and when to carry out an action. *Note Writing
484Rules: Rules.
485
486 A makefile may contain other text besides rules, but a simple
487makefile need only contain rules. Rules may look somewhat more
488complicated than shown in this template, but all fit the pattern more
489or less.
490
491
492File: make.info, Node: Simple Makefile, Next: How Make Works, Prev: Rule Introduction, Up: Introduction
493
4942.2 A Simple Makefile
495=====================
496
497Here is a straightforward makefile that describes the way an executable
498file called `edit' depends on eight object files which, in turn, depend
499on eight C source and three header files.
500
501 In this example, all the C files include `defs.h', but only those
502defining editing commands include `command.h', and only low level files
503that change the editor buffer include `buffer.h'.
504
505 edit : main.o kbd.o command.o display.o \
506 insert.o search.o files.o utils.o
507 cc -o edit main.o kbd.o command.o display.o \
508 insert.o search.o files.o utils.o
509
510 main.o : main.c defs.h
511 cc -c main.c
512 kbd.o : kbd.c defs.h command.h
513 cc -c kbd.c
514 command.o : command.c defs.h command.h
515 cc -c command.c
516 display.o : display.c defs.h buffer.h
517 cc -c display.c
518 insert.o : insert.c defs.h buffer.h
519 cc -c insert.c
520 search.o : search.c defs.h buffer.h
521 cc -c search.c
522 files.o : files.c defs.h buffer.h command.h
523 cc -c files.c
524 utils.o : utils.c defs.h
525 cc -c utils.c
526 clean :
527 rm edit main.o kbd.o command.o display.o \
528 insert.o search.o files.o utils.o
529
530We split each long line into two lines using backslash-newline; this is
531like using one long line, but is easier to read.
532
533 To use this makefile to create the executable file called `edit',
534type:
535
536 make
537
538 To use this makefile to delete the executable file and all the object
539files from the directory, type:
540
541 make clean
542
543 In the example makefile, the targets include the executable file
544`edit', and the object files `main.o' and `kbd.o'. The prerequisites
545are files such as `main.c' and `defs.h'. In fact, each `.o' file is
546both a target and a prerequisite. Commands include `cc -c main.c' and
547`cc -c kbd.c'.
548
549 When a target is a file, it needs to be recompiled or relinked if any
550of its prerequisites change. In addition, any prerequisites that are
551themselves automatically generated should be updated first. In this
552example, `edit' depends on each of the eight object files; the object
553file `main.o' depends on the source file `main.c' and on the header
554file `defs.h'.
555
556 A shell command follows each line that contains a target and
557prerequisites. These shell commands say how to update the target file.
558A tab character must come at the beginning of every command line to
559distinguish command lines from other lines in the makefile. (Bear in
560mind that `make' does not know anything about how the commands work.
561It is up to you to supply commands that will update the target file
562properly. All `make' does is execute the commands in the rule you have
563specified when the target file needs to be updated.)
564
565 The target `clean' is not a file, but merely the name of an action.
566Since you normally do not want to carry out the actions in this rule,
567`clean' is not a prerequisite of any other rule. Consequently, `make'
568never does anything with it unless you tell it specifically. Note that
569this rule not only is not a prerequisite, it also does not have any
570prerequisites, so the only purpose of the rule is to run the specified
571commands. Targets that do not refer to files but are just actions are
572called "phony targets". *Note Phony Targets::, for information about
573this kind of target. *Note Errors in Commands: Errors, to see how to
574cause `make' to ignore errors from `rm' or any other command.
575
576
577File: make.info, Node: How Make Works, Next: Variables Simplify, Prev: Simple Makefile, Up: Introduction
578
5792.3 How `make' Processes a Makefile
580===================================
581
582By default, `make' starts with the first target (not targets whose
583names start with `.'). This is called the "default goal". ("Goals"
584are the targets that `make' strives ultimately to update. You can
585override this behavior using the command line (*note Arguments to
586Specify the Goals: Goals.) or with the `.DEFAULT_GOAL' special variable
587(*note Other Special Variables: Special Variables.).
588
589 In the simple example of the previous section, the default goal is to
590update the executable program `edit'; therefore, we put that rule first.
591
592 Thus, when you give the command:
593
594 make
595
596`make' reads the makefile in the current directory and begins by
597processing the first rule. In the example, this rule is for relinking
598`edit'; but before `make' can fully process this rule, it must process
599the rules for the files that `edit' depends on, which in this case are
600the object files. Each of these files is processed according to its
601own rule. These rules say to update each `.o' file by compiling its
602source file. The recompilation must be done if the source file, or any
603of the header files named as prerequisites, is more recent than the
604object file, or if the object file does not exist.
605
606 The other rules are processed because their targets appear as
607prerequisites of the goal. If some other rule is not depended on by the
608goal (or anything it depends on, etc.), that rule is not processed,
609unless you tell `make' to do so (with a command such as `make clean').
610
611 Before recompiling an object file, `make' considers updating its
612prerequisites, the source file and header files. This makefile does not
613specify anything to be done for them--the `.c' and `.h' files are not
614the targets of any rules--so `make' does nothing for these files. But
615`make' would update automatically generated C programs, such as those
616made by Bison or Yacc, by their own rules at this time.
617
618 After recompiling whichever object files need it, `make' decides
619whether to relink `edit'. This must be done if the file `edit' does
620not exist, or if any of the object files are newer than it. If an
621object file was just recompiled, it is now newer than `edit', so `edit'
622is relinked.
623
624 Thus, if we change the file `insert.c' and run `make', `make' will
625compile that file to update `insert.o', and then link `edit'. If we
626change the file `command.h' and run `make', `make' will recompile the
627object files `kbd.o', `command.o' and `files.o' and then link the file
628`edit'.
629
630
631File: make.info, Node: Variables Simplify, Next: make Deduces, Prev: How Make Works, Up: Introduction
632
6332.4 Variables Make Makefiles Simpler
634====================================
635
636In our example, we had to list all the object files twice in the rule
637for `edit' (repeated here):
638
639 edit : main.o kbd.o command.o display.o \
640 insert.o search.o files.o utils.o
641 cc -o edit main.o kbd.o command.o display.o \
642 insert.o search.o files.o utils.o
643
644 Such duplication is error-prone; if a new object file is added to the
645system, we might add it to one list and forget the other. We can
646eliminate the risk and simplify the makefile by using a variable.
647"Variables" allow a text string to be defined once and substituted in
648multiple places later (*note How to Use Variables: Using Variables.).
649
650 It is standard practice for every makefile to have a variable named
651`objects', `OBJECTS', `objs', `OBJS', `obj', or `OBJ' which is a list
652of all object file names. We would define such a variable `objects'
653with a line like this in the makefile:
654
655 objects = main.o kbd.o command.o display.o \
656 insert.o search.o files.o utils.o
657
658Then, each place we want to put a list of the object file names, we can
659substitute the variable's value by writing `$(objects)' (*note How to
660Use Variables: Using Variables.).
661
662 Here is how the complete simple makefile looks when you use a
663variable for the object files:
664
665 objects = main.o kbd.o command.o display.o \
666 insert.o search.o files.o utils.o
667
668 edit : $(objects)
669 cc -o edit $(objects)
670 main.o : main.c defs.h
671 cc -c main.c
672 kbd.o : kbd.c defs.h command.h
673 cc -c kbd.c
674 command.o : command.c defs.h command.h
675 cc -c command.c
676 display.o : display.c defs.h buffer.h
677 cc -c display.c
678 insert.o : insert.c defs.h buffer.h
679 cc -c insert.c
680 search.o : search.c defs.h buffer.h
681 cc -c search.c
682 files.o : files.c defs.h buffer.h command.h
683 cc -c files.c
684 utils.o : utils.c defs.h
685 cc -c utils.c
686 clean :
687 rm edit $(objects)
688
689
690File: make.info, Node: make Deduces, Next: Combine By Prerequisite, Prev: Variables Simplify, Up: Introduction
691
6922.5 Letting `make' Deduce the Commands
693======================================
694
695It is not necessary to spell out the commands for compiling the
696individual C source files, because `make' can figure them out: it has an
697"implicit rule" for updating a `.o' file from a correspondingly named
698`.c' file using a `cc -c' command. For example, it will use the
699command `cc -c main.c -o main.o' to compile `main.c' into `main.o'. We
700can therefore omit the commands from the rules for the object files.
701*Note Using Implicit Rules: Implicit Rules.
702
703 When a `.c' file is used automatically in this way, it is also
704automatically added to the list of prerequisites. We can therefore omit
705the `.c' files from the prerequisites, provided we omit the commands.
706
707 Here is the entire example, with both of these changes, and a
708variable `objects' as suggested above:
709
710 objects = main.o kbd.o command.o display.o \
711 insert.o search.o files.o utils.o
712
713 edit : $(objects)
714 cc -o edit $(objects)
715
716 main.o : defs.h
717 kbd.o : defs.h command.h
718 command.o : defs.h command.h
719 display.o : defs.h buffer.h
720 insert.o : defs.h buffer.h
721 search.o : defs.h buffer.h
722 files.o : defs.h buffer.h command.h
723 utils.o : defs.h
724
725 .PHONY : clean
726 clean :
727 rm edit $(objects)
728
729This is how we would write the makefile in actual practice. (The
730complications associated with `clean' are described elsewhere. See
731*Note Phony Targets::, and *Note Errors in Commands: Errors.)
732
733 Because implicit rules are so convenient, they are important. You
734will see them used frequently.
735
736
737File: make.info, Node: Combine By Prerequisite, Next: Cleanup, Prev: make Deduces, Up: Introduction
738
7392.6 Another Style of Makefile
740=============================
741
742When the objects of a makefile are created only by implicit rules, an
743alternative style of makefile is possible. In this style of makefile,
744you group entries by their prerequisites instead of by their targets.
745Here is what one looks like:
746
747 objects = main.o kbd.o command.o display.o \
748 insert.o search.o files.o utils.o
749
750 edit : $(objects)
751 cc -o edit $(objects)
752
753 $(objects) : defs.h
754 kbd.o command.o files.o : command.h
755 display.o insert.o search.o files.o : buffer.h
756
757Here `defs.h' is given as a prerequisite of all the object files;
758`command.h' and `buffer.h' are prerequisites of the specific object
759files listed for them.
760
761 Whether this is better is a matter of taste: it is more compact, but
762some people dislike it because they find it clearer to put all the
763information about each target in one place.
764
765
766File: make.info, Node: Cleanup, Prev: Combine By Prerequisite, Up: Introduction
767
7682.7 Rules for Cleaning the Directory
769====================================
770
771Compiling a program is not the only thing you might want to write rules
772for. Makefiles commonly tell how to do a few other things besides
773compiling a program: for example, how to delete all the object files
774and executables so that the directory is `clean'.
775
776 Here is how we could write a `make' rule for cleaning our example
777editor:
778
779 clean:
780 rm edit $(objects)
781
782 In practice, we might want to write the rule in a somewhat more
783complicated manner to handle unanticipated situations. We would do
784this:
785
786 .PHONY : clean
787 clean :
788 -rm edit $(objects)
789
790This prevents `make' from getting confused by an actual file called
791`clean' and causes it to continue in spite of errors from `rm'. (See
792*Note Phony Targets::, and *Note Errors in Commands: Errors.)
793
794A rule such as this should not be placed at the beginning of the
795makefile, because we do not want it to run by default! Thus, in the
796example makefile, we want the rule for `edit', which recompiles the
797editor, to remain the default goal.
798
799 Since `clean' is not a prerequisite of `edit', this rule will not
800run at all if we give the command `make' with no arguments. In order
801to make the rule run, we have to type `make clean'. *Note How to Run
802`make': Running.
803
804
805File: make.info, Node: Makefiles, Next: Rules, Prev: Introduction, Up: Top
806
8073 Writing Makefiles
808*******************
809
810The information that tells `make' how to recompile a system comes from
811reading a data base called the "makefile".
812
813* Menu:
814
815* Makefile Contents:: What makefiles contain.
816* Makefile Names:: How to name your makefile.
817* Include:: How one makefile can use another makefile.
818* MAKEFILES Variable:: The environment can specify extra makefiles.
819* MAKEFILE_LIST Variable:: Discover which makefiles have been read.
820* Special Variables:: Other special variables.
821* Remaking Makefiles:: How makefiles get remade.
822* Overriding Makefiles:: How to override part of one makefile
823 with another makefile.
824* Reading Makefiles:: How makefiles are parsed.
825* Secondary Expansion:: How and when secondary expansion is performed.
826
827
828File: make.info, Node: Makefile Contents, Next: Makefile Names, Prev: Makefiles, Up: Makefiles
829
8303.1 What Makefiles Contain
831==========================
832
833Makefiles contain five kinds of things: "explicit rules", "implicit
834rules", "variable definitions", "directives", and "comments". Rules,
835variables, and directives are described at length in later chapters.
836
837 * An "explicit rule" says when and how to remake one or more files,
838 called the rule's "targets". It lists the other files that the
839 targets depend on, called the "prerequisites" of the target, and
840 may also give commands to use to create or update the targets.
841 *Note Writing Rules: Rules.
842
843 * An "implicit rule" says when and how to remake a class of files
844 based on their names. It describes how a target may depend on a
845 file with a name similar to the target and gives commands to
846 create or update such a target. *Note Using Implicit Rules:
847 Implicit Rules.
848
849 * A "variable definition" is a line that specifies a text string
850 value for a variable that can be substituted into the text later.
851 The simple makefile example shows a variable definition for
852 `objects' as a list of all object files (*note Variables Make
853 Makefiles Simpler: Variables Simplify.).
854
855 * A "directive" is a command for `make' to do something special while
856 reading the makefile. These include:
857
858 * Reading another makefile (*note Including Other Makefiles:
859 Include.).
860
861 * Deciding (based on the values of variables) whether to use or
862 ignore a part of the makefile (*note Conditional Parts of
863 Makefiles: Conditionals.).
864
865 * Defining a variable from a verbatim string containing
866 multiple lines (*note Defining Variables Verbatim: Defining.).
867
868 * `#' in a line of a makefile starts a "comment". It and the rest
869 of the line are ignored, except that a trailing backslash not
870 escaped by another backslash will continue the comment across
871 multiple lines. A line containing just a comment (with perhaps
872 spaces before it) is effectively blank, and is ignored. If you
873 want a literal `#', escape it with a backslash (e.g., `\#').
874 Comments may appear on any line in the makefile, although they are
875 treated specially in certain situations.
876
877 Within a command script (if the line begins with a TAB character)
878 the entire line is passed to the shell, just as with any other
879 line that begins with a TAB. The shell decides how to interpret
880 the text: whether or not this is a comment is up to the shell.
881
882 Within a `define' directive, comments are not ignored during the
883 definition of the variable, but rather kept intact in the value of
884 the variable. When the variable is expanded they will either be
885 treated as `make' comments or as command script text, depending on
886 the context in which the variable is evaluated.
887
888
889File: make.info, Node: Makefile Names, Next: Include, Prev: Makefile Contents, Up: Makefiles
890
8913.2 What Name to Give Your Makefile
892===================================
893
894By default, when `make' looks for the makefile, it tries the following
895names, in order: `GNUmakefile', `makefile' and `Makefile'.
896
897 Normally you should call your makefile either `makefile' or
898`Makefile'. (We recommend `Makefile' because it appears prominently
899near the beginning of a directory listing, right near other important
900files such as `README'.) The first name checked, `GNUmakefile', is not
901recommended for most makefiles. You should use this name if you have a
902makefile that is specific to GNU `make', and will not be understood by
903other versions of `make'. Other `make' programs look for `makefile' and
904`Makefile', but not `GNUmakefile'.
905
906 If `make' finds none of these names, it does not use any makefile.
907Then you must specify a goal with a command argument, and `make' will
908attempt to figure out how to remake it using only its built-in implicit
909rules. *Note Using Implicit Rules: Implicit Rules.
910
911 If you want to use a nonstandard name for your makefile, you can
912specify the makefile name with the `-f' or `--file' option. The
913arguments `-f NAME' or `--file=NAME' tell `make' to read the file NAME
914as the makefile. If you use more than one `-f' or `--file' option, you
915can specify several makefiles. All the makefiles are effectively
916concatenated in the order specified. The default makefile names
917`GNUmakefile', `makefile' and `Makefile' are not checked automatically
918if you specify `-f' or `--file'.
919
920
921File: make.info, Node: Include, Next: MAKEFILES Variable, Prev: Makefile Names, Up: Makefiles
922
9233.3 Including Other Makefiles
924=============================
925
926The `include' directive tells `make' to suspend reading the current
927makefile and read one or more other makefiles before continuing. The
928directive is a line in the makefile that looks like this:
929
930 include FILENAMES...
931
932FILENAMES can contain shell file name patterns. If FILENAMES is empty,
933nothing is included and no error is printed.
934
935 Extra spaces are allowed and ignored at the beginning of the line,
936but a tab is not allowed. (If the line begins with a tab, it will be
937considered a command line.) Whitespace is required between `include'
938and the file names, and between file names; extra whitespace is ignored
939there and at the end of the directive. A comment starting with `#' is
940allowed at the end of the line. If the file names contain any variable
941or function references, they are expanded. *Note How to Use Variables:
942Using Variables.
943
944 For example, if you have three `.mk' files, `a.mk', `b.mk', and
945`c.mk', and `$(bar)' expands to `bish bash', then the following
946expression
947
948 include foo *.mk $(bar)
949
950 is equivalent to
951
952 include foo a.mk b.mk c.mk bish bash
953
954 When `make' processes an `include' directive, it suspends reading of
955the containing makefile and reads from each listed file in turn. When
956that is finished, `make' resumes reading the makefile in which the
957directive appears.
958
959 One occasion for using `include' directives is when several programs,
960handled by individual makefiles in various directories, need to use a
961common set of variable definitions (*note Setting Variables: Setting.)
962or pattern rules (*note Defining and Redefining Pattern Rules: Pattern
963Rules.).
964
965 Another such occasion is when you want to generate prerequisites from
966source files automatically; the prerequisites can be put in a file that
967is included by the main makefile. This practice is generally cleaner
968than that of somehow appending the prerequisites to the end of the main
969makefile as has been traditionally done with other versions of `make'.
970*Note Automatic Prerequisites::.
971
972 If the specified name does not start with a slash, and the file is
973not found in the current directory, several other directories are
974searched. First, any directories you have specified with the `-I' or
975`--include-dir' option are searched (*note Summary of Options: Options
976Summary.). Then the following directories (if they exist) are
977searched, in this order: `PREFIX/include' (normally `/usr/local/include'
978(1)) `/usr/gnu/include', `/usr/local/include', `/usr/include'.
979
980 If an included makefile cannot be found in any of these directories,
981a warning message is generated, but it is not an immediately fatal
982error; processing of the makefile containing the `include' continues.
983Once it has finished reading makefiles, `make' will try to remake any
984that are out of date or don't exist. *Note How Makefiles Are Remade:
985Remaking Makefiles. Only after it has tried to find a way to remake a
986makefile and failed, will `make' diagnose the missing makefile as a
987fatal error.
988
989 If you want `make' to simply ignore a makefile which does not exist
990and cannot be remade, with no error message, use the `-include'
991directive instead of `include', like this:
992
993 -include FILENAMES...
994
995 This acts like `include' in every way except that there is no error
996(not even a warning) if any of the FILENAMES do not exist. For
997compatibility with some other `make' implementations, `sinclude' is
998another name for `-include'.
999
1000 ---------- Footnotes ----------
1001
1002 (1) GNU Make compiled for MS-DOS and MS-Windows behaves as if PREFIX
1003has been defined to be the root of the DJGPP tree hierarchy.
1004
1005
1006File: make.info, Node: MAKEFILES Variable, Next: MAKEFILE_LIST Variable, Prev: Include, Up: Makefiles
1007
10083.4 The Variable `MAKEFILES'
1009============================
1010
1011If the environment variable `MAKEFILES' is defined, `make' considers
1012its value as a list of names (separated by whitespace) of additional
1013makefiles to be read before the others. This works much like the
1014`include' directive: various directories are searched for those files
1015(*note Including Other Makefiles: Include.). In addition, the default
1016goal is never taken from one of these makefiles and it is not an error
1017if the files listed in `MAKEFILES' are not found.
1018
1019 The main use of `MAKEFILES' is in communication between recursive
1020invocations of `make' (*note Recursive Use of `make': Recursion.). It
1021usually is not desirable to set the environment variable before a
1022top-level invocation of `make', because it is usually better not to
1023mess with a makefile from outside. However, if you are running `make'
1024without a specific makefile, a makefile in `MAKEFILES' can do useful
1025things to help the built-in implicit rules work better, such as
1026defining search paths (*note Directory Search::).
1027
1028 Some users are tempted to set `MAKEFILES' in the environment
1029automatically on login, and program makefiles to expect this to be done.
1030This is a very bad idea, because such makefiles will fail to work if
1031run by anyone else. It is much better to write explicit `include'
1032directives in the makefiles. *Note Including Other Makefiles: Include.
1033
1034
1035File: make.info, Node: MAKEFILE_LIST Variable, Next: Special Variables, Prev: MAKEFILES Variable, Up: Makefiles
1036
10373.5 The Variable `MAKEFILE_LIST'
1038================================
1039
1040As `make' reads various makefiles, including any obtained from the
1041`MAKEFILES' variable, the command line, the default files, or from
1042`include' directives, their names will be automatically appended to the
1043`MAKEFILE_LIST' variable. They are added right before `make' begins to
1044parse them.
1045
1046 This means that if the first thing a makefile does is examine the
1047last word in this variable, it will be the name of the current makefile.
1048Once the current makefile has used `include', however, the last word
1049will be the just-included makefile.
1050
1051 If a makefile named `Makefile' has this content:
1052
1053 name1 := $(lastword $(MAKEFILE_LIST))
1054
1055 include inc.mk
1056
1057 name2 := $(lastword $(MAKEFILE_LIST))
1058
1059 all:
1060 @echo name1 = $(name1)
1061 @echo name2 = $(name2)
1062
1063then you would expect to see this output:
1064
1065 name1 = Makefile
1066 name2 = inc.mk
1067
1068 *Note Text Functions::, for more information on the `word' and
1069`words' functions used above. *Note The Two Flavors of Variables:
1070Flavors, for more information on simply-expanded (`:=') variable
1071definitions.
1072
1073
1074File: make.info, Node: Special Variables, Next: Remaking Makefiles, Prev: MAKEFILE_LIST Variable, Up: Makefiles
1075
10763.6 Other Special Variables
1077===========================
1078
1079GNU `make' also supports other special variables. Unless otherwise
1080documented here, these values lose their special properties if they are
1081set by a makefile or on the command line.
1082
1083`.DEFAULT_GOAL'
1084 Sets the default goal to be used if no targets were specified on
1085 the command line (*note Arguments to Specify the Goals: Goals.).
1086 The `.DEFAULT_GOAL' variable allows you to discover the current
1087 default goal, restart the default goal selection algorithm by
1088 clearing its value, or to explicitly set the default goal. The
1089 following example illustrates these cases:
1090
1091 # Query the default goal.
1092 ifeq ($(.DEFAULT_GOAL),)
1093 $(warning no default goal is set)
1094 endif
1095
1096 .PHONY: foo
1097 foo: ; @echo $@
1098
1099 $(warning default goal is $(.DEFAULT_GOAL))
1100
1101 # Reset the default goal.
1102 .DEFAULT_GOAL :=
1103
1104 .PHONY: bar
1105 bar: ; @echo $@
1106
1107 $(warning default goal is $(.DEFAULT_GOAL))
1108
1109 # Set our own.
1110 .DEFAULT_GOAL := foo
1111
1112 This makefile prints:
1113
1114 no default goal is set
1115 default goal is foo
1116 default goal is bar
1117 foo
1118
1119 Note that assigning more than one target name to `.DEFAULT_GOAL' is
1120 illegal and will result in an error.
1121
1122`MAKE_RESTARTS'
1123 This variable is set only if this instance of `make' has restarted
1124 (*note How Makefiles Are Remade: Remaking Makefiles.): it will
1125 contain the number of times this instance has restarted. Note
1126 this is not the same as recursion (counted by the `MAKELEVEL'
1127 variable). You should not set, modify, or export this variable.
1128
1129`.VARIABLES'
1130 Expands to a list of the _names_ of all global variables defined
1131 so far. This includes variables which have empty values, as well
1132 as built-in variables (*note Variables Used by Implicit Rules:
1133 Implicit Variables.), but does not include any variables which are
1134 only defined in a target-specific context. Note that any value
1135 you assign to this variable will be ignored; it will always return
1136 its special value.
1137
1138`.FEATURES'
1139 Expands to a list of special features supported by this version of
1140 `make'. Possible values include:
1141
1142 `archives'
1143 Supports `ar' (archive) files using special filename syntax.
1144 *Note Using `make' to Update Archive Files: Archives.
1145
1146 `check-symlink'
1147 Supports the `-L' (`--check-symlink-times') flag. *Note
1148 Summary of Options: Options Summary.
1149
1150 `else-if'
1151 Supports "else if" non-nested conditionals. *Note Syntax of
1152 Conditionals: Conditional Syntax.
1153
1154 `jobserver'
1155 Supports "job server" enhanced parallel builds. *Note
1156 Parallel Execution: Parallel.
1157
1158 `second-expansion'
1159 Supports secondary expansion of prerequisite lists.
1160
1161 `order-only'
1162 Supports order-only prerequisites. *Note Types of
1163 Prerequisites: Prerequisite Types.
1164
1165 `target-specific'
1166 Supports target-specific and pattern-specific variable
1167 assignments. *Note Target-specific Variable Values:
1168 Target-specific.
1169
1170
1171`.INCLUDE_DIRS'
1172 Expands to a list of directories that `make' searches for included
1173 makefiles (*note Including Other Makefiles: Include.).
1174
1175
1176
1177File: make.info, Node: Remaking Makefiles, Next: Overriding Makefiles, Prev: Special Variables, Up: Makefiles
1178
11793.7 How Makefiles Are Remade
1180============================
1181
1182Sometimes makefiles can be remade from other files, such as RCS or SCCS
1183files. If a makefile can be remade from other files, you probably want
1184`make' to get an up-to-date version of the makefile to read in.
1185
1186 To this end, after reading in all makefiles, `make' will consider
1187each as a goal target and attempt to update it. If a makefile has a
1188rule which says how to update it (found either in that very makefile or
1189in another one) or if an implicit rule applies to it (*note Using
1190Implicit Rules: Implicit Rules.), it will be updated if necessary.
1191After all makefiles have been checked, if any have actually been
1192changed, `make' starts with a clean slate and reads all the makefiles
1193over again. (It will also attempt to update each of them over again,
1194but normally this will not change them again, since they are already up
1195to date.)
1196
1197 If you know that one or more of your makefiles cannot be remade and
1198you want to keep `make' from performing an implicit rule search on
1199them, perhaps for efficiency reasons, you can use any normal method of
1200preventing implicit rule lookup to do so. For example, you can write an
1201explicit rule with the makefile as the target, and an empty command
1202string (*note Using Empty Commands: Empty Commands.).
1203
1204 If the makefiles specify a double-colon rule to remake a file with
1205commands but no prerequisites, that file will always be remade (*note
1206Double-Colon::). In the case of makefiles, a makefile that has a
1207double-colon rule with commands but no prerequisites will be remade
1208every time `make' is run, and then again after `make' starts over and
1209reads the makefiles in again. This would cause an infinite loop:
1210`make' would constantly remake the makefile, and never do anything
1211else. So, to avoid this, `make' will *not* attempt to remake makefiles
1212which are specified as targets of a double-colon rule with commands but
1213no prerequisites.
1214
1215 If you do not specify any makefiles to be read with `-f' or `--file'
1216options, `make' will try the default makefile names; *note What Name to
1217Give Your Makefile: Makefile Names. Unlike makefiles explicitly
1218requested with `-f' or `--file' options, `make' is not certain that
1219these makefiles should exist. However, if a default makefile does not
1220exist but can be created by running `make' rules, you probably want the
1221rules to be run so that the makefile can be used.
1222
1223 Therefore, if none of the default makefiles exists, `make' will try
1224to make each of them in the same order in which they are searched for
1225(*note What Name to Give Your Makefile: Makefile Names.) until it
1226succeeds in making one, or it runs out of names to try. Note that it
1227is not an error if `make' cannot find or make any makefile; a makefile
1228is not always necessary.
1229
1230 When you use the `-t' or `--touch' option (*note Instead of
1231Executing the Commands: Instead of Execution.), you would not want to
1232use an out-of-date makefile to decide which targets to touch. So the
1233`-t' option has no effect on updating makefiles; they are really
1234updated even if `-t' is specified. Likewise, `-q' (or `--question')
1235and `-n' (or `--just-print') do not prevent updating of makefiles,
1236because an out-of-date makefile would result in the wrong output for
1237other targets. Thus, `make -f mfile -n foo' will update `mfile', read
1238it in, and then print the commands to update `foo' and its prerequisites
1239without running them. The commands printed for `foo' will be those
1240specified in the updated contents of `mfile'.
1241
1242 However, on occasion you might actually wish to prevent updating of
1243even the makefiles. You can do this by specifying the makefiles as
1244goals in the command line as well as specifying them as makefiles.
1245When the makefile name is specified explicitly as a goal, the options
1246`-t' and so on do apply to them.
1247
1248 Thus, `make -f mfile -n mfile foo' would read the makefile `mfile',
1249print the commands needed to update it without actually running them,
1250and then print the commands needed to update `foo' without running
1251them. The commands for `foo' will be those specified by the existing
1252contents of `mfile'.
1253
1254
1255File: make.info, Node: Overriding Makefiles, Next: Reading Makefiles, Prev: Remaking Makefiles, Up: Makefiles
1256
12573.8 Overriding Part of Another Makefile
1258=======================================
1259
1260Sometimes it is useful to have a makefile that is mostly just like
1261another makefile. You can often use the `include' directive to include
1262one in the other, and add more targets or variable definitions.
1263However, if the two makefiles give different commands for the same
1264target, `make' will not let you just do this. But there is another way.
1265
1266 In the containing makefile (the one that wants to include the other),
1267you can use a match-anything pattern rule to say that to remake any
1268target that cannot be made from the information in the containing
1269makefile, `make' should look in another makefile. *Note Pattern
1270Rules::, for more information on pattern rules.
1271
1272 For example, if you have a makefile called `Makefile' that says how
1273to make the target `foo' (and other targets), you can write a makefile
1274called `GNUmakefile' that contains:
1275
1276 foo:
1277 frobnicate > foo
1278
1279 %: force
1280 @$(MAKE) -f Makefile $@
1281 force: ;
1282
1283 If you say `make foo', `make' will find `GNUmakefile', read it, and
1284see that to make `foo', it needs to run the command `frobnicate > foo'.
1285If you say `make bar', `make' will find no way to make `bar' in
1286`GNUmakefile', so it will use the commands from the pattern rule: `make
1287-f Makefile bar'. If `Makefile' provides a rule for updating `bar',
1288`make' will apply the rule. And likewise for any other target that
1289`GNUmakefile' does not say how to make.
1290
1291 The way this works is that the pattern rule has a pattern of just
1292`%', so it matches any target whatever. The rule specifies a
1293prerequisite `force', to guarantee that the commands will be run even
1294if the target file already exists. We give `force' target empty
1295commands to prevent `make' from searching for an implicit rule to build
1296it--otherwise it would apply the same match-anything rule to `force'
1297itself and create a prerequisite loop!
1298
1299
1300File: make.info, Node: Reading Makefiles, Next: Secondary Expansion, Prev: Overriding Makefiles, Up: Makefiles
1301
13023.9 How `make' Reads a Makefile
1303===============================
1304
1305GNU `make' does its work in two distinct phases. During the first
1306phase it reads all the makefiles, included makefiles, etc. and
1307internalizes all the variables and their values, implicit and explicit
1308rules, and constructs a dependency graph of all the targets and their
1309prerequisites. During the second phase, `make' uses these internal
1310structures to determine what targets will need to be rebuilt and to
1311invoke the rules necessary to do so.
1312
1313 It's important to understand this two-phase approach because it has a
1314direct impact on how variable and function expansion happens; this is
1315often a source of some confusion when writing makefiles. Here we will
1316present a summary of the phases in which expansion happens for different
1317constructs within the makefile. We say that expansion is "immediate"
1318if it happens during the first phase: in this case `make' will expand
1319any variables or functions in that section of a construct as the
1320makefile is parsed. We say that expansion is "deferred" if expansion
1321is not performed immediately. Expansion of deferred construct is not
1322performed until either the construct appears later in an immediate
1323context, or until the second phase.
1324
1325 You may not be familiar with some of these constructs yet. You can
1326reference this section as you become familiar with them, in later
1327chapters.
1328
1329Variable Assignment
1330-------------------
1331
1332Variable definitions are parsed as follows:
1333
1334 IMMEDIATE = DEFERRED
1335 IMMEDIATE ?= DEFERRED
1336 IMMEDIATE := IMMEDIATE
1337 IMMEDIATE += DEFERRED or IMMEDIATE
1338
1339 define IMMEDIATE
1340 DEFERRED
1341 endef
1342
1343 For the append operator, `+=', the right-hand side is considered
1344immediate if the variable was previously set as a simple variable
1345(`:='), and deferred otherwise.
1346
1347Conditional Statements
1348----------------------
1349
1350All instances of conditional syntax are parsed immediately, in their
1351entirety; this includes the `ifdef', `ifeq', `ifndef', and `ifneq'
1352forms. Of course this means that automatic variables cannot be used in
1353conditional statements, as automatic variables are not set until the
1354command script for that rule is invoked. If you need to use automatic
1355variables in a conditional you _must_ use shell conditional syntax, in
1356your command script proper, for these tests, not `make' conditionals.
1357
1358Rule Definition
1359---------------
1360
1361A rule is always expanded the same way, regardless of the form:
1362
1363 IMMEDIATE : IMMEDIATE ; DEFERRED
1364 DEFERRED
1365
1366 That is, the target and prerequisite sections are expanded
1367immediately, and the commands used to construct the target are always
1368deferred. This general rule is true for explicit rules, pattern rules,
1369suffix rules, static pattern rules, and simple prerequisite definitions.
1370
1371
1372File: make.info, Node: Secondary Expansion, Prev: Reading Makefiles, Up: Makefiles
1373
13743.10 Secondary Expansion
1375========================
1376
1377In the previous section we learned that GNU `make' works in two
1378distinct phases: a read-in phase and a target-update phase (*note How
1379`make' Reads a Makefile: Reading Makefiles.). GNU make also has the
1380ability to enable a _second expansion_ of the prerequisites (only) for
1381some or all targets defined in the makefile. In order for this second
1382expansion to occur, the special target `.SECONDEXPANSION' must be
1383defined before the first prerequisite list that makes use of this
1384feature.
1385
1386 If that special target is defined then in between the two phases
1387mentioned above, right at the end of the read-in phase, all the
1388prerequisites of the targets defined after the special target are
1389expanded a _second time_. In most circumstances this secondary
1390expansion will have no effect, since all variable and function
1391references will have been expanded during the initial parsing of the
1392makefiles. In order to take advantage of the secondary expansion phase
1393of the parser, then, it's necessary to _escape_ the variable or
1394function reference in the makefile. In this case the first expansion
1395merely un-escapes the reference but doesn't expand it, and expansion is
1396left to the secondary expansion phase. For example, consider this
1397makefile:
1398
1399 .SECONDEXPANSION:
1400 ONEVAR = onefile
1401 TWOVAR = twofile
1402 myfile: $(ONEVAR) $$(TWOVAR)
1403
1404 After the first expansion phase the prerequisites list of the
1405`myfile' target will be `onefile' and `$(TWOVAR)'; the first
1406(unescaped) variable reference to ONEVAR is expanded, while the second
1407(escaped) variable reference is simply unescaped, without being
1408recognized as a variable reference. Now during the secondary expansion
1409the first word is expanded again but since it contains no variable or
1410function references it remains the static value `onefile', while the
1411second word is now a normal reference to the variable TWOVAR, which is
1412expanded to the value `twofile'. The final result is that there are
1413two prerequisites, `onefile' and `twofile'.
1414
1415 Obviously, this is not a very interesting case since the same result
1416could more easily have been achieved simply by having both variables
1417appear, unescaped, in the prerequisites list. One difference becomes
1418apparent if the variables are reset; consider this example:
1419
1420 .SECONDEXPANSION:
1421 AVAR = top
1422 onefile: $(AVAR)
1423 twofile: $$(AVAR)
1424 AVAR = bottom
1425
1426 Here the prerequisite of `onefile' will be expanded immediately, and
1427resolve to the value `top', while the prerequisite of `twofile' will
1428not be full expanded until the secondary expansion and yield a value of
1429`bottom'.
1430
1431 This is marginally more exciting, but the true power of this feature
1432only becomes apparent when you discover that secondary expansions
1433always take place within the scope of the automatic variables for that
1434target. This means that you can use variables such as `$@', `$*', etc.
1435during the second expansion and they will have their expected values,
1436just as in the command script. All you have to do is defer the
1437expansion by escaping the `$'. Also, secondary expansion occurs for
1438both explicit and implicit (pattern) rules. Knowing this, the possible
1439uses for this feature increase dramatically. For example:
1440
1441 .SECONDEXPANSION:
1442 main_OBJS := main.o try.o test.o
1443 lib_OBJS := lib.o api.o
1444
1445 main lib: $$($$@_OBJS)
1446
1447 Here, after the initial expansion the prerequisites of both the
1448`main' and `lib' targets will be `$($@_OBJS)'. During the secondary
1449expansion, the `$@' variable is set to the name of the target and so
1450the expansion for the `main' target will yield `$(main_OBJS)', or
1451`main.o try.o test.o', while the secondary expansion for the `lib'
1452target will yield `$(lib_OBJS)', or `lib.o api.o'.
1453
1454 You can also mix functions here, as long as they are properly
1455escaped:
1456
1457 main_SRCS := main.c try.c test.c
1458 lib_SRCS := lib.c api.c
1459
1460 .SECONDEXPANSION:
1461 main lib: $$(patsubst %.c,%.o,$$($$@_SRCS))
1462
1463 This version allows users to specify source files rather than object
1464files, but gives the same resulting prerequisites list as the previous
1465example.
1466
1467 Evaluation of automatic variables during the secondary expansion
1468phase, especially of the target name variable `$$@', behaves similarly
1469to evaluation within command scripts. However, there are some subtle
1470differences and "corner cases" which come into play for the different
1471types of rule definitions that `make' understands. The subtleties of
1472using the different automatic variables are described below.
1473
1474Secondary Expansion of Explicit Rules
1475-------------------------------------
1476
1477During the secondary expansion of explicit rules, `$$@' and `$$%'
1478evaluate, respectively, to the file name of the target and, when the
1479target is an archive member, the target member name. The `$$<'
1480variable evaluates to the first prerequisite in the first rule for this
1481target. `$$^' and `$$+' evaluate to the list of all prerequisites of
1482rules _that have already appeared_ for the same target (`$$+' with
1483repetitions and `$$^' without). The following example will help
1484illustrate these behaviors:
1485
1486 .SECONDEXPANSION:
1487
1488 foo: foo.1 bar.1 $$< $$^ $$+ # line #1
1489
1490 foo: foo.2 bar.2 $$< $$^ $$+ # line #2
1491
1492 foo: foo.3 bar.3 $$< $$^ $$+ # line #3
1493
1494 In the first prerequisite list, all three variables (`$$<', `$$^',
1495and `$$+') expand to the empty string. In the second, they will have
1496values `foo.1', `foo.1 bar.1', and `foo.1 bar.1' respectively. In the
1497third they will have values `foo.1', `foo.1 bar.1 foo.2 bar.2', and
1498`foo.1 bar.1 foo.2 bar.2' respectively.
1499
1500 Rules undergo secondary expansion in makefile order, except that the
1501rule with the command script is always evaluated last.
1502
1503 The variables `$$?' and `$$*' are not available and expand to the
1504empty string.
1505
1506Secondary Expansion of Static Pattern Rules
1507-------------------------------------------
1508
1509Rules for secondary expansion of static pattern rules are identical to
1510those for explicit rules, above, with one exception: for static pattern
1511rules the `$$*' variable is set to the pattern stem. As with explicit
1512rules, `$$?' is not available and expands to the empty string.
1513
1514Secondary Expansion of Implicit Rules
1515-------------------------------------
1516
1517As `make' searches for an implicit rule, it substitutes the stem and
1518then performs secondary expansion for every rule with a matching target
1519pattern. The value of the automatic variables is derived in the same
1520fashion as for static pattern rules. As an example:
1521
1522 .SECONDEXPANSION:
1523
1524 foo: bar
1525
1526 foo foz: fo%: bo%
1527
1528 %oo: $$< $$^ $$+ $$*
1529
1530 When the implicit rule is tried for target `foo', `$$<' expands to
1531`bar', `$$^' expands to `bar boo', `$$+' also expands to `bar boo', and
1532`$$*' expands to `f'.
1533
1534 Note that the directory prefix (D), as described in *Note Implicit
1535Rule Search Algorithm: Implicit Rule Search, is appended (after
1536expansion) to all the patterns in the prerequisites list. As an
1537example:
1538
1539 .SECONDEXPANSION:
1540
1541 /tmp/foo.o:
1542
1543 %.o: $$(addsuffix /%.c,foo bar) foo.h
1544
1545 The prerequisite list after the secondary expansion and directory
1546prefix reconstruction will be `/tmp/foo/foo.c /tmp/var/bar/foo.c
1547foo.h'. If you are not interested in this reconstruction, you can use
1548`$$*' instead of `%' in the prerequisites list.
1549
1550
1551File: make.info, Node: Rules, Next: Commands, Prev: Makefiles, Up: Top
1552
15534 Writing Rules
1554***************
1555
1556A "rule" appears in the makefile and says when and how to remake
1557certain files, called the rule's "targets" (most often only one per
1558rule). It lists the other files that are the "prerequisites" of the
1559target, and "commands" to use to create or update the target.
1560
1561 The order of rules is not significant, except for determining the
1562"default goal": the target for `make' to consider, if you do not
1563otherwise specify one. The default goal is the target of the first
1564rule in the first makefile. If the first rule has multiple targets,
1565only the first target is taken as the default. There are two
1566exceptions: a target starting with a period is not a default unless it
1567contains one or more slashes, `/', as well; and, a target that defines
1568a pattern rule has no effect on the default goal. (*Note Defining and
1569Redefining Pattern Rules: Pattern Rules.)
1570
1571 Therefore, we usually write the makefile so that the first rule is
1572the one for compiling the entire program or all the programs described
1573by the makefile (often with a target called `all'). *Note Arguments to
1574Specify the Goals: Goals.
1575
1576* Menu:
1577
1578* Rule Example:: An example explained.
1579* Rule Syntax:: General syntax explained.
1580* Prerequisite Types:: There are two types of prerequisites.
1581* Wildcards:: Using wildcard characters such as `*'.
1582* Directory Search:: Searching other directories for source files.
1583* Phony Targets:: Using a target that is not a real file's name.
1584* Force Targets:: You can use a target without commands
1585 or prerequisites to mark other targets
1586 as phony.
1587* Empty Targets:: When only the date matters and the
1588 files are empty.
1589* Special Targets:: Targets with special built-in meanings.
1590* Multiple Targets:: When to make use of several targets in a rule.
1591* Multiple Rules:: How to use several rules with the same target.
1592* Static Pattern:: Static pattern rules apply to multiple targets
1593 and can vary the prerequisites according to
1594 the target name.
1595* Double-Colon:: How to use a special kind of rule to allow
1596 several independent rules for one target.
1597* Automatic Prerequisites:: How to automatically generate rules giving
1598 prerequisites from source files themselves.
1599
1600
1601File: make.info, Node: Rule Example, Next: Rule Syntax, Prev: Rules, Up: Rules
1602
16034.1 Rule Example
1604================
1605
1606Here is an example of a rule:
1607
1608 foo.o : foo.c defs.h # module for twiddling the frobs
1609 cc -c -g foo.c
1610
1611 Its target is `foo.o' and its prerequisites are `foo.c' and
1612`defs.h'. It has one command, which is `cc -c -g foo.c'. The command
1613line starts with a tab to identify it as a command.
1614
1615 This rule says two things:
1616
1617 * How to decide whether `foo.o' is out of date: it is out of date if
1618 it does not exist, or if either `foo.c' or `defs.h' is more recent
1619 than it.
1620
1621 * How to update the file `foo.o': by running `cc' as stated. The
1622 command does not explicitly mention `defs.h', but we presume that
1623 `foo.c' includes it, and that that is why `defs.h' was added to
1624 the prerequisites.
1625
1626
1627File: make.info, Node: Rule Syntax, Next: Prerequisite Types, Prev: Rule Example, Up: Rules
1628
16294.2 Rule Syntax
1630===============
1631
1632In general, a rule looks like this:
1633
1634 TARGETS : PREREQUISITES
1635 COMMAND
1636 ...
1637
1638or like this:
1639
1640 TARGETS : PREREQUISITES ; COMMAND
1641 COMMAND
1642 ...
1643
1644 The TARGETS are file names, separated by spaces. Wildcard
1645characters may be used (*note Using Wildcard Characters in File Names:
1646Wildcards.) and a name of the form `A(M)' represents member M in
1647archive file A (*note Archive Members as Targets: Archive Members.).
1648Usually there is only one target per rule, but occasionally there is a
1649reason to have more (*note Multiple Targets in a Rule: Multiple
1650Targets.).
1651
1652 The COMMAND lines start with a tab character. The first command may
1653appear on the line after the prerequisites, with a tab character, or may
1654appear on the same line, with a semicolon. Either way, the effect is
1655the same. There are other differences in the syntax of command lines.
1656*Note Writing the Commands in Rules: Commands.
1657
1658 Because dollar signs are used to start `make' variable references,
1659if you really want a dollar sign in a target or prerequisite you must
1660write two of them, `$$' (*note How to Use Variables: Using Variables.).
1661If you have enabled secondary expansion (*note Secondary Expansion::)
1662and you want a literal dollar sign in the prerequisites lise, you must
1663actually write _four_ dollar signs (`$$$$').
1664
1665 You may split a long line by inserting a backslash followed by a
1666newline, but this is not required, as `make' places no limit on the
1667length of a line in a makefile.
1668
1669 A rule tells `make' two things: when the targets are out of date,
1670and how to update them when necessary.
1671
1672 The criterion for being out of date is specified in terms of the
1673PREREQUISITES, which consist of file names separated by spaces.
1674(Wildcards and archive members (*note Archives::) are allowed here too.)
1675A target is out of date if it does not exist or if it is older than any
1676of the prerequisites (by comparison of last-modification times). The
1677idea is that the contents of the target file are computed based on
1678information in the prerequisites, so if any of the prerequisites
1679changes, the contents of the existing target file are no longer
1680necessarily valid.
1681
1682 How to update is specified by COMMANDS. These are lines to be
1683executed by the shell (normally `sh'), but with some extra features
1684(*note Writing the Commands in Rules: Commands.).
1685
1686
1687File: make.info, Node: Prerequisite Types, Next: Wildcards, Prev: Rule Syntax, Up: Rules
1688
16894.3 Types of Prerequisites
1690==========================
1691
1692There are actually two different types of prerequisites understood by
1693GNU `make': normal prerequisites such as described in the previous
1694section, and "order-only" prerequisites. A normal prerequisite makes
1695two statements: first, it imposes an order of execution of build
1696commands: any commands necessary to build any of a target's
1697prerequisites will be fully executed before any commands necessary to
1698build the target. Second, it imposes a dependency relationship: if any
1699prerequisite is newer than the target, then the target is considered
1700out-of-date and must be rebuilt.
1701
1702 Normally, this is exactly what you want: if a target's prerequisite
1703is updated, then the target should also be updated.
1704
1705 Occasionally, however, you have a situation where you want to impose
1706a specific ordering on the rules to be invoked _without_ forcing the
1707target to be updated if one of those rules is executed. In that case,
1708you want to define "order-only" prerequisites. Order-only
1709prerequisites can be specified by placing a pipe symbol (`|') in the
1710prerequisites list: any prerequisites to the left of the pipe symbol
1711are normal; any prerequisites to the right are order-only:
1712
1713 TARGETS : NORMAL-PREREQUISITES | ORDER-ONLY-PREREQUISITES
1714
1715 The normal prerequisites section may of course be empty. Also, you
1716may still declare multiple lines of prerequisites for the same target:
1717they are appended appropriately. Note that if you declare the same
1718file to be both a normal and an order-only prerequisite, the normal
1719prerequisite takes precedence (since they are a strict superset of the
1720behavior of an order-only prerequisite).
1721
1722
1723File: make.info, Node: Wildcards, Next: Directory Search, Prev: Prerequisite Types, Up: Rules
1724
17254.4 Using Wildcard Characters in File Names
1726===========================================
1727
1728A single file name can specify many files using "wildcard characters".
1729The wildcard characters in `make' are `*', `?' and `[...]', the same as
1730in the Bourne shell. For example, `*.c' specifies a list of all the
1731files (in the working directory) whose names end in `.c'.
1732
1733 The character `~' at the beginning of a file name also has special
1734significance. If alone, or followed by a slash, it represents your home
1735directory. For example `~/bin' expands to `/home/you/bin'. If the `~'
1736is followed by a word, the string represents the home directory of the
1737user named by that word. For example `~john/bin' expands to
1738`/home/john/bin'. On systems which don't have a home directory for
1739each user (such as MS-DOS or MS-Windows), this functionality can be
1740simulated by setting the environment variable HOME.
1741
1742 Wildcard expansion is performed by `make' automatically in targets
1743and in prerequisites. In commands the shell is responsible for
1744wildcard expansion. In other contexts, wildcard expansion happens only
1745if you request it explicitly with the `wildcard' function.
1746
1747 The special significance of a wildcard character can be turned off by
1748preceding it with a backslash. Thus, `foo\*bar' would refer to a
1749specific file whose name consists of `foo', an asterisk, and `bar'.
1750
1751* Menu:
1752
1753* Wildcard Examples:: Several examples
1754* Wildcard Pitfall:: Problems to avoid.
1755* Wildcard Function:: How to cause wildcard expansion where
1756 it does not normally take place.
1757
1758
1759File: make.info, Node: Wildcard Examples, Next: Wildcard Pitfall, Prev: Wildcards, Up: Wildcards
1760
17614.4.1 Wildcard Examples
1762-----------------------
1763
1764Wildcards can be used in the commands of a rule, where they are expanded
1765by the shell. For example, here is a rule to delete all the object
1766files:
1767
1768 clean:
1769 rm -f *.o
1770
1771 Wildcards are also useful in the prerequisites of a rule. With the
1772following rule in the makefile, `make print' will print all the `.c'
1773files that have changed since the last time you printed them:
1774
1775 print: *.c
1776 lpr -p $?
1777 touch print
1778
1779This rule uses `print' as an empty target file; see *Note Empty Target
1780Files to Record Events: Empty Targets. (The automatic variable `$?' is
1781used to print only those files that have changed; see *Note Automatic
1782Variables::.)
1783
1784 Wildcard expansion does not happen when you define a variable.
1785Thus, if you write this:
1786
1787 objects = *.o
1788
1789then the value of the variable `objects' is the actual string `*.o'.
1790However, if you use the value of `objects' in a target, prerequisite or
1791command, wildcard expansion will take place at that time. To set
1792`objects' to the expansion, instead use:
1793
1794 objects := $(wildcard *.o)
1795
1796*Note Wildcard Function::.
1797
1798
1799File: make.info, Node: Wildcard Pitfall, Next: Wildcard Function, Prev: Wildcard Examples, Up: Wildcards
1800
18014.4.2 Pitfalls of Using Wildcards
1802---------------------------------
1803
1804Now here is an example of a naive way of using wildcard expansion, that
1805does not do what you would intend. Suppose you would like to say that
1806the executable file `foo' is made from all the object files in the
1807directory, and you write this:
1808
1809 objects = *.o
1810
1811 foo : $(objects)
1812 cc -o foo $(CFLAGS) $(objects)
1813
1814The value of `objects' is the actual string `*.o'. Wildcard expansion
1815happens in the rule for `foo', so that each _existing_ `.o' file
1816becomes a prerequisite of `foo' and will be recompiled if necessary.
1817
1818 But what if you delete all the `.o' files? When a wildcard matches
1819no files, it is left as it is, so then `foo' will depend on the
1820oddly-named file `*.o'. Since no such file is likely to exist, `make'
1821will give you an error saying it cannot figure out how to make `*.o'.
1822This is not what you want!
1823
1824 Actually it is possible to obtain the desired result with wildcard
1825expansion, but you need more sophisticated techniques, including the
1826`wildcard' function and string substitution. *Note The Function
1827`wildcard': Wildcard Function.
1828
1829 Microsoft operating systems (MS-DOS and MS-Windows) use backslashes
1830to separate directories in pathnames, like so:
1831
1832 c:\foo\bar\baz.c
1833
1834 This is equivalent to the Unix-style `c:/foo/bar/baz.c' (the `c:'
1835part is the so-called drive letter). When `make' runs on these
1836systems, it supports backslashes as well as the Unix-style forward
1837slashes in pathnames. However, this support does _not_ include the
1838wildcard expansion, where backslash is a quote character. Therefore,
1839you _must_ use Unix-style slashes in these cases.
1840
1841
1842File: make.info, Node: Wildcard Function, Prev: Wildcard Pitfall, Up: Wildcards
1843
18444.4.3 The Function `wildcard'
1845-----------------------------
1846
1847Wildcard expansion happens automatically in rules. But wildcard
1848expansion does not normally take place when a variable is set, or
1849inside the arguments of a function. If you want to do wildcard
1850expansion in such places, you need to use the `wildcard' function, like
1851this:
1852
1853 $(wildcard PATTERN...)
1854
1855This string, used anywhere in a makefile, is replaced by a
1856space-separated list of names of existing files that match one of the
1857given file name patterns. If no existing file name matches a pattern,
1858then that pattern is omitted from the output of the `wildcard'
1859function. Note that this is different from how unmatched wildcards
1860behave in rules, where they are used verbatim rather than ignored
1861(*note Wildcard Pitfall::).
1862
1863 One use of the `wildcard' function is to get a list of all the C
1864source files in a directory, like this:
1865
1866 $(wildcard *.c)
1867
1868 We can change the list of C source files into a list of object files
1869by replacing the `.c' suffix with `.o' in the result, like this:
1870
1871 $(patsubst %.c,%.o,$(wildcard *.c))
1872
1873(Here we have used another function, `patsubst'. *Note Functions for
1874String Substitution and Analysis: Text Functions.)
1875
1876 Thus, a makefile to compile all C source files in the directory and
1877then link them together could be written as follows:
1878
1879 objects := $(patsubst %.c,%.o,$(wildcard *.c))
1880
1881 foo : $(objects)
1882 cc -o foo $(objects)
1883
1884(This takes advantage of the implicit rule for compiling C programs, so
1885there is no need to write explicit rules for compiling the files.
1886*Note The Two Flavors of Variables: Flavors, for an explanation of
1887`:=', which is a variant of `='.)
1888
1889
1890File: make.info, Node: Directory Search, Next: Phony Targets, Prev: Wildcards, Up: Rules
1891
18924.5 Searching Directories for Prerequisites
1893===========================================
1894
1895For large systems, it is often desirable to put sources in a separate
1896directory from the binaries. The "directory search" features of `make'
1897facilitate this by searching several directories automatically to find
1898a prerequisite. When you redistribute the files among directories, you
1899do not need to change the individual rules, just the search paths.
1900
1901* Menu:
1902
1903* General Search:: Specifying a search path that applies
1904 to every prerequisite.
1905* Selective Search:: Specifying a search path
1906 for a specified class of names.
1907* Search Algorithm:: When and how search paths are applied.
1908* Commands/Search:: How to write shell commands that work together
1909 with search paths.
1910* Implicit/Search:: How search paths affect implicit rules.
1911* Libraries/Search:: Directory search for link libraries.
1912
1913
1914File: make.info, Node: General Search, Next: Selective Search, Prev: Directory Search, Up: Directory Search
1915
19164.5.1 `VPATH': Search Path for All Prerequisites
1917------------------------------------------------
1918
1919The value of the `make' variable `VPATH' specifies a list of
1920directories that `make' should search. Most often, the directories are
1921expected to contain prerequisite files that are not in the current
1922directory; however, `make' uses `VPATH' as a search list for both
1923prerequisites and targets of rules.
1924
1925 Thus, if a file that is listed as a target or prerequisite does not
1926exist in the current directory, `make' searches the directories listed
1927in `VPATH' for a file with that name. If a file is found in one of
1928them, that file may become the prerequisite (see below). Rules may then
1929specify the names of files in the prerequisite list as if they all
1930existed in the current directory. *Note Writing Shell Commands with
1931Directory Search: Commands/Search.
1932
1933 In the `VPATH' variable, directory names are separated by colons or
1934blanks. The order in which directories are listed is the order followed
1935by `make' in its search. (On MS-DOS and MS-Windows, semi-colons are
1936used as separators of directory names in `VPATH', since the colon can
1937be used in the pathname itself, after the drive letter.)
1938
1939 For example,
1940
1941 VPATH = src:../headers
1942
1943specifies a path containing two directories, `src' and `../headers',
1944which `make' searches in that order.
1945
1946 With this value of `VPATH', the following rule,
1947
1948 foo.o : foo.c
1949
1950is interpreted as if it were written like this:
1951
1952 foo.o : src/foo.c
1953
1954assuming the file `foo.c' does not exist in the current directory but
1955is found in the directory `src'.
1956
1957
1958File: make.info, Node: Selective Search, Next: Search Algorithm, Prev: General Search, Up: Directory Search
1959
19604.5.2 The `vpath' Directive
1961---------------------------
1962
1963Similar to the `VPATH' variable, but more selective, is the `vpath'
1964directive (note lower case), which allows you to specify a search path
1965for a particular class of file names: those that match a particular
1966pattern. Thus you can supply certain search directories for one class
1967of file names and other directories (or none) for other file names.
1968
1969 There are three forms of the `vpath' directive:
1970
1971`vpath PATTERN DIRECTORIES'
1972 Specify the search path DIRECTORIES for file names that match
1973 PATTERN.
1974
1975 The search path, DIRECTORIES, is a list of directories to be
1976 searched, separated by colons (semi-colons on MS-DOS and
1977 MS-Windows) or blanks, just like the search path used in the
1978 `VPATH' variable.
1979
1980`vpath PATTERN'
1981 Clear out the search path associated with PATTERN.
1982
1983`vpath'
1984 Clear all search paths previously specified with `vpath'
1985 directives.
1986
1987 A `vpath' pattern is a string containing a `%' character. The
1988string must match the file name of a prerequisite that is being searched
1989for, the `%' character matching any sequence of zero or more characters
1990(as in pattern rules; *note Defining and Redefining Pattern Rules:
1991Pattern Rules.). For example, `%.h' matches files that end in `.h'.
1992(If there is no `%', the pattern must match the prerequisite exactly,
1993which is not useful very often.)
1994
1995 `%' characters in a `vpath' directive's pattern can be quoted with
1996preceding backslashes (`\'). Backslashes that would otherwise quote
1997`%' characters can be quoted with more backslashes. Backslashes that
1998quote `%' characters or other backslashes are removed from the pattern
1999before it is compared to file names. Backslashes that are not in
2000danger of quoting `%' characters go unmolested.
2001
2002 When a prerequisite fails to exist in the current directory, if the
2003PATTERN in a `vpath' directive matches the name of the prerequisite
2004file, then the DIRECTORIES in that directive are searched just like
2005(and before) the directories in the `VPATH' variable.
2006
2007 For example,
2008
2009 vpath %.h ../headers
2010
2011tells `make' to look for any prerequisite whose name ends in `.h' in
2012the directory `../headers' if the file is not found in the current
2013directory.
2014
2015 If several `vpath' patterns match the prerequisite file's name, then
2016`make' processes each matching `vpath' directive one by one, searching
2017all the directories mentioned in each directive. `make' handles
2018multiple `vpath' directives in the order in which they appear in the
2019makefile; multiple directives with the same pattern are independent of
2020each other.
2021
2022 Thus,
2023
2024 vpath %.c foo
2025 vpath % blish
2026 vpath %.c bar
2027
2028will look for a file ending in `.c' in `foo', then `blish', then `bar',
2029while
2030
2031 vpath %.c foo:bar
2032 vpath % blish
2033
2034will look for a file ending in `.c' in `foo', then `bar', then `blish'.
2035
2036
2037File: make.info, Node: Search Algorithm, Next: Commands/Search, Prev: Selective Search, Up: Directory Search
2038
20394.5.3 How Directory Searches are Performed
2040------------------------------------------
2041
2042When a prerequisite is found through directory search, regardless of
2043type (general or selective), the pathname located may not be the one
2044that `make' actually provides you in the prerequisite list. Sometimes
2045the path discovered through directory search is thrown away.
2046
2047 The algorithm `make' uses to decide whether to keep or abandon a
2048path found via directory search is as follows:
2049
2050 1. If a target file does not exist at the path specified in the
2051 makefile, directory search is performed.
2052
2053 2. If the directory search is successful, that path is kept and this
2054 file is tentatively stored as the target.
2055
2056 3. All prerequisites of this target are examined using this same
2057 method.
2058
2059 4. After processing the prerequisites, the target may or may not need
2060 to be rebuilt:
2061
2062 a. If the target does _not_ need to be rebuilt, the path to the
2063 file found during directory search is used for any
2064 prerequisite lists which contain this target. In short, if
2065 `make' doesn't need to rebuild the target then you use the
2066 path found via directory search.
2067
2068 b. If the target _does_ need to be rebuilt (is out-of-date), the
2069 pathname found during directory search is _thrown away_, and
2070 the target is rebuilt using the file name specified in the
2071 makefile. In short, if `make' must rebuild, then the target
2072 is rebuilt locally, not in the directory found via directory
2073 search.
2074
2075 This algorithm may seem complex, but in practice it is quite often
2076exactly what you want.
2077
2078 Other versions of `make' use a simpler algorithm: if the file does
2079not exist, and it is found via directory search, then that pathname is
2080always used whether or not the target needs to be built. Thus, if the
2081target is rebuilt it is created at the pathname discovered during
2082directory search.
2083
2084 If, in fact, this is the behavior you want for some or all of your
2085directories, you can use the `GPATH' variable to indicate this to
2086`make'.
2087
2088 `GPATH' has the same syntax and format as `VPATH' (that is, a space-
2089or colon-delimited list of pathnames). If an out-of-date target is
2090found by directory search in a directory that also appears in `GPATH',
2091then that pathname is not thrown away. The target is rebuilt using the
2092expanded path.
2093
2094
2095File: make.info, Node: Commands/Search, Next: Implicit/Search, Prev: Search Algorithm, Up: Directory Search
2096
20974.5.4 Writing Shell Commands with Directory Search
2098--------------------------------------------------
2099
2100When a prerequisite is found in another directory through directory
2101search, this cannot change the commands of the rule; they will execute
2102as written. Therefore, you must write the commands with care so that
2103they will look for the prerequisite in the directory where `make' finds
2104it.
2105
2106 This is done with the "automatic variables" such as `$^' (*note
2107Automatic Variables::). For instance, the value of `$^' is a list of
2108all the prerequisites of the rule, including the names of the
2109directories in which they were found, and the value of `$@' is the
2110target. Thus:
2111
2112 foo.o : foo.c
2113 cc -c $(CFLAGS) $^ -o $@
2114
2115(The variable `CFLAGS' exists so you can specify flags for C
2116compilation by implicit rules; we use it here for consistency so it will
2117affect all C compilations uniformly; *note Variables Used by Implicit
2118Rules: Implicit Variables.)
2119
2120 Often the prerequisites include header files as well, which you do
2121not want to mention in the commands. The automatic variable `$<' is
2122just the first prerequisite:
2123
2124 VPATH = src:../headers
2125 foo.o : foo.c defs.h hack.h
2126 cc -c $(CFLAGS) $< -o $@
2127
2128
2129File: make.info, Node: Implicit/Search, Next: Libraries/Search, Prev: Commands/Search, Up: Directory Search
2130
21314.5.5 Directory Search and Implicit Rules
2132-----------------------------------------
2133
2134The search through the directories specified in `VPATH' or with `vpath'
2135also happens during consideration of implicit rules (*note Using
2136Implicit Rules: Implicit Rules.).
2137
2138 For example, when a file `foo.o' has no explicit rule, `make'
2139considers implicit rules, such as the built-in rule to compile `foo.c'
2140if that file exists. If such a file is lacking in the current
2141directory, the appropriate directories are searched for it. If `foo.c'
2142exists (or is mentioned in the makefile) in any of the directories, the
2143implicit rule for C compilation is applied.
2144
2145 The commands of implicit rules normally use automatic variables as a
2146matter of necessity; consequently they will use the file names found by
2147directory search with no extra effort.
2148
2149
2150File: make.info, Node: Libraries/Search, Prev: Implicit/Search, Up: Directory Search
2151
21524.5.6 Directory Search for Link Libraries
2153-----------------------------------------
2154
2155Directory search applies in a special way to libraries used with the
2156linker. This special feature comes into play when you write a
2157prerequisite whose name is of the form `-lNAME'. (You can tell
2158something strange is going on here because the prerequisite is normally
2159the name of a file, and the _file name_ of a library generally looks
2160like `libNAME.a', not like `-lNAME'.)
2161
2162 When a prerequisite's name has the form `-lNAME', `make' handles it
2163specially by searching for the file `libNAME.so' in the current
2164directory, in directories specified by matching `vpath' search paths
2165and the `VPATH' search path, and then in the directories `/lib',
2166`/usr/lib', and `PREFIX/lib' (normally `/usr/local/lib', but
2167MS-DOS/MS-Windows versions of `make' behave as if PREFIX is defined to
2168be the root of the DJGPP installation tree).
2169
2170 If that file is not found, then the file `libNAME.a' is searched
2171for, in the same directories as above.
2172
2173 For example, if there is a `/usr/lib/libcurses.a' library on your
2174system (and no `/usr/lib/libcurses.so' file), then
2175
2176 foo : foo.c -lcurses
2177 cc $^ -o $@
2178
2179would cause the command `cc foo.c /usr/lib/libcurses.a -o foo' to be
2180executed when `foo' is older than `foo.c' or than
2181`/usr/lib/libcurses.a'.
2182
2183 Although the default set of files to be searched for is `libNAME.so'
2184and `libNAME.a', this is customizable via the `.LIBPATTERNS' variable.
2185Each word in the value of this variable is a pattern string. When a
2186prerequisite like `-lNAME' is seen, `make' will replace the percent in
2187each pattern in the list with NAME and perform the above directory
2188searches using that library filename. If no library is found, the next
2189word in the list will be used.
2190
2191 The default value for `.LIBPATTERNS' is `lib%.so lib%.a', which
2192provides the default behavior described above.
2193
2194 You can turn off link library expansion completely by setting this
2195variable to an empty value.
2196
2197
2198File: make.info, Node: Phony Targets, Next: Force Targets, Prev: Directory Search, Up: Rules
2199
22004.6 Phony Targets
2201=================
2202
2203A phony target is one that is not really the name of a file. It is
2204just a name for some commands to be executed when you make an explicit
2205request. There are two reasons to use a phony target: to avoid a
2206conflict with a file of the same name, and to improve performance.
2207
2208 If you write a rule whose commands will not create the target file,
2209the commands will be executed every time the target comes up for
2210remaking. Here is an example:
2211
2212 clean:
2213 rm *.o temp
2214
2215Because the `rm' command does not create a file named `clean', probably
2216no such file will ever exist. Therefore, the `rm' command will be
2217executed every time you say `make clean'.
2218
2219 The phony target will cease to work if anything ever does create a
2220file named `clean' in this directory. Since it has no prerequisites,
2221the file `clean' would inevitably be considered up to date, and its
2222commands would not be executed. To avoid this problem, you can
2223explicitly declare the target to be phony, using the special target
2224`.PHONY' (*note Special Built-in Target Names: Special Targets.) as
2225follows:
2226
2227 .PHONY : clean
2228
2229Once this is done, `make clean' will run the commands regardless of
2230whether there is a file named `clean'.
2231
2232 Since it knows that phony targets do not name actual files that
2233could be remade from other files, `make' skips the implicit rule search
2234for phony targets (*note Implicit Rules::). This is why declaring a
2235target phony is good for performance, even if you are not worried about
2236the actual file existing.
2237
2238 Thus, you first write the line that states that `clean' is a phony
2239target, then you write the rule, like this:
2240
2241 .PHONY: clean
2242 clean:
2243 rm *.o temp
2244
2245 Another example of the usefulness of phony targets is in conjunction
2246with recursive invocations of `make' (for more information, see *Note
2247Recursive Use of `make': Recursion.). In this case the makefile will
2248often contain a variable which lists a number of subdirectories to be
2249built. One way to handle this is with one rule whose command is a
2250shell loop over the subdirectories, like this:
2251
2252 SUBDIRS = foo bar baz
2253
2254 subdirs:
2255 for dir in $(SUBDIRS); do \
2256 $(MAKE) -C $$dir; \
2257 done
2258
2259 There are a few problems with this method, however. First, any error
2260detected in a submake is not noted by this rule, so it will continue to
2261build the rest of the directories even when one fails. This can be
2262overcome by adding shell commands to note the error and exit, but then
2263it will do so even if `make' is invoked with the `-k' option, which is
2264unfortunate. Second, and perhaps more importantly, you cannot take
2265advantage of `make''s ability to build targets in parallel (*note
2266Parallel Execution: Parallel.), since there is only one rule.
2267
2268 By declaring the subdirectories as phony targets (you must do this as
2269the subdirectory obviously always exists; otherwise it won't be built)
2270you can remove these problems:
2271
2272 SUBDIRS = foo bar baz
2273
2274 .PHONY: subdirs $(SUBDIRS)
2275
2276 subdirs: $(SUBDIRS)
2277
2278 $(SUBDIRS):
2279 $(MAKE) -C $@
2280
2281 foo: baz
2282
2283 Here we've also declared that the `foo' subdirectory cannot be built
2284until after the `baz' subdirectory is complete; this kind of
2285relationship declaration is particularly important when attempting
2286parallel builds.
2287
2288 A phony target should not be a prerequisite of a real target file;
2289if it is, its commands are run every time `make' goes to update that
2290file. As long as a phony target is never a prerequisite of a real
2291target, the phony target commands will be executed only when the phony
2292target is a specified goal (*note Arguments to Specify the Goals:
2293Goals.).
2294
2295 Phony targets can have prerequisites. When one directory contains
2296multiple programs, it is most convenient to describe all of the
2297programs in one makefile `./Makefile'. Since the target remade by
2298default will be the first one in the makefile, it is common to make
2299this a phony target named `all' and give it, as prerequisites, all the
2300individual programs. For example:
2301
2302 all : prog1 prog2 prog3
2303 .PHONY : all
2304
2305 prog1 : prog1.o utils.o
2306 cc -o prog1 prog1.o utils.o
2307
2308 prog2 : prog2.o
2309 cc -o prog2 prog2.o
2310
2311 prog3 : prog3.o sort.o utils.o
2312 cc -o prog3 prog3.o sort.o utils.o
2313
2314Now you can say just `make' to remake all three programs, or specify as
2315arguments the ones to remake (as in `make prog1 prog3'). Phoniness is
2316not inherited: the prerequisites of a phony target are not themselves
2317phony, unless explicitly declared to be so.
2318
2319 When one phony target is a prerequisite of another, it serves as a
2320subroutine of the other. For example, here `make cleanall' will delete
2321the object files, the difference files, and the file `program':
2322
2323 .PHONY: cleanall cleanobj cleandiff
2324
2325 cleanall : cleanobj cleandiff
2326 rm program
2327
2328 cleanobj :
2329 rm *.o
2330
2331 cleandiff :
2332 rm *.diff
2333
2334
2335File: make.info, Node: Force Targets, Next: Empty Targets, Prev: Phony Targets, Up: Rules
2336
23374.7 Rules without Commands or Prerequisites
2338===========================================
2339
2340If a rule has no prerequisites or commands, and the target of the rule
2341is a nonexistent file, then `make' imagines this target to have been
2342updated whenever its rule is run. This implies that all targets
2343depending on this one will always have their commands run.
2344
2345 An example will illustrate this:
2346
2347 clean: FORCE
2348 rm $(objects)
2349 FORCE:
2350
2351 Here the target `FORCE' satisfies the special conditions, so the
2352target `clean' that depends on it is forced to run its commands. There
2353is nothing special about the name `FORCE', but that is one name
2354commonly used this way.
2355
2356 As you can see, using `FORCE' this way has the same results as using
2357`.PHONY: clean'.
2358
2359 Using `.PHONY' is more explicit and more efficient. However, other
2360versions of `make' do not support `.PHONY'; thus `FORCE' appears in
2361many makefiles. *Note Phony Targets::.
2362
2363
2364File: make.info, Node: Empty Targets, Next: Special Targets, Prev: Force Targets, Up: Rules
2365
23664.8 Empty Target Files to Record Events
2367=======================================
2368
2369The "empty target" is a variant of the phony target; it is used to hold
2370commands for an action that you request explicitly from time to time.
2371Unlike a phony target, this target file can really exist; but the file's
2372contents do not matter, and usually are empty.
2373
2374 The purpose of the empty target file is to record, with its
2375last-modification time, when the rule's commands were last executed. It
2376does so because one of the commands is a `touch' command to update the
2377target file.
2378
2379 The empty target file should have some prerequisites (otherwise it
2380doesn't make sense). When you ask to remake the empty target, the
2381commands are executed if any prerequisite is more recent than the
2382target; in other words, if a prerequisite has changed since the last
2383time you remade the target. Here is an example:
2384
2385 print: foo.c bar.c
2386 lpr -p $?
2387 touch print
2388
2389With this rule, `make print' will execute the `lpr' command if either
2390source file has changed since the last `make print'. The automatic
2391variable `$?' is used to print only those files that have changed
2392(*note Automatic Variables::).
2393
2394
2395File: make.info, Node: Special Targets, Next: Multiple Targets, Prev: Empty Targets, Up: Rules
2396
23974.9 Special Built-in Target Names
2398=================================
2399
2400Certain names have special meanings if they appear as targets.
2401
2402`.PHONY'
2403 The prerequisites of the special target `.PHONY' are considered to
2404 be phony targets. When it is time to consider such a target,
2405 `make' will run its commands unconditionally, regardless of
2406 whether a file with that name exists or what its last-modification
2407 time is. *Note Phony Targets: Phony Targets.
2408
2409`.SUFFIXES'
2410 The prerequisites of the special target `.SUFFIXES' are the list
2411 of suffixes to be used in checking for suffix rules. *Note
2412 Old-Fashioned Suffix Rules: Suffix Rules.
2413
2414`.DEFAULT'
2415 The commands specified for `.DEFAULT' are used for any target for
2416 which no rules are found (either explicit rules or implicit rules).
2417 *Note Last Resort::. If `.DEFAULT' commands are specified, every
2418 file mentioned as a prerequisite, but not as a target in a rule,
2419 will have these commands executed on its behalf. *Note Implicit
2420 Rule Search Algorithm: Implicit Rule Search.
2421
2422`.PRECIOUS'
2423 The targets which `.PRECIOUS' depends on are given the following
2424 special treatment: if `make' is killed or interrupted during the
2425 execution of their commands, the target is not deleted. *Note
2426 Interrupting or Killing `make': Interrupts. Also, if the target
2427 is an intermediate file, it will not be deleted after it is no
2428 longer needed, as is normally done. *Note Chains of Implicit
2429 Rules: Chained Rules. In this latter respect it overlaps with the
2430 `.SECONDARY' special target.
2431
2432 You can also list the target pattern of an implicit rule (such as
2433 `%.o') as a prerequisite file of the special target `.PRECIOUS' to
2434 preserve intermediate files created by rules whose target patterns
2435 match that file's name.
2436
2437`.INTERMEDIATE'
2438 The targets which `.INTERMEDIATE' depends on are treated as
2439 intermediate files. *Note Chains of Implicit Rules: Chained Rules.
2440 `.INTERMEDIATE' with no prerequisites has no effect.
2441
2442`.SECONDARY'
2443 The targets which `.SECONDARY' depends on are treated as
2444 intermediate files, except that they are never automatically
2445 deleted. *Note Chains of Implicit Rules: Chained Rules.
2446
2447 `.SECONDARY' with no prerequisites causes all targets to be treated
2448 as secondary (i.e., no target is removed because it is considered
2449 intermediate).
2450
2451`.SECONDEXPANSION'
2452 If `.SECONDEXPANSION' is mentioned as a target anywhere in the
2453 makefile, then all prerequisite lists defined _after_ it appears
2454 will be expanded a second time after all makefiles have been read
2455 in. *Note Secondary Expansion: Secondary Expansion.
2456
2457 The prerequisites of the special target `.SUFFIXES' are the list
2458 of suffixes to be used in checking for suffix rules. *Note
2459 Old-Fashioned Suffix Rules: Suffix Rules.
2460
2461`.DELETE_ON_ERROR'
2462 If `.DELETE_ON_ERROR' is mentioned as a target anywhere in the
2463 makefile, then `make' will delete the target of a rule if it has
2464 changed and its commands exit with a nonzero exit status, just as
2465 it does when it receives a signal. *Note Errors in Commands:
2466 Errors.
2467
2468`.IGNORE'
2469 If you specify prerequisites for `.IGNORE', then `make' will
2470 ignore errors in execution of the commands run for those particular
2471 files. The commands for `.IGNORE' are not meaningful.
2472
2473 If mentioned as a target with no prerequisites, `.IGNORE' says to
2474 ignore errors in execution of commands for all files. This usage
2475 of `.IGNORE' is supported only for historical compatibility. Since
2476 this affects every command in the makefile, it is not very useful;
2477 we recommend you use the more selective ways to ignore errors in
2478 specific commands. *Note Errors in Commands: Errors.
2479
2480`.LOW_RESOLUTION_TIME'
2481 If you specify prerequisites for `.LOW_RESOLUTION_TIME', `make'
2482 assumes that these files are created by commands that generate low
2483 resolution time stamps. The commands for `.LOW_RESOLUTION_TIME'
2484 are not meaningful.
2485
2486 The high resolution file time stamps of many modern hosts lessen
2487 the chance of `make' incorrectly concluding that a file is up to
2488 date. Unfortunately, these hosts provide no way to set a high
2489 resolution file time stamp, so commands like `cp -p' that
2490 explicitly set a file's time stamp must discard its subsecond
2491 part. If a file is created by such a command, you should list it
2492 as a prerequisite of `.LOW_RESOLUTION_TIME' so that `make' does
2493 not mistakenly conclude that the file is out of date. For example:
2494
2495 .LOW_RESOLUTION_TIME: dst
2496 dst: src
2497 cp -p src dst
2498
2499 Since `cp -p' discards the subsecond part of `src''s time stamp,
2500 `dst' is typically slightly older than `src' even when it is up to
2501 date. The `.LOW_RESOLUTION_TIME' line causes `make' to consider
2502 `dst' to be up to date if its time stamp is at the start of the
2503 same second that `src''s time stamp is in.
2504
2505 Due to a limitation of the archive format, archive member time
2506 stamps are always low resolution. You need not list archive
2507 members as prerequisites of `.LOW_RESOLUTION_TIME', as `make' does
2508 this automatically.
2509
2510`.SILENT'
2511 If you specify prerequisites for `.SILENT', then `make' will not
2512 print the commands to remake those particular files before
2513 executing them. The commands for `.SILENT' are not meaningful.
2514
2515 If mentioned as a target with no prerequisites, `.SILENT' says not
2516 to print any commands before executing them. This usage of
2517 `.SILENT' is supported only for historical compatibility. We
2518 recommend you use the more selective ways to silence specific
2519 commands. *Note Command Echoing: Echoing. If you want to silence
2520 all commands for a particular run of `make', use the `-s' or
2521 `--silent' option (*note Options Summary::).
2522
2523`.EXPORT_ALL_VARIABLES'
2524 Simply by being mentioned as a target, this tells `make' to export
2525 all variables to child processes by default. *Note Communicating
2526 Variables to a Sub-`make': Variables/Recursion.
2527
2528`.NOTPARALLEL'
2529 If `.NOTPARALLEL' is mentioned as a target, then this invocation of
2530 `make' will be run serially, even if the `-j' option is given.
2531 Any recursively invoked `make' command will still be run in
2532 parallel (unless its makefile contains this target). Any
2533 prerequisites on this target are ignored.
2534
2535 Any defined implicit rule suffix also counts as a special target if
2536it appears as a target, and so does the concatenation of two suffixes,
2537such as `.c.o'. These targets are suffix rules, an obsolete way of
2538defining implicit rules (but a way still widely used). In principle,
2539any target name could be special in this way if you break it in two and
2540add both pieces to the suffix list. In practice, suffixes normally
2541begin with `.', so these special target names also begin with `.'.
2542*Note Old-Fashioned Suffix Rules: Suffix Rules.
2543
2544
2545File: make.info, Node: Multiple Targets, Next: Multiple Rules, Prev: Special Targets, Up: Rules
2546
25474.10 Multiple Targets in a Rule
2548===============================
2549
2550A rule with multiple targets is equivalent to writing many rules, each
2551with one target, and all identical aside from that. The same commands
2552apply to all the targets, but their effects may vary because you can
2553substitute the actual target name into the command using `$@'. The
2554rule contributes the same prerequisites to all the targets also.
2555
2556 This is useful in two cases.
2557
2558 * You want just prerequisites, no commands. For example:
2559
2560 kbd.o command.o files.o: command.h
2561
2562 gives an additional prerequisite to each of the three object files
2563 mentioned.
2564
2565 * Similar commands work for all the targets. The commands do not
2566 need to be absolutely identical, since the automatic variable `$@'
2567 can be used to substitute the particular target to be remade into
2568 the commands (*note Automatic Variables::). For example:
2569
2570 bigoutput littleoutput : text.g
2571 generate text.g -$(subst output,,$@) > $@
2572
2573 is equivalent to
2574
2575 bigoutput : text.g
2576 generate text.g -big > bigoutput
2577 littleoutput : text.g
2578 generate text.g -little > littleoutput
2579
2580 Here we assume the hypothetical program `generate' makes two types
2581 of output, one if given `-big' and one if given `-little'. *Note
2582 Functions for String Substitution and Analysis: Text Functions,
2583 for an explanation of the `subst' function.
2584
2585 Suppose you would like to vary the prerequisites according to the
2586target, much as the variable `$@' allows you to vary the commands. You
2587cannot do this with multiple targets in an ordinary rule, but you can
2588do it with a "static pattern rule". *Note Static Pattern Rules: Static
2589Pattern.
2590
2591
2592File: make.info, Node: Multiple Rules, Next: Static Pattern, Prev: Multiple Targets, Up: Rules
2593
25944.11 Multiple Rules for One Target
2595==================================
2596
2597One file can be the target of several rules. All the prerequisites
2598mentioned in all the rules are merged into one list of prerequisites for
2599the target. If the target is older than any prerequisite from any rule,
2600the commands are executed.
2601
2602 There can only be one set of commands to be executed for a file. If
2603more than one rule gives commands for the same file, `make' uses the
2604last set given and prints an error message. (As a special case, if the
2605file's name begins with a dot, no error message is printed. This odd
2606behavior is only for compatibility with other implementations of
2607`make'... you should avoid using it). Occasionally it is useful to
2608have the same target invoke multiple commands which are defined in
2609different parts of your makefile; you can use "double-colon rules"
2610(*note Double-Colon::) for this.
2611
2612 An extra rule with just prerequisites can be used to give a few extra
2613prerequisites to many files at once. For example, makefiles often have
2614a variable, such as `objects', containing a list of all the compiler
2615output files in the system being made. An easy way to say that all of
2616them must be recompiled if `config.h' changes is to write the following:
2617
2618 objects = foo.o bar.o
2619 foo.o : defs.h
2620 bar.o : defs.h test.h
2621 $(objects) : config.h
2622
2623 This could be inserted or taken out without changing the rules that
2624really specify how to make the object files, making it a convenient
2625form to use if you wish to add the additional prerequisite
2626intermittently.
2627
2628 Another wrinkle is that the additional prerequisites could be
2629specified with a variable that you set with a command argument to `make'
2630(*note Overriding Variables: Overriding.). For example,
2631
2632 extradeps=
2633 $(objects) : $(extradeps)
2634
2635means that the command `make extradeps=foo.h' will consider `foo.h' as
2636a prerequisite of each object file, but plain `make' will not.
2637
2638 If none of the explicit rules for a target has commands, then `make'
2639searches for an applicable implicit rule to find some commands *note
2640Using Implicit Rules: Implicit Rules.).
2641
2642
2643File: make.info, Node: Static Pattern, Next: Double-Colon, Prev: Multiple Rules, Up: Rules
2644
26454.12 Static Pattern Rules
2646=========================
2647
2648"Static pattern rules" are rules which specify multiple targets and
2649construct the prerequisite names for each target based on the target
2650name. They are more general than ordinary rules with multiple targets
2651because the targets do not have to have identical prerequisites. Their
2652prerequisites must be _analogous_, but not necessarily _identical_.
2653
2654* Menu:
2655
2656* Static Usage:: The syntax of static pattern rules.
2657* Static versus Implicit:: When are they better than implicit rules?
2658
2659
2660File: make.info, Node: Static Usage, Next: Static versus Implicit, Prev: Static Pattern, Up: Static Pattern
2661
26624.12.1 Syntax of Static Pattern Rules
2663-------------------------------------
2664
2665Here is the syntax of a static pattern rule:
2666
2667 TARGETS ...: TARGET-PATTERN: PREREQ-PATTERNS ...
2668 COMMANDS
2669 ...
2670
2671The TARGETS list specifies the targets that the rule applies to. The
2672targets can contain wildcard characters, just like the targets of
2673ordinary rules (*note Using Wildcard Characters in File Names:
2674Wildcards.).
2675
2676 The TARGET-PATTERN and PREREQ-PATTERNS say how to compute the
2677prerequisites of each target. Each target is matched against the
2678TARGET-PATTERN to extract a part of the target name, called the "stem".
2679This stem is substituted into each of the PREREQ-PATTERNS to make the
2680prerequisite names (one from each PREREQ-PATTERN).
2681
2682 Each pattern normally contains the character `%' just once. When the
2683TARGET-PATTERN matches a target, the `%' can match any part of the
2684target name; this part is called the "stem". The rest of the pattern
2685must match exactly. For example, the target `foo.o' matches the
2686pattern `%.o', with `foo' as the stem. The targets `foo.c' and
2687`foo.out' do not match that pattern.
2688
2689 The prerequisite names for each target are made by substituting the
2690stem for the `%' in each prerequisite pattern. For example, if one
2691prerequisite pattern is `%.c', then substitution of the stem `foo'
2692gives the prerequisite name `foo.c'. It is legitimate to write a
2693prerequisite pattern that does not contain `%'; then this prerequisite
2694is the same for all targets.
2695
2696 `%' characters in pattern rules can be quoted with preceding
2697backslashes (`\'). Backslashes that would otherwise quote `%'
2698characters can be quoted with more backslashes. Backslashes that quote
2699`%' characters or other backslashes are removed from the pattern before
2700it is compared to file names or has a stem substituted into it.
2701Backslashes that are not in danger of quoting `%' characters go
2702unmolested. For example, the pattern `the\%weird\\%pattern\\' has
2703`the%weird\' preceding the operative `%' character, and `pattern\\'
2704following it. The final two backslashes are left alone because they
2705cannot affect any `%' character.
2706
2707 Here is an example, which compiles each of `foo.o' and `bar.o' from
2708the corresponding `.c' file:
2709
2710 objects = foo.o bar.o
2711
2712 all: $(objects)
2713
2714 $(objects): %.o: %.c
2715 $(CC) -c $(CFLAGS) $< -o $@
2716
2717Here `$<' is the automatic variable that holds the name of the
2718prerequisite and `$@' is the automatic variable that holds the name of
2719the target; see *Note Automatic Variables::.
2720
2721 Each target specified must match the target pattern; a warning is
2722issued for each target that does not. If you have a list of files,
2723only some of which will match the pattern, you can use the `filter'
2724function to remove nonmatching file names (*note Functions for String
2725Substitution and Analysis: Text Functions.):
2726
2727 files = foo.elc bar.o lose.o
2728
2729 $(filter %.o,$(files)): %.o: %.c
2730 $(CC) -c $(CFLAGS) $< -o $@
2731 $(filter %.elc,$(files)): %.elc: %.el
2732 emacs -f batch-byte-compile $<
2733
2734In this example the result of `$(filter %.o,$(files))' is `bar.o
2735lose.o', and the first static pattern rule causes each of these object
2736files to be updated by compiling the corresponding C source file. The
2737result of `$(filter %.elc,$(files))' is `foo.elc', so that file is made
2738from `foo.el'.
2739
2740 Another example shows how to use `$*' in static pattern rules:
2741
2742 bigoutput littleoutput : %output : text.g
2743 generate text.g -$* > $@
2744
2745When the `generate' command is run, `$*' will expand to the stem,
2746either `big' or `little'.
2747
2748
2749File: make.info, Node: Static versus Implicit, Prev: Static Usage, Up: Static Pattern
2750
27514.12.2 Static Pattern Rules versus Implicit Rules
2752-------------------------------------------------
2753
2754A static pattern rule has much in common with an implicit rule defined
2755as a pattern rule (*note Defining and Redefining Pattern Rules: Pattern
2756Rules.). Both have a pattern for the target and patterns for
2757constructing the names of prerequisites. The difference is in how
2758`make' decides _when_ the rule applies.
2759
2760 An implicit rule _can_ apply to any target that matches its pattern,
2761but it _does_ apply only when the target has no commands otherwise
2762specified, and only when the prerequisites can be found. If more than
2763one implicit rule appears applicable, only one applies; the choice
2764depends on the order of rules.
2765
2766 By contrast, a static pattern rule applies to the precise list of
2767targets that you specify in the rule. It cannot apply to any other
2768target and it invariably does apply to each of the targets specified.
2769If two conflicting rules apply, and both have commands, that's an error.
2770
2771 The static pattern rule can be better than an implicit rule for these
2772reasons:
2773
2774 * You may wish to override the usual implicit rule for a few files
2775 whose names cannot be categorized syntactically but can be given
2776 in an explicit list.
2777
2778 * If you cannot be sure of the precise contents of the directories
2779 you are using, you may not be sure which other irrelevant files
2780 might lead `make' to use the wrong implicit rule. The choice
2781 might depend on the order in which the implicit rule search is
2782 done. With static pattern rules, there is no uncertainty: each
2783 rule applies to precisely the targets specified.
2784
2785
2786File: make.info, Node: Double-Colon, Next: Automatic Prerequisites, Prev: Static Pattern, Up: Rules
2787
27884.13 Double-Colon Rules
2789=======================
2790
2791"Double-colon" rules are rules written with `::' instead of `:' after
2792the target names. They are handled differently from ordinary rules
2793when the same target appears in more than one rule.
2794
2795 When a target appears in multiple rules, all the rules must be the
2796same type: all ordinary, or all double-colon. If they are
2797double-colon, each of them is independent of the others. Each
2798double-colon rule's commands are executed if the target is older than
2799any prerequisites of that rule. If there are no prerequisites for that
2800rule, its commands are always executed (even if the target already
2801exists). This can result in executing none, any, or all of the
2802double-colon rules.
2803
2804 Double-colon rules with the same target are in fact completely
2805separate from one another. Each double-colon rule is processed
2806individually, just as rules with different targets are processed.
2807
2808 The double-colon rules for a target are executed in the order they
2809appear in the makefile. However, the cases where double-colon rules
2810really make sense are those where the order of executing the commands
2811would not matter.
2812
2813 Double-colon rules are somewhat obscure and not often very useful;
2814they provide a mechanism for cases in which the method used to update a
2815target differs depending on which prerequisite files caused the update,
2816and such cases are rare.
2817
2818 Each double-colon rule should specify commands; if it does not, an
2819implicit rule will be used if one applies. *Note Using Implicit Rules:
2820Implicit Rules.
2821
2822
2823File: make.info, Node: Automatic Prerequisites, Prev: Double-Colon, Up: Rules
2824
28254.14 Generating Prerequisites Automatically
2826===========================================
2827
2828In the makefile for a program, many of the rules you need to write often
2829say only that some object file depends on some header file. For
2830example, if `main.c' uses `defs.h' via an `#include', you would write:
2831
2832 main.o: defs.h
2833
2834You need this rule so that `make' knows that it must remake `main.o'
2835whenever `defs.h' changes. You can see that for a large program you
2836would have to write dozens of such rules in your makefile. And, you
2837must always be very careful to update the makefile every time you add
2838or remove an `#include'.
2839
2840 To avoid this hassle, most modern C compilers can write these rules
2841for you, by looking at the `#include' lines in the source files.
2842Usually this is done with the `-M' option to the compiler. For
2843example, the command:
2844
2845 cc -M main.c
2846
2847generates the output:
2848
2849 main.o : main.c defs.h
2850
2851Thus you no longer have to write all those rules yourself. The
2852compiler will do it for you.
2853
2854 Note that such a prerequisite constitutes mentioning `main.o' in a
2855makefile, so it can never be considered an intermediate file by implicit
2856rule search. This means that `make' won't ever remove the file after
2857using it; *note Chains of Implicit Rules: Chained Rules.
2858
2859 With old `make' programs, it was traditional practice to use this
2860compiler feature to generate prerequisites on demand with a command like
2861`make depend'. That command would create a file `depend' containing
2862all the automatically-generated prerequisites; then the makefile could
2863use `include' to read them in (*note Include::).
2864
2865 In GNU `make', the feature of remaking makefiles makes this practice
2866obsolete--you need never tell `make' explicitly to regenerate the
2867prerequisites, because it always regenerates any makefile that is out
2868of date. *Note Remaking Makefiles::.
2869
2870 The practice we recommend for automatic prerequisite generation is
2871to have one makefile corresponding to each source file. For each
2872source file `NAME.c' there is a makefile `NAME.d' which lists what
2873files the object file `NAME.o' depends on. That way only the source
2874files that have changed need to be rescanned to produce the new
2875prerequisites.
2876
2877 Here is the pattern rule to generate a file of prerequisites (i.e.,
2878a makefile) called `NAME.d' from a C source file called `NAME.c':
2879
2880 %.d: %.c
2881 @set -e; rm -f $@; \
2882 $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
2883 sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
2884 rm -f $@.$$$$
2885
2886*Note Pattern Rules::, for information on defining pattern rules. The
2887`-e' flag to the shell causes it to exit immediately if the `$(CC)'
2888command (or any other command) fails (exits with a nonzero status).
2889
2890 With the GNU C compiler, you may wish to use the `-MM' flag instead
2891of `-M'. This omits prerequisites on system header files. *Note
2892Options Controlling the Preprocessor: (gcc.info)Preprocessor Options,
2893for details.
2894
2895 The purpose of the `sed' command is to translate (for example):
2896
2897 main.o : main.c defs.h
2898
2899into:
2900
2901 main.o main.d : main.c defs.h
2902
2903This makes each `.d' file depend on all the source and header files
2904that the corresponding `.o' file depends on. `make' then knows it must
2905regenerate the prerequisites whenever any of the source or header files
2906changes.
2907
2908 Once you've defined the rule to remake the `.d' files, you then use
2909the `include' directive to read them all in. *Note Include::. For
2910example:
2911
2912 sources = foo.c bar.c
2913
2914 include $(sources:.c=.d)
2915
2916(This example uses a substitution variable reference to translate the
2917list of source files `foo.c bar.c' into a list of prerequisite
2918makefiles, `foo.d bar.d'. *Note Substitution Refs::, for full
2919information on substitution references.) Since the `.d' files are
2920makefiles like any others, `make' will remake them as necessary with no
2921further work from you. *Note Remaking Makefiles::.
2922
2923 Note that the `.d' files contain target definitions; you should be
2924sure to place the `include' directive _after_ the first, default goal
2925in your makefiles or run the risk of having a random object file become
2926the default goal. *Note How Make Works::.
2927
2928
2929File: make.info, Node: Commands, Next: Using Variables, Prev: Rules, Up: Top
2930
29315 Writing the Commands in Rules
2932*******************************
2933
2934The commands of a rule consist of one or more shell command lines to be
2935executed, one at a time, in the order they appear. Typically, the
2936result of executing these commands is that the target of the rule is
2937brought up to date.
2938
2939 Users use many different shell programs, but commands in makefiles
2940are always interpreted by `/bin/sh' unless the makefile specifies
2941otherwise. *Note Command Execution: Execution.
2942
2943* Menu:
2944
2945* Command Syntax:: Command syntax features and pitfalls.
2946* Echoing:: How to control when commands are echoed.
2947* Execution:: How commands are executed.
2948* Parallel:: How commands can be executed in parallel.
2949* Errors:: What happens after a command execution error.
2950* Interrupts:: What happens when a command is interrupted.
2951* Recursion:: Invoking `make' from makefiles.
2952* Sequences:: Defining canned sequences of commands.
2953* Empty Commands:: Defining useful, do-nothing commands.
2954
2955
2956File: make.info, Node: Command Syntax, Next: Echoing, Prev: Commands, Up: Commands
2957
29585.1 Command Syntax
2959==================
2960
2961Makefiles have the unusual property that there are really two distinct
2962syntaxes in one file. Most of the makefile uses `make' syntax (*note
2963Writing Makefiles: Makefiles.). However, commands are meant to be
2964interpreted by the shell and so they are written using shell syntax.
2965The `make' program does not try to understand shell syntax: it performs
2966only a very few specific translations on the content of the command
2967before handing it to the shell.
2968
2969 Each command line must start with a tab, except that the first
2970command line may be attached to the target-and-prerequisites line with a
2971semicolon in between. _Any_ line in the makefile that begins with a
2972tab and appears in a "rule context" (that is, after a rule has been
2973started until another rule or variable definition) will be considered a
2974command line for that rule. Blank lines and lines of just comments may
2975appear among the command lines; they are ignored.
2976
2977 Some consequences of these rules include:
2978
2979 * A blank line that begins with a tab is not blank: it's an empty
2980 command (*note Empty Commands::).
2981
2982 * A comment in a command line is not a `make' comment; it will be
2983 passed to the shell as-is. Whether the shell treats it as a
2984 comment or not depends on your shell.
2985
2986 * A variable definition in a "rule context" which is indented by a
2987 tab as the first character on the line, will be considered a
2988 command line, not a `make' variable definition, and passed to the
2989 shell.
2990
2991 * A conditional expression (`ifdef', `ifeq', etc. *note Syntax of
2992 Conditionals: Conditional Syntax.) in a "rule context" which is
2993 indented by a tab as the first character on the line, will be
2994 considered a command line and be passed to the shell.
2995
2996
2997* Menu:
2998
2999* Splitting Lines:: Breaking long command lines for readability.
3000* Variables in Commands:: Using `make' variables in commands.
3001
3002
3003File: make.info, Node: Splitting Lines, Next: Variables in Commands, Prev: Command Syntax, Up: Command Syntax
3004
30055.1.1 Splitting Command Lines
3006-----------------------------
3007
3008One of the few ways in which `make' does interpret command lines is
3009checking for a backslash just before the newline. As in normal
3010makefile syntax, a single command can be split into multiple lines in
3011the makefile by placing a backslash before each newline. A sequence of
3012lines like this is considered a single command, and one instance of the
3013shell will be invoked to run it.
3014
3015 However, in contrast to how they are treated in other places in a
3016makefile, backslash-newline pairs are _not_ removed from the command.
3017Both the backslash and the newline characters are preserved and passed
3018to the shell. How the backslash-newline is interpreted depends on your
3019shell. If the first character of the next line after the
3020backslash-newline is a tab, then that tab (and only that tab) is
3021removed. Whitespace is never added to the command.
3022
3023 For example, this makefile:
3024
3025 all :
3026 @echo no\
3027 space
3028 @echo no\
3029 space
3030 @echo one \
3031 space
3032 @echo one\
3033 space
3034
3035consists of four separate shell commands where the output is:
3036
3037 nospace
3038 nospace
3039 one space
3040 one space
3041
3042 As a more complex example, this makefile:
3043
3044 all : ; @echo 'hello \
3045 world' ; echo "hello \
3046 world"
3047
3048will run one shell with a command script of:
3049
3050 echo 'hello \
3051 world' ; echo "hello \
3052 world"
3053
3054which, according to shell quoting rules, will yield the following
3055output:
3056
3057 hello \
3058 world
3059 hello world
3060
3061Notice how the backslash/newline pair was removed inside the string
3062quoted with double quotes (`"..."'), but not from the string quoted
3063with single quotes (`'...''). This is the way the default shell
3064(`/bin/sh') handles backslash/newline pairs. If you specify a
3065different shell in your makefiles it may treat them differently.
3066
3067 Sometimes you want to split a long line inside of single quotes, but
3068you don't want the backslash-newline to appear in the quoted content.
3069This is often the case when passing scripts to languages such as Perl,
3070where extraneous backslashes inside the script can change its meaning
3071or even be a syntax error. One simple way of handling this is to place
3072the quoted string, or even the entire command, into a `make' variable
3073then use the variable in the command. In this situation the newline
3074quoting rules for makefiles will be used, and the backslash-newline
3075will be removed. If we rewrite our example above using this method:
3076
3077 HELLO = 'hello \
3078 world'
3079
3080 all : ; @echo $(HELLO)
3081
3082we will get output like this:
3083
3084 hello world
3085
3086 If you like, you can also use target-specific variables (*note
3087Target-specific Variable Values: Target-specific.) to obtain a tighter
3088correspondence between the variable and the command that uses it.
3089
3090
3091File: make.info, Node: Variables in Commands, Prev: Splitting Lines, Up: Command Syntax
3092
30935.1.2 Using Variables in Commands
3094---------------------------------
3095
3096The other way in which `make' processes commands is by expanding any
3097variable references in them (*note Basics of Variable References:
3098Reference.). This occurs after make has finished reading all the
3099makefiles and the target is determined to be out of date; so, the
3100commands for targets which are not rebuilt are never expanded.
3101
3102 Variable and function references in commands have identical syntax
3103and semantics to references elsewhere in the makefile. They also have
3104the same quoting rules: if you want a dollar sign to appear in your
3105command, you must double it (`$$'). For shells like the default shell,
3106that use dollar signs to introduce variables, it's important to keep
3107clear in your mind whether the variable you want to reference is a
3108`make' variable (use a single dollar sign) or a shell variable (use two
3109dollar signs). For example:
3110
3111 LIST = one two three
3112 all:
3113 for i in $(LIST); do \
3114 echo $$i; \
3115 done
3116
3117results in the following command being passed to the shell:
3118
3119 for i in one two three; do \
3120 echo $i; \
3121 done
3122
3123which generates the expected result:
3124
3125 one
3126 two
3127 three
3128
3129
3130File: make.info, Node: Echoing, Next: Execution, Prev: Command Syntax, Up: Commands
3131
31325.2 Command Echoing
3133===================
3134
3135Normally `make' prints each command line before it is executed. We
3136call this "echoing" because it gives the appearance that you are typing
3137the commands yourself.
3138
3139 When a line starts with `@', the echoing of that line is suppressed.
3140The `@' is discarded before the command is passed to the shell.
3141Typically you would use this for a command whose only effect is to print
3142something, such as an `echo' command to indicate progress through the
3143makefile:
3144
3145 @echo About to make distribution files
3146
3147 When `make' is given the flag `-n' or `--just-print' it only echoes
3148commands, it won't execute them. *Note Summary of Options: Options
3149Summary. In this case and only this case, even the commands starting
3150with `@' are printed. This flag is useful for finding out which
3151commands `make' thinks are necessary without actually doing them.
3152
3153 The `-s' or `--silent' flag to `make' prevents all echoing, as if
3154all commands started with `@'. A rule in the makefile for the special
3155target `.SILENT' without prerequisites has the same effect (*note
3156Special Built-in Target Names: Special Targets.). `.SILENT' is
3157essentially obsolete since `@' is more flexible.
3158
3159
3160File: make.info, Node: Execution, Next: Parallel, Prev: Echoing, Up: Commands
3161
31625.3 Command Execution
3163=====================
3164
3165When it is time to execute commands to update a target, they are
3166executed by invoking a new subshell for each command line. (In
3167practice, `make' may take shortcuts that do not affect the results.)
3168
3169 *Please note:* this implies that setting shell variables and
3170invoking shell commands such as `cd' that set a context local to each
3171process will not affect the following command lines.(1) If you want to
3172use `cd' to affect the next statement, put both statements in a single
3173command line. Then `make' will invoke one shell to run the entire
3174line, and the shell will execute the statements in sequence. For
3175example:
3176
3177 foo : bar/lose
3178 cd $(@D) && gobble $(@F) > ../$@
3179
3180Here we use the shell AND operator (`&&') so that if the `cd' command
3181fails, the script will fail without trying to invoke the `gobble'
3182command in the wrong directory, which could cause problems (in this
3183case it would certainly cause `../foo' to be truncated, at least).
3184
3185* Menu:
3186
3187* Choosing the Shell:: How `make' chooses the shell used
3188 to run commands.
3189
3190 ---------- Footnotes ----------
3191
3192 (1) On MS-DOS, the value of current working directory is *global*, so
3193changing it _will_ affect the following command lines on those systems.
3194
3195
3196File: make.info, Node: Choosing the Shell, Prev: Execution, Up: Execution
3197
31985.3.1 Choosing the Shell
3199------------------------
3200
3201The program used as the shell is taken from the variable `SHELL'. If
3202this variable is not set in your makefile, the program `/bin/sh' is
3203used as the shell.
3204
3205 Unlike most variables, the variable `SHELL' is never set from the
3206environment. This is because the `SHELL' environment variable is used
3207to specify your personal choice of shell program for interactive use.
3208It would be very bad for personal choices like this to affect the
3209functioning of makefiles. *Note Variables from the Environment:
3210Environment.
3211
3212 Furthermore, when you do set `SHELL' in your makefile that value is
3213_not_ exported in the environment to commands that `make' invokes.
3214Instead, the value inherited from the user's environment, if any, is
3215exported. You can override this behavior by explicitly exporting
3216`SHELL' (*note Communicating Variables to a Sub-`make':
3217Variables/Recursion.), forcing it to be passed in the environment to
3218commands.
3219
3220 However, on MS-DOS and MS-Windows the value of `SHELL' in the
3221environment *is* used, since on those systems most users do not set
3222this variable, and therefore it is most likely set specifically to be
3223used by `make'. On MS-DOS, if the setting of `SHELL' is not suitable
3224for `make', you can set the variable `MAKESHELL' to the shell that
3225`make' should use; if set it will be used as the shell instead of the
3226value of `SHELL'.
3227
3228Choosing a Shell in DOS and Windows
3229...................................
3230
3231Choosing a shell in MS-DOS and MS-Windows is much more complex than on
3232other systems.
3233
3234 On MS-DOS, if `SHELL' is not set, the value of the variable
3235`COMSPEC' (which is always set) is used instead.
3236
3237 The processing of lines that set the variable `SHELL' in Makefiles
3238is different on MS-DOS. The stock shell, `command.com', is
3239ridiculously limited in its functionality and many users of `make' tend
3240to install a replacement shell. Therefore, on MS-DOS, `make' examines
3241the value of `SHELL', and changes its behavior based on whether it
3242points to a Unix-style or DOS-style shell. This allows reasonable
3243functionality even if `SHELL' points to `command.com'.
3244
3245 If `SHELL' points to a Unix-style shell, `make' on MS-DOS
3246additionally checks whether that shell can indeed be found; if not, it
3247ignores the line that sets `SHELL'. In MS-DOS, GNU `make' searches for
3248the shell in the following places:
3249
3250 1. In the precise place pointed to by the value of `SHELL'. For
3251 example, if the makefile specifies `SHELL = /bin/sh', `make' will
3252 look in the directory `/bin' on the current drive.
3253
3254 2. In the current directory.
3255
3256 3. In each of the directories in the `PATH' variable, in order.
3257
3258
3259 In every directory it examines, `make' will first look for the
3260specific file (`sh' in the example above). If this is not found, it
3261will also look in that directory for that file with one of the known
3262extensions which identify executable files. For example `.exe',
3263`.com', `.bat', `.btm', `.sh', and some others.
3264
3265 If any of these attempts is successful, the value of `SHELL' will be
3266set to the full pathname of the shell as found. However, if none of
3267these is found, the value of `SHELL' will not be changed, and thus the
3268line that sets it will be effectively ignored. This is so `make' will
3269only support features specific to a Unix-style shell if such a shell is
3270actually installed on the system where `make' runs.
3271
3272 Note that this extended search for the shell is limited to the cases
3273where `SHELL' is set from the Makefile; if it is set in the environment
3274or command line, you are expected to set it to the full pathname of the
3275shell, exactly as things are on Unix.
3276
3277 The effect of the above DOS-specific processing is that a Makefile
3278that contains `SHELL = /bin/sh' (as many Unix makefiles do), will work
3279on MS-DOS unaltered if you have e.g. `sh.exe' installed in some
3280directory along your `PATH'.
3281
3282
3283File: make.info, Node: Parallel, Next: Errors, Prev: Execution, Up: Commands
3284
32855.4 Parallel Execution
3286======================
3287
3288GNU `make' knows how to execute several commands at once. Normally,
3289`make' will execute only one command at a time, waiting for it to
3290finish before executing the next. However, the `-j' or `--jobs' option
3291tells `make' to execute many commands simultaneously.
3292
3293 On MS-DOS, the `-j' option has no effect, since that system doesn't
3294support multi-processing.
3295
3296 If the `-j' option is followed by an integer, this is the number of
3297commands to execute at once; this is called the number of "job slots".
3298If there is nothing looking like an integer after the `-j' option,
3299there is no limit on the number of job slots. The default number of job
3300slots is one, which means serial execution (one thing at a time).
3301
3302 One unpleasant consequence of running several commands
3303simultaneously is that output generated by the commands appears
3304whenever each command sends it, so messages from different commands may
3305be interspersed.
3306
3307 Another problem is that two processes cannot both take input from the
3308same device; so to make sure that only one command tries to take input
3309from the terminal at once, `make' will invalidate the standard input
3310streams of all but one running command. This means that attempting to
3311read from standard input will usually be a fatal error (a `Broken pipe'
3312signal) for most child processes if there are several.
3313
3314 It is unpredictable which command will have a valid standard input
3315stream (which will come from the terminal, or wherever you redirect the
3316standard input of `make'). The first command run will always get it
3317first, and the first command started after that one finishes will get
3318it next, and so on.
3319
3320 We will change how this aspect of `make' works if we find a better
3321alternative. In the mean time, you should not rely on any command using
3322standard input at all if you are using the parallel execution feature;
3323but if you are not using this feature, then standard input works
3324normally in all commands.
3325
3326 Finally, handling recursive `make' invocations raises issues. For
3327more information on this, see *Note Communicating Options to a
3328Sub-`make': Options/Recursion.
3329
3330 If a command fails (is killed by a signal or exits with a nonzero
3331status), and errors are not ignored for that command (*note Errors in
3332Commands: Errors.), the remaining command lines to remake the same
3333target will not be run. If a command fails and the `-k' or
3334`--keep-going' option was not given (*note Summary of Options: Options
3335Summary.), `make' aborts execution. If make terminates for any reason
3336(including a signal) with child processes running, it waits for them to
3337finish before actually exiting.
3338
3339 When the system is heavily loaded, you will probably want to run
3340fewer jobs than when it is lightly loaded. You can use the `-l' option
3341to tell `make' to limit the number of jobs to run at once, based on the
3342load average. The `-l' or `--max-load' option is followed by a
3343floating-point number. For example,
3344
3345 -l 2.5
3346
3347will not let `make' start more than one job if the load average is
3348above 2.5. The `-l' option with no following number removes the load
3349limit, if one was given with a previous `-l' option.
3350
3351 More precisely, when `make' goes to start up a job, and it already
3352has at least one job running, it checks the current load average; if it
3353is not lower than the limit given with `-l', `make' waits until the load
3354average goes below that limit, or until all the other jobs finish.
3355
3356 By default, there is no load limit.
3357
3358
3359File: make.info, Node: Errors, Next: Interrupts, Prev: Parallel, Up: Commands
3360
33615.5 Errors in Commands
3362======================
3363
3364After each shell command returns, `make' looks at its exit status. If
3365the command completed successfully, the next command line is executed
3366in a new shell; after the last command line is finished, the rule is
3367finished.
3368
3369 If there is an error (the exit status is nonzero), `make' gives up on
3370the current rule, and perhaps on all rules.
3371
3372 Sometimes the failure of a certain command does not indicate a
3373problem. For example, you may use the `mkdir' command to ensure that a
3374directory exists. If the directory already exists, `mkdir' will report
3375an error, but you probably want `make' to continue regardless.
3376
3377 To ignore errors in a command line, write a `-' at the beginning of
3378the line's text (after the initial tab). The `-' is discarded before
3379the command is passed to the shell for execution.
3380
3381 For example,
3382
3383 clean:
3384 -rm -f *.o
3385
3386This causes `rm' to continue even if it is unable to remove a file.
3387
3388 When you run `make' with the `-i' or `--ignore-errors' flag, errors
3389are ignored in all commands of all rules. A rule in the makefile for
3390the special target `.IGNORE' has the same effect, if there are no
3391prerequisites. These ways of ignoring errors are obsolete because `-'
3392is more flexible.
3393
3394 When errors are to be ignored, because of either a `-' or the `-i'
3395flag, `make' treats an error return just like success, except that it
3396prints out a message that tells you the status code the command exited
3397with, and says that the error has been ignored.
3398
3399 When an error happens that `make' has not been told to ignore, it
3400implies that the current target cannot be correctly remade, and neither
3401can any other that depends on it either directly or indirectly. No
3402further commands will be executed for these targets, since their
3403preconditions have not been achieved.
3404
3405 Normally `make' gives up immediately in this circumstance, returning
3406a nonzero status. However, if the `-k' or `--keep-going' flag is
3407specified, `make' continues to consider the other prerequisites of the
3408pending targets, remaking them if necessary, before it gives up and
3409returns nonzero status. For example, after an error in compiling one
3410object file, `make -k' will continue compiling other object files even
3411though it already knows that linking them will be impossible. *Note
3412Summary of Options: Options Summary.
3413
3414 The usual behavior assumes that your purpose is to get the specified
3415targets up to date; once `make' learns that this is impossible, it
3416might as well report the failure immediately. The `-k' option says
3417that the real purpose is to test as many of the changes made in the
3418program as possible, perhaps to find several independent problems so
3419that you can correct them all before the next attempt to compile. This
3420is why Emacs' `compile' command passes the `-k' flag by default.
3421
3422 Usually when a command fails, if it has changed the target file at
3423all, the file is corrupted and cannot be used--or at least it is not
3424completely updated. Yet the file's time stamp says that it is now up to
3425date, so the next time `make' runs, it will not try to update that
3426file. The situation is just the same as when the command is killed by a
3427signal; *note Interrupts::. So generally the right thing to do is to
3428delete the target file if the command fails after beginning to change
3429the file. `make' will do this if `.DELETE_ON_ERROR' appears as a
3430target. This is almost always what you want `make' to do, but it is
3431not historical practice; so for compatibility, you must explicitly
3432request it.
3433
3434
3435File: make.info, Node: Interrupts, Next: Recursion, Prev: Errors, Up: Commands
3436
34375.6 Interrupting or Killing `make'
3438==================================
3439
3440If `make' gets a fatal signal while a command is executing, it may
3441delete the target file that the command was supposed to update. This is
3442done if the target file's last-modification time has changed since
3443`make' first checked it.
3444
3445 The purpose of deleting the target is to make sure that it is remade
3446from scratch when `make' is next run. Why is this? Suppose you type
3447`Ctrl-c' while a compiler is running, and it has begun to write an
3448object file `foo.o'. The `Ctrl-c' kills the compiler, resulting in an
3449incomplete file whose last-modification time is newer than the source
3450file `foo.c'. But `make' also receives the `Ctrl-c' signal and deletes
3451this incomplete file. If `make' did not do this, the next invocation
3452of `make' would think that `foo.o' did not require updating--resulting
3453in a strange error message from the linker when it tries to link an
3454object file half of which is missing.
3455
3456 You can prevent the deletion of a target file in this way by making
3457the special target `.PRECIOUS' depend on it. Before remaking a target,
3458`make' checks to see whether it appears on the prerequisites of
3459`.PRECIOUS', and thereby decides whether the target should be deleted
3460if a signal happens. Some reasons why you might do this are that the
3461target is updated in some atomic fashion, or exists only to record a
3462modification-time (its contents do not matter), or must exist at all
3463times to prevent other sorts of trouble.
3464
3465
3466File: make.info, Node: Recursion, Next: Sequences, Prev: Interrupts, Up: Commands
3467
34685.7 Recursive Use of `make'
3469===========================
3470
3471Recursive use of `make' means using `make' as a command in a makefile.
3472This technique is useful when you want separate makefiles for various
3473subsystems that compose a larger system. For example, suppose you have
3474a subdirectory `subdir' which has its own makefile, and you would like
3475the containing directory's makefile to run `make' on the subdirectory.
3476You can do it by writing this:
3477
3478 subsystem:
3479 cd subdir && $(MAKE)
3480
3481or, equivalently, this (*note Summary of Options: Options Summary.):
3482
3483 subsystem:
3484 $(MAKE) -C subdir
3485
3486 You can write recursive `make' commands just by copying this example,
3487but there are many things to know about how they work and why, and about
3488how the sub-`make' relates to the top-level `make'. You may also find
3489it useful to declare targets that invoke recursive `make' commands as
3490`.PHONY' (for more discussion on when this is useful, see *Note Phony
3491Targets::).
3492
3493 For your convenience, when GNU `make' starts (after it has processed
3494any `-C' options) it sets the variable `CURDIR' to the pathname of the
3495current working directory. This value is never touched by `make'
3496again: in particular note that if you include files from other
3497directories the value of `CURDIR' does not change. The value has the
3498same precedence it would have if it were set in the makefile (by
3499default, an environment variable `CURDIR' will not override this
3500value). Note that setting this variable has no impact on the operation
3501of `make' (it does not cause `make' to change its working directory,
3502for example).
3503
3504* Menu:
3505
3506* MAKE Variable:: The special effects of using `$(MAKE)'.
3507* Variables/Recursion:: How to communicate variables to a sub-`make'.
3508* Options/Recursion:: How to communicate options to a sub-`make'.
3509* -w Option:: How the `-w' or `--print-directory' option
3510 helps debug use of recursive `make' commands.
3511
3512
3513File: make.info, Node: MAKE Variable, Next: Variables/Recursion, Prev: Recursion, Up: Recursion
3514
35155.7.1 How the `MAKE' Variable Works
3516-----------------------------------
3517
3518Recursive `make' commands should always use the variable `MAKE', not
3519the explicit command name `make', as shown here:
3520
3521 subsystem:
3522 cd subdir && $(MAKE)
3523
3524 The value of this variable is the file name with which `make' was
3525invoked. If this file name was `/bin/make', then the command executed
3526is `cd subdir && /bin/make'. If you use a special version of `make' to
3527run the top-level makefile, the same special version will be executed
3528for recursive invocations.
3529
3530 As a special feature, using the variable `MAKE' in the commands of a
3531rule alters the effects of the `-t' (`--touch'), `-n' (`--just-print'),
3532or `-q' (`--question') option. Using the `MAKE' variable has the same
3533effect as using a `+' character at the beginning of the command line.
3534*Note Instead of Executing the Commands: Instead of Execution. This
3535special feature is only enabled if the `MAKE' variable appears directly
3536in the command script: it does not apply if the `MAKE' variable is
3537referenced through expansion of another variable. In the latter case
3538you must use the `+' token to get these special effects.
3539
3540 Consider the command `make -t' in the above example. (The `-t'
3541option marks targets as up to date without actually running any
3542commands; see *Note Instead of Execution::.) Following the usual
3543definition of `-t', a `make -t' command in the example would create a
3544file named `subsystem' and do nothing else. What you really want it to
3545do is run `cd subdir && make -t'; but that would require executing the
3546command, and `-t' says not to execute commands.
3547
3548 The special feature makes this do what you want: whenever a command
3549line of a rule contains the variable `MAKE', the flags `-t', `-n' and
3550`-q' do not apply to that line. Command lines containing `MAKE' are
3551executed normally despite the presence of a flag that causes most
3552commands not to be run. The usual `MAKEFLAGS' mechanism passes the
3553flags to the sub-`make' (*note Communicating Options to a Sub-`make':
3554Options/Recursion.), so your request to touch the files, or print the
3555commands, is propagated to the subsystem.
3556
3557
3558File: make.info, Node: Variables/Recursion, Next: Options/Recursion, Prev: MAKE Variable, Up: Recursion
3559
35605.7.2 Communicating Variables to a Sub-`make'
3561---------------------------------------------
3562
3563Variable values of the top-level `make' can be passed to the sub-`make'
3564through the environment by explicit request. These variables are
3565defined in the sub-`make' as defaults, but do not override what is
3566specified in the makefile used by the sub-`make' makefile unless you
3567use the `-e' switch (*note Summary of Options: Options Summary.).
3568
3569 To pass down, or "export", a variable, `make' adds the variable and
3570its value to the environment for running each command. The sub-`make',
3571in turn, uses the environment to initialize its table of variable
3572values. *Note Variables from the Environment: Environment.
3573
3574 Except by explicit request, `make' exports a variable only if it is
3575either defined in the environment initially or set on the command line,
3576and if its name consists only of letters, numbers, and underscores.
3577Some shells cannot cope with environment variable names consisting of
3578characters other than letters, numbers, and underscores.
3579
3580 The value of the `make' variable `SHELL' is not exported. Instead,
3581the value of the `SHELL' variable from the invoking environment is
3582passed to the sub-`make'. You can force `make' to export its value for
3583`SHELL' by using the `export' directive, described below. *Note
3584Choosing the Shell::.
3585
3586 The special variable `MAKEFLAGS' is always exported (unless you
3587unexport it). `MAKEFILES' is exported if you set it to anything.
3588
3589 `make' automatically passes down variable values that were defined
3590on the command line, by putting them in the `MAKEFLAGS' variable.
3591*Note Options/Recursion::.
3592
3593 Variables are _not_ normally passed down if they were created by
3594default by `make' (*note Variables Used by Implicit Rules: Implicit
3595Variables.). The sub-`make' will define these for itself.
3596
3597 If you want to export specific variables to a sub-`make', use the
3598`export' directive, like this:
3599
3600 export VARIABLE ...
3601
3602If you want to _prevent_ a variable from being exported, use the
3603`unexport' directive, like this:
3604
3605 unexport VARIABLE ...
3606
3607In both of these forms, the arguments to `export' and `unexport' are
3608expanded, and so could be variables or functions which expand to a
3609(list of) variable names to be (un)exported.
3610
3611 As a convenience, you can define a variable and export it at the same
3612time by doing:
3613
3614 export VARIABLE = value
3615
3616has the same result as:
3617
3618 VARIABLE = value
3619 export VARIABLE
3620
3621and
3622
3623 export VARIABLE := value
3624
3625has the same result as:
3626
3627 VARIABLE := value
3628 export VARIABLE
3629
3630 Likewise,
3631
3632 export VARIABLE += value
3633
3634is just like:
3635
3636 VARIABLE += value
3637 export VARIABLE
3638
3639*Note Appending More Text to Variables: Appending.
3640
3641 You may notice that the `export' and `unexport' directives work in
3642`make' in the same way they work in the shell, `sh'.
3643
3644 If you want all variables to be exported by default, you can use
3645`export' by itself:
3646
3647 export
3648
3649This tells `make' that variables which are not explicitly mentioned in
3650an `export' or `unexport' directive should be exported. Any variable
3651given in an `unexport' directive will still _not_ be exported. If you
3652use `export' by itself to export variables by default, variables whose
3653names contain characters other than alphanumerics and underscores will
3654not be exported unless specifically mentioned in an `export' directive.
3655
3656 The behavior elicited by an `export' directive by itself was the
3657default in older versions of GNU `make'. If your makefiles depend on
3658this behavior and you want to be compatible with old versions of
3659`make', you can write a rule for the special target
3660`.EXPORT_ALL_VARIABLES' instead of using the `export' directive. This
3661will be ignored by old `make's, while the `export' directive will cause
3662a syntax error.
3663
3664 Likewise, you can use `unexport' by itself to tell `make' _not_ to
3665export variables by default. Since this is the default behavior, you
3666would only need to do this if `export' had been used by itself earlier
3667(in an included makefile, perhaps). You *cannot* use `export' and
3668`unexport' by themselves to have variables exported for some commands
3669and not for others. The last `export' or `unexport' directive that
3670appears by itself determines the behavior for the entire run of `make'.
3671
3672 As a special feature, the variable `MAKELEVEL' is changed when it is
3673passed down from level to level. This variable's value is a string
3674which is the depth of the level as a decimal number. The value is `0'
3675for the top-level `make'; `1' for a sub-`make', `2' for a
3676sub-sub-`make', and so on. The incrementation happens when `make' sets
3677up the environment for a command.
3678
3679 The main use of `MAKELEVEL' is to test it in a conditional directive
3680(*note Conditional Parts of Makefiles: Conditionals.); this way you can
3681write a makefile that behaves one way if run recursively and another
3682way if run directly by you.
3683
3684 You can use the variable `MAKEFILES' to cause all sub-`make'
3685commands to use additional makefiles. The value of `MAKEFILES' is a
3686whitespace-separated list of file names. This variable, if defined in
3687the outer-level makefile, is passed down through the environment; then
3688it serves as a list of extra makefiles for the sub-`make' to read
3689before the usual or specified ones. *Note The Variable `MAKEFILES':
3690MAKEFILES Variable.
3691
3692
3693File: make.info, Node: Options/Recursion, Next: -w Option, Prev: Variables/Recursion, Up: Recursion
3694
36955.7.3 Communicating Options to a Sub-`make'
3696-------------------------------------------
3697
3698Flags such as `-s' and `-k' are passed automatically to the sub-`make'
3699through the variable `MAKEFLAGS'. This variable is set up
3700automatically by `make' to contain the flag letters that `make'
3701received. Thus, if you do `make -ks' then `MAKEFLAGS' gets the value
3702`ks'.
3703
3704 As a consequence, every sub-`make' gets a value for `MAKEFLAGS' in
3705its environment. In response, it takes the flags from that value and
3706processes them as if they had been given as arguments. *Note Summary
3707of Options: Options Summary.
3708
3709 Likewise variables defined on the command line are passed to the
3710sub-`make' through `MAKEFLAGS'. Words in the value of `MAKEFLAGS' that
3711contain `=', `make' treats as variable definitions just as if they
3712appeared on the command line. *Note Overriding Variables: Overriding.
3713
3714 The options `-C', `-f', `-o', and `-W' are not put into `MAKEFLAGS';
3715these options are not passed down.
3716
3717 The `-j' option is a special case (*note Parallel Execution:
3718Parallel.). If you set it to some numeric value `N' and your operating
3719system supports it (most any UNIX system will; others typically won't),
3720the parent `make' and all the sub-`make's will communicate to ensure
3721that there are only `N' jobs running at the same time between them all.
3722Note that any job that is marked recursive (*note Instead of Executing
3723the Commands: Instead of Execution.) doesn't count against the total
3724jobs (otherwise we could get `N' sub-`make's running and have no slots
3725left over for any real work!)
3726
3727 If your operating system doesn't support the above communication,
3728then `-j 1' is always put into `MAKEFLAGS' instead of the value you
3729specified. This is because if the `-j' option were passed down to
3730sub-`make's, you would get many more jobs running in parallel than you
3731asked for. If you give `-j' with no numeric argument, meaning to run
3732as many jobs as possible in parallel, this is passed down, since
3733multiple infinities are no more than one.
3734
3735 If you do not want to pass the other flags down, you must change the
3736value of `MAKEFLAGS', like this:
3737
3738 subsystem:
3739 cd subdir && $(MAKE) MAKEFLAGS=
3740
3741 The command line variable definitions really appear in the variable
3742`MAKEOVERRIDES', and `MAKEFLAGS' contains a reference to this variable.
3743If you do want to pass flags down normally, but don't want to pass
3744down the command line variable definitions, you can reset
3745`MAKEOVERRIDES' to empty, like this:
3746
3747 MAKEOVERRIDES =
3748
3749This is not usually useful to do. However, some systems have a small
3750fixed limit on the size of the environment, and putting so much
3751information into the value of `MAKEFLAGS' can exceed it. If you see
3752the error message `Arg list too long', this may be the problem. (For
3753strict compliance with POSIX.2, changing `MAKEOVERRIDES' does not
3754affect `MAKEFLAGS' if the special target `.POSIX' appears in the
3755makefile. You probably do not care about this.)
3756
3757 A similar variable `MFLAGS' exists also, for historical
3758compatibility. It has the same value as `MAKEFLAGS' except that it
3759does not contain the command line variable definitions, and it always
3760begins with a hyphen unless it is empty (`MAKEFLAGS' begins with a
3761hyphen only when it begins with an option that has no single-letter
3762version, such as `--warn-undefined-variables'). `MFLAGS' was
3763traditionally used explicitly in the recursive `make' command, like
3764this:
3765
3766 subsystem:
3767 cd subdir && $(MAKE) $(MFLAGS)
3768
3769but now `MAKEFLAGS' makes this usage redundant. If you want your
3770makefiles to be compatible with old `make' programs, use this
3771technique; it will work fine with more modern `make' versions too.
3772
3773 The `MAKEFLAGS' variable can also be useful if you want to have
3774certain options, such as `-k' (*note Summary of Options: Options
3775Summary.), set each time you run `make'. You simply put a value for
3776`MAKEFLAGS' in your environment. You can also set `MAKEFLAGS' in a
3777makefile, to specify additional flags that should also be in effect for
3778that makefile. (Note that you cannot use `MFLAGS' this way. That
3779variable is set only for compatibility; `make' does not interpret a
3780value you set for it in any way.)
3781
3782 When `make' interprets the value of `MAKEFLAGS' (either from the
3783environment or from a makefile), it first prepends a hyphen if the value
3784does not already begin with one. Then it chops the value into words
3785separated by blanks, and parses these words as if they were options
3786given on the command line (except that `-C', `-f', `-h', `-o', `-W',
3787and their long-named versions are ignored; and there is no error for an
3788invalid option).
3789
3790 If you do put `MAKEFLAGS' in your environment, you should be sure not
3791to include any options that will drastically affect the actions of
3792`make' and undermine the purpose of makefiles and of `make' itself.
3793For instance, the `-t', `-n', and `-q' options, if put in one of these
3794variables, could have disastrous consequences and would certainly have
3795at least surprising and probably annoying effects.
3796
3797
3798File: make.info, Node: -w Option, Prev: Options/Recursion, Up: Recursion
3799
38005.7.4 The `--print-directory' Option
3801------------------------------------
3802
3803If you use several levels of recursive `make' invocations, the `-w' or
3804`--print-directory' option can make the output a lot easier to
3805understand by showing each directory as `make' starts processing it and
3806as `make' finishes processing it. For example, if `make -w' is run in
3807the directory `/u/gnu/make', `make' will print a line of the form:
3808
3809 make: Entering directory `/u/gnu/make'.
3810
3811before doing anything else, and a line of the form:
3812
3813 make: Leaving directory `/u/gnu/make'.
3814
3815when processing is completed.
3816
3817 Normally, you do not need to specify this option because `make' does
3818it for you: `-w' is turned on automatically when you use the `-C'
3819option, and in sub-`make's. `make' will not automatically turn on `-w'
3820if you also use `-s', which says to be silent, or if you use
3821`--no-print-directory' to explicitly disable it.
3822
3823
3824File: make.info, Node: Sequences, Next: Empty Commands, Prev: Recursion, Up: Commands
3825
38265.8 Defining Canned Command Sequences
3827=====================================
3828
3829When the same sequence of commands is useful in making various targets,
3830you can define it as a canned sequence with the `define' directive, and
3831refer to the canned sequence from the rules for those targets. The
3832canned sequence is actually a variable, so the name must not conflict
3833with other variable names.
3834
3835 Here is an example of defining a canned sequence of commands:
3836
3837 define run-yacc
3838 yacc $(firstword $^)
3839 mv y.tab.c $@
3840 endef
3841
3842Here `run-yacc' is the name of the variable being defined; `endef'
3843marks the end of the definition; the lines in between are the commands.
3844The `define' directive does not expand variable references and
3845function calls in the canned sequence; the `$' characters, parentheses,
3846variable names, and so on, all become part of the value of the variable
3847you are defining. *Note Defining Variables Verbatim: Defining, for a
3848complete explanation of `define'.
3849
3850 The first command in this example runs Yacc on the first
3851prerequisite of whichever rule uses the canned sequence. The output
3852file from Yacc is always named `y.tab.c'. The second command moves the
3853output to the rule's target file name.
3854
3855 To use the canned sequence, substitute the variable into the
3856commands of a rule. You can substitute it like any other variable
3857(*note Basics of Variable References: Reference.). Because variables
3858defined by `define' are recursively expanded variables, all the
3859variable references you wrote inside the `define' are expanded now.
3860For example:
3861
3862 foo.c : foo.y
3863 $(run-yacc)
3864
3865`foo.y' will be substituted for the variable `$^' when it occurs in
3866`run-yacc''s value, and `foo.c' for `$@'.
3867
3868 This is a realistic example, but this particular one is not needed in
3869practice because `make' has an implicit rule to figure out these
3870commands based on the file names involved (*note Using Implicit Rules:
3871Implicit Rules.).
3872
3873 In command execution, each line of a canned sequence is treated just
3874as if the line appeared on its own in the rule, preceded by a tab. In
3875particular, `make' invokes a separate subshell for each line. You can
3876use the special prefix characters that affect command lines (`@', `-',
3877and `+') on each line of a canned sequence. *Note Writing the Commands
3878in Rules: Commands. For example, using this canned sequence:
3879
3880 define frobnicate
3881 @echo "frobnicating target $@"
3882 frob-step-1 $< -o $@-step-1
3883 frob-step-2 $@-step-1 -o $@
3884 endef
3885
3886`make' will not echo the first line, the `echo' command. But it _will_
3887echo the following two command lines.
3888
3889 On the other hand, prefix characters on the command line that refers
3890to a canned sequence apply to every line in the sequence. So the rule:
3891
3892 frob.out: frob.in
3893 @$(frobnicate)
3894
3895does not echo _any_ commands. (*Note Command Echoing: Echoing, for a
3896full explanation of `@'.)
3897
3898
3899File: make.info, Node: Empty Commands, Prev: Sequences, Up: Commands
3900
39015.9 Using Empty Commands
3902========================
3903
3904It is sometimes useful to define commands which do nothing. This is
3905done simply by giving a command that consists of nothing but
3906whitespace. For example:
3907
3908 target: ;
3909
3910defines an empty command string for `target'. You could also use a
3911line beginning with a tab character to define an empty command string,
3912but this would be confusing because such a line looks empty.
3913
3914 You may be wondering why you would want to define a command string
3915that does nothing. The only reason this is useful is to prevent a
3916target from getting implicit commands (from implicit rules or the
3917`.DEFAULT' special target; *note Implicit Rules:: and *note Defining
3918Last-Resort Default Rules: Last Resort.).
3919
3920 You may be inclined to define empty command strings for targets that
3921are not actual files, but only exist so that their prerequisites can be
3922remade. However, this is not the best way to do that, because the
3923prerequisites may not be remade properly if the target file actually
3924does exist. *Note Phony Targets: Phony Targets, for a better way to do
3925this.
3926
3927
3928File: make.info, Node: Using Variables, Next: Conditionals, Prev: Commands, Up: Top
3929
39306 How to Use Variables
3931**********************
3932
3933A "variable" is a name defined in a makefile to represent a string of
3934text, called the variable's "value". These values are substituted by
3935explicit request into targets, prerequisites, commands, and other parts
3936of the makefile. (In some other versions of `make', variables are
3937called "macros".)
3938
3939 Variables and functions in all parts of a makefile are expanded when
3940read, except for the shell commands in rules, the right-hand sides of
3941variable definitions using `=', and the bodies of variable definitions
3942using the `define' directive.
3943
3944 Variables can represent lists of file names, options to pass to
3945compilers, programs to run, directories to look in for source files,
3946directories to write output in, or anything else you can imagine.
3947
3948 A variable name may be any sequence of characters not containing `:',
3949`#', `=', or leading or trailing whitespace. However, variable names
3950containing characters other than letters, numbers, and underscores
3951should be avoided, as they may be given special meanings in the future,
3952and with some shells they cannot be passed through the environment to a
3953sub-`make' (*note Communicating Variables to a Sub-`make':
3954Variables/Recursion.).
3955
3956 Variable names are case-sensitive. The names `foo', `FOO', and
3957`Foo' all refer to different variables.
3958
3959 It is traditional to use upper case letters in variable names, but we
3960recommend using lower case letters for variable names that serve
3961internal purposes in the makefile, and reserving upper case for
3962parameters that control implicit rules or for parameters that the user
3963should override with command options (*note Overriding Variables:
3964Overriding.).
3965
3966 A few variables have names that are a single punctuation character or
3967just a few characters. These are the "automatic variables", and they
3968have particular specialized uses. *Note Automatic Variables::.
3969
3970* Menu:
3971
3972* Reference:: How to use the value of a variable.
3973* Flavors:: Variables come in two flavors.
3974* Advanced:: Advanced features for referencing a variable.
3975* Values:: All the ways variables get their values.
3976* Setting:: How to set a variable in the makefile.
3977* Appending:: How to append more text to the old value
3978 of a variable.
3979* Override Directive:: How to set a variable in the makefile even if
3980 the user has set it with a command argument.
3981* Defining:: An alternate way to set a variable
3982 to a verbatim string.
3983* Environment:: Variable values can come from the environment.
3984* Target-specific:: Variable values can be defined on a per-target
3985 basis.
3986* Pattern-specific:: Target-specific variable values can be applied
3987 to a group of targets that match a pattern.
3988
3989
3990File: make.info, Node: Reference, Next: Flavors, Prev: Using Variables, Up: Using Variables
3991
39926.1 Basics of Variable References
3993=================================
3994
3995To substitute a variable's value, write a dollar sign followed by the
3996name of the variable in parentheses or braces: either `$(foo)' or
3997`${foo}' is a valid reference to the variable `foo'. This special
3998significance of `$' is why you must write `$$' to have the effect of a
3999single dollar sign in a file name or command.
4000
4001 Variable references can be used in any context: targets,
4002prerequisites, commands, most directives, and new variable values.
4003Here is an example of a common case, where a variable holds the names
4004of all the object files in a program:
4005
4006 objects = program.o foo.o utils.o
4007 program : $(objects)
4008 cc -o program $(objects)
4009
4010 $(objects) : defs.h
4011
4012 Variable references work by strict textual substitution. Thus, the
4013rule
4014
4015 foo = c
4016 prog.o : prog.$(foo)
4017 $(foo)$(foo) -$(foo) prog.$(foo)
4018
4019could be used to compile a C program `prog.c'. Since spaces before the
4020variable value are ignored in variable assignments, the value of `foo'
4021is precisely `c'. (Don't actually write your makefiles this way!)
4022
4023 A dollar sign followed by a character other than a dollar sign,
4024open-parenthesis or open-brace treats that single character as the
4025variable name. Thus, you could reference the variable `x' with `$x'.
4026However, this practice is strongly discouraged, except in the case of
4027the automatic variables (*note Automatic Variables::).
4028
4029
4030File: make.info, Node: Flavors, Next: Advanced, Prev: Reference, Up: Using Variables
4031
40326.2 The Two Flavors of Variables
4033================================
4034
4035There are two ways that a variable in GNU `make' can have a value; we
4036call them the two "flavors" of variables. The two flavors are
4037distinguished in how they are defined and in what they do when expanded.
4038
4039 The first flavor of variable is a "recursively expanded" variable.
4040Variables of this sort are defined by lines using `=' (*note Setting
4041Variables: Setting.) or by the `define' directive (*note Defining
4042Variables Verbatim: Defining.). The value you specify is installed
4043verbatim; if it contains references to other variables, these
4044references are expanded whenever this variable is substituted (in the
4045course of expanding some other string). When this happens, it is
4046called "recursive expansion".
4047
4048 For example,
4049
4050 foo = $(bar)
4051 bar = $(ugh)
4052 ugh = Huh?
4053
4054 all:;echo $(foo)
4055
4056will echo `Huh?': `$(foo)' expands to `$(bar)' which expands to
4057`$(ugh)' which finally expands to `Huh?'.
4058
4059 This flavor of variable is the only sort supported by other versions
4060of `make'. It has its advantages and its disadvantages. An advantage
4061(most would say) is that:
4062
4063 CFLAGS = $(include_dirs) -O
4064 include_dirs = -Ifoo -Ibar
4065
4066will do what was intended: when `CFLAGS' is expanded in a command, it
4067will expand to `-Ifoo -Ibar -O'. A major disadvantage is that you
4068cannot append something on the end of a variable, as in
4069
4070 CFLAGS = $(CFLAGS) -O
4071
4072because it will cause an infinite loop in the variable expansion.
4073(Actually `make' detects the infinite loop and reports an error.)
4074
4075 Another disadvantage is that any functions (*note Functions for
4076Transforming Text: Functions.) referenced in the definition will be
4077executed every time the variable is expanded. This makes `make' run
4078slower; worse, it causes the `wildcard' and `shell' functions to give
4079unpredictable results because you cannot easily control when they are
4080called, or even how many times.
4081
4082 To avoid all the problems and inconveniences of recursively expanded
4083variables, there is another flavor: simply expanded variables.
4084
4085 "Simply expanded variables" are defined by lines using `:=' (*note
4086Setting Variables: Setting.). The value of a simply expanded variable
4087is scanned once and for all, expanding any references to other
4088variables and functions, when the variable is defined. The actual
4089value of the simply expanded variable is the result of expanding the
4090text that you write. It does not contain any references to other
4091variables; it contains their values _as of the time this variable was
4092defined_. Therefore,
4093
4094 x := foo
4095 y := $(x) bar
4096 x := later
4097
4098is equivalent to
4099
4100 y := foo bar
4101 x := later
4102
4103 When a simply expanded variable is referenced, its value is
4104substituted verbatim.
4105
4106 Here is a somewhat more complicated example, illustrating the use of
4107`:=' in conjunction with the `shell' function. (*Note The `shell'
4108Function: Shell Function.) This example also shows use of the variable
4109`MAKELEVEL', which is changed when it is passed down from level to
4110level. (*Note Communicating Variables to a Sub-`make':
4111Variables/Recursion, for information about `MAKELEVEL'.)
4112
4113 ifeq (0,${MAKELEVEL})
4114 whoami := $(shell whoami)
4115 host-type := $(shell arch)
4116 MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
4117 endif
4118
4119An advantage of this use of `:=' is that a typical `descend into a
4120directory' command then looks like this:
4121
4122 ${subdirs}:
4123 ${MAKE} -C $@ all
4124
4125 Simply expanded variables generally make complicated makefile
4126programming more predictable because they work like variables in most
4127programming languages. They allow you to redefine a variable using its
4128own value (or its value processed in some way by one of the expansion
4129functions) and to use the expansion functions much more efficiently
4130(*note Functions for Transforming Text: Functions.).
4131
4132 You can also use them to introduce controlled leading whitespace into
4133variable values. Leading whitespace characters are discarded from your
4134input before substitution of variable references and function calls;
4135this means you can include leading spaces in a variable value by
4136protecting them with variable references, like this:
4137
4138 nullstring :=
4139 space := $(nullstring) # end of the line
4140
4141Here the value of the variable `space' is precisely one space. The
4142comment `# end of the line' is included here just for clarity. Since
4143trailing space characters are _not_ stripped from variable values, just
4144a space at the end of the line would have the same effect (but be
4145rather hard to read). If you put whitespace at the end of a variable
4146value, it is a good idea to put a comment like that at the end of the
4147line to make your intent clear. Conversely, if you do _not_ want any
4148whitespace characters at the end of your variable value, you must
4149remember not to put a random comment on the end of the line after some
4150whitespace, such as this:
4151
4152 dir := /foo/bar # directory to put the frobs in
4153
4154Here the value of the variable `dir' is `/foo/bar ' (with four
4155trailing spaces), which was probably not the intention. (Imagine
4156something like `$(dir)/file' with this definition!)
4157
4158 There is another assignment operator for variables, `?='. This is
4159called a conditional variable assignment operator, because it only has
4160an effect if the variable is not yet defined. This statement:
4161
4162 FOO ?= bar
4163
4164is exactly equivalent to this (*note The `origin' Function: Origin
4165Function.):
4166
4167 ifeq ($(origin FOO), undefined)
4168 FOO = bar
4169 endif
4170
4171 Note that a variable set to an empty value is still defined, so `?='
4172will not set that variable.
4173
4174
4175File: make.info, Node: Advanced, Next: Values, Prev: Flavors, Up: Using Variables
4176
41776.3 Advanced Features for Reference to Variables
4178================================================
4179
4180This section describes some advanced features you can use to reference
4181variables in more flexible ways.
4182
4183* Menu:
4184
4185* Substitution Refs:: Referencing a variable with
4186 substitutions on the value.
4187* Computed Names:: Computing the name of the variable to refer to.
4188
4189
4190File: make.info, Node: Substitution Refs, Next: Computed Names, Prev: Advanced, Up: Advanced
4191
41926.3.1 Substitution References
4193-----------------------------
4194
4195A "substitution reference" substitutes the value of a variable with
4196alterations that you specify. It has the form `$(VAR:A=B)' (or
4197`${VAR:A=B}') and its meaning is to take the value of the variable VAR,
4198replace every A at the end of a word with B in that value, and
4199substitute the resulting string.
4200
4201 When we say "at the end of a word", we mean that A must appear
4202either followed by whitespace or at the end of the value in order to be
4203replaced; other occurrences of A in the value are unaltered. For
4204example:
4205
4206 foo := a.o b.o c.o
4207 bar := $(foo:.o=.c)
4208
4209sets `bar' to `a.c b.c c.c'. *Note Setting Variables: Setting.
4210
4211 A substitution reference is actually an abbreviation for use of the
4212`patsubst' expansion function (*note Functions for String Substitution
4213and Analysis: Text Functions.). We provide substitution references as
4214well as `patsubst' for compatibility with other implementations of
4215`make'.
4216
4217 Another type of substitution reference lets you use the full power of
4218the `patsubst' function. It has the same form `$(VAR:A=B)' described
4219above, except that now A must contain a single `%' character. This
4220case is equivalent to `$(patsubst A,B,$(VAR))'. *Note Functions for
4221String Substitution and Analysis: Text Functions, for a description of
4222the `patsubst' function.
4223
4224For example:
4225
4226 foo := a.o b.o c.o
4227 bar := $(foo:%.o=%.c)
4228
4229sets `bar' to `a.c b.c c.c'.
4230
4231
4232File: make.info, Node: Computed Names, Prev: Substitution Refs, Up: Advanced
4233
42346.3.2 Computed Variable Names
4235-----------------------------
4236
4237Computed variable names are a complicated concept needed only for
4238sophisticated makefile programming. For most purposes you need not
4239consider them, except to know that making a variable with a dollar sign
4240in its name might have strange results. However, if you are the type
4241that wants to understand everything, or you are actually interested in
4242what they do, read on.
4243
4244 Variables may be referenced inside the name of a variable. This is
4245called a "computed variable name" or a "nested variable reference".
4246For example,
4247
4248 x = y
4249 y = z
4250 a := $($(x))
4251
4252defines `a' as `z': the `$(x)' inside `$($(x))' expands to `y', so
4253`$($(x))' expands to `$(y)' which in turn expands to `z'. Here the
4254name of the variable to reference is not stated explicitly; it is
4255computed by expansion of `$(x)'. The reference `$(x)' here is nested
4256within the outer variable reference.
4257
4258 The previous example shows two levels of nesting, but any number of
4259levels is possible. For example, here are three levels:
4260
4261 x = y
4262 y = z
4263 z = u
4264 a := $($($(x)))
4265
4266Here the innermost `$(x)' expands to `y', so `$($(x))' expands to
4267`$(y)' which in turn expands to `z'; now we have `$(z)', which becomes
4268`u'.
4269
4270 References to recursively-expanded variables within a variable name
4271are reexpanded in the usual fashion. For example:
4272
4273 x = $(y)
4274 y = z
4275 z = Hello
4276 a := $($(x))
4277
4278defines `a' as `Hello': `$($(x))' becomes `$($(y))' which becomes
4279`$(z)' which becomes `Hello'.
4280
4281 Nested variable references can also contain modified references and
4282function invocations (*note Functions for Transforming Text:
4283Functions.), just like any other reference. For example, using the
4284`subst' function (*note Functions for String Substitution and Analysis:
4285Text Functions.):
4286
4287 x = variable1
4288 variable2 := Hello
4289 y = $(subst 1,2,$(x))
4290 z = y
4291 a := $($($(z)))
4292
4293eventually defines `a' as `Hello'. It is doubtful that anyone would
4294ever want to write a nested reference as convoluted as this one, but it
4295works: `$($($(z)))' expands to `$($(y))' which becomes `$($(subst
42961,2,$(x)))'. This gets the value `variable1' from `x' and changes it
4297by substitution to `variable2', so that the entire string becomes
4298`$(variable2)', a simple variable reference whose value is `Hello'.
4299
4300 A computed variable name need not consist entirely of a single
4301variable reference. It can contain several variable references, as
4302well as some invariant text. For example,
4303
4304 a_dirs := dira dirb
4305 1_dirs := dir1 dir2
4306
4307 a_files := filea fileb
4308 1_files := file1 file2
4309
4310 ifeq "$(use_a)" "yes"
4311 a1 := a
4312 else
4313 a1 := 1
4314 endif
4315
4316 ifeq "$(use_dirs)" "yes"
4317 df := dirs
4318 else
4319 df := files
4320 endif
4321
4322 dirs := $($(a1)_$(df))
4323
4324will give `dirs' the same value as `a_dirs', `1_dirs', `a_files' or
4325`1_files' depending on the settings of `use_a' and `use_dirs'.
4326
4327 Computed variable names can also be used in substitution references:
4328
4329 a_objects := a.o b.o c.o
4330 1_objects := 1.o 2.o 3.o
4331
4332 sources := $($(a1)_objects:.o=.c)
4333
4334defines `sources' as either `a.c b.c c.c' or `1.c 2.c 3.c', depending
4335on the value of `a1'.
4336
4337 The only restriction on this sort of use of nested variable
4338references is that they cannot specify part of the name of a function
4339to be called. This is because the test for a recognized function name
4340is done before the expansion of nested references. For example,
4341
4342 ifdef do_sort
4343 func := sort
4344 else
4345 func := strip
4346 endif
4347
4348 bar := a d b g q c
4349
4350 foo := $($(func) $(bar))
4351
4352attempts to give `foo' the value of the variable `sort a d b g q c' or
4353`strip a d b g q c', rather than giving `a d b g q c' as the argument
4354to either the `sort' or the `strip' function. This restriction could
4355be removed in the future if that change is shown to be a good idea.
4356
4357 You can also use computed variable names in the left-hand side of a
4358variable assignment, or in a `define' directive, as in:
4359
4360 dir = foo
4361 $(dir)_sources := $(wildcard $(dir)/*.c)
4362 define $(dir)_print
4363 lpr $($(dir)_sources)
4364 endef
4365
4366This example defines the variables `dir', `foo_sources', and
4367`foo_print'.
4368
4369 Note that "nested variable references" are quite different from
4370"recursively expanded variables" (*note The Two Flavors of Variables:
4371Flavors.), though both are used together in complex ways when doing
4372makefile programming.
4373
4374
4375File: make.info, Node: Values, Next: Setting, Prev: Advanced, Up: Using Variables
4376
43776.4 How Variables Get Their Values
4378==================================
4379
4380Variables can get values in several different ways:
4381
4382 * You can specify an overriding value when you run `make'. *Note
4383 Overriding Variables: Overriding.
4384
4385 * You can specify a value in the makefile, either with an assignment
4386 (*note Setting Variables: Setting.) or with a verbatim definition
4387 (*note Defining Variables Verbatim: Defining.).
4388
4389 * Variables in the environment become `make' variables. *Note
4390 Variables from the Environment: Environment.
4391
4392 * Several "automatic" variables are given new values for each rule.
4393 Each of these has a single conventional use. *Note Automatic
4394 Variables::.
4395
4396 * Several variables have constant initial values. *Note Variables
4397 Used by Implicit Rules: Implicit Variables.
4398
4399
4400File: make.info, Node: Setting, Next: Appending, Prev: Values, Up: Using Variables
4401
44026.5 Setting Variables
4403=====================
4404
4405To set a variable from the makefile, write a line starting with the
4406variable name followed by `=' or `:='. Whatever follows the `=' or
4407`:=' on the line becomes the value. For example,
4408
4409 objects = main.o foo.o bar.o utils.o
4410
4411defines a variable named `objects'. Whitespace around the variable
4412name and immediately after the `=' is ignored.
4413
4414 Variables defined with `=' are "recursively expanded" variables.
4415Variables defined with `:=' are "simply expanded" variables; these
4416definitions can contain variable references which will be expanded
4417before the definition is made. *Note The Two Flavors of Variables:
4418Flavors.
4419
4420 The variable name may contain function and variable references, which
4421are expanded when the line is read to find the actual variable name to
4422use.
4423
4424 There is no limit on the length of the value of a variable except the
4425amount of swapping space on the computer. When a variable definition is
4426long, it is a good idea to break it into several lines by inserting
4427backslash-newline at convenient places in the definition. This will not
4428affect the functioning of `make', but it will make the makefile easier
4429to read.
4430
4431 Most variable names are considered to have the empty string as a
4432value if you have never set them. Several variables have built-in
4433initial values that are not empty, but you can set them in the usual
4434ways (*note Variables Used by Implicit Rules: Implicit Variables.).
4435Several special variables are set automatically to a new value for each
4436rule; these are called the "automatic" variables (*note Automatic
4437Variables::).
4438
4439 If you'd like a variable to be set to a value only if it's not
4440already set, then you can use the shorthand operator `?=' instead of
4441`='. These two settings of the variable `FOO' are identical (*note The
4442`origin' Function: Origin Function.):
4443
4444 FOO ?= bar
4445
4446and
4447
4448 ifeq ($(origin FOO), undefined)
4449 FOO = bar
4450 endif
4451
4452
4453File: make.info, Node: Appending, Next: Override Directive, Prev: Setting, Up: Using Variables
4454
44556.6 Appending More Text to Variables
4456====================================
4457
4458Often it is useful to add more text to the value of a variable already
4459defined. You do this with a line containing `+=', like this:
4460
4461 objects += another.o
4462
4463This takes the value of the variable `objects', and adds the text
4464`another.o' to it (preceded by a single space). Thus:
4465
4466 objects = main.o foo.o bar.o utils.o
4467 objects += another.o
4468
4469sets `objects' to `main.o foo.o bar.o utils.o another.o'.
4470
4471 Using `+=' is similar to:
4472
4473 objects = main.o foo.o bar.o utils.o
4474 objects := $(objects) another.o
4475
4476but differs in ways that become important when you use more complex
4477values.
4478
4479 When the variable in question has not been defined before, `+=' acts
4480just like normal `=': it defines a recursively-expanded variable.
4481However, when there _is_ a previous definition, exactly what `+=' does
4482depends on what flavor of variable you defined originally. *Note The
4483Two Flavors of Variables: Flavors, for an explanation of the two
4484flavors of variables.
4485
4486 When you add to a variable's value with `+=', `make' acts
4487essentially as if you had included the extra text in the initial
4488definition of the variable. If you defined it first with `:=', making
4489it a simply-expanded variable, `+=' adds to that simply-expanded
4490definition, and expands the new text before appending it to the old
4491value just as `:=' does (see *Note Setting Variables: Setting, for a
4492full explanation of `:='). In fact,
4493
4494 variable := value
4495 variable += more
4496
4497is exactly equivalent to:
4498
4499
4500 variable := value
4501 variable := $(variable) more
4502
4503 On the other hand, when you use `+=' with a variable that you defined
4504first to be recursively-expanded using plain `=', `make' does something
4505a bit different. Recall that when you define a recursively-expanded
4506variable, `make' does not expand the value you set for variable and
4507function references immediately. Instead it stores the text verbatim,
4508and saves these variable and function references to be expanded later,
4509when you refer to the new variable (*note The Two Flavors of Variables:
4510Flavors.). When you use `+=' on a recursively-expanded variable, it is
4511this unexpanded text to which `make' appends the new text you specify.
4512
4513 variable = value
4514 variable += more
4515
4516is roughly equivalent to:
4517
4518 temp = value
4519 variable = $(temp) more
4520
4521except that of course it never defines a variable called `temp'. The
4522importance of this comes when the variable's old value contains
4523variable references. Take this common example:
4524
4525 CFLAGS = $(includes) -O
4526 ...
4527 CFLAGS += -pg # enable profiling
4528
4529The first line defines the `CFLAGS' variable with a reference to another
4530variable, `includes'. (`CFLAGS' is used by the rules for C
4531compilation; *note Catalogue of Implicit Rules: Catalogue of Rules.)
4532Using `=' for the definition makes `CFLAGS' a recursively-expanded
4533variable, meaning `$(includes) -O' is _not_ expanded when `make'
4534processes the definition of `CFLAGS'. Thus, `includes' need not be
4535defined yet for its value to take effect. It only has to be defined
4536before any reference to `CFLAGS'. If we tried to append to the value
4537of `CFLAGS' without using `+=', we might do it like this:
4538
4539 CFLAGS := $(CFLAGS) -pg # enable profiling
4540
4541This is pretty close, but not quite what we want. Using `:=' redefines
4542`CFLAGS' as a simply-expanded variable; this means `make' expands the
4543text `$(CFLAGS) -pg' before setting the variable. If `includes' is not
4544yet defined, we get ` -O -pg', and a later definition of `includes'
4545will have no effect. Conversely, by using `+=' we set `CFLAGS' to the
4546_unexpanded_ value `$(includes) -O -pg'. Thus we preserve the
4547reference to `includes', so if that variable gets defined at any later
4548point, a reference like `$(CFLAGS)' still uses its value.
4549
4550
4551File: make.info, Node: Override Directive, Next: Defining, Prev: Appending, Up: Using Variables
4552
45536.7 The `override' Directive
4554============================
4555
4556If a variable has been set with a command argument (*note Overriding
4557Variables: Overriding.), then ordinary assignments in the makefile are
4558ignored. If you want to set the variable in the makefile even though
4559it was set with a command argument, you can use an `override'
4560directive, which is a line that looks like this:
4561
4562 override VARIABLE = VALUE
4563
4564or
4565
4566 override VARIABLE := VALUE
4567
4568 To append more text to a variable defined on the command line, use:
4569
4570 override VARIABLE += MORE TEXT
4571
4572*Note Appending More Text to Variables: Appending.
4573
4574 The `override' directive was not invented for escalation in the war
4575between makefiles and command arguments. It was invented so you can
4576alter and add to values that the user specifies with command arguments.
4577
4578 For example, suppose you always want the `-g' switch when you run the
4579C compiler, but you would like to allow the user to specify the other
4580switches with a command argument just as usual. You could use this
4581`override' directive:
4582
4583 override CFLAGS += -g
4584
4585 You can also use `override' directives with `define' directives.
4586This is done as you might expect:
4587
4588 override define foo
4589 bar
4590 endef
4591
4592*Note Defining Variables Verbatim: Defining.
4593
4594
4595File: make.info, Node: Defining, Next: Environment, Prev: Override Directive, Up: Using Variables
4596
45976.8 Defining Variables Verbatim
4598===============================
4599
4600Another way to set the value of a variable is to use the `define'
4601directive. This directive has an unusual syntax which allows newline
4602characters to be included in the value, which is convenient for defining
4603both canned sequences of commands (*note Defining Canned Command
4604Sequences: Sequences.), and also sections of makefile syntax to use
4605with `eval' (*note Eval Function::).
4606
4607 The `define' directive is followed on the same line by the name of
4608the variable and nothing more. The value to give the variable appears
4609on the following lines. The end of the value is marked by a line
4610containing just the word `endef'. Aside from this difference in
4611syntax, `define' works just like `=': it creates a recursively-expanded
4612variable (*note The Two Flavors of Variables: Flavors.). The variable
4613name may contain function and variable references, which are expanded
4614when the directive is read to find the actual variable name to use.
4615
4616 You may nest `define' directives: `make' will keep track of nested
4617directives and report an error if they are not all properly closed with
4618`endef'. Note that lines beginning with tab characters are considered
4619part of a command script, so any `define' or `endef' strings appearing
4620on such a line will not be considered `make' operators.
4621
4622 define two-lines
4623 echo foo
4624 echo $(bar)
4625 endef
4626
4627 The value in an ordinary assignment cannot contain a newline; but the
4628newlines that separate the lines of the value in a `define' become part
4629of the variable's value (except for the final newline which precedes
4630the `endef' and is not considered part of the value).
4631
4632 When used in a command script, the previous example is functionally
4633equivalent to this:
4634
4635 two-lines = echo foo; echo $(bar)
4636
4637since two commands separated by semicolon behave much like two separate
4638shell commands. However, note that using two separate lines means
4639`make' will invoke the shell twice, running an independent subshell for
4640each line. *Note Command Execution: Execution.
4641
4642 If you want variable definitions made with `define' to take
4643precedence over command-line variable definitions, you can use the
4644`override' directive together with `define':
4645
4646 override define two-lines
4647 foo
4648 $(bar)
4649 endef
4650
4651*Note The `override' Directive: Override Directive.
4652
4653
4654File: make.info, Node: Environment, Next: Target-specific, Prev: Defining, Up: Using Variables
4655
46566.9 Variables from the Environment
4657==================================
4658
4659Variables in `make' can come from the environment in which `make' is
4660run. Every environment variable that `make' sees when it starts up is
4661transformed into a `make' variable with the same name and value.
4662However, an explicit assignment in the makefile, or with a command
4663argument, overrides the environment. (If the `-e' flag is specified,
4664then values from the environment override assignments in the makefile.
4665*Note Summary of Options: Options Summary. But this is not recommended
4666practice.)
4667
4668 Thus, by setting the variable `CFLAGS' in your environment, you can
4669cause all C compilations in most makefiles to use the compiler switches
4670you prefer. This is safe for variables with standard or conventional
4671meanings because you know that no makefile will use them for other
4672things. (Note this is not totally reliable; some makefiles set
4673`CFLAGS' explicitly and therefore are not affected by the value in the
4674environment.)
4675
4676 When `make' runs a command script, variables defined in the makefile
4677are placed into the environment of that command. This allows you to
4678pass values to sub-`make' invocations (*note Recursive Use of `make':
4679Recursion.). By default, only variables that came from the environment
4680or the command line are passed to recursive invocations. You can use
4681the `export' directive to pass other variables. *Note Communicating
4682Variables to a Sub-`make': Variables/Recursion, for full details.
4683
4684 Other use of variables from the environment is not recommended. It
4685is not wise for makefiles to depend for their functioning on
4686environment variables set up outside their control, since this would
4687cause different users to get different results from the same makefile.
4688This is against the whole purpose of most makefiles.
4689
4690 Such problems would be especially likely with the variable `SHELL',
4691which is normally present in the environment to specify the user's
4692choice of interactive shell. It would be very undesirable for this
4693choice to affect `make'; so, `make' handles the `SHELL' environment
4694variable in a special way; see *Note Choosing the Shell::.
4695
4696
4697File: make.info, Node: Target-specific, Next: Pattern-specific, Prev: Environment, Up: Using Variables
4698
46996.10 Target-specific Variable Values
4700====================================
4701
4702Variable values in `make' are usually global; that is, they are the
4703same regardless of where they are evaluated (unless they're reset, of
4704course). One exception to that is automatic variables (*note Automatic
4705Variables::).
4706
4707 The other exception is "target-specific variable values". This
4708feature allows you to define different values for the same variable,
4709based on the target that `make' is currently building. As with
4710automatic variables, these values are only available within the context
4711of a target's command script (and in other target-specific assignments).
4712
4713 Set a target-specific variable value like this:
4714
4715 TARGET ... : VARIABLE-ASSIGNMENT
4716
4717or like this:
4718
4719 TARGET ... : override VARIABLE-ASSIGNMENT
4720
4721or like this:
4722
4723 TARGET ... : export VARIABLE-ASSIGNMENT
4724
4725 Multiple TARGET values create a target-specific variable value for
4726each member of the target list individually.
4727
4728 The VARIABLE-ASSIGNMENT can be any valid form of assignment;
4729recursive (`='), static (`:='), appending (`+='), or conditional
4730(`?='). All variables that appear within the VARIABLE-ASSIGNMENT are
4731evaluated within the context of the target: thus, any
4732previously-defined target-specific variable values will be in effect.
4733Note that this variable is actually distinct from any "global" value:
4734the two variables do not have to have the same flavor (recursive vs.
4735static).
4736
4737 Target-specific variables have the same priority as any other
4738makefile variable. Variables provided on the command-line (and in the
4739environment if the `-e' option is in force) will take precedence.
4740Specifying the `override' directive will allow the target-specific
4741variable value to be preferred.
4742
4743 There is one more special feature of target-specific variables: when
4744you define a target-specific variable that variable value is also in
4745effect for all prerequisites of this target, and all their
4746prerequisites, etc. (unless those prerequisites override that variable
4747with their own target-specific variable value). So, for example, a
4748statement like this:
4749
4750 prog : CFLAGS = -g
4751 prog : prog.o foo.o bar.o
4752
4753will set `CFLAGS' to `-g' in the command script for `prog', but it will
4754also set `CFLAGS' to `-g' in the command scripts that create `prog.o',
4755`foo.o', and `bar.o', and any command scripts which create their
4756prerequisites.
4757
4758 Be aware that a given prerequisite will only be built once per
4759invocation of make, at most. If the same file is a prerequisite of
4760multiple targets, and each of those targets has a different value for
4761the same target-specific variable, then the first target to be built
4762will cause that prerequisite to be built and the prerequisite will
4763inherit the target-specific value from the first target. It will
4764ignore the target-specific values from any other targets.
4765
4766
4767File: make.info, Node: Pattern-specific, Prev: Target-specific, Up: Using Variables
4768
47696.11 Pattern-specific Variable Values
4770=====================================
4771
4772In addition to target-specific variable values (*note Target-specific
4773Variable Values: Target-specific.), GNU `make' supports
4774pattern-specific variable values. In this form, the variable is
4775defined for any target that matches the pattern specified. If a target
4776matches more than one pattern, all the matching pattern-specific
4777variables are interpreted in the order in which they were defined in
4778the makefile, and collected together into one set. Variables defined
4779in this way are searched after any target-specific variables defined
4780explicitly for that target, and before target-specific variables
4781defined for the parent target.
4782
4783 Set a pattern-specific variable value like this:
4784
4785 PATTERN ... : VARIABLE-ASSIGNMENT
4786
4787or like this:
4788
4789 PATTERN ... : override VARIABLE-ASSIGNMENT
4790
4791where PATTERN is a %-pattern. As with target-specific variable values,
4792multiple PATTERN values create a pattern-specific variable value for
4793each pattern individually. The VARIABLE-ASSIGNMENT can be any valid
4794form of assignment. Any command-line variable setting will take
4795precedence, unless `override' is specified.
4796
4797 For example:
4798
4799 %.o : CFLAGS = -O
4800
4801will assign `CFLAGS' the value of `-O' for all targets matching the
4802pattern `%.o'.
4803
4804
4805File: make.info, Node: Conditionals, Next: Functions, Prev: Using Variables, Up: Top
4806
48077 Conditional Parts of Makefiles
4808********************************
4809
4810A "conditional" causes part of a makefile to be obeyed or ignored
4811depending on the values of variables. Conditionals can compare the
4812value of one variable to another, or the value of a variable to a
4813constant string. Conditionals control what `make' actually "sees" in
4814the makefile, so they _cannot_ be used to control shell commands at the
4815time of execution.
4816
4817* Menu:
4818
4819* Conditional Example:: Example of a conditional
4820* Conditional Syntax:: The syntax of conditionals.
4821* Testing Flags:: Conditionals that test flags.
4822
4823
4824File: make.info, Node: Conditional Example, Next: Conditional Syntax, Prev: Conditionals, Up: Conditionals
4825
48267.1 Example of a Conditional
4827============================
4828
4829The following example of a conditional tells `make' to use one set of
4830libraries if the `CC' variable is `gcc', and a different set of
4831libraries otherwise. It works by controlling which of two command
4832lines will be used as the command for a rule. The result is that
4833`CC=gcc' as an argument to `make' changes not only which compiler is
4834used but also which libraries are linked.
4835
4836 libs_for_gcc = -lgnu
4837 normal_libs =
4838
4839 foo: $(objects)
4840 ifeq ($(CC),gcc)
4841 $(CC) -o foo $(objects) $(libs_for_gcc)
4842 else
4843 $(CC) -o foo $(objects) $(normal_libs)
4844 endif
4845
4846 This conditional uses three directives: one `ifeq', one `else' and
4847one `endif'.
4848
4849 The `ifeq' directive begins the conditional, and specifies the
4850condition. It contains two arguments, separated by a comma and
4851surrounded by parentheses. Variable substitution is performed on both
4852arguments and then they are compared. The lines of the makefile
4853following the `ifeq' are obeyed if the two arguments match; otherwise
4854they are ignored.
4855
4856 The `else' directive causes the following lines to be obeyed if the
4857previous conditional failed. In the example above, this means that the
4858second alternative linking command is used whenever the first
4859alternative is not used. It is optional to have an `else' in a
4860conditional.
4861
4862 The `endif' directive ends the conditional. Every conditional must
4863end with an `endif'. Unconditional makefile text follows.
4864
4865 As this example illustrates, conditionals work at the textual level:
4866the lines of the conditional are treated as part of the makefile, or
4867ignored, according to the condition. This is why the larger syntactic
4868units of the makefile, such as rules, may cross the beginning or the
4869end of the conditional.
4870
4871 When the variable `CC' has the value `gcc', the above example has
4872this effect:
4873
4874 foo: $(objects)
4875 $(CC) -o foo $(objects) $(libs_for_gcc)
4876
4877When the variable `CC' has any other value, the effect is this:
4878
4879 foo: $(objects)
4880 $(CC) -o foo $(objects) $(normal_libs)
4881
4882 Equivalent results can be obtained in another way by
4883conditionalizing a variable assignment and then using the variable
4884unconditionally:
4885
4886 libs_for_gcc = -lgnu
4887 normal_libs =
4888
4889 ifeq ($(CC),gcc)
4890 libs=$(libs_for_gcc)
4891 else
4892 libs=$(normal_libs)
4893 endif
4894
4895 foo: $(objects)
4896 $(CC) -o foo $(objects) $(libs)
4897
4898
4899File: make.info, Node: Conditional Syntax, Next: Testing Flags, Prev: Conditional Example, Up: Conditionals
4900
49017.2 Syntax of Conditionals
4902==========================
4903
4904The syntax of a simple conditional with no `else' is as follows:
4905
4906 CONDITIONAL-DIRECTIVE
4907 TEXT-IF-TRUE
4908 endif
4909
4910The TEXT-IF-TRUE may be any lines of text, to be considered as part of
4911the makefile if the condition is true. If the condition is false, no
4912text is used instead.
4913
4914 The syntax of a complex conditional is as follows:
4915
4916 CONDITIONAL-DIRECTIVE
4917 TEXT-IF-TRUE
4918 else
4919 TEXT-IF-FALSE
4920 endif
4921
4922 or:
4923
4924 CONDITIONAL-DIRECTIVE
4925 TEXT-IF-ONE-IS-TRUE
4926 else CONDITIONAL-DIRECTIVE
4927 TEXT-IF-TRUE
4928 else
4929 TEXT-IF-FALSE
4930 endif
4931
4932There can be as many "`else' CONDITIONAL-DIRECTIVE" clauses as
4933necessary. Once a given condition is true, TEXT-IF-TRUE is used and no
4934other clause is used; if no condition is true then TEXT-IF-FALSE is
4935used. The TEXT-IF-TRUE and TEXT-IF-FALSE can be any number of lines of
4936text.
4937
4938 The syntax of the CONDITIONAL-DIRECTIVE is the same whether the
4939conditional is simple or complex; after an `else' or not. There are
4940four different directives that test different conditions. Here is a
4941table of them:
4942
4943`ifeq (ARG1, ARG2)'
4944`ifeq 'ARG1' 'ARG2''
4945`ifeq "ARG1" "ARG2"'
4946`ifeq "ARG1" 'ARG2''
4947`ifeq 'ARG1' "ARG2"'
4948 Expand all variable references in ARG1 and ARG2 and compare them.
4949 If they are identical, the TEXT-IF-TRUE is effective; otherwise,
4950 the TEXT-IF-FALSE, if any, is effective.
4951
4952 Often you want to test if a variable has a non-empty value. When
4953 the value results from complex expansions of variables and
4954 functions, expansions you would consider empty may actually
4955 contain whitespace characters and thus are not seen as empty.
4956 However, you can use the `strip' function (*note Text Functions::)
4957 to avoid interpreting whitespace as a non-empty value. For
4958 example:
4959
4960 ifeq ($(strip $(foo)),)
4961 TEXT-IF-EMPTY
4962 endif
4963
4964 will evaluate TEXT-IF-EMPTY even if the expansion of `$(foo)'
4965 contains whitespace characters.
4966
4967`ifneq (ARG1, ARG2)'
4968`ifneq 'ARG1' 'ARG2''
4969`ifneq "ARG1" "ARG2"'
4970`ifneq "ARG1" 'ARG2''
4971`ifneq 'ARG1' "ARG2"'
4972 Expand all variable references in ARG1 and ARG2 and compare them.
4973 If they are different, the TEXT-IF-TRUE is effective; otherwise,
4974 the TEXT-IF-FALSE, if any, is effective.
4975
4976`ifdef VARIABLE-NAME'
4977 The `ifdef' form takes the _name_ of a variable as its argument,
4978 not a reference to a variable. The value of that variable has a
4979 non-empty value, the TEXT-IF-TRUE is effective; otherwise, the
4980 TEXT-IF-FALSE, if any, is effective. Variables that have never
4981 been defined have an empty value. The text VARIABLE-NAME is
4982 expanded, so it could be a variable or function that expands to
4983 the name of a variable. For example:
4984
4985 bar = true
4986 foo = bar
4987 ifdef $(foo)
4988 frobozz = yes
4989 endif
4990
4991 The variable reference `$(foo)' is expanded, yielding `bar', which
4992 is considered to be the name of a variable. The variable `bar' is
4993 not expanded, but its value is examined to determine if it is
4994 non-empty.
4995
4996 Note that `ifdef' only tests whether a variable has a value. It
4997 does not expand the variable to see if that value is nonempty.
4998 Consequently, tests using `ifdef' return true for all definitions
4999 except those like `foo ='. To test for an empty value, use
5000 `ifeq ($(foo),)'. For example,
5001
5002 bar =
5003 foo = $(bar)
5004 ifdef foo
5005 frobozz = yes
5006 else
5007 frobozz = no
5008 endif
5009
5010 sets `frobozz' to `yes', while:
5011
5012 foo =
5013 ifdef foo
5014 frobozz = yes
5015 else
5016 frobozz = no
5017 endif
5018
5019 sets `frobozz' to `no'.
5020
5021`ifndef VARIABLE-NAME'
5022 If the variable VARIABLE-NAME has an empty value, the TEXT-IF-TRUE
5023 is effective; otherwise, the TEXT-IF-FALSE, if any, is effective.
5024 The rules for expansion and testing of VARIABLE-NAME are identical
5025 to the `ifdef' directive.
5026
5027 Extra spaces are allowed and ignored at the beginning of the
5028conditional directive line, but a tab is not allowed. (If the line
5029begins with a tab, it will be considered a command for a rule.) Aside
5030from this, extra spaces or tabs may be inserted with no effect anywhere
5031except within the directive name or within an argument. A comment
5032starting with `#' may appear at the end of the line.
5033
5034 The other two directives that play a part in a conditional are `else'
5035and `endif'. Each of these directives is written as one word, with no
5036arguments. Extra spaces are allowed and ignored at the beginning of the
5037line, and spaces or tabs at the end. A comment starting with `#' may
5038appear at the end of the line.
5039
5040 Conditionals affect which lines of the makefile `make' uses. If the
5041condition is true, `make' reads the lines of the TEXT-IF-TRUE as part
5042of the makefile; if the condition is false, `make' ignores those lines
5043completely. It follows that syntactic units of the makefile, such as
5044rules, may safely be split across the beginning or the end of the
5045conditional.
5046
5047 `make' evaluates conditionals when it reads a makefile.
5048Consequently, you cannot use automatic variables in the tests of
5049conditionals because they are not defined until commands are run (*note
5050Automatic Variables::).
5051
5052 To prevent intolerable confusion, it is not permitted to start a
5053conditional in one makefile and end it in another. However, you may
5054write an `include' directive within a conditional, provided you do not
5055attempt to terminate the conditional inside the included file.
5056
5057
5058File: make.info, Node: Testing Flags, Prev: Conditional Syntax, Up: Conditionals
5059
50607.3 Conditionals that Test Flags
5061================================
5062
5063You can write a conditional that tests `make' command flags such as
5064`-t' by using the variable `MAKEFLAGS' together with the `findstring'
5065function (*note Functions for String Substitution and Analysis: Text
5066Functions.). This is useful when `touch' is not enough to make a file
5067appear up to date.
5068
5069 The `findstring' function determines whether one string appears as a
5070substring of another. If you want to test for the `-t' flag, use `t'
5071as the first string and the value of `MAKEFLAGS' as the other.
5072
5073 For example, here is how to arrange to use `ranlib -t' to finish
5074marking an archive file up to date:
5075
5076 archive.a: ...
5077 ifneq (,$(findstring t,$(MAKEFLAGS)))
5078 +touch archive.a
5079 +ranlib -t archive.a
5080 else
5081 ranlib archive.a
5082 endif
5083
5084The `+' prefix marks those command lines as "recursive" so that they
5085will be executed despite use of the `-t' flag. *Note Recursive Use of
5086`make': Recursion.
5087
5088
5089File: make.info, Node: Functions, Next: Running, Prev: Conditionals, Up: Top
5090
50918 Functions for Transforming Text
5092*********************************
5093
5094"Functions" allow you to do text processing in the makefile to compute
5095the files to operate on or the commands to use. You use a function in a
5096"function call", where you give the name of the function and some text
5097(the "arguments") for the function to operate on. The result of the
5098function's processing is substituted into the makefile at the point of
5099the call, just as a variable might be substituted.
5100
5101* Menu:
5102
5103* Syntax of Functions:: How to write a function call.
5104* Text Functions:: General-purpose text manipulation functions.
5105* File Name Functions:: Functions for manipulating file names.
5106* Conditional Functions:: Functions that implement conditions.
5107* Foreach Function:: Repeat some text with controlled variation.
5108* Call Function:: Expand a user-defined function.
5109* Value Function:: Return the un-expanded value of a variable.
5110* Eval Function:: Evaluate the arguments as makefile syntax.
5111* Origin Function:: Find where a variable got its value.
5112* Flavor Function:: Find out the flavor of a variable.
5113* Shell Function:: Substitute the output of a shell command.
5114* Make Control Functions:: Functions that control how make runs.
5115
5116
5117File: make.info, Node: Syntax of Functions, Next: Text Functions, Prev: Functions, Up: Functions
5118
51198.1 Function Call Syntax
5120========================
5121
5122A function call resembles a variable reference. It looks like this:
5123
5124 $(FUNCTION ARGUMENTS)
5125
5126or like this:
5127
5128 ${FUNCTION ARGUMENTS}
5129
5130 Here FUNCTION is a function name; one of a short list of names that
5131are part of `make'. You can also essentially create your own functions
5132by using the `call' builtin function.
5133
5134 The ARGUMENTS are the arguments of the function. They are separated
5135from the function name by one or more spaces or tabs, and if there is
5136more than one argument, then they are separated by commas. Such
5137whitespace and commas are not part of an argument's value. The
5138delimiters which you use to surround the function call, whether
5139parentheses or braces, can appear in an argument only in matching pairs;
5140the other kind of delimiters may appear singly. If the arguments
5141themselves contain other function calls or variable references, it is
5142wisest to use the same kind of delimiters for all the references; write
5143`$(subst a,b,$(x))', not `$(subst a,b,${x})'. This is because it is
5144clearer, and because only one type of delimiter is matched to find the
5145end of the reference.
5146
5147 The text written for each argument is processed by substitution of
5148variables and function calls to produce the argument value, which is
5149the text on which the function acts. The substitution is done in the
5150order in which the arguments appear.
5151
5152 Commas and unmatched parentheses or braces cannot appear in the text
5153of an argument as written; leading spaces cannot appear in the text of
5154the first argument as written. These characters can be put into the
5155argument value by variable substitution. First define variables
5156`comma' and `space' whose values are isolated comma and space
5157characters, then substitute these variables where such characters are
5158wanted, like this:
5159
5160 comma:= ,
5161 empty:=
5162 space:= $(empty) $(empty)
5163 foo:= a b c
5164 bar:= $(subst $(space),$(comma),$(foo))
5165 # bar is now `a,b,c'.
5166
5167Here the `subst' function replaces each space with a comma, through the
5168value of `foo', and substitutes the result.
5169
5170
5171File: make.info, Node: Text Functions, Next: File Name Functions, Prev: Syntax of Functions, Up: Functions
5172
51738.2 Functions for String Substitution and Analysis
5174==================================================
5175
5176Here are some functions that operate on strings:
5177
5178`$(subst FROM,TO,TEXT)'
5179 Performs a textual replacement on the text TEXT: each occurrence
5180 of FROM is replaced by TO. The result is substituted for the
5181 function call. For example,
5182
5183 $(subst ee,EE,feet on the street)
5184
5185 substitutes the string `fEEt on the strEEt'.
5186
5187`$(patsubst PATTERN,REPLACEMENT,TEXT)'
5188 Finds whitespace-separated words in TEXT that match PATTERN and
5189 replaces them with REPLACEMENT. Here PATTERN may contain a `%'
5190 which acts as a wildcard, matching any number of any characters
5191 within a word. If REPLACEMENT also contains a `%', the `%' is
5192 replaced by the text that matched the `%' in PATTERN. Only the
5193 first `%' in the PATTERN and REPLACEMENT is treated this way; any
5194 subsequent `%' is unchanged.
5195
5196 `%' characters in `patsubst' function invocations can be quoted
5197 with preceding backslashes (`\'). Backslashes that would
5198 otherwise quote `%' characters can be quoted with more backslashes.
5199 Backslashes that quote `%' characters or other backslashes are
5200 removed from the pattern before it is compared file names or has a
5201 stem substituted into it. Backslashes that are not in danger of
5202 quoting `%' characters go unmolested. For example, the pattern
5203 `the\%weird\\%pattern\\' has `the%weird\' preceding the operative
5204 `%' character, and `pattern\\' following it. The final two
5205 backslashes are left alone because they cannot affect any `%'
5206 character.
5207
5208 Whitespace between words is folded into single space characters;
5209 leading and trailing whitespace is discarded.
5210
5211 For example,
5212
5213 $(patsubst %.c,%.o,x.c.c bar.c)
5214
5215 produces the value `x.c.o bar.o'.
5216
5217 Substitution references (*note Substitution References:
5218 Substitution Refs.) are a simpler way to get the effect of the
5219 `patsubst' function:
5220
5221 $(VAR:PATTERN=REPLACEMENT)
5222
5223 is equivalent to
5224
5225 $(patsubst PATTERN,REPLACEMENT,$(VAR))
5226
5227 The second shorthand simplifies one of the most common uses of
5228 `patsubst': replacing the suffix at the end of file names.
5229
5230 $(VAR:SUFFIX=REPLACEMENT)
5231
5232 is equivalent to
5233
5234 $(patsubst %SUFFIX,%REPLACEMENT,$(VAR))
5235
5236 For example, you might have a list of object files:
5237
5238 objects = foo.o bar.o baz.o
5239
5240 To get the list of corresponding source files, you could simply
5241 write:
5242
5243 $(objects:.o=.c)
5244
5245 instead of using the general form:
5246
5247 $(patsubst %.o,%.c,$(objects))
5248
5249`$(strip STRING)'
5250 Removes leading and trailing whitespace from STRING and replaces
5251 each internal sequence of one or more whitespace characters with a
5252 single space. Thus, `$(strip a b c )' results in `a b c'.
5253
5254 The function `strip' can be very useful when used in conjunction
5255 with conditionals. When comparing something with the empty string
5256 `' using `ifeq' or `ifneq', you usually want a string of just
5257 whitespace to match the empty string (*note Conditionals::).
5258
5259 Thus, the following may fail to have the desired results:
5260
5261 .PHONY: all
5262 ifneq "$(needs_made)" ""
5263 all: $(needs_made)
5264 else
5265 all:;@echo 'Nothing to make!'
5266 endif
5267
5268 Replacing the variable reference `$(needs_made)' with the function
5269 call `$(strip $(needs_made))' in the `ifneq' directive would make
5270 it more robust.
5271
5272`$(findstring FIND,IN)'
5273 Searches IN for an occurrence of FIND. If it occurs, the value is
5274 FIND; otherwise, the value is empty. You can use this function in
5275 a conditional to test for the presence of a specific substring in
5276 a given string. Thus, the two examples,
5277
5278 $(findstring a,a b c)
5279 $(findstring a,b c)
5280
5281 produce the values `a' and `' (the empty string), respectively.
5282 *Note Testing Flags::, for a practical application of `findstring'.
5283
5284`$(filter PATTERN...,TEXT)'
5285 Returns all whitespace-separated words in TEXT that _do_ match any
5286 of the PATTERN words, removing any words that _do not_ match. The
5287 patterns are written using `%', just like the patterns used in the
5288 `patsubst' function above.
5289
5290 The `filter' function can be used to separate out different types
5291 of strings (such as file names) in a variable. For example:
5292
5293 sources := foo.c bar.c baz.s ugh.h
5294 foo: $(sources)
5295 cc $(filter %.c %.s,$(sources)) -o foo
5296
5297 says that `foo' depends of `foo.c', `bar.c', `baz.s' and `ugh.h'
5298 but only `foo.c', `bar.c' and `baz.s' should be specified in the
5299 command to the compiler.
5300
5301`$(filter-out PATTERN...,TEXT)'
5302 Returns all whitespace-separated words in TEXT that _do not_ match
5303 any of the PATTERN words, removing the words that _do_ match one
5304 or more. This is the exact opposite of the `filter' function.
5305
5306 For example, given:
5307
5308 objects=main1.o foo.o main2.o bar.o
5309 mains=main1.o main2.o
5310
5311 the following generates a list which contains all the object files
5312 not in `mains':
5313
5314 $(filter-out $(mains),$(objects))
5315
5316`$(sort LIST)'
5317 Sorts the words of LIST in lexical order, removing duplicate
5318 words. The output is a list of words separated by single spaces.
5319 Thus,
5320
5321 $(sort foo bar lose)
5322
5323 returns the value `bar foo lose'.
5324
5325 Incidentally, since `sort' removes duplicate words, you can use it
5326 for this purpose even if you don't care about the sort order.
5327
5328`$(word N,TEXT)'
5329 Returns the Nth word of TEXT. The legitimate values of N start
5330 from 1. If N is bigger than the number of words in TEXT, the
5331 value is empty. For example,
5332
5333 $(word 2, foo bar baz)
5334
5335 returns `bar'.
5336
5337`$(wordlist S,E,TEXT)'
5338 Returns the list of words in TEXT starting with word S and ending
5339 with word E (inclusive). The legitimate values of S start from 1;
5340 E may start from 0. If S is bigger than the number of words in
5341 TEXT, the value is empty. If E is bigger than the number of words
5342 in TEXT, words up to the end of TEXT are returned. If S is
5343 greater than E, nothing is returned. For example,
5344
5345 $(wordlist 2, 3, foo bar baz)
5346
5347 returns `bar baz'.
5348
5349`$(words TEXT)'
5350 Returns the number of words in TEXT. Thus, the last word of TEXT
5351 is `$(word $(words TEXT),TEXT)'.
5352
5353`$(firstword NAMES...)'
5354 The argument NAMES is regarded as a series of names, separated by
5355 whitespace. The value is the first name in the series. The rest
5356 of the names are ignored.
5357
5358 For example,
5359
5360 $(firstword foo bar)
5361
5362 produces the result `foo'. Although `$(firstword TEXT)' is the
5363 same as `$(word 1,TEXT)', the `firstword' function is retained for
5364 its simplicity.
5365
5366`$(lastword NAMES...)'
5367 The argument NAMES is regarded as a series of names, separated by
5368 whitespace. The value is the last name in the series.
5369
5370 For example,
5371
5372 $(lastword foo bar)
5373
5374 produces the result `bar'. Although `$(lastword TEXT)' is the
5375 same as `$(word $(words TEXT),TEXT)', the `lastword' function was
5376 added for its simplicity and better performance.
5377
5378 Here is a realistic example of the use of `subst' and `patsubst'.
5379Suppose that a makefile uses the `VPATH' variable to specify a list of
5380directories that `make' should search for prerequisite files (*note
5381`VPATH' Search Path for All Prerequisites: General Search.). This
5382example shows how to tell the C compiler to search for header files in
5383the same list of directories.
5384
5385 The value of `VPATH' is a list of directories separated by colons,
5386such as `src:../headers'. First, the `subst' function is used to
5387change the colons to spaces:
5388
5389 $(subst :, ,$(VPATH))
5390
5391This produces `src ../headers'. Then `patsubst' is used to turn each
5392directory name into a `-I' flag. These can be added to the value of
5393the variable `CFLAGS', which is passed automatically to the C compiler,
5394like this:
5395
5396 override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
5397
5398The effect is to append the text `-Isrc -I../headers' to the previously
5399given value of `CFLAGS'. The `override' directive is used so that the
5400new value is assigned even if the previous value of `CFLAGS' was
5401specified with a command argument (*note The `override' Directive:
5402Override Directive.).
5403
5404
5405File: make.info, Node: File Name Functions, Next: Conditional Functions, Prev: Text Functions, Up: Functions
5406
54078.3 Functions for File Names
5408============================
5409
5410Several of the built-in expansion functions relate specifically to
5411taking apart file names or lists of file names.
5412
5413 Each of the following functions performs a specific transformation
5414on a file name. The argument of the function is regarded as a series
5415of file names, separated by whitespace. (Leading and trailing
5416whitespace is ignored.) Each file name in the series is transformed in
5417the same way and the results are concatenated with single spaces
5418between them.
5419
5420`$(dir NAMES...)'
5421 Extracts the directory-part of each file name in NAMES. The
5422 directory-part of the file name is everything up through (and
5423 including) the last slash in it. If the file name contains no
5424 slash, the directory part is the string `./'. For example,
5425
5426 $(dir src/foo.c hacks)
5427
5428 produces the result `src/ ./'.
5429
5430`$(notdir NAMES...)'
5431 Extracts all but the directory-part of each file name in NAMES.
5432 If the file name contains no slash, it is left unchanged.
5433 Otherwise, everything through the last slash is removed from it.
5434
5435 A file name that ends with a slash becomes an empty string. This
5436 is unfortunate, because it means that the result does not always
5437 have the same number of whitespace-separated file names as the
5438 argument had; but we do not see any other valid alternative.
5439
5440 For example,
5441
5442 $(notdir src/foo.c hacks)
5443
5444 produces the result `foo.c hacks'.
5445
5446`$(suffix NAMES...)'
5447 Extracts the suffix of each file name in NAMES. If the file name
5448 contains a period, the suffix is everything starting with the last
5449 period. Otherwise, the suffix is the empty string. This
5450 frequently means that the result will be empty when NAMES is not,
5451 and if NAMES contains multiple file names, the result may contain
5452 fewer file names.
5453
5454 For example,
5455
5456 $(suffix src/foo.c src-1.0/bar.c hacks)
5457
5458 produces the result `.c .c'.
5459
5460`$(basename NAMES...)'
5461 Extracts all but the suffix of each file name in NAMES. If the
5462 file name contains a period, the basename is everything starting
5463 up to (and not including) the last period. Periods in the
5464 directory part are ignored. If there is no period, the basename
5465 is the entire file name. For example,
5466
5467 $(basename src/foo.c src-1.0/bar hacks)
5468
5469 produces the result `src/foo src-1.0/bar hacks'.
5470
5471`$(addsuffix SUFFIX,NAMES...)'
5472 The argument NAMES is regarded as a series of names, separated by
5473 whitespace; SUFFIX is used as a unit. The value of SUFFIX is
5474 appended to the end of each individual name and the resulting
5475 larger names are concatenated with single spaces between them.
5476 For example,
5477
5478 $(addsuffix .c,foo bar)
5479
5480 produces the result `foo.c bar.c'.
5481
5482`$(addprefix PREFIX,NAMES...)'
5483 The argument NAMES is regarded as a series of names, separated by
5484 whitespace; PREFIX is used as a unit. The value of PREFIX is
5485 prepended to the front of each individual name and the resulting
5486 larger names are concatenated with single spaces between them.
5487 For example,
5488
5489 $(addprefix src/,foo bar)
5490
5491 produces the result `src/foo src/bar'.
5492
5493`$(join LIST1,LIST2)'
5494 Concatenates the two arguments word by word: the two first words
5495 (one from each argument) concatenated form the first word of the
5496 result, the two second words form the second word of the result,
5497 and so on. So the Nth word of the result comes from the Nth word
5498 of each argument. If one argument has more words that the other,
5499 the extra words are copied unchanged into the result.
5500
5501 For example, `$(join a b,.c .o)' produces `a.c b.o'.
5502
5503 Whitespace between the words in the lists is not preserved; it is
5504 replaced with a single space.
5505
5506 This function can merge the results of the `dir' and `notdir'
5507 functions, to produce the original list of files which was given
5508 to those two functions.
5509
5510`$(wildcard PATTERN)'
5511 The argument PATTERN is a file name pattern, typically containing
5512 wildcard characters (as in shell file name patterns). The result
5513 of `wildcard' is a space-separated list of the names of existing
5514 files that match the pattern. *Note Using Wildcard Characters in
5515 File Names: Wildcards.
5516
5517`$(realpath NAMES...)'
5518 For each file name in NAMES return the canonical absolute name. A
5519 canonical name does not contain any `.' or `..' components, nor
5520 any repeated path separators (`/') or symlinks. In case of a
5521 failure the empty string is returned. Consult the `realpath(3)'
5522 documentation for a list of possible failure causes.
5523
5524`$(abspath NAMES...)'
5525 For each file name in NAMES return an absolute name that does not
5526 contain any `.' or `..' components, nor any repeated path
5527 separators (`/'). Note that, in contrast to `realpath' function,
5528 `abspath' does not resolve symlinks and does not require the file
5529 names to refer to an existing file or directory. Use the
5530 `wildcard' function to test for existence.
5531
5532
5533File: make.info, Node: Conditional Functions, Next: Foreach Function, Prev: File Name Functions, Up: Functions
5534
55358.4 Functions for Conditionals
5536==============================
5537
5538There are three functions that provide conditional expansion. A key
5539aspect of these functions is that not all of the arguments are expanded
5540initially. Only those arguments which need to be expanded, will be
5541expanded.
5542
5543`$(if CONDITION,THEN-PART[,ELSE-PART])'
5544 The `if' function provides support for conditional expansion in a
5545 functional context (as opposed to the GNU `make' makefile
5546 conditionals such as `ifeq' (*note Syntax of Conditionals:
5547 Conditional Syntax.).
5548
5549 The first argument, CONDITION, first has all preceding and
5550 trailing whitespace stripped, then is expanded. If it expands to
5551 any non-empty string, then the condition is considered to be true.
5552 If it expands to an empty string, the condition is considered to
5553 be false.
5554
5555 If the condition is true then the second argument, THEN-PART, is
5556 evaluated and this is used as the result of the evaluation of the
5557 entire `if' function.
5558
5559 If the condition is false then the third argument, ELSE-PART, is
5560 evaluated and this is the result of the `if' function. If there is
5561 no third argument, the `if' function evaluates to nothing (the
5562 empty string).
5563
5564 Note that only one of the THEN-PART or the ELSE-PART will be
5565 evaluated, never both. Thus, either can contain side-effects
5566 (such as `shell' function calls, etc.)
5567
5568`$(or CONDITION1[,CONDITION2[,CONDITION3...]])'
5569 The `or' function provides a "short-circuiting" OR operation.
5570 Each argument is expanded, in order. If an argument expands to a
5571 non-empty string the processing stops and the result of the
5572 expansion is that string. If, after all arguments are expanded,
5573 all of them are false (empty), then the result of the expansion is
5574 the empty string.
5575
5576`$(and CONDITION1[,CONDITION2[,CONDITION3...]])'
5577 The `and' function provides a "short-circuiting" AND operation.
5578 Each argument is expanded, in order. If an argument expands to an
5579 empty string the processing stops and the result of the expansion
5580 is the empty string. If all arguments expand to a non-empty
5581 string then the result of the expansion is the expansion of the
5582 last argument.
5583
5584
5585
5586File: make.info, Node: Foreach Function, Next: Call Function, Prev: Conditional Functions, Up: Functions
5587
55888.5 The `foreach' Function
5589==========================
5590
5591The `foreach' function is very different from other functions. It
5592causes one piece of text to be used repeatedly, each time with a
5593different substitution performed on it. It resembles the `for' command
5594in the shell `sh' and the `foreach' command in the C-shell `csh'.
5595
5596 The syntax of the `foreach' function is:
5597
5598 $(foreach VAR,LIST,TEXT)
5599
5600The first two arguments, VAR and LIST, are expanded before anything
5601else is done; note that the last argument, TEXT, is *not* expanded at
5602the same time. Then for each word of the expanded value of LIST, the
5603variable named by the expanded value of VAR is set to that word, and
5604TEXT is expanded. Presumably TEXT contains references to that
5605variable, so its expansion will be different each time.
5606
5607 The result is that TEXT is expanded as many times as there are
5608whitespace-separated words in LIST. The multiple expansions of TEXT
5609are concatenated, with spaces between them, to make the result of
5610`foreach'.
5611
5612 This simple example sets the variable `files' to the list of all
5613files in the directories in the list `dirs':
5614
5615 dirs := a b c d
5616 files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
5617
5618 Here TEXT is `$(wildcard $(dir)/*)'. The first repetition finds the
5619value `a' for `dir', so it produces the same result as `$(wildcard
5620a/*)'; the second repetition produces the result of `$(wildcard b/*)';
5621and the third, that of `$(wildcard c/*)'.
5622
5623 This example has the same result (except for setting `dirs') as the
5624following example:
5625
5626 files := $(wildcard a/* b/* c/* d/*)
5627
5628 When TEXT is complicated, you can improve readability by giving it a
5629name, with an additional variable:
5630
5631 find_files = $(wildcard $(dir)/*)
5632 dirs := a b c d
5633 files := $(foreach dir,$(dirs),$(find_files))
5634
5635Here we use the variable `find_files' this way. We use plain `=' to
5636define a recursively-expanding variable, so that its value contains an
5637actual function call to be reexpanded under the control of `foreach'; a
5638simply-expanded variable would not do, since `wildcard' would be called
5639only once at the time of defining `find_files'.
5640
5641 The `foreach' function has no permanent effect on the variable VAR;
5642its value and flavor after the `foreach' function call are the same as
5643they were beforehand. The other values which are taken from LIST are
5644in effect only temporarily, during the execution of `foreach'. The
5645variable VAR is a simply-expanded variable during the execution of
5646`foreach'. If VAR was undefined before the `foreach' function call, it
5647is undefined after the call. *Note The Two Flavors of Variables:
5648Flavors.
5649
5650 You must take care when using complex variable expressions that
5651result in variable names because many strange things are valid variable
5652names, but are probably not what you intended. For example,
5653
5654 files := $(foreach Esta escrito en espanol!,b c ch,$(find_files))
5655
5656might be useful if the value of `find_files' references the variable
5657whose name is `Esta escrito en espanol!' (es un nombre bastante largo,
5658no?), but it is more likely to be a mistake.
5659
5660
5661File: make.info, Node: Call Function, Next: Value Function, Prev: Foreach Function, Up: Functions
5662
56638.6 The `call' Function
5664=======================
5665
5666The `call' function is unique in that it can be used to create new
5667parameterized functions. You can write a complex expression as the
5668value of a variable, then use `call' to expand it with different values.
5669
5670 The syntax of the `call' function is:
5671
5672 $(call VARIABLE,PARAM,PARAM,...)
5673
5674 When `make' expands this function, it assigns each PARAM to
5675temporary variables `$(1)', `$(2)', etc. The variable `$(0)' will
5676contain VARIABLE. There is no maximum number of parameter arguments.
5677There is no minimum, either, but it doesn't make sense to use `call'
5678with no parameters.
5679
5680 Then VARIABLE is expanded as a `make' variable in the context of
5681these temporary assignments. Thus, any reference to `$(1)' in the
5682value of VARIABLE will resolve to the first PARAM in the invocation of
5683`call'.
5684
5685 Note that VARIABLE is the _name_ of a variable, not a _reference_ to
5686that variable. Therefore you would not normally use a `$' or
5687parentheses when writing it. (You can, however, use a variable
5688reference in the name if you want the name not to be a constant.)
5689
5690 If VARIABLE is the name of a builtin function, the builtin function
5691is always invoked (even if a `make' variable by that name also exists).
5692
5693 The `call' function expands the PARAM arguments before assigning
5694them to temporary variables. This means that VARIABLE values
5695containing references to builtin functions that have special expansion
5696rules, like `foreach' or `if', may not work as you expect.
5697
5698 Some examples may make this clearer.
5699
5700 This macro simply reverses its arguments:
5701
5702 reverse = $(2) $(1)
5703
5704 foo = $(call reverse,a,b)
5705
5706Here FOO will contain `b a'.
5707
5708 This one is slightly more interesting: it defines a macro to search
5709for the first instance of a program in `PATH':
5710
5711 pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
5712
5713 LS := $(call pathsearch,ls)
5714
5715Now the variable LS contains `/bin/ls' or similar.
5716
5717 The `call' function can be nested. Each recursive invocation gets
5718its own local values for `$(1)', etc. that mask the values of
5719higher-level `call'. For example, here is an implementation of a "map"
5720function:
5721
5722 map = $(foreach a,$(2),$(call $(1),$(a)))
5723
5724 Now you can MAP a function that normally takes only one argument,
5725such as `origin', to multiple values in one step:
5726
5727 o = $(call map,origin,o map MAKE)
5728
5729 and end up with O containing something like `file file default'.
5730
5731 A final caution: be careful when adding whitespace to the arguments
5732to `call'. As with other functions, any whitespace contained in the
5733second and subsequent arguments is kept; this can cause strange
5734effects. It's generally safest to remove all extraneous whitespace when
5735providing parameters to `call'.
5736
5737
5738File: make.info, Node: Value Function, Next: Eval Function, Prev: Call Function, Up: Functions
5739
57408.7 The `value' Function
5741========================
5742
5743The `value' function provides a way for you to use the value of a
5744variable _without_ having it expanded. Please note that this does not
5745undo expansions which have already occurred; for example if you create
5746a simply expanded variable its value is expanded during the definition;
5747in that case the `value' function will return the same result as using
5748the variable directly.
5749
5750 The syntax of the `value' function is:
5751
5752 $(value VARIABLE)
5753
5754 Note that VARIABLE is the _name_ of a variable; not a _reference_ to
5755that variable. Therefore you would not normally use a `$' or
5756parentheses when writing it. (You can, however, use a variable
5757reference in the name if you want the name not to be a constant.)
5758
5759 The result of this function is a string containing the value of
5760VARIABLE, without any expansion occurring. For example, in this
5761makefile:
5762
5763 FOO = $PATH
5764
5765 all:
5766 @echo $(FOO)
5767 @echo $(value FOO)
5768
5769The first output line would be `ATH', since the "$P" would be expanded
5770as a `make' variable, while the second output line would be the current
5771value of your `$PATH' environment variable, since the `value' function
5772avoided the expansion.
5773
5774 The `value' function is most often used in conjunction with the
5775`eval' function (*note Eval Function::).
5776
5777
5778File: make.info, Node: Eval Function, Next: Origin Function, Prev: Value Function, Up: Functions
5779
57808.8 The `eval' Function
5781=======================
5782
5783The `eval' function is very special: it allows you to define new
5784makefile constructs that are not constant; which are the result of
5785evaluating other variables and functions. The argument to the `eval'
5786function is expanded, then the results of that expansion are parsed as
5787makefile syntax. The expanded results can define new `make' variables,
5788targets, implicit or explicit rules, etc.
5789
5790 The result of the `eval' function is always the empty string; thus,
5791it can be placed virtually anywhere in a makefile without causing
5792syntax errors.
5793
5794 It's important to realize that the `eval' argument is expanded
5795_twice_; first by the `eval' function, then the results of that
5796expansion are expanded again when they are parsed as makefile syntax.
5797This means you may need to provide extra levels of escaping for "$"
5798characters when using `eval'. The `value' function (*note Value
5799Function::) can sometimes be useful in these situations, to circumvent
5800unwanted expansions.
5801
5802 Here is an example of how `eval' can be used; this example combines
5803a number of concepts and other functions. Although it might seem
5804overly complex to use `eval' in this example, rather than just writing
5805out the rules, consider two things: first, the template definition (in
5806`PROGRAM_template') could need to be much more complex than it is here;
5807and second, you might put the complex, "generic" part of this example
5808into another makefile, then include it in all the individual makefiles.
5809Now your individual makefiles are quite straightforward.
5810
5811 PROGRAMS = server client
5812
5813 server_OBJS = server.o server_priv.o server_access.o
5814 server_LIBS = priv protocol
5815
5816 client_OBJS = client.o client_api.o client_mem.o
5817 client_LIBS = protocol
5818
5819 # Everything after this is generic
5820
5821 .PHONY: all
5822 all: $(PROGRAMS)
5823
5824 define PROGRAM_template
5825 $(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
5826 ALL_OBJS += $$($(1)_OBJS)
5827 endef
5828
5829 $(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
5830
5831 $(PROGRAMS):
5832 $(LINK.o) $^ $(LDLIBS) -o $@
5833
5834 clean:
5835 rm -f $(ALL_OBJS) $(PROGRAMS)
5836
5837
5838File: make.info, Node: Origin Function, Next: Flavor Function, Prev: Eval Function, Up: Functions
5839
58408.9 The `origin' Function
5841=========================
5842
5843The `origin' function is unlike most other functions in that it does
5844not operate on the values of variables; it tells you something _about_
5845a variable. Specifically, it tells you where it came from.
5846
5847 The syntax of the `origin' function is:
5848
5849 $(origin VARIABLE)
5850
5851 Note that VARIABLE is the _name_ of a variable to inquire about; not
5852a _reference_ to that variable. Therefore you would not normally use a
5853`$' or parentheses when writing it. (You can, however, use a variable
5854reference in the name if you want the name not to be a constant.)
5855
5856 The result of this function is a string telling you how the variable
5857VARIABLE was defined:
5858
5859`undefined'
5860 if VARIABLE was never defined.
5861
5862`default'
5863 if VARIABLE has a default definition, as is usual with `CC' and so
5864 on. *Note Variables Used by Implicit Rules: Implicit Variables.
5865 Note that if you have redefined a default variable, the `origin'
5866 function will return the origin of the later definition.
5867
5868`environment'
5869 if VARIABLE was defined as an environment variable and the `-e'
5870 option is _not_ turned on (*note Summary of Options: Options
5871 Summary.).
5872
5873`environment override'
5874 if VARIABLE was defined as an environment variable and the `-e'
5875 option _is_ turned on (*note Summary of Options: Options Summary.).
5876
5877`file'
5878 if VARIABLE was defined in a makefile.
5879
5880`command line'
5881 if VARIABLE was defined on the command line.
5882
5883`override'
5884 if VARIABLE was defined with an `override' directive in a makefile
5885 (*note The `override' Directive: Override Directive.).
5886
5887`automatic'
5888 if VARIABLE is an automatic variable defined for the execution of
5889 the commands for each rule (*note Automatic Variables::).
5890
5891 This information is primarily useful (other than for your curiosity)
5892to determine if you want to believe the value of a variable. For
5893example, suppose you have a makefile `foo' that includes another
5894makefile `bar'. You want a variable `bletch' to be defined in `bar' if
5895you run the command `make -f bar', even if the environment contains a
5896definition of `bletch'. However, if `foo' defined `bletch' before
5897including `bar', you do not want to override that definition. This
5898could be done by using an `override' directive in `foo', giving that
5899definition precedence over the later definition in `bar';
5900unfortunately, the `override' directive would also override any command
5901line definitions. So, `bar' could include:
5902
5903 ifdef bletch
5904 ifeq "$(origin bletch)" "environment"
5905 bletch = barf, gag, etc.
5906 endif
5907 endif
5908
5909If `bletch' has been defined from the environment, this will redefine
5910it.
5911
5912 If you want to override a previous definition of `bletch' if it came
5913from the environment, even under `-e', you could instead write:
5914
5915 ifneq "$(findstring environment,$(origin bletch))" ""
5916 bletch = barf, gag, etc.
5917 endif
5918
5919 Here the redefinition takes place if `$(origin bletch)' returns
5920either `environment' or `environment override'. *Note Functions for
5921String Substitution and Analysis: Text Functions.
5922
5923
5924File: make.info, Node: Flavor Function, Next: Shell Function, Prev: Origin Function, Up: Functions
5925
59268.10 The `flavor' Function
5927==========================
5928
5929The `flavor' function is unlike most other functions (and like `origin'
5930function) in that it does not operate on the values of variables; it
5931tells you something _about_ a variable. Specifically, it tells you the
5932flavor of a variable (*note The Two Flavors of Variables: Flavors.).
5933
5934 The syntax of the `flavor' function is:
5935
5936 $(flavor VARIABLE)
5937
5938 Note that VARIABLE is the _name_ of a variable to inquire about; not
5939a _reference_ to that variable. Therefore you would not normally use a
5940`$' or parentheses when writing it. (You can, however, use a variable
5941reference in the name if you want the name not to be a constant.)
5942
5943 The result of this function is a string that identifies the flavor
5944of the variable VARIABLE:
5945
5946`undefined'
5947 if VARIABLE was never defined.
5948
5949`recursive'
5950 if VARIABLE is a recursively expanded variable.
5951
5952`simple'
5953 if VARIABLE is a simply expanded variable.
5954
5955
5956
5957File: make.info, Node: Shell Function, Next: Make Control Functions, Prev: Flavor Function, Up: Functions
5958
59598.11 The `shell' Function
5960=========================
5961
5962The `shell' function is unlike any other function other than the
5963`wildcard' function (*note The Function `wildcard': Wildcard Function.)
5964in that it communicates with the world outside of `make'.
5965
5966 The `shell' function performs the same function that backquotes
5967(``') perform in most shells: it does "command expansion". This means
5968that it takes as an argument a shell command and evaluates to the
5969output of the command. The only processing `make' does on the result
5970is to convert each newline (or carriage-return / newline pair) to a
5971single space. If there is a trailing (carriage-return and) newline it
5972will simply be removed.
5973
5974 The commands run by calls to the `shell' function are run when the
5975function calls are expanded (*note How `make' Reads a Makefile: Reading
5976Makefiles.). Because this function involves spawning a new shell, you
5977should carefully consider the performance implications of using the
5978`shell' function within recursively expanded variables vs. simply
5979expanded variables (*note The Two Flavors of Variables: Flavors.).
5980
5981 Here are some examples of the use of the `shell' function:
5982
5983 contents := $(shell cat foo)
5984
5985sets `contents' to the contents of the file `foo', with a space (rather
5986than a newline) separating each line.
5987
5988 files := $(shell echo *.c)
5989
5990sets `files' to the expansion of `*.c'. Unless `make' is using a very
5991strange shell, this has the same result as `$(wildcard *.c)' (as long
5992as at least one `.c' file exists).
5993
5994
5995File: make.info, Node: Make Control Functions, Prev: Shell Function, Up: Functions
5996
59978.12 Functions That Control Make
5998================================
5999
6000These functions control the way make runs. Generally, they are used to
6001provide information to the user of the makefile or to cause make to stop
6002if some sort of environmental error is detected.
6003
6004`$(error TEXT...)'
6005 Generates a fatal error where the message is TEXT. Note that the
6006 error is generated whenever this function is evaluated. So, if
6007 you put it inside a command script or on the right side of a
6008 recursive variable assignment, it won't be evaluated until later.
6009 The TEXT will be expanded before the error is generated.
6010
6011 For example,
6012
6013 ifdef ERROR1
6014 $(error error is $(ERROR1))
6015 endif
6016
6017 will generate a fatal error during the read of the makefile if the
6018 `make' variable `ERROR1' is defined. Or,
6019
6020 ERR = $(error found an error!)
6021
6022 .PHONY: err
6023 err: ; $(ERR)
6024
6025 will generate a fatal error while `make' is running, if the `err'
6026 target is invoked.
6027
6028`$(warning TEXT...)'
6029 This function works similarly to the `error' function, above,
6030 except that `make' doesn't exit. Instead, TEXT is expanded and
6031 the resulting message is displayed, but processing of the makefile
6032 continues.
6033
6034 The result of the expansion of this function is the empty string.
6035
6036`$(info TEXT...)'
6037 This function does nothing more than print its (expanded)
6038 argument(s) to standard output. No makefile name or line number
6039 is added. The result of the expansion of this function is the
6040 empty string.
6041
6042
6043File: make.info, Node: Running, Next: Implicit Rules, Prev: Functions, Up: Top
6044
60459 How to Run `make'
6046*******************
6047
6048A makefile that says how to recompile a program can be used in more
6049than one way. The simplest use is to recompile every file that is out
6050of date. Usually, makefiles are written so that if you run `make' with
6051no arguments, it does just that.
6052
6053 But you might want to update only some of the files; you might want
6054to use a different compiler or different compiler options; you might
6055want just to find out which files are out of date without changing them.
6056
6057 By giving arguments when you run `make', you can do any of these
6058things and many others.
6059
6060 The exit status of `make' is always one of three values:
6061`0'
6062 The exit status is zero if `make' is successful.
6063
6064`2'
6065 The exit status is two if `make' encounters any errors. It will
6066 print messages describing the particular errors.
6067
6068`1'
6069 The exit status is one if you use the `-q' flag and `make'
6070 determines that some target is not already up to date. *Note
6071 Instead of Executing the Commands: Instead of Execution.
6072
6073* Menu:
6074
6075* Makefile Arguments:: How to specify which makefile to use.
6076* Goals:: How to use goal arguments to specify which
6077 parts of the makefile to use.
6078* Instead of Execution:: How to use mode flags to specify what
6079 kind of thing to do with the commands
6080 in the makefile other than simply
6081 execute them.
6082* Avoiding Compilation:: How to avoid recompiling certain files.
6083* Overriding:: How to override a variable to specify
6084 an alternate compiler and other things.
6085* Testing:: How to proceed past some errors, to
6086 test compilation.
6087* Options Summary:: Summary of Options
6088
6089
6090File: make.info, Node: Makefile Arguments, Next: Goals, Prev: Running, Up: Running
6091
60929.1 Arguments to Specify the Makefile
6093=====================================
6094
6095The way to specify the name of the makefile is with the `-f' or
6096`--file' option (`--makefile' also works). For example, `-f altmake'
6097says to use the file `altmake' as the makefile.
6098
6099 If you use the `-f' flag several times and follow each `-f' with an
6100argument, all the specified files are used jointly as makefiles.
6101
6102 If you do not use the `-f' or `--file' flag, the default is to try
6103`GNUmakefile', `makefile', and `Makefile', in that order, and use the
6104first of these three which exists or can be made (*note Writing
6105Makefiles: Makefiles.).
6106
6107
6108File: make.info, Node: Goals, Next: Instead of Execution, Prev: Makefile Arguments, Up: Running
6109
61109.2 Arguments to Specify the Goals
6111==================================
6112
6113The "goals" are the targets that `make' should strive ultimately to
6114update. Other targets are updated as well if they appear as
6115prerequisites of goals, or prerequisites of prerequisites of goals, etc.
6116
6117 By default, the goal is the first target in the makefile (not
6118counting targets that start with a period). Therefore, makefiles are
6119usually written so that the first target is for compiling the entire
6120program or programs they describe. If the first rule in the makefile
6121has several targets, only the first target in the rule becomes the
6122default goal, not the whole list. You can manage the selection of the
6123default goal from within your makefile using the `.DEFAULT_GOAL'
6124variable (*note Other Special Variables: Special Variables.).
6125
6126 You can also specify a different goal or goals with command-line
6127arguments to `make'. Use the name of the goal as an argument. If you
6128specify several goals, `make' processes each of them in turn, in the
6129order you name them.
6130
6131 Any target in the makefile may be specified as a goal (unless it
6132starts with `-' or contains an `=', in which case it will be parsed as
6133a switch or variable definition, respectively). Even targets not in
6134the makefile may be specified, if `make' can find implicit rules that
6135say how to make them.
6136
6137 `Make' will set the special variable `MAKECMDGOALS' to the list of
6138goals you specified on the command line. If no goals were given on the
6139command line, this variable is empty. Note that this variable should
6140be used only in special circumstances.
6141
6142 An example of appropriate use is to avoid including `.d' files
6143during `clean' rules (*note Automatic Prerequisites::), so `make' won't
6144create them only to immediately remove them again:
6145
6146 sources = foo.c bar.c
6147
6148 ifneq ($(MAKECMDGOALS),clean)
6149 include $(sources:.c=.d)
6150 endif
6151
6152 One use of specifying a goal is if you want to compile only a part of
6153the program, or only one of several programs. Specify as a goal each
6154file that you wish to remake. For example, consider a directory
6155containing several programs, with a makefile that starts like this:
6156
6157 .PHONY: all
6158 all: size nm ld ar as
6159
6160 If you are working on the program `size', you might want to say
6161`make size' so that only the files of that program are recompiled.
6162
6163 Another use of specifying a goal is to make files that are not
6164normally made. For example, there may be a file of debugging output,
6165or a version of the program that is compiled specially for testing,
6166which has a rule in the makefile but is not a prerequisite of the
6167default goal.
6168
6169 Another use of specifying a goal is to run the commands associated
6170with a phony target (*note Phony Targets::) or empty target (*note
6171Empty Target Files to Record Events: Empty Targets.). Many makefiles
6172contain a phony target named `clean' which deletes everything except
6173source files. Naturally, this is done only if you request it
6174explicitly with `make clean'. Following is a list of typical phony and
6175empty target names. *Note Standard Targets::, for a detailed list of
6176all the standard target names which GNU software packages use.
6177
6178`all'
6179 Make all the top-level targets the makefile knows about.
6180
6181`clean'
6182 Delete all files that are normally created by running `make'.
6183
6184`mostlyclean'
6185 Like `clean', but may refrain from deleting a few files that people
6186 normally don't want to recompile. For example, the `mostlyclean'
6187 target for GCC does not delete `libgcc.a', because recompiling it
6188 is rarely necessary and takes a lot of time.
6189
6190`distclean'
6191`realclean'
6192`clobber'
6193 Any of these targets might be defined to delete _more_ files than
6194 `clean' does. For example, this would delete configuration files
6195 or links that you would normally create as preparation for
6196 compilation, even if the makefile itself cannot create these files.
6197
6198`install'
6199 Copy the executable file into a directory that users typically
6200 search for commands; copy any auxiliary files that the executable
6201 uses into the directories where it will look for them.
6202
6203`print'
6204 Print listings of the source files that have changed.
6205
6206`tar'
6207 Create a tar file of the source files.
6208
6209`shar'
6210 Create a shell archive (shar file) of the source files.
6211
6212`dist'
6213 Create a distribution file of the source files. This might be a
6214 tar file, or a shar file, or a compressed version of one of the
6215 above, or even more than one of the above.
6216
6217`TAGS'
6218 Update a tags table for this program.
6219
6220`check'
6221`test'
6222 Perform self tests on the program this makefile builds.
6223
6224
6225File: make.info, Node: Instead of Execution, Next: Avoiding Compilation, Prev: Goals, Up: Running
6226
62279.3 Instead of Executing the Commands
6228=====================================
6229
6230The makefile tells `make' how to tell whether a target is up to date,
6231and how to update each target. But updating the targets is not always
6232what you want. Certain options specify other activities for `make'.
6233
6234`-n'
6235`--just-print'
6236`--dry-run'
6237`--recon'
6238 "No-op". The activity is to print what commands would be used to
6239 make the targets up to date, but not actually execute them.
6240
6241`-t'
6242`--touch'
6243 "Touch". The activity is to mark the targets as up to date without
6244 actually changing them. In other words, `make' pretends to compile
6245 the targets but does not really change their contents.
6246
6247`-q'
6248`--question'
6249 "Question". The activity is to find out silently whether the
6250 targets are up to date already; but execute no commands in either
6251 case. In other words, neither compilation nor output will occur.
6252
6253`-W FILE'
6254`--what-if=FILE'
6255`--assume-new=FILE'
6256`--new-file=FILE'
6257 "What if". Each `-W' flag is followed by a file name. The given
6258 files' modification times are recorded by `make' as being the
6259 present time, although the actual modification times remain the
6260 same. You can use the `-W' flag in conjunction with the `-n' flag
6261 to see what would happen if you were to modify specific files.
6262
6263 With the `-n' flag, `make' prints the commands that it would
6264normally execute but does not execute them.
6265
6266 With the `-t' flag, `make' ignores the commands in the rules and
6267uses (in effect) the command `touch' for each target that needs to be
6268remade. The `touch' command is also printed, unless `-s' or `.SILENT'
6269is used. For speed, `make' does not actually invoke the program
6270`touch'. It does the work directly.
6271
6272 With the `-q' flag, `make' prints nothing and executes no commands,
6273but the exit status code it returns is zero if and only if the targets
6274to be considered are already up to date. If the exit status is one,
6275then some updating needs to be done. If `make' encounters an error,
6276the exit status is two, so you can distinguish an error from a target
6277that is not up to date.
6278
6279 It is an error to use more than one of these three flags in the same
6280invocation of `make'.
6281
6282 The `-n', `-t', and `-q' options do not affect command lines that
6283begin with `+' characters or contain the strings `$(MAKE)' or
6284`${MAKE}'. Note that only the line containing the `+' character or the
6285strings `$(MAKE)' or `${MAKE}' is run regardless of these options.
6286Other lines in the same rule are not run unless they too begin with `+'
6287or contain `$(MAKE)' or `${MAKE}' (*Note How the `MAKE' Variable Works:
6288MAKE Variable.)
6289
6290 The `-W' flag provides two features:
6291
6292 * If you also use the `-n' or `-q' flag, you can see what `make'
6293 would do if you were to modify some files.
6294
6295 * Without the `-n' or `-q' flag, when `make' is actually executing
6296 commands, the `-W' flag can direct `make' to act as if some files
6297 had been modified, without actually modifying the files.
6298
6299 Note that the options `-p' and `-v' allow you to obtain other
6300information about `make' or about the makefiles in use (*note Summary
6301of Options: Options Summary.).
6302
6303
6304File: make.info, Node: Avoiding Compilation, Next: Overriding, Prev: Instead of Execution, Up: Running
6305
63069.4 Avoiding Recompilation of Some Files
6307========================================
6308
6309Sometimes you may have changed a source file but you do not want to
6310recompile all the files that depend on it. For example, suppose you add
6311a macro or a declaration to a header file that many other files depend
6312on. Being conservative, `make' assumes that any change in the header
6313file requires recompilation of all dependent files, but you know that
6314they do not need to be recompiled and you would rather not waste the
6315time waiting for them to compile.
6316
6317 If you anticipate the problem before changing the header file, you
6318can use the `-t' flag. This flag tells `make' not to run the commands
6319in the rules, but rather to mark the target up to date by changing its
6320last-modification date. You would follow this procedure:
6321
6322 1. Use the command `make' to recompile the source files that really
6323 need recompilation, ensuring that the object files are up-to-date
6324 before you begin.
6325
6326 2. Make the changes in the header files.
6327
6328 3. Use the command `make -t' to mark all the object files as up to
6329 date. The next time you run `make', the changes in the header
6330 files will not cause any recompilation.
6331
6332 If you have already changed the header file at a time when some files
6333do need recompilation, it is too late to do this. Instead, you can use
6334the `-o FILE' flag, which marks a specified file as "old" (*note
6335Summary of Options: Options Summary.). This means that the file itself
6336will not be remade, and nothing else will be remade on its account.
6337Follow this procedure:
6338
6339 1. Recompile the source files that need compilation for reasons
6340 independent of the particular header file, with `make -o
6341 HEADERFILE'. If several header files are involved, use a separate
6342 `-o' option for each header file.
6343
6344 2. Touch all the object files with `make -t'.
6345
6346
6347File: make.info, Node: Overriding, Next: Testing, Prev: Avoiding Compilation, Up: Running
6348
63499.5 Overriding Variables
6350========================
6351
6352An argument that contains `=' specifies the value of a variable: `V=X'
6353sets the value of the variable V to X. If you specify a value in this
6354way, all ordinary assignments of the same variable in the makefile are
6355ignored; we say they have been "overridden" by the command line
6356argument.
6357
6358 The most common way to use this facility is to pass extra flags to
6359compilers. For example, in a properly written makefile, the variable
6360`CFLAGS' is included in each command that runs the C compiler, so a
6361file `foo.c' would be compiled something like this:
6362
6363 cc -c $(CFLAGS) foo.c
6364
6365 Thus, whatever value you set for `CFLAGS' affects each compilation
6366that occurs. The makefile probably specifies the usual value for
6367`CFLAGS', like this:
6368
6369 CFLAGS=-g
6370
6371 Each time you run `make', you can override this value if you wish.
6372For example, if you say `make CFLAGS='-g -O'', each C compilation will
6373be done with `cc -c -g -O'. (This also illustrates how you can use
6374quoting in the shell to enclose spaces and other special characters in
6375the value of a variable when you override it.)
6376
6377 The variable `CFLAGS' is only one of many standard variables that
6378exist just so that you can change them this way. *Note Variables Used
6379by Implicit Rules: Implicit Variables, for a complete list.
6380
6381 You can also program the makefile to look at additional variables of
6382your own, giving the user the ability to control other aspects of how
6383the makefile works by changing the variables.
6384
6385 When you override a variable with a command argument, you can define
6386either a recursively-expanded variable or a simply-expanded variable.
6387The examples shown above make a recursively-expanded variable; to make a
6388simply-expanded variable, write `:=' instead of `='. But, unless you
6389want to include a variable reference or function call in the _value_
6390that you specify, it makes no difference which kind of variable you
6391create.
6392
6393 There is one way that the makefile can change a variable that you
6394have overridden. This is to use the `override' directive, which is a
6395line that looks like this: `override VARIABLE = VALUE' (*note The
6396`override' Directive: Override Directive.).
6397
6398
6399File: make.info, Node: Testing, Next: Options Summary, Prev: Overriding, Up: Running
6400
64019.6 Testing the Compilation of a Program
6402========================================
6403
6404Normally, when an error happens in executing a shell command, `make'
6405gives up immediately, returning a nonzero status. No further commands
6406are executed for any target. The error implies that the goal cannot be
6407correctly remade, and `make' reports this as soon as it knows.
6408
6409 When you are compiling a program that you have just changed, this is
6410not what you want. Instead, you would rather that `make' try compiling
6411every file that can be tried, to show you as many compilation errors as
6412possible.
6413
6414 On these occasions, you should use the `-k' or `--keep-going' flag.
6415This tells `make' to continue to consider the other prerequisites of
6416the pending targets, remaking them if necessary, before it gives up and
6417returns nonzero status. For example, after an error in compiling one
6418object file, `make -k' will continue compiling other object files even
6419though it already knows that linking them will be impossible. In
6420addition to continuing after failed shell commands, `make -k' will
6421continue as much as possible after discovering that it does not know
6422how to make a target or prerequisite file. This will always cause an
6423error message, but without `-k', it is a fatal error (*note Summary of
6424Options: Options Summary.).
6425
6426 The usual behavior of `make' assumes that your purpose is to get the
6427goals up to date; once `make' learns that this is impossible, it might
6428as well report the failure immediately. The `-k' flag says that the
6429real purpose is to test as much as possible of the changes made in the
6430program, perhaps to find several independent problems so that you can
6431correct them all before the next attempt to compile. This is why Emacs'
6432`M-x compile' command passes the `-k' flag by default.
6433
6434
6435File: make.info, Node: Options Summary, Prev: Testing, Up: Running
6436
64379.7 Summary of Options
6438======================
6439
6440Here is a table of all the options `make' understands:
6441
6442`-b'
6443`-m'
6444 These options are ignored for compatibility with other versions of
6445 `make'.
6446
6447`-B'
6448`--always-make'
6449 Consider all targets out-of-date. GNU `make' proceeds to consider
6450 targets and their prerequisites using the normal algorithms;
6451 however, all targets so considered are always remade regardless of
6452 the status of their prerequisites. To avoid infinite recursion, if
6453 `MAKE_RESTARTS' (*note Other Special Variables: Special
6454 Variables.) is set to a number greater than 0 this option is
6455 disabled when considering whether to remake makefiles (*note How
6456 Makefiles Are Remade: Remaking Makefiles.).
6457
6458`-C DIR'
6459`--directory=DIR'
6460 Change to directory DIR before reading the makefiles. If multiple
6461 `-C' options are specified, each is interpreted relative to the
6462 previous one: `-C / -C etc' is equivalent to `-C /etc'. This is
6463 typically used with recursive invocations of `make' (*note
6464 Recursive Use of `make': Recursion.).
6465
6466`-d'
6467 Print debugging information in addition to normal processing. The
6468 debugging information says which files are being considered for
6469 remaking, which file-times are being compared and with what
6470 results, which files actually need to be remade, which implicit
6471 rules are considered and which are applied--everything interesting
6472 about how `make' decides what to do. The `-d' option is
6473 equivalent to `--debug=a' (see below).
6474
6475`--debug[=OPTIONS]'
6476 Print debugging information in addition to normal processing.
6477 Various levels and types of output can be chosen. With no
6478 arguments, print the "basic" level of debugging. Possible
6479 arguments are below; only the first character is considered, and
6480 values must be comma- or space-separated.
6481
6482 `a (all)'
6483 All types of debugging output are enabled. This is
6484 equivalent to using `-d'.
6485
6486 `b (basic)'
6487 Basic debugging prints each target that was found to be
6488 out-of-date, and whether the build was successful or not.
6489
6490 `v (verbose)'
6491 A level above `basic'; includes messages about which
6492 makefiles were parsed, prerequisites that did not need to be
6493 rebuilt, etc. This option also enables `basic' messages.
6494
6495 `i (implicit)'
6496 Prints messages describing the implicit rule searches for
6497 each target. This option also enables `basic' messages.
6498
6499 `j (jobs)'
6500 Prints messages giving details on the invocation of specific
6501 subcommands.
6502
6503 `m (makefile)'
6504 By default, the above messages are not enabled while trying
6505 to remake the makefiles. This option enables messages while
6506 rebuilding makefiles, too. Note that the `all' option does
6507 enable this option. This option also enables `basic'
6508 messages.
6509
6510`-e'
6511`--environment-overrides'
6512 Give variables taken from the environment precedence over
6513 variables from makefiles. *Note Variables from the Environment:
6514 Environment.
6515
6516`-f FILE'
6517`--file=FILE'
6518`--makefile=FILE'
6519 Read the file named FILE as a makefile. *Note Writing Makefiles:
6520 Makefiles.
6521
6522`-h'
6523`--help'
6524 Remind you of the options that `make' understands and then exit.
6525
6526`-i'
6527`--ignore-errors'
6528 Ignore all errors in commands executed to remake files. *Note
6529 Errors in Commands: Errors.
6530
6531`-I DIR'
6532`--include-dir=DIR'
6533 Specifies a directory DIR to search for included makefiles. *Note
6534 Including Other Makefiles: Include. If several `-I' options are
6535 used to specify several directories, the directories are searched
6536 in the order specified.
6537
6538`-j [JOBS]'
6539`--jobs[=JOBS]'
6540 Specifies the number of jobs (commands) to run simultaneously.
6541 With no argument, `make' runs as many jobs simultaneously as
6542 possible. If there is more than one `-j' option, the last one is
6543 effective. *Note Parallel Execution: Parallel, for more
6544 information on how commands are run. Note that this option is
6545 ignored on MS-DOS.
6546
6547`-k'
6548`--keep-going'
6549 Continue as much as possible after an error. While the target that
6550 failed, and those that depend on it, cannot be remade, the other
6551 prerequisites of these targets can be processed all the same.
6552 *Note Testing the Compilation of a Program: Testing.
6553
6554`-l [LOAD]'
6555`--load-average[=LOAD]'
6556`--max-load[=LOAD]'
6557 Specifies that no new jobs (commands) should be started if there
6558 are other jobs running and the load average is at least LOAD (a
6559 floating-point number). With no argument, removes a previous load
6560 limit. *Note Parallel Execution: Parallel.
6561
6562`-L'
6563`--check-symlink-times'
6564 On systems that support symbolic links, this option causes `make'
6565 to consider the timestamps on any symbolic links in addition to the
6566 timestamp on the file referenced by those links. When this option
6567 is provided, the most recent timestamp among the file and the
6568 symbolic links is taken as the modification time for this target
6569 file.
6570
6571`-n'
6572`--just-print'
6573`--dry-run'
6574`--recon'
6575 Print the commands that would be executed, but do not execute them.
6576 *Note Instead of Executing the Commands: Instead of Execution.
6577
6578`-o FILE'
6579`--old-file=FILE'
6580`--assume-old=FILE'
6581 Do not remake the file FILE even if it is older than its
6582 prerequisites, and do not remake anything on account of changes in
6583 FILE. Essentially the file is treated as very old and its rules
6584 are ignored. *Note Avoiding Recompilation of Some Files: Avoiding
6585 Compilation.
6586
6587`-p'
6588`--print-data-base'
6589 Print the data base (rules and variable values) that results from
6590 reading the makefiles; then execute as usual or as otherwise
6591 specified. This also prints the version information given by the
6592 `-v' switch (see below). To print the data base without trying to
6593 remake any files, use `make -qp'. To print the data base of
6594 predefined rules and variables, use `make -p -f /dev/null'. The
6595 data base output contains filename and linenumber information for
6596 command and variable definitions, so it can be a useful debugging
6597 tool in complex environments.
6598
6599`-q'
6600`--question'
6601 "Question mode". Do not run any commands, or print anything; just
6602 return an exit status that is zero if the specified targets are
6603 already up to date, one if any remaking is required, or two if an
6604 error is encountered. *Note Instead of Executing the Commands:
6605 Instead of Execution.
6606
6607`-r'
6608`--no-builtin-rules'
6609 Eliminate use of the built-in implicit rules (*note Using Implicit
6610 Rules: Implicit Rules.). You can still define your own by writing
6611 pattern rules (*note Defining and Redefining Pattern Rules:
6612 Pattern Rules.). The `-r' option also clears out the default list
6613 of suffixes for suffix rules (*note Old-Fashioned Suffix Rules:
6614 Suffix Rules.). But you can still define your own suffixes with a
6615 rule for `.SUFFIXES', and then define your own suffix rules. Note
6616 that only _rules_ are affected by the `-r' option; default
6617 variables remain in effect (*note Variables Used by Implicit
6618 Rules: Implicit Variables.); see the `-R' option below.
6619
6620`-R'
6621`--no-builtin-variables'
6622 Eliminate use of the built-in rule-specific variables (*note
6623 Variables Used by Implicit Rules: Implicit Variables.). You can
6624 still define your own, of course. The `-R' option also
6625 automatically enables the `-r' option (see above), since it
6626 doesn't make sense to have implicit rules without any definitions
6627 for the variables that they use.
6628
6629`-s'
6630`--silent'
6631`--quiet'
6632 Silent operation; do not print the commands as they are executed.
6633 *Note Command Echoing: Echoing.
6634
6635`-S'
6636`--no-keep-going'
6637`--stop'
6638 Cancel the effect of the `-k' option. This is never necessary
6639 except in a recursive `make' where `-k' might be inherited from
6640 the top-level `make' via `MAKEFLAGS' (*note Recursive Use of
6641 `make': Recursion.) or if you set `-k' in `MAKEFLAGS' in your
6642 environment.
6643
6644`-t'
6645`--touch'
6646 Touch files (mark them up to date without really changing them)
6647 instead of running their commands. This is used to pretend that
6648 the commands were done, in order to fool future invocations of
6649 `make'. *Note Instead of Executing the Commands: Instead of
6650 Execution.
6651
6652`-v'
6653`--version'
6654 Print the version of the `make' program plus a copyright, a list
6655 of authors, and a notice that there is no warranty; then exit.
6656
6657`-w'
6658`--print-directory'
6659 Print a message containing the working directory both before and
6660 after executing the makefile. This may be useful for tracking
6661 down errors from complicated nests of recursive `make' commands.
6662 *Note Recursive Use of `make': Recursion. (In practice, you
6663 rarely need to specify this option since `make' does it for you;
6664 see *Note The `--print-directory' Option: -w Option.)
6665
6666`--no-print-directory'
6667 Disable printing of the working directory under `-w'. This option
6668 is useful when `-w' is turned on automatically, but you do not
6669 want to see the extra messages. *Note The `--print-directory'
6670 Option: -w Option.
6671
6672`-W FILE'
6673`--what-if=FILE'
6674`--new-file=FILE'
6675`--assume-new=FILE'
6676 Pretend that the target FILE has just been modified. When used
6677 with the `-n' flag, this shows you what would happen if you were
6678 to modify that file. Without `-n', it is almost the same as
6679 running a `touch' command on the given file before running `make',
6680 except that the modification time is changed only in the
6681 imagination of `make'. *Note Instead of Executing the Commands:
6682 Instead of Execution.
6683
6684`--warn-undefined-variables'
6685 Issue a warning message whenever `make' sees a reference to an
6686 undefined variable. This can be helpful when you are trying to
6687 debug makefiles which use variables in complex ways.
6688
6689
6690File: make.info, Node: Implicit Rules, Next: Archives, Prev: Running, Up: Top
6691
669210 Using Implicit Rules
6693***********************
6694
6695Certain standard ways of remaking target files are used very often. For
6696example, one customary way to make an object file is from a C source
6697file using the C compiler, `cc'.
6698
6699 "Implicit rules" tell `make' how to use customary techniques so that
6700you do not have to specify them in detail when you want to use them.
6701For example, there is an implicit rule for C compilation. File names
6702determine which implicit rules are run. For example, C compilation
6703typically takes a `.c' file and makes a `.o' file. So `make' applies
6704the implicit rule for C compilation when it sees this combination of
6705file name endings.
6706
6707 A chain of implicit rules can apply in sequence; for example, `make'
6708will remake a `.o' file from a `.y' file by way of a `.c' file.
6709
6710 The built-in implicit rules use several variables in their commands
6711so that, by changing the values of the variables, you can change the
6712way the implicit rule works. For example, the variable `CFLAGS'
6713controls the flags given to the C compiler by the implicit rule for C
6714compilation.
6715
6716 You can define your own implicit rules by writing "pattern rules".
6717
6718 "Suffix rules" are a more limited way to define implicit rules.
6719Pattern rules are more general and clearer, but suffix rules are
6720retained for compatibility.
6721
6722* Menu:
6723
6724* Using Implicit:: How to use an existing implicit rule
6725 to get the commands for updating a file.
6726* Catalogue of Rules:: A list of built-in implicit rules.
6727* Implicit Variables:: How to change what predefined rules do.
6728* Chained Rules:: How to use a chain of implicit rules.
6729* Pattern Rules:: How to define new implicit rules.
6730* Last Resort:: How to define commands for rules which
6731 cannot find any.
6732* Suffix Rules:: The old-fashioned style of implicit rule.
6733* Implicit Rule Search:: The precise algorithm for applying
6734 implicit rules.
6735
6736
6737File: make.info, Node: Using Implicit, Next: Catalogue of Rules, Prev: Implicit Rules, Up: Implicit Rules
6738
673910.1 Using Implicit Rules
6740=========================
6741
6742To allow `make' to find a customary method for updating a target file,
6743all you have to do is refrain from specifying commands yourself. Either
6744write a rule with no command lines, or don't write a rule at all. Then
6745`make' will figure out which implicit rule to use based on which kind
6746of source file exists or can be made.
6747
6748 For example, suppose the makefile looks like this:
6749
6750 foo : foo.o bar.o
6751 cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
6752
6753Because you mention `foo.o' but do not give a rule for it, `make' will
6754automatically look for an implicit rule that tells how to update it.
6755This happens whether or not the file `foo.o' currently exists.
6756
6757 If an implicit rule is found, it can supply both commands and one or
6758more prerequisites (the source files). You would want to write a rule
6759for `foo.o' with no command lines if you need to specify additional
6760prerequisites, such as header files, that the implicit rule cannot
6761supply.
6762
6763 Each implicit rule has a target pattern and prerequisite patterns.
6764There may be many implicit rules with the same target pattern. For
6765example, numerous rules make `.o' files: one, from a `.c' file with the
6766C compiler; another, from a `.p' file with the Pascal compiler; and so
6767on. The rule that actually applies is the one whose prerequisites
6768exist or can be made. So, if you have a file `foo.c', `make' will run
6769the C compiler; otherwise, if you have a file `foo.p', `make' will run
6770the Pascal compiler; and so on.
6771
6772 Of course, when you write the makefile, you know which implicit rule
6773you want `make' to use, and you know it will choose that one because you
6774know which possible prerequisite files are supposed to exist. *Note
6775Catalogue of Implicit Rules: Catalogue of Rules, for a catalogue of all
6776the predefined implicit rules.
6777
6778 Above, we said an implicit rule applies if the required
6779prerequisites "exist or can be made". A file "can be made" if it is
6780mentioned explicitly in the makefile as a target or a prerequisite, or
6781if an implicit rule can be recursively found for how to make it. When
6782an implicit prerequisite is the result of another implicit rule, we say
6783that "chaining" is occurring. *Note Chains of Implicit Rules: Chained
6784Rules.
6785
6786 In general, `make' searches for an implicit rule for each target, and
6787for each double-colon rule, that has no commands. A file that is
6788mentioned only as a prerequisite is considered a target whose rule
6789specifies nothing, so implicit rule search happens for it. *Note
6790Implicit Rule Search Algorithm: Implicit Rule Search, for the details
6791of how the search is done.
6792
6793 Note that explicit prerequisites do not influence implicit rule
6794search. For example, consider this explicit rule:
6795
6796 foo.o: foo.p
6797
6798The prerequisite on `foo.p' does not necessarily mean that `make' will
6799remake `foo.o' according to the implicit rule to make an object file, a
6800`.o' file, from a Pascal source file, a `.p' file. For example, if
6801`foo.c' also exists, the implicit rule to make an object file from a C
6802source file is used instead, because it appears before the Pascal rule
6803in the list of predefined implicit rules (*note Catalogue of Implicit
6804Rules: Catalogue of Rules.).
6805
6806 If you do not want an implicit rule to be used for a target that has
6807no commands, you can give that target empty commands by writing a
6808semicolon (*note Defining Empty Commands: Empty Commands.).
6809
6810
6811File: make.info, Node: Catalogue of Rules, Next: Implicit Variables, Prev: Using Implicit, Up: Implicit Rules
6812
681310.2 Catalogue of Implicit Rules
6814================================
6815
6816Here is a catalogue of predefined implicit rules which are always
6817available unless the makefile explicitly overrides or cancels them.
6818*Note Canceling Implicit Rules: Canceling Rules, for information on
6819canceling or overriding an implicit rule. The `-r' or
6820`--no-builtin-rules' option cancels all predefined rules.
6821
6822 This manual only documents the default rules available on POSIX-based
6823operating systems. Other operating systems, such as VMS, Windows,
6824OS/2, etc. may have different sets of default rules. To see the full
6825list of default rules and variables available in your version of GNU
6826`make', run `make -p' in a directory with no makefile.
6827
6828 Not all of these rules will always be defined, even when the `-r'
6829option is not given. Many of the predefined implicit rules are
6830implemented in `make' as suffix rules, so which ones will be defined
6831depends on the "suffix list" (the list of prerequisites of the special
6832target `.SUFFIXES'). The default suffix list is: `.out', `.a', `.ln',
6833`.o', `.c', `.cc', `.C', `.cpp', `.p', `.f', `.F', `.r', `.y', `.l',
6834`.s', `.S', `.mod', `.sym', `.def', `.h', `.info', `.dvi', `.tex',
6835`.texinfo', `.texi', `.txinfo', `.w', `.ch' `.web', `.sh', `.elc',
6836`.el'. All of the implicit rules described below whose prerequisites
6837have one of these suffixes are actually suffix rules. If you modify
6838the suffix list, the only predefined suffix rules in effect will be
6839those named by one or two of the suffixes that are on the list you
6840specify; rules whose suffixes fail to be on the list are disabled.
6841*Note Old-Fashioned Suffix Rules: Suffix Rules, for full details on
6842suffix rules.
6843
6844Compiling C programs
6845 `N.o' is made automatically from `N.c' with a command of the form
6846 `$(CC) -c $(CPPFLAGS) $(CFLAGS)'.
6847
6848Compiling C++ programs
6849 `N.o' is made automatically from `N.cc', `N.cpp', or `N.C' with a
6850 command of the form `$(CXX) -c $(CPPFLAGS) $(CXXFLAGS)'. We
6851 encourage you to use the suffix `.cc' for C++ source files instead
6852 of `.C'.
6853
6854Compiling Pascal programs
6855 `N.o' is made automatically from `N.p' with the command `$(PC) -c
6856 $(PFLAGS)'.
6857
6858Compiling Fortran and Ratfor programs
6859 `N.o' is made automatically from `N.r', `N.F' or `N.f' by running
6860 the Fortran compiler. The precise command used is as follows:
6861
6862 `.f'
6863 `$(FC) -c $(FFLAGS)'.
6864
6865 `.F'
6866 `$(FC) -c $(FFLAGS) $(CPPFLAGS)'.
6867
6868 `.r'
6869 `$(FC) -c $(FFLAGS) $(RFLAGS)'.
6870
6871Preprocessing Fortran and Ratfor programs
6872 `N.f' is made automatically from `N.r' or `N.F'. This rule runs
6873 just the preprocessor to convert a Ratfor or preprocessable
6874 Fortran program into a strict Fortran program. The precise
6875 command used is as follows:
6876
6877 `.F'
6878 `$(FC) -F $(CPPFLAGS) $(FFLAGS)'.
6879
6880 `.r'
6881 `$(FC) -F $(FFLAGS) $(RFLAGS)'.
6882
6883Compiling Modula-2 programs
6884 `N.sym' is made from `N.def' with a command of the form `$(M2C)
6885 $(M2FLAGS) $(DEFFLAGS)'. `N.o' is made from `N.mod'; the form is:
6886 `$(M2C) $(M2FLAGS) $(MODFLAGS)'.
6887
6888Assembling and preprocessing assembler programs
6889 `N.o' is made automatically from `N.s' by running the assembler,
6890 `as'. The precise command is `$(AS) $(ASFLAGS)'.
6891
6892 `N.s' is made automatically from `N.S' by running the C
6893 preprocessor, `cpp'. The precise command is `$(CPP) $(CPPFLAGS)'.
6894
6895Linking a single object file
6896 `N' is made automatically from `N.o' by running the linker
6897 (usually called `ld') via the C compiler. The precise command
6898 used is `$(CC) $(LDFLAGS) N.o $(LOADLIBES) $(LDLIBS)'.
6899
6900 This rule does the right thing for a simple program with only one
6901 source file. It will also do the right thing if there are multiple
6902 object files (presumably coming from various other source files),
6903 one of which has a name matching that of the executable file.
6904 Thus,
6905
6906 x: y.o z.o
6907
6908 when `x.c', `y.c' and `z.c' all exist will execute:
6909
6910 cc -c x.c -o x.o
6911 cc -c y.c -o y.o
6912 cc -c z.c -o z.o
6913 cc x.o y.o z.o -o x
6914 rm -f x.o
6915 rm -f y.o
6916 rm -f z.o
6917
6918 In more complicated cases, such as when there is no object file
6919 whose name derives from the executable file name, you must write
6920 an explicit command for linking.
6921
6922 Each kind of file automatically made into `.o' object files will
6923 be automatically linked by using the compiler (`$(CC)', `$(FC)' or
6924 `$(PC)'; the C compiler `$(CC)' is used to assemble `.s' files)
6925 without the `-c' option. This could be done by using the `.o'
6926 object files as intermediates, but it is faster to do the
6927 compiling and linking in one step, so that's how it's done.
6928
6929Yacc for C programs
6930 `N.c' is made automatically from `N.y' by running Yacc with the
6931 command `$(YACC) $(YFLAGS)'.
6932
6933Lex for C programs
6934 `N.c' is made automatically from `N.l' by running Lex. The actual
6935 command is `$(LEX) $(LFLAGS)'.
6936
6937Lex for Ratfor programs
6938 `N.r' is made automatically from `N.l' by running Lex. The actual
6939 command is `$(LEX) $(LFLAGS)'.
6940
6941 The convention of using the same suffix `.l' for all Lex files
6942 regardless of whether they produce C code or Ratfor code makes it
6943 impossible for `make' to determine automatically which of the two
6944 languages you are using in any particular case. If `make' is
6945 called upon to remake an object file from a `.l' file, it must
6946 guess which compiler to use. It will guess the C compiler, because
6947 that is more common. If you are using Ratfor, make sure `make'
6948 knows this by mentioning `N.r' in the makefile. Or, if you are
6949 using Ratfor exclusively, with no C files, remove `.c' from the
6950 list of implicit rule suffixes with:
6951
6952 .SUFFIXES:
6953 .SUFFIXES: .o .r .f .l ...
6954
6955Making Lint Libraries from C, Yacc, or Lex programs
6956 `N.ln' is made from `N.c' by running `lint'. The precise command
6957 is `$(LINT) $(LINTFLAGS) $(CPPFLAGS) -i'. The same command is
6958 used on the C code produced from `N.y' or `N.l'.
6959
6960TeX and Web
6961 `N.dvi' is made from `N.tex' with the command `$(TEX)'. `N.tex'
6962 is made from `N.web' with `$(WEAVE)', or from `N.w' (and from
6963 `N.ch' if it exists or can be made) with `$(CWEAVE)'. `N.p' is
6964 made from `N.web' with `$(TANGLE)' and `N.c' is made from `N.w'
6965 (and from `N.ch' if it exists or can be made) with `$(CTANGLE)'.
6966
6967Texinfo and Info
6968 `N.dvi' is made from `N.texinfo', `N.texi', or `N.txinfo', with
6969 the command `$(TEXI2DVI) $(TEXI2DVI_FLAGS)'. `N.info' is made from
6970 `N.texinfo', `N.texi', or `N.txinfo', with the command
6971 `$(MAKEINFO) $(MAKEINFO_FLAGS)'.
6972
6973RCS
6974 Any file `N' is extracted if necessary from an RCS file named
6975 either `N,v' or `RCS/N,v'. The precise command used is
6976 `$(CO) $(COFLAGS)'. `N' will not be extracted from RCS if it
6977 already exists, even if the RCS file is newer. The rules for RCS
6978 are terminal (*note Match-Anything Pattern Rules: Match-Anything
6979 Rules.), so RCS files cannot be generated from another source;
6980 they must actually exist.
6981
6982SCCS
6983 Any file `N' is extracted if necessary from an SCCS file named
6984 either `s.N' or `SCCS/s.N'. The precise command used is
6985 `$(GET) $(GFLAGS)'. The rules for SCCS are terminal (*note
6986 Match-Anything Pattern Rules: Match-Anything Rules.), so SCCS
6987 files cannot be generated from another source; they must actually
6988 exist.
6989
6990 For the benefit of SCCS, a file `N' is copied from `N.sh' and made
6991 executable (by everyone). This is for shell scripts that are
6992 checked into SCCS. Since RCS preserves the execution permission
6993 of a file, you do not need to use this feature with RCS.
6994
6995 We recommend that you avoid using of SCCS. RCS is widely held to
6996 be superior, and is also free. By choosing free software in place
6997 of comparable (or inferior) proprietary software, you support the
6998 free software movement.
6999
7000 Usually, you want to change only the variables listed in the table
7001above, which are documented in the following section.
7002
7003 However, the commands in built-in implicit rules actually use
7004variables such as `COMPILE.c', `LINK.p', and `PREPROCESS.S', whose
7005values contain the commands listed above.
7006
7007 `make' follows the convention that the rule to compile a `.X' source
7008file uses the variable `COMPILE.X'. Similarly, the rule to produce an
7009executable from a `.X' file uses `LINK.X'; and the rule to preprocess a
7010`.X' file uses `PREPROCESS.X'.
7011
7012 Every rule that produces an object file uses the variable
7013`OUTPUT_OPTION'. `make' defines this variable either to contain `-o
7014$@', or to be empty, depending on a compile-time option. You need the
7015`-o' option to ensure that the output goes into the right file when the
7016source file is in a different directory, as when using `VPATH' (*note
7017Directory Search::). However, compilers on some systems do not accept
7018a `-o' switch for object files. If you use such a system, and use
7019`VPATH', some compilations will put their output in the wrong place. A
7020possible workaround for this problem is to give `OUTPUT_OPTION' the
7021value `; mv $*.o $@'.
7022
7023
7024File: make.info, Node: Implicit Variables, Next: Chained Rules, Prev: Catalogue of Rules, Up: Implicit Rules
7025
702610.3 Variables Used by Implicit Rules
7027=====================================
7028
7029The commands in built-in implicit rules make liberal use of certain
7030predefined variables. You can alter the values of these variables in
7031the makefile, with arguments to `make', or in the environment to alter
7032how the implicit rules work without redefining the rules themselves.
7033You can cancel all variables used by implicit rules with the `-R' or
7034`--no-builtin-variables' option.
7035
7036 For example, the command used to compile a C source file actually
7037says `$(CC) -c $(CFLAGS) $(CPPFLAGS)'. The default values of the
7038variables used are `cc' and nothing, resulting in the command `cc -c'.
7039By redefining `CC' to `ncc', you could cause `ncc' to be used for all C
7040compilations performed by the implicit rule. By redefining `CFLAGS' to
7041be `-g', you could pass the `-g' option to each compilation. _All_
7042implicit rules that do C compilation use `$(CC)' to get the program
7043name for the compiler and _all_ include `$(CFLAGS)' among the arguments
7044given to the compiler.
7045
7046 The variables used in implicit rules fall into two classes: those
7047that are names of programs (like `CC') and those that contain arguments
7048for the programs (like `CFLAGS'). (The "name of a program" may also
7049contain some command arguments, but it must start with an actual
7050executable program name.) If a variable value contains more than one
7051argument, separate them with spaces.
7052
7053 The following tables describe of some of the more commonly-used
7054predefined variables. This list is not exhaustive, and the default
7055values shown here may not be what are selected by `make' for your
7056environment. To see the complete list of predefined variables for your
7057instance of GNU `make' you can run `make -p' in a directory with no
7058makefiles.
7059
7060 Here is a table of some of the more common variables used as names of
7061programs in built-in rules: makefiles.
7062
7063`AR'
7064 Archive-maintaining program; default `ar'.
7065
7066`AS'
7067 Program for compiling assembly files; default `as'.
7068
7069`CC'
7070 Program for compiling C programs; default `cc'.
7071
7072`CO'
7073 Program for checking out files from RCS; default `co'.
7074
7075`CXX'
7076 Program for compiling C++ programs; default `g++'.
7077
7078`CO'
7079 Program for extracting a file from RCS; default `co'.
7080
7081`CPP'
7082 Program for running the C preprocessor, with results to standard
7083 output; default `$(CC) -E'.
7084
7085`FC'
7086 Program for compiling or preprocessing Fortran and Ratfor programs;
7087 default `f77'.
7088
7089`GET'
7090 Program for extracting a file from SCCS; default `get'.
7091
7092`LEX'
7093 Program to use to turn Lex grammars into source code; default
7094 `lex'.
7095
7096`YACC'
7097 Program to use to turn Yacc grammars into source code; default
7098 `yacc'.
7099
7100`LINT'
7101 Program to use to run lint on source code; default `lint'.
7102
7103`M2C'
7104 Program to use to compile Modula-2 source code; default `m2c'.
7105
7106`PC'
7107 Program for compiling Pascal programs; default `pc'.
7108
7109`MAKEINFO'
7110 Program to convert a Texinfo source file into an Info file; default
7111 `makeinfo'.
7112
7113`TEX'
7114 Program to make TeX DVI files from TeX source; default `tex'.
7115
7116`TEXI2DVI'
7117 Program to make TeX DVI files from Texinfo source; default
7118 `texi2dvi'.
7119
7120`WEAVE'
7121 Program to translate Web into TeX; default `weave'.
7122
7123`CWEAVE'
7124 Program to translate C Web into TeX; default `cweave'.
7125
7126`TANGLE'
7127 Program to translate Web into Pascal; default `tangle'.
7128
7129`CTANGLE'
7130 Program to translate C Web into C; default `ctangle'.
7131
7132`RM'
7133 Command to remove a file; default `rm -f'.
7134
7135 Here is a table of variables whose values are additional arguments
7136for the programs above. The default values for all of these is the
7137empty string, unless otherwise noted.
7138
7139`ARFLAGS'
7140 Flags to give the archive-maintaining program; default `rv'.
7141
7142`ASFLAGS'
7143 Extra flags to give to the assembler (when explicitly invoked on a
7144 `.s' or `.S' file).
7145
7146`CFLAGS'
7147 Extra flags to give to the C compiler.
7148
7149`CXXFLAGS'
7150 Extra flags to give to the C++ compiler.
7151
7152`COFLAGS'
7153 Extra flags to give to the RCS `co' program.
7154
7155`CPPFLAGS'
7156 Extra flags to give to the C preprocessor and programs that use it
7157 (the C and Fortran compilers).
7158
7159`FFLAGS'
7160 Extra flags to give to the Fortran compiler.
7161
7162`GFLAGS'
7163 Extra flags to give to the SCCS `get' program.
7164
7165`LDFLAGS'
7166 Extra flags to give to compilers when they are supposed to invoke
7167 the linker, `ld'.
7168
7169`LFLAGS'
7170 Extra flags to give to Lex.
7171
7172`YFLAGS'
7173 Extra flags to give to Yacc.
7174
7175`PFLAGS'
7176 Extra flags to give to the Pascal compiler.
7177
7178`RFLAGS'
7179 Extra flags to give to the Fortran compiler for Ratfor programs.
7180
7181`LINTFLAGS'
7182 Extra flags to give to lint.
7183
7184
7185File: make.info, Node: Chained Rules, Next: Pattern Rules, Prev: Implicit Variables, Up: Implicit Rules
7186
718710.4 Chains of Implicit Rules
7188=============================
7189
7190Sometimes a file can be made by a sequence of implicit rules. For
7191example, a file `N.o' could be made from `N.y' by running first Yacc
7192and then `cc'. Such a sequence is called a "chain".
7193
7194 If the file `N.c' exists, or is mentioned in the makefile, no
7195special searching is required: `make' finds that the object file can be
7196made by C compilation from `N.c'; later on, when considering how to
7197make `N.c', the rule for running Yacc is used. Ultimately both `N.c'
7198and `N.o' are updated.
7199
7200 However, even if `N.c' does not exist and is not mentioned, `make'
7201knows how to envision it as the missing link between `N.o' and `N.y'!
7202In this case, `N.c' is called an "intermediate file". Once `make' has
7203decided to use the intermediate file, it is entered in the data base as
7204if it had been mentioned in the makefile, along with the implicit rule
7205that says how to create it.
7206
7207 Intermediate files are remade using their rules just like all other
7208files. But intermediate files are treated differently in two ways.
7209
7210 The first difference is what happens if the intermediate file does
7211not exist. If an ordinary file B does not exist, and `make' considers
7212a target that depends on B, it invariably creates B and then updates
7213the target from B. But if B is an intermediate file, then `make' can
7214leave well enough alone. It won't bother updating B, or the ultimate
7215target, unless some prerequisite of B is newer than that target or
7216there is some other reason to update that target.
7217
7218 The second difference is that if `make' _does_ create B in order to
7219update something else, it deletes B later on after it is no longer
7220needed. Therefore, an intermediate file which did not exist before
7221`make' also does not exist after `make'. `make' reports the deletion
7222to you by printing a `rm -f' command showing which file it is deleting.
7223
7224 Ordinarily, a file cannot be intermediate if it is mentioned in the
7225makefile as a target or prerequisite. However, you can explicitly mark
7226a file as intermediate by listing it as a prerequisite of the special
7227target `.INTERMEDIATE'. This takes effect even if the file is mentioned
7228explicitly in some other way.
7229
7230 You can prevent automatic deletion of an intermediate file by
7231marking it as a "secondary" file. To do this, list it as a
7232prerequisite of the special target `.SECONDARY'. When a file is
7233secondary, `make' will not create the file merely because it does not
7234already exist, but `make' does not automatically delete the file.
7235Marking a file as secondary also marks it as intermediate.
7236
7237 You can list the target pattern of an implicit rule (such as `%.o')
7238as a prerequisite of the special target `.PRECIOUS' to preserve
7239intermediate files made by implicit rules whose target patterns match
7240that file's name; see *Note Interrupts::.
7241
7242 A chain can involve more than two implicit rules. For example, it is
7243possible to make a file `foo' from `RCS/foo.y,v' by running RCS, Yacc
7244and `cc'. Then both `foo.y' and `foo.c' are intermediate files that
7245are deleted at the end.
7246
7247 No single implicit rule can appear more than once in a chain. This
7248means that `make' will not even consider such a ridiculous thing as
7249making `foo' from `foo.o.o' by running the linker twice. This
7250constraint has the added benefit of preventing any infinite loop in the
7251search for an implicit rule chain.
7252
7253 There are some special implicit rules to optimize certain cases that
7254would otherwise be handled by rule chains. For example, making `foo'
7255from `foo.c' could be handled by compiling and linking with separate
7256chained rules, using `foo.o' as an intermediate file. But what
7257actually happens is that a special rule for this case does the
7258compilation and linking with a single `cc' command. The optimized rule
7259is used in preference to the step-by-step chain because it comes
7260earlier in the ordering of rules.
7261
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette