where is stdin defined in c standard library?

℡╲_俬逩灬. 提交于 2019-12-18 04:45:17

问题


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?


回答1:


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:

_IO_FILE *stdin = (FILE *) &_IO_2_1_stdin_;

Which is in turn defined using a macro in libio/stdfiles.c like this:

DEF_STDFILE(_IO_2_1_stdin_, 0, 0, _IO_NO_WRITES);

The definition of the DEF_STDFILE macro varies depending on a few things, but it more or less sets up an appropriate FILE struct using the file descriptor 0 (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.




回答2:


I believe it's defined in stdio.c which is compiled into in libc (on gnu based systems)




回答3:


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.




回答4:


In the standard library code, where else? In a Linux machine around here it's in libc.a:stdio.o, found using nm -o /usr/lib/libc.a | grep stdin | grep D. If you want to read some code, see the GNU C Library.




回答5:


The C standard explicitly states that stdin is a macro defined in stdio.h. It is not allowed to be defined anywhere else.

C11 7.21.1

"The header <stdio.h> defines several macros, ..." /--/

"The macros are..." /--/

stderr
stdin
stdout

which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects associated, respectively, with the standard error, input, and output streams.

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.



来源:https://stackoverflow.com/questions/6906238/where-is-stdin-defined-in-c-standard-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!