6. Conditional Builds

It is common for source files or build flags to only be needed conditionally, for example if they are only needed on particular host operating systems, or they implement an optional feature.

To implement conditionality, automake provides the AM_CONDITIONAL macro, and conditional blocks in Makefile.am files.

The parameters of AM_CONDITIONAL are as follows

AM_CONDITIONAL(block-name, test-expression)
block-name

A literal string that will be used to reference the conditional case. A valid block name starts with a letter and includes only letters, numbers and the underscore symbol. By unwritten convention, this is usually all capitals.

test-expression

A conditional expression that will be evaluated within a AS_IF block. A shell expression the return value of which is used to determine whether the block is true or false. Commonly using test for comparison of strings.

The block syntax is extremely simple, as it is implemented as simple if/else/endif blocks in Makefile.am:

if block-name
  # Normal syntax
else
  # More normal syntax
endif

Caveat: AM_CONDITIONAL Cannot be Conditional

Because of a quirk of implementation, the calls to AM_CONDITIONAL have to be expanded unconditionally in the configure script. This means that you cannot use AM_CONDITIONAL within an AS_IF block or equivalent.

Instead, you should either repeat the same test as the block, or (if the conditionals themselves are complicated) use a convenience variable to hold the value the conditional can provide:

AS_IF([test "x$host_os" != "xdarwin"], [needextralib=yes],
    [test "x$host_cpu" = "xpowerpc"], [needextralib=yes])

AM_CONDITIONAL([EXTRALIB], [test "x$needextralib" = "xyes"])

Example 2.9.  Using AM_CONDITIONAL with configure Options

Another common usage pattern for conditionals is to enable optional features. In this case, the conditional is subordinate to an autoconf option, see Section 3, “Adding Options”.

AC_ARG_ENABLE([feature],
    AS_HELP_STRING([--disable-feature], [Disable feature]))
AM_CONDITIONAL([FEATURE], [test "x$enable_feature" != "xno"])