16.4. Macros

 < Day Day Up > 

This section summarizes creating and using macros , internal macros, macro modifiers, macros with special handling, and text manipulation with macros and functions.

16.4.1. Creating and Using Macros

Macros (often called variables) are like variables in a programming language. In make, they are most similar to variables in the shell language, having string values that can be assigned, referenced, and compared.

16.4.1.1. Defining macros

GNU make provides multiple ways to define macros. The different mechanisms affect how make treats the value being assigned. This in turn affects how the value is treated when the macro's value is retrieved, or referenced. GNU make defines two types of variables, called recursively expanded variables and simply expanded variables, respectively. The various macro assignment forms are as follows:


name = value

Create a recursively expanded variable. The value of name is the verbatim text on the right side of the =. If this value contains any references to other variable values, those values are retrieved and expanded when the original variable is referenced. For example:

     bar = v1     foo = $(bar)            Value of bar retrieved when foo's value is referenced     ...     x = $(foo)              x is assigned 'v1'     bar = v2     y = $(foo)              y is assigned 'v2' 


name := value

Create a simply expanded variable. The value is expanded completely, immediately at the time of the assignment. Any variable references in value are expanded then and there. For example:

     bar = v1     foo := $(bar)           foo is assigned 'v1'     x = $(foo)              x is assigned 'v1'     bar = v2     y = $(foo)              y is still assigned 'v1' 

A significant advantage of simply expanded variables is that they work like variables in most programming languages, allowing you to use their values in assignments to themselves:

     x := $(x) other stuff 


name += value

Append value to the contents of variable name. If name was never defined, += acts like =, creating a recursively defined variable. Otherwise, the result of += depends upon the type of name. If name was defined with =, then value is appended literally to the contents of name. However, if name was defined with :=, then make completely expands value before appending it to the contents of name.


name ?= value

Create recursively expanded variable name with value value only if name is not defined. Note that a variable that has been given an empty value is still considered to be defined.


define name


...


endef

Define a recursively expanded variable, similar to =. However, using define, you can give a macro a value that contains one or more newlines. This is not possible with the other assignment forms (=, :=, +=, ?=).

16.4.1.2. Macro values

Macro values are retrieved by prefixing the macro name with a $. A plain $ is enough for macros whose names are a single character, such as $< and $@. However, macro names of two or more characters must be enclosed in parentheses and preceded by a $. For example, $(CC), $(CPP), and so on.

Although it was not documented, the original V7 Unix version of make allowed the use of curly braces instead of parentheses: ${CC}, ${RM}, and so on.[*] All Unix versions and GNU make support this as well, and it is included in POSIX. This usage was particularly common in makefiles in the BSD distributions. There is no real reason to prefer one over the other, although long-time Unix programmers may prefer the parentheses form, since that is what was originally documented.

[*] See the function subst( ) in http://minnie.tuhs.org/UnixTree/V7/usr/src/cmd/make/misc.c.html.

16.4.1.3. Exporting macros

By default, make exports variables to subprocesses only if those variables were already in the environment or if they were defined on the command line. Furthermore, only variables whose names contain just letters, digits, and underscores are exported, as many shells cannot handle environment variables with punctuation characters in their names. You can use the export directive to control exporting of specific variables, or all variables. The unexport directive indicates that a particular variable should not be exported; it cancels the effect of a previous export command. The command forms are as follows:


export

By itself, the export directive causes make to export all alphanumerically named variables to the environment (where underscore counts as a letter too).


export var

Export variable var to the environment. The variable will be exported even if its name contains nonalphanumeric characters.


export var = value


export var := value


export var += value


export var ? value

Perform the kind of assignment indicated by the given operator (as described earlier), and then export the variable to the environment.


unexport var

Do not export variable var to the environment. Cancels a previous export of var (for example, from a separate, included makefile).

16.4.1.4. Overriding command-line macros

Normally, when a macro is defined on the command line, the given value is used, and any value assigned to the macro within the makefile is ignored. Occasionally, you may wish to force a variable to have a certain value, or to append a value to a variable, no matter what value was given on the command line. This is the job of the override directive.


override var = value


override var := value


override var += value


override var ? value


override define name


...


endef

Perform the kind of assignment indicated by the given operator (as described earlier), and then export the variable to the environment.

The example given in the GNU make documentation, GNU Make: A Program for Directing Recompilation, is forcing CFLAGS to always contain the -g option:

     override CFLAGS += -g 

16.4.2. Internal Macros

$?

The list of prerequisites that have been changed more recently than the current target. Can be used only in normal makefile entries not suffix rules.

$@

