[英]Where errno is defined and allocated in C/C++?
我在这里检查errno.h的源代码: http : //unix.superglobalmegacorp.com/Net2/newsrc/sys/errno.h.html
它表明errno被声明为extern,当我们使用errno时,我们可以直接为其赋值。 这意味着errno是在其他地方定义和分配的,实际上在哪里定义?
在20年前具有版权的源代码的链接示例中,C运行时库很可能具有变量int errno;
某处。 extern int errno;
标头中的含义只是“此变量存在,您将在其他地方找到它”-可能在实际调用main
函数的代码旁边,或类似的内容。
通常,在具有线程的现代OS中, errno
严格来说不是变量。
这是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 */
__errno_location
确切实现方式取决于哪个操作系统的版本,但从本质__errno_location
,它类似于:
__thread int errno;
其中__thread
转换C ++ 11 thread_local
存储说明符,并且作为某种“交换每个线程的数据”类型的存储而被OS支持。 确切的实现方式再次取决于操作系统。 在x86和x86-64中, fs
和gs
用于“每个CPU”和“每个线程”存储(但是它们是“对立的”,我不记得现在是哪个)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.