Search code examples
autotoolsautomakelibtool

How to append arguments to the end of the libtool-generated compiler command line in GNU Build System?


I'm trying to cross-compile a project with GNU autotools and MinGW.

This project uses winsock2 API which needs the -lws2_32 flag, and with normal usage (using CFLAGS or AM_LDFLAGS), the flag will not work anyway and I always get the following error message:

undefined reference to `__imp_WSACleanup'

# and a lot of other undefined references which belongs to winsock2

After some research, I found that the flag -lws2_32 must be put at the end of the compiler command, otherwise it will not work.

With manually running the compiler command with a -lws2_32 flag at the end, I confirmed this will work for me, thus, the TRUE question approaches:

What is the proper way to append arguments to the end of the compiler command line which is generated by libtool in GNU Build System (autotools)?

I did some research for this, but the only way I've found is hacking libtool, seems this is not the proper way to do this.


Solution

  • This project uses winsock2 API which needs the -lws2_32 flag, and with normal usage (using CFLAGS or AM_LDFLAGS), the flag will not work

    Putting library names in *_LDFLAGS is not normal or even correct usage, largely because of precisely the issue you describe. Link commands are sensitive to the order of arguments, and generally, libraries need to be named after the object files that reference them. The LDFLAGS family of variables are expanded early in each link command line, before the target's object files.

    What is the proper way to append arguments to the end of the compiler command line which is generated by libtool in GNU Build System (autotools)?

    There are several ways to approach that. The most conventional one is to use AC_CHECK_LIB or AC_SEARCH_LIBS in your configure.ac. For instance,

    # configure.ac ...
    
    AC_SEARCH_LIBS([WSACleanup], [ws2_32], [], [AC_MSG_ERROR([Could not find required library libws2_32])])
    
    # ...
    

    By default, when these successfully locate the library, they prepend the appropriate library flag to the LIBS output variable, whose contents are expanded late in each link command line. Thus, this approach does not require any corresponding support in your Makefile.am.


    The other primary alternatives are the LDADD family of variables (for linking program targets) and the LIBADD family of variables (for linking library targets). LDADD and LIBADD themselves apply to all programs and all libraries, respectively, defined in the same Makefile.am, or you can prefix them with a target name to specify libraries for that target alone (for example, foo_LIBADD). For instance,

    # Makefile.am ...
    
    bin_PROGRAMS = myprog
    
    # ...
    
    myprog_LDADD = -lws2_32
    
    # ...
    

    Consult the Automake manual for more details.