This is make.info, produced by makeinfo version 4.0 from make.texinfo.

INFO-DIR-SECTION GNU Packages
START-INFO-DIR-ENTRY
* Make: (make).            Remake files automatically.
END-INFO-DIR-ENTRY

   This file documents the GNU Make utility, which determines
automatically which pieces of a large program need to be recompiled,
and issues the commands to recompile them.

   This is Edition 0.54, last updated 09 September 1999, of `The GNU
Make Manual', for `make', Version 3.78.1.

   Copyright (C) 1988, '89, '90, '91, '92, '93, '94, '95, '96, '97,
'98, '99         Free Software Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Free Software Foundation.


File: make.info,  Node: Flavors,  Next: Advanced,  Prev: Reference,  Up: Using Variables

The Two Flavors of Variables
============================

   There are two ways that a variable in GNU `make' can have a value;
we call them the two "flavors" of variables.  The two flavors are
distinguished in how they are defined and in what they do when expanded.

   The first flavor of variable is a "recursively expanded" variable.
Variables of this sort are defined by lines using `=' (*note Setting
Variables: Setting.) or by the `define' directive (*note Defining
Variables Verbatim: Defining.).  The value you specify is installed
verbatim; if it contains references to other variables, these
references are expanded whenever this variable is substituted (in the
course of expanding some other string).  When this happens, it is
called "recursive expansion".

   For example,

     foo = $(bar)
     bar = $(ugh)
     ugh = Huh?
     
     all:;echo $(foo)

will echo `Huh?': `$(foo)' expands to `$(bar)' which expands to
`$(ugh)' which finally expands to `Huh?'.

   This flavor of variable is the only sort supported by other versions
of `make'.  It has its advantages and its disadvantages.  An advantage
(most would say) is that:

     CFLAGS = $(include_dirs) -O
     include_dirs = -Ifoo -Ibar

will do what was intended: when `CFLAGS' is expanded in a command, it
will expand to `-Ifoo -Ibar -O'.  A major disadvantage is that you
cannot append something on the end of a variable, as in

     CFLAGS = $(CFLAGS) -O

because it will cause an infinite loop in the variable expansion.
(Actually `make' detects the infinite loop and reports an error.)

   Another disadvantage is that any functions (*note Functions for
Transforming Text: Functions.)  referenced in the definition will be
executed every time the variable is expanded.  This makes `make' run
slower; worse, it causes the `wildcard' and `shell' functions to give
unpredictable results because you cannot easily control when they are
called, or even how many times.

   To avoid all the problems and inconveniences of recursively expanded
