[Top] [Contents] [Index] [ ? ]

GNU make

The GNU make utility automatically determines which pieces of a large program need to be recompiled, and issues the commands to recompile them.

This is Edition 0.51 of the GNU Make Manual, last updated 26 Aug 1997 for make Version 3.76 Beta.

This manual describes make and contains the following chapters:

1. Overview of make  
2. An Introduction to Makefiles  An introduction to make.
3. Writing Makefiles  Makefiles tell make what to do.
4. Writing Rules  Rules describe when a file must be remade.
5. Writing the Commands in Rules  Commands say how to remake a file.
6. How to Use Variables  You can use variables to avoid repetition.
7. Conditional Parts of Makefiles  Use or ignore parts of the makefile based on the values of variables.
8. Functions for Transforming Text  Many powerful ways to manipulate text.
9. How to Run make  How to invoke make on the command line.
10. Using Implicit Rules  Use implicit rules to treat many files alike, based on their file names.
11. Using make to Update Archive Files  How make can update library archives.
12. Features of GNU make  Features GNU make has over other makes.
13. Incompatibilities and Missing Features  What GNU make lacks from other makes.
14. Makefile Conventions  Conventions for makefiles in GNU programs.
A. Quick Reference  A quick reference for experienced users.
B. Complex Makefile Example  A real example of a straightforward, but nontrivial, makefile.
Index of Concepts  
Index of Functions, Variables, & Directives  

 -- The Detailed Node Listing ---

Overview of make

Preparing and Running Make  
1.1 How to Read This Manual  On Reading this Text
1.2 Problems and Bugs  

An Introduction to Makefiles

2.1 What a Rule Looks Like  What a rule looks like.
2.2 A Simple Makefile  
2.3 How make Processes a Makefile  How make Processes This Makefile
2.4 Variables Make Makefiles Simpler  
2.5 Letting make Deduce the Commands  
2.6 Another Style of Makefile  
2.7 Rules for Cleaning the Directory  

Writing Makefiles

3.1 What Makefiles Contain  What makefiles contain.
3.2 What Name to Give Your Makefile  How to name your makefile.
3.3 Including Other Makefiles  How one makefile can use another makefile.
3.4 The Variable MAKEFILES  The environment can specify extra makefiles.
3.5 How Makefiles Are Remade  How makefiles get remade.
3.6 Overriding Part of Another Makefile  How to override part of one makefile with another makefile.

Writing Rules

4.1 Rule Example  An example explained.
4.2 Rule Syntax  General syntax explained.
4.3 Using Wildcard Characters in File Names  Using wildcard characters such as `*'.
4.4 Searching Directories for Dependencies  Searching other directories for source files.
4.5 Phony Targets  Using a target that is not a real file's name.
4.6 Rules without Commands or Dependencies  You can use a target without commands or dependencies to mark other targets as phony.
4.7 Empty Target Files to Record Events  When only the date matters and the files are empty.
4.8 Special Built-in Target Names  Targets with special built-in meanings.
4.9 Multiple Targets in a Rule  When to make use of several targets in a rule.
4.10 Multiple Rules for One Target  How to use several rules with the same target.
4.11 Static Pattern Rules  Static pattern rules apply to multiple targets and can vary the dependencies according to the target name.
4.12 Double-Colon Rules  How to use a special kind of rule to allow several independent rules for one target.
4.13 Generating Dependencies Automatically  How to automatically generate rules giving dependencies from the source files themselves.

Using Wildcard Characters in File Names

4.3.1 Wildcard Examples  Several examples
4.3.2 Pitfalls of Using Wildcards  Problems to avoid.
4.3.3 The Function wildcard  How to cause wildcard expansion where it does not normally take place.

Searching Directories for Dependencies

4.4.1 VPATH: Search Path for All Dependencies  Specifying a search path that applies to every dependency.
4.4.2 The vpath Directive  Specifying a search path for a specified class of names.
4.4.3 How Directory Searches are Performed  When and how search paths are applied.
4.4.4 Writing Shell Commands with Directory Search  How to write shell commands that work together with search paths.
4.4.5 Directory Search and Implicit Rules  How search paths affect implicit rules.
4.4.6 Directory Search for Link Libraries  Directory search for link libraries.

Static Pattern Rules

4.11.1 Syntax of Static Pattern Rules  The syntax of static pattern rules.
4.11.2 Static Pattern Rules versus Implicit Rules  When are they better than implicit rules?

Writing the Commands in Rules

5.1 Command Echoing  How to control when commands are echoed.
5.2 Command Execution  How commands are executed.
5.3 Parallel Execution  How commands can be executed in parallel.
5.4 Errors in Commands  What happens after a command execution error.
5.5 Interrupting or Killing make  What happens when a command is interrupted.
5.6 Recursive Use of make  Invoking make from makefiles.
5.7 Defining Canned Command Sequences  Defining canned sequences of commands.
5.8 Using Empty Commands  Defining useful, do-nothing commands.

Recursive Use of make

5.6.1 How the MAKE Variable Works  The special effects of using `$(MAKE)'.
5.6.2 Communicating Variables to a Sub-make  How to communicate variables to a sub-make.
5.6.3 Communicating Options to a Sub-make  How to communicate options to a sub-make.
5.6.4 The `--print-directory' Option  How the `-w' or `--print-directory' option helps debug use of recursive make commands.

How to Use Variables

6.1 Basics of Variable References  How to use the value of a variable.
6.2 The Two Flavors of Variables  Variables come in two flavors.
6.3 Advanced Features for Reference to Variables  Advanced features for referencing a variable.
6.4 How Variables Get Their Values  All the ways variables get their values.
6.5 Setting Variables  How to set a variable in the makefile.
6.6 Appending More Text to Variables  How to append more text to the old value of a variable.
6.7 The override Directive  How to set a variable in the makefile even if the user has set it with a command argument.
6.8 Defining Variables Verbatim  An alternate way to set a variable to a verbatim string.
6.9 Variables from the Environment  Variable values can come from the environment.
10.5.3 Automatic Variables  Some special variables have predefined meanings for use with implicit rules.

