Significance of -pthread flag when compiling

C++CLinuxPthreads

C++ Problem Overview


In various multi threaded C and C++ projects I've seen the -pthread flag applied to both the compiling and linking stage while others don't use it at all and just pass -lpthread to the linking stage.

Is there any danger not compiling and linking with the -pthread flag - i.e. what does -pthread actually do ? I'm primarily interested in Linux platforms.

C++ Solutions


Solution 1 - C++

Try:

gcc -dumpspecs | grep pthread

and look for anything that starts with %{pthread:.

On my computer, this causes files to be compiled with -D_REENTRANT, and linked with -lpthread. On other platforms, this could differ. Use -pthread for most portability.

Using _REENTRANT, on GNU libc, changes the way some libc headers work. As a specific example, it makes errno call a function returning a thread-local location.

Solution 2 - C++

From man gcc:

> -pthread > Adds support for multithreading with the pthreads > library. This > option sets flags for both the preprocessor and linker.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleeeroyView Question on Stackoverflow
Solution 1 - C++Chris Jester-YoungView Answer on Stackoverflow
Solution 2 - C++DmitryView Answer on Stackoverflow