VirtualBox

source: kBuild/branches/GNU/src/gmake/doc/make.info-1@ 152

Last change on this file since 152 was 152, checked in by (none), 20 years ago

This commit was manufactured by cvs2svn to create branch 'GNU'.

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