clinker

Two functions from the same library: why does one generate undefined reference while the other doesn't?


I want to replace pthread_mutex_lock by pthread_mutex_trylock in a function and when I do so, I get the "undefined reference" error message (See below). If I replace the lines 411-13 by pthread_mutex_lock(&cmd_queue_lock), I don't get the linker error.

They are both from the same library which I already include. Why does one generate the linker error and the other doesn't? More importantly, how can I fix it? I tried adding "extern int pthread_mutex_trylock" and changing the order of the .o files in Makefile but both don't work.

$ nl clientmain.c

    12  #include <stdio.h>
    ...
    21  #include <pthread.h>

    411 if (pthread_mutex_trylock(&cmd_queue_lock) == EBUSY) {
    412     continue;
    413 }

$ make
clientmain.o: In function `createHC':
clientmain.c:411: undefined reference to `pthread_mutex_trylock'
collect2: ld returned 1 exit status
make: *** [clientmain] Error 1

Solution

  • Admittedly I can't find any reference to a manual page telling this, but adding -lpthread to your final linking phase will probably do the job. I found it by looking for the symbol pthread_mutex_trylock in all /usr/lib/lib*.a files and /usr/lib/libpthread.a was the only one defining the symbol. Reverse engineering.

    The manual page of gcc does say that you can/should use the -pthread option to gcc to include POSIX thread support, so that is probably the royal route. This option worked on my system too. Interestingly the regular /usr/lib/libc.a does offer the pthread_mutex_lock but not the pthread_mutex_trylock so that caused your confusion. Note that the manual page of gcc is also saying that this option has effect on preprocessing, so it may be more and better than just linking against /usr/lib/libpthread.a.