Next: , Previous: , Up: Tutorial   [Contents][Index]

4.5 Adding a configure flag

You may wish to give users a way to enable or disable features when they build the program. This can be done by adding an option that they can use when invoking your configure script.

For example, suppose the features implemented in the program in the previous section with the GMP library are optional. We can provide a --without-libgmp option to disable the use of the library.

Here is the check in

    [AS_HELP_STRING([--without-libgmp],[Disable use of libgmp]),,
if test "x$with_libgmp" != xno; then
  AC_CHECK_LIB([gmp], [__gmpz_add])
  if test "x$ac_cv_lib_gmp___gmpz_add" = xno; then
    AC_MSG_ERROR([libgmp is required])
  # Is the AC_DEFINE actualy required?
  AC_DEFINE([HAVE_LIBGMP], [1], [Define if you have libgmp])


AC_ARG_WITH adds two command-line options to the configure script based on its first argument, in this case ‘--with-libgmp’ and ‘--without-libgmp’. If either of these is given, AC_ARG_WIDTH sets the shell variable ‘with_libgmp’ to an appropriate value.

The second argument uses AS_HELP_STRING to format a line which AC_ARG_WIDTH adds to the output of ‘./configure --help’:

Optional Packages:
  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
  --without-libgmp        Disable use of libgmp

The third argument to AC_ARG_WITH is shell code for it to execute if the use gave either the --with and --without options to configure: in our example, this argument is blank. The fourth argument is shell code to execute if neither of these options were given; in this case we default to trying to use the library.

This example introduces the use of the AC_DEFINE macro, which defines a C preprocessor symbol, just as ‘HAVE_LIBGMP’ was defined by AC_CHECK_LIB. This provides a way other than output variables for a configure script to have an effect on how make builds software. The first argument to AC_DEFINE is the name of a preprocessor symbol, and the second argument is the value for the symbol to take.

This use of the AC_CONFIG_HEADERS macro places preprocessor symbol definitions set by AC_DEFINE in a C header file called config.h. This header file can be included by the other source files for the program to get these definitions. Before, we passed the values of these symbols on the command-line via the DEFS output variable. The configure script still sets DEFS, but its value is now ‘-DHAVE_CONFIG_H -I.’.

In order to update the build system after adding a use of AC_DEFINE, you need to run autoreconf. This creates a template file for config.h, called (autoreconf runs a program called autoheader to do this.)

In your C source files you can then include the header file with

#include <config.h>

and conditionally use code using preprocessor conditionals:

/* Code using libgmp */

Next: , Previous: , Up: Tutorial   [Contents][Index]