gcccompiler-errorslinkerposition

Compile error gcc -lpthread position


This work:

    gcc a.o b.o -o a -lpthread

This does not work:

    gcc -lpthread a.o b.o -o a

and shows some errors like this:

undefined reference to `pthread_create'

So when I compile using Makefile, it generate

    gcc -lpthread a.o b.o -o a

Which does not work.

Any ideas?

P.S: I am using gcc 4.6.3/Ubuntu 12.04


Solution

  • First of all, you want to use -pthread, not -lpthread, when compiling with pthread - -pthread may enable some compile-time options that are required for the program to work in multhithreaded environment.

    The problem isn't really with your command line - it's a problem with GNU ld. GNU ld, upon encountering an -lXXX option, reads all the symbols defined by libXXX.so or libXXX.a, checks if any of those symbols have been mentioned in files that have been specified before the -lXXX option in the command line, and forgets about the rest of the symbols.

    In other words: command line order of object files and libraries changes behavior of the linker.

    This might've been reasonable back when computers had really limited memory, but nowadays it's just a silly artifact from long forgotten times, that should've been already fixed some time ago.

    Of course, there might arise a problem of linking with several libraries defining the same symbol, but there certainly are saner ways to allow expected behavior for such cases.


    Bottom line: for GNU ld (which is called by gcc), only the first command from your question is valid, because ld still lives in the previous computing era.

    For extra sanity, use -pthread both when linking and compiling your pthread-related programs.