为什么我们不会得到编译时错误,即使我们不包括stdio.h在C程序中? [英] Why don't we get a compile time error even if we don't include stdio.h in a C program?

查看:144
本文介绍了为什么我们不会得到编译时错误,即使我们不包括stdio.h在C程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我首先没有包含任何头文件时,编译器如何知道sleep函数原型或者甚至printf函数?

How does the compiler know the prototype of sleep function or even printf function, when I did not include any header file in the first place?

指定 sleep(1,1,xyz)或任意任意数量的参数,编译器仍会编译它。
但奇怪的是gcc能够在链接时找到这个函数的定义,我不明白这是怎么可能的,因为实际 sleep()函数只有一个参数,但我们的程序提到了三个参数。

Moreover, if I specify sleep(1,1,"xyz") or any arbitrary number of arguments, the compiler still compiles it. But the strange thing is that gcc is able to find the definition of this function at link time, I don't understand how is this possible, because actual sleep() function takes a single argument only, but our program mentioned three arguments.

/********************************/
int main()
{
 short int i;
 for(i = 0; i<5; i++)
 {
    printf("%d",i);`print("code sample");`
    sleep(1);
 }
 return 0;
}


推荐答案

编译器将假定函数返回int并接受您提供的任何数量的参数。

Lacking a more specific prototype, the compiler will assume that the function returns int and takes whatever number of arguments you provide.

根据CPU体系结构,可以在寄存器中传递参数(例如,a0到a3 on MIPS),或者像在原始的x86调用约定中那样将它们推入堆栈。在任一情况下,传递额外的参数是无害的。被调用函数不会使用传入的寄存器,也不会在堆栈中引用额外的参数,但是没有什么不好的结果。

Depending on the CPU architecture arguments can be passed in registers (for example, a0 through a3 on MIPS) or by pushing them onto the stack as in the original x86 calling convention. In either case, passing extra arguments is harmless. The called function won't use the registers passed in nor reference the extra arguments on the stack, but nothing bad happens.

传递更少的参数是更有问题的。被调用函数将使用恰当的寄存器或堆栈位置中发生的任何垃圾,并且可能会发生连接。

Passing in fewer arguments is more problematic. The called function will use whatever garbage happened to be in the appropriate register or stack location, and hijinks may ensue.

这篇关于为什么我们不会得到编译时错误,即使我们不包括stdio.h在C程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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