Search code examples
cmakefileautotools

How to include -lm in Makefile.am or configure.ac


I have a program called neuromz that I compile using

gcc neuromz.c -lm -o neuromz

It's work fine but if I try to add to my project a configure.ac and Makefile.am, with Makefile.am:

bin_PROGRAMS = neuromz
neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h 
neuromz_CFLAGS = -lm

the result is:

/home/mz/programming/ctest/ANN/ann.c:11: undefined reference to `exp'
/home/mz/programming/ctest/ANN/ann.c:11: undefined reference to `exp'

How can I fix it?


Solution

  • As @MikeKinghan already described, the Automake variables for specifying extra libraries into a program are *_LDADD. I'll add, however, that if you're only building one program, or if all of the programs you're building need the same libraries, then you can use LDADD instead. This can be more convenient, and it sometimes produces smaller Makefile's, too:

    bin_PROGRAMS = neuromz
    LDADD = -lm
    
    neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h 
    

    HOWEVER, if you're satisfied to make a once-for-all decision about libm for the programs built by your build system, then I'd recommend handling it in Autoconf instead of Automake. If you put this in your configure.ac ...

    AC_SEARCH_LIBS([sqrt], [m])
    

    ... then

    • Your configure script will check whether libm needs to be explicitly linked at all (which depends on your environment and tool chain), and will add -lm only if necessary.

    • You don't then need to say anything about it in your Makefile.am, nor be concerned with which Automake variable to use.