1

I am writing a c code on ubuntu that creates a certain number of threads I have already added pthreads library but when I run the code it ends up with this error

Threads.cc:(.text+0x128): undefined reference to 'pthread_create'

Threads.cc:(.text+0x15b): undefined reference to 'pthread_join'

I am using ubuntu 15.04 virtual machine. I have tried many suggested solutions, non of them worked! any help would be appreciated

1 Answers1

1

I have already added pthreads library [..]

No. You haven't. If you did you wouldn't get this problem. You probably mean to say you included <pthread.h>. But that doesn't link with pthreads library.

Add pthread at the end of your compilation options. For example,

gcc -o out myfile.c -pthread
P.P
  • 117,907
  • 20
  • 175
  • 238
  • yes it worked .. thank you very much:) – Rand Krayshan Dec 03 '15 at 13:09
  • I just had the same problem, but my script was already adding `-lpthread`. It was supposed to work fine. But maybe this directive is compiler dependent ? – Cyan Feb 24 '17 at 08:07
  • @Cyan `-pthread` (or `-lpthread`) should at the end of the compilation command. What compiler are you using? Can't tell without seeing the full compilation command. – P.P Feb 24 '17 at 08:09
  • @P.P : can't tell ... both `-pthread` and `-lpthread` work fine on all targets and computers I could test directly. This involves gcc from 4.4 to 6.2, and clang from 3.5 to 3.9, linux and os-x. Problem happens on some remote machine I have little information about. This machine prefers `-pthread`, and would fail with `-lpthread`. I don't even know its compiler ... – Cyan Feb 24 '17 at 18:35
  • 1
    @Cyan `-pthread` vs `-lpthread` makes no difference on recent (10 years or so) GCC toolchains. "This machine prefers -pthread, and would fail with -lpthread" <- this suggests that machine is sufficiently old. I always compile with `-pthread` so that I don't have to remember these details (of GCC). Perhaps, you could do the same (and make your script compile with `-pthread` -- this must be inserted *at* the end of compile options i.e. libraries must after the object/C files you compile). – P.P Feb 24 '17 at 18:45