The name of the current target, except in makefile entries for making libraries, where it becomes the library name. (For libguide.a(dontpanic.o), $@ is libguide.a). Can be used both in normal makefile entries and in suffix rules.

$$@

The name of the current target. Can be used only to the right of the colon in dependency lines. This is provided only for compatibility with System V make; its use is not recommended.

$<

The name of the current prerequisite that has been modified more recently than the current target.

$*

The name without the suffix of the current prerequisite that has been modified more recently than the current target. Should be used only in implicit rules or static pattern rules.

$%

The name of the corresponding .o file when the current target is a library module. (For libguide.a(dontpanic.o), $% is dontpanic.o). Can be used both in normal makefile entries and in suffix rules.

$^

The list of prerequisites for the current target. For archive members, only the member name is listed. Even if a prerequisite appears multiple times in a dependency list for a target, it only appears once in the value of $^.

$+

Like $^, but prerequisites that appear multiple times in a dependency list for a target are repeated. This is most useful for libraries, since multiple dependencies upon a library can make sense and be useful.

$$

A literal $ for use in rule command lines: for example, when referencing shell variables in the environment or within a loop.

$|

The order-only prerequisites for the current target.


16.4.3. Macro Modifiers

Macro modifiers may be applied to the built-in internal macros listed earlier, except for $$.


D

The directory portion of any internal macro name. Valid uses are:

     $(%D)     $(@D)     $(*D)     $$(@D)     $(<D)     $(^D)     $(?D)     @(+D) 


F

The file portion of any internal macro name. Valid uses are:

     $(%F)     $(@F)     $(*F)     $$(@F)     $(<F)     $(^F)     $(?F)     @(+F) 

16.4.4. Macros with Special Handling

CURDIR

The current working directory. Set by make but not used by it, for use in makefiles.

.LIBPATTERNS

Used for finding link library names as prerequisites of the form -lname. For each such prerequisite, make searches in the current directory, directories matching any vpath directives, directories named by the VPATH variable, /lib, /usr/lib, and prefix/lib, where prefix is the installation directory for GNU make (normally /usr/local).

The default value of .LIBPATTERNS is lib%.so lib%.a. Thus make first searches for a shared library file, and then for a regular archive library.

MAKE

The full pathname used to invoke make. It is special because command lines containing the string $(MAKE) or ${MAKE} are always executed, even when any of the -n, -q, or -t options are used.

MAKECMDGOALS

The targets given to make on the command line.

MAKEFILE_LIST

A list of makefiles read so far. The rightmost entry in the list is the name of the makefile currently being read.

MAKEFILES

Environment variable: make reads the whitespace-separated list of files named in it before reading any other makefiles.

MAKEFLAGS

Contains the flags inherited in the environment variable MAKEFLAGS, plus any command-line options. Used to pass the flags to subsequent invocations of make, usually via command lines in a makefile entry that contain $(MAKE).

MAKELEVEL

The depth of recursion (sub-make invocation). Primarily for use in conditional statements so that a makefile can act in one way as the top-level makefile and in another way if invoked by another make.

OVERRIDES

A list of the command-line variable definitions. MAKEFLAGS refers to this variable. By setting it to the empty string:

     MAKEOVERRIDES =

You can pass down the command-line options to sub-makes but avoid passing down the variable assignments.

MAKESHELL

For MS-DOS only, the shell make should use for running commands.

MFLAGS

Similar to MAKEFLAGS, this variable is set for compatibility with other versions of make. It contains the same options as in MAKEFLAGS, but not the variable settings. It was designed for explicit use on command lines that invoke make. For example:

     mylib:             cd mylib && $(MAKE) $(MFLAGS)

The use of MAKEFLAGS is preferred.

SHELL

Sets the shell that interprets commands. If this macro isn't defined, the default is /bin/sh. On MS-DOS, if SHELL not set, the value of COMSPEC is used; see also the MAKESHELL variable, earlier in this list.

SUFFIXES

The default list of suffixes, before make reads and processes makefiles.

.VARIABLES

A list of all variables defined in all makefiles read up to the point that this variable is referenced.

VPATH

Specifies a list of directories to search for prerequisites when not found in the current directory. Directories in the list should be separated with spaces or colons.


16.4.5. Text Manipulation with Macros and Functions

Standard versions of make provide a limited text manipulation facility:


$( macro: s1= s2)

Evaluates to the current definition of $(macro), after substituting the string s2 for every occurrence of s1 that occurs either immediately before a blank or tab, or at the end of the macro definition.

GNU make supports this for compatibility with Unix make and the POSIX standard. However, GNU make goes far beyond simple text substitution, providing a host of functions for text manipulation. The following list provides a brief description of each function.


