Compiling C source code using autotools

If you’ve built any c based packages on any flavor of Unix for development, you might be aware of following steps,

./configure 
make
make install

It does 3 things,

  1. Configure the software
  2. Build the software
  3. Install the software

Programs that are built in this way have usually been packaged using a suite of programs collectively referred as autotools. It includes autoconf, automake and many other programs, all of which work together to make the life of a software maintainer significantly easier.

Hello World

Here is the hello.c file,

#include <stdio.h>
int main(int argc, char* argv[]) 
{
printf("Hello world\n");
return 0;
}

Now, we will need a file called configure.ac, which is written in m4sh — a combination of m4 macros and POSIX shell script — to describe what the configure script needs to do.

AC_INIT([helloworld], [0.1], [mehul]) 
AM_INIT_AUTOMAKE
AC_PROG_CC
AC_CONFIG_FILES([Makefile])
AC_OUTPUT

Next, we will create a Makefile.am file, which will be used by automake to generate Makefile.in,

AUTOMAKE_OPTIONS = foreign 
bin_PROGRAMS = hello
hello_SOURCES = hello.c

The bin prefix tells automake that the file listed here should be installed to the directory defined by the variable bindir.

Putting it all together

First, we need to generate an m4 environment for autotools to use,

aclocal

Now, we can run autoconf to turn configure.ac => configure and automake to turn Makefile.am => Makefile.in

autoconf
automake --add-missing

Running your program

./configure
make
./hello

Have a cheerful day… :)

Reference: Robots

Like what you read? Give Mehul Prajapati a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.