6

We write this statement when we are compiling a C program that has threads implemented in them. I could not understand why we use -D_REENTRANT here. e.g gcc t1.c -lpthread -D_REENTRANT

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ahmed
  • 2,176
  • 5
  • 26
  • 40
  • 2
    Possible duplicate of [What is the \_REENTRANT flag?](http://stackoverflow.com/questions/2601753/what-is-the-reentrant-flag) – Calimo Dec 22 '16 at 12:27

3 Answers3

12

Actually, the recommended way to compile with threads in GCC is using the -pthread option. It is equivalent to -lpthread -D_REENTRANT so you have actually no problem.

The flags do the following:

  • -lpthread instructs the linker to use the appropriate library versions for thread compatibility.

  • -D_REENTRANT tells the compiler to use the declarations (functions, types, ...) necessary for thread usage.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • For GCC 6 and earlier, -pthread was a machine-specific option for RS/6000 and PowerPC, as well as Solaris 2. Since GCC 7, -pthread has been generalised for all platforms. (GCC 7 was released in May 2017, and this answer was written over 3 year before that.) – Jetski S-type Oct 08 '18 at 02:40
6

Compilers like gcc use -D name to predefine name as a macro with definition 1.

In the program source code and header files, you will see compiler directives that check for _REENTRANT and does something when this macro is true or 1.

If this macro is not passed to the compiler, then the compiler directive _REENTRANT would be false or 0.

Take this example from /usr/include/features.h.

#if defined _REENTRANT || defined _THREAD_SAFE
# define __USE_REENTRANT    1
#endif

You will see that it tells the compiler what to do if _REENTRANT is defined.

Finally, you have to link your code agains pthread library so you can use pthread_*() family like pthread_create(), pthread_join().

When -lpthread is passed to the linker, the code gets linked with libpthread.so.

alvits
  • 6,550
  • 1
  • 28
  • 28
6

You don't have to write it. But it is recommended.

Defining _REENTRANT causes the compiler to use thread safe (i.e. re-entrant) versions of several functions in the C library.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Khurram Raza
  • 659
  • 8
  • 9