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