Why do we write -D_REENTRANT when compiling C code using threads

We write this statement when we compile a C program in which streams are implemented. I could not understand why we are using -D_REENTRANT here. eg,gcc t1.c -lpthread -D_REENTRANT

+4
source share
3 answers

You do not need to write. But recommended.

Defining _REENTRANT forces the compiler to use thread-safe (i.e., repetitive) versions of several functions in the C library.

+5
source

Actually, the recommended way to compile with streams in GCC uses the parameter -pthread. This is equivalent -lpthread -D_REENTRANT, so you have no problem.

Flags perform the following actions:

  • -lpthread .

  • -D_REENTRANT (, ,...), .

+7

, gcc, -D name name 1.

, _REENTRANT -, true 1.

, _REENTRANT false 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 the _REENTRANT parameter is defined.

Finally, you need to associate your library with the code pthread, so you can use the family pthread_*(), for example pthread_create(), pthread_join().

When -lpthreadpassed to the linker, the code binds to libpthread.so.

+3
source

All Articles