14
votes

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.

6
Related: stackoverflow.com/questions/2127797/…, you should be using -pthread too. - Mat

6 Answers

25
votes

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.

5
votes

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.

3
votes

Because GCC doesn't do auto-linking of libraries triggered by header inclusion (as opposed to MSVC, or so I've been told).

3
votes

The header file just declares what the pthread functions are and how they should be called. -lpthread links to the library itself, containing the actual functions.

The compiler has no idea how you're going to resolve the functions in pthread.h. You might want to use a static library, the one provided by the system, some compatible implementation - heck, you might implement them yourself in another source file. It's up to the linker, and doesn't concern the compiler.

1
votes

By including the header files you tell the compiler which functions he's going to see. But if these functions are in an external library, like the pthread functions, you need to link this library to your program so it can actually access those functions. That's what -lpthread is doing.

1
votes

Pthread.h header file is included in the posix thread program but you need -lpthread while compiling because it links it with the library of pthread NOTE: -lpthread -lpcap all are the switches with gcc compiler that can link particular library in our source code. (lpthread means "link pthread" library)