c 标准库中的 stdin 定义在哪里?
我在 stdio.h 中找到了这一行:
extern struct _IO_FILE *stdin;
基于这个“extern”关键字,我认为这只是一个声明。我想知道 stdin 是在哪里定义和初始化的?
I found this line in stdio.h :
extern struct _IO_FILE *stdin;
Based on this 'extern' keyword, i assume this is just a declaration. I wonder where is stdin defined and initialized?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它在 C 库的源代码中定义。您通常只需要编译头文件,但您可以找到许多开源标准库(如 glibc)的源代码。
在 glibc 中,它在 libio/stdio.c 中定义如下:
又使用 libio/stdfiles.c 中的宏进行定义,如下所示
:
DEF_STDFILE
宏根据一些因素而有所不同,但它或多或少使用文件描述符0
(这是标准的)设置了适当的FILE
结构在 Unix 上输入)。该定义可能(当然确实)因您的 C 库而异,当然也因平台而异。如果您愿意,您可以继续围绕标准库 I/O 组件的各个部分进行探索。
It's defined in the source code of your C library. You typically only need the headers for compilation, but you can find the source code for many open-source standard libraries (like glibc).
In glibc, it's defined in
libio/stdio.c
as like this:Which is in turn defined using a macro in
libio/stdfiles.c
like this:The definition of the
DEF_STDFILE
macro varies depending on a few things, but it more or less sets up an appropriateFILE
struct using the file descriptor0
(which is standard input on Unix).The definition may (and of course does) vary depending on your C library, and certainly by platform. If you want, you can continue the goose chase around the various parts of your standard library's I/O component.
C 标准明确指出
stdin
是在stdio.h
中定义的宏。不允许在其他地方定义它。C11 7.21.1
该宏当然可以指向在其他地方实现的实现细节,例如在“stdio.c”中或编译器库选择放置它的任何内容。
The C standard explicitly states that
stdin
is a macro defined instdio.h
. It is not allowed to be defined anywhere else.C11 7.21.1
This macro can of course point at implementation details that are implemented elsewhere, such as in a "stdio.c" or whatever the compiler library chose to put it.
我相信它是在
stdio.c
中定义的,它被编译到libc
中(在基于 gnu 的系统上)I believe it's defined in
stdio.c
which is compiled into inlibc
(on gnu based systems)该定义将取决于实现,以及您找到它的位置。对我来说,在 OSX 10.6 上,它在 stdio.h 中定义为 FILE(结构)。
stdin 的类型为 _IO_FILE,这是一个在某处明确定义的结构,可能在 stdio.h 中。如果没有,请检查 stdio.h 中包含的头文件中 _IO_FILE 的定义。
The definition will be implementation dependent, as will where you find it. For me, on OSX 10.6, it's defined in stdio.h, as a FILE (a struct).
stdin is of the type _IO_FILE, a struct which is clearly defined somewhere, probably in stdio.h. If not, check in the header files included in stdio.h for a definition of _IO_FILE.
在标准库代码中,还有什么地方呢?在这附近的 Linux 机器中,它位于 libc.a:stdio.o 中,可以使用 nm -o /usr/lib/libc.a | 找到。 grep 标准输入 | grep D 。如果您想阅读一些代码,请参阅 GNU C 库。
In the standard library code, where else? In a Linux machine around here it's in
libc.a:stdio.o
, found usingnm -o /usr/lib/libc.a | grep stdin | grep D
. If you want to read some code, see the GNU C Library.