Do I need -D_REENTRANT with -pthreads?

Solution 1:

For me the best answer was the comment from pts if only he bothered to submit it as answer:

You investigated properly and answered your own question. Use g++ -pthread, it is equivalent to g++ -lpthread -D_REENTRANT. Using g++ -D_REENTRANT would be different, it may not set all the linker flags. – pts May 18 at 0:30

Solution 2:

From the gcc info pages:

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

So just the -pthread flag should be sufficient. I wouldn't recommend only passing it to some of your code, however.

As Chris suggested in the comments, using gcc -dumpspecs on Linux does indeed confirm that it sets preprocessor flags as well:

%{posix:-D_POSIX_SOURCE} %{pthread:-D_REENTRANT}

Solution 3:

gcc's -pthreads flag sets the relevant compiler and linker flags necessary for pthreads support on the platform you're on.

You're right, on linux x86 (and probably many other platforms), that's equivalent to '-D_REENTRANT -lpthread' but that's not necessarily true on all platforms.

(For at least some time, on aix, -pthread caused g++ to link in a completely different libstdc++.a. I don't know if that's still the case now, though...)