Start a GNU Autotools C/C++ project

Gnu Autotools is a suite of tools used to create a portable build system mainly used for compiling C/C++ projects. This post serves as a quick reference for using Autotools to get started building a new C/C++ project. I assume you know enough Unix to be dangerous.

Get Started:
If you don’t already have automake, install it now:

sudo apt-get install automake

Create a new configure.ac in the root of your new project directory.

ACPREREQ(2.59) ACINIT(hello world, 1.0, yourname@youremail.org) ACCANONICALSYSTEM # create a cross platform build system AMINITAUTOMAKE # init automake ACPROGCC #check for C compiler ACPROGCXX #check for C++ compiler ACARGENABLE([debug], ASHELPSTRING([--enable-debug], [compile with -g -O0]), [echo "compiling with -g -O0" CFLAGS="-g -O0" CXXFLAGS="-g -O0" ] ) #output Makefiles ACCONFIGFILES([ Makefile ]) AC_OUTPUT

Now run

touch NEWS README AUTHORS ChangeLog && autoreconf -i

Every time you make changes to the configure.ac, you need to re-run autoreconf -i to re-generate a new configure script.

Create a Makefile.am

binPROGRAMS = hello helloSOURCES = main.c

This Makefile.am will create a executable called ‘hello’ and it will be installed in the ‘bin’ directory. Automake takes care of setting up build rules for you. All you have to do is list the sources the are needed to build your modules. Even things like code dependencies are done for you.

Build libraries
When it comes to building libraries, you get two choices: runlib or libtool. Runlib is the basic way to create static libraries. Libtool is a bit more advanced but can be a bit more flexable.

Runlib:
configure.ac:

AC_PROG_RANLIB

Makefile.am:

libLIBRARIES = mymodule.a mymodulea_SOURCES = file.c file.h

Libtool:
configure.ac:

LT_INIT

Makefile.am:

libLTLIBRARIES = mymodule.la mymodulelaSOURCES = file.c file.h mymodulela_HEADERS = something.h #declare public headers that will be installed

Things you can add to your configure.ac to make it better

  • Configuration headers

    ACCONFIGHEADERS([config.h]) #setup config header

  • Check for external modules
    PKGCHECKMODULES( FFMPEG, libavutil libavformat libavcodec libswscale, , )

This checks for external module. This creates a $FFMPEGLIBS and $FFMPEGCFLAGS. Later you can use these to compile your program. Modify your Makefile.am with:

mymodulelaCPPFLAGS = $(FFMPEGCFLAGS) mymodulelaLIBADD = $(FFMPEGLIBS)

More info on PKGCHECKMODULES macro and Using libraries with automake and autoconfig.

  1. Check for C++ compiler
    ACPROGCXX

  2. Create tests
    Makefile.am:

    checkPROGRAMS = test1 test1SOURCES = test1.c test1LDADD = libmylib.la test1LDFLAGS = -no-install

The -no-install is important because otherwise, libtool will create a wrapper script that probally will not play nice with your debugger. (See Libtool Wrapers for more details)

Paul Soucy

Read more posts by this author.