views:

3743

answers:

3

On Linux (kernel 2.6.5) our build system calls gcc with -D_REENTRANT.

Is this still required when using pthreads?

How is it related to gcc -pthread option? I understand that I should use -pthread with pthreads, do I still need -D_REENTRANT?

On a side note, is there any difference that you know off between the usage of REENTRANT between gcc 3.3.3 and gcc 4.x.x ?

When I use -pthread gcc option I can see that _REENTRANT gets defined. Will omitting -D_REENTRANT from command line make any difference, for example could some objects be compiled without multithreaded support and then linked into binary that uses pthreads and will cause problems?

I assume it should be ok just to use: g++ -pthread

> echo | g++          -E -dM -c - > singlethreaded
> echo | g++ -pthread -E -dM -c - > multithreaded
> diff singlethreaded multithreaded
39a40
> #define _REENTRANT 1

We're compiling multiple static libraries and applications that link with the static libraries, both libraries and application use pthreads.

I believe it was required at some stage in the past but want to know if it is still required. Googling hasn't returned any recent information mentioning -D_REENTRANT with pthreads. Could you point me to links or references discussing the use in recent version of kernel/gcc/pthread?

Clarification: At the moment we're using -D_REENTRANT and -lpthread, I assume I can replace them with just g++ -pthread, looking at man gcc it sets the flags for both preprocessor and linker. Any thoughts?

+1  A: 

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}
bdonlan
+2  A: 

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...)

Stobor
+1  A: 

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

stefanB
Should that be "... it is equivalent to g++ -lpthread -D_REENTRANT" ? i.e. the second -pthread should be -lpthread
BruceCran
Correct, probably typo in the original comment ...
stefanB