0

I have this simple c-code

It works fine when i link it as

gcc  -g app.c.o  -o app  -lrt -lpthread -lc

But if we change order of linking libc and libthread

gcc  -g app.c.o  -o app  -lrt -lc -lpthread

it does not work.

We know on FreeBSD stubs of pthread-functions in libc are made as weak reference. For example

objdump -T /lib/libc.so.7 | grep pthread_cond_signal
00000000000e2bf0  w   DF .text  0000000000000011  FBSD_1.0    pthread_cond_signal

It means order of linking is not matter. Why so?

andreych
  • 181
  • 6
  • I've found the same issue http://lists.freebsd.org/pipermail/freebsd-hackers/2011-April/035083.html, but i dont undestand why linker choose libc's fork, not libthr. fork is made as weak reference too. – andreych Jun 17 '13 at 14:29

2 Answers2

1

Compile and link using the option -pthread. Note the missing "ell".


Update:

  • -pthread instructs all tools involved in creating a binary (pre-processor, compiler, linker) to take care that the application/library to be build runs as intended. (This obviously is only necessary if the source makes use of any member(s) of the pthread_*-family of functions.)

  • Whereas -lpthread links a library called libpthread, nothing more and nothing less.

The difference in detail is implementation specific.

Note: if -pthread has been specified -lpthread is not necessary as well as not recommended to be specfied.

alk
  • 69,737
  • 10
  • 105
  • 255
0

The reason for the behavior is that the linker only does a single pass through the libraries in the provided order to resolve symbols.

So, it needs to know about the pthread_* functions from -lpthread before it can resolve references to those functions in later libraries.

I believe the use of weak references is so that you can have functions in -lc that need -lpthread, but if you don't reference those functions in -lc than it isn't an error that its references to pthread_* couldn't be resolved.

TheDreamer
  • 36
  • 1
  • 4