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

9. Writing Autoconf Macros

When you write a feature test that could be applicable to more than one software package, the best thing to do is encapsulate it in a new macro. Here are some instructions and guidelines for writing Autoconf macros.

9.1 Macro Definitions  Basic format of an Autoconf macro
9.2 Macro Names  What to call your new macros
9.3 Reporting Messages  Notifying autoconf users
9.4 Dependencies Between Macros  What to do when macros depend on other macros
9.5 Obsoleting Macros  Warning about old ways of doing things
9.6 Coding Style  Writing Autoconf macros à la Autoconf


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

9.1 Macro Definitions

Autoconf macros are defined using the AC_DEFUN macro, which is similar to the M4 builtin m4_define macro. In addition to defining a macro, AC_DEFUN adds to it some code that is used to constrain the order in which macros are called (see section 9.4.1 Prerequisite Macros).

An Autoconf macro definition looks like this:

 
AC_DEFUN(macro-name, macro-body)

You can refer to any arguments passed to the macro as `$1', `$2', etc. See section `How to define new macros' in GNU m4, for more complete information on writing M4 macros.

Be sure to properly quote both the macro-body and the macro-name to avoid any problems if the macro happens to have been previously defined.

Each macro should have a header comment that gives its prototype, and a brief description. When arguments have default values, display them in the prototype. For example:

 
# AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
# --------------------------------------
m4_define([AC_MSG_ERROR],
[{ _AC_ECHO([configure: error: $1], 2); exit m4_default([$2], 1); }])

Comments about the macro should be left in the header comment. Most other comments will make their way into `configure', so just keep using `#' to introduce comments.

If you have some very special comments about pure M4 code, comments that make no sense in `configure' and in the header comment, then use the builtin dnl: it causes m4 to discard the text through the next newline.

Keep in mind that dnl is rarely needed to introduce comments; dnl is more useful to get rid of the newlines following macros that produce no output, such as AC_REQUIRE.


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

9.2 Macro Names

All of the Autoconf macros have all-uppercase names starting with `AC_' to prevent them from accidentally conflicting with other text. All shell variables that they use for internal purposes have mostly-lowercase names starting with `ac_'. To ensure that your macros don't conflict with present or future Autoconf macros, you should prefix your own macro names and any shell variables they use with some other sequence. Possibilities include your initials, or an abbreviation for the name of your organization or software package.

Most of the Autoconf macros' names follow a structured naming convention that indicates the kind of feature check by the name. The macro names consist of several words, separated by underscores, going from most general to most specific. The names of their cache variables use the same convention (see section 7.3.1 Cache Variable Names, for more information on them).

The first word of the name after `AC_' usually tells the category of feature being tested. Here are the categories used in Autoconf for specific test macros, the kind of macro that you are more likely to write. They are also used for cache variables, in all-lowercase. Use them where applicable; where they're not, invent your own categories.

C
C language builtin features.
DECL
Declarations of C variables in header files.
FUNC
Functions in libraries.
GROUP
UNIX group owners of files.
HEADER
Header files.
LIB
C libraries.
PATH
The full path names to files, including programs.
PROG
The base names of programs.
MEMBER
Members of aggregates.
SYS
Operating system features.
TYPE
C builtin or declared types.
VAR
C variables in libraries.

After the category comes the name of the particular feature being tested. Any further words in the macro name indicate particular aspects of the feature. For example, AC_FUNC_UTIME_NULL checks the behavior of the utime function when called with a NULL pointer.

An internal macro should have a name that starts with an underscore; Autoconf internals should therefore start with `_AC_'. Additionally, a macro that is an internal subroutine of another macro should have a name that starts with an underscore and the name of that other macro, followed by one or more words saying what the internal macro does. For example, AC_PATH_X has internal macros _AC_PATH_X_XMKMF and _AC_PATH_X_DIRECT.


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

9.3 Reporting Messages