variables, there is another flavor: simply expanded variables.

   "Simply expanded variables" are defined by lines using `:=' (*note
Setting Variables: Setting.).  The value of a simply expanded variable
is scanned once and for all, expanding any references to other
variables and functions, when the variable is defined.  The actual
value of the simply expanded variable is the result of expanding the
text that you write.  It does not contain any references to other
variables; it contains their values _as of the time this variable was
defined_.  Therefore,

     x := foo
     y := $(x) bar
     x := later

is equivalent to

     y := foo bar
     x := later

   When a simply expanded variable is referenced, its value is
substituted verbatim.

   Here is a somewhat more complicated example, illustrating the use of
`:=' in conjunction with the `shell' function.  (*Note The `shell'
Function: Shell Function.)  This example also shows use of the variable
`MAKELEVEL', which is changed when it is passed down from level to
level.  (*Note Communicating Variables to a Sub-`make':
Variables/Recursion, for information about `MAKELEVEL'.)

     ifeq (0,${MAKELEVEL})
     cur-dir   := $(shell pwd)
     whoami    := $(shell whoami)
     host-type := $(shell arch)
     MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
     endif

An advantage of this use of `:=' is that a typical `descend into a
directory' command then looks like this:

     ${subdirs}:
           ${MAKE} cur-dir=${cur-dir}/$@ -C $@ all

   Simply expanded variables generally make complicated makefile
programming more predictable because they work like variables in most
programming languages.  They allow you to redefine a variable using its
own value (or its value processed in some way by one of the expansion
functions) and to use the expansion functions much more efficiently
(*note Functions for Transforming Text: Functions.).

   You can also use them to introduce controlled leading whitespace into
variable values.  Leading whitespace characters are discarded from your
input before substitution of variable references and function calls;
this means you can include leading spaces in a variable value by
protecting them with variable references, like this:

     nullstring :=
     space := $(nullstring) # end of the line

Here the value of the variable `space' is precisely one space.  The
comment `# end of the line' is included here just for clarity.  Since
trailing space characters are _not_ stripped from variable values, just
a space at the end of the line would have the same effect (but be
rather hard to read).  If you put whitespace at the end of a variable
value, it is a good idea to put a comment like that at the end of the
line to make your intent clear.  Conversely, if you do _not_ want any
whitespace characters at the end of your variable value, you must
remember not to put a random comment on the end of the line after some
whitespace, such as this:

     dir := /foo/bar    # directory to put the frobs in

Here the value of the variable `dir' is `/foo/bar    ' (with four
trailing spaces), which was probably not the intention.  (Imagine
something like `$(dir)/file' with this definition!)

   There is another assignment operator for variables, `?='.  This is
called a conditional variable assignment operator, because it only has
an effect if the variable is not yet defined.  This statement:

     FOO ?= bar

is exactly equivalent to this (*note The `origin' Function: Origin
Function.):

     ifeq ($(origin FOO), undefined)
       FOO = bar
     endif

   Note that a variable set to an empty value is still defined, so `?='
will not set that variable.


File: make.info,  Node: Advanced,  Next: Values,  Prev: Flavors,  Up: Using Variables

Advanced Features for Reference to Variables
============================================

   This section describes some advanced features you can use to
reference variables in more flexible ways.

* Menu:

* Substitution Refs::           Referencing a variable with
                                  substitutions on the value.
* Computed Names::              Computing the name of the variable to refer to.


File: make.info,  Node: Substitution Refs,  Next: Computed Names,  Up: Advanced

Substitution References
-----------------------

   A "substitution reference" substitutes the value of a variable with
alterations that you specify.  It has the form `$(VAR:A=B)' (or
`${VAR:A=B}') and its meaning is to take the value of the variable VAR,
replace every A at the end of a word with B in that value, and
substitute the resulting string.

   When we say "at the end of a word", we mean that A must appear
either followed by whitespace or at the end of the value in order to be
replaced; other occurrences of A in the value are unaltered.  For
example:

     foo := a.o b.o c.o
     bar := $(foo:.o=.c)

sets `bar' to `a.c b.c c.c'.  *Note Setting Variables: Setting.

   A substitution reference is actually an abbreviation for use of the
`patsubst' expansion function (*note Functions for String Substitution
and Analysis: Text Functions.).  We provide substitution references as
well as `patsubst' for compatibility with other implementations of
`make'.

   Another type of substitution reference lets you use the full power of
the `patsubst' function.  It has the same form `$(VAR:A=B)' described
above, except that now A must contain a single `%' character.  This
case is equivalent to `$(patsubst A,B,$(VAR))'.  *Note Functions for
String Substitution and Analysis: Text Functions, for a description of
the `patsubst' function.

For example:

     foo := a.o b.o c.o
     bar := $(foo:%.o=%.c)

sets `bar' to `a.c b.c c.c'.


File: make.info,  Node: Computed Names,  Prev: Substitution Refs,  Up: Advanced

Computed Variable Names
-----------------------

   Computed variable names are a complicated concept needed only for
sophisticated makefile programming.  For most purposes you need not
consider them, except to know that making a variable with a dollar sign
in its name might have strange results.  However, if you are the type
that wants to understand everything, or you are actually interested in
what they do, read on.

   Variables may be referenced inside the name of a variable.  This is
called a "computed variable name" or a "nested variable reference".
For example,

     x = y
     y = z
     a := $($(x))

defines `a' as `z': the `$(x)' inside `$($(x))' expands to `y', so
`$($(x))' expands to `$(y)' which in turn expands to `z'.  Here the
name of the variable to reference is not stated explicitly; it is
computed by expansion of `$(x)'.  The reference `$(x)' here is nested
within the outer variable reference.

   The previous example shows two levels of nesting, but any number of
levels is possible.  For example, here are three levels:

     x = y
     y = z
     z = u
     a := $($($(x)))

Here the innermost `$(x)' expands to `y', so `$($(x))' expands to
`$(y)' which in turn expands to `z'; now we have `$(z)', which becomes
`u'.

   References to recursively-expanded variables within a variable name
are reexpanded in the usual fashion.  For example:

     x = $(y)
     y = z
     z = Hello
     a := $($(x))

defines `a' as `Hello': `$($(x))' becomes `$($(y))' which becomes
`$(z)' which becomes `Hello'.

   Nested variable references can also contain modified references and
function invocations (*note Functions for Transforming Text:
Functions.), just like any other reference.  For example, using the
`subst' function (*note Functions for String Substitution and Analysis:
Text Functions.):

     x = variable1
     variable2 := Hello
     y = $(subst 1,2,$(x))
     z = y
     a := $($($(z)))

eventually defines `a' as `Hello'.  It is doubtful that anyone would
ever want to write a nested reference as convoluted as this one, but it
works: `$($($(z)))' expands to `$($(y))' which becomes `$($(subst
1,2,$(x)))'.  This gets the value `variable1' from `x' and changes it
by substitution to `variable2', so that the entire string becomes
`$(variable2)', a simple variable reference whose value is `Hello'.

   A computed variable name need not consist entirely of a single
variable reference.  It can contain several variable references, as
well as some invariant text.  For example,

     a_dirs := dira dirb
     1_dirs := dir1 dir2
     
     a_files := filea fileb
     1_files := file1 file2
     
     ifeq "$(use_a)" "yes"
     a1 := a
     else
     a1 := 1
     endif
     
     ifeq "$(use_dirs)" "yes"
     df := dirs
     else
     df := files
     endif
     
     dirs := $($(a1)_$(df))

will give `dirs' the same value as `a_dirs', `1_dirs', `a_files' or
`1_files' depending on the settings of `use_a' and `use_dirs'.

   Computed variable names can also be used in substitution references:

     a_objects := a.o b.o c.o
     1_objects := 1.o 2.o 3.o
     
     sources := $($(a1)_objects:.o=.c)

defines `sources' as either `a.c b.c c.c' or `1.c 2.c 3.c', depending
on the value of `a1'.

   The only restriction on this sort of use of nested variable
references is that they cannot specify part of the name of a function
to be called.  This is because the test for a recognized function name
is done before the expansion of nested references.  For example,

     ifdef do_sort
     func := sort
     else
     func := strip
     endif
     
     bar := a d b g q c
     
     foo := $($(func) $(bar))

attempts to give `foo' the value of the variable `sort a d b g q c' or
`strip a d b g q c', rather than giving `a d b g q c' as the argument
to either the `sort' or the `strip' function.  This restriction could
be removed in the future if that change is shown to be a good idea.

   You can also use computed variable names in the left-hand side of a
variable assignment, or in a `define' directive, as in:

     dir = foo
     $(dir)_sources := $(wildcard $(dir)/*.c)
     define $(dir)_print
     lpr $($(dir)_sources)
     endef

This example defines the variables `dir', `foo_sources', and
`foo_print'.

   Note that "nested variable references" are quite different from
"recursively expanded variables" (*note The Two Flavors of Variables:
Flavors.), though both are used together in complex ways when doing
makefile programming.


File: make.info,  Node: Values,  Next: Setting,  Prev: Advanced,  Up: Using Variables

How Variables Get Their Values
==============================

   Variables can get values in several different ways:

   * You can specify an overriding value when you run `make'.  *Note
     Overriding Variables: Overriding.

   * You can specify a value in the makefile, either with an assignment
     (*note Setting Variables: Setting.) or with a verbatim definition
     (*note Defining Variables Verbatim: Defining.).

   * Variables in the environment become `make' variables.  *Note
     Variables from the Environment: Environment.

   * Several "automatic" variables are given new values for each rule.
     Each of these has a single conventional use.  *Note Automatic
     Variables: Automatic.

   * Several variables have constant initial values.  *Note Variables
     Used by Implicit Rules: Implicit Variables.


File: make.info,  Node: Setting,  Next: Appending,  Prev: Values,  Up: Using Variables

Setting Variables
=================

   To set a variable from the makefile, write a line starting with the
variable name followed by `=' or `:='.  Whatever follows the `=' or
`:=' on the line becomes the value.  For example,

     objects = main.o foo.o bar.o utils.o

defines a variable named `objects'.  Whitespace around the variable
name and immediately after the `=' is ignored.

   Variables defined with `=' are "recursively expanded" variables.
Variables defined with `:=' are "simply expanded" variables; these
definitions can contain variable references which will be expanded
before the definition is made.  *Note The Two Flavors of Variables:
Flavors.

   The variable name may contain function and variable references, which
are expanded when the line is read to find the actual variable name to
use.

   There is no limit on the length of the value of a variable except the
amount of swapping space on the computer.  When a variable definition is
long, it is a good idea to break it into several lines by inserting
backslash-newline at convenient places in the definition.  This will not
affect the functioning of `make', but it will make the makefile easier
to read.

   Most variable names are considered to have the empty string as a
value if you have never set them.  Several variables have built-in
initial values that are not empty, but you can set them in the usual
ways (*note Variables Used by Implicit Rules: Implicit Variables.).
Several special variables are set automatically to a new value for each
rule; these are called the "automatic" variables (*note Automatic
Variables: Automatic.).

   If you'd like a variable to be set to a value only if it's not
already set, then you can use the shorthand operator `?=' instead of
`='.  These two settings of the variable `FOO' are identical (*note The
`origin' Function: Origin Function.):

     FOO ?= bar

and

     ifeq ($(origin FOO), undefined)
     FOO = bar
     endif


File: make.info,  Node: Appending,  Next: Override Directive,  Prev: Setting,  Up: Using Variables

Appending More Text to Variables
================================

   Often it is useful to add more text to the value of a variable
already defined.  You do this with a line containing `+=', like this:

     objects += another.o

This takes the value of the variable `objects', and adds the text
`another.o' to it (preceded by a single space).  Thus:

     objects = main.o foo.o bar.o utils.o
     objects += another.o

sets `objects' to `main.o foo.o bar.o utils.o another.o'.

   Using `+=' is similar to:

     objects = main.o foo.o bar.o utils.o
     objects := $(objects) another.o

but differs in ways that become important when you use more complex
values.

   When the variable in question has not been defined before, `+=' acts
just like normal `=': it defines a recursively-expanded variable.
However, when there _is_ a previous definition, exactly what `+=' does
depends on what flavor of variable you defined originally.  *Note The
Two Flavors of Variables: Flavors, for an explanation of the two
flavors of variables.

   When you add to a variable's value with `+=', `make' acts
essentially as if you had included the extra text in the initial
definition of the variable.  If you defined it first with `:=', making
it a simply-expanded variable, `+=' adds to that simply-expanded
definition, and expands the new text before appending it to the old
value just as `:=' does (*note Setting Variables: Setting., for a full
explanation of `:=').  In fact,

     variable := value
     variable += more

is exactly equivalent to:

     variable := value
     variable := $(variable) more

   On the other hand, when you use `+=' with a variable that you defined
first to be recursively-expanded using plain `=', `make' does something
a bit different.  Recall that when you define a recursively-expanded
variable, `make' does not expand the value you set for variable and
function references immediately.  Instead it stores the text verbatim,
and saves these variable and function references to be expanded later,
when you refer to the new variable (*note The Two Flavors of Variables:
Flavors.).  When you use `+=' on a recursively-expanded variable, it is
this unexpanded text to which `make' appends the new text you specify.

     variable = value
     variable += more

is roughly equivalent to:

     temp = value
     variable = $(temp) more

except that of course it never defines a variable called `temp'.  The
importance of this comes when the variable's old value contains
variable references.  Take this common example:

     CFLAGS = $(includes) -O
     ...
     CFLAGS += -pg # enable profiling

The first line defines the `CFLAGS' variable with a reference to another
variable, `includes'.  (`CFLAGS' is used by the rules for C
compilation; *note Catalogue of Implicit Rules: Catalogue of Rules..)
Using `=' for the definition makes `CFLAGS' a recursively-expanded
variable, meaning `$(includes) -O' is _not_ expanded when `make'
processes the definition of `CFLAGS'.  Thus, `includes' need not be
defined yet for its value to take effect.  It only has to be defined
before any reference to `CFLAGS'.  If we tried to append to the value
of `CFLAGS' without using `+=', we might do it like this:

     CFLAGS := $(CFLAGS) -pg # enable profiling

