Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-lpthread option of gcc

Tags:

gcc

pthreads

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.

like image 313
David Johns Avatar asked Feb 17 '12 16:02

David Johns


2 Answers

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.

like image 173
Alok Save Avatar answered Sep 19 '22 21:09

Alok Save


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.

like image 37
Dan Fego Avatar answered Sep 16 '22 21:09

Dan Fego