Advanced Features for Reference to Variables

6.3.1 Substitution References  Referencing a variable with substitutions on the value.
6.3.2 Computed Variable Names  Computing the name of the variable to refer to.

Conditional Parts of Makefiles

7.1 Example of a Conditional  Example of a conditional
7.2 Syntax of Conditionals  The syntax of conditionals.
7.3 Conditionals that Test Flags  Conditionals that test flags.

Functions for Transforming Text

8.1 Function Call Syntax  How to write a function call.
8.2 Functions for String Substitution and Analysis  General-purpose text manipulation functions.
8.3 Functions for File Names  Functions for manipulating file names.
8.4 The foreach Function  Repeat some text with controlled variation.
8.5 The origin Function  Find where a variable got its value.
8.6 The shell Function  Substitute the output of a shell command.

How to Run make

9.1 Arguments to Specify the Makefile  How to specify which makefile to use.
9.2 Arguments to Specify the Goals  How to use goal arguments to specify which parts of the makefile to use.
9.3 Instead of Executing the Commands  How to use mode flags to specify what kind of thing to do with the commands in the makefile other than simply execute them.
9.4 Avoiding Recompilation of Some Files  How to avoid recompiling certain files.
9.5 Overriding Variables  How to override a variable to specify an alternate compiler and other things.
9.6 Testing the Compilation of a Program  How to proceed past some errors, to test compilation.
9.7 Summary of Options  

Using Implicit Rules

10.1 Using Implicit Rules  How to use an existing implicit rule to get the commands for updating a file.
10.2 Catalogue of Implicit Rules  A list of built-in implicit rules.
10.3 Variables Used by Implicit Rules  How to change what predefined rules do.
10.4 Chains of Implicit Rules  How to use a chain of implicit rules.
10.5 Defining and Redefining Pattern Rules  How to define new implicit rules.
10.6 Defining Last-Resort Default Rules  How to defining commands for rules which cannot find any.
10.7 Old-Fashioned Suffix Rules  The old-fashioned style of implicit rule.
10.8 Implicit Rule Search Algorithm  The precise algorithm for applying implicit rules.

Defining and Redefining Pattern Rules

10.5.1 Introduction to Pattern Rules  An introduction to pattern rules.
10.5.2 Pattern Rule Examples  Examples of pattern rules.
10.5.3 Automatic Variables  How to use automatic variables in the commands of implicit rules.
10.5.4 How Patterns Match  How patterns match.
10.5.5 Match-Anything Pattern Rules  Precautions you should take prior to defining rules that can match any target file whatever.
10.5.6 Canceling Implicit Rules  How to override or cancel built-in rules.

Using make to Update Archive Files

11.1 Archive Members as Targets  Archive members as targets.
11.2 Implicit Rule for Archive Member Targets  The implicit rule for archive member targets.
11.3 Dangers When Using Archives  Dangers to watch out for when using archives.
11.4 Suffix Rules for Archive Files  You can write a special kind of suffix rule for updating archives.

Implicit Rule for Archive Member Targets

11.2.1 Updating Archive Symbol Directories  How to update archive symbol directories.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1. Overview of make

The make utility automatically determines which pieces of a large program need to be recompiled, and issues commands to recompile them. This manual describes GNU make, which was implemented by Richard Stallman and Roland McGrath. GNU make conforms to section 6.2 of IEEE Standard 1003.2-1992 (POSIX.2).

Our examples show C programs, since they are most common, but you can use make with any programming language whose compiler can be run with a shell command. Indeed, make is not limited to programs. You can use it to describe any task where some files must be updated automatically from others whenever the others change.

Preparing and Running Make  
1.1 How to Read This Manual  On Reading this Text
1.2 Problems and Bugs  

Preparing and Running Make

To prepare to use make, you must write a file called the makefile that describes the relationships among files in your program and provides commands for updating each file. In a program, typically, the executable file is updated from object files, which are in turn made by compiling source files.

Once a suitable makefile exists, each time you change some source files, this simple shell command:

 
make

suffices to perform all necessary recompilations. The make program uses the makefile data base and the last-modification times of the files to decide which of the files need to be updated. For each of those files, it issues the commands recorded in the data base.

You can provide command line arguments to make to control which files should be recompiled, or how. See section How to Run make.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1 How to Read This Manual

If you are new to make, or are looking for a general introduction, read the first few sections of each chapter, skipping the later sections. In each chapter, the first few sections contain introductory or general information and the later sections contain specialized or technical information. The exception is the second chapter, An Introduction to Makefiles, all of which is introductory.

If you are familiar with other make programs, see Features of GNU make, which lists the enhancements GNU make has, and Incompatibilities and Missing Features, which explains the few things GNU make lacks that others have.

For a quick summary, see 9.7 Summary of Options, A. Quick Reference, and 4.8 Special Built-in Target Names.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2 Problems and Bugs

If you have problems with GNU make or think you've found a bug, please report it to the developers; we cannot promise to do anything but we might well want to fix it.

Before reporting a bug, make sure you've actually found a real bug. Carefully reread the documentation and see if it really says you can do what you're trying to do. If it's not clear whether you should be able to do something or not, report that too; it's a bug in the documentation!

Before reporting a bug or trying to fix it yourself, try to isolate it to the smallest possible makefile that reproduces the problem. Then send us the makefile and the exact results make gave you. Also say what you expected to occur; this will help us decide whether the problem was really in the documentation.

Once you've got a precise problem, please send electronic mail either through the Internet or via UUCP:

 
Internet address:
    bug-gnu-utils@prep.ai.mit.edu

