简体   繁体   中英

What does '#include <stdio.h>' really do in a C program

I am new to c programming and I was coding some simple programs "Hello world" style.

In all of these programs I put #include<stdio.h> in the top but I am not sure what this means exactly. I googled it and I found that stdio.h is a file that has commands for the preprocessor, but what is a preprocessor? I thought when I write code, I compile it and my code transforms to a form that a "computer" can read and then I can run it. Can somebody explain to me what the usage of this command is?

It looks for the stdio.h file and effectively copy-pastes it in the place of this #include statements. This file contains so-called function prototypes of functions such as printf() , scanf() , ... so that compiler knows what are their parameters and return values.

The simplest explanation perhaps should be that your program calls or uses many functions whose code is not part of your program itself. For eg if you write "printf" in your code to print something, the compiler does not know what to do with that call.

stdio.h is the place where information for that printf resides.

Update:

Rather the prototype of printf function (name, return type and parameters) reside in stdio.h. That is all required in the compilation phase. The actual code of printf is included in the linking phase, which comes after compilation.

The include statement basically inserts all function prototypes BEFORE the actual compilation. Hence the name preprocessor.

Update 2:

Since the question focused on include statement (and the OP also asked about writing definition of functions himself, another important aspect is if it is written like (note the angular brackets)

#include <stdio.h>

The preprocessor assumes, it is a standard library header and looks in the system folders first where the compiler has been installed.

If instead a programmer defines a function by himself and place the .h file in the current working directory, he would use (note the double quotes)

#include "stdio.h"

Following illustrates it and the behavior is portable across all platforms.

It tells the compiler to use functions, structures, macros and etc from file sdtio.h, which represents a part of glibc(or whatever is the standart C library you got). Compiler also adds record to the output executable "to-link list", that it should be linked to standart C library.

源代码中的预处理器指令是在程序编译之前处理的语句,在此步骤之后,源代码被转换为扩展的源代码,因为它现在包含对标准 C 库中已经定义的函数的引用(或任何其他),如 printf、scanf、putw、getchar 等。 stdio.h 是一个带有“.h”扩展名的文件,它包含 c 中使用的标准输入输出函数的原型(不是定义)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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