This is pretty close, but not quite what we want.  Using `:=' redefines
`CFLAGS' as a simply-expanded variable; this means `make' expands the
text `$(CFLAGS) -pg' before setting the variable.  If `includes' is not
yet defined, we get ` -O -pg', and a later definition of `includes'
will have no effect.  Conversely, by using `+=' we set `CFLAGS' to the
_unexpanded_ value `$(includes) -O -pg'.  Thus we preserve the
reference to `includes', so if that variable gets defined at any later
point, a reference like `$(CFLAGS)' still uses its value.


File: make.info,  Node: Override Directive,  Next: Defining,  Prev: Appending,  Up: Using Variables

The `override' Directive
========================

   If a variable has been set with a command argument (*note Overriding
Variables: Overriding.), then ordinary assignments in the makefile are
ignored.  If you want to set the variable in the makefile even though
it was set with a command argument, you can use an `override'
directive, which is a line that looks like this:

     override VARIABLE = VALUE

or

     override VARIABLE := VALUE

   To append more text to a variable defined on the command line, use:

     override VARIABLE += MORE TEXT

*Note Appending More Text to Variables: Appending.

   The `override' directive was not invented for escalation in the war
between makefiles and command arguments.  It was invented so you can
alter and add to values that the user specifies with command arguments.

   For example, suppose you always want the `-g' switch when you run the
C compiler, but you would like to allow the user to specify the other
switches with a command argument just as usual.  You could use this
`override' directive:

     override CFLAGS += -g

   You can also use `override' directives with `define' directives.