UUCP path:
    mit-eddie!prep.ai.mit.edu!bug-gnu-utils

Please include the version number of make you are using. You can get this information with the command `make --version'. Be sure also to include the type of machine and operating system you are using. If possible, include the contents of the file `config.h' that is generated by the configuration process.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2. An Introduction to Makefiles

You need a file called a makefile to tell make what to do. Most often, the makefile tells make how to compile and link a program.

In this chapter, we will discuss a simple makefile that describes how to compile and link a text editor which consists of eight C source files and three header files. The makefile can also tell make how to run miscellaneous commands when explicitly asked (for example, to remove certain files as a clean-up operation). To see a more complex example of a makefile, see B. Complex Makefile Example.

When make recompiles the editor, each changed C source file must be recompiled. If a header file has changed, each C source file that includes the header file must be recompiled to be safe. Each compilation produces an object file corresponding to the source file. Finally, if any source file has been recompiled, all the object files, whether newly made or saved from previous compilations, must be linked together to produce the new executable editor.

2.1 What a Rule Looks Like  What a rule looks like.
2.2 A Simple Makefile  
2.3 How make Processes a Makefile  How make Processes This Makefile
2.4 Variables Make Makefiles Simpler  
2.5 Letting make Deduce the Commands  
2.6 Another Style of Makefile  
2.7 Rules for Cleaning the Directory  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.1 What a Rule Looks Like

A simple makefile consists of "rules" with the following shape:

 
target ... : dependencies ...
        command
        ...
        ...

A target is usually the name of a file that is generated by a program; examples of targets are executable or object files. A target can also be the name of an action to carry out, such as `clean' (see section 4.5 Phony Targets).

A dependency is a file that is used as input to create the target. A target often depends on several files.

A command is an action that make carries out. A rule may have more than one command, each on its own line. Please note: you need to put a tab character at the beginning of every command line! This is an obscurity that catches the unwary.

Usually a command is in a rule with dependencies and serves to create a target file if any of the dependencies change. However, the rule that specifies commands for the target need not have dependencies. For example, the rule containing the delete command associated with the target `clean' does not have dependencies.

A rule, then, explains how and when to remake certain files which are the targets of the particular rule. make carries out the commands on the dependencies to create or update the target. A rule can also explain how and when to carry out an action. See section Writing Rules.

A makefile may contain other text besides rules, but a simple makefile need only contain rules. Rules may look somewhat more complicated than shown in this template, but all fit the pattern more or less.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.2 A Simple Makefile

Here is a straightforward makefile that describes the way an executable file called edit depends on eight object files which, in turn, depend on eight C source and three header files.

In this example, all the C files include `defs.h', but only those defining editing commands include `command.h', and only low level files that change the editor buffer include `buffer.h'.

 
edit : main.o kbd.o command.o display.o \
       insert.o search.o files.o utils.o
        cc -o edit main.o kbd.o command.o display.o \
                   insert.o search.o files.o utils.o

main.o : main.c defs.h
        cc -c main.c
kbd.o : kbd.c defs.h command.h
        cc -c kbd.c
command.o : command.c defs.h command.h
        cc -c command.c
display.o : display.c defs.h buffer.h
        cc -c display.c
insert.o : insert.c defs.h buffer.h
        cc -c insert.c
search.o : search.c defs.h buffer.h
        cc -c search.c
files.o : files.c defs.h buffer.h command.h
        cc -c files.c
utils.o : utils.c defs.h
        cc -c utils.c
clean :
        rm edit main.o kbd.o command.o display.o \
           insert.o search.o files.o utils.o

We split each long line into two lines using backslash-newline; this is like using one long line, but is easier to read.

To use this makefile to create the executable file called `edit', type:

 
make

To use this makefile to delete the executable file and all the object files from the directory, type:

 
make clean

In the example makefile, the targets include the executable file `edit', and the object files `main.o' and `kbd.o'. The dependencies are files such as `main.c' and `defs.h'. In fact, each `.o' file is both a target and a dependency. Commands include `cc -c main.c' and `cc -c kbd.c'.

When a target is a file, it needs to be recompiled or relinked if any of its dependencies change. In addition, any dependencies that are themselves automatically generated should be updated first. In this example, `edit' depends on each of the eight object files; the object file `main.o' depends on the source file `main.c' and on the header file `defs.h'.

A shell command follows each line that contains a target and dependencies. These shell commands say how to update the target file. A tab character must come at the beginning of every command line to distinguish commands lines from other lines in the makefile. (Bear in mind that make does not know anything about how the commands work. It is up to you to supply commands that will update the target file properly. All make does is execute the commands in the rule you have specified when the target file needs to be updated.)

The target `clean' is not a file, but merely the name of an action. Since you normally do not want to carry out the actions in this rule, `clean' is not a dependency of any other rule. Consequently, make never does anything with it unless you tell it specifically. Note that this rule not only is not a dependency, it also does not have any dependencies, so the only purpose of the rule is to run the specified commands. Targets that do not refer to files but are just actions are called phony targets. See section 4.5 Phony Targets, for information about this kind of target. See section Errors in Commands, to see how to cause make to ignore errors from rm or any other command.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3 How make Processes a Makefile

