As I know, if I want to use pthread library in linux environment I must include pthread.h and compile the source code with -lpthread option. But I don't understand why I should compile with -lpthread option. I think the option is redundant... because I already declared to include pthread.h header file so that gcc links pthread library. Why does gcc not link pthread library file automatically by reading #include?
Thanks in advance.
Well linking and compilation are two separate phases.
You include the header pthread.h
so that the compiler understands the data types & symbol names, which you use in your source files but are defined/declared in the pthread library header file.
You link to the pthread libray using -lpthread
so that the linker can actually find those symbols in the pthread library during the linking stage.
Having #include <pthread.h>
in your code doesn't link in the library; it only includes the header for compilation. That allows the compiler to see the various structures, function declarations, etc. included. Having -lpthread
actually causes the linking to be done by the linker. So the include tells the compiler what's available, and the -lpthread
actually allows the program to call the functions within the library at runtime.
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