Fixing your issue is as easy as changing the name of your static variable.
static int myerrno_variable = 0;
int *myerrno_location(void){
return &myerrno_variable;
}
Notice that your version is still not thread safe since all threads are accessing the same myerrno_variable
. A real implementation would return a thread specific memory location. In GCC, there is an extension that provides the __thread
storage class. C.11 provides its own version of that called thread_local
, but it is only available if thread support is provided by the implementation (which can be checked by looking if __STDC_NO_THREADS__
is defined or not).
static __thread int myerrno_variable_gcc; /* if using GCC */
static thread_local int my_errno_variable_c11; /* if __STD_NO_THREADS__ isn't defined */
On a POSIX system without a thread local feature, an implementation could use pthread_getspecific()
to get a pointer to thread specific data that was allocated for each thread, and set with pthread_setspecific()
. See the manual for more information.