543

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 function ‘exit’
/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?

6
  • 7
    Additionally: depending on the platform, you may need (a) a different compiler for threads, (b) a different libc for threads (i.e. -lc_r), (c) -thread or -threads or other, instead of or in addition to -lpthread.
    – ephemient
    Commented Nov 3, 2009 at 1:42
  • Just a little above that example, you'll see a table of the correct compiler commands, whether it be GCC, IBM, etc. 'Employed Russian' is correct. Commented Jun 26, 2011 at 6:47
  • 10
    Can you please unmark my answer, so that I can delete it (and mark the one that is actually correct, which is the highest-voted one)? Commented Nov 22, 2012 at 0:41
  • 6
    -lpthread is needed during compile
    – How Chen
    Commented Jan 28, 2014 at 8:21
  • 12
    solution LDFLAGS= -pthread -lpthread
    – dsnk
    Commented Oct 29, 2015 at 9:01

16 Answers 16

922

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.

Read this or this detailed explanation.

11
  • 6
    +1 this solution worked... otheres did not. Also, suggestion that 'libraries should follow sources and objects' is great advice -- a citation or further explanation would be great.
    – sholsapp
    Commented Jan 13, 2012 at 3:02
  • 9
    @sholsapp Here is the explanation: webpages.charter.net/ppluzhnikov/linker.html Commented Jan 13, 2012 at 4:33
  • 2
    This still errored for me till I put -lpthread at the very end of my command. gcc term.c -lpthread
    – CornSmith
    Commented Apr 18, 2013 at 23:49
  • 5
    For anyone using CODEBLOCKS: Add -pthread to Project Build Options -> Linker Settings -> Other linker options. Commented Oct 4, 2015 at 13:23
  • 1
    "On a system with only libpthread.a installed"...... or libpthread.so , right ? Commented Apr 13, 2019 at 18:04
56

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.
2
  • 1
    It's not a good idea to use a non-standard flag when a standard flag exists that has the same function on your platform. Commented Sep 25, 2019 at 2:01
  • This worked for me ... other solutions didn't Commented Dec 8, 2022 at 10:57
45

in eclipse

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

2
  • Same tip applyes in code::project (and I think others IDE too)
    – Fil
    Commented Jan 29, 2017 at 17:00
  • 1
    I know this might be a little late, but. If you cannot find the C/C++ Build setting in the properties (I couldn't, maybe it's by installation or a bug), then there is a direct lower level workaround using the CMakeLists.txt file. You need to insert SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread") before the add_executable command. This will instruct the linker to do the same (see CMAKE_EXE_LINKER_FLAGS and SET documentation for more help). Commented Sep 10, 2020 at 7:13
36

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!

1
  • confirmed in Ubuntu 16.x
    – ingconti
    Commented Mar 22, 2021 at 11:21
32

If you are using cmake, you can use:

add_compile_options(-pthread)

Or

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

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}
)
1
  • 7
    This has the same effect but used the Threads::Threads target rather than the CMAKE_THREAD_LIBS_INIT variable. target_link_libraries(helloworld PUBLIC Threads::Threads) Commented Aug 9, 2020 at 16:34
20

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

11

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

0
8

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.

2
  • When I do that, I get the error "pthread: No such file or directory"
    – Niko O
    Commented Oct 26, 2021 at 12:40
  • My link was failing in a Release build but succeeding in the Debug build. It turns out that the -pthread was missing from the Release build. Make sure both build environments match.
    – J. Martin
    Commented Sep 22, 2022 at 14:43
4

You need to use the option -lpthread with gcc.

2
  • 8
    wrong information! -lpthread is not an "option", it specifies a library.
    – user1709175
    Commented Jul 13, 2015 at 17:32
  • 1
    a command line option (in contrast to a command line argument) Commented Jun 19, 2019 at 16:36
4

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

0
4

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.
       ....
4

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.

3

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.

1
  • _REENTRANT is an example that was used with some GCC versions. Newer standards, etc may change the structure that is used to alter they system/compiler headers depending on what language version, OS and C library is used. Commented Apr 3, 2022 at 22:01
0

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

LDFLAGS='-lpthread'

Hope it'll help somebody too...

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.