Undefined reference to pthread_create in Linux

CLinuxMultithreadingPthreads

C Problem Overview


I picked up the following demo off the web from https://computing.llnl.gov/tutorials/pthreads/

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

But when I compile it on my machine (running Ubuntu Linux 9.04) I get the following error:

corey@ubuntu:~/demo$ gcc -o term term.c
term.c: In function ‘main’:
term.c:23: warning: incompatible implicit declaration of built-in functionexit’
/tmp/cc8BMzwx.o: In function `main':
term.c:(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

This doesn't make any sense to me, because the header includes pthread.h, which should have the pthread_create function. Any ideas what's going wrong?

C Solutions


Solution 1 - C

For Linux the correct command is:

gcc -pthread -o term term.c

In general, libraries should follow sources and objects on command line, and -lpthread is not an "option", it's a library specification. On a system with only libpthread.a installed,

gcc -lpthread ...

will fail to link.

Solution 2 - C

For Linux the correct command is:

gcc -o term term.c -lpthread
  1. you have to put -lpthread just after the compile command,this command will tell to the compiler to execute program with pthread.h library.
  2. gcc -l links with a library file.Link -l with library name without the lib prefix.

Solution 3 - C

in eclipse

properties->c/c++Build->setting->GCC C++ linker->libraries in top part add "pthread"

Solution 4 - C

Running from the Linux terminal, what worked for me was compiling using the following command (suppose the c file I want to compile is called test.c):

gcc -o test test.c -pthread

Hope it helps somebody!

Solution 5 - C

If you are using cmake, you can use:

add_compile_options(-pthread)

Or

SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")

Solution 6 - C

I believe the proper way of adding pthread in CMake is with the following

find_package (Threads REQUIRED)

target_link_libraries(helloworld
    ${CMAKE_THREAD_LIBS_INIT}
)

Solution 7 - C

Acutally, it gives several examples of compile commands used for pthreads codes are listed in the table below, if you continue reading the following tutorial:

https://computing.llnl.gov/tutorials/pthreads/#Compiling

enter image description here

Solution 8 - C

Compile it like this : gcc demo.c -o demo -pthread

Solution 9 - C

In Visual Studio 2019 specify -pthread in the property pages for the project under:

> Linker -> Command Line -> Additional Options

Type in -pthread in the textbox.

Solution 10 - C

You need to use the option -lpthread with gcc.

Solution 11 - C

you need only Add "pthread" in proprieties=>C/C++ build=>GCC C++ Linker=>Libraries=> top part "Libraries(-l)". thats it

Solution 12 - C

check man page and you will get.

Compile and link with -pthread.

SYNOPSIS
       #include <pthread.h>

       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);


       Compile and link with -pthread.
       ....

Solution 13 - C

Since none of the answers exactly covered my need (using MSVS Code), I add here my experience with this IDE and CMAKE build tools too.

Step 1: Make sure in your .cpp, (or .hpp if needed) you have included:

#include <functional>

Step 2 For MSVSCode IDE users: Add this line to your c_cpp_properties.json file:

"compilerArgs": ["-pthread"],

Add this line to your c_cpp_properties.json file

Step 2 For CMAKE build tools users: Add this line to your CMakeLists.txt

set(CMAKE_CXX_FLAGS "-pthread")

Note: Adding flag -lpthread (instead of -pthread) results in failed linking.

Solution 14 - C

In Anjuta, go to the Build menu, then Configure Project. In the Configure Options box, add:

LDFLAGS='-lpthread'

Hope it'll help somebody too...

Solution 15 - C

Sometimes, if you use multiple library, check the library dependency. (e.g. -lpthread -lSDL... <==> ... -lSDL -lpthread)

Solution 16 - C

From man gcc,

  -pthread
       Define additional macros required for using the POSIX threads library.
       You should use this option consistently for both compilation and linking.
       This option is supported on GNU/Linux targets, 
           most other Unix derivatives, 
           and also on x86 Cygwin and MinGW targets.

It is correct that -pthread is an option and the best way to handle this. There are statements in some answers that it generates different compiled code. This is misleading.

If you wish to duplicate -pthread, you could use -lpthread -D_REENTRANT=1. So there are two things going on with the -pthread option.

Indeed it links with the pthread library as many answers express. Also, the order of the pthread library is important because it may override some weak symbols. So a correct version using -lpthread may need to have it multiple times on the command line.

The other important part is the _REENTRANT define. Note, that this is in the implementation namespace. Some people may care for portability and other not. However, it is very important that it is defined as the first thing in the compilation unit. This symbol will alter the way that many system headers files are parsed.

You can include #define _REENTRANT 1 at the top of every source file, but it is much easier to have it on the command line. Again, the -pthread is the best way to achieve this. Also, gcc may change the way this is implemented in the future. However, I think it is important for programmers to understand what is going on.


> term.c: In function ‘main’: term.c:23: warning: incompatible implicit > declaration of built-in function ‘exit’

You never included <stdlib.h>, where exit() is declared. Also, I think newer versions of gcc have removed the need for _REENTRANT.

So, it is NOT generating different code. Ie, the backend of the compiler is NOT different. It is only conditional compilation and linking to different libraries. It does not generate 'lock free' code or add appropriate machine barriers because you have used this option.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRalphView Question on Stackoverflow
Solution 1 - CEmployed RussianView Answer on Stackoverflow
Solution 2 - CGopika BGView Answer on Stackoverflow
Solution 3 - CsamView Answer on Stackoverflow
Solution 4 - CAlexander NenartovichView Answer on Stackoverflow
Solution 5 - CJayhelloView Answer on Stackoverflow
Solution 6 - CRufusView Answer on Stackoverflow
Solution 7 - CdylannininView Answer on Stackoverflow
Solution 8 - CleesagaciousView Answer on Stackoverflow
Solution 9 - CWBuckView Answer on Stackoverflow
Solution 10 - CxiaolongView Answer on Stackoverflow
Solution 11 - CsamView Answer on Stackoverflow
Solution 12 - Ckalu WangView Answer on Stackoverflow
Solution 13 - CSold OutView Answer on Stackoverflow
Solution 14 - CnaXa stands with UkraineView Answer on Stackoverflow
Solution 15 - Cuser1793997View Answer on Stackoverflow
Solution 16 - Cartless noiseView Answer on Stackoverflow