This is done as you might expect:

     override define foo
     bar
     endef

*Note Defining Variables Verbatim: Defining.


File: make.info,  Node: Defining,  Next: Environment,  Prev: Override Directive,  Up: Using Variables

Defining Variables Verbatim
===========================

Another way to set the value of a variable is to use the `define'
directive.  This directive has an unusual syntax which allows newline
characters to be included in the value, which is convenient for defining
canned sequences of commands (*note Defining Canned Command Sequences:
Sequences.).

   The `define' directive is followed on the same line by the name of
the variable and nothing more.  The value to give the variable appears
on the following lines.  The end of the value is marked by a line
containing just the word `endef'.  Aside from this difference in
syntax, `define' works just like `=': it creates a recursively-expanded
variable (*note The Two Flavors of Variables: Flavors.).  The variable
name may contain function and variable references, which are expanded
when the directive is read to find the actual variable name to use.

     define two-lines
     echo foo
     echo $(bar)
     endef

   The value in an ordinary assignment cannot contain a newline; but the
newlines that separate the lines of the value in a `define' become part
of the variable's value (except for the final newline which precedes
the `endef' and is not considered part of the value).

   The previous example is functionally equivalent to this:

     two-lines = echo foo; echo $(bar)

since two commands separated by semicolon behave much like two separate
shell commands.  However, note that using two separate lines means
`make' will invoke the shell twice, running an independent subshell for
each line.  *Note Command Execution: Execution.

   If you want variable definitions made with `define' to take
precedence over command-line variable definitions, you can use the
`override' directive together with `define':

     override define two-lines
     foo
     $(bar)
     endef

*Note The `override' Directive: Override Directive.


File: make.info,  Node: Environment,  Next: Target-specific,  Prev: Defining,  Up: Using Variables

Variables from the Environment
==============================

   Variables in `make' can come from the environment in which `make' is