When macros statically diagnose abnormal situations, benign or fatal, they should report them using these macros. For dynamic issues, i.e., when configure is run, see 7.4 Printing Messages.

Macro: AC_DIAGNOSE (category, message)
Report message as a warning (or as an error if requested by the user) if it falls into the category. You are encouraged to use standard categories, which currently include:

`all'
messages that don't fall into one of the following category. Use of an empty category is equivalent.

`cross'
related to cross compilation issues.

`obsolete'
use of an obsolete construct.

`syntax'
dubious syntactic constructs, incorrectly ordered macro calls.

Macro: AC_WARNING (message)
Equivalent to `AC_DIAGNOSE([syntax], message)', but you are strongly encouraged to use a finer grained category.

Macro: AC_FATAL (message)
Report a severe error message, and have autoconf die.

When the user runs `autoconf -W error', warnings from AC_DIAGNOSE and AC_WARNING are reported as error, see 3.4 Using autoconf to Create configure.


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

9.4 Dependencies Between Macros

Some Autoconf macros depend on other macros having been called first in order to work correctly. Autoconf provides a way to ensure that certain macros are called if needed and a way to warn the user if macros are called in an order that might cause incorrect operation.

9.4.1 Prerequisite Macros  Ensuring required information
9.4.2 Suggested Ordering  Warning about possible ordering problems


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

9.4.1 Prerequisite Macros

A macro that you write might need to use values that have previously been computed by other macros. For example, AC_DECL_YYTEXT examines the output of flex or lex, so it depends on AC_PROG_LEX having been called first to set the shell variable LEX.

Rather than forcing the user of the macros to keep track of the dependencies between them, you can use the AC_REQUIRE macro to do it automatically. AC_REQUIRE can ensure that a macro is only called if it is needed, and only called once.

Macro: AC_REQUIRE (macro-name)
If the M4 macro macro-name has not already been called, call it (without any arguments). Make sure to quote macro-name with square brackets. macro-name must have been defined using AC_DEFUN or else contain a call to AC_PROVIDE to indicate that it has been called.

AC_REQUIRE must be used inside an AC_DEFUN'd macro; it must not be called from the top level.

