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
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With