5

So my questions is: Why do you need '-lpthread' at the end of a compiling command?

Why does this command work:

gcc -o name name.c -lpthread

but this won't:

gcc -o name name.c

I am using the pthread.h library in my c code.
I already looked online for some answers but didn't really find anything that answered it understandably

Lundin
  • 195,001
  • 40
  • 254
  • 396
T H
  • 365
  • 1
  • 2
  • 9
  • Presumably because pthreads isn't standard C. All libs that aren't standard C are linked with `-lsomething`. – Lundin Nov 26 '19 at 14:58
  • https://stackoverflow.com/questions/23250863/difference-between-pthread-and-lpthread-while-compiling – Mat Nov 26 '19 at 15:00

2 Answers2

8

pthread.h is not a library it is just a header file which gives you declaration (not the actual body of function) of functions which you will be using for multi-threading.

using -libpthread or -lpthread while compiling actually links the GCC library pthread with your code. Hence the compiler flag, -libLIBRARY_NAME or -lLIBRARY_NAME is essential.

If you don't include the flags -l or -lib with LIBRARY_NAME you won't be able to use the external libraries.

In this case, say if you are using functions pthread_create and pthread_join, so you'll get an error saying:

undefined reference to `pthread_create'

undefined reference to `pthread_join'
  • 1
    a header file (which is informally called as .h file) only contains declaration of functions. where as a library which can be static library (.a file) or dynamic library (.dll file on windows & .so file on linux distributions) consist of binary version of code (it's more than that) but that's the most simplest explanation which I can find out. for more information refer. https://www.geeksforgeeks.org/difference-header-file-library/ – Prajwal Shetye Nov 26 '19 at 15:16
5

The -l options tells the linker to link in the specified external library, in this case the pthread library.

Including pthread.h allows you to use the functions in the pthread library in you code. However, unlike the functions declared in places like studio.h or stdlib.h, the actual code for the functions in pthread.h are not linked in by default.

So if you use functions from this library and fail to use -lpthread, the linking phase will fail because it will be unable to find functions in the library such as pthread_create, among others.

dbush
  • 205,898
  • 23
  • 218
  • 273