Sometimes one might need to run the preprocessor on some source file. Usually it is a bad idea, as you typically need to compile your project, not merely run the preprocessor on it; therefore you certainly want to run the compiler, not the preprocessor. Resist the temptation of following the easiest path.
Nevertheless, if you need to run the preprocessor, then use
AC_PREPROC_IFELSE
.
The macros described in this section cannot be used for tests in Erlang, Fortran, or Go, since those languages require no preprocessor.
Run the preprocessor of the current language (see Language Choice)
on the input, run the shell commands action-if-true on
success, action-if-false otherwise. The input can be made
by AC_LANG_PROGRAM
and friends.
This macro uses CPPFLAGS
, but not CFLAGS
, because
-g, -O, etc. are not valid options to many C
preprocessors.
It is customary to report unexpected failures with
AC_MSG_FAILURE
. If needed, action-if-true can further access
the preprocessed output in the file conftest.i.
For instance:
AC_INIT([Hello], [1.0]<EMAIL_ADDRESS>AC_DEFINE([HELLO_WORLD], ["Hello, World\n"], [Greetings string.]) AC_PREPROC_IFELSE( [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]], [[fputs (hw, stdout);]])], [AC_MSG_RESULT([OK])], [AC_MSG_FAILURE([unexpected preprocessor failure])])
might result in:
checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether the compiler supports GNU C... yes checking whether gcc accepts -g... yes checking for gcc option to enable C11 features... -std=gnu11 checking how to run the C preprocessor... gcc -std=gnu11 -E OK
The macro AC_TRY_CPP
(see Obsolete Macros) used to play the
role of AC_PREPROC_IFELSE
, but double quotes its argument, making
it impossible to use it to elaborate sources. You are encouraged to
get rid of your old use of the macro AC_TRY_CPP
in favor of
AC_PREPROC_IFELSE
, but, in the first place, are you sure you need
to run the preprocessor and not the compiler?
If the output of running the preprocessor on the system header file header-file matches the extended regular expression pattern, execute shell commands action-if-found, otherwise execute action-if-not-found.
See below for some problems involving this macro.
program is the text of a C or C++ program, on which shell variable, back quote, and backslash substitutions are performed. If the output of running the preprocessor on program matches the extended regular expression pattern, execute shell commands action-if-found, otherwise execute action-if-not-found.
See below for some problems involving this macro.
AC_EGREP_CPP
and AC_EGREP_HEADER
should be used with care,
as preprocessors can insert line breaks between output tokens. For
example, the preprocessor might transform this:
#define MAJOR 2 #define MINOR 23 Version MAJOR . MINOR
into this:
Version 2 . 23
Because preprocessors are allowed to insert white space, change escapes
in string contants, insert backlash-newline pairs, or do any of a number
of things that do not change the meaning of the preprocessed program, it
is better to rely on AC_PREPROC_IFELSE
than to resort to
AC_EGREP_CPP
or AC_EGREP_HEADER
.
Next: Running the Linker, Previous: Running the Preprocessor, Up: Writing Tests [Contents][Index]
To check for a syntax feature of the current language’s (see Language Choice) compiler, such as whether it recognizes a certain keyword, or
simply to try some library feature, use AC_COMPILE_IFELSE
to try
to compile a small program that uses that feature.
Run the compiler and compilation flags of the current language
(see Language Choice) on the input, run the shell commands
action-if-true on success, action-if-false otherwise. The
input can be made by AC_LANG_PROGRAM
and friends.
It is customary to report unexpected failures with
AC_MSG_FAILURE
. This macro does not try to link; use
AC_LINK_IFELSE
if you need to do that (see Running the Linker). If needed, action-if-true can further access the
just-compiled object file conftest.$OBJEXT.
This macro uses AC_REQUIRE
for the compiler associated with the
current language, which means that if the compiler has not yet been
determined, the compiler determination will be made prior to the body of
the outermost AC_DEFUN
macro that triggered this macro to
expand (see Expanded Before Required).
For tests in Erlang, the input must be the source code of a module named
conftest
. AC_COMPILE_IFELSE
generates a conftest.beam
file that can be interpreted by the Erlang virtual machine (ERL
). It is
recommended to use AC_LANG_PROGRAM
to specify the test program,
to ensure that the Erlang module has the right name.
Next: Checking Runtime Behavior, Previous: Running the Compiler, Up: Writing Tests [Contents][Index]
To check for a library, a function, or a global variable, Autoconf
configure
scripts try to compile and link a small program that
uses it. This is unlike Metaconfig, which by default uses nm
or
ar
on the C library to try to figure out which functions are
available. Trying to link with the function is usually a more reliable
approach because it avoids dealing with the variations in the options
and output formats of nm
and ar
and in the location of the
standard libraries. It also allows configuring for cross-compilation or
checking a function’s runtime behavior if needed. On the other hand,
it can be slower than scanning the libraries once, but accuracy is more
important than speed.
AC_LINK_IFELSE
is used to compile test programs to test for
functions and global variables. It is also used by AC_CHECK_LIB
to check for libraries (see Library Files), by adding the library being
checked for to LIBS
temporarily and trying to link a small
program.
Run the compiler (and compilation flags) and the linker of the current
language (see Language Choice) on the input, run the shell
commands action-if-true on success, action-if-false
otherwise. The input can be made by AC_LANG_PROGRAM
and
friends. If needed, action-if-true can further access the
just-linked program file conftest$EXEEXT.
LDFLAGS
and LIBS
are used for linking, in addition to the
current compilation flags.
It is customary to report unexpected failures with
AC_MSG_FAILURE
. This macro does not try to execute the program;
use AC_RUN_IFELSE
if you need to do that (see Checking Runtime Behavior).
The AC_LINK_IFELSE
macro cannot be used for Erlang tests, since Erlang
programs are interpreted and do not require linking.
Next: Systemology, Previous: Running the Linker, Up: Writing Tests [Contents][Index]
Sometimes you need to find out how a system performs at runtime, such as whether a given function has a certain capability or bug. If you can, make such checks when your program runs instead of when it is configured. You can check for things like the machine’s endianness when your program initializes itself.
If you really need to test for a runtime behavior while configuring,
you can write a test program to determine the result, and compile and
run it using AC_RUN_IFELSE
. Avoid running test programs if
possible, because this prevents people from configuring your package for
cross-compiling.
Run the compiler (and compilation flags) and the linker of the current language (see Language Choice) on the input, then execute the resulting program. If the program returns an exit status of 0 when executed, run shell commands action-if-true. Otherwise, run shell commands action-if-false.
The input can be made by AC_LANG_PROGRAM
and friends.
LDFLAGS
and LIBS
are used for linking, in addition to the
compilation flags of the current language (see Language Choice).
Additionally, action-if-true can run ./conftest$EXEEXT
for further testing.
In the action-if-false section, the failing exit status is available in the shell variable ‘$?’. This exit status might be that of a failed compilation, or it might be that of a failed program execution.
If cross-compilation mode is enabled (this is the case if either the
compiler being used does not produce executables that run on the system
where configure
is being run, or if the options --build
and --host
were both specified and their values are different),
then the test program is
not run. If the optional shell commands action-if-cross-compiling
are given, those commands are run instead; typically these commands
provide pessimistic defaults that allow cross-compilation to work even
if the guess was wrong. If the fourth argument is empty or omitted, but
cross-compilation is detected, then configure
prints an error
message and exits. If you want your package to be useful in a
cross-compilation scenario, you should provide a non-empty
action-if-cross-compiling clause, as well as wrap the
AC_RUN_IFELSE
compilation inside an AC_CACHE_CHECK
(see Caching Results) which allows the user to override the
pessimistic default if needed.
It is customary to report unexpected failures with
AC_MSG_FAILURE
.
autoconf
prints a warning message when creating
configure
each time it encounters a call to
AC_RUN_IFELSE
with no action-if-cross-compiling argument
given. If you are not concerned about users configuring your package
for cross-compilation, you may ignore the warning. A few of the macros
distributed with Autoconf produce this warning message; but if this is a
problem for you, please report it as a bug, along with an appropriate
pessimistic guess to use instead.
To configure for cross-compiling you can also choose a value for those parameters based on the canonical system name (see Manual Configuration). Alternatively, set up a test results cache file with the correct values for the host system (see Caching Results).
To provide a default for calls of AC_RUN_IFELSE
that are embedded
in other macros, including a few of the ones that come with Autoconf,
you can test whether the shell variable cross_compiling
is set to
‘yes’, and then use an alternate method to get the results instead
of calling the macros.
It is also permissible to temporarily assign to cross_compiling
in order to force tests to behave as though they are in a
cross-compilation environment, particularly since this provides a way to
test your action-if-cross-compiling even when you are not using a
cross-compiler.
# We temporarily set cross-compile mode to force AC_COMPUTE_INT # to use the slow link-only method save_cross_compiling=$cross_compiling cross_compiling=yes AC_COMPUTE_INT([…]) cross_compiling=$save_cross_compiling
A C or C++ runtime test should be portable. See Portable C and C++ Programming.
Erlang tests must exit themselves the Erlang VM by calling the halt/1
function: the given status code is used to determine the success of the test
(status is 0
) or its failure (status is different than 0
), as
explained above. It must be noted that data output through the standard output
(e.g., using io:format/2
) may be truncated when halting the VM.
Therefore, if a test must output configuration information, it is recommended
to create and to output data into the temporary file named conftest.out,
using the functions of module file
. The conftest.out
file is
automatically deleted by the AC_RUN_IFELSE
macro. For instance, a
simplified implementation of Autoconf’s AC_ERLANG_SUBST_LIB_DIR
macro is:
AC_INIT([LibdirTest], [1.0]<EMAIL_ADDRESS>AC_ERLANG_NEED_ERL AC_LANG(Erlang) AC_RUN_IFELSE( [AC_LANG_PROGRAM([], [dnl file:write_file("conftest.out", code:lib_dir()), halt(0)])], [echo "code:lib_dir() returned: `cat conftest.out`"], [AC_MSG_FAILURE([test Erlang program execution failed])])
Next: Multiple Cases, Previous: Checking Runtime Behavior, Up: Writing Tests [Contents][Index]
This section aims at presenting some systems and pointers to documentation. It may help you addressing particular problems reported by users.
Posix-conforming systems are derived from the Unix operating system.
The Rosetta Stone for Unix contains a table correlating the features of various Posix-conforming systems. Unix History is a simplified diagram of how many Unix systems were derived from each other.
The Heirloom Project provides some variants of traditional implementations of Unix utilities.
Darwin is also known as Mac OS X. Beware that the file system can be case-preserving, but case insensitive. This can cause nasty problems, since for instance the installation attempt for a package having an INSTALL file can result in ‘make install’ report that nothing was to be done!
That’s all dependent on whether the file system is a UFS (case sensitive) or HFS+ (case preserving). By default Apple wants you to install the OS on HFS+. Unfortunately, there are some pieces of software which really need to be built on UFS. We may want to rebuild Darwin to have both UFS and HFS+ available (and put the /local/build tree on the UFS).
QNX is a realtime operating system running on Intel architecture meant to be scalable from the small embedded systems to the hundred processor super-computer. It claims to be Posix certified. More information is available on the QNX home page.
Officially this was called the “Seventh Edition” of “the UNIX time-sharing system” but we use the more-common name “Unix version 7”. Documentation is available in the Unix Seventh Edition Manual. Previous versions of Unix are called “Unix version 6”, etc., but they were not as widely used.
Previous: Systemology, Up: Writing Tests [Contents][Index]
Some operations are accomplished in several possible ways, depending on the OS variant. Checking for them essentially requires a “case statement”. Autoconf does not directly provide one; however, it is easy to simulate by using a shell variable to keep track of whether a way to perform the operation has been found yet.
Here is an example that uses the shell variable fstype
to keep
track of whether the remaining cases need to be checked. Note that
since the value of fstype
is under our control, we don’t have to
use the longer ‘test "x$fstype" = xno’.
AC_MSG_CHECKING([how to get file system type]) fstype=no # The order of these tests is important. AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h> #include <sys/fstyp.h>]])], [AC_DEFINE([FSTYPE_STATVFS], [1], [Define if statvfs exists.]) fstype=SVR4]) if test $fstype = no; then AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h> #include <sys/fstyp.h>]])], [AC_DEFINE([FSTYPE_USG_STATFS], [1], [Define if USG statfs.]) fstype=SVR3]) fi if test $fstype = no; then AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h> #include <sys/vmount.h>]])]), [AC_DEFINE([FSTYPE_AIX_STATFS], [1], [Define if AIX statfs.]) fstype=AIX]) fi # (more cases omitted here) AC_MSG_RESULT([$fstype])
Next: Programming in M4, Previous: Writing Tests, Up: Autoconf [Contents][Index]
Once configure
has determined whether a feature exists, what can
it do to record that information? There are four sorts of things it can
do: define a C preprocessor symbol, set a variable in the output files,
save the result in a cache file for future configure
runs, and
print a message letting the user know the result of the test.
Next: Setting Output Variables, Up: Results of Tests [Contents][Index]
A common action to take in response to a feature test is to define a C
preprocessor symbol indicating the results of the test. That is done by
calling AC_DEFINE
or AC_DEFINE_UNQUOTED
.
By default, AC_OUTPUT
places the symbols defined by these macros
into the output variable DEFS
, which contains an option
-Dsymbol=value for each symbol defined. Unlike in
Autoconf version 1, there is no variable DEFS
defined while
configure
is running. To check whether Autoconf macros have
already defined a certain C preprocessor symbol, test the value of the
appropriate cache variable, as in this example:
AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1], [Define if vprintf exists.])]) if test "x$ac_cv_func_vprintf" != xyes; then AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1], [Define if _doprnt exists.])]) fi
If AC_CONFIG_HEADERS
has been called, then instead of creating
DEFS
, AC_OUTPUT
creates a header file by substituting the
correct values into #define
statements in a template file.
See Configuration Header Files, for more information about this kind of
output.
Define variable to value (verbatim), by defining a C preprocessor macro for variable. variable should be a C identifier, optionally suffixed by a parenthesized argument list to define a C preprocessor macro with arguments. The macro argument list, if present, should be a comma-separated list of C identifiers, possibly terminated by an ellipsis ‘...’ if C99-or-later syntax is employed. variable should not contain comments, white space, trigraphs, backslash-newlines, universal character names, or non-ASCII characters.
value may contain backslash-escaped newlines, which will be
preserved if you use AC_CONFIG_HEADERS
but flattened if passed
via @DEFS@
(with no effect on the compilation, since the
preprocessor sees only one line in the first place). value should
not contain raw newlines. If you are not using
AC_CONFIG_HEADERS
, value should not contain any ‘#’
characters, as make
tends to eat them. To use a shell
variable, use AC_DEFINE_UNQUOTED
instead.
description is only useful if you are using
AC_CONFIG_HEADERS
. In this case, description is put into
the generated config.h.in as the comment before the macro define.
The following example defines the C preprocessor variable
EQUATION
to be the string constant ‘"$a > $b"’:
AC_DEFINE([EQUATION], ["$a > $b"], [Equation string.])
If neither value nor description are given, then value defaults to 1 instead of to the empty string. This is for backwards compatibility with older versions of Autoconf, but this usage is obsolescent and may be withdrawn in future versions of Autoconf.
If the variable is a literal string, it is passed to
m4_pattern_allow
(see Forbidden Patterns).
If multiple AC_DEFINE
statements are executed for the same
variable name (not counting any parenthesized argument list),
the last one wins.
Like AC_DEFINE
, but three shell expansions are
performed—once—on variable and value: variable expansion
(‘$’), command substitution (‘`’), and backslash escaping
(‘\’), as if in an unquoted here-document. Single and double quote
characters in the value have no
special meaning. Use this macro instead of AC_DEFINE
when
variable or value is a shell variable. Examples:
AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"], [Configuration machine file.]) AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups], [getgroups return type.]) AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1], [Translated header name.])
Due to a syntactical oddity of the Bourne shell, do not use
semicolons to separate AC_DEFINE
or AC_DEFINE_UNQUOTED
calls from other macro calls or shell code; that can cause syntax errors
in the resulting configure
script. Use either blanks or
newlines. That is, do this:
AC_CHECK_HEADER([elf.h], [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
or this:
AC_CHECK_HEADER([elf.h], [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
instead of this:
AC_CHECK_HEADER([elf.h], [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
Next: Special Characters in Output Variables, Previous: Defining C Preprocessor Symbols, Up: Results of Tests [Contents][Index]
Another way to record the results of tests is to set output
variables, which are shell variables whose values are substituted into
files that configure
outputs. The two macros below create new
output variables. See Preset Output Variables, for a list of output
variables that are always available.
Create an output variable from a shell variable. Make AC_OUTPUT
substitute the variable variable into output files (typically one
or more makefiles). This means that AC_OUTPUT
replaces instances of ‘@variable@’ in input files with the
value that the shell variable variable has when AC_OUTPUT
is called. The value can contain any non-NUL
character, including
newline. If you are using Automake 1.11 or newer, for newlines in values
you might want to consider using AM_SUBST_NOTMAKE
to prevent
automake
from adding a line variable =
@variable@
to the Makefile.in files (see Automake in Other things Automake recognizes).
Variable occurrences should not overlap: e.g., an input file should
not contain ‘@var1@var2@’ if var1 and var2
are variable names.
The substituted value is not rescanned for more output variables;
occurrences of ‘@variable@’ in the value are inserted
literally into the output file. (The algorithm uses the special marker
|#_!!_#|
internally, so neither the substituted value nor the
output file may contain |#_!!_#|
.)
If value is given, in addition assign it to variable.
The string variable is passed to m4_pattern_allow
(see Forbidden Patterns). variable is not further expanded,
even if there is another macro by the same name.
Another way to create an output variable from a shell variable. Make
AC_OUTPUT
insert (without substitutions) the contents of the file
named by shell variable variable into output files. This means
that AC_OUTPUT
replaces instances of
‘@variable@’ in output files (such as Makefile.in)
with the contents of the file that the shell variable variable
names when AC_OUTPUT
is called. Set the variable to
/dev/null for cases that do not have a file to insert.
This substitution occurs only when the ‘@variable@’ is on a
line by itself, optionally surrounded by spaces and tabs. The
substitution replaces the whole line, including the spaces, tabs, and
the terminating newline.
This macro is useful for inserting makefile fragments containing
special dependencies or other make
directives for particular host
or target types into makefiles. For example, configure.ac
could contain:
AC_SUBST_FILE([host_frag]) host_frag=$srcdir/conf/sun4.mh
and then a Makefile.in could contain:
@host_frag@
The string variable is passed to m4_pattern_allow
(see Forbidden Patterns).
Running configure
in varying environments can be extremely
dangerous. If for instance the user runs ‘CC=bizarre-cc
./configure’, then the cache, config.h, and many other output
files depend upon bizarre-cc
being the C compiler. If
for some reason the user runs ./configure
again, or if it is
run via ‘./config.status --recheck’, (See Automatic Remaking,
and see config.status Invocation), then the configuration can be
inconsistent, composed of results depending upon two different
compilers.
Environment variables that affect this situation, such as ‘CC’
above, are called precious variables, and can be declared as such
by AC_ARG_VAR
.
Declare variable is a precious variable, and include its description in the variable section of ‘./configure --help’.
Being precious means that
AC_SUBST
.
configure
was launched is
saved in the cache, including if it was not specified on the command
line but via the environment. Indeed, while configure
can
notice the definition of CC
in ‘./configure CC=bizarre-cc’,
it is impossible to notice it in ‘CC=bizarre-cc ./configure’,
which, unfortunately, is what most users do.
We emphasize that it is the initial value of variable which
is saved, not that found during the execution of configure
.
Indeed, specifying ‘./configure FOO=foo’ and letting
‘./configure’ guess that FOO
is foo
can be two
different things.
configure
runs. For instance:
$ ./configure --silent --config-cache $ CC=cc ./configure --silent --config-cache configure: error: 'CC' was not set in the previous run configure: error: changes in the environment can compromise \ the build configure: error: run 'make distclean' and/or \ 'rm config.cache' and start over
and similarly if the variable is unset, or if its content is changed. If the content has white space changes only, then the error is degraded to a warning only, but the old value is reused.
$ CC=/usr/bin/cc ./configure var=raboof --silent $ ./config.status --recheck running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \ CC=/usr/bin/cc --no-create --no-recursion
Next: Caching Results, Previous: Setting Output Variables, Up: Results of Tests [Contents][Index]
Many output variables are intended to be evaluated both by
make
and by the shell. Some characters are expanded
differently in these two contexts, so to avoid confusion these
variables’ values should not contain any of the following characters:
" # $ & ' ( ) * ; < > ? [ \ ^ ` |
Also, these variables’ values should neither contain newlines, nor start with ‘~’, nor contain white space or ‘:’ immediately followed by ‘~’. The values can contain nonempty sequences of white space characters like tabs and spaces, but each such sequence might arbitrarily be replaced by a single space during substitution.
These restrictions apply both to the values that configure
computes, and to the values set directly by the user. For example, the
following invocations of configure
are problematic, since they
attempt to use special characters within CPPFLAGS
and white space
within $(srcdir)
:
CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure' '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
Next: Printing Messages, Previous: Special Characters in Output Variables, Up: Results of Tests [Contents][Index]
To avoid checking for the same features repeatedly in various
configure
scripts (or in repeated runs of one script),
configure
can optionally save the results of many checks in a
cache file (see Cache Files). If a configure
script
runs with caching enabled and finds a cache file, it reads the results
of previous runs from the cache and avoids rerunning those checks. As a
result, configure
can then run much faster than if it had to
perform all of the checks every time.
Ensure that the results of the check identified by cache-id are
available. If the results of the check were in the cache file that was
read, and configure
was not given the --quiet or
--silent option, print a message saying that the result was
cached; otherwise, run the shell commands commands-to-set-it. If
the shell commands are run to determine the value, the value is
saved in the cache file just before configure
creates its output
files. See Cache Variable Names, for how to choose the name of the
cache-id variable.
The commands-to-set-it must have no side effects except for setting the variable cache-id, see below.
A wrapper for AC_CACHE_VAL
that takes care of printing the
messages. This macro provides a convenient shorthand for the most
common way to use these macros. It calls AC_MSG_CHECKING
for
message, then AC_CACHE_VAL
with the cache-id and
commands arguments, and AC_MSG_RESULT
with cache-id.
The commands-to-set-it must have no side effects except for setting the variable cache-id, see below.
It is common to find buggy macros using AC_CACHE_VAL
or
AC_CACHE_CHECK
, because people are tempted to call
AC_DEFINE
in the commands-to-set-it. Instead, the code that
follows the call to AC_CACHE_VAL
should call
AC_DEFINE
, by examining the value of the cache variable. For
instance, the following macro is broken:
AC_DEFUN([AC_SHELL_TRUE], [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works], [my_cv_shell_true_works=no (true) 2>/dev/null && my_cv_shell_true_works=yes if test "x$my_cv_shell_true_works" = xyes; then AC_DEFINE([TRUE_WORKS], [1], [Define if 'true(1)' works properly.]) fi]) ])
This fails if the cache is enabled: the second time this macro is run,
TRUE_WORKS
will not be defined. The proper implementation
is:
AC_DEFUN([AC_SHELL_TRUE], [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works], [my_cv_shell_true_works=no (true) 2>/dev/null && my_cv_shell_true_works=yes]) if test "x$my_cv_shell_true_works" = xyes; then AC_DEFINE([TRUE_WORKS], [1], [Define if 'true(1)' works properly.]) fi ])
Also, commands-to-set-it should not print any messages, for
example with AC_MSG_CHECKING
; do that before calling
AC_CACHE_VAL
, so the messages are printed regardless of whether
the results of the check are retrieved from the cache or determined by
running the shell commands.
Next: Cache Files, Up: Caching Results [Contents][Index]
The names of cache variables should have the following format:
package-prefix_cv_value-type_specific-value_[additional-options]
for example, ‘ac_cv_header_stat_broken’ or ‘ac_cv_prog_gcc_traditional’. The parts of the variable name are:
An abbreviation for your package or organization; the same prefix you begin local Autoconf macros with, except lowercase by convention. For cache values used by the distributed Autoconf macros, this value is ‘ac’.
_cv_
Indicates that this shell variable is a cache value. This string must be present in the variable name, including the leading underscore.
A convention for classifying cache values, to produce a rational naming system. The values used in Autoconf are listed in Macro Names.
Which member of the class of cache values this test applies to. For example, which function (‘alloca’), program (‘gcc’), or output variable (‘INSTALL’).
Any particular behavior of the specific member that this test applies to. For example, ‘broken’ or ‘set’. This part of the name may be omitted if it does not apply.
The values assigned to cache variables may not contain newlines. Usually, their values are Boolean (‘yes’ or ‘no’) or the names of files or functions; so this is not an important restriction. Cache Variable Index for an index of cache variables with documented semantics.
Next: Cache Checkpointing, Previous: Cache Variable Names, Up: Caching Results [Contents][Index]
A cache file is a shell script that caches the results of configure
tests run on one system so they can be shared between configure scripts
and configure runs. It is not useful on other systems. If its contents
are invalid for some reason, the user may delete or edit it, or override
documented cache variables on the configure
command line.
By default, configure
uses no cache file,
to avoid problems caused by accidental
use of stale cache files.
To enable caching, configure
accepts --config-cache (or
-C) to cache results in the file config.cache.
Alternatively, --cache-file=file specifies that
file be the cache file. The cache file is created if it does not
exist already. When configure
calls configure
scripts in
subdirectories, it uses the --cache-file argument so that they
share the same cache. See Configuring Other Packages in Subdirectories, for information on
configuring subdirectories with the AC_CONFIG_SUBDIRS
macro.
config.status only pays attention to the cache file if it is
given the --recheck option, which makes it rerun
configure
.
It is wrong to try to distribute cache files for particular system types. There is too much room for error in doing that, and too much administrative overhead in maintaining them. For any features that can’t be guessed automatically, use the standard method of the canonical system type and linking files (see Manual Configuration).
The site initialization script can specify a site-wide cache file to
use, instead of the usual per-program cache. In this case, the cache
file gradually accumulates information whenever someone runs a new
configure
script. (Running configure
merges the new cache
results with the existing cache file.) This may cause problems,
however, if the system configuration (e.g., the installed libraries or
compilers) changes and the stale cache file is not deleted.
If configure
is interrupted at the right time when it updates
a cache file outside of the build directory where the configure
script is run, it may leave behind a temporary file named after the
cache file with digits following it. You may safely delete such a file.
Previous: Cache Files, Up: Caching Results [Contents][Index]
If your configure script, or a macro called from configure.ac, happens
to abort the configure process, it may be useful to checkpoint the cache
a few times at key points using AC_CACHE_SAVE
. Doing so
reduces the amount of time it takes to rerun the configure script with
(hopefully) the error that caused the previous abort corrected.
Loads values from existing cache file, or creates a new cache file if a
cache file is not found. Called automatically from AC_INIT
.
Flushes all cached values to the cache file. Called automatically from
AC_OUTPUT
, but it can be quite useful to call
AC_CACHE_SAVE
at key points in configure.ac.
For instance:
… AC_INIT, etc. …
# Checks for programs.
AC_PROG_CC
AC_PROG_AWK
… more program checks …
AC_CACHE_SAVE
# Checks for libraries.
AC_CHECK_LIB([nsl], [gethostbyname])
AC_CHECK_LIB([socket], [connect])
… more lib checks …
AC_CACHE_SAVE
# Might abort… AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])]) AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
… AC_OUTPUT, etc. …
Previous: Caching Results, Up: Results of Tests [Contents][Index]
configure
scripts need to give users running them several kinds
of information. The following macros print messages in ways appropriate
for each kind. The arguments to all of them get enclosed in shell
double quotes, so the shell performs variable and back-quote
substitution on them.
These macros are all wrappers around the echo
shell command.
They direct output to the appropriate file descriptor (see File Descriptor Macros).
configure
scripts should rarely need to run echo
directly
to print messages for the user. Using these macros makes it easy to
change how and when each kind of message is printed; such changes need
only be made to the macro definitions and all the callers change
automatically.
To diagnose static issues, i.e., when autoconf
is run, see
Diagnostic messages from M4sugar.
Notify the user that configure
is checking for a particular
feature. This macro prints a message that starts with ‘checking ’
and ends with ‘...’ and no newline. It must be followed by a call
to AC_MSG_RESULT
to print the result of the check and the
newline. The feature-description should be something like
‘whether the Fortran compiler accepts C++ comments’ or ‘for
_Alignof’.
This macro prints nothing if configure
is run with the
--quiet or --silent option.
Notify the user of the results of a check. result-description is
almost always the value of the cache variable for the check, typically
‘yes’, ‘no’, or a file name. This macro should follow a call
to AC_MSG_CHECKING
, and the result-description should be
the completion of the message printed by the call to
AC_MSG_CHECKING
.
This macro prints nothing if configure
is run with the
--quiet or --silent option.
Deliver the message to the user. It is useful mainly to print a general description of the overall purpose of a group of feature checks, e.g.,
AC_MSG_NOTICE([checking if stack overflow is detectable])
This macro prints nothing if configure
is run with the
--quiet or --silent option.
Notify the user of an error that prevents configure
from
completing. This macro prints an error message to the standard error
output and exits configure
with exit-status (‘$?’
by default, except that ‘0’ is converted to ‘1’).
error-description should be something like ‘invalid value
$HOME for \$HOME’.
The error-description should start with a lower-case letter, and “cannot” is preferred to “can’t”.
This AC_MSG_ERROR
wrapper notifies the user of an error that
prevents configure
from completing and that additional
details are provided in config.log. This is typically used when
abnormal results are found during a compilation.
Notify the configure
user of a possible problem. This macro
prints the message to the standard error output; configure
continues running afterward, so macros that call AC_MSG_WARN
should
provide a default (back-up) behavior for the situations they warn about.
problem-description should be something like ‘ln -s seems to
make hard links’.
Next: Programming in M4sh, Previous: Results of Tests, Up: Autoconf [Contents][Index]
Autoconf is written on top of two layers: M4sugar, which provides convenient macros for pure M4 programming, and M4sh, which provides macros dedicated to shell script generation.
As of this version of Autoconf, these two layers still contain experimental macros, whose interface might change in the future. As a matter of fact, anything that is not documented must not be used.
Next: Using autom4te
, Up: Programming in M4 [Contents][Index]
The most common problem with existing macros is an improper quotation. This section, which users of Autoconf can skip, but which macro writers must read, first justifies the quotation scheme that was chosen for Autoconf and then ends with a rule of thumb. Understanding the former helps one to follow the latter.
changequote
is EvilNext: One Macro Call, Up: M4 Quotation [Contents][Index]
To fully understand where proper quotation is important, you first need to know what the special characters are in Autoconf: ‘#’ introduces a comment inside which no macro expansion is performed, ‘,’ separates arguments, ‘[’ and ‘]’ are the quotes themselves3, ‘(’ and ‘)’ (which M4 tries to match by pairs), and finally ‘$’ inside a macro definition.
In order to understand the delicate case of macro calls, we first have to present some obvious failures. Below they are “obvious-ified”, but when you find them in real life, they are usually in disguise.
Comments, introduced by a hash and running up to the newline, are opaque tokens to the top level: active characters are turned off, and there is no macro expansion:
# define([def], ine) ⇒# define([def], ine)
Each time there can be a macro expansion, there is a quotation expansion, i.e., one level of quotes is stripped:
int tab[10]; ⇒int tab10; [int tab[10];] ⇒int tab[10];
Without this in mind, the reader might try hopelessly to use her macro
array
:
define([array], [int tab[10];]) array ⇒int tab10; [array] ⇒array
How can you correctly output the intended results4?
Next: Quoting and Parameters, Previous: Active Characters, Up: M4 Quotation [Contents][Index]
Let’s proceed on the interaction between active characters and macros with this small macro, which just returns its first argument:
define([car], [$1])
The two pairs of quotes above are not part of the arguments of
define
; rather, they are understood by the top level when it
tries to find the arguments of define
. Therefore, assuming
car
is not already defined, it is equivalent to write:
define(car, $1)
But, while it is acceptable for a configure.ac to avoid unnecessary quotes, it is bad practice for Autoconf macros which must both be more robust and also advocate perfect style.
At the top level, there are only two possibilities: either you quote or you don’t:
car(foo, bar, baz) ⇒foo [car(foo, bar, baz)] ⇒car(foo, bar, baz)
Let’s pay attention to the special characters:
car(#) error→EOF in argument list
The closing parenthesis is hidden in the comment; with a hypothetical quoting, the top level understood it this way:
car([#)]
Proper quotation, of course, fixes the problem:
car([#]) ⇒#
Here are more examples:
car(foo, bar) ⇒foo car([foo, bar]) ⇒foo, bar car((foo, bar)) ⇒(foo, bar) car([(foo], [bar)]) ⇒(foo define([a], [b]) ⇒ car(a) ⇒b car([a]) ⇒b car([[a]]) ⇒a car([[[a]]]) ⇒[a]
Next: Quotation and Nested Macros, Previous: One Macro Call, Up: M4 Quotation [Contents][Index]
When M4 encounters ‘$’ within a macro definition, followed immediately by a character it recognizes (‘0’…‘9’, ‘#’, ‘@’, or ‘*’), it will perform M4 parameter expansion. This happens regardless of how many layers of quotes the parameter expansion is nested within, or even if it occurs in text that will be rescanned as a comment.
define([none], [$1]) ⇒ define([one], [[$1]]) ⇒ define([two], [[[$1]]]) ⇒ define([comment], [# $1]) ⇒ define([active], [ACTIVE]) ⇒ none([active]) ⇒ACTIVE one([active]) ⇒active two([active]) ⇒[active] comment([active]) ⇒# active
On the other hand, since autoconf generates shell code, you often want to output shell variable expansion, rather than performing M4 parameter expansion. To do this, you must use M4 quoting to separate the ‘$’ from the next character in the definition of your macro. If the macro definition occurs in single-quoted text, then insert another level of quoting; if the usage is already inside a double-quoted string, then split it into concatenated strings.
define([foo], [a single-quoted $[]1 definition]) ⇒ define([bar], [[a double-quoted $][1 definition]]) ⇒ foo ⇒a single-quoted $1 definition bar ⇒a double-quoted $1 definition
Posix states that M4 implementations are free to provide implementation extensions when ‘${’ is encountered in a macro definition. Autoconf reserves the longer sequence ‘${{’ for use with planned extensions that will be available in the future GNU M4 2.0, but guarantees that all other instances of ‘${’ will be output literally. Therefore, this idiom can also be used to output shell code parameter references:
define([first], [${1}])first ⇒${1}
Posix also states that ‘$11’ should expand to the first parameter concatenated with a literal ‘1’, although some versions of GNU M4 expand the eleventh parameter instead. For portability, you should only use single-digit M4 parameter expansion.
With this in mind, we can explore the cases where macros invoke macros...
Next: changequote
is Evil, Previous: Quoting and Parameters, Up: M4 Quotation [Contents][Index]
The examples below use the following macros:
define([car], [$1]) define([active], [ACT, IVE]) define([array], [int tab[10]])
Each additional embedded macro call introduces other possible interesting quotations:
car(active) ⇒ACT car([active]) ⇒ACT, IVE car([[active]]) ⇒active
In the first case, the top level looks for the arguments of car
,
and finds ‘active’. Because M4 evaluates its arguments
before applying the macro, ‘active’ is expanded, which results in:
car(ACT, IVE) ⇒ACT
In the second case, the top level gives ‘active’ as first and only
argument of car
, which results in:
active ⇒ACT, IVE
i.e., the argument is evaluated after the macro that invokes it.
In the third case, car
receives ‘[active]’, which results in:
[active] ⇒active
exactly as we already saw above.
The example above, applied to a more realistic example, gives:
car(int tab[10];) ⇒int tab10; car([int tab[10];]) ⇒int tab10; car([[int tab[10];]]) ⇒int tab[10];
Huh? The first case is easily understood, but why is the second wrong,
and the third right? To understand that, you must know that after
M4 expands a macro, the resulting text is immediately subjected
to macro expansion and quote removal. This means that the quote removal
occurs twice—first before the argument is passed to the car
macro, and second after the car
macro expands to the first
argument.
As the author of the Autoconf macro car
, you then consider it to
be incorrect that your users have to double-quote the arguments of
car
, so you “fix” your macro. Let’s call it qar
for
quoted car:
define([qar], [[$1]])
and check that qar
is properly fixed:
qar([int tab[10];]) ⇒int tab[10];
Ahhh! That’s much better.
But note what you’ve done: now that the result of qar
is always
a literal string, the only time a user can use nested macros is if she
relies on an unquoted macro call:
qar(active) ⇒ACT qar([active]) ⇒active
leaving no way for her to reproduce what she used to do with car
:
car([active]) ⇒ACT, IVE
Worse yet: she wants to use a macro that produces a set of cpp
macros:
define([my_includes], [#include <stdio.h>]) car([my_includes]) ⇒#include <stdio.h> qar(my_includes) error→EOF in argument list
This macro, qar
, because it double quotes its arguments, forces
its users to leave their macro calls unquoted, which is dangerous.
Commas and other active symbols are interpreted by M4 before
they are given to the macro, often not in the way the users expect.
Also, because qar
behaves differently from the other macros,
it’s an exception that should be avoided in Autoconf.
Next: Quadrigraphs, Previous: Quotation and Nested Macros, Up: M4 Quotation [Contents][Index]
changequote
is EvilThe temptation is often high to bypass proper quotation, in particular
when it’s late at night. Then, many experienced Autoconf hackers
finally surrender to the dark side of the force and use the ultimate
weapon: changequote
.
The M4 builtin changequote
belongs to a set of primitives that
allow one to adjust the syntax of the language to adjust it to one’s
needs. For instance, by default M4 uses ‘`’ and ‘'’ as
quotes, but in the context of shell programming (and actually of most
programming languages), that’s about the worst choice one can make:
because of strings and back-quoted expressions in shell code (such as
‘'this'’ and ‘`that`’), and because of literal characters in usual
programming languages (as in ‘'0'’), there are many unbalanced
‘`’ and ‘'’. Proper M4 quotation then becomes a nightmare, if
not impossible. In order to make M4 useful in such a context, its
designers have equipped it with changequote
, which makes it
possible to choose another pair of quotes. M4sugar, M4sh, Autoconf, and
Autotest all have chosen to use ‘[’ and ‘]’. Not especially
because they are unlikely characters, but because they are
characters unlikely to be unbalanced.
There are other magic primitives, such as changecom
to specify
what syntactic forms are comments (it is common to see
‘changecom(<!--, -->)’ when M4 is used to produce HTML pages),
changeword
and changesyntax
to change other syntactic
details (such as the character to denote the nth argument, ‘$’ by
default, the parentheses around arguments, etc.).
These primitives are really meant to make M4 more useful for specific domains: they should be considered like command line options: --quotes, --comments, --words, and --syntax. Nevertheless, they are implemented as M4 builtins, as it makes M4 libraries self contained (no need for additional options).
There lies the problem...
The problem is that it is then tempting to use them in the middle of an M4 script, as opposed to its initialization. This, if not carefully thought out, can lead to disastrous effects: you are changing the language in the middle of the execution. Changing and restoring the syntax is often not enough: if you happened to invoke macros in between, these macros are lost, as the current syntax is probably not the one they were implemented with.
Next: Dealing with unbalanced parentheses, Previous: changequote
is Evil, Up: M4 Quotation [Contents][Index]
When writing an Autoconf macro you may occasionally need to generate special characters that are difficult to express with the standard Autoconf quoting rules. For example, you may need to output the regular expression ‘[^[]’, which matches any character other than ‘[’. This expression contains unbalanced brackets so it cannot be put easily into an M4 macro.
Additionally, there are a few m4sugar macros (such as m4_split
and m4_expand
) which internally use special markers in addition
to the regular quoting characters. If the arguments to these macros
contain the literal strings ‘-=<{(’ or ‘)}>=-’, the macros
might behave incorrectly.
You can work around these problems by using one of the following quadrigraphs:
‘[’
‘]’
‘$’
‘#’
‘(’
‘)’
Expands to nothing.
Quadrigraphs are replaced at a late stage of the translation process,
after m4
is run, so they do not get in the way of M4 quoting.
For example, the string ‘^@<:@’, independently of its quotation,
appears as ‘^[’ in the output.
The empty quadrigraph can be used:
Trailing spaces are smashed by autom4te
. This is a feature.
For instance ‘@<@&t@:@’ produces ‘@<:@’. For a more contrived example:
m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl m4_split([a )}>=- b -=<{( c]) ⇒[a], [], [B], [], [c] m4_split([a )}@&t@>=- b -=<@&t@{( c]) ⇒[a], [)}>=-], [b], [-=<{(], [c]
For instance you might want to mention AC_FOO
in a comment, while
still being sure that autom4te
still catches unexpanded
‘AC_*’. Then write ‘AC@&t@_FOO’.
The name ‘@&t@’ was suggested by Paul Eggert:
I should give some credit to the ‘@&t@’ pun. The ‘&’ is my own invention, but the ‘t’ came from the source code of the ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame), and which used ‘mt’ to denote the empty string. In C, it would have looked like something like:
char const mt[] = "";but of course the source code was written in Algol 68.
I don’t know where he got ‘mt’ from: it could have been his own invention, and I suppose it could have been a common pun around the Cambridge University computer lab at the time.
Next: Quotation Rule Of Thumb, Previous: Quadrigraphs, Up: M4 Quotation [Contents][Index]
One of the pitfalls of portable shell programming is that
if you intend your script to run with obsolescent shells,
case
statements require unbalanced parentheses.
See Limitations of Shell Builtins.
With syntax highlighting
editors, the presence of unbalanced ‘)’ can interfere with editors
that perform syntax highlighting of macro contents based on finding the
matching ‘(’. Another concern is how much editing must be done
when transferring code snippets between shell scripts and macro
definitions. But most importantly, the presence of unbalanced
parentheses can introduce expansion bugs.
For an example, here is an underquoted attempt to use the macro
my_case
, which happens to expand to a portable case
statement:
AC_DEFUN([my_case], [case $file_name in *.c) echo "C source code";; esac]) AS_IF(:, my_case)
In the above example, the AS_IF
call under-quotes its arguments.
As a result, the unbalanced ‘)’ generated by the premature
expansion of my_case
results in expanding AS_IF
with a
truncated parameter, and the expansion is syntactically invalid:
if :; then case $file_name in *.c fi echo "C source code";; esac)
If nothing else, this should emphasize the importance of the quoting
arguments to macro calls. On the other hand, there are several
variations for defining my_case
to be more robust, even when used
without proper quoting, each with some benefits and some drawbacks.
AC_DEFUN([my_case], [case $file_name in (*.c) echo "C source code";; esac])
This is simple and provides balanced parentheses. Although this is not
portable to obsolescent shells (notably Solaris 10 /bin/sh
),
platforms with these shells invariably have a more-modern shell
available somewhere so this approach typically suffices nowadays.
AC_DEFUN([my_case], [case $file_name in #( *.c) echo "C source code";; esac])
This version provides balanced parentheses to several editors, and can be copied and pasted into a terminal as is. Unfortunately, it is still unbalanced as an Autoconf argument, since ‘#(’ is an M4 comment that masks the normal properties of ‘(’.
AC_DEFUN([my_case], [case $file_name in @%:@( *.c) echo "C source code";; esac])
This version provides balanced parentheses to even more editors, and can be used as a balanced Autoconf argument. Unfortunately, it requires some editing before it can be copied and pasted into a terminal, and the use of the quadrigraph ‘@%:@’ for ‘#’ reduces readability.
AC_DEFUN([my_case], [case $file_name in *.c[)] echo "C source code";; esac])
This version quotes the ‘)’, so that it can be used as a balanced Autoconf argument. As written, this is not balanced to an editor, but it can be coupled with ‘[#(]’ to meet that need, too. However, it still requires some edits before it can be copied and pasted into a terminal.
AC_DEFUN([my_case], [[case $file_name in #( *.c) echo "C source code";; esac]])
Since the entire macro is double-quoted, there is no problem with using this as an Autoconf argument; and since the double-quoting is over the entire statement, this code can be easily copied and pasted into a terminal. However, the double quoting prevents the expansion of any macros inside the case statement, which may cause its own set of problems.
AS_CASE
AC_DEFUN([my_case], [AS_CASE([$file_name], [*.c], [echo "C source code"])])
This version avoids the balancing issue altogether, by relying on
AS_CASE
(see Common Shell Constructs); it also allows for the
expansion of AC_REQUIRE
to occur prior to the entire case
statement, rather than within a branch of the case statement that might
not be taken. However, the abstraction comes with a penalty that it is
no longer a quick copy, paste, and edit to get back to shell code.
Previous: Dealing with unbalanced parentheses, Up: M4 Quotation [Contents][Index]
To conclude, the quotation rule of thumb is:
Never over-quote, never under-quote, in particular in the definition of macros. In the few places where the macros need to use brackets (usually in C program text or regular expressions), properly quote the arguments!
It is common to read Autoconf programs with snippets like:
AC_TRY_LINK( changequote(<<, >>)dnl <<#include <time.h> #ifndef tzname /* For SGI. */ extern char *tzname[]; /* RS6000 and others reject char **tzname. */ #endif>>, changequote([, ])dnl [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
which is incredibly useless since AC_TRY_LINK
is already
double quoting, so you just need:
AC_TRY_LINK( [#include <time.h> #ifndef tzname /* For SGI. */ extern char *tzname[]; /* RS6000 and others reject char **tzname. */ #endif], [atoi (*tzname);], [ac_cv_var_tzname=yes], [ac_cv_var_tzname=no])
The M4-fluent reader might note that these two examples are rigorously equivalent, since M4 swallows both the ‘changequote(<<, >>)’ and ‘<<’ ‘>>’ when it collects the arguments: these quotes are not part of the arguments!
Simplified, the example above is just doing this:
changequote(<<, >>)dnl <<[]>> changequote([, ])dnl
instead of simply:
[[]]
With macros that do not double quote their arguments (which is the rule), double-quote the (risky) literals:
AC_LINK_IFELSE([AC_LANG_PROGRAM( [[#include <time.h> #ifndef tzname /* For SGI. */ extern char *tzname[]; /* RS6000 and others reject char **tzname. */ #endif]], [atoi (*tzname);])], [ac_cv_var_tzname=yes], [ac_cv_var_tzname=no])
Please note that the macro AC_TRY_LINK
is obsolete, so you really
should be using AC_LINK_IFELSE
instead.
See Quadrigraphs, for what to do if you run into a hopeless case where quoting does not suffice.
When you create a configure
script using newly written macros,
examine it carefully to check whether you need to add more quotes in
your macros. If one or more words have disappeared in the M4
output, you need more quotes. When in doubt, quote.
However, it’s also possible to put on too many layers of quotes. If
this happens, the resulting configure
script may contain
unexpanded macros. The autoconf
program checks for this problem
by looking for the string ‘AC_’ in configure. However, this
heuristic does not work in general: for example, it does not catch
overquoting in AC_DEFINE
descriptions.
Next: Programming in M4sugar, Previous: M4 Quotation, Up: Programming in M4 [Contents][Index]
autom4te
The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
to Autoconf per se, heavily rely on M4. All these different uses
revealed common needs factored into a layer over M4:
autom4te
5.
autom4te
is a preprocessor that is like m4
.
It supports M4 extensions designed for use in tools like Autoconf.
Next: Customizing autom4te
, Up: Using autom4te
[Contents][Index]
autom4te
The command line arguments are modeled after M4’s:
autom4te options files
where the files are directly passed to m4
. By default,
GNU M4 is found during configuration, but the environment
variable
M4
can be set to tell autom4te
where to look. In addition
to the regular expansion, it handles the replacement of the quadrigraphs
(see Quadrigraphs), and of ‘__oline__’, the current line in the
output. It supports an extended syntax for the files:
This file is an M4 frozen file. Note that all the previous files are ignored. See the --melt option for the rationale.
If found in the library path, the file is included for expansion, otherwise it is ignored instead of triggering a failure.
Of course, it supports the Autoconf common subset of options:
Print a summary of the command line options and exit.
Print the version number of Autoconf and exit.
Report processing steps.
Don’t remove the temporary files and be even more verbose.
Also look for input files in dir. Multiple invocations accumulate.
Save output (script or trace) to file. The file - stands for the standard output.
As an extension of m4
, it includes the following options:
Enable or disable warnings related to each category. See m4_warn, for a comprehensive list of categories. Special values include:
Enable all categories of warnings.
Disable all categories of warnings.
Treat all warnings as errors.
Disable warnings falling into category.
The enviroment variable WARNINGS
may also be set to a
comma-separated list of warning categories to enable or disable.
It is interpreted exactly the same way as the argument of
--warnings, but unknown categories are silently ignored.
The command line takes precedence; for instance, if WARNINGS
is set to obsolete
, but -Wnone is given on the
command line, no warnings will be issued.
Some categories of warnings are on by default. Again, for details see m4_warn.
Do not use frozen files. Any argument file.m4f
is
replaced by file.m4
. This helps tracing the macros which
are executed only when the files are frozen, typically
m4_define
. For instance, running:
autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
is roughly equivalent to running:
m4 1.m4 2.m4 3.m4 4.m4 input.m4
while
autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
is equivalent to:
m4 --reload-state=4.m4f input.m4
Produce a frozen state file. autom4te
freezing is stricter
than M4’s: it must produce no warnings, and no output other than empty
lines (a line with white space is not empty) and comments
(starting with ‘#’). Unlike m4
’s similarly-named option,
this option takes no argument:
autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
corresponds to
m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
Set the mode of the non-traces output to octal-mode; by default ‘0666’.
As another additional feature over m4
, autom4te
caches its results. GNU M4 is able to produce a regular
output and traces at the same time. Traces are heavily used in the
GNU Build System: autoheader
uses them to build
config.h.in, autoreconf
to determine what
GNU Build System components are used, automake
to
“parse” configure.ac etc. To avoid recomputation,
traces are cached while performing regular expansion,
and conversely. This cache is (actually, the caches are) stored in
the directory autom4te.cache. It can safely be removed
at any moment (especially if for some reason autom4te
considers it trashed).
Specify the name of the directory where the result should be cached. Passing an empty value disables caching. Be sure to pass a relative file name, as for the time being, global caches are not supported.
Don’t cache the results.
If a cache is used, consider it obsolete (but update it anyway).
Because traces are so important to the GNU Build System,
autom4te
provides high level tracing features as compared to
M4, and helps exploiting the cache:
Trace the invocations of macro according to the format. Multiple --trace arguments can be used to list several macros. Multiple --trace arguments for a single macro are not cumulative; instead, you should just make format as long as needed.
The format is a regular string, with newlines if desired, and several special escape codes. It defaults to ‘$f:$l:$n:$%’. It can use the following special escapes:
The character ‘$’.
The file name from which macro is called.
The line number from which macro is called.
The depth of the macro call. This is an M4 technical detail that you probably don’t want to know about.
The name of the macro.
The numth argument of the call to macro.
All the arguments passed to macro, separated by the character sep or the string separator (‘,’ by default). Each argument is quoted, i.e., enclosed in a pair of square brackets.
As above, but the arguments are not quoted.
As above, but the arguments are not quoted, all new line characters in the arguments are smashed, and the default separator is ‘:’.
The escape ‘$%’ produces single-line trace outputs (unless you put newlines in the ‘separator’), while ‘$@’ and ‘$*’ do not.
See Using autoconf
to Create configure
, for examples of trace uses.
Cache the traces of macro, but do not enable traces. This is
especially important to save CPU cycles in the future. For instance,
when invoked, autoconf
pre-selects all the macros that
autoheader
, automake
, autoreconf
, etc.,
trace, so that running m4
is not needed to trace them: the
cache suffices. This results in a huge speed-up.
Finally, autom4te
introduces the concept of Autom4te
libraries. They consists in a powerful yet extremely simple feature:
sets of combined command line arguments:
Use the language Autom4te library. Current languages include:
M4sugar
create M4sugar output.
M4sh
create M4sh executable shell scripts.
Autotest
create Autotest executable test suites.
Autoconf-without-aclocal-m4
create Autoconf executable configure scripts without reading aclocal.m4.
Autoconf
create Autoconf executable configure scripts. This language inherits
all the characteristics of Autoconf-without-aclocal-m4
and
additionally reads aclocal.m4.
Prepend directory dir to the search path. This is used to include the language-specific files before any third-party macros.
As an example, if Autoconf is installed in its default location, /usr/local, the command ‘autom4te -l m4sugar foo.m4’ is strictly equivalent to the command:
autom4te --prepend-include /usr/local/share/autoconf \ m4sugar/m4sugar.m4f foo.m4
Recursive expansion applies here: the command ‘autom4te -l m4sh foo.m4’ is the same as ‘autom4te --language M4sugar m4sugar/m4sh.m4f foo.m4’, i.e.:
autom4te --prepend-include /usr/local/share/autoconf \ m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
The definition of the languages is stored in autom4te.cfg.
Previous: Invoking autom4te
, Up: Using autom4te
[Contents][Index]
autom4te
One can customize autom4te
via ~/.autom4te.cfg (i.e.,
as found in the user home directory), and ./.autom4te.cfg (i.e.,
as found in the directory from which autom4te
is run). The
order is first reading autom4te.cfg, then ~/.autom4te.cfg,
then ./.autom4te.cfg, and finally the command line arguments.
In these text files, comments are introduced with #
, and empty
lines are ignored. Customization is performed on a per-language basis,
wrapped in between a ‘begin-language: "language"’,
‘end-language: "language"’ pair.
Customizing a language stands for appending options (see Invoking autom4te
) to the current definition of the language. Options, and
more generally arguments, are introduced by ‘args:
arguments’. You may use the traditional shell syntax to quote the
arguments.
As an example, to disable Autoconf caches (autom4te.cache) globally, include the following lines in ~/.autom4te.cfg:
## ------------------ ## ## User Preferences. ## ## ------------------ ## begin-language: "Autoconf-without-aclocal-m4" args: --no-cache end-language: "Autoconf-without-aclocal-m4"
Next: Debugging via autom4te, Previous: Using autom4te
, Up: Programming in M4 [Contents][Index]
M4 by itself provides only a small, but sufficient, set of all-purpose macros. M4sugar introduces additional generic macros. Its name was coined by Lars J. Aas: “Readability And Greater Understanding Stands 4 M4sugar”.
M4sugar reserves the macro namespace ‘^_m4_’ for internal use, and the macro namespace ‘^m4_’ for M4sugar macros. You should not define your own macros into these namespaces.
Next: Diagnostic messages from M4sugar, Up: Programming in M4sugar [Contents][Index]
With a few exceptions, all the M4 native macros are moved in the
‘m4_’ pseudo-namespace, e.g., M4sugar renames define
as
m4_define
etc.
The list of macros unchanged from M4, except for their name, is:
Some M4 macros are redefined, and are slightly incompatible with their native equivalent.
All M4 macros starting with ‘__’ retain their original name: for
example, no m4__file__
is defined.
This is not technically a macro, but a feature of Autom4te. The
sequence __oline__
can be used similarly to the other m4sugar
location macros, but rather than expanding to the location of the input
file, it is translated to the line number where it appears in the output
file after all other M4 expansions.
This macro kept its original name: no m4_dnl
is defined.
This macro corresponds to patsubst
. The name m4_patsubst
is kept for future versions of M4sugar, once GNU M4 2.0 is
released and supports extended regular expression syntax.
This macro corresponds to regexp
. The name m4_regexp
is kept for future versions of M4sugar, once GNU M4 2.0 is
released and supports extended regular expression syntax.
These macros aren’t directly builtins, but are closely related to
m4_pushdef
and m4_defn
. m4_copy
and
m4_rename
ensure that dest is undefined, while
m4_copy_force
and m4_rename_force
overwrite any existing
definition. All four macros then proceed to copy the entire pushdef
stack of definitions of source over to dest. m4_copy
and m4_copy_force
preserve the source (including in the special
case where source is undefined), while m4_rename
and
m4_rename_force
undefine the original macro name (making it an
error to rename an undefined source).
Note that attempting to invoke a renamed macro might not work, since the macro may have a dependence on helper macros accessed via composition of ‘$0’ but that were not also renamed; likewise, other macros may have a hard-coded dependence on source and could break if source has been deleted. On the other hand, it is always safe to rename a macro to temporarily move it out of the way, then rename it back later to restore original semantics.
This macro fails if macro is not defined, even when using older
versions of M4 that did not warn. See m4_undefine
.
Unfortunately, in order to support these older versions of M4, there are
some situations involving unbalanced quotes where concatenating multiple
macros together will work in newer M4 but not in m4sugar; use
quadrigraphs to work around this.
M4sugar relies heavily on diversions, so rather than behaving as a
primitive, m4_divert
behaves like:
m4_divert_pop()m4_divert_push([diversion])
See Diversion support, for more details about the use of the diversion stack. In particular, this implies that diversion should be a named diversion rather than a raw number. But be aware that it is seldom necessary to explicitly change the diversion stack, and that when done incorrectly, it can lead to syntactically invalid scripts.
m4_dumpdef
is like the M4 builtin, except that this version
requires at least one argument, output always goes to standard error
rather than the current debug file, no sorting is done on multiple
arguments, and an error is issued if any
name is undefined. m4_dumpdefs
is a convenience macro that
calls m4_dumpdef
for all of the
m4_pushdef
stack of definitions, starting with the current, and
silently does nothing if name is undefined.
Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
builtin is output as the empty string. This behavior is rectified by
using M4 1.6 or newer. However, this behavior difference means that
m4_dumpdef
should only be used while developing m4sugar macros,
and never in the final published form of a macro.
Like m4_esyscmd
, this macro expands to the result of running
command in a shell. The difference is that any trailing newlines
are removed, so that the output behaves more like shell command
substitution.
This macro corresponds to m4exit
.
This macro corresponds to ifelse
. string-1 and
string-2 are compared literally, so usually one of the two
arguments is passed unquoted. See Conditional constructs, for more
conditional idioms.
Like the M4 builtins, but warn against multiple inclusions of file.
Posix requires maketemp
to replace the trailing ‘X’
characters in template with the process id, without regards to the
existence of a file by that name, but this a security hole. When this
was pointed out to the Posix folks, they agreed to invent a new macro
mkstemp
that always creates a uniquely named file, but not all
versions of GNU M4 support the new macro. In M4sugar,
m4_maketemp
and m4_mkstemp
are synonyms for each other,
and both have the secure semantics regardless of which macro the
underlying M4 provides.
This macro fails if macro is not defined, even when using older
versions of M4 that did not warn. See m4_undefine
.
This macro fails if macro is not defined, even when using older versions of M4 that did not warn. Use
m4_ifdef([macro], [m4_undefine([macro])])
if you are not sure whether macro is defined.
Unlike the M4 builtin, at least one diversion must be specified.
Also, since the M4sugar diversion stack prefers named
diversions, the use of m4_undivert
to include files is risky.
See Diversion support, for more details about the use of the
diversion stack. But be aware that it is seldom necessary to explicitly
change the diversion stack, and that when done incorrectly, it can lead
to syntactically invalid scripts.
These macros correspond to m4wrap
. Posix requires arguments of
multiple wrap calls to be reprocessed at EOF in the same order
as the original calls (first-in, first-out). GNU M4 versions
through 1.4.10, however, reprocess them in reverse order (last-in,
first-out). Both orders are useful, therefore, you can rely on
m4_wrap
to provide FIFO semantics and m4_wrap_lifo
for
LIFO semantics, regardless of the underlying GNU M4 version.
Unlike the GNU M4 builtin, these macros only recognize one
argument, and avoid token pasting between consecutive invocations. On
the other hand, nested calls to m4_wrap
from within wrapped text
work just as in the builtin.
Next: Diversion support, Previous: Redefined M4 Macros, Up: Programming in M4sugar [Contents][Index]
When macros statically diagnose abnormal situations, benign or fatal,
they should report them using these macros. For issuing dynamic issues,
i.e., when configure
is run, see Printing Messages.
Assert that the arithmetic expression evaluates to non-zero.
Otherwise, issue a fatal error, and exit autom4te
with
exit-status.
Similar to the builtin m4_errprint
, except that a newline is
guaranteed after message.
Report a severe error message prefixed with the current location,
and have autom4te
die.
Useful as a prefix in a message line. Short for:
__file__:__line__
Report message as a warning (or as an error if requested by the
user) if warnings of the category are turned on. If the message
is emitted, it is prefixed with the current location, and followed by a
call trace of all macros defined via AC_DEFUN
used to get to the
current expansion.
The category must be one of:
Warnings about constructs that may interfere with cross-compilation,
such as using AC_RUN_IFELSE
without a default.
Warnings related to the GNU Coding Standards (see The GNU Coding Standards). On by default.
Warnings about obsolete features. On by default.
Warnings about redefinitions of Autoconf internals.
Warnings about non-portable constructs.
Warnings about recursive Make variable expansions ($(foo$(x))
).
Extra warnings about non-portable constructs, covering rarely-used tools.
Warnings about questionable syntactic constructs, incorrectly ordered macro calls, typos, etc. On by default.
Warnings about unsupported features. On by default.
Hacking Note: The set of categories is defined by code in
autom4te
, not by M4sugar itself. Additions should be
coordinated with Automake, so that both sets of tools accept the same
options.
Next: Conditional constructs, Previous: Diagnostic messages from M4sugar, Up: Programming in M4sugar [Contents][Index]
M4sugar makes heavy use of diversions under the hood, because it is often the case that text that must appear early in the output is not discovered until late in the input. Additionally, some of the topological sorting algorithms used in resolving macro dependencies use diversions. However, most macros should not need to change diversions directly, but rather rely on higher-level M4sugar macros to manage diversions transparently. If you change diversions improperly, you risk generating a syntactically invalid script, because an incorrect diversion will violate assumptions made by many macros about whether prerequisite text has been previously output. In short, if you manually change the diversion, you should not expect any macros provided by the Autoconf package to work until you have restored the diversion stack back to its original state.
In the rare case that it is necessary to write a macro that explicitly
outputs text to a different diversion, it is important to be aware of an
M4 limitation regarding diversions: text only goes to a diversion if it
is not part of argument collection. Therefore, any macro that changes
the current diversion cannot be used as an unquoted argument to another
macro, but must be expanded at the top level. The macro
m4_expand
will diagnose any attempt to change diversions, since
it is generally useful only as an argument to another macro. The
following example shows what happens when diversion manipulation is
attempted within macro arguments:
m4_do([normal text] m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL]) [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl ⇒normal text ⇒unwanted
Notice that the unquoted text unwanted
is output, even though it
was processed while the current diversion was KILL
, because it
was collected as part of the argument to m4_do
. However, the
text discarded
disappeared as desired, because the diversion
changes were single-quoted, and were not expanded until the top-level
rescan of the output of m4_do
.
To make diversion management easier, M4sugar uses the concept of named
diversions. Rather than using diversion numbers directly, it is nicer
to associate a name with each diversion. The diversion number associated
with a particular diversion name is an implementation detail, and a
syntax warning is issued if a diversion number is used instead of a
name. In general, you should not output text
to a named diversion until after calling the appropriate initialization
routine for your language (m4_init
, AS_INIT
,
AT_INIT
, …), although there are some exceptions documented
below.
M4sugar defines two named diversions.
 This is the default diversion once M4sugar is initialized.
GROW
This diversion is used behind the scenes by topological sorting macros,
such as AC_REQUIRE
.
M4sh adds several more named diversions.
BINSH
This diversion is reserved for the ‘#!’ interpreter line.
HEADER-REVISION
This diversion holds text from AC_REVISION
.
HEADER-COMMENT
This diversion holds comments about the purpose of a file.
HEADER-COPYRIGHT
This diversion is managed by AC_COPYRIGHT
.
M4SH-SANITIZE
This diversion contains M4sh sanitization code, used to ensure M4sh is executing in a reasonable shell environment.
M4SH-INIT
This diversion contains M4sh initialization code, initializing variables that are required by other M4sh macros.
BODY
This diversion contains the body of the shell code, and is the default diversion once M4sh is initialized.
Autotest inherits diversions from M4sh, and changes the default
diversion from BODY
back to KILL
. It also adds several
more named diversions, with the following subset designed for developer
use.
PREPARE_TESTS
This diversion contains initialization sequences which are executed
after atconfig and atlocal, and after all command line
arguments have been parsed, but prior to running any tests. It can be
used to set up state that is required across all tests. This diversion
will work even before AT_INIT
.
Autoconf inherits diversions from M4sh, and adds the following named diversions which developers can utilize.
DEFAULTS
This diversion contains shell variable assignments to set defaults that must be in place before arguments are parsed. This diversion is placed early enough in configure that it is unsafe to expand any autoconf macros into this diversion.
HELP_ENABLE
If AC_PRESERVE_HELP_ORDER
was used, then text placed in this
diversion will be included as part of a quoted here-doc providing all of
the --help output of configure related to options
created by AC_ARG_WITH
and AC_ARG_ENABLE
.
INIT_PREPARE
This diversion occurs after all command line options have been parsed, but prior to the main body of the configure script. This diversion is the last chance to insert shell code such as variable assignments or shell function declarations that will used by the expansion of other macros.
For now, the remaining named diversions of Autoconf, Autoheader, and Autotest are not documented. In other words, intentionally outputting text into an undocumented diversion is subject to breakage in a future release of Autoconf.
Permanently discard any text that has been diverted into diversion.
Similar to m4_divert_text
, except that content is only
output to diversion if this is the first time that
m4_divert_once
has been called with its particular arguments.
If provided, check that the current diversion is indeed diversion.
Then change to the diversion located earlier on the stack, giving an
error if an attempt is made to pop beyond the initial m4sugar diversion
of KILL
.
Remember the former diversion on the diversion stack, and output subsequent text into diversion. M4sugar maintains a diversion stack, and issues an error if there is not a matching pop for every push.
Output content and a newline into diversion, without affecting the current diversion. Shorthand for:
m4_divert_push([diversion])content m4_divert_pop([diversion])dnl
One use of m4_divert_text
is to develop two related macros, where
macro ‘MY_A’ does the work, but adjusts what work is performed
based on whether the optional macro ‘MY_B’ has also been expanded.
Of course, it is possible to use AC_BEFORE
within MY_A
to
require that ‘MY_B’ occurs first, if it occurs at all. But this
imposes an ordering restriction on the user; it would be nicer if macros
‘MY_A’ and ‘MY_B’ can be invoked in either order. The trick
is to let ‘MY_B’ leave a breadcrumb in an early diversion, which
‘MY_A’ can then use to determine whether ‘MY_B’ has been
expanded.
AC_DEFUN([MY_A], [# various actions if test -n "$b_was_used"; then # extra action fi]) AC_DEFUN([MY_B], [AC_REQUIRE([MY_A])dnl m4_divert_text([INIT_PREPARE], [b_was_used=true])])
Initialize the M4sugar environment, setting up the default named
diversion to be KILL
.
Next: Looping constructs, Previous: Diversion support, Up: Programming in M4sugar [Contents][Index]
The following macros provide additional conditional constructs as
convenience wrappers around m4_if
.
The string string is repeatedly compared against a series of regex arguments; if a match is found, the expansion is the corresponding value, otherwise, the macro moves on to the next regex. If no regex match, then the result is the optional default, or nothing.
The string string is altered by regex-1 and subst-1, as if by:
m4_bpatsubst([[string]], [regex], [subst])
The result of the substitution is then passed through the next set of regex and subst, and so forth. An empty subst implies deletion of any matched portions in the current string. Note that this macro over-quotes string; this behavior is intentional, so that the result of each step of the recursion remains as a quoted string. However, it means that anchors (‘^’ and ‘$’ in the regex will line up with the extra quotations, and not the characters of the original string. The overquoting is removed after the final substitution.
Test string against multiple value possibilities, resulting in the first if-value for a match, or in the optional default. This is shorthand for:
m4_if([string], [value-1], [if-value-1], [string], [value-2], [if-value-2], …, [default])
This macro was introduced in Autoconf 2.62. Similar to m4_if
,
except that each test is expanded only when it is encountered.
This is useful for short-circuiting expensive tests; while m4_if
requires all its strings to be expanded up front before doing
comparisons, m4_cond
only expands a test when all earlier
tests have failed.
For an example, these two sequences give the same result, but in the
case where ‘$1’ does not contain a backslash, the m4_cond
version only expands m4_index
once, instead of five times, for
faster computation if this is a common case for ‘$1’. Notice that
every third argument is unquoted for m4_if
, and quoted for
m4_cond
:
m4_if(m4_index([$1], [\]), [-1], [$2], m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2], m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2], m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3], m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3], [$2]) m4_cond([m4_index([$1], [\])], [-1], [$2], [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2], [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2], [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3], [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3], [$2])
If expr-1 contains text, use it. Otherwise, select expr-2.
m4_default
expands the result, while m4_default_quoted
does not. Useful for providing a fixed default if the expression that
results in expr-1 would otherwise be empty. The difference
between m4_default
and m4_default_nblank
is whether an
argument consisting of just blanks (space, tab, newline) is
significant. When using the expanding versions, note that an argument
may contain text but still expand to an empty string.
m4_define([active], [ACTIVE])dnl m4_define([empty], [])dnl m4_define([demo1], [m4_default([$1], [$2])])dnl m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl demo1([active], [default]) ⇒ACTIVE demo1([], [active]) ⇒ACTIVE demo1([empty], [text]) ⇒ -demo1([ ], [active])- ⇒- - demo2([active], [default]) ⇒active demo2([], [active]) ⇒active demo2([empty], [text]) ⇒empty -demo2([ ], [active])- ⇒- - demo3([active], [default]) ⇒ACTIVE demo3([], [active]) ⇒ACTIVE demo3([empty], [text]) ⇒ -demo3([ ], [active])- ⇒-ACTIVE- demo4([active], [default]) ⇒active demo4([], [active]) ⇒active demo4([empty], [text]) ⇒empty -demo4([ ], [active])- ⇒-active-
If macro does not already have a definition, then define it to default-definition.
If cond is empty or consists only of blanks (space, tab, newline), then expand if-blank; otherwise, expand if-text. Two variants exist, in order to make it easier to select the correct logical sense when using only two parameters. Note that this is more efficient than the equivalent behavior of:
m4_ifval(m4_normalize([cond]), if-text, if-blank)
This is shorthand for:
m4_ifdef([macro], [if-defined], [if-not-defined])
If macro is undefined, or is defined as the empty string, expand to if-false. Otherwise, expands to if-true. Similar to:
m4_ifval(m4_defn([macro]), [if-true], [if-false])
except that it is not an error if macro is undefined.
Expands to if-true if cond is not empty, otherwise to if-false. This is shorthand for:
m4_if([cond], [], [if-false], [if-true])
Similar to m4_ifval
, except guarantee that a newline is present
after any non-empty expansion. Often followed by dnl
.
Expand to text, and add a newline if text is not empty.
Often followed by dnl
.
Next: Evaluation Macros, Previous: Conditional constructs, Up: Programming in M4sugar [Contents][Index]
The following macros are useful in implementing recursive algorithms in
M4, including loop operations. An M4 list is formed by quoting a list
of quoted elements; generally the lists are comma-separated, although
m4_foreach_w
is whitespace-separated. For example, the list
‘[[a], [b,c]]’ contains two elements: ‘[a]’ and ‘[b,c]’.
It is common to see lists with unquoted elements when those elements are
not likely to be macro names, as in ‘[fputc_unlocked,
fgetc_unlocked]’.
Although not generally recommended, it is possible for quoted lists to have side effects; all side effects are expanded only once, and prior to visiting any list element. On the other hand, the fact that unquoted macros are expanded exactly once means that macros without side effects can be used to generate lists. For example,
m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i]) error→hi ⇒123 m4_define([list], [[1], [2], [3]]) ⇒ m4_foreach([i], [list], [i]) ⇒123
Extracts argument n (larger than 0) from the remaining arguments. If there are too few arguments, the empty string is used. For any n besides 1, this is more efficient than the similar ‘m4_car(m4_shiftn([n], [], [arg…]))’.
Expands to the quoted first arg. Can be used with m4_cdr
to recursively iterate
through a list. Generally, when using quoted lists of quoted elements,
m4_car
should be called without any extra quotes.
Expands to a quoted list of all but the first arg, or the empty
string if there was only one argument. Generally, when using quoted
lists of quoted elements, m4_cdr
should be called without any
extra quotes.
For example, this is a simple implementation of m4_map
; note how
each iteration checks for the end of recursion, then merely applies the
first argument to the first element of the list, then repeats with the
rest of the list. (The actual implementation in M4sugar is a bit more
involved, to gain some speed and share code with m4_map_sep
, and
also to avoid expanding side effects in ‘$2’ twice).
m4_define([m4_map], [m4_ifval([$2], [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]]) ⇒ 1 2 a
Loop over the numeric values between first and last including bounds by increments of step. For each iteration, expand expression with the numeric value assigned to var. If step is omitted, it defaults to ‘1’ or ‘-1’ depending on the order of the limits. If given, step has to match this order. The number of iterations is determined independently from definition of var; iteration cannot be short-circuited or lengthened by modifying var from within expression.
Loop over the comma-separated M4 list list, assigning each value to var, and expand expression. The following example outputs two lines:
m4_foreach([myvar], [[foo], [bar, baz]], [echo myvar ])dnl ⇒echo foo ⇒echo bar, baz
Note that for some forms of expression, it may be faster to use
m4_map_args
.
Loop over the white-space-separated list list, assigning each value
to var, and expand expression. If var is only
referenced once in expression, it is more efficient to use
m4_map_args_w
.
The deprecated macro AC_FOREACH
is an alias of
m4_foreach_w
.
Loop over the comma separated quoted list of argument descriptions in
list, and invoke macro with the arguments. An argument
description is in turn a comma-separated quoted list of quoted elements,
suitable for m4_apply
. The macros m4_map
and
m4_map_sep
ignore empty argument descriptions, while
m4_mapall
and m4_mapall_sep
invoke macro with no
arguments. The macros m4_map_sep
and m4_mapall_sep
additionally expand separator between invocations of macro.
Note that separator is expanded, unlike in m4_join
. When
separating output with commas, this means that the map result can be
used as a series of arguments, by using a single-quoted comma as
separator, or as a single string, by using a double-quoted comma.
m4_map([m4_count], []) ⇒ m4_map([ m4_count], [[], [[1]], [[1], [2]]]) ⇒ 1 2 m4_mapall([ m4_count], [[], [[1]], [[1], [2]]]) ⇒ 0 1 2 m4_map_sep([m4_eval], [,], [[[1+2]], [[10], [16]]]) ⇒3,a m4_map_sep([m4_echo], [,], [[[a]], [[b]]]) ⇒a,b m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]])) ⇒2 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]) ⇒a,b m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])) ⇒1
Repeatedly invoke macro with each successive arg as its only
argument. In the following example, three solutions are presented with
the same expansion; the solution using m4_map_args
is the most
efficient.
m4_define([active], [ACTIVE])dnl m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))]) ⇒ plain active m4_map([ m4_echo], [[[plain]], [[active]]]) ⇒ plain active m4_map_args([ m4_echo], [plain], [active]) ⇒ plain active
In cases where it is useful to operate on additional parameters besides
the list elements, the macro m4_curry
can be used in macro
to supply the argument currying necessary to generate the desired
argument list. In the following example, list_add_n
is more
efficient than list_add_x
. On the other hand, using
m4_map_args_sep
can be even more efficient.
m4_define([list], [[1], [2], [3]])dnl m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl dnl list_add_n(N, ARG...) dnl Output a list consisting of each ARG added to N m4_define([list_add_n], [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@)))])dnl list_add_n([1], list) ⇒2,3,4 list_add_n([2], list) ⇒3,4,5 m4_define([list_add_x], [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@)), [,add([$1],m4_defn([var]))]))])dnl list_add_x([1], list) ⇒2,3,4
arg…) For every pair of arguments arg, invoke macro with two arguments. If there is an odd number of arguments, invoke macro-end, which defaults to macro, with the remaining argument.
m4_map_args_pair([, m4_reverse], [], [1], [2], [3]) ⇒, 2, 1, 3 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3]) ⇒, 2, 1, [3] m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4]) ⇒, 2, 1, 4, 3
Expand the sequence pre[arg]post
for each
argument, additionally expanding sep between arguments. One
common use of this macro is constructing a macro call, where the opening
and closing parentheses are split between pre and post; in
particular, m4_map_args([macro], [arg])
is equivalent
to m4_map_args_sep([macro(], [)], [], [arg])
. This
macro provides the most efficient means for iterating over an arbitrary
list of arguments, particularly when repeatedly constructing a macro
call with more arguments than arg.
Expand the sequence pre[word]post
for each word in
the whitespace-separated string, additionally expanding sep
between words. This macro provides the most efficient means for
iterating over a whitespace-separated string. In particular,
m4_map_args_w([string], [action(], [)])
is more
efficient than m4_foreach_w([var], [string],
[action(m4_defn([var]))])
.
m4_shiftn
performs count iterations of m4_shift
,
along with validation that enough arguments were passed in to match the
shift count, and that the count is positive. m4_shift2
and
m4_shift3
are specializations
of m4_shiftn
, introduced in Autoconf 2.62, and are more efficient
for two and three shifts, respectively.
For each of the m4_pushdef
definitions of macro, expand
action with the single argument of a definition of macro.
m4_stack_foreach
starts with the oldest definition, while
m4_stack_foreach_lifo
starts with the current definition.
action should not push or pop definitions of macro, nor is
there any guarantee that the current definition of macro matches
the argument that was passed to action. The macro m4_curry
can be used if action needs more than one argument, although in
that case it is more efficient to use m4_stack_foreach_sep.
Due to technical limitations, there are a few low-level m4sugar
functions, such as m4_pushdef
, that cannot be used as the
macro argument.
m4_pushdef([a], [1])m4_pushdef([a], [2])dnl m4_stack_foreach([a], [ m4_incr]) ⇒ 2 3 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])]) ⇒ cd bcd
Expand the sequence pre[definition]post
for each
m4_pushdef
definition of macro, additionally expanding
sep between definitions. m4_stack_foreach_sep
visits the
oldest definition first, while m4_stack_foreach_sep_lifo
visits
the current definition first. This macro provides the most efficient
means for iterating over a pushdef stack. In particular,
m4_stack_foreach([macro], [action])
is short for
m4_stack_foreach_sep([macro], [action(], [)])
.
Next: String manipulation in M4, Previous: Looping constructs, Up: Programming in M4sugar [Contents][Index]
The following macros give some control over the order of the evaluation by adding or removing levels of quotes.
Apply the elements of the quoted, comma-separated list as the
arguments to macro. If list is empty, invoke macro
without arguments. Note the difference between m4_indir
, which
expects its first argument to be a macro name but can use names that are
otherwise invalid, and m4_apply
, where macro can contain
other text, but must end in a valid macro name.
m4_apply([m4_count], []) ⇒0 m4_apply([m4_count], [[]]) ⇒1 m4_apply([m4_count], [[1], [2]]) ⇒2 m4_apply([m4_join], [[|], [1], [2]]) ⇒1|2
This macro returns the decimal count of the number of arguments it was passed.
This macro performs argument currying. The expansion of this macro is another macro name that expects exactly one argument; that argument is then appended to the arg list, and then macro is expanded with the resulting argument list.
m4_curry([m4_curry], [m4_reverse], [1])([2])([3]) ⇒3, 2, 1
Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
pass the definition of a builtin macro as the argument to the output of
m4_curry
; the empty string is used instead of the builtin token.
This behavior is rectified by using M4 1.6 or newer.
This macro loops over its arguments and expands each arg in
sequence. Its main use is for readability; it allows the use of
indentation and fewer dnl
to result in the same expansion. This
macro guarantees that no expansion will be concatenated with subsequent
text; to achieve full concatenation, use m4_unquote(m4_join([],
arg…))
.
m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl m4_do([a],[b])c ⇒abc m4_unquote(m4_join([],[a],[b]))c ⇒3 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl m4_do([a],[b])c ⇒ABC m4_unquote(m4_join([],[a],[b]))c ⇒3
Return the arguments as a quoted list of quoted arguments. Conveniently, if there is just one arg, this effectively adds a level of quoting.
Return the arguments as a series of double-quoted arguments. Whereas
m4_dquote
returns a single argument, m4_dquote_elt
returns
as many arguments as it was passed.
Return the arguments, with the same level of quoting. Other than discarding whitespace after unquoted commas, this macro is a no-op.
Return the expansion of arg as a quoted string. Whereas
m4_quote
is designed to collect expanded text into a single
argument, m4_expand
is designed to perform one level of expansion
on quoted text. One distinction is in the treatment of whitespace
following a comma in the original arg. Any time multiple
arguments are collected into one with m4_quote
, the M4 argument
collection rules discard the whitespace. However, with m4_expand
,
whitespace is preserved, even after the expansion of macros contained in
arg. Additionally, m4_expand
is able to expand text that
would involve an unterminated comment, whereas expanding that same text
as the argument to m4_quote
runs into difficulty in finding the
end of the argument. Since manipulating diversions during argument
collection is inherently unsafe, m4_expand
issues an error if
arg attempts to change the current diversion (see Diversion support).
m4_define([active], [ACT, IVE])dnl m4_define([active2], [[ACT, IVE]])dnl m4_quote(active, active) ⇒ACT,IVE,ACT,IVE m4_expand([active, active]) ⇒ACT, IVE, ACT, IVE m4_quote(active2, active2) ⇒ACT, IVE,ACT, IVE m4_expand([active2, active2]) ⇒ACT, IVE, ACT, IVE m4_expand([# m4_echo]) ⇒# m4_echo m4_quote(# m4_echo) ) ⇒# m4_echo) ⇒
Note that m4_expand
cannot handle an arg that expands to
literal unbalanced quotes, but that quadrigraphs can be used when
unbalanced output is necessary. Likewise, unbalanced parentheses should
be supplied with double quoting or a quadrigraph.
m4_define([pattern], [[!@<:@]])dnl m4_define([bar], [BAR])dnl m4_expand([case $foo in m4_defn([pattern])@:}@ bar ;; *[)] blah ;; esac]) ⇒case $foo in ⇒ [![]) BAR ;; ⇒ *) blah ;; ⇒esac
This macro was introduced in Autoconf 2.62. Expands to nothing, ignoring all of its arguments. By itself, this isn’t very useful. However, it can be used to conditionally ignore an arbitrary number of arguments, by deciding which macro name to apply to a list of arguments.
dnl foo outputs a message only if [debug] is defined. m4_define([foo], [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
Note that for earlier versions of Autoconf, the macro __gnu__
can
serve the same purpose, although it is less readable.
This macro exists to aid debugging of M4sugar algorithms. Its net
effect is similar to m4_dquote
—it produces a quoted list of
quoted arguments, for each arg. The difference is that this
version uses a comma-newline separator instead of just comma, to improve
readability of the list; with the result that it is less efficient than
m4_dquote
.
m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl m4_dquote(zero, [one], [[two]]) ⇒[0],[one],[[two]] m4_make_list(zero, [one], [[two]]) ⇒[0], ⇒[one], ⇒[[two]] m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number]) ⇒ 0 1 two m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number]) ⇒ 0 1 two
Return the arguments as a single entity, i.e., wrap them into a pair of quotes. This effectively collapses multiple arguments into one, although it loses whitespace after unquoted commas in the process.
Outputs each argument with the same level of quoting, but in reverse order, and with space following each comma for readability.
m4_define([active], [ACT,IVE]) ⇒ m4_reverse(active, [active]) ⇒active, IVE, ACT
This macro was introduced in Autoconf 2.62. Expand each argument,
separated by commas. For a single arg, this effectively removes a
layer of quoting, and m4_unquote([arg])
is more efficient
than the equivalent m4_do([arg])
. For multiple arguments,
this results in an unquoted list of expansions. This is commonly used
with m4_split
, in order to convert a single quoted list into a
series of quoted elements.
The following example aims at emphasizing the difference between several
scenarios: not using these macros, using m4_defn
, using
m4_quote
, using m4_dquote
, and using m4_expand
.
$ cat example.m4 dnl Overquote, so that quotes are visible. m4_define([show], [$[]1 = [$1], $[]@ = [$@]]) m4_define([a], [A]) m4_define([mkargs], [1, 2[,] 3]) m4_define([arg1], [[$1]]) m4_divert([0])dnl show(a, b) show([a, b]) show(m4_quote(a, b)) show(m4_dquote(a, b)) show(m4_expand([a, b])) arg1(mkargs) arg1([mkargs]) arg1(m4_defn([mkargs])) arg1(m4_quote(mkargs)) arg1(m4_dquote(mkargs)) arg1(m4_expand([mkargs])) $ autom4te -l m4sugar example.m4 $1 = A, $@ = [A],[b] $1 = a, b, $@ = [a, b] $1 = A,b, $@ = [A,b] $1 = [A],[b], $@ = [[A],[b]] $1 = A, b, $@ = [A, b] 1 mkargs 1, 2[,] 3 1,2, 3 [1],[2, 3] 1, 2, 3
Next: Arithmetic computation in M4, Previous: Evaluation Macros, Up: Programming in M4sugar [Contents][Index]
The following macros may be used to manipulate strings in M4. Many of the macros in this section intentionally result in quoted strings as output, rather than subjecting the arguments to further expansions. As a result, if you are manipulating text that contains active M4 characters, the arguments are passed with single quoting rather than double.
Redefine macro-name to its former contents with separator and string added at the end. If macro-name was undefined before (but not if it was defined but empty), then no separator is added. As of Autoconf 2.62, neither string nor separator are expanded during this macro; instead, they are expanded when macro-name is invoked.
m4_append
can be used to grow strings, and m4_append_uniq
to grow strings without duplicating substrings. Additionally,
m4_append_uniq
takes two optional parameters as of Autoconf 2.62;
if-uniq is expanded if string was appended, and
if-duplicate is expanded if string was already present.
Also, m4_append_uniq
warns if separator is not empty, but
occurs within string, since that can lead to duplicates.
Note that m4_append
can scale linearly in the length of the final
string, depending on the quality of the underlying M4 implementation,
while m4_append_uniq
has an inherent quadratic scaling factor.
If an algorithm can tolerate duplicates in the final string, use the
former for speed. If duplicates must be avoided, consider using
m4_set_add
instead (see Set manipulation in M4).
m4_define([active], [ACTIVE])dnl m4_append([sentence], [This is an])dnl m4_append([sentence], [ active ])dnl m4_append([sentence], [symbol.])dnl sentence ⇒This is an ACTIVE symbol. m4_undefine([active])dnl ⇒This is an active symbol. m4_append_uniq([list], [one], [, ], [new], [existing]) ⇒new m4_append_uniq([list], [one], [, ], [new], [existing]) ⇒existing m4_append_uniq([list], [two], [, ], [new], [existing]) ⇒new m4_append_uniq([list], [three], [, ], [new], [existing]) ⇒new m4_append_uniq([list], [two], [, ], [new], [existing]) ⇒existing list ⇒one, two, three m4_dquote(list) ⇒[one],[two],[three] m4_append([list2], [one], [[, ]])dnl m4_append_uniq([list2], [two], [[, ]])dnl m4_append([list2], [three], [[, ]])dnl list2 ⇒one, two, three m4_dquote(list2) ⇒[one, two, three]
This macro was introduced in Autoconf 2.62. It is similar to
m4_append_uniq
, but treats strings as a whitespace
separated list of words to append, and only appends unique words.
macro-name is updated with a single space between new words.
m4_append_uniq_w([numbers], [1 1 2])dnl m4_append_uniq_w([numbers], [ 2 3 ])dnl numbers ⇒1 2 3
Output string in quotes, but without a trailing newline. The
macro m4_chomp
is slightly faster, and removes at most one
newline; the macro m4_chomp_all
removes all consecutive trailing
newlines. Unlike m4_flatten
, embedded newlines are left intact,
and backslash does not influence the result.
This macro produces a quoted string containing the pairwise combination of every element of the quoted, comma-separated prefix-list, and every element from the suffix arguments. Each pairwise combination is joined with infix in the middle, and successive pairs are joined by separator. No expansion occurs on any of the arguments. No output occurs if either the prefix or suffix list is empty, but the lists can contain empty elements.
m4_define([a], [oops])dnl m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3]) ⇒a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3 m4_combine([, ], [[a], [b]], [-]) ⇒ m4_combine([, ], [[a], [b]], [-], []) ⇒a-, b- m4_combine([, ], [], [-], [1], [2]) ⇒ m4_combine([, ], [[]], [-], [1], [2]) ⇒-1, -2
Convert all instances of ‘[’, ‘]’, ‘#’, and ‘$’ within string into their respective quadrigraphs. The result is still a quoted string.
Flatten string into a single line. Delete all backslash-newline pairs, and replace all remaining newlines with a space. The result is still a quoted string.
Concatenate each arg, separated by separator.
joinall
uses every argument, while join
omits empty
arguments so that there are no back-to-back separators in the output.
The result is a quoted string.
m4_define([active], [ACTIVE])dnl m4_join([|], [one], [], [active], [two]) ⇒one|active|two m4_joinall([|], [one], [], [active], [two]) ⇒one||active|two
Note that if all you intend to do is join args with commas between
them, to form a quoted list suitable for m4_foreach
, it is more
efficient to use m4_dquote
.
This macro was introduced in Autoconf 2.62, and expands to a newline, followed by any text. It is primarily useful for maintaining macro formatting, and ensuring that M4 does not discard leading whitespace during argument collection.
Remove leading and trailing spaces and tabs, sequences of
backslash-then-newline, and replace multiple spaces, tabs, and newlines
with a single space. This is a combination of m4_flatten
and
m4_strip
. To determine if string consists only of bytes
that would be removed by m4_normalize
, you can use
m4_ifblank
.
Backslash-escape all characters in string that are active in regexps.
Split string into an M4 list of elements quoted by ‘[’ and ‘]’, while keeping white space at the beginning and at the end. If regexp is given, use it instead of ‘[\t ]+’ for splitting. If string is empty, the result is an empty list.
Strip whitespace from string. Sequences of spaces and tabs are
reduced to a single space, then leading and trailing spaces are removed.
The result is still a quoted string. Note that this does not interfere
with newlines; if you want newlines stripped as well, consider
m4_flatten
, or do it all at once with m4_normalize
. To
quickly test if string has only whitespace, use m4_ifblank
.
Add a text box around message, using frame as the border character above and below the message. The frame argument must be a single byte, and does not support quadrigraphs. The frame correctly accounts for the subsequent expansion of message. For example:
m4_define([macro], [abc])dnl m4_text_box([macro]) ⇒## --- ## ⇒## abc ## ⇒## --- ##
The message must contain balanced quotes and parentheses, although quadrigraphs can be used to work around this.
Break string into a series of whitespace-separated words, then output those words separated by spaces, and wrapping lines any time the output would exceed width columns. If given, prefix1 begins the first line, and prefix begins all wrapped lines. If prefix1 is longer than prefix, then the first line consists of just prefix1. If prefix is longer than prefix1, padding is inserted so that the first word of string begins at the same indentation as all wrapped lines. Note that using literal tab characters in any of the arguments will interfere with the calculation of width. No expansions occur on prefix, prefix1, or the words of string, although quadrigraphs are recognized.
For some examples:
m4_text_wrap([Short string */], [ ], [/* ], [20]) ⇒/* Short string */ m4_text_wrap([Much longer string */], [ ], [/* ], [20]) ⇒/* Much longer ⇒ string */ m4_text_wrap([Short doc.], [ ], [ --short ], [30]) ⇒ --short Short doc. m4_text_wrap([Short doc.], [ ], [ --too-wide ], [30]) ⇒ --too-wide ⇒ Short doc. m4_text_wrap([Super long documentation.], [ ], [ --too-wide ], 30) ⇒ --too-wide ⇒ Super long ⇒ documentation.
Return string with letters converted to upper or lower case, respectively.
Next: Set manipulation in M4, Previous: String manipulation in M4, Up: Programming in M4sugar [Contents][Index]
The following macros facilitate integer arithmetic operations.
Where a parameter is documented as taking an arithmetic expression, you
can use anything that can be parsed by m4_eval
.
Compare the arithmetic expressions expr-1 and expr-2, and expand to ‘-1’ if expr-1 is smaller, ‘0’ if they are equal, and ‘1’ if expr-1 is larger.
Compare the two M4 lists consisting of comma-separated arithmetic expressions, left to right. Expand to ‘-1’ for the first element pairing where the value from list-1 is smaller, ‘1’ where the value from list-2 is smaller, or ‘0’ if both lists have the same values. If one list is shorter than the other, the remaining elements of the longer list are compared against zero.
m4_list_cmp([1, 0], [1]) ⇒0 m4_list_cmp([1, [1 * 0]], [1, 0]) ⇒0 m4_list_cmp([1, 2], [1, 0]) ⇒1 m4_list_cmp([1, [1+1], 3],[1, 2]) ⇒1 m4_list_cmp([1, 2, -3], [1, 2]) ⇒-1 m4_list_cmp([1, 0], [1, 2]) ⇒-1 m4_list_cmp([1], [1, 2]) ⇒-1
This macro was introduced in Autoconf 2.62. Expand to the decimal value of the maximum arithmetic expression among all the arguments.
This macro was introduced in Autoconf 2.62. Expand to the decimal value of the minimum arithmetic expression among all the arguments.
Expand to ‘-1’ if the arithmetic expression expr is negative, ‘1’ if it is positive, and ‘0’ if it is zero.
This macro was introduced in Autoconf 2.53, but had a number of usability limitations that were not lifted until Autoconf 2.62. Compare the version strings version-1 and version-2, and expand to ‘-1’ if version-1 is smaller, ‘0’ if they are the same, or ‘1’ version-2 is smaller. Version strings must be a list of elements separated by ‘.’, ‘,’ or ‘-’, where each element is a number along with optional case-insensitive letters designating beta releases. The comparison stops at the leftmost element that contains a difference, although a 0 element compares equal to a missing element.
It is permissible to include commit identifiers in version, such as an abbreviated SHA1 of the commit, provided there is still a monotonically increasing prefix to allow for accurate version-based comparisons. For example, this paragraph was written when the development snapshot of autoconf claimed to be at version ‘2.61a-248-dc51’, or 248 commits after the 2.61a release, with an abbreviated commit identification of ‘dc51’.
m4_version_compare([1.1], [2.0]) ⇒-1 m4_version_compare([2.0b], [2.0a]) ⇒1 m4_version_compare([1.1.1], [1.1.1a]) ⇒-1 m4_version_compare([1.2], [1.1.1a]) ⇒1 m4_version_compare([1.0], [1]) ⇒0 m4_version_compare([1.1pre], [1.1PRE]) ⇒0 m4_version_compare([1.1a], [1,10]) ⇒-1 m4_version_compare([2.61a], [2.61a-248-dc51]) ⇒-1 m4_version_compare([2.61b], [2.61a-248-dc51]) ⇒1
Compares version against the version of Autoconf currently
running. If the running version is at version or newer, expand
if-new-enough, but if version is larger than the version
currently executing, expand if-old, which defaults to printing an
error message and exiting m4sugar with status 63. When given only one
argument, this behaves like AC_PREREQ
(see Dealing with Autoconf versions).
Remember that the autoconf philosophy favors feature checks over version
checks.
Next: Forbidden Patterns, Previous: Arithmetic computation in M4, Up: Programming in M4sugar [Contents][Index]
Sometimes, it is necessary to track a set of data, where the order does
not matter and where there are no duplicates in the set. The following
macros facilitate set manipulations. Each set is an opaque object,
which can only be accessed via these basic operations. The underlying
implementation guarantees linear scaling for set creation, which is more
efficient than using the quadratic m4_append_uniq
. Both set
names and values can be arbitrary strings, except for unbalanced quotes.
This implementation ties up memory for removed elements until the next
operation that must traverse all the elements of a set; and although
that may slow down some operations until the memory for removed elements
is pruned, it still guarantees linear performance.
Adds the string value as a member of set set. Expand if-uniq if the element was added, or if-dup if it was previously in the set. Operates in amortized constant time, so that set creation scales linearly.
Adds each value to the set set. This is slightly more
efficient than repeatedly invoking m4_set_add
.
Expands if-present if the string value is a member of set, otherwise if-absent.
m4_set_contains([a], [1], [yes], [no]) ⇒no m4_set_add([a], [1], [added], [dup]) ⇒added m4_set_add([a], [1], [added], [dup]) ⇒dup m4_set_contains([a], [1], [yes], [no]) ⇒yes m4_set_remove([a], [1], [removed], [missing]) ⇒removed m4_set_contains([a], [1], [yes], [no]) ⇒no m4_set_remove([a], [1], [removed], [missing]) ⇒missing
Expands to a single string consisting of all the members of the set
set, each separated by sep, which is not expanded.
m4_set_contents
leaves the elements in set but reclaims any
memory occupied by removed elements, while m4_set_dump
is a
faster one-shot action that also deletes the set. No provision is made
for disambiguating members that contain a non-empty sep as a
substring; use m4_set_empty
to distinguish between an empty set
and the set containing only the empty string. The order of the output
is unspecified; in the current implementation, part of the speed of
m4_set_dump
results from using a different output order than
m4_set_contents
. These macros scale linearly in the size of the
set before memory pruning, and m4_set_contents([set],
[sep])
is faster than
m4_joinall([sep]m4_set_listc([set]))
.
m4_set_add_all([a], [1], [2], [3]) ⇒ m4_set_contents([a], [-]) ⇒1-2-3 m4_joinall([-]m4_set_listc([a])) ⇒1-2-3 m4_set_dump([a], [-]) ⇒3-2-1 m4_set_contents([a]) ⇒ m4_set_add([a], []) ⇒ m4_set_contents([a], [-]) ⇒
Delete all elements and memory associated with set. This is linear in the set size, and faster than removing one element at a time.
Compute the relation between seta and setb, and output the result as a list of quoted arguments without duplicates and with a leading comma. Set difference selects the elements in seta but not setb, intersection selects only elements in both sets, and union selects elements in either set. These actions are linear in the sum of the set sizes. The leading comma is necessary to distinguish between no elements and the empty string as the only element.
m4_set_add_all([a], [1], [2], [3]) ⇒ m4_set_add_all([b], [3], [], [4]) ⇒ m4_set_difference([a], [b]) ⇒,1,2 m4_set_difference([b], [a]) ⇒,,4 m4_set_intersection([a], [b]) ⇒,3 m4_set_union([a], [b]) ⇒,1,2,3,,4
Expand if-empty if the set set has no elements, otherwise
expand if-elements. This macro operates in constant time. Using
this macro can help disambiguate output from m4_set_contents
or
m4_set_list
.
For each element in the set set, expand action with the
macro variable defined as the set element. Behavior is
unspecified if action recursively lists the contents of set
(although listing other sets is acceptable), or if it modifies the set
in any way other than removing the element currently contained in
variable. This macro is faster than the corresponding
m4_foreach([variable],
m4_indir([m4_dquote]m4_set_listc([set])), [action])
,
although m4_set_map
might be faster still.
m4_set_add_all([a]m4_for([i], [1], [5], [], [,i])) ⇒ m4_set_contents([a]) ⇒12345 m4_set_foreach([a], [i], [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])]) ⇒24 m4_set_contents([a]) ⇒135
Produce a list of arguments, where each argument is a quoted element
from the set set. The variant m4_set_listc
is unambiguous,
by adding a leading comma if there are any set elements, whereas the
variant m4_set_list
cannot distinguish between an empty set and a
set containing only the empty string. These can be directly used in
macros that take multiple arguments, such as m4_join
or
m4_set_add_all
, or wrapped by m4_dquote
for macros that
take a quoted list, such as m4_map
or m4_foreach
. Any
memory occupied by removed elements is reclaimed during these macros.
m4_set_add_all([a], [1], [2], [3]) ⇒ m4_set_list([a]) ⇒1,2,3 m4_set_list([b]) ⇒ m4_set_listc([b]) ⇒ m4_count(m4_set_list([b])) ⇒1 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))]) ⇒0 m4_set_add([b], []) ⇒ m4_set_list([b]) ⇒ m4_set_listc([b]) ⇒, m4_count(m4_set_list([b])) ⇒1 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))]) ⇒1
For each element in the set set, expand action with a single
argument of the set element. Behavior is unspecified if action
recursively lists the contents of set (although listing other sets
is acceptable), or if it modifies the set in any way other than removing
the element passed as an argument. This macro is faster than either
corresponding counterpart of
m4_map_args([action]m4_set_listc([set]))
or
m4_set_foreach([set], [var],
[action(m4_defn([var]))])
. It is possible to use m4_curry
if more than one argument is needed for action, although it is
more efficient to use m4_set_map_sep
in that case.
For each element in the set set, expand
pre[element]post
, additionally expanding sep
between elements. Behavior is unspecified if the expansion recursively
lists the contents of set (although listing other sets
is acceptable), or if it modifies the set in any way other than removing
the element visited by the expansion. This macro provides the most
efficient means for non-destructively visiting the elements of a set; in
particular, m4_set_map([set], [action])
is equivalent
to m4_set_map_sep([set], [action(], [)])
.
If value is an element in the set set, then remove it and
expand if-present. Otherwise expand if-absent. This macro
operates in constant time so that multiple removals will scale linearly
rather than quadratically; but when used outside of
m4_set_foreach
or m4_set_map
, it leaves memory occupied
until the set is later
compacted by m4_set_contents
or m4_set_list
. Several
other set operations are then less efficient between the time of element
removal and subsequent memory compaction, but still maintain their
guaranteed scaling performance.
Expand to the size of the set set. This implementation operates
in constant time, and is thus more efficient than
m4_eval(m4_count(m4_set_listc([set])) - 1)
.
Previous: Set manipulation in M4, Up: Programming in M4sugar [Contents][Index]
M4sugar provides a means to define suspicious patterns, patterns describing tokens which should not be found in the output. For instance, if an Autoconf configure script includes tokens such as ‘AC_DEFINE’, or ‘dnl’, then most probably something went wrong (typically a macro was not evaluated because of overquotation).
M4sugar forbids all the tokens matching ‘^_?m4_’ and ‘^dnl$’. Additional layers, such as M4sh and Autoconf, add additional forbidden patterns to the list.
Declare that no token matching pattern must be found in the
output. The output file is (temporarily) split into one word per line
as part of the autom4te
post-processing, with each line (and
therefore word) then being checked against the Perl regular expression
pattern. If the regular expression matches, and
m4_pattern_allow
does not also match, then an error is raised.
Comments are not checked; this can be a problem if, for instance, you have some macro left unexpanded after an ‘#include’. No consensus is currently found in the Autoconf community, as some people consider it should be valid to name macros in comments (which doesn’t make sense to the authors of this documentation: input, such as macros, should be documented by ‘dnl’ comments; reserving ‘#’-comments to document the output).
As an example, if you define your own macros that begin with ‘M_’
and are composed from capital letters and underscores, the specification
of m4_pattern_forbid([^M_[A-Z_]+])
will ensure all your macros
are expanded when not used in comments.
As an example of a common use of this macro, consider what happens in
packages that want to use the pkg-config
script via the
third-party PKG_CHECK_MODULES
macro. By default, if a developer
checks out the development tree but has not yet installed the pkg-config
macros locally, they can manage to successfully run autoconf
on the package, but the resulting configure file will likely
result in a confusing shell message about a syntax error on the line
mentioning the unexpanded PKG_CHECK_MODULES
macro. On the other hand,
if configure.ac includes m4_pattern_forbid([^PKG_])
, the
missing pkg-config macros will be detected immediately without allowing
autoconf
to succeed.
Of course, you might encounter exceptions to these generic rules, for instance you might have to refer to ‘$m4_flags’.
Any token matching pattern is allowed, including if it matches an
m4_pattern_forbid
pattern.
For example, Gnulib uses m4_pattern_forbid([^gl_])
to reserve the
gl_
namespace for itself, but also uses
m4_pattern_allow([^gl_ES$])
to avoid a false negative on the
valid locale name.
Previous: Programming in M4sugar, Up: Programming in M4 [Contents][Index]
At times, it is desirable to see what was happening inside m4, to see
why output was not matching expectations. However, post-processing done
by autom4te
means that directly using the m4 builtin
m4_traceon
is likely to interfere with operation. Also, frequent
diversion changes and the concept of forbidden tokens make it difficult
to use m4_defn
to generate inline comments in the final output.
There are a couple of tools to help with this. One is the use of the
--trace option provided by autom4te
(as well as each
of the programs that wrap autom4te
, such as
autoconf
), in order to inspect when a macro is called and with
which arguments. For example, when this paragraph was written, the
autoconf version could be found by:
$ autoconf --trace=AC_INIT configure.ac:23:AC_INIT:GNU<EMAIL_ADDRESS>$ autoconf --trace='AC_INIT:version is $2' version is 2.63b.95-3963
Another trick is to print out the expansion of various m4 expressions to
standard error or to an independent file, with no further m4 expansion,
and without interfering with diversion changes or the post-processing
done to standard output. m4_errprintn
shows a given expression
on standard error. For example, if you want to see the expansion of an
autoconf primitive or of one of your autoconf macros, you can do it like
this:
$ cat <<\EOF > configure.ac AC_INIT m4_errprintn([The definition of AC_DEFINE_UNQUOTED:]) m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED])) AC_OUTPUT EOF $ autoconf error→The definition of AC_DEFINE_UNQUOTED: error→_AC_DEFINE_Q([], $@)
Next: Writing Autoconf Macros, Previous: Programming in M4, Up: Autoconf [Contents][Index]
M4sh, pronounced “mash”, is aiming at producing portable Bourne shell scripts. This name was coined by Lars J. Aas, who notes that, according to the Webster’s Revised Unabridged Dictionary (1913):
Mash \Mash\, n. [Akin to G. meisch, maisch, meische, maische, mash, wash, and prob. to AS. miscian to mix. See “Mix”.]
- A mass of mixed ingredients reduced to a soft pulpy state by beating or pressure...
- A mixture of meal or bran and water fed to animals.
- A mess; trouble. [Obs.] –Beau. & Fl.
M4sh reserves the M4 macro namespace ‘^_AS_’ for internal use, and the namespace ‘^AS_’ for M4sh macros. It also reserves the shell and environment variable namespace ‘^as_’, and the here-document delimiter namespace ‘^_AS[A-Z]’ in the output file. You should not define your own macros or output shell code that conflicts with these namespaces.
Next: Support for indirect variable names, Up: Programming in M4sh [Contents][Index]
M4sh provides portable alternatives for some common shell constructs that unfortunately are not portable in practice.
Expand into shell code that will output text surrounded by a box with char in the top and bottom border. text should not contain a newline, but may contain shell expansions valid for unquoted here-documents. char defaults to ‘-’, but can be any character except ‘/’, ‘'’, ‘"’, ‘\’, ‘&’, or ‘`’. This is useful for outputting a comment box into log files to separate distinct phases of script operation.
Expand into a shell ‘case’ statement, where word is matched
against one or more patterns. if-matched is run if the
corresponding pattern matched word, else default is run.
See Prerequisite Macros for why
this macro should be used instead of plain ‘case’ in code
outside of an AC_DEFUN
macro, when the contents of the
‘case’ use AC_REQUIRE
directly or indirectly.
See Limitations of Shell Builtins,
for how this macro avoids some portability issues.
See Dealing with unbalanced parentheses
for how this macro lets you write code with balanced parentheses
even if your code must run on obsolescent shells.
Output the directory portion of file-name. For example,
if $file
is ‘/one/two/three’, the command
dir=`AS_DIRNAME(["$file"])`
sets dir
to ‘/one/two’.
This interface may be improved in the future to avoid forks and losing trailing newlines.
Emits word to the standard output, followed by a newline. word
must be a single shell word (typically a quoted string). The bytes of
word are output as-is, even if it starts with "-" or contains "\".
Redirections can be placed outside the macro invocation. This is much
more portable than using echo
(see Limitations of
Shell Builtins).
Emits word to the standard output, without a following newline. word must be a single shell word (typically a quoted string) and, for portability, should not include more than one newline. The bytes of word are output as-is, even if it starts with "-" or contains "\". Redirections can be placed outside the macro invocation.
Expands to string, with any characters in chars escaped with
a backslash (‘\’). chars should be at most four bytes long,
and only contain characters from the set ‘`\"$’; however,
characters may be safely listed more than once in chars for the
sake of syntax highlighting editors. The current implementation expands
string after adding escapes; if string contains macro calls
that in turn expand to text needing shell quoting, you can use
AS_ESCAPE(m4_dquote(m4_expand([string])))
.
The default for chars (‘\"$`’) is the set of characters needing escapes when string will be used literally within double quotes. One common variant is the set of characters to protect when string will be used literally within back-ticks or an unquoted here-document (‘\$`’). Another common variant is ‘""’, which can be used to form a double-quoted string containing the same expansions that would have occurred if string were expanded in an unquoted here-document; however, when using this variant, care must be taken that string does not use double quotes within complex variable expansions (such as ‘${foo-`echo "hi"`}’) that would be broken with improper escapes.
This macro is often used with AS_ECHO
. For an example, observe
the output generated by the shell code generated from this snippet:
foo=bar AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"]) ⇒"$foo" = "bar" m4_define([macro], [a, [\b]]) AS_ECHO(["AS_ESCAPE([[macro]])"]) ⇒macro AS_ECHO(["AS_ESCAPE([macro])"]) ⇒a, b AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"]) ⇒a, \b
To escape a string that will be placed within single quotes, use:
m4_bpatsubst([[string]], ['], ['\\''])
Emit code to probe whether file is a regular file with executable permissions (and not a directory with search permissions). The caller is responsible for quoting file.
Emit code to exit the shell with status, defaulting to ‘$?’.
This macro
works around shells that see the exit status of the command prior to
exit
inside a ‘trap 0’ handler (see Limitations
of Shell Builtins).
Run shell code test1. If test1 exits with a zero status then run shell code run-if-true1, else examine further tests. If no test exits with a zero status, run shell code run-if-false, with simplifications if either run-if-true1 or run-if-false is empty. For example,
AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])], [test "x$foo" != xno], [HANDLE_FOO([maybe])], [echo foo not specified])
ensures any required macros of HANDLE_FOO
are expanded before the first test.
This macro should be used instead of plain ‘if’ in code
outside of an AC_DEFUN
macro, when the contents of the ‘if’
use AC_REQUIRE
directly or indirectly (see Prerequisite Macros).
Make the directory file-name, including intervening directories
as necessary. This is equivalent to ‘mkdir -p -- file-name’,
except that it is portable to older versions of mkdir
that
lack support for the -p option or for the --
delimiter (see Limitations of Usual Tools). Also,
AS_MKDIR_P
succeeds if file-name is a symbolic link to an existing directory,
even though Posix is unclear whether ‘mkdir -p’ should
succeed in that case. If creation of file-name fails, exit the
script.
Also see the AC_PROG_MKDIR_P
macro (see Particular Program Checks).
Emit shell code to set the value of ‘$?’ to status, as
efficiently as possible. However, this is not guaranteed to abort a
shell running with set -e
(see Limitations of Shell
Builtins). This should also be used at the end of a complex shell
function instead of ‘return’ (see Shell Functions) to avoid
a DJGPP shell bug.
Transform expression into a valid right-hand side for a C #define
.
For example:
# This outputs "#define HAVE_CHAR_P 1". # Notice the m4 quoting around #, to prevent an m4 comment type="char *" echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
Transform expression into shell code that generates a valid shell
variable name. The result is literal when possible at m4 time, but must
be used with eval
if expression causes shell indirections.
For example:
# This outputs "Have it!". header="sys/some file.h" eval AS_TR_SH([HAVE_$header])=yes if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
Set the polymorphic shell variable var to dir/file, but optimizing the common cases (dir or file is ‘.’, file is absolute, etc.).
Unsets the shell variable var, working around bugs in older shells (see Limitations of Shell Builtins). var can be a literal or indirect variable name.