简体   繁体   English

errno在C / C ++中定义和分配的位置?

[英]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 我在这里检查errno.h的源代码: 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. 它表明errno被声明为extern,当我们使用errno时,我们可以直接为其赋值。 It means that errno is defined and allocated somewhere else, where is defined indeed? 这意味着errno是在其他地方定义和分配的,实际上在哪里定义?

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; 在20年前具有版权的源代码的链接示例中,C运行时库很可能具有变量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. 标头中的含义只是“此变量存在,您将在其他地方找到它”-可能在实际调用main函数的代码旁边,或类似的内容。

Typically in a modern OS with threads, errno isn't strictly a variable. 通常,在具有线程的现代OS中, errno严格来说不是变量。

This is the example in Linux, from /usr/include/bits/errno.h in glibc. 这是Linux中的示例,来自glibc中的/usr/include/bits/errno.h。

# 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: __errno_location确切实现方式取决于哪个操作系统的版本,但从本质__errno_location ,它类似于:

__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. 其中__thread转换C ++ 11 thread_local存储说明符,并且作为某种“交换每个线程的数据”类型的存储而被OS支持。 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) 在x86和x86-64中, fsgs用于“每个CPU”和“每个线程”存储(但是它们是“对立的”,我不记得现在是哪个)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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