无头的C程序 [英] C program without header

查看:144
本文介绍了无头的C程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的Hello World程序用C

I write "hello world" program in C.

void main()
{ printf("Hello World"); }
// note that I haven't included any header file

该程序将警告编译为

The program compiles with warning as

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的地址的 ,其次是呼叫的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 正确的头让你使用的功能正确的声明,因为这种隐含的声明是代precated,因为它是容易出错的。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