Best practices with autotools

2365

Author: Diego "Flameeyes" Pettenò

The core of GNU’s compile chain — the set of tools used to build GNU software packages — is the so-called “autotools,” a term that refers to the autoconf and automake programs, as well as libtoolize, autoheader, pkg-config, and sometimes gettext. These tools let you compile GNU software on a wide variety of platforms and Unix and Unix-like operating systems, providing developers a framework to check for the presence of the libraries, functions, and tools that they want to use. While autotools are great in the hands of an experienced developer, they can be quite a handful for the first-time user, and it’s not so rare that packages are shipped with working-but-broken autotools support. This article will cover some of the most common errors people make when using autotools and ways to achieve better results.

Regardless of anyone’s opinion about them, we currently have no valid alternative for autotools. Projects such as Scons are not as portable as autotools, and they don’t embody enough knowledge to be useful yet. We have tons of automatic checks with autotools, and a lot of libraries come with an m4 library with macros to check for their presence.

The basic structure of an autotooled project is simple. Autoconf uses a configure.ac file (formerly configure.in) written in m4 language to create a configure script with the help of an aclocal.m4 file (created by aclocal using the m4 libraries on its search path and acinclude.m4 file). For every directory there’s a Makefile.am file, used by automake to create the Makefile.in templates, which are processed and transformed in the real makefiles by the configure script. You can also avoid using automake and just write your own Makefile.in files, but this is quite complex, and you lose a few features of autotools.

In a configure.ac file you can use macros you define yourself, the default ones provided by autoconf and aclocal, or external macros provided, for instance, by other packages. In such a case aclocal will create the aclocal.m4 file adding the library files it finds on the system’s library with the defined macros; this is a critical step to have a working autotooled project, as we’ll see in a moment.

A Makefile.am is mainly a declaration of intents: you can fill some targets variables with the name of the targets you want to build. These variables are structured in a format like placetoinstall_TYPEOFTARGET. The place is the location in a hierarchical Unix filesystem (bin, lib, include, …), a non-used keyword that can be defined with an arbitrary path (using the keyworddir variable), or the special keyword noinst that marks the targets that need not to be installed (for example private headers, or static libraries used during build). After naming the target, you can use the name (replacing dots with underscores) as the prefix for the variables that affects its build. In this way you can provide special CFLAGS, LDFLAGS, and LDADD variables used during the build of a single target, instead of changing them for all the targets. You can also use variables collected during configure phase, if you passed them to the AC_SUBST macro in configure.ac, so that they are replaced inside makefiles. Also, though defining CFLAGS and LDFLAGS on a per-target basis seems useful, adding static flags in Makefile.am is a bad thing for portability, as you can’t tell if the compiler you’re using supports them, or if you really need them (-ldl put in LDFLAGS is a good example of a flag needed on Linux but not on FreeBSD); in such cases you should use configure.ac to add these flags.

The most commonly used macros in configure.ac are AC_CHECK_HEADERS, AC_CHECK_FUNCTS, and AC_CHECK_LIB, which test for the presence of, respectively, some header files, some library functions, and a given library (with a specific function in it). They are important for portability as they provides a way to check which headers are present and which are not (for example system headers that have different locations in different operating systems), and to check whether a function is present in the system library (asprintf() is missing in OpenBSD for example, while it’s present on GNU C library and FreeBSD), and finally to check for the presence of some third-party library or to see if a specific link to a library is needed to get some functions (for example dlopen() function is in libdl library on GNU systems, while it’s provided by the system’s C library on FreeBSD).

Along with testing for the presence or absence of functions or headers (and sometimes libraries) you usually need to change the code’s path (for example to avoid the use of missing functions, or to define a drop-in replacement for them). Autoconf is commonly coupled with another tool, autoheader, which creates a config.h.in template, used by configure script to create a config.h header in which are defined a few preprocessor macros in form of HAVE_givenfunction or HAVE_givenheader_H which can be tested with #ifdef/#ifndef directives inside a C or C++ source file to change the code according to the features present.

Here are some practices to keep in mind to help you use autotools to create the most portable code possible.

The config.h header file should be considered to be an internal header file, so it should be used just by the single package in which it’s created. You should avoid editing the config.h.in template to add your own code there, as this requires you to manually update it according to the configure.ac you’re writing.

Unfortunately a few projects, such as Net-SNMP, export this header file with other libraries’ headers, which requires any projects that use their libraries to include them (or provide their own copy of the internal Net-SNMP structures). This is a bad thing, as the autotools structure of a library project should be invisible to software using it (which might not use autotools at all). Also, changes in autotools behavior are anything but rare, so you can have two identical checks with different results due to changes in the way they are executed. If you need to define your own wrappers or replacements in case something is not in the environment you’re compiling for, you should do that in private headers that do not get installed (declared as noinst_HEADERS in Makefile.am files).