By default, make starts with the first target (not targets whose names start with `.'). This is called the default goal. (Goals are the targets that make strives ultimately to update. See section Arguments to Specify the Goals.)

In the simple example of the previous section, the default goal is to update the executable program `edit'; therefore, we put that rule first.

Thus, when you give the command:

 
make

make reads the makefile in the current directory and begins by processing the first rule. In the example, this rule is for relinking `edit'; but before make can fully process this rule, it must process the rules for the files that `edit' depends on, which in this case are the object files. Each of these files is processed according to its own rule. These rules say to update each `.o' file by compiling its source file. The recompilation must be done if the source file, or any of the header files named as dependencies, is more recent than the object file, or if the object file does not exist.

The other rules are processed because their targets appear as dependencies of the goal. If some other rule is not depended on by the goal (or anything it depends on, etc.), that rule is not processed, unless you tell make to do so (with a command such as make clean).

Before recompiling an object file, make considers updating its dependencies, the source file and header files. This makefile does not specify anything to be done for them--the `.c' and `.h' files are not the targets of any rules--so make does nothing for these files. But make would update automatically generated C programs, such as those made by Bison or Yacc, by their own rules at this time.

After recompiling whichever object files need it, make decides whether to relink `edit'. This must be done if the file `edit' does not exist, or if any of the object files are newer than it. If an object file was just recompiled, it is now newer than `edit', so `edit' is relinked.

Thus, if we change the file `insert.c' and run make, make will compile that file to update `insert.o', and then link `edit'. If we change the file `command.h' and run make, make will recompile the object files `kbd.o', `command.o' and `files.o' and then link the file `edit'.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4 Variables Make Makefiles Simpler

In our example, we had to list all the object files twice in the rule for `edit' (repeated here):

 
edit : main.o kbd.o command.o display.o \
              insert.o search.o files.o utils.o
        cc -o edit main.o kbd.o command.o display.o \
                   insert.o search.o files.o utils.o

Such duplication is error-prone; if a new object file is added to the system, we might add it to one list and forget the other. We can eliminate the risk and simplify the makefile by using a variable. Variables allow a text string to be defined once and substituted in multiple places later (see section How to Use Variables).

It is standard practice for every makefile to have a variable named objects, OBJECTS, objs, OBJS, obj, or OBJ which is a list of all object file names. We would define such a variable objects with a line like this in the makefile:

 
objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o

Then, each place we want to put a list of the object file names, we can substitute the variable's value by writing `$(objects)' (see section How to Use Variables).

Here is how the complete simple makefile looks when you use a variable for the object files:

 
objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o

edit : $(objects)
        cc -o edit $(objects)
main.o : main.c defs.h
        cc -c main.c
kbd.o : kbd.c defs.h command.h
        cc -c kbd.c
command.o : command.c defs.h command.h
        cc -c command.c
display.o : display.c defs.h buffer.h
        cc -c display.c
insert.o : insert.c defs.h buffer.h
        cc -c insert.c
search.o : search.c defs.h buffer.h
        cc -c search.c
files.o : files.c defs.h buffer.h command.h
        cc -c files.c
utils.o : utils.c defs.h
        cc -c utils.c
clean :
        rm edit $(objects)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5 Letting make Deduce the Commands

It is not necessary to spell out the commands for compiling the individual C source files, because make can figure them out: it has an implicit rule for updating a `.o' file from a correspondingly named `.c' file using a `cc -c' command. For example, it will use the command `cc -c main.c -o main.o' to compile `main.c' into `main.o'. We can therefore omit the commands from the rules for the object files. See section Using Implicit Rules.

When a `.c' file is used automatically in this way, it is also automatically added to the list of dependencies. We can therefore omit the `.c' files from the dependencies, provided we omit the commands.

Here is the entire example, with both of these changes, and a variable objects as suggested above:

 
objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o

edit : $(objects)
        cc -o edit $(objects)

main.o : defs.h
kbd.o : defs.h command.h
command.o : defs.h command.h
display.o : defs.h buffer.h
insert.o : defs.h buffer.h
search.o : defs.h buffer.h
files.o : defs.h buffer.h command.h
utils.o : defs.h

.PHONY : clean
clean :
        -rm edit $(objects)

This is how we would write the makefile in actual practice. (The complications associated with `clean' are described elsewhere. See 4.5 Phony Targets, and Errors in Commands.)

Because implicit rules are so convenient, they are important. You will see them used frequently.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.6 Another Style of Makefile

When the objects of a makefile are created only by implicit rules, an alternative style of makefile is possible. In this style of makefile, you group entries by their dependencies instead of by their targets. Here is what one looks like:

 
objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o

edit : $(objects)
        cc -o edit $(objects)

$(objects) : defs.h
kbd.o command.o files.o : command.h
display.o insert.o search.o files.o : buffer.h

Here `defs.h' is given as a dependency of all the object files; `command.h' and `buffer.h' are dependencies of the specific object files listed for them.

Whether this is better is a matter of taste: it is more compact, but some people dislike it because they find it clearer to put all the information about each target in one place.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.7 Rules for Cleaning the Directory

Compiling a program is not the only thing you might want to write rules for. Makefiles commonly tell how to do a few other things besides compiling a program: for example, how to delete all the object files and executables so that the directory is `clean'.

Here is how we could write a make rule for cleaning our example editor:

 
clean:
        rm edit $(objects)

In practice, we might want to write the rule in a somewhat more complicated manner to handle unanticipated situations. We would do this:

 
.PHONY : clean
clean :
        -rm edit $(objects)

This prevents make from getting confused by an actual file called `clean' and causes it to continue in spite of errors from rm. (See 4.5 Phony Targets, and Errors in Commands.)

A rule such as this should not be placed at the beginning of the makefile, because we do not want it to run by default! Thus, in the example makefile, we want the rule for edit, which recompiles the editor, to remain the default goal.

Since clean is not a dependency of edit, this rule will not run at all if we give the command `make' with no arguments. In order to make the rule run, we have to type `make clean'. See section How to Run make.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3. Writing Makefiles

The information that tells make how to recompile a system comes from reading a data base called the makefile.

3.1 What Makefiles Contain  What makefiles contain.
3.2 What Name to Give Your Makefile  How to name your makefile.
3.3 Including Other Makefiles  How one makefile can use another makefile.
3.4 The Variable MAKEFILES  The environment can specify extra makefiles.
3.5 How Makefiles Are Remade  How makefiles get remade.
3.6 Overriding Part of Another Makefile  How to override part of one makefile with another makefile.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.1 What Makefiles Contain

Makefiles contain five kinds of things: explicit rules, implicit rules, variable definitions, directives, and comments. Rules, variables, and directives are described at length in later chapters.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2 What Name to Give Your Makefile

By default, when make looks for the makefile, it tries the following names, in order: `GNUmakefile', `makefile' and `Makefile'.

Normally you should call your makefile either `makefile' or `Makefile'. (We recommend `Makefile' because it appears prominently near the beginning of a directory listing, right near other important files such as `README'.) The first name checked, `GNUmakefile', is not recommended for most makefiles. You should use this name if you have a makefile that is specific to GNU make, and will not be understood by other versions of make. Other make programs look for `makefile' and `Makefile', but not `GNUmakefile'.

If make finds none of these names, it does not use any makefile. Then you must specify a goal with a command argument, and make will attempt to figure out how to remake it using only its built-in implicit rules. See section Using Implicit Rules.

If you want to use a nonstandard name for your makefile, you can specify the makefile name with the `-f' or `--file' option. The arguments `-f name' or `--file=name' tell make to read the file name as the makefile. If you use more than one `-f' or `--file' option, you can specify several makefiles. All the makefiles are effectively concatenated in the order specified. The default makefile names `GNUmakefile', `makefile' and `Makefile' are not checked automatically if you specify `-f' or `--file'.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3 Including Other Makefiles

The include directive tells make to suspend reading the current makefile and read one or more other makefiles before continuing. The directive is a line in the makefile that looks like this:

 
include filenames...

filenames can contain shell file name patterns.

Extra spaces are allowed and ignored at the beginning of the line, but a tab is not allowed. (If the line begins with a tab, it will be considered a command line.) Whitespace is required between include and the file names, and between file names; extra whitespace is ignored there and at the end of the directive. A comment starting with `#' is allowed at the end of the line. If the file names contain any variable or function references, they are expanded. See section How to Use Variables.

For example, if you have three `.mk' files, `a.mk', `b.mk', and `c.mk', and $(bar) expands to bish bash, then the following expression

 
include foo *.mk $(bar)

is equivalent to

 
include foo a.mk b.mk c.mk bish bash

When make processes an include directive, it suspends reading of the containing makefile and reads from each listed file in turn. When that is finished, make resumes reading the makefile in which the directive appears.

One occasion for using include directives is when several programs, handled by individual makefiles in various directories, need to use a common set of variable definitions (see section Setting Variables) or pattern rules (see section Defining and Redefining Pattern Rules).

Another such occasion is when you want to generate dependencies from source files automatically; the dependencies can be put in a file that is included by the main makefile. This practice is generally cleaner than that of somehow appending the dependencies to the end of the main makefile as has been traditionally done with other versions of make. See section 4.13 Generating Dependencies Automatically.

If the specified name does not start with a slash, and the file is not found in the current directory, several other directories are searched. First, any directories you have specified with the `-I' or `--include-dir' option are searched (see section Summary of Options). Then the following directories (if they exist) are searched, in this order: `prefix/include' (normally `/usr/local/include' (1)) `/usr/gnu/include', `/usr/local/include', `/usr/include'.

If an included makefile cannot be found in any of these directories, a warning message is generated, but it is not an immediately fatal error; processing of the makefile containing the include continues. Once it has finished reading makefiles, make will try to remake any that are out of date or don't exist. See section How Makefiles Are Remade. Only after it has tried to find a way to remake a makefile and failed, will make diagnose the missing makefile as a fatal error.

If you want make to simply ignore a makefile which does not exist and cannot be remade, with no error message, use the -include directive instead of include, like this:

 
-include filenames...

This is acts like include in every way except that there is no error (not even a warning) if any of the filenames do not exist. For compatibility with some other make implementations, sinclude is another name for -include.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4 The Variable MAKEFILES

If the environment variable MAKEFILES is defined, make considers its value as a list of names (separated by whitespace) of additional makefiles to be read before the others. This works much like the include directive: various directories are searched for those files (see section Including Other Makefiles). In addition, the default goal is never taken from one of these makefiles and it is not an error if the files listed in MAKEFILES are not found.

The main use of MAKEFILES is in communication between recursive invocations of make (see section Recursive Use of make). It usually is not desirable to set the environment variable before a top-level invocation of make, because it is usually better not to mess with a makefile from outside. However, if you are running make without a specific makefile, a makefile in MAKEFILES can do useful things to help the built-in implicit rules work better, such as defining search paths (see section 4.4 Searching Directories for Dependencies).

Some users are tempted to set MAKEFILES in the environment automatically on login, and program makefiles to expect this to be done. This is a very bad idea, because such makefiles will fail to work if run by anyone else. It is much better to write explicit include directives in the makefiles. See section Including Other Makefiles.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.5 How Makefiles Are Remade

Sometimes makefiles can be remade from other files, such as RCS or SCCS files. If a makefile can be remade from other files, you probably want make to get an up-to-date version of the makefile to read in.

To this end, after reading in all makefiles, make will consider each as a goal target and attempt to update it. If a makefile has a rule which says how to update it (found either in that very makefile or in another one) or if an implicit rule applies to it (see section Using Implicit Rules), it will be updated if necessary. After all makefiles have been checked, if any have actually been changed, make starts with a clean slate and reads all the makefiles over again. (It will also attempt to update each of them over again, but normally this will not change them again, since they are already up to date.)

If the makefiles specify a double-colon rule to remake a file with commands but no dependencies, that file will always be remade (see section 4.12 Double-Colon Rules). In the case of makefiles, a makefile that has a double-colon rule with commands but no dependencies will be remade every time make is run, and then again after make starts over and reads the makefiles in again. This would cause an infinite loop: make would constantly remake the makefile, and never do anything else. So, to avoid this, make will not attempt to remake makefiles which are specified as double-colon targets but have no dependencies.

If you do not specify any makefiles to be read with `-f' or `--file' options, make will try the default makefile names; see section What Name to Give Your Makefile. Unlike makefiles explicitly requested with `-f' or `--file' options, make is not certain that these makefiles should exist. However, if a default makefile does not exist but can be created by running make rules, you probably want the rules to be run so that the makefile can be used.

Therefore, if none of the default makefiles exists, make will try to make each of them in the same order in which they are searched for (see section What Name to Give Your Makefile) until it succeeds in making one, or it runs out of names to try. Note that it is not an error if make cannot find or make any makefile; a makefile is not always necessary.

When you use the `-t' or `--touch' option (see section Instead of Executing the Commands), you would not want to use an out-of-date makefile to decide which targets to touch. So the `-t' option has no effect on updating makefiles; they are really updated even if `-t' is specified. Likewise, `-q' (or `--question') and `-n' (or `--just-print') do not prevent updating of makefiles, because an out-of-date makefile would result in the wrong output for other targets. Thus, `make -f mfile -n foo' will update `mfile', read it in, and then print the commands to update `foo' and its dependencies without running them. The commands printed for `foo' will be those specified in the updated contents of `mfile'.

However, on occasion you might actually wish to prevent updating of even the makefiles. You can do this by specifying the makefiles as goals in the command line as well as specifying them as makefiles. When the makefile name is specified explicitly as a goal, the options `-t' and so on do apply to them.

Thus, `make -f mfile -n mfile foo' would read the makefile `mfile', print the commands needed to update it without actually running them, and then print the commands needed to update `foo' without running them. The commands for `foo' will be those specified by the existing contents of `mfile'.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.6 Overriding Part of Another Makefile

Sometimes it is useful to have a makefile that is mostly just like another makefile. You can often use the `include' directive to include one in the other, and add more targets or variable definitions. However, if the two makefiles give different commands for the same target, make will not let you just do this. But there is another way.

In the containing makefile (the one that wants to include the other), you can use a match-anything pattern rule to say that to remake any target that cannot be made from the information in the containing makefile, make should look in another makefile. See section 10.5 Defining and Redefining Pattern Rules, for more information on pattern rules.

For example, if you have a makefile called `Makefile' that says how to make the target `foo' (and other targets), you can write a makefile called `GNUmakefile' that contains:

 
foo:
        frobnicate > foo

%: force
        @$(MAKE) -f Makefile $@
force: ;

If you say `make foo', make will find `GNUmakefile', read it, and see that to make `foo', it needs to run the command `frobnicate > foo'. If you say `make bar', make will find no way to make `bar' in `GNUmakefile', so it will use the commands from the pattern rule: `make -f Makefile bar'. If `Makefile' provides a rule for updating `bar', make will apply the rule. And likewise for any other target that `GNUmakefile' does not say how to make.

The way this works is that the pattern rule has a pattern of just `%', so it matches any target whatever. The rule specifies a dependency `force', to guarantee that the commands will be run even if the target file already exists. We give `force' target empty commands to prevent make from searching for an implicit rule to build it--otherwise it would apply the same match-anything rule to `force' itself and create a dependency loop!


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4. Writing Rules

A rule appears in the makefile and says when and how to remake certain files, called the rule's targets (most often only one per rule). It lists the other files that are the dependencies of the target, and commands to use to create or update the target.

The order of rules is not significant, except for determining the default goal: the target for make to consider, if you do not otherwise specify one. The default goal is the target of the first rule in the first makefile. If the first rule has multiple targets, only the first target is taken as the default. There are two exceptions: a target starting with a period is not a default unless it contains one or more slashes, `/', as well; and, a target that defines a pattern rule has no effect on the default goal. (See section Defining and Redefining Pattern Rules.)

Therefore, we usually write the makefile so that the first rule is the one for compiling the entire program or all the programs described by the makefile (often with a target called `all'). See section Arguments to Specify the Goals.

4.1 Rule Example  An example explained.
4.2 Rule Syntax  General syntax explained.
4.3 Using Wildcard Characters in File Names  Using wildcard characters such as `*'.
4.4 Searching Directories for Dependencies  Searching other directories for source files.
4.5 Phony Targets  Using a target that is not a real file's name.
4.6 Rules without Commands or Dependencies  You can use a target without commands or dependencies to mark other targets as phony.
4.7 Empty Target Files to Record Events  When only the date matters and the files are empty.
4.8 Special Built-in Target Names  Targets with special built-in meanings.
4.9 Multiple Targets in a Rule  When to make use of several targets in a rule.
4.10 Multiple Rules for One Target  How to use several rules with the same target.
4.11 Static Pattern Rules  Static pattern rules apply to multiple targets and can vary the dependencies according to the target name.
4.12 Double-Colon Rules  How to use a special kind of rule to allow several independent rules for one target.
4.13 Generating Dependencies Automatically  How to automatically generate rules giving dependencies from the source files themselves.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.1 Rule Example

Here is an example of a rule:

 
foo.o : foo.c defs.h       # module for twiddling the frobs
        cc -c -g foo.c

Its target is `foo.o' and its dependencies are `foo.c' and `defs.h'. It has one command, which is `cc -c -g foo.c'. The command line starts with a tab to identify it as a command.

This rule says two things:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.2 Rule Syntax

In general, a rule looks like this:

 
targets : dependencies
        command
        ...

or like this:

 
targets : dependencies ; command
        command
        ...

The targets are file names, separated by spaces. Wildcard characters may be used (see section Using Wildcard Characters in File Names) and a name of the form `a(m)' represents member m in archive file a (see section Archive Members as Targets). Usually there is only one target per rule, but occasionally there is a reason to have more (see section Multiple Targets in a Rule).

The command lines start with a tab character. The first command may appear on the line after the dependencies, with a tab character, or may appear on the same line, with a semicolon. Either way, the effect is the same. See section Writing the Commands in Rules.

Because dollar signs are used to start variable references, if you really want a dollar sign in a rule you must write two of them, `$$' (see section How to Use Variables). You may split a long line by inserting a backslash followed by a newline, but this is not required, as make places no limit on the length of a line in a makefile.

A rule tells make two things: when the targets are out of date, and how to update them when necessary.

The criterion for being out of date is specified in terms of the dependencies, which consist of file names separated by spaces. (Wildcards and archive members (see section 11. Using make to Update Archive Files) are allowed here too.) A target is out of date if it does not exist or if it is older than any of the dependencies (by comparison of last-modification times). The idea is that the contents of the target file are computed based on information in the dependencies, so if any of the dependencies changes, the contents of the existing target file are no longer necessarily valid.

How to update is specified by commands. These are lines to be executed by the shell (normally `sh'), but with some extra features (see section Writing the Commands in Rules).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.3 Using Wildcard Characters in File Names

A single file name can specify many files using wildcard characters. The wildcard characters in make are `*', `?' and `[...]', the same as in the Bourne shell. For example, `*.c' specifies a list of all the files (in the working directory) whose names end in `.c'.

The character `~' at the beginning of a file name also has special significance. If alone, or followed by a slash, it represents your home directory. For example `~/bin' expands to `/home/you/bin'. If the `~' is followed by a word, the string represents the home directory of the user named by that word. For example `~john/bin' expands to `/home/john/bin'. On systems which don't have a home directory for each user (such as MS-DOS or MS-Windows), this functionality can be simulated by setting the environment variable HOME.

Wildcard expansion happens automatically in targets, in dependencies, and in commands (where the shell does the expansion). In other contexts, wildcard expansion happens only if you request it explicitly with the wildcard function.

The special significance of a wildcard character can be turned off by preceding it with a backslash. Thus, `foo\*bar' would refer to a specific file whose name consists of `foo', an asterisk, and `bar'.

4.3.1 Wildcard Examples  Several examples
4.3.2 Pitfalls of Using Wildcards  Problems to avoid.
4.3.3 The Function wildcard  How to cause wildcard expansion where it does not normally take place.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.3.1 Wildcard Examples

Wildcards can be used in the commands of a rule, where they are expanded by the shell. For example, here is a rule to delete all the object files:

 
clean:
        rm -f *.o

Wildcards are also useful in the dependencies of a rule. With the following rule in the makefile, `make print' will print all the `.c' files that have changed since the last time you printed them:

 
print: *.c
        lpr -p $?
        touch print

This rule uses `print' as an empty target file; see Empty Target Files to Record Events. (The automatic variable `$?' is used to print only those files that have changed; see Automatic Variables.)

Wildcard expansion does not happen when you define a variable. Thus, if you write this:

 
objects = *.o

then the value of the variable objects is the actual string `*.o'. However, if you use the value of objects in a target, dependency or command, wildcard expansion will take place at that time. To set objects to the expansion, instead use:

 
objects := $(wildcard *.o)

See section 4.3.3 The Function wildcard.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.3.2 Pitfalls of Using Wildcards

Now here is an example of a naive way of using wildcard expansion, that does not do what you would intend. Suppose you would like to say that the executable file `foo' is made from all the object files in the directory, and you write this:

 
objects = *.o

foo : $(objects)
        cc -o foo $(CFLAGS) $(objects)

The value of objects is the actual string `*.o'. Wildcard expansion happens in the rule for `foo', so that each existing `.o' file becomes a dependency of `foo' and will be recompiled if necessary.

But what if you delete all the `.o' files? When a wildcard matches no files, it is left as it is, so then `foo' will depend on the oddly-named file `*.o'. Since no such file is likely to exist, make will give you an error saying it cannot figure out how to make `*.o'. This is not what you want!

Actually it is possible to obtain the desired result with wildcard expansion, but you need more sophisticated techniques, including the wildcard function and string substitution. See section The Function wildcard.

Microsoft operating systems (MS-DOS and MS-Windows) use backslashes to separate directories in pathnames, like so:

 
  c:\foo\bar\baz.c

This is equivalent to the Unix-style `c:/foo/bar/baz.c' (the `c:' part is the so-called drive letter). When make runs on these systems, it supports backslashes as well as the Unix-style forward slashes in pathnames. However, this support does not include the wildcard expansion, where backslash is a quote character. Therefore, you must use Unix-style slashes in these cases.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.3.3 The Function wildcard

Wildcard expansion happens automatically in rules. But wildcard expansion does not normally take place when a variable is set, or inside the arguments of a function. If you want to do wildcard expansion in such places, you need to use the wildcard function, like this:

 
$(wildcard pattern...)

This string, used anywhere in a makefile, is replaced by a space-separated list of names of existing files that match one of the given file name patterns. If no existing file name matches a pattern, then that pattern is omitted from the output of the wildcard function. Note that this is different from how unmatched wildcards behave in rules, where they are used verbatim rather than ignored (see section 4.3.2 Pitfalls of Using Wildcards).

One use of the wildcard function is to get a list of all the C source files in a directory, like this:

 
$(wildcard *.c)

We can change the list of C source files into a list of object files by replacing the `.c' suffix with `.o' in the result, like this:

 
$(patsubst %.c,%.o,$(wildcard *.c))

(Here we have used another function, patsubst. See section Functions for String Substitution and Analysis.)

Thus, a makefile to compile all C source files in the directory and then link them together could be written as follows:

 
objects := $(patsubst %.c,%.o,$(wildcard *.c))

foo : $(objects)
        cc -o foo $(objects)

(This takes advantage of the implicit rule for compiling C programs, so there is no need to write explicit rules for compiling the files. See section The Two Flavors of Variables, for an explanation of `:=', which is a variant of `='.)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.4 Searching Directories for Dependencies

For large systems, it is often desirable to put sources in a separate directory from the binaries. The directory search features of make facilitate this by searching several directories automatically to find a dependency. When you redistribute the files among directories, you do not need to change the individual rules, just the search paths.

4.4.1 VPATH: Search Path for All Dependencies  Specifying a search path that applies to every dependency.
4.4.2 The vpath Directive  Specifying a search path for a specified class of names.
4.4.3 How Directory Searches are Performed  When and how search paths are applied.
4.4.4 Writing Shell Commands with Directory Search  How to write shell commands that work together with search paths.
4.4.5 Directory Search and Implicit Rules  How search paths affect implicit rules.
4.4.6 Directory Search for Link Libraries  Directory search for link libraries.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.4.1 VPATH: Search Path for All Dependencies

The value of the make variable VPATH specifies a list of directories that make should search. Most often, the directories are expected to contain dependency files that are not in the current directory; however, VPATH specifies a search list that make applies for all files, including files which are targets of rules.

Thus, if a file that is listed as a target or dependency does not exist in the current directory, make searches the directories listed in VPATH for a file with that name. If a file is found in one of them, that file may become the dependency (see below). Rules may then specify the names of files in the dependency list as if they all existed in the current directory. See section Writing Shell Commands with Directory Search.

In the VPATH variable, directory names are separated by colons or blanks. The order in which directories are listed is the order followed by make in its search. (On MS-DOS and MS-Windows, semi-colons are used as separators of directory names in VPATH, since the colon can be used in the pathname itself, after the drive letter.)

For example,

 
VPATH = src:../headers

specifies a path containing two directories, `src' and `../headers', which make searches in that order.

With this value of VPATH, the following rule,

 
foo.o : foo.c

is interpreted as if it were written like this:

 
foo.o : src/foo.c

assuming the file `foo.c' does not exist in the current directory but is found in the directory `src'.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.4.2 The vpath Directive

Similar to the VPATH variable, but more selective, is the vpath directive (note lower case), which allows you to specify a search path for a particular class of file names: those that match a particular pattern. Thus you can supply certain search directories for one class of file names and other directories (or none) for other file names.

There are three forms of the vpath directive:

vpath pattern directories
Specify the search path directories for file names that match pattern.

The search path, directories, is a list of directories to be searched, separated by colons (semi-colons on MS-DOS and MS-Windows) or blanks, just like the search path used in the VPATH variable.

vpath pattern
Clear out the search path associated with pattern.

vpath

Clear all search paths previously specified with vpath directives.

A vpath pattern is a string containing a `%' character. The string must match the file name of a dependency that is being searched for, the `%' character matching any sequence of zero or more characters (as in pattern rules; see section Defining and Redefining Pattern Rules). For example, %.h matches files that end in .h. (If there is no `%', the pattern must match the dependency exactly, which is not useful very often.)

`%' characters in a vpath directive's pattern can be quoted with preceding backslashes (`\'). Backslashes that would otherwise quote `%' characters can be quoted with more backslashes. Backslashes that quote `%' characters or other backslashes are removed from the pattern before it is compared to file names. Backslashes that are not in danger of quoting `%' characters go unmolested.

When a dependency fails to exist in the current directory, if the pattern in a vpath directive matches the name of the dependency file, then the directories in that directive are searched just like (and before) the directories in the VPATH variable.

For example,

 
vpath %.h ../headers

tells make to look for any dependency whose name ends in `.h' in the directory `../headers' if the file is not found in the current directory.

If several vpath patterns match the dependency file's name, then make processes each matching vpath directive one by one, searching all the directories mentioned in each directive. make handles multiple vpath directives in the order in which they appear in the makefile; multiple directives with the same pattern are independent of each other.

Thus,

 
vpath %.c foo
vpath %   blish
vpath %.c bar

will look for a file ending in `.c' in `foo', then `blish', then `bar', while

 
vpath %.c foo:bar
vpath %   blish

will look for a file ending in `.c' in `foo', then `bar', then `blish'.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.4.3 How Directory Searches are Performed

When a dependency is found through directory search, regardless of type (general or selective), the pathname located may not be the one that make actually provides you in the dependency list. Sometimes the path discovered through directory search is thrown away.

The algorithm make uses to decide whether to keep or abandon a path found via directory search is as follows:

  1. If a target file does not exist at the path specified in the makefile, directory search is performed.

  2. If the directory search is successful, that path is kept and this file is tentatively stored as the target.

  3. All dependencies of this target are examined using this same method.

  4. After processing the dependencies, the target may or may not need to be rebuilt:

    1. If the target does not need to be rebuilt, the path to the file found during directory search is used for any dependency lists which contain this target. In short, if make doesn't need to rebuild the target then you use the path found via directory search.

    2. If the target does need to be rebuilt (is out-of-date), the pathname found during directory search is thrown away, and the target is rebuilt using the file name specified in the makefile. In short, if make must rebuild, then the target is rebuilt locally, not in the directory found via directory search.

This algorithm may seem complex, but in practice it is quite often exactly what you want.

Other versions of make use a simpler algorithm: if the file does not exist, and it is found via directory search, then that pathname is always used whether or not the target needs to be built. Thus, if the target is rebuilt it is created at the pathname discovered during directory search.

If, in fact, this is the behavior you want for some or all of your directories, you can use the GPATH variable to indicate this to make.

GPATH has the same syntax and format as VPATH (that is, a space- or colon-delimited list of pathnames). If an out-of-date target is found by directory search in a directory that also appears in GPATH, then that pathname is not thrown away. The target is rebuilt using the expanded path.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]