Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need '-lpthread'?

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

like image 531
T H Avatar asked Nov 26 '19 14:11

T H


2 Answers

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'
like image 69
Prajwal Shetye Avatar answered Oct 16 '22 08:10

Prajwal Shetye


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.

like image 39
dbush Avatar answered Oct 16 '22 08:10

dbush