VirtualBox

source: kBuild/tags/TAG_INNOTEK_2005-12-16/src/gmake/doc/make.info-1@ 366

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

This commit was manufactured by cvs2svn to create tag
'TAG_INNOTEK_2005-12-16'.

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