2
votes

If you use C++ threads with the GCC compiler (or perhaps more accurately, with the libstdc++ C++ standard library which ships with GCC) on Linux, you may need to include the -pthread option in your build process to get things to compile and link properly.

What I'm curious about is which library headers invoke that requirement? #include <thread> is an obvious one, but are there other standard library headers which implicitly have a pthread dependency for libstdc++?

3
probably <future> - Big Temp
Assume ALL. The standard doesn't have any restrictions on standard headers including other headers so <iostream> could have <thread> included. - NathanOliver
If your implementation uses pthread or not for threading is an implementation detail. If you get a linker error add the library. When I include standard threading headers <thread> I don't need to specifically link against -lpthread. I assume that my implementation of the standard is doing the appropriate linking for me (or dynamically loading the appropriate libraries at runtime, I don't know nor should I care (in most cases)). - Martin York
@MartinYork I'm asking about implementation details. This is not a "according to the standard ..." question, this is an "in practice ..." question. - R.M.

3 Answers

2
votes

It's not so much header files, but specific functionality. Anything that creates threads under the hood will need or greatly benefit from linking with -lpthread, such as std::async from <future>.

2
votes

<thread> <mutex> <condition_variable> <future> <shared_mutex> <stop_token> all use Pthreads types and functions.

The Networking TS headers such as <experimental/net> and <experimental/executor> use <mutex> and <future> so they also depend on Pthreads.

We'll soon be adding more concurrency headers such as <latch> <barrier> <semaphore>.

Basically anything related to concurrency and synchronization, except <atomic> which notably does not depend on anything from Pthreads.

1
votes

On Solaris prior to version 10, errno was a global variable in a single-threaded build, but a macro expanding into a function call in a multi-threaded build. That was a source of problems when people linked multi-threaded apps with single-threaded libraries unwittingly. See Compiling Multithreaded Code for more details.

On Linux, errno is always a macro expanding into a function call that reads a thread-specific errno regardless whether -pthread is specified.

Compiling with -pthread defines macro _REENTRANT, but none of the GNU C and C++ standard library headers use that macro. Boost library does use it.