Search code examples
cautotoolsautoconf

How to have different build options for two programs in the same autotools project


I have a simple autotools project with two programs: one and two.

Only one of the program depends on a library (math in this example), and I would like that the other program not to be linked with this library.

Here are my files:

configure.ac

AC_INIT([test], [0.1], [[email protected]])
AC_CONFIG_AUX_DIR([build-aux])
AM_INIT_AUTOMAKE([foreign -Wall -Werror])
AC_PROG_CC
AC_CHECK_LIB([m], [log])
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([Makefile])
AC_OUTPUT    

Makefile.am

bin_PROGRAMS = one two
one_SOURCES = one.c
two_SOURCES = two.c

one.c (headers removed)

int main(void)
{
    /* do depend on lib math*/
    printf("log[15] = %f\n", log(15));
    return 0;
}

two.c (headers removed)

int main(void)
{
    /* do NOT depend on lib math*/
    printf("15 = %d\n", 15);
    return 0;
}

When I build this

autoreconf --install
./configure
make

The programs are well build :

# compilation 
gcc .... -c -o one.o one.c
# link
gcc .... -o one one.o -lm
# compilation 
gcc .... -c -o two.o two.c
# link THE PROBLEM IS HERE, I don't want `-lm` to be added here
gcc .... -o two two.o -lm     

Solution

  • Only one of the program depends on a library (math in this example), and I would like that the other program not to be linked with this library.

    It takes some care to build programs with different options in the same Autotools project. The usual approach is to create separate output variables for those bits that are not common to all projects, and use them in your Makefile.am to define appropriate per-target build variables.

    In your example, it is the link options specifying the math library that are target-specific, so you need to capture them in their own variable. The AC_CHECK_LIB and AC_SEARCH_LIBS macros both prepend the appropriate library link option to the LIBS output variable, which is one of the sources from which Automake draws global link options, so if you use these, you need to also do something to avoid the math library option from remaining in LIBS. Alternatively, you could devise some other mechanism for testing the math library options.

    One good trick would be to save the value of LIBS before running AC_CHECK_LIB, extract the math library options, if any, afterward, and then restore the original value of LIBS. This is a relatively common Autoconf idiom. For example,

    LIBS_save=$LIBS
    
    AC_CHECK_LIB([m], [log])
    
    LIBM_LDFLAGS=${LIBS%${LIBS_save}}
    AC_SUBST([LIBM_LDFLAGS])
    
    LIBS=$LIBS_save
    

    Your Makefile.am might then look like so:

    bin_PROGRAMS = one two
    
    one_SOURCES = one.c
    one_LDADD = $(LIBM_LDFLAGS)
    
    two_SOURCES = two.c