Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

linux

errno

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?

like image 735
silverwen Avatar asked Oct 31 '25 08:10

silverwen


1 Answers

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)

like image 76
Mats Petersson Avatar answered Nov 01 '25 22:11

Mats Petersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!