Always provide the m4 files you used. As autotools have been in use for years, many packages (for example libraries) that can be reused by other programs provide an m4 library file in /usr/share/aclocal that makes it possible to check for their presence (for example using the -config scripts) with a simple macro call. These files are used by aclocal to create the aclocal.m4 file, and they usually are present on the developers’ systems where aclocal is executed to create the release, but when they are for optional dependencies, they can be missing on users’ systems. While this is usually not a problem, because users rarely executes aclocal, it’s a problem for source distributions, such as Gentoo, where sometimes you need to patch a Makefile.am or the configure.ac and then re-run autoconf without having all the optional dependencies installed (or having different versions, which can be incompatible or bugged, of the same m4 file).

To avoid this problem, you should create an m4 subdirectory in your package’s directory and then put there the m4 library files you are using. You must then call aclocal with aclocal -I m4 options to search in that directory before the system library. You can then choose whether to put that directory under revision control (CVS, SVN, or whatever else you are using) or just create it for the releases. The latter case is the bare minimum requirement for a package. It minimizes the amount of revision-controlled code and ensures that you’re always using the latest m4 version, but has the drawback that anyone who checks out your repository won’t be able to execute autoconf without having to look on a release tarball to take the m4 from (and that might not work, as you can have updated the configure.ac to suit a newer macro or added more dependencies). On the other hand, putting the m4 directory under revision control sometimes tempts the developers to change the macros to suit their needs. Although this seems logical, as the m4 files are under your revision control, it will upset many package maintainers, as sometimes new versions of m4 files fix bugs or support newer options and installation paths (for example multilib setups), and having the m4 files modified makes it impossible to just replace them with updated versions. It also mean that when you’re going to update an m4 file you must redo the modification against the original.

m4 files are always a problem to work with. They must replicate almost the same code from library to library (depending on the way you need to provide CFLAGS/LDFLAGS: with tests or with a -config script). To avoid this problem, the GNOME and FreeDesktop projects developed a tool called pkg-config, which provides both an executable binary and an m4 file to include in configure.ac files, and lets developers check for the presence of a given library (and/or package), provided that the package itself installed a pkg-config .pc data file. This approach simplifies the work of maintaining configure.ac scripts, and requires a lot less time to be processed during execution of configure script, as it uses the information provided by the installed package itself instead of just trying if it’s present. On the other hand, this approach means that an error the developers make concerning a dependency can break the user program, as they just hardcode the compiler and linker flags in the data file and the configure script doesn’t actually check whether the library works. Fortunately, this doesn’t happen too often.

To create the configure file, you need PKG_CHECK_MODULES, contained in the pkg.m4 library. You should add that file to your m4 directory. If pkg-config dependency is mandatory (as the tool is run by the configure script) you can’t be sure that the m4 file you are using is the same as one on users’ systems, nor you can be sure that it does not include extra bugs, as it can be older than yours.

Always check for the libraries you’re going to link to, if you have them as mandatory dependencies. Usually autoconf macros or pkg-config data files define prerequisite libraries that you need to successfully link to your library. Also, some functions that are in extra libraries in some systems (like dlopen() in libdl on Linux and Mac OS X) can be in the libc of another system (the same function is in libc on FreeBSD). In these cases you need to check whether the function can be found without linking to anything, or if you need to use a specific library (for example to avoid linking to a non-existent libdl that would fail where it’s not needed).

Be careful with GNU extensions. One of the things that makes portability a big pain is the use of extension functions, which are provided by GNU libc but aren’t present on other C libraries like BSD’s or uClibc. When you use such functions, you should always provide a “drop-in replacement,” a function that can provide the same functionality as the library function, maybe with less performance or security, which can be used when the extension function is not present on system’s C library. Those functions must be protected by a #ifdef HAVE_function ... #endif block, so that they don’t get duplicated when they are already present. Make sure that these functions are not exported by the library to the external users; they should be declared inside an internal header, to avoid breaking other libraries that may be doing similar tricks.

Avoid compiling OS-specific code when not needed. When a program optionally supports specific libraries or specific operating systems, it’s not rare to have entire source files that are specific to that code path. To avoid compiling them when they’re not needed, use the AM_CONDITIONAL macro inside a configure.ac file. This automake macro (usable only if you’re using automake to build the project) allows you to define if .. endif blocks inside a Makefile.am file, inside which you can set special variables. You can, for example, add a “platformsrcs” variable that you set to the right source file for the platform to build for, then use in a _SOURCES variable.

However, there are two common errors developers make when using AM_CONDITIONAL. The first is the use of AM_CONDITIONAL in an already conditional branch (for example under an info or in a case switch), which leads to automake complaining about a conditional defined only conditionally (AM_CONDITIONAL must be called on global scope, out of every if block, so you must define a variable to contain the status of the conditions and then test against when calling the AM_CONDITIONAL). The other one is that you can’t change the targets’ variables directly, and you must define “commodity” variables, whose results empty out of the conditional, to add or remove source files and targets.

