没有头文件的 C 程序 [英] C program without header
问题描述
我用 C 编写了hello world"程序.
I write "hello world" program in C.
void main()
{ printf("Hello World"); }
// note that I haven't included any header file
程序编译时出现警告
vikram@vikram-Studio-XPS-1645:~$ gcc hello.c
hello.c: In function ‘main’:
hello.c:2:2: warning: incompatible implicit declaration of built-in function ‘printf’
vikram@vikram-Studio-XPS-1645:~$ ./a.out
Hello Worldvikram@vikram-Studio-XPS-1645:~$
这怎么可能?操作系统如何在不包含任何标头的情况下链接库?
How is this possible? How does the OS link a library without including any header?
推荐答案
编译器通过引用一个名为 printf()
的函数来构建你的源文件,它实际采用什么参数或它的返回类型是什么.生成的程序集包含程序静态数据区中字符串"Hello World"
的地址的push
,后跟call
printf
.
The compiler builds your source file with a reference to a function called printf()
, without knowing what arguments it actually takes or what its return type is. The generated assembly contains a push
of the address of the string "Hello World"
in the static data area of your program, followed by a call
to printf
.
将目标文件链接到可执行文件时,链接器会看到对printf
的引用并提供C 标准库函数printf()
.巧合,您传递的参数 (const char*
) 与真正的 printf()
的声明兼容,因此它可以正常运行.但是,请注意您的程序隐式声明的 printf()
具有返回类型 int
(我认为),标准 printf()
也拥有;但是如果它们不同,并且您要将调用 printf()
的结果分配给一个变量,那么您将处于未定义行为的领域,并且您可能会得到不正确的值.
When linking your object file into an executable, the linker sees a reference to printf
and supplies the C standard library function printf()
. By coincidence, the argument you have passed (const char*
) is compatible with the declaration of the real printf()
, so it functions correctly. However, note that the printf()
that your program implicitly declares has return type int
(I think), which the standard printf()
also has; but if they differed, and you were to assign the result of calling printf()
to a variable, you would be in the land of undefined behaviour and you would likely get an incorrect value.
长话短说:#include
为您使用的函数获取正确声明的正确标头,因为这种隐式声明已被弃用,因为它容易出错.
Long story short: #include
the correct headers to get the correct declarations for functions you use, because this kind of implicit declaration is deprecated, because it is error-prone.
这篇关于没有头文件的 C 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!