$(addprefix prefix, names ...)

Generates a new list, created by prepending prefix to each of the names.


$(addsuffix suffix, names ...)

Generates a new list, created by appending suffix to each of the names.


$(basename names ...)

Returns a list of the basename of each of the names. The basename is the text up to but not including the final period.


$(call var, param, ...)

The call function allows you to treat the value of a variable as a procedure. var is the name of a variable, not a variable reference. The params are assigned to temporary variables that may be referenced as $(1), $(2), and so on. $(0) will be the name of the variable. The value of var should reference the temporary values. The result of call is the result of evaluating var in this way. If var names a built-in function, that function is always called, even if a make variable of the same name exists. Finally, call may be used recursively; each invocation gets its own $(1), $(2), and so on.


$(dir names ...)

Returns a list of the directory part of each of the names. The directory part is all text, up to and including the final / character. If there is no /, the two characters ./ are used.


$(error text ...)

Causes make to produce a fatal error message consisting of text.


$(filter pattern ..., text)

Chooses the words in text that match any pattern. Patterns are written using %, as for the patsubst function.


$(filter-out pattern ..., text)

Like filter, but selects the words that do not match the patterns.


$(findstring find, text)

Searches text for an instance of find. If found, the result is find; otherwise, it's the empty string.


$(firstword names ...)

Returns the first word in names.


$(foreach var, words, text)

This function is similar to the for loop in the shell. It expands var and words, first. The result of expanding var names a macro. make then loops, setting var to each word in words, and then evaluating text. The result is the concatenation of all the iterations. The text should contain a reference to the variable for this to work correctly.

If var is defined before the foreach is evaluated, it maintains the same value it had after the evaluation. If it was undefined before the foreach, it remains undefined afterwords. In effect, foreach creates a temporary, private variable named var.


$(if condition, then-text[, else-text])

The condition is evaluated. If, after removing leading and trailing whitespace, the result is not empty, the condition is considered to be true, and the result of if is the expansion of the then-text. Otherwise, the condition is considered to be false, and the result is the expansion of else-text, if any. If there's no else-text, then a false condition produces the empty string. Only one or the other of then-text and else-text is evaluated.


$(join list1, list2)

Produces a new list where the first element is the concatenation of the first elements in list1 and list2, the second element is the concatenation of the second elements in list1 and list2, and so on.


$(notdir names ...)

Returns a list of the nondirectory part of each of the names. The nondirectory part is all the text after the final /, if any. If not, it's the entire name.


$(origin variable)

Returns a string describing the origin of variable. Here, variable is a variable name (foo), not a variable reference ($(foo)). Possible return values are one of the following:

automatic

The variable is an automatic variable for use in the commands of rules, such as $* and $@.

command line

The variable was defined on the command line.

default

The variable is one of those defined by make's built-in rules, such as CC.

environment

The variable was defined in the environment, and -e was not used.

environment override

The variable was defined in the environment, and -e was used.

file

The variable was defined in a makefile.

override

The variable was defined with an override command. See the earlier section "Overriding command-line macros."

undefined

The variable was never given a value.



$(patsubst pattern, replacement, text)

Replaces words in text that match pattern with replacement. The pattern should use a % as a wildcard character. In replacement, a % acts as the placeholder for the text that matched the % in pattern. This is a general form of string substitution. For example, the traditional OBJS = $(SRCS:.c=.o) could instead be written OBJS = $(patsubst %.c, %.o, $(SRCS)).


$(shell command)

Runs the shell command command and returns the output. make converts newlines in the output into spaces and removes trailing newlines. This is similar to '...' in the shell.


$(sort list)

Returns a sorted copy of the words in list, with duplicates removed. Each word is separated from the next by a single space.


$(subst from, to, text)

Replaces every instance of from in text with to.


$(suffix names ...)

Returns a list of the suffixes of each name. The suffix is the final period and any following text. Returns an empty string for a name without a period.


$(strip string)

Removes leading and trailing whitespace from string and converts internal runs of whitespace into single spaces. This is especially useful in conjunction with conditionals.


$(warning text ...)

Causes make to produce a warning message consisting of text.


$(wildcard pattern ...)

Creates a space-separated list of filenames that match the shell pattern pattern. (Note! Not a make-style % pattern.)


$(word n, text)

Returns the nth word of text, counting from one.


$(wordlist start, end, text)

Creates a new list consisting of the words start to end in text. Counting starts at one.


$(words text)

Returns the number of words in text.

     < Day Day Up > 


    Unix in a Nutshell
    Unix in a Nutshell, Fourth Edition
    ISBN: 0596100299
    EAN: 2147483647
    Year: 2005
    Pages: 201

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net