run.  Every environment variable that `make' sees when it starts up is
transformed into a `make' variable with the same name and value.  But
an explicit assignment in the makefile, or with a command argument,
overrides the environment.  (If the `-e' flag is specified, then values
from the environment override assignments in the makefile.  *Note
Summary of Options: Options Summary.  But this is not recommended
practice.)

   Thus, by setting the variable `CFLAGS' in your environment, you can
cause all C compilations in most makefiles to use the compiler switches
you prefer.  This is safe for variables with standard or conventional
meanings because you know that no makefile will use them for other
things.  (But this is not totally reliable; some makefiles set `CFLAGS'
explicitly and therefore are not affected by the value in the
environment.)

   When `make' is invoked recursively, variables defined in the outer
invocation can be passed to inner invocations through the environment
(*note Recursive Use of `make': Recursion.).  By default, only
variables that came from the environment or the command line are passed
to recursive invocations.  You can use the `export' directive to pass
other variables.  *Note Communicating Variables to a Sub-`make':
Variables/Recursion, for full details.

   Other use of variables from the environment is not recommended.  It
is not wise for makefiles to depend for their functioning on
environment variables set up outside their control, since this would
cause different users to get different results from the same makefile.
This is against the whole purpose of most makefiles.

   Such problems would be especially likely with the variable `SHELL',
which is normally present in the environment to specify the user's
choice of interactive shell.  It would be very undesirable for this
choice to affect `make'.  So `make' ignores the environment value of
`SHELL' (except on MS-DOS and MS-Windows, where `SHELL' is usually not
set.  *Note Special handling of SHELL on MS-DOS: Execution.)


File: make.info,  Node: Target-specific,  Next: Pattern-specific,  Prev: Environment,  Up: Using Variables

Target-specific Variable Values
===============================

   Variable values in `make' are usually global; that is, they are the
same regardless of where they are evaluated (unless they're reset, of
course).  One exception to that is automatic variables (*note Automatic
Variables: Automatic.).

   The other exception is "target-specific variable values".  This
feature allows you to define different values for the same variable,
based on the target that `make' is currently building.  As with
automatic variables, these values are only available within the context
of a target's command script (and in other target-specific assignments).

   Set a target-specific variable value like this:

     TARGET ... : VARIABLE-ASSIGNMENT

or like this:

     TARGET ... : override VARIABLE-ASSIGNMENT

   Multiple TARGET values create a target-specific variable value for
each member of the target list individually.

   The VARIABLE-ASSIGNMENT can be any valid form of assignment;
recursive (`='), static (`:='), appending (`+='), or conditional
(`?=').  All variables that appear within the VARIABLE-ASSIGNMENT are
evaluated within the context of the target: thus, any
previously-defined target-specific variable values will be in effect.
Note that this variable is actually distinct from any "global" value:
the two variables do not have to have the same flavor (recursive vs.
static).

   Target-specific variables have the same priority as any other
makefile variable.  Variables provided on the command-line (and in the
environment if the `-e' option is in force) will take precedence.
Specifying the `override' directive will allow the target-specific
variable value to be preferred.

   There is one more special feature of target-specific variables: when
you define a target-specific variable, that variable value is also in
effect for all prerequisites of this target (unless those prerequisites
override it with their own target-specific variable value).  So, for
example, a statement like this:

     prog : CFLAGS = -g
     prog : prog.o foo.o bar.o

will set `CFLAGS' to `-g' in the command script for `prog', but it will
also set `CFLAGS' to `-g' in the command scripts that create `prog.o',
`foo.o', and `bar.o', and any command scripts which create their
prerequisites.


File: make.info,  Node: Pattern-specific,  Prev: Target-specific,  Up: Using Variables

Pattern-specific Variable Values
================================

   In addition to target-specific variable values (*note
Target-specific Variable Values: Target-specific.), GNU `make' supports
pattern-specific variable values.  In this form, a variable is defined
for any target that matches the pattern specified.  Variables defined in
this way are searched after any target-specific variables defined
explicitly for that target, and before target-specific variables defined
for the parent target.

   Set a pattern-specific variable value like this:

     PATTERN ... : VARIABLE-ASSIGNMENT

or like this:

     PATTERN ... : override VARIABLE-ASSIGNMENT

where PATTERN is a %-pattern.  As with target-specific variable values,
multiple PATTERN values create a pattern-specific variable value for
each pattern individually.  The VARIABLE-ASSIGNMENT can be any valid
form of assignment.  Any command-line variable setting will take
precedence, unless `override' is specified.

   For example:

     %.o : CFLAGS = -O

will assign `CFLAGS' the value of `-O' for all targets matching the
pattern `%.o'.


File: make.info,  Node: Conditionals,  Next: Functions,  Prev: Using Variables,  Up: Top

Conditional Parts of Makefiles
******************************

   A "conditional" causes part of a makefile to be obeyed or ignored
depending on the values of variables.  Conditionals can compare the
value of one variable to another, or the value of a variable to a
constant string.  Conditionals control what `make' actually "sees" in
the makefile, so they _cannot_ be used to control shell commands at the
time of execution.

* Menu:

* Conditional Example::         Example of a conditional
* Conditional Syntax::          The syntax of conditionals.
* Testing Flags::               Conditionals that test flags.


File: make.info,  Node: Conditional Example,  Next: Conditional Syntax,  Up: Conditionals

Example of a Conditional
========================

   The following example of a conditional tells `make' to use one set
of libraries if the `CC' variable is `gcc', and a different set of
libraries otherwise.  It works by controlling which of two command
lines will be used as the command for a rule.  The result is that
`CC=gcc' as an argument to `make' changes not only which compiler is
used but also which libraries are linked.

     libs_for_gcc = -lgnu
     normal_libs =
     
     foo: $(objects)
     ifeq ($(CC),gcc)
             $(CC) -o foo $(objects) $(libs_for_gcc)
     else
             $(CC) -o foo $(objects) $(normal_libs)
     endif

   This conditional uses three directives: one `ifeq', one `else' and
one `endif'.

   The `ifeq' directive begins the conditional, and specifies the
condition.  It contains two arguments, separated by a comma and
surrounded by parentheses.  Variable substitution is performed on both
arguments and then they are compared.  The lines of the makefile
following the `ifeq' are obeyed if the two arguments match; otherwise
they are ignored.

   The `else' directive causes the following lines to be obeyed if the
previous conditional failed.  In the example above, this means that the
second alternative linking command is used whenever the first
alternative is not used.  It is optional to have an `else' in a
conditional.

   The `endif' directive ends the conditional.  Every conditional must
end with an `endif'.  Unconditional makefile text follows.

   As this example illustrates, conditionals work at the textual level:
the lines of the conditional are treated as part of the makefile, or
ignored, according to the condition.  This is why the larger syntactic
units of the makefile, such as rules, may cross the beginning or the
end of the conditional.

   When the variable `CC' has the value `gcc', the above example has
this effect:

     foo: $(objects)
             $(CC) -o foo $(objects) $(libs_for_gcc)

When the variable `CC' has any other value, the effect is this:

     foo: $(objects)
             $(CC) -o foo $(objects) $(normal_libs)

   Equivalent results can be obtained in another way by
conditionalizing a variable assignment and then using the variable
unconditionally:

     libs_for_gcc = -lgnu
     normal_libs =
     
     ifeq ($(CC),gcc)
       libs=$(libs_for_gcc)
     else
       libs=$(normal_libs)
     endif
     
     foo: $(objects)
             $(CC) -o foo $(objects) $(libs)


File: make.info,  Node: Conditional Syntax,  Next: Testing Flags,  Prev: Conditional Example,  Up: Conditionals

Syntax of Conditionals
======================

   The syntax of a simple conditional with no `else' is as follows:

     CONDITIONAL-DIRECTIVE
     TEXT-IF-TRUE
     endif

The TEXT-IF-TRUE may be any lines of text, to be considered as part of
the makefile if the condition is true.  If the condition is false, no
text is used instead.

   The syntax of a complex conditional is as follows:

     CONDITIONAL-DIRECTIVE
     TEXT-IF-TRUE
     else
     TEXT-IF-FALSE
     endif

If the condition is true, TEXT-IF-TRUE is used; otherwise,
TEXT-IF-FALSE is used instead.  The TEXT-IF-FALSE can be any number of
lines of text.

   The syntax of the CONDITIONAL-DIRECTIVE is the same whether the
conditional is simple or complex.  There are four different directives
that test different conditions.  Here is a table of them:

`ifeq (ARG1, ARG2)'
`ifeq 'ARG1' 'ARG2''
`ifeq "ARG1" "ARG2"'
`ifeq "ARG1" 'ARG2''
`ifeq 'ARG1' "ARG2"'
     Expand all variable references in ARG1 and ARG2 and compare them.
     If they are identical, the TEXT-IF-TRUE is effective; otherwise,
     the TEXT-IF-FALSE, if any, is effective.

     Often you want to test if a variable has a non-empty value.  When
     the value results from complex expansions of variables and
     functions, expansions you would consider empty may actually
     contain whitespace characters and thus are not seen as empty.
     However, you can use the `strip' function (*note Text Functions::)
     to avoid interpreting whitespace as a non-empty value.  For
     example:

          ifeq ($(strip $(foo)),)
          TEXT-IF-EMPTY
          endif

     will evaluate TEXT-IF-EMPTY even if the expansion of `$(foo)'
     contains whitespace characters.

`ifneq (ARG1, ARG2)'
`ifneq 'ARG1' 'ARG2''
`ifneq "ARG1" "ARG2"'
`ifneq "ARG1" 'ARG2''
`ifneq 'ARG1' "ARG2"'
     Expand all variable references in ARG1 and ARG2 and compare them.
     If they are different, the TEXT-IF-TRUE is effective; otherwise,
     the TEXT-IF-FALSE, if any, is effective.

`ifdef VARIABLE-NAME'
     If the variable VARIABLE-NAME has a non-empty value, the
     TEXT-IF-TRUE is effective; otherwise, the TEXT-IF-FALSE, if any,
     is effective.  Variables that have never been defined have an
     empty value.

     Note that `ifdef' only tests whether a variable has a value.  It
     does not expand the variable to see if that value is nonempty.
     Consequently, tests using `ifdef' return true for all definitions
     except those like `foo ='.  To test for an empty value, use
     `ifeq ($(foo),)'.  For example,

          bar =
          foo = $(bar)
          ifdef foo
          frobozz = yes
          else
          frobozz = no
          endif

     sets `frobozz' to `yes', while:

          foo =
          ifdef foo
          frobozz = yes
          else
          frobozz = no
          endif

     sets `frobozz' to `no'.

`ifndef VARIABLE-NAME'
     If the variable VARIABLE-NAME has an empty value, the TEXT-IF-TRUE
     is effective; otherwise, the TEXT-IF-FALSE, if any, is effective.

   Extra spaces are allowed and ignored at the beginning of the
conditional directive line, but a tab is not allowed.  (If the line
begins with a tab, it will be considered a command for a rule.)  Aside
from this, extra spaces or tabs may be inserted with no effect anywhere
except within the directive name or within an argument.  A comment
starting with `#' may appear at the end of the line.

   The other two directives that play a part in a conditional are `else'
and `endif'.  Each of these directives is written as one word, with no
arguments.  Extra spaces are allowed and ignored at the beginning of the
line, and spaces or tabs at the end.  A comment starting with `#' may
appear at the end of the line.

   Conditionals affect which lines of the makefile `make' uses.  If the
condition is true, `make' reads the lines of the TEXT-IF-TRUE as part
of the makefile; if the condition is false, `make' ignores those lines
completely.  It follows that syntactic units of the makefile, such as
rules, may safely be split across the beginning or the end of the
conditional.

   `make' evaluates conditionals when it reads a makefile.
Consequently, you cannot use automatic variables in the tests of
conditionals because they are not defined until commands are run (*note
Automatic Variables: Automatic.).

   To prevent intolerable confusion, it is not permitted to start a
conditional in one makefile and end it in another.  However, you may
write an `include' directive within a conditional, provided you do not
attempt to terminate the conditional inside the included file.


File: make.info,  Node: Testing Flags,  Prev: Conditional Syntax,  Up: Conditionals

Conditionals that Test Flags
============================

   You can write a conditional that tests `make' command flags such as
`-t' by using the variable `MAKEFLAGS' together with the `findstring'
function (*note Functions for String Substitution and Analysis: Text
Functions.).  This is useful when `touch' is not enough to make a file
appear up to date.

   The `findstring' function determines whether one string appears as a
substring of another.  If you want to test for the `-t' flag, use `t'
as the first string and the value of `MAKEFLAGS' as the other.

   For example, here is how to arrange to use `ranlib -t' to finish
marking an archive file up to date:

     archive.a: ...
     ifneq (,$(findstring t,$(MAKEFLAGS)))
             +touch archive.a
             +ranlib -t archive.a
     else
             ranlib archive.a
     endif

The `+' prefix marks those command lines as "recursive" so that they
will be executed despite use of the `-t' flag.  *Note Recursive Use of
`make': Recursion.


File: make.info,  Node: Functions,  Next: Running,  Prev: Conditionals,  Up: Top

Functions for Transforming Text
*******************************

   "Functions" allow you to do text processing in the makefile to
compute the files to operate on or the commands to use.  You use a
function in a "function call", where you give the name of the function
and some text (the "arguments") for the function to operate on.  The
result of the function's processing is substituted into the makefile at
the point of the call, just as a variable might be substituted.

* Menu:

* Syntax of Functions::         How to write a function call.
* Text Functions::              General-purpose text manipulation functions.
* File Name Functions::         Functions for manipulating file names.
* Foreach Function::            Repeat some text with controlled variation.
* If Function::                 Conditionally expand a value.
* Call Function::               Expand a user-defined function.
* Origin Function::             Find where a variable got its value.
* Shell Function::              Substitute the output of a shell command.
* Make Control Functions::      Functions that control how make runs.


File: make.info,  Node: Syntax of Functions,  Next: Text Functions,  Up: Functions

Function Call Syntax
====================

   A function call resembles a variable reference.  It looks like this:

     $(FUNCTION ARGUMENTS)

or like this:

     ${FUNCTION ARGUMENTS}

   Here FUNCTION is a function name; one of a short list of names that
are part of `make'.  You can also essentially create your own functions
by using the `call' builtin function.

   The ARGUMENTS are the arguments of the function.  They are separated
from the function name by one or more spaces or tabs, and if there is
more than one argument, then they are separated by commas.  Such
whitespace and commas are not part of an argument's value.  The
delimiters which you use to surround the function call, whether
parentheses or braces, can appear in an argument only in matching pairs;
the other kind of delimiters may appear singly.  If the arguments
themselves contain other function calls or variable references, it is
wisest to use the same kind of delimiters for all the references; write
`$(subst a,b,$(x))', not `$(subst a,b,${x})'.  This is because it is
clearer, and because only one type of delimiter is matched to find the
end of the reference.

   The text written for each argument is processed by substitution of
variables and function calls to produce the argument value, which is
the text on which the function acts.  The substitution is done in the
order in which the arguments appear.

   Commas and unmatched parentheses or braces cannot appear in the text
of an argument as written; leading spaces cannot appear in the text of
the first argument as written.  These characters can be put into the
argument value by variable substitution.  First define variables
`comma' and `space' whose values are isolated comma and space
characters, then substitute these variables where such characters are
wanted, like this:

     comma:= ,
     empty:=
     space:= $(empty) $(empty)
     foo:= a b c
     bar:= $(subst $(space),$(comma),$(foo))
     # bar is now `a,b,c'.

Here the `subst' function replaces each space with a comma, through the
value of `foo', and substitutes the result.


File: make.info,  Node: Text Functions,  Next: File Name Functions,  Prev: Syntax of Functions,  Up: Functions

Functions for String Substitution and Analysis
==============================================

   Here are some functions that operate on strings:

`$(subst FROM,TO,TEXT)'
     Performs a textual replacement on the text TEXT: each occurrence
     of FROM is replaced by TO.  The result is substituted for the
     function call.  For example,

          $(subst ee,EE,feet on the street)

     substitutes the string `fEEt on the strEEt'.

`$(patsubst PATTERN,REPLACEMENT,TEXT)'
     Finds whitespace-separated words in TEXT that match PATTERN and
     replaces them with REPLACEMENT.  Here PATTERN may contain a `%'
     which acts as a wildcard, matching any number of any characters
     within a word.  If REPLACEMENT also contains a `%', the `%' is
     replaced by the text that matched the `%' in PATTERN.

     `%' characters in `patsubst' function invocations 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 file names or has a
     stem substituted into it.  Backslashes that are not in danger of
     quoting `%' characters go unmolested.  For example, the pattern
     `the\%weird\\%pattern\\' has `the%weird\' preceding the operative
     `%' character, and `pattern\\' following it.  The final two
     backslashes are left alone because they cannot affect any `%'
     character.

     Whitespace between words is folded into single space characters;
     leading and trailing whitespace is discarded.

     For example,

          $(patsubst %.c,%.o,x.c.c bar.c)

     produces the value `x.c.o bar.o'.

     Substitution references (*note Substitution References:
     Substitution Refs.) are a simpler way to get the effect of the
     `patsubst' function:

          $(VAR:PATTERN=REPLACEMENT)

     is equivalent to

          $(patsubst PATTERN,REPLACEMENT,$(VAR))

     The second shorthand simplifies one of the most common uses of
     `patsubst': replacing the suffix at the end of file names.

          $(VAR:SUFFIX=REPLACEMENT)

     is equivalent to

          $(patsubst %SUFFIX,%REPLACEMENT,$(VAR))

     For example, you might have a list of object files:

          objects = foo.o bar.o baz.o

     To get the list of corresponding source files, you could simply
     write:

          $(objects:.o=.c)

     instead of using the general form:

          $(patsubst %.o,%.c,$(objects))

`$(strip STRING)'
     Removes leading and trailing whitespace from STRING and replaces
     each internal sequence of one or more whitespace characters with a
     single space.  Thus, `$(strip a b  c )' results in `a b c'.

     The function `strip' can be very useful when used in conjunction
     with conditionals.  When comparing something with the empty string
     `' using `ifeq' or `ifneq', you usually want a string of just
     whitespace to match the empty string (*note Conditionals::).

     Thus, the following may fail to have the desired results:

          .PHONY: all
          ifneq   "$(needs_made)" ""
          all: $(needs_made)
          else
          all:;@echo 'Nothing to make!'
          endif

     Replacing the variable reference `$(needs_made)' with the function
     call `$(strip $(needs_made))' in the `ifneq' directive would make
     it more robust.

`$(findstring FIND,IN)'
     Searches IN for an occurrence of FIND.  If it occurs, the value is
     FIND; otherwise, the value is empty.  You can use this function in
     a conditional to test for the presence of a specific substring in
     a given string.  Thus, the two examples,

          $(findstring a,a b c)
          $(findstring a,b c)

     produce the values `a' and `' (the empty string), respectively.
     *Note Testing Flags::, for a practical application of `findstring'.

`$(filter PATTERN...,TEXT)'
     Returns all whitespace-separated words in TEXT that _do_ match any
     of the PATTERN words, removing any words that _do not_ match.  The
     patterns are written using `%', just like the patterns used in the
     `patsubst' function above.

     The `filter' function can be used to separate out different types
     of strings (such as file names) in a variable.  For example:

          sources := foo.c bar.c baz.s ugh.h
          foo: $(sources)
                  cc $(filter %.c %.s,$(sources)) -o foo

     says that `foo' depends of `foo.c', `bar.c', `baz.s' and `ugh.h'
     but only `foo.c', `bar.c' and `baz.s' should be specified in the
     command to the compiler.

`$(filter-out PATTERN...,TEXT)'
     Returns all whitespace-separated words in TEXT that _do not_ match
     any of the PATTERN words, removing the words that _do_ match one
     or more.  This is the exact opposite of the `filter' function.

     Removes all whitespace-separated words in TEXT that _do_ match the
     PATTERN words, returning only the words that _do not_ match.  This
     is the exact opposite of the `filter' function.

     For example, given:

          objects=main1.o foo.o main2.o bar.o
          mains=main1.o main2.o

     the following generates a list which contains all the object files
     not in `mains':

          $(filter-out $(mains),$(objects))

`$(sort LIST)'
     Sorts the words of LIST in lexical order, removing duplicate
     words.  The output is a list of words separated by single spaces.
     Thus,

          $(sort foo bar lose)

     returns the value `bar foo lose'.

     Incidentally, since `sort' removes duplicate words, you can use it
     for this purpose even if you don't care about the sort order.

   Here is a realistic example of the use of `subst' and `patsubst'.
Suppose that a makefile uses the `VPATH' variable to specify a list of
directories that `make' should search for prerequisite files (*note
`VPATH' Search Path for All Prerequisites: General Search.).  This
example shows how to tell the C compiler to search for header files in
the same list of directories.

   The value of `VPATH' is a list of directories separated by colons,
such as `src:../headers'.  First, the `subst' function is used to
change the colons to spaces:

     $(subst :, ,$(VPATH))

This produces `src ../headers'.  Then `patsubst' is used to turn each
directory name into a `-I' flag.  These can be added to the value of
the variable `CFLAGS', which is passed automatically to the C compiler,
like this:

     override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))

The effect is to append the text `-Isrc -I../headers' to the previously
given value of `CFLAGS'.  The `override' directive is used so that the
new value is assigned even if the previous value of `CFLAGS' was
specified with a command argument (*note The `override' Directive:
Override Directive.).