AC_REQUIRE is often misunderstood. It really implements dependencies between macros in the sense that if one macro depends upon another, the latter will be expanded before the body of the former. In particular, `AC_REQUIRE(FOO)' is not replaced with the body of FOO. For instance, this definition of macros:

 
AC_DEFUN([TRAVOLTA],
[test "$body_temparature_in_celsius" -gt "38" &&
  dance_floor=occupied])
AC_DEFUN([NEWTON_JOHN],
[test "$hair_style" = "curly" &&
  dance_floor=occupied])

AC_DEFUN([RESERVE_DANCE_FLOOR],
[if date | grep '^Sat.*pm' >/dev/null 2>&1; then
  AC_REQUIRE([TRAVOLTA])
  AC_REQUIRE([NEWTON_JOHN])
fi])

with this `configure.ac'

 
AC_INIT
RESERVE_DANCE_FLOOR
if test "$dance_floor" = occupied; then
  AC_MSG_ERROR([cannot pick up here, let's move])
fi

will not leave you with a better chance to meet a kindred soul at other times than Saturday night since it expands into:

 
test "$body_temperature_in_Celsius" -gt "38" &&
  dance_floor=occupied
test "$hair_style" = "curly" &&
  dance_floor=occupied
fi
if date | grep '^Sat.*pm' >/dev/null 2>&1; then


fi

This behavior was chosen on purpose: (i) it prevents messages in required macros from interrupting the messages in the requiring macros; (ii) it avoids bad surprises when shell conditionals are used, as in:

 
if ...; then
  AC_REQUIRE([SOME_CHECK])
fi
...
SOME_CHECK

You are encouraged to put all AC_REQUIREs at the beginning of a macro. You can use dnl to avoid the empty lines they leave.


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

9.4.2 Suggested Ordering

Some macros should be run before another macro if both are called, but neither requires that the other be called. For example, a macro that changes the behavior of the C compiler should be called before any macros that run the C compiler. Many of these dependencies are noted in the documentation.

Autoconf provides the AC_BEFORE macro to warn users when macros with this kind of dependency appear out of order in a `configure.ac' file. The warning occurs when creating configure from `configure.ac', not when running configure.

For example, AC_PROG_CPP checks whether the C compiler can run the C preprocessor when given the `-E' option. It should therefore be called after any macros that change which C compiler is being used, such as AC_PROG_CC. So AC_PROG_CC contains:

 
AC_BEFORE([$0], [AC_PROG_CPP])dnl

This warns the user if a call to AC_PROG_CPP has already occurred when AC_PROG_CC is called.

Macro: AC_BEFORE (this-macro-name, called-macro-name)
Make m4 print a warning message to the standard error output if called-macro-name has already been called. this-macro-name should be the name of the macro that is calling AC_BEFORE. The macro called-macro-name must have been defined using AC_DEFUN or else contain a call to AC_PROVIDE to indicate that it has been called.


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

9.5 Obsoleting Macros

Configuration and portability technology has evolved over the years. Often better ways of solving a particular problem are developed, or ad-hoc approaches are systematized. This process has occurred in many parts of Autoconf. One result is that some of the macros are now considered obsolete; they still work, but are no longer considered the best thing to do, hence they should be replaced with more modern macros. Ideally, autoupdate should substitute the old macro calls with their modern implementation.

Autoconf provides a simple means to obsolete a macro.

Macro: AU_DEFUN (old-macro, implementation, [message])
Define old-macro as implementation. The only difference with AC_DEFUN is that the user will be warned that old-macro is now obsolete.

If she then uses autoupdate, the call to old-macro will be replaced by the modern implementation. The additional message is then printed.


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

9.6 Coding Style

The Autoconf macros follow a strict coding style. You are encouraged to follow this style, especially if you intend to distribute your macro, either by contributing it to Autoconf itself, or via other means.

The first requirement is to pay great attention to the quotation, for more details, see 3.1.2 The Autoconf Language, and 8.1 M4 Quotation.

Do not try to invent new interfaces. It is likely that there is a macro in Autoconf that resembles the macro you are defining: try to stick to this existing interface (order of arguments, default values, etc.). We are conscious that some of these interfaces are not perfect; nevertheless, when harmless, homogeneity should be preferred over creativity.

Be careful about clashes both between M4 symbols and between shell variables.

If you stick to the suggested M4 naming scheme (see section 9.2 Macro Names), you are unlikely to generate conflicts. Nevertheless, when you need to set a special value, avoid using a regular macro name; rather, use an "impossible" name. For instance, up to version 2.13, the macro AC_SUBST used to remember what symbols were already defined by setting AC_SUBST_symbol, which is a regular macro name. But since there is a macro named AC_SUBST_FILE, it was just impossible to `AC_SUBST(FILE)'! In this case, AC_SUBST(symbol) or _AC_SUBST(symbol) should have been used (yes, with the parentheses)...or better yet, high-level macros such as AC_EXPAND_ONCE.

No Autoconf macro should ever enter the user-variable name space; i.e., except for the variables that are the actual result of running the macro, all shell variables should start with ac_. In addition, small macros or any macro that is likely to be embedded in other macros should be careful not to use obvious names.

Do not use dnl to introduce comments: most of the comments you are likely to write are either header comments which are not output anyway, or comments that should make their way into `configure'. There are exceptional cases where you do want to comment special M4 constructs, in which case dnl is right, but keep in mind that it is unlikely.

M4 ignores the leading spaces before each argument, use this feature to indent in such a way that arguments are (more or less) aligned with the opening parenthesis of the macro being called. For instance, instead of

 
AC_CACHE_CHECK(for EMX OS/2 environment,
ac_cv_emxos2,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
[ac_cv_emxos2=yes], [ac_cv_emxos2=no])])

write

 
AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
                   [ac_cv_emxos2=yes],
                   [ac_cv_emxos2=no])])

or even

 
AC_CACHE_CHECK([for EMX OS/2 environment],
               [ac_cv_emxos2],
               [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
                                                   [return __EMX__;])],
                                  [ac_cv_emxos2=yes],
                                  [ac_cv_emxos2=no])])

When using AC_TRY_RUN or any macro that cannot work when cross-compiling, provide a pessimistic value (typically `no').

Feel free to use various tricks to prevent auxiliary tools, such as syntax-highlighting editors, from behaving improperly. For instance, instead of:

 
m4_bpatsubst([$1], [$"])

use

 
m4_bpatsubst([$1], [$""])

so that Emacsen do not open a endless "string" at the first quote. For the same reasons, avoid:

 
test $[#] != 0

and use:

 
test $[@%:@] != 0

Otherwise, the closing bracket would be hidden inside a `#'-comment, breaking the bracket-matching highlighting from Emacsen. Note the preferred style to escape from M4: `$[1]', `$[@]', etc. Do not escape when it is unneeded. Common examples of useless quotation are `[$]$1' (write `$$1'), `[$]var' (use `$var'), etc. If you add portability issues to the picture, you'll prefer `${1+"$[@]"}' to `"[$]@"', and you'll prefer do something better than hacking Autoconf :-).

When using sed, don't use `-e' except for indenting purpose. With the s command, the preferred separator is `/' unless `/' itself is used in the command, in which case you should use `,'.

See section 9.1 Macro Definitions, for details on how to define a macro. If a macro doesn't use AC_REQUIRE and it is expected to never be the object of an AC_REQUIRE directive, then use define. In case of doubt, use AC_DEFUN. All the AC_REQUIRE statements should be at the beginning of the macro, dnl'ed.

You should not rely on the number of arguments: instead of checking whether an argument is missing, test that it is not empty. It provides both a simpler and a more predictable interface to the user, and saves room for further arguments.

Unless the macro is short, try to leave the closing `])' at the beginning of a line, followed by a comment that repeats the name of the macro being defined. This introduces an additional newline in configure; normally, that is not a problem, but if you want to remove it you can use `[]dnl' on the last line. You can similarly use `[]dnl' after a macro call to remove its newline. `[]dnl' is recommended instead of `dnl' to ensure that M4 does not interpret the `dnl' as being attached to the preceding text or macro output. For example, instead of:

 
AC_DEFUN([AC_PATH_X],
[AC_MSG_CHECKING([for X])
AC_REQUIRE_CPP()
# ...omitted...
  AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
fi])

you would write:

 
AC_DEFUN([AC_PATH_X],
[AC_REQUIRE_CPP()[]dnl
AC_MSG_CHECKING([for X])
# ...omitted...
  AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
fi[]dnl
])# AC_PATH_X

If the macro is long, try to split it into logical chunks. Typically, macros that check for a bug in a function and prepare its AC_LIBOBJ replacement should have an auxiliary macro to perform this setup. Do not hesitate to introduce auxiliary macros to factor your code.

In order to highlight the recommended coding style, here is a macro written the old way:

 
dnl Check for EMX on OS/2.
dnl _AC_EMXOS2
AC_DEFUN(_AC_EMXOS2,
[AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
ac_cv_emxos2=yes, ac_cv_emxos2=no)])
test "$ac_cv_emxos2" = yes && EMXOS2=yes])

and the new way:

 
# _AC_EMXOS2
# ----------
# Check for EMX on OS/2.
define([_AC_EMXOS2],
[AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
                   [ac_cv_emxos2=yes],
                   [ac_cv_emxos2=no])])
test "$ac_cv_emxos2" = yes && EMXOS2=yes[]dnl
])# _AC_EMXOS2


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

This document was generated by Dirk Vermeir on May, 8 2002 using texi2html