Many projects, to avoid compiling code for specific code paths, add the entire files in #ifdef ... #endif preprocessor conditionals. While this usually works, it makes the code ugly and error-prone, as a single statement out of the conditional block can be compiled where the source file is not needed. It also misleads users sometimes, as the source files seem to be compiled in situations where they don’t make sense.

Be smart in looking for operating system or hardware platform. Sometimes you need to search for a specific operating system or hardware platform. The right way to do this depends on where you need to know this. If you must know it to enable extra tests on configure, or you must add extra targets on makefiles, you must do the check in configure.ac. On the other hand, if the difference must be known in a source file, for example to enable an optional asm-coded function, you should rely directly on the compiler/preprocessor, so you should use #ifdef directives with the default macros enabled on the target platform (for example __linux__, __i386__, _ARC_PPC, __sparc__, _FreeBSD_ and __APPLE__).

Don’t run commands in configure.ac. If you need to check for hardware or operating system in a configure.ac, you should avoid using the uname command, despite this being one of the most common way to do such a test. This is actually an error, as this breaks crosscompilation. Autotools supports crosscompile projects from one machine to another using hosts definitions: strings in the form “hardware-vendor-os” (actually, “hardware-vendor-os-libc” when GNU libc is used), such as i686-pc-linux-gnu and x86_64-unknown-freebsd5.4. CHOST is the host definition for the system you’re compiling the software for, CBUILD is the host definition for the system you’re compiling on; when CHOST and CBUILD differ, you’re crosscompiling.

In the examples above, the first host definition shows an x86-like system, with a pentium2-equivalent (or later) processor, running a Linux kernel with a GNU libc (usually this refers to a GNU/Linux system). The second refers to an AMD64 system with a FreeBSD 5.4 operating system. (For a GNU/kFreeBSD system, which uses FreeBSD kernel and GNU libc, the host definition is hw-unknown-freebsd-gnu, while for a Gentoo/FreeBSD, using FreeBSD’s kernel and libc, but with Gentoo framework, the host definition is hw-gentoo-freebsd5.4.) By using $host and $build variables inside a configure.ac script you can enable or disable specific features based on the operating system or on the hardware platform you’re compiling to or on.

Don’t abuse “automagic” dependencies. One of the most useful features of autotools are the automatic checks for the presence of a library, which are often used to automatically enable support for extra dependencies and such. However, abusing this feature makes the build of a package a bit of a problem. While this is quite useful for first-time users, and although most of the projects having complex dependencies (such as multimedia programs like xine and VLC) use a plugin-based framework that allows them to avoid most of the breakages, “automagic” dependencies are a great pain for packagers, especially ones working on source-based distributions such as Gentoo and ports-like frameworks. When you build something with automagical dependencies you enable the functions supported by the libraries found on the system on which the configure script is run. This means that the output binaries might not work on a system that shares the same base packages but misses one extra library, for example. Also, you can’t tell the exact dependencies of a package, as some might be optional and not be built when the libraries are not present.

To avoid this, autoconf allows you to add –enable/–disable and –with/–without options to configure scripts. With such options you can forcefully enable or disable a specific option (such as the support for an extra library or for a specific feature), and leave the default to automatic tests.

Unfortunately, many developers misunderstand the meaning of the two parameters of the functions used to add those options (AC_ARG_ENABLE and AC_ARG_WITH). They represent the code to execute when a parameter is passed and when one is not. Many developers mistakenly think that the two parameters define the code to execute when the feature is enabled and when is disabled. While this usually works when you pass a parameter just to change the default behavior, many source-based distributions pass parameters also to confirm the default behavior, which leads to errors (features explicitely requested missing). Being able to disable optional features if they don’t add dependencies (think of OSS audio support on Linux) is always a good thing for users, who can avoid building extra code if they don’t plan to use it, and prevents maintainers from doing dirty caching tricks to enable or disable features as their users request.

While autotools were a big problem for both developers and maintainers because there are different incompatible versions that do not get along well together (since they install in the same places, with the same names) and which are used in different combinations, the use of autotools saves maintainers from doing all sorts of dirty tricks to compile software. If you look at ebuild from Gentoo’s portage, the few that do not use autotools are the more complex ones, as they need to check variables on very different setups (we can or not have NPTL support; we can be on Linux, FreeBSD, or Mac OS X; we can be using GLIBC or another libc; and so on), while autotools usually take care of that on their own. It’s also true that many patches applied by maintainers are to fix broken autotools script in upstream sources, but this is just a little problem compared to the chaos of using special build systems that don’t work at all with little environmental changes.

Autotools can be quite tricky for newcomers, but when you start using them on a daily basis you find it’s a lot easier than having to deal with manual makefiles or other strange build tools such as imake or qmake, or even worse, special autotools-like build scripts that try to recognize the system they are building on. Autotools makes it simple to support new OSes and new hardware platforms, and saves maintainers and porters from having to learn how to custom-build a system to fix compilation. By carefully writing a script, developers can support new platforms without any changes at all.