Why does GCC require "-lpthread" to link against pthread functions but doesn't require arguments to link against other functions?

Viewed 99

If I use pthread functions, I must use the "-lpthread" argument on GCC to ensure proper linking. However, why doesn't GCC require additional arguments when linking against other standard functions? Examples: printf, scanf, POSIX sockets, etc.

1 Answers

On UNIX-like systems, some parts of the C library have historically been implemented in separate shared objects. The compiler driver (gcc) only links implicitly with -lc (and the dynamic loader), but not these other shared objects, such as -lm (math library), -ldl (dynamic linker/dlopen), or in your case, -lpthread. There is no technical reason for this separation: musl puts everything into the dynamic loader (including -lc).

Regarding libpthread, there were several POSIX thread libraries that could be used with glibc, LinuxThreads and FSU Threads being popular ones. This means that the programmer could pick different threading libraries using the appropriate -l (and perhaps -I) options.

The integrated Native POSIX Threads Library (NPTL) displaced all of them fairly soon after its integration into glibc, so allowing the developer to choose is not a concern anymore. However, internal in glibc, the split into separate objects remained. In glibc version 2.34, libpthread was finally integrated into the main (implicitly linked) object for glibc as well:

Related