std::cout
is defined in GCC's own C++ standard library, which g++
links to by default, and it only depends on standard C I/O facilities such as FILE*
and basic file I/O, which are provided in libc
, which gcc
and g++
also link to by default. So everything you need to use std::cout
is linked to by default.
Functions such as pthread_create
are not part of the C++ or C standard libraries, they are defined in the separate library libpthread
. That library is not linked to by default by GCC, because Pthreads is not part of the language (it's defined by a different standard, POSIX, but not the language standards) and also because linking to libpthread
unconditionally would make many C++ programs run slower, for reasons explained below.
GCC's C++ standard library uses reference counting in a number of places (e.g. in the Copy-On-Write implementation of std::string
and in std::shared_ptr
) and in multithreaded applications the reference count updates need to use atomic instructions. In non-multithreaded applications the atomic operations are not needed, so libstdc++ uses normal, non-atomic updates if the program is single-threaded. The way it detects whether the program multithreaded or not is by checking whether the program is linked to libpthread
or not. So linking to libpthread
for all programs by default would cause the library to think all programs are multithreaded, and to always use the slower atomic operations, even when the program doesn't use any threads.
So to avoid making some programs slower it is the user's responsibility to link to libpthread
explicitly when required.
On POSIX platforms std::thread
is a thin wrapper around Pthreads, so the same rule applies for that type as for the functions like pthread_create
: the user must link to libpthread
manually. That's true even though std::thread
is part of the language standard, but because it's implemented on top of Pthreads and because of the performance implications described above, the user must link to it manually.
-pthread
for both linking and compiling. When compiling it defines_REENTRANT
macro, when linking it links the necessary libraries. – Frank-pthread
not-lpthread
, and the answer is complicated), or is it using pthreads directly (in which case the answer is that GCC only links with the standard C++ library by default)? – Poddy