What is the correct way to build a thread-safe, multiplatform C library? <p>Consider the following trivial C program,</p> <pre><code>#include &lt;errno.h&gt; int main(int argc, char* argv[]) { return errno; } </code></pre> <p>When compiled on Solaris, the behavior of this code is dependent on the presence of <code>-D_REENTRANT</code>.</p> <pre><code>solaris$ cc -E test.c | grep return return errno; solaris$ cc -D_REENTRANT -E test.c | grep return return ( * ( ___errno ( ) ) ); </code></pre> <p>with the latter version being thread-safe. If we compile the same code on Linux, we get the same behavior independent of <code>-D_REENTRANT</code></p> <pre><code>linux$ gcc -E test.c | grep return return (*__errno_location ()); linux$ gcc -D_REENTRANT -E test.c | grep return return (*__errno_location ()); </code></pre> <p>Solaris' <code>cc</code> has the option <code>-mt</code>, which implies <code>-D_REENTRANT</code>, as does <code>gcc</code>'s <code>-pthread</code>. However, for a library, specifying these multi-threaded options seems poor, as it injects an unnecessary dependency on the threading runtime. However, if the library needs to be thread-safe (including errno), then the thread-safe semantics are needed at both compile time of the library and of the deriving code. On Linux, this is easy, because errno is always thread-local, but that's not guaranteed on other systems as just demonstrated.</p> <p>That results in the question: how is a thread-safe library properly compiled and distributed with headers? One option would be to <code>#define _REENTRANT</code> in the main header, but this would cause issues if <code>#include &lt;errno.h&gt;</code> occurs before the library header inclusion. Another option is to compile the library with <code>-D_REENTRANT</code>, and have the main header <code>#error</code> if <code>_REENTRANT</code> is not defined.</p> <p>What's the correct/best way to make a thread-safe library and ensure it correctly inter-operates with the code it is linked with?</p>