Thursday, November 5, 2015

Supporting Out-Of-Source-Code-Tree Build with Autotools

Some opensource code are not trivial to be build out of it's source (code) tree. This is especially true in some opensource libraries because they generate intermediate file(s) which must be handled accordingly. But, fear not, there are two Autoconf constructs (or rather internal variables) that can help you tame this wild library code. They are $(top_srcdir) and $(top_builddir). Refer to Autoconf Preset Output Variables for their details.

I'll take libevent as a real-world example because this library generates an intermediate header file at build time which must be included in the build process (event-config.h). This is where $(top_srcdir) and $(top_builddir) come into play. If you want to be able to build out-of-source-tree, you need to include this generated file into your application code that uses libevent. You use $(top_builddir) for that. In the meantime, you also need to include the "ordinary" include file in the source tree, and that's where $(top_srcdir) comes into play.

Let's assume, your source tree looks like below and your application links to this particular libevent version statically:
.
├── libevent-2.0.22-stable
│   ├── autom4te.cache
│   ├── compat
│   │   └── sys
│   ├── include
│   │   └── event2
│   ├── m4
│   ├── sample
│   ├── test
│   └── WIN32-Code
│       └── event2
└── your_application_code_dir

In your_application_code_dir, you need to have a Makefile.am file with the following contents:
### NOTE:
### $(top_builddir) is required for libevent because there is 
### an include file (event-config.h) that is generated at build-time.
### This file will be in the build directory instead of the source code 
### directory if you build out-of-tree.
###
AM_CPPFLAGS = -I$(top_srcdir)/libevent-2.0.22-stable/include \
       -I$(top_builddir)/libevent-2.0.22-stable/include
  

## Omitted for clarity .. 

bin_PROGRAMS = your_program_name

your_program_name_SOURCES = your_program_name.c
your_program_name_LDADD = $(top_builddir)/libevent-2.0.22-stable/libevent_core.la

## Omitted for clarity .. 
The code in Makefile.am above (placed in your_application_code_dir) should be enough to make it possible to build libevent out-of-source-tree. As you see, both the include file in the build directory (out of the source code tree) and the include file in the source code tree are included. This should make it less of hassle to keep your source code tree clean all the time. Especially if you are using RCS such as subversion, git or mercurial.

Hopefully this helps those who intend to always build autotools code out-of-(source)-tree.
Post a Comment

No comments: