简体   繁体   中英

Where errno is defined and allocated in C/C++?

I check the source code for errno.h here: http://unix.superglobalmegacorp.com/Net2/newsrc/sys/errno.h.html

It shows that errno is declared as extern, and when we use errno we can assign value to it directly. It means that errno is defined and allocated somewhere else, where is defined indeed?

In the linked example to source-code with a copyright from over 20 years ago, most likely the C runtime library has a variable int errno; somewhere. extern int errno; in a header just means "this variable exists, you'll find it somewhere else" - maybe next to the code that actually calls your main function, or something similar.

Typically in a modern OS with threads, errno isn't strictly a variable.

This is the example in Linux, from /usr/include/bits/errno.h in glibc.

# ifndef __ASSEMBLER__

/* Function to get address of global `errno' variable.  */
extern int *__errno_location (void) __THROW __attribute__ ((__const__));

#  if !defined _LIBC || defined _LIBC_REENTRANT
/* When using threads, errno is a per-thread value.  */
#   define errno (*__errno_location ())
#  endif
# endif /* !__ASSEMBLER__ */
#endif /* _ERRNO_H */

Exactly how this the __errno_location is implemented depends on which version of what OS, but essentially, it's something like:

__thread int errno;

where __thread translates the C++11 thread_local storage specifier, and is supported by the OS as some kind of "swap the data per thread" type storage. Exactly how that is implemented is again depending on the OS. In x86 and x86-64, fs and gs are used for "per CPU" and "per thread" storage (but they are "opposed" and I can't quite remember which